@hunsu/bridge 0.1.3 → 0.2.0-next.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,70 +1,457 @@
1
1
  #!/usr/bin/env node
2
- import { startStudioBridge } from "./index.js";
3
- async function main(argv = process.argv.slice(2)) {
4
- const parsed = parseArgs(argv);
5
- if (parsed.command === "help" || hasFlag(parsed, "help")) {
6
- printHelp();
7
- return 0;
2
+ var Nee=Object.create;var vS=Object.defineProperty;var Oee=Object.getOwnPropertyDescriptor;var Mee=Object.getOwnPropertyNames;var Lee=Object.getPrototypeOf,Hee=Object.prototype.hasOwnProperty;var Nt=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var N=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),wi=(t,e)=>{for(var r in e)vS(t,r,{get:e[r],enumerable:!0})},E3=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Mee(e))!Hee.call(t,i)&&i!==r&&vS(t,i,{get:()=>e[i],enumerable:!(n=Oee(e,i))||n.enumerable});return t};var tt=(t,e,r)=>(r=t!=null?Nee(Lee(t)):{},E3(e||!t||!t.__esModule?vS(r,"default",{value:t,enumerable:!0}):r,t)),Vi=t=>E3(vS({},"__esModule",{value:!0}),t);var Ou=ce(ZU=>{function Jme(){var t,e=!1,r=this;r._DeArray=function(n,i,o){return[n.slice(i,i+o)]},r._EnArray=function(n,i,o,s){for(var a=0;a<o;n[i+a]=s[a]?s[a]:0,a++);},r._DeChar=function(n,i){return String.fromCharCode(n[i])},r._EnChar=function(n,i,o){n[i]=o.charCodeAt(0)},r._DeInt=function(n,i){var o=e?t.len-1:0,s=e?-1:1,a=o+s*t.len,c,u,d;for(c=0,u=o,d=1;u!=a;c+=n[i+u]*d,u+=s,d*=256);return t.bSigned&&c&Math.pow(2,t.len*8-1)&&(c-=Math.pow(2,t.len*8)),c},r._EnInt=function(n,i,o){var s=e?t.len-1:0,a=e?-1:1,c=s+a*t.len,u;for(o=o<t.min?t.min:o>t.max?t.max:o,u=s;u!=c;n[i+u]=o&255,u+=a,o>>=8);},r._DeString=function(n,i,o){for(var s=new Array(o),a=0;a<o;s[a]=String.fromCharCode(n[i+a]),a++);return s.join("")},r._EnString=function(n,i,o,s){for(var a,c=0;c<o;n[i+c]=(a=s.charCodeAt(c))?a:0,c++);},r._De754=function(n,i){var o,s,a,c,u,d,l,f,p,g;for(l=t.mLen,f=t.len*8-t.mLen-1,g=(1<<f)-1,p=g>>1,c=e?0:t.len-1,u=e?1:-1,o=n[i+c],c+=u,d=-7,s=o&(1<<-d)-1,o>>=-d,d+=f;d>0;s=s*256+n[i+c],c+=u,d-=8);for(a=s&(1<<-d)-1,s>>=-d,d+=l;d>0;a=a*256+n[i+c],c+=u,d-=8);switch(s){case 0:s=1-p;break;case g:return a?NaN:(o?-1:1)*(1/0);default:a=a+Math.pow(2,l),s=s-p;break}return(o?-1:1)*a*Math.pow(2,s-l)},r._En754=function(n,i,o){var s,a,c,u,d,l,f,p,g,v;for(f=t.mLen,p=t.len*8-t.mLen-1,v=(1<<p)-1,g=v>>1,s=o<0?1:0,o=Math.abs(o),isNaN(o)||o==1/0?(c=isNaN(o)?1:0,a=v):(a=Math.floor(Math.log(o)/Math.LN2),o*(l=Math.pow(2,-a))<1&&(a--,l*=2),a+g>=1?o+=t.rt/l:o+=t.rt*Math.pow(2,1-g),o*l>=2&&(a++,l/=2),a+g>=v?(c=0,a=v):a+g>=1?(c=(o*l-1)*Math.pow(2,f),a=a+g):(c=o*Math.pow(2,g-1)*Math.pow(2,f),a=0)),u=e?t.len-1:0,d=e?-1:1;f>=8;n[i+u]=c&255,u+=d,c/=256,f-=8);for(a=a<<f|c,p+=f;p>0;n[i+u]=a&255,u+=d,a/=256,p-=8);n[i+u-d]|=s*128},r._DeInt64=function(n,i){var o=e?0:7,s=e?1:-1,a=o+s*8,c=[0,0,!t.bSigned],u,d,l;for(u=o,l=1,d=0;u!=a;c[l]=(c[l]<<8>>>0)+n[i+u],u+=s,d++,l=d<4?1:0);return c},r._EnInt64=function(n,i,o){var s=e?0:7,a=e?1:-1,c=s+a*8,u,d,l,f;for(u=s,l=1,d=0,f=24;u!=c;n[i+u]=o[l]>>f&255,u+=a,d++,l=d<4?1:0,f=24-8*(d%4));},r._sPattern="(\\d + )?([AxcbBhHsfdiIlLqQ])",r._lenLut={A:1,x:1,c:1,b:1,B:1,h:2,H:2,s:1,f:4,d:8,i:4,I:4,l:4,L:4,q:8,Q:8},r._elLut={A:{en:r._EnArray,de:r._DeArray},s:{en:r._EnString,de:r._DeString},c:{en:r._EnChar,de:r._DeChar},b:{en:r._EnInt,de:r._DeInt,len:1,bSigned:!0,min:-Math.pow(2,7),max:Math.pow(2,7)-1},B:{en:r._EnInt,de:r._DeInt,len:1,bSigned:!1,min:0,max:Math.pow(2,8)-1},h:{en:r._EnInt,de:r._DeInt,len:2,bSigned:!0,min:-Math.pow(2,15),max:Math.pow(2,15)-1},H:{en:r._EnInt,de:r._DeInt,len:2,bSigned:!1,min:0,max:Math.pow(2,16)-1},i:{en:r._EnInt,de:r._DeInt,len:4,bSigned:!0,min:-Math.pow(2,31),max:Math.pow(2,31)-1},I:{en:r._EnInt,de:r._DeInt,len:4,bSigned:!1,min:0,max:Math.pow(2,32)-1},l:{en:r._EnInt,de:r._DeInt,len:4,bSigned:!0,min:-Math.pow(2,31),max:Math.pow(2,31)-1},L:{en:r._EnInt,de:r._DeInt,len:4,bSigned:!1,min:0,max:Math.pow(2,32)-1},f:{en:r._En754,de:r._De754,len:4,mLen:23,rt:Math.pow(2,-24)-Math.pow(2,-77)},d:{en:r._En754,de:r._De754,len:8,mLen:52,rt:0},q:{en:r._EnInt64,de:r._DeInt64,bSigned:!0},Q:{en:r._EnInt64,de:r._DeInt64,bSigned:!1}},r._UnpackSeries=function(n,i,o,s){for(var a=t.de,c=[],u=0;u<n;c.push(a(o,s+u*i)),u++);return c},r._PackSeries=function(n,i,o,s,a,c){for(var u=t.en,d=0;d<n;u(o,s+d*i,a[c+d]),d++);},r.Unpack=function(n,i,o){e=n.charAt(0)!="<",o=o||0;for(var s=new RegExp(this._sPattern,"g"),a,c,u,d=[];a=s.exec(n);){if(c=a[1]==null||a[1]==""?1:parseInt(a[1]),u=this._lenLut[a[2]],o+c*u>i.length)return;switch(a[2]){case"A":case"s":d.push(this._elLut[a[2]].de(i,o,c));break;case"c":case"b":case"B":case"h":case"H":case"i":case"I":case"l":case"L":case"f":case"d":case"q":case"Q":t=this._elLut[a[2]],d.push(this._UnpackSeries(c,u,i,o));break}o+=c*u}return Array.prototype.concat.apply([],d)},r.PackTo=function(n,i,o,s){e=n.charAt(0)!="<";for(var a=new RegExp(this._sPattern,"g"),c,u,d,l,f=0;c=a.exec(n);){if(u=c[1]==null||c[1]==""?1:parseInt(c[1]),d=this._lenLut[c[2]],o+u*d>i.length)return!1;switch(c[2]){case"A":case"s":if(f+1>s.length)return!1;this._elLut[c[2]].en(i,o,u,s[f]),f+=1;break;case"c":case"b":case"B":case"h":case"H":case"i":case"I":case"l":case"L":case"f":case"d":case"q":case"Q":if(t=this._elLut[c[2]],f+u>s.length)return!1;this._PackSeries(u,d,i,o,s,f),f+=u;break;case"x":for(l=0;l<u;l++)i[o+l]=0;break}o+=u*d}return i},r.Pack=function(n,i){return this.PackTo(n,new Array(this.CalcLength(n)),0,i)},r.CalcLength=function(n){for(var i=new RegExp(this._sPattern,"g"),o=0,s;s=i.exec(n);)o+=(s[1]==null||s[1]==""?1:parseInt(s[1]))*this._lenLut[s[2]];return o}}ZU.jspack=new Jme});var t9=ce((q3e,e9)=>{var Tp=1e3,Dp=Tp*60,Bp=Dp*60,Al=Bp*24,Xme=Al*7,Yme=Al*365.25;e9.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return Qme(t);if(r==="number"&&isFinite(t))return e.long?ehe(t):Zme(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function Qme(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*Yme;case"weeks":case"week":case"w":return r*Xme;case"days":case"day":case"d":return r*Al;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Bp;case"minutes":case"minute":case"mins":case"min":case"m":return r*Dp;case"seconds":case"second":case"secs":case"sec":case"s":return r*Tp;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function Zme(t){var e=Math.abs(t);return e>=Al?Math.round(t/Al)+"d":e>=Bp?Math.round(t/Bp)+"h":e>=Dp?Math.round(t/Dp)+"m":e>=Tp?Math.round(t/Tp)+"s":t+"ms"}function ehe(t){var e=Math.abs(t);return e>=Al?_w(t,e,Al,"day"):e>=Bp?_w(t,e,Bp,"hour"):e>=Dp?_w(t,e,Dp,"minute"):e>=Tp?_w(t,e,Tp,"second"):t+" ms"}function _w(t,e,r,n){var i=e>=r*1.5;return Math.round(t/r)+" "+n+(i?"s":"")}});var zP=ce((W3e,r9)=>{function the(t){r.debug=r,r.default=r,r.coerce=c,r.disable=s,r.enable=i,r.enabled=a,r.humanize=t9(),r.destroy=u,Object.keys(t).forEach(d=>{r[d]=t[d]}),r.names=[],r.skips=[],r.formatters={};function e(d){let l=0;for(let f=0;f<d.length;f++)l=(l<<5)-l+d.charCodeAt(f),l|=0;return r.colors[Math.abs(l)%r.colors.length]}r.selectColor=e;function r(d){let l,f=null,p,g;function v(...b){if(!v.enabled)return;let C=v,D=Number(new Date),_=D-(l||D);C.diff=_,C.prev=l,C.curr=D,l=D,b[0]=r.coerce(b[0]),typeof b[0]!="string"&&b.unshift("%O");let F=0;b[0]=b[0].replace(/%([a-zA-Z%])/g,(z,Ce)=>{if(z==="%%")return"%";F++;let de=r.formatters[Ce];if(typeof de=="function"){let R=b[F];z=de.call(C,R),b.splice(F,1),F--}return z}),r.formatArgs.call(C,b),(C.log||r.log).apply(C,b)}return v.namespace=d,v.useColors=r.useColors(),v.color=r.selectColor(d),v.extend=n,v.destroy=r.destroy,Object.defineProperty(v,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(p!==r.namespaces&&(p=r.namespaces,g=r.enabled(d)),g),set:b=>{f=b}}),typeof r.init=="function"&&r.init(v),v}function n(d,l){let f=r(this.namespace+(typeof l>"u"?":":l)+d);return f.log=this.log,f}function i(d){r.save(d),r.namespaces=d,r.names=[],r.skips=[];let l=(typeof d=="string"?d:"").trim().replace(" ",",").split(",").filter(Boolean);for(let f of l)f[0]==="-"?r.skips.push(f.slice(1)):r.names.push(f)}function o(d,l){let f=0,p=0,g=-1,v=0;for(;f<d.length;)if(p<l.length&&(l[p]===d[f]||l[p]==="*"))l[p]==="*"?(g=p,v=f,p++):(f++,p++);else if(g!==-1)p=g+1,v++,f=v;else return!1;for(;p<l.length&&l[p]==="*";)p++;return p===l.length}function s(){let d=[...r.names,...r.skips.map(l=>"-"+l)].join(",");return r.enable(""),d}function a(d){for(let l of r.skips)if(o(d,l))return!1;for(let l of r.names)if(o(d,l))return!0;return!1}function c(d){return d instanceof Error?d.stack||d.message:d}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}r9.exports=the});var n9=ce((to,Tw)=>{to.formatArgs=nhe;to.save=ihe;to.load=ohe;to.useColors=rhe;to.storage=she();to.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();to.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function rhe(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function nhe(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Tw.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(r++,i==="%c"&&(n=r))}),t.splice(n,0,e)}to.log=console.debug||console.log||(()=>{});function ihe(t){try{t?to.storage.setItem("debug",t):to.storage.removeItem("debug")}catch{}}function ohe(){let t;try{t=to.storage.getItem("debug")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function she(){try{return localStorage}catch{}}Tw.exports=zP()(to);var{formatters:ahe}=Tw.exports;ahe.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var o9={};wi(o9,{createSupportsColor:()=>KP,default:()=>phe});import JP from"node:process";import che from"node:os";import i9 from"node:tty";function wo(t,e=globalThis.Deno?globalThis.Deno.args:JP.argv){let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),i=e.indexOf("--");return n!==-1&&(i===-1||n<i)}function uhe(){if(!("FORCE_COLOR"in Cr))return;if(Cr.FORCE_COLOR==="true")return 1;if(Cr.FORCE_COLOR==="false")return 0;if(Cr.FORCE_COLOR.length===0)return 1;let t=Math.min(Number.parseInt(Cr.FORCE_COLOR,10),3);if([0,1,2,3].includes(t))return t}function dhe(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function lhe(t,{streamIsTTY:e,sniffFlags:r=!0}={}){let n=uhe();n!==void 0&&(Dw=n);let i=r?Dw:n;if(i===0)return 0;if(r){if(wo("color=16m")||wo("color=full")||wo("color=truecolor"))return 3;if(wo("color=256"))return 2}if("TF_BUILD"in Cr&&"AGENT_NAME"in Cr)return 1;if(t&&!e&&i===void 0)return 0;let o=i||0;if(Cr.TERM==="dumb")return o;if(JP.platform==="win32"){let s=che.release().split(".");return Number(s[0])>=10&&Number(s[2])>=10586?Number(s[2])>=14931?3:2:1}if("CI"in Cr)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(s=>s in Cr)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(s=>s in Cr)||Cr.CI_NAME==="codeship"?1:o;if("TEAMCITY_VERSION"in Cr)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Cr.TEAMCITY_VERSION)?1:0;if(Cr.COLORTERM==="truecolor"||Cr.TERM==="xterm-kitty"||Cr.TERM==="xterm-ghostty"||Cr.TERM==="wezterm")return 3;if("TERM_PROGRAM"in Cr){let s=Number.parseInt((Cr.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Cr.TERM_PROGRAM){case"iTerm.app":return s>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Cr.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Cr.TERM)||"COLORTERM"in Cr?1:o}function KP(t,e={}){let r=lhe(t,{streamIsTTY:t&&t.isTTY,...e});return dhe(r)}var Cr,Dw,fhe,phe,s9=N(()=>{({env:Cr}=JP);wo("no-color")||wo("no-colors")||wo("color=false")||wo("color=never")?Dw=0:(wo("color")||wo("colors")||wo("color=true")||wo("color=always"))&&(Dw=1);fhe={stdout:KP({isTTY:i9.isatty(1)}),stderr:KP({isTTY:i9.isatty(2)})},phe=fhe});var c9=ce((In,Nw)=>{var mhe=Nt("node:tty"),Bw=Nt("node:util");In.init=bhe;In.log=vhe;In.formatArgs=ghe;In.save=xhe;In.load=She;In.useColors=hhe;In.destroy=Bw.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");In.colors=[6,2,3,4,5,1];try{let t=(s9(),Vi(o9));t&&(t.stderr||t).level>=2&&(In.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}In.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let r=e.substring(6).toLowerCase().replace(/_([a-z])/g,(i,o)=>o.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),t[r]=n,t},{});function hhe(){return"colors"in In.inspectOpts?!!In.inspectOpts.colors:mhe.isatty(process.stderr.fd)}function ghe(t){let{namespace:e,useColors:r}=this;if(r){let n=this.color,i="\x1B[3"+(n<8?n:"8;5;"+n),o=` ${i};1m${e} \x1B[0m`;t[0]=o+t[0].split(`
3
+ `).join(`
4
+ `+o),t.push(i+"m+"+Nw.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=yhe()+e+" "+t[0]}function yhe(){return In.inspectOpts.hideDate?"":new Date().toISOString()+" "}function vhe(...t){return process.stderr.write(Bw.formatWithOptions(In.inspectOpts,...t)+`
5
+ `)}function xhe(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function She(){return process.env.DEBUG}function bhe(t){t.inspectOpts={};let e=Object.keys(In.inspectOpts);for(let r=0;r<e.length;r++)t.inspectOpts[e[r]]=In.inspectOpts[e[r]]}Nw.exports=zP()(In);var{formatters:a9}=Nw.exports;a9.o=function(t){return this.inspectOpts.colors=this.useColors,Bw.inspect(t,this.inspectOpts).split(`
6
+ `).map(e=>e.trim()).join(" ")};a9.O=function(t){return this.inspectOpts.colors=this.useColors,Bw.inspect(t,this.inspectOpts)}});var u9=ce((K3e,XP)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?XP.exports=n9():XP.exports=c9()});var Ow=ce(Np=>{"use strict";Object.defineProperty(Np,"__esModule",{value:!0});var whe=Nt("node:net");function Ihe(t){switch(whe.isIP(t)){case 4:return Buffer.from(t.split(".").map(i=>parseInt(i,10)));case 6:let e=t.split(":"),r=Buffer.alloc(16),n=0;e[e.length-1]===""&&(e[e.length-1]="0");for(let i=0;i<e.length;i++){if(e[i]===""){i+1<e.length&&e[i+1]!==""&&(n=16-(e.length-i-1)*2);continue}r.writeUInt16BE(parseInt(e[i],16),n),n+=2}return r;default:return null}}Np.bytesFromIP=Ihe;function Ehe(t){switch(t.length){case 4:return[t[0],t[1],t[2],t[3]].join(".");case 16:let e=[],r=-1,n=0,i=-1,o=0;for(let s=0;s<t.length;s+=2){let a=t[s]<<8|t[s+1];a===0?(n++,r===-1&&(r=e.length),n>o&&(o=n,i=r)):(r=-1,n=0),e.push(a.toString(16))}if(o>0){let s="",a=e.slice(i+o);e.length=i,e.length===0&&(s+=":"),a.length===0&&(s+=":"),e.push(s,...a)}return e.join(":");default:return""}}Np.bytesToIP=Ehe;var Mu=Object.create(null),d9=/^[0-9.]+$/;function khe(t){return d9.test(t)&&Mu[t]!==""?t:Mu[t]==null?"":Mu[t]}Np.getOID=khe;function Rhe(t){return!d9.test(t)&&Mu[t]!==""||Mu[t]==null?t:Mu[t]}Np.getOIDName=Rhe;function ue(t,e){Mu[t]=e,Mu[e]=t}ue("1.2.840.113549.1.1.1","rsaEncryption");ue("1.2.840.113549.1.1.4","md5WithRsaEncryption");ue("1.2.840.113549.1.1.5","sha1WithRsaEncryption");ue("1.2.840.113549.1.1.8","mgf1");ue("1.2.840.113549.1.1.10","RSASSA-PSS");ue("1.2.840.113549.1.1.11","sha256WithRsaEncryption");ue("1.2.840.113549.1.1.12","sha384WithRsaEncryption");ue("1.2.840.113549.1.1.13","sha512WithRsaEncryption");ue("1.2.840.10045.2.1","ecEncryption");ue("1.2.840.10045.4.1","ecdsaWithSha1");ue("1.2.840.10045.4.3.2","ecdsaWithSha256");ue("1.2.840.10045.4.3.3","ecdsaWithSha384");ue("1.2.840.10045.4.3.4","ecdsaWithSha512");ue("1.2.840.10040.4.3","dsaWithSha1");ue("2.16.840.1.101.3.4.3.2","dsaWithSha256");ue("1.3.14.3.2.7","desCBC");ue("1.3.14.3.2.26","sha1");ue("2.16.840.1.101.3.4.2.1","sha256");ue("2.16.840.1.101.3.4.2.2","sha384");ue("2.16.840.1.101.3.4.2.3","sha512");ue("1.2.840.113549.2.5","md5");ue("1.3.101.110","X25519");ue("1.3.101.111","X448");ue("1.3.101.112","Ed25519");ue("1.3.101.113","Ed448");ue("1.2.840.113549.1.7.1","data");ue("1.2.840.113549.1.7.2","signedData");ue("1.2.840.113549.1.7.3","envelopedData");ue("1.2.840.113549.1.7.4","signedAndEnvelopedData");ue("1.2.840.113549.1.7.5","digestedData");ue("1.2.840.113549.1.7.6","encryptedData");ue("1.2.840.113549.1.9.1","emailAddress");ue("1.2.840.113549.1.9.2","unstructuredName");ue("1.2.840.113549.1.9.3","contentType");ue("1.2.840.113549.1.9.4","messageDigest");ue("1.2.840.113549.1.9.5","signingTime");ue("1.2.840.113549.1.9.6","counterSignature");ue("1.2.840.113549.1.9.7","challengePassword");ue("1.2.840.113549.1.9.8","unstructuredAddress");ue("1.2.840.113549.1.9.14","extensionRequest");ue("1.2.840.113549.1.9.20","friendlyName");ue("1.2.840.113549.1.9.21","localKeyId");ue("1.2.840.113549.1.9.22.1","x509Certificate");ue("1.2.840.113549.1.12.10.1.1","keyBag");ue("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");ue("1.2.840.113549.1.12.10.1.3","certBag");ue("1.2.840.113549.1.12.10.1.4","crlBag");ue("1.2.840.113549.1.12.10.1.5","secretBag");ue("1.2.840.113549.1.12.10.1.6","safeContentsBag");ue("1.2.840.113549.1.5.13","pkcs5PBES2");ue("1.2.840.113549.1.5.12","pkcs5PBKDF2");ue("1.2.840.113549.2.7","hmacWithSha1");ue("1.2.840.113549.2.9","hmacWithSha256");ue("1.2.840.113549.2.10","hmacWithSha384");ue("1.2.840.113549.2.11","hmacWithSha512");ue("1.2.840.113549.3.7","3desCBC");ue("2.16.840.1.101.3.4.1.2","aesCBC128");ue("2.16.840.1.101.3.4.1.42","aesCBC256");ue("2.5.4.3","commonName");ue("2.5.4.5","serialName");ue("2.5.4.6","countryName");ue("2.5.4.7","localityName");ue("2.5.4.8","stateOrProvinceName");ue("2.5.4.10","organizationName");ue("2.5.4.11","organizationalUnitName");ue("2.5.4.15","businessCategory");ue("2.16.840.1.113730.1.1","nsCertType");ue("2.5.29.2","keyAttributes");ue("2.5.29.4","keyUsageRestriction");ue("2.5.29.6","subtreesConstraint");ue("2.5.29.9","subjectDirectoryAttributes");ue("2.5.29.14","subjectKeyIdentifier");ue("2.5.29.15","keyUsage");ue("2.5.29.16","privateKeyUsagePeriod");ue("2.5.29.17","subjectAltName");ue("2.5.29.18","issuerAltName");ue("2.5.29.19","basicConstraints");ue("2.5.29.20","cRLNumber");ue("2.5.29.21","cRLReason");ue("2.5.29.22","expirationDate");ue("2.5.29.23","instructionCode");ue("2.5.29.24","invalidityDate");ue("2.5.29.27","deltaCRLIndicator");ue("2.5.29.28","issuingDistributionPoint");ue("2.5.29.29","certificateIssuer");ue("2.5.29.30","nameConstraints");ue("2.5.29.31","cRLDistributionPoints");ue("2.5.29.32","certificatePolicies");ue("2.5.29.33","policyMappings");ue("2.5.29.35","authorityKeyIdentifier");ue("2.5.29.36","policyConstraints");ue("2.5.29.37","extKeyUsage");ue("2.5.29.46","freshestCRL");ue("2.5.29.54","inhibitAnyPolicy");ue("1.3.6.1.4.1.311.60.2.1.2","jurisdictionST");ue("1.3.6.1.4.1.311.60.2.1.3","jurisdictionC");ue("1.3.6.1.4.1.11129.2.4.2","timestampList");ue("1.3.6.1.5.5.7.1.1","authorityInfoAccess");ue("1.3.6.1.5.5.7.3.1","serverAuth");ue("1.3.6.1.5.5.7.3.2","clientAuth");ue("1.3.6.1.5.5.7.3.3","codeSigning");ue("1.3.6.1.5.5.7.3.4","emailProtection");ue("1.3.6.1.5.5.7.3.8","timeStamping");ue("1.3.6.1.5.5.7.48.1","authorityInfoAccessOcsp");ue("1.3.6.1.5.5.7.48.2","authorityInfoAccessIssuers")});var Lw=ce((X3e,Mw)=>{(function(t){"use strict";var e=function(y){var I,w=new Float64Array(16);if(y)for(I=0;I<y.length;I++)w[I]=y[I];return w},r=function(){throw new Error("no PRNG")},n=new Uint8Array(16),i=new Uint8Array(32);i[0]=9;var o=e(),s=e([1]),a=e([56129,1]),c=e([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),u=e([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),d=e([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),l=e([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),f=e([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function p(y,I,w,m){y[I]=w>>24&255,y[I+1]=w>>16&255,y[I+2]=w>>8&255,y[I+3]=w&255,y[I+4]=m>>24&255,y[I+5]=m>>16&255,y[I+6]=m>>8&255,y[I+7]=m&255}function g(y,I,w,m,E){var O,U=0;for(O=0;O<E;O++)U|=y[I+O]^w[m+O];return(1&U-1>>>8)-1}function v(y,I,w,m){return g(y,I,w,m,16)}function b(y,I,w,m){return g(y,I,w,m,32)}function C(y,I,w,m){for(var E=m[0]&255|(m[1]&255)<<8|(m[2]&255)<<16|(m[3]&255)<<24,O=w[0]&255|(w[1]&255)<<8|(w[2]&255)<<16|(w[3]&255)<<24,U=w[4]&255|(w[5]&255)<<8|(w[6]&255)<<16|(w[7]&255)<<24,ee=w[8]&255|(w[9]&255)<<8|(w[10]&255)<<16|(w[11]&255)<<24,Ie=w[12]&255|(w[13]&255)<<8|(w[14]&255)<<16|(w[15]&255)<<24,Qe=m[4]&255|(m[5]&255)<<8|(m[6]&255)<<16|(m[7]&255)<<24,He=I[0]&255|(I[1]&255)<<8|(I[2]&255)<<16|(I[3]&255)<<24,Jt=I[4]&255|(I[5]&255)<<8|(I[6]&255)<<16|(I[7]&255)<<24,We=I[8]&255|(I[9]&255)<<8|(I[10]&255)<<16|(I[11]&255)<<24,lt=I[12]&255|(I[13]&255)<<8|(I[14]&255)<<16|(I[15]&255)<<24,ht=m[8]&255|(m[9]&255)<<8|(m[10]&255)<<16|(m[11]&255)<<24,Et=w[16]&255|(w[17]&255)<<8|(w[18]&255)<<16|(w[19]&255)<<24,bt=w[20]&255|(w[21]&255)<<8|(w[22]&255)<<16|(w[23]&255)<<24,gt=w[24]&255|(w[25]&255)<<8|(w[26]&255)<<16|(w[27]&255)<<24,vt=w[28]&255|(w[29]&255)<<8|(w[30]&255)<<16|(w[31]&255)<<24,yt=m[12]&255|(m[13]&255)<<8|(m[14]&255)<<16|(m[15]&255)<<24,ze=E,nt=O,$e=U,Ke=ee,Ye=Ie,Oe=Qe,J=He,X=Jt,pe=We,Z=lt,te=ht,ve=Et,st=bt,kt=gt,Ct=vt,Rt=yt,A,Bt=0;Bt<20;Bt+=2)A=ze+st|0,Ye^=A<<7|A>>>25,A=Ye+ze|0,pe^=A<<9|A>>>23,A=pe+Ye|0,st^=A<<13|A>>>19,A=st+pe|0,ze^=A<<18|A>>>14,A=Oe+nt|0,Z^=A<<7|A>>>25,A=Z+Oe|0,kt^=A<<9|A>>>23,A=kt+Z|0,nt^=A<<13|A>>>19,A=nt+kt|0,Oe^=A<<18|A>>>14,A=te+J|0,Ct^=A<<7|A>>>25,A=Ct+te|0,$e^=A<<9|A>>>23,A=$e+Ct|0,J^=A<<13|A>>>19,A=J+$e|0,te^=A<<18|A>>>14,A=Rt+ve|0,Ke^=A<<7|A>>>25,A=Ke+Rt|0,X^=A<<9|A>>>23,A=X+Ke|0,ve^=A<<13|A>>>19,A=ve+X|0,Rt^=A<<18|A>>>14,A=ze+Ke|0,nt^=A<<7|A>>>25,A=nt+ze|0,$e^=A<<9|A>>>23,A=$e+nt|0,Ke^=A<<13|A>>>19,A=Ke+$e|0,ze^=A<<18|A>>>14,A=Oe+Ye|0,J^=A<<7|A>>>25,A=J+Oe|0,X^=A<<9|A>>>23,A=X+J|0,Ye^=A<<13|A>>>19,A=Ye+X|0,Oe^=A<<18|A>>>14,A=te+Z|0,ve^=A<<7|A>>>25,A=ve+te|0,pe^=A<<9|A>>>23,A=pe+ve|0,Z^=A<<13|A>>>19,A=Z+pe|0,te^=A<<18|A>>>14,A=Rt+Ct|0,st^=A<<7|A>>>25,A=st+Rt|0,kt^=A<<9|A>>>23,A=kt+st|0,Ct^=A<<13|A>>>19,A=Ct+kt|0,Rt^=A<<18|A>>>14;ze=ze+E|0,nt=nt+O|0,$e=$e+U|0,Ke=Ke+ee|0,Ye=Ye+Ie|0,Oe=Oe+Qe|0,J=J+He|0,X=X+Jt|0,pe=pe+We|0,Z=Z+lt|0,te=te+ht|0,ve=ve+Et|0,st=st+bt|0,kt=kt+gt|0,Ct=Ct+vt|0,Rt=Rt+yt|0,y[0]=ze>>>0&255,y[1]=ze>>>8&255,y[2]=ze>>>16&255,y[3]=ze>>>24&255,y[4]=nt>>>0&255,y[5]=nt>>>8&255,y[6]=nt>>>16&255,y[7]=nt>>>24&255,y[8]=$e>>>0&255,y[9]=$e>>>8&255,y[10]=$e>>>16&255,y[11]=$e>>>24&255,y[12]=Ke>>>0&255,y[13]=Ke>>>8&255,y[14]=Ke>>>16&255,y[15]=Ke>>>24&255,y[16]=Ye>>>0&255,y[17]=Ye>>>8&255,y[18]=Ye>>>16&255,y[19]=Ye>>>24&255,y[20]=Oe>>>0&255,y[21]=Oe>>>8&255,y[22]=Oe>>>16&255,y[23]=Oe>>>24&255,y[24]=J>>>0&255,y[25]=J>>>8&255,y[26]=J>>>16&255,y[27]=J>>>24&255,y[28]=X>>>0&255,y[29]=X>>>8&255,y[30]=X>>>16&255,y[31]=X>>>24&255,y[32]=pe>>>0&255,y[33]=pe>>>8&255,y[34]=pe>>>16&255,y[35]=pe>>>24&255,y[36]=Z>>>0&255,y[37]=Z>>>8&255,y[38]=Z>>>16&255,y[39]=Z>>>24&255,y[40]=te>>>0&255,y[41]=te>>>8&255,y[42]=te>>>16&255,y[43]=te>>>24&255,y[44]=ve>>>0&255,y[45]=ve>>>8&255,y[46]=ve>>>16&255,y[47]=ve>>>24&255,y[48]=st>>>0&255,y[49]=st>>>8&255,y[50]=st>>>16&255,y[51]=st>>>24&255,y[52]=kt>>>0&255,y[53]=kt>>>8&255,y[54]=kt>>>16&255,y[55]=kt>>>24&255,y[56]=Ct>>>0&255,y[57]=Ct>>>8&255,y[58]=Ct>>>16&255,y[59]=Ct>>>24&255,y[60]=Rt>>>0&255,y[61]=Rt>>>8&255,y[62]=Rt>>>16&255,y[63]=Rt>>>24&255}function D(y,I,w,m){for(var E=m[0]&255|(m[1]&255)<<8|(m[2]&255)<<16|(m[3]&255)<<24,O=w[0]&255|(w[1]&255)<<8|(w[2]&255)<<16|(w[3]&255)<<24,U=w[4]&255|(w[5]&255)<<8|(w[6]&255)<<16|(w[7]&255)<<24,ee=w[8]&255|(w[9]&255)<<8|(w[10]&255)<<16|(w[11]&255)<<24,Ie=w[12]&255|(w[13]&255)<<8|(w[14]&255)<<16|(w[15]&255)<<24,Qe=m[4]&255|(m[5]&255)<<8|(m[6]&255)<<16|(m[7]&255)<<24,He=I[0]&255|(I[1]&255)<<8|(I[2]&255)<<16|(I[3]&255)<<24,Jt=I[4]&255|(I[5]&255)<<8|(I[6]&255)<<16|(I[7]&255)<<24,We=I[8]&255|(I[9]&255)<<8|(I[10]&255)<<16|(I[11]&255)<<24,lt=I[12]&255|(I[13]&255)<<8|(I[14]&255)<<16|(I[15]&255)<<24,ht=m[8]&255|(m[9]&255)<<8|(m[10]&255)<<16|(m[11]&255)<<24,Et=w[16]&255|(w[17]&255)<<8|(w[18]&255)<<16|(w[19]&255)<<24,bt=w[20]&255|(w[21]&255)<<8|(w[22]&255)<<16|(w[23]&255)<<24,gt=w[24]&255|(w[25]&255)<<8|(w[26]&255)<<16|(w[27]&255)<<24,vt=w[28]&255|(w[29]&255)<<8|(w[30]&255)<<16|(w[31]&255)<<24,yt=m[12]&255|(m[13]&255)<<8|(m[14]&255)<<16|(m[15]&255)<<24,ze=E,nt=O,$e=U,Ke=ee,Ye=Ie,Oe=Qe,J=He,X=Jt,pe=We,Z=lt,te=ht,ve=Et,st=bt,kt=gt,Ct=vt,Rt=yt,A,Bt=0;Bt<20;Bt+=2)A=ze+st|0,Ye^=A<<7|A>>>25,A=Ye+ze|0,pe^=A<<9|A>>>23,A=pe+Ye|0,st^=A<<13|A>>>19,A=st+pe|0,ze^=A<<18|A>>>14,A=Oe+nt|0,Z^=A<<7|A>>>25,A=Z+Oe|0,kt^=A<<9|A>>>23,A=kt+Z|0,nt^=A<<13|A>>>19,A=nt+kt|0,Oe^=A<<18|A>>>14,A=te+J|0,Ct^=A<<7|A>>>25,A=Ct+te|0,$e^=A<<9|A>>>23,A=$e+Ct|0,J^=A<<13|A>>>19,A=J+$e|0,te^=A<<18|A>>>14,A=Rt+ve|0,Ke^=A<<7|A>>>25,A=Ke+Rt|0,X^=A<<9|A>>>23,A=X+Ke|0,ve^=A<<13|A>>>19,A=ve+X|0,Rt^=A<<18|A>>>14,A=ze+Ke|0,nt^=A<<7|A>>>25,A=nt+ze|0,$e^=A<<9|A>>>23,A=$e+nt|0,Ke^=A<<13|A>>>19,A=Ke+$e|0,ze^=A<<18|A>>>14,A=Oe+Ye|0,J^=A<<7|A>>>25,A=J+Oe|0,X^=A<<9|A>>>23,A=X+J|0,Ye^=A<<13|A>>>19,A=Ye+X|0,Oe^=A<<18|A>>>14,A=te+Z|0,ve^=A<<7|A>>>25,A=ve+te|0,pe^=A<<9|A>>>23,A=pe+ve|0,Z^=A<<13|A>>>19,A=Z+pe|0,te^=A<<18|A>>>14,A=Rt+Ct|0,st^=A<<7|A>>>25,A=st+Rt|0,kt^=A<<9|A>>>23,A=kt+st|0,Ct^=A<<13|A>>>19,A=Ct+kt|0,Rt^=A<<18|A>>>14;y[0]=ze>>>0&255,y[1]=ze>>>8&255,y[2]=ze>>>16&255,y[3]=ze>>>24&255,y[4]=Oe>>>0&255,y[5]=Oe>>>8&255,y[6]=Oe>>>16&255,y[7]=Oe>>>24&255,y[8]=te>>>0&255,y[9]=te>>>8&255,y[10]=te>>>16&255,y[11]=te>>>24&255,y[12]=Rt>>>0&255,y[13]=Rt>>>8&255,y[14]=Rt>>>16&255,y[15]=Rt>>>24&255,y[16]=J>>>0&255,y[17]=J>>>8&255,y[18]=J>>>16&255,y[19]=J>>>24&255,y[20]=X>>>0&255,y[21]=X>>>8&255,y[22]=X>>>16&255,y[23]=X>>>24&255,y[24]=pe>>>0&255,y[25]=pe>>>8&255,y[26]=pe>>>16&255,y[27]=pe>>>24&255,y[28]=Z>>>0&255,y[29]=Z>>>8&255,y[30]=Z>>>16&255,y[31]=Z>>>24&255}function _(y,I,w,m){C(y,I,w,m)}function F(y,I,w,m){D(y,I,w,m)}var he=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function z(y,I,w,m,E,O,U){var ee=new Uint8Array(16),Ie=new Uint8Array(64),Qe,He;for(He=0;He<16;He++)ee[He]=0;for(He=0;He<8;He++)ee[He]=O[He];for(;E>=64;){for(_(Ie,ee,U,he),He=0;He<64;He++)y[I+He]=w[m+He]^Ie[He];for(Qe=1,He=8;He<16;He++)Qe=Qe+(ee[He]&255)|0,ee[He]=Qe&255,Qe>>>=8;E-=64,I+=64,m+=64}if(E>0)for(_(Ie,ee,U,he),He=0;He<E;He++)y[I+He]=w[m+He]^Ie[He];return 0}function Ce(y,I,w,m,E){var O=new Uint8Array(16),U=new Uint8Array(64),ee,Ie;for(Ie=0;Ie<16;Ie++)O[Ie]=0;for(Ie=0;Ie<8;Ie++)O[Ie]=m[Ie];for(;w>=64;){for(_(U,O,E,he),Ie=0;Ie<64;Ie++)y[I+Ie]=U[Ie];for(ee=1,Ie=8;Ie<16;Ie++)ee=ee+(O[Ie]&255)|0,O[Ie]=ee&255,ee>>>=8;w-=64,I+=64}if(w>0)for(_(U,O,E,he),Ie=0;Ie<w;Ie++)y[I+Ie]=U[Ie];return 0}function de(y,I,w,m,E){var O=new Uint8Array(32);F(O,m,E,he);for(var U=new Uint8Array(8),ee=0;ee<8;ee++)U[ee]=m[ee+16];return Ce(y,I,w,U,O)}function R(y,I,w,m,E,O,U){var ee=new Uint8Array(32);F(ee,O,U,he);for(var Ie=new Uint8Array(8),Qe=0;Qe<8;Qe++)Ie[Qe]=O[Qe+16];return z(y,I,w,m,E,Ie,ee)}var V=function(y){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var I,w,m,E,O,U,ee,Ie;I=y[0]&255|(y[1]&255)<<8,this.r[0]=I&8191,w=y[2]&255|(y[3]&255)<<8,this.r[1]=(I>>>13|w<<3)&8191,m=y[4]&255|(y[5]&255)<<8,this.r[2]=(w>>>10|m<<6)&7939,E=y[6]&255|(y[7]&255)<<8,this.r[3]=(m>>>7|E<<9)&8191,O=y[8]&255|(y[9]&255)<<8,this.r[4]=(E>>>4|O<<12)&255,this.r[5]=O>>>1&8190,U=y[10]&255|(y[11]&255)<<8,this.r[6]=(O>>>14|U<<2)&8191,ee=y[12]&255|(y[13]&255)<<8,this.r[7]=(U>>>11|ee<<5)&8065,Ie=y[14]&255|(y[15]&255)<<8,this.r[8]=(ee>>>8|Ie<<8)&8191,this.r[9]=Ie>>>5&127,this.pad[0]=y[16]&255|(y[17]&255)<<8,this.pad[1]=y[18]&255|(y[19]&255)<<8,this.pad[2]=y[20]&255|(y[21]&255)<<8,this.pad[3]=y[22]&255|(y[23]&255)<<8,this.pad[4]=y[24]&255|(y[25]&255)<<8,this.pad[5]=y[26]&255|(y[27]&255)<<8,this.pad[6]=y[28]&255|(y[29]&255)<<8,this.pad[7]=y[30]&255|(y[31]&255)<<8};V.prototype.blocks=function(y,I,w){for(var m=this.fin?0:2048,E,O,U,ee,Ie,Qe,He,Jt,We,lt,ht,Et,bt,gt,vt,yt,ze,nt,$e,Ke=this.h[0],Ye=this.h[1],Oe=this.h[2],J=this.h[3],X=this.h[4],pe=this.h[5],Z=this.h[6],te=this.h[7],ve=this.h[8],st=this.h[9],kt=this.r[0],Ct=this.r[1],Rt=this.r[2],A=this.r[3],Bt=this.r[4],Xt=this.r[5],Yt=this.r[6],Tt=this.r[7],Wt=this.r[8],Vt=this.r[9];w>=16;)E=y[I+0]&255|(y[I+1]&255)<<8,Ke+=E&8191,O=y[I+2]&255|(y[I+3]&255)<<8,Ye+=(E>>>13|O<<3)&8191,U=y[I+4]&255|(y[I+5]&255)<<8,Oe+=(O>>>10|U<<6)&8191,ee=y[I+6]&255|(y[I+7]&255)<<8,J+=(U>>>7|ee<<9)&8191,Ie=y[I+8]&255|(y[I+9]&255)<<8,X+=(ee>>>4|Ie<<12)&8191,pe+=Ie>>>1&8191,Qe=y[I+10]&255|(y[I+11]&255)<<8,Z+=(Ie>>>14|Qe<<2)&8191,He=y[I+12]&255|(y[I+13]&255)<<8,te+=(Qe>>>11|He<<5)&8191,Jt=y[I+14]&255|(y[I+15]&255)<<8,ve+=(He>>>8|Jt<<8)&8191,st+=Jt>>>5|m,We=0,lt=We,lt+=Ke*kt,lt+=Ye*(5*Vt),lt+=Oe*(5*Wt),lt+=J*(5*Tt),lt+=X*(5*Yt),We=lt>>>13,lt&=8191,lt+=pe*(5*Xt),lt+=Z*(5*Bt),lt+=te*(5*A),lt+=ve*(5*Rt),lt+=st*(5*Ct),We+=lt>>>13,lt&=8191,ht=We,ht+=Ke*Ct,ht+=Ye*kt,ht+=Oe*(5*Vt),ht+=J*(5*Wt),ht+=X*(5*Tt),We=ht>>>13,ht&=8191,ht+=pe*(5*Yt),ht+=Z*(5*Xt),ht+=te*(5*Bt),ht+=ve*(5*A),ht+=st*(5*Rt),We+=ht>>>13,ht&=8191,Et=We,Et+=Ke*Rt,Et+=Ye*Ct,Et+=Oe*kt,Et+=J*(5*Vt),Et+=X*(5*Wt),We=Et>>>13,Et&=8191,Et+=pe*(5*Tt),Et+=Z*(5*Yt),Et+=te*(5*Xt),Et+=ve*(5*Bt),Et+=st*(5*A),We+=Et>>>13,Et&=8191,bt=We,bt+=Ke*A,bt+=Ye*Rt,bt+=Oe*Ct,bt+=J*kt,bt+=X*(5*Vt),We=bt>>>13,bt&=8191,bt+=pe*(5*Wt),bt+=Z*(5*Tt),bt+=te*(5*Yt),bt+=ve*(5*Xt),bt+=st*(5*Bt),We+=bt>>>13,bt&=8191,gt=We,gt+=Ke*Bt,gt+=Ye*A,gt+=Oe*Rt,gt+=J*Ct,gt+=X*kt,We=gt>>>13,gt&=8191,gt+=pe*(5*Vt),gt+=Z*(5*Wt),gt+=te*(5*Tt),gt+=ve*(5*Yt),gt+=st*(5*Xt),We+=gt>>>13,gt&=8191,vt=We,vt+=Ke*Xt,vt+=Ye*Bt,vt+=Oe*A,vt+=J*Rt,vt+=X*Ct,We=vt>>>13,vt&=8191,vt+=pe*kt,vt+=Z*(5*Vt),vt+=te*(5*Wt),vt+=ve*(5*Tt),vt+=st*(5*Yt),We+=vt>>>13,vt&=8191,yt=We,yt+=Ke*Yt,yt+=Ye*Xt,yt+=Oe*Bt,yt+=J*A,yt+=X*Rt,We=yt>>>13,yt&=8191,yt+=pe*Ct,yt+=Z*kt,yt+=te*(5*Vt),yt+=ve*(5*Wt),yt+=st*(5*Tt),We+=yt>>>13,yt&=8191,ze=We,ze+=Ke*Tt,ze+=Ye*Yt,ze+=Oe*Xt,ze+=J*Bt,ze+=X*A,We=ze>>>13,ze&=8191,ze+=pe*Rt,ze+=Z*Ct,ze+=te*kt,ze+=ve*(5*Vt),ze+=st*(5*Wt),We+=ze>>>13,ze&=8191,nt=We,nt+=Ke*Wt,nt+=Ye*Tt,nt+=Oe*Yt,nt+=J*Xt,nt+=X*Bt,We=nt>>>13,nt&=8191,nt+=pe*A,nt+=Z*Rt,nt+=te*Ct,nt+=ve*kt,nt+=st*(5*Vt),We+=nt>>>13,nt&=8191,$e=We,$e+=Ke*Vt,$e+=Ye*Wt,$e+=Oe*Tt,$e+=J*Yt,$e+=X*Xt,We=$e>>>13,$e&=8191,$e+=pe*Bt,$e+=Z*A,$e+=te*Rt,$e+=ve*Ct,$e+=st*kt,We+=$e>>>13,$e&=8191,We=(We<<2)+We|0,We=We+lt|0,lt=We&8191,We=We>>>13,ht+=We,Ke=lt,Ye=ht,Oe=Et,J=bt,X=gt,pe=vt,Z=yt,te=ze,ve=nt,st=$e,I+=16,w-=16;this.h[0]=Ke,this.h[1]=Ye,this.h[2]=Oe,this.h[3]=J,this.h[4]=X,this.h[5]=pe,this.h[6]=Z,this.h[7]=te,this.h[8]=ve,this.h[9]=st},V.prototype.finish=function(y,I){var w=new Uint16Array(10),m,E,O,U;if(this.leftover){for(U=this.leftover,this.buffer[U++]=1;U<16;U++)this.buffer[U]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(m=this.h[1]>>>13,this.h[1]&=8191,U=2;U<10;U++)this.h[U]+=m,m=this.h[U]>>>13,this.h[U]&=8191;for(this.h[0]+=m*5,m=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=m,m=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=m,w[0]=this.h[0]+5,m=w[0]>>>13,w[0]&=8191,U=1;U<10;U++)w[U]=this.h[U]+m,m=w[U]>>>13,w[U]&=8191;for(w[9]-=8192,E=(m^1)-1,U=0;U<10;U++)w[U]&=E;for(E=~E,U=0;U<10;U++)this.h[U]=this.h[U]&E|w[U];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,O=this.h[0]+this.pad[0],this.h[0]=O&65535,U=1;U<8;U++)O=(this.h[U]+this.pad[U]|0)+(O>>>16)|0,this.h[U]=O&65535;y[I+0]=this.h[0]>>>0&255,y[I+1]=this.h[0]>>>8&255,y[I+2]=this.h[1]>>>0&255,y[I+3]=this.h[1]>>>8&255,y[I+4]=this.h[2]>>>0&255,y[I+5]=this.h[2]>>>8&255,y[I+6]=this.h[3]>>>0&255,y[I+7]=this.h[3]>>>8&255,y[I+8]=this.h[4]>>>0&255,y[I+9]=this.h[4]>>>8&255,y[I+10]=this.h[5]>>>0&255,y[I+11]=this.h[5]>>>8&255,y[I+12]=this.h[6]>>>0&255,y[I+13]=this.h[6]>>>8&255,y[I+14]=this.h[7]>>>0&255,y[I+15]=this.h[7]>>>8&255},V.prototype.update=function(y,I,w){var m,E;if(this.leftover){for(E=16-this.leftover,E>w&&(E=w),m=0;m<E;m++)this.buffer[this.leftover+m]=y[I+m];if(w-=E,I+=E,this.leftover+=E,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(w>=16&&(E=w-w%16,this.blocks(y,I,E),I+=E,w-=E),w){for(m=0;m<w;m++)this.buffer[this.leftover+m]=y[I+m];this.leftover+=w}};function le(y,I,w,m,E,O){var U=new V(O);return U.update(w,m,E),U.finish(y,I),0}function se(y,I,w,m,E,O){var U=new Uint8Array(16);return le(U,0,w,m,E,O),v(y,I,U,0)}function H(y,I,w,m,E){var O;if(w<32)return-1;for(R(y,0,I,0,w,m,E),le(y,16,y,32,w-32,y),O=0;O<16;O++)y[O]=0;return 0}function G(y,I,w,m,E){var O,U=new Uint8Array(32);if(w<32||(de(U,0,32,m,E),se(I,16,I,32,w-32,U)!==0))return-1;for(R(y,0,I,0,w,m,E),O=0;O<32;O++)y[O]=0;return 0}function j(y,I){var w;for(w=0;w<16;w++)y[w]=I[w]|0}function me(y){var I,w,m=1;for(I=0;I<16;I++)w=y[I]+m+65535,m=Math.floor(w/65536),y[I]=w-m*65536;y[0]+=m-1+37*(m-1)}function Pe(y,I,w){for(var m,E=~(w-1),O=0;O<16;O++)m=E&(y[O]^I[O]),y[O]^=m,I[O]^=m}function Te(y,I){var w,m,E,O=e(),U=e();for(w=0;w<16;w++)U[w]=I[w];for(me(U),me(U),me(U),m=0;m<2;m++){for(O[0]=U[0]-65517,w=1;w<15;w++)O[w]=U[w]-65535-(O[w-1]>>16&1),O[w-1]&=65535;O[15]=U[15]-32767-(O[14]>>16&1),E=O[15]>>16&1,O[14]&=65535,Pe(U,O,1-E)}for(w=0;w<16;w++)y[2*w]=U[w]&255,y[2*w+1]=U[w]>>8}function P(y,I){var w=new Uint8Array(32),m=new Uint8Array(32);return Te(w,y),Te(m,I),b(w,0,m,0)}function B(y){var I=new Uint8Array(32);return Te(I,y),I[0]&1}function K(y,I){var w;for(w=0;w<16;w++)y[w]=I[2*w]+(I[2*w+1]<<8);y[15]&=32767}function T(y,I,w){for(var m=0;m<16;m++)y[m]=I[m]+w[m]}function $(y,I,w){for(var m=0;m<16;m++)y[m]=I[m]-w[m]}function ye(y,I,w){var m,E,O=0,U=0,ee=0,Ie=0,Qe=0,He=0,Jt=0,We=0,lt=0,ht=0,Et=0,bt=0,gt=0,vt=0,yt=0,ze=0,nt=0,$e=0,Ke=0,Ye=0,Oe=0,J=0,X=0,pe=0,Z=0,te=0,ve=0,st=0,kt=0,Ct=0,Rt=0,A=w[0],Bt=w[1],Xt=w[2],Yt=w[3],Tt=w[4],Wt=w[5],Vt=w[6],zr=w[7],ir=w[8],Lr=w[9],Hr=w[10],Ur=w[11],cn=w[12],jn=w[13],qn=w[14],Wn=w[15];m=I[0],O+=m*A,U+=m*Bt,ee+=m*Xt,Ie+=m*Yt,Qe+=m*Tt,He+=m*Wt,Jt+=m*Vt,We+=m*zr,lt+=m*ir,ht+=m*Lr,Et+=m*Hr,bt+=m*Ur,gt+=m*cn,vt+=m*jn,yt+=m*qn,ze+=m*Wn,m=I[1],U+=m*A,ee+=m*Bt,Ie+=m*Xt,Qe+=m*Yt,He+=m*Tt,Jt+=m*Wt,We+=m*Vt,lt+=m*zr,ht+=m*ir,Et+=m*Lr,bt+=m*Hr,gt+=m*Ur,vt+=m*cn,yt+=m*jn,ze+=m*qn,nt+=m*Wn,m=I[2],ee+=m*A,Ie+=m*Bt,Qe+=m*Xt,He+=m*Yt,Jt+=m*Tt,We+=m*Wt,lt+=m*Vt,ht+=m*zr,Et+=m*ir,bt+=m*Lr,gt+=m*Hr,vt+=m*Ur,yt+=m*cn,ze+=m*jn,nt+=m*qn,$e+=m*Wn,m=I[3],Ie+=m*A,Qe+=m*Bt,He+=m*Xt,Jt+=m*Yt,We+=m*Tt,lt+=m*Wt,ht+=m*Vt,Et+=m*zr,bt+=m*ir,gt+=m*Lr,vt+=m*Hr,yt+=m*Ur,ze+=m*cn,nt+=m*jn,$e+=m*qn,Ke+=m*Wn,m=I[4],Qe+=m*A,He+=m*Bt,Jt+=m*Xt,We+=m*Yt,lt+=m*Tt,ht+=m*Wt,Et+=m*Vt,bt+=m*zr,gt+=m*ir,vt+=m*Lr,yt+=m*Hr,ze+=m*Ur,nt+=m*cn,$e+=m*jn,Ke+=m*qn,Ye+=m*Wn,m=I[5],He+=m*A,Jt+=m*Bt,We+=m*Xt,lt+=m*Yt,ht+=m*Tt,Et+=m*Wt,bt+=m*Vt,gt+=m*zr,vt+=m*ir,yt+=m*Lr,ze+=m*Hr,nt+=m*Ur,$e+=m*cn,Ke+=m*jn,Ye+=m*qn,Oe+=m*Wn,m=I[6],Jt+=m*A,We+=m*Bt,lt+=m*Xt,ht+=m*Yt,Et+=m*Tt,bt+=m*Wt,gt+=m*Vt,vt+=m*zr,yt+=m*ir,ze+=m*Lr,nt+=m*Hr,$e+=m*Ur,Ke+=m*cn,Ye+=m*jn,Oe+=m*qn,J+=m*Wn,m=I[7],We+=m*A,lt+=m*Bt,ht+=m*Xt,Et+=m*Yt,bt+=m*Tt,gt+=m*Wt,vt+=m*Vt,yt+=m*zr,ze+=m*ir,nt+=m*Lr,$e+=m*Hr,Ke+=m*Ur,Ye+=m*cn,Oe+=m*jn,J+=m*qn,X+=m*Wn,m=I[8],lt+=m*A,ht+=m*Bt,Et+=m*Xt,bt+=m*Yt,gt+=m*Tt,vt+=m*Wt,yt+=m*Vt,ze+=m*zr,nt+=m*ir,$e+=m*Lr,Ke+=m*Hr,Ye+=m*Ur,Oe+=m*cn,J+=m*jn,X+=m*qn,pe+=m*Wn,m=I[9],ht+=m*A,Et+=m*Bt,bt+=m*Xt,gt+=m*Yt,vt+=m*Tt,yt+=m*Wt,ze+=m*Vt,nt+=m*zr,$e+=m*ir,Ke+=m*Lr,Ye+=m*Hr,Oe+=m*Ur,J+=m*cn,X+=m*jn,pe+=m*qn,Z+=m*Wn,m=I[10],Et+=m*A,bt+=m*Bt,gt+=m*Xt,vt+=m*Yt,yt+=m*Tt,ze+=m*Wt,nt+=m*Vt,$e+=m*zr,Ke+=m*ir,Ye+=m*Lr,Oe+=m*Hr,J+=m*Ur,X+=m*cn,pe+=m*jn,Z+=m*qn,te+=m*Wn,m=I[11],bt+=m*A,gt+=m*Bt,vt+=m*Xt,yt+=m*Yt,ze+=m*Tt,nt+=m*Wt,$e+=m*Vt,Ke+=m*zr,Ye+=m*ir,Oe+=m*Lr,J+=m*Hr,X+=m*Ur,pe+=m*cn,Z+=m*jn,te+=m*qn,ve+=m*Wn,m=I[12],gt+=m*A,vt+=m*Bt,yt+=m*Xt,ze+=m*Yt,nt+=m*Tt,$e+=m*Wt,Ke+=m*Vt,Ye+=m*zr,Oe+=m*ir,J+=m*Lr,X+=m*Hr,pe+=m*Ur,Z+=m*cn,te+=m*jn,ve+=m*qn,st+=m*Wn,m=I[13],vt+=m*A,yt+=m*Bt,ze+=m*Xt,nt+=m*Yt,$e+=m*Tt,Ke+=m*Wt,Ye+=m*Vt,Oe+=m*zr,J+=m*ir,X+=m*Lr,pe+=m*Hr,Z+=m*Ur,te+=m*cn,ve+=m*jn,st+=m*qn,kt+=m*Wn,m=I[14],yt+=m*A,ze+=m*Bt,nt+=m*Xt,$e+=m*Yt,Ke+=m*Tt,Ye+=m*Wt,Oe+=m*Vt,J+=m*zr,X+=m*ir,pe+=m*Lr,Z+=m*Hr,te+=m*Ur,ve+=m*cn,st+=m*jn,kt+=m*qn,Ct+=m*Wn,m=I[15],ze+=m*A,nt+=m*Bt,$e+=m*Xt,Ke+=m*Yt,Ye+=m*Tt,Oe+=m*Wt,J+=m*Vt,X+=m*zr,pe+=m*ir,Z+=m*Lr,te+=m*Hr,ve+=m*Ur,st+=m*cn,kt+=m*jn,Ct+=m*qn,Rt+=m*Wn,O+=38*nt,U+=38*$e,ee+=38*Ke,Ie+=38*Ye,Qe+=38*Oe,He+=38*J,Jt+=38*X,We+=38*pe,lt+=38*Z,ht+=38*te,Et+=38*ve,bt+=38*st,gt+=38*kt,vt+=38*Ct,yt+=38*Rt,E=1,m=O+E+65535,E=Math.floor(m/65536),O=m-E*65536,m=U+E+65535,E=Math.floor(m/65536),U=m-E*65536,m=ee+E+65535,E=Math.floor(m/65536),ee=m-E*65536,m=Ie+E+65535,E=Math.floor(m/65536),Ie=m-E*65536,m=Qe+E+65535,E=Math.floor(m/65536),Qe=m-E*65536,m=He+E+65535,E=Math.floor(m/65536),He=m-E*65536,m=Jt+E+65535,E=Math.floor(m/65536),Jt=m-E*65536,m=We+E+65535,E=Math.floor(m/65536),We=m-E*65536,m=lt+E+65535,E=Math.floor(m/65536),lt=m-E*65536,m=ht+E+65535,E=Math.floor(m/65536),ht=m-E*65536,m=Et+E+65535,E=Math.floor(m/65536),Et=m-E*65536,m=bt+E+65535,E=Math.floor(m/65536),bt=m-E*65536,m=gt+E+65535,E=Math.floor(m/65536),gt=m-E*65536,m=vt+E+65535,E=Math.floor(m/65536),vt=m-E*65536,m=yt+E+65535,E=Math.floor(m/65536),yt=m-E*65536,m=ze+E+65535,E=Math.floor(m/65536),ze=m-E*65536,O+=E-1+37*(E-1),E=1,m=O+E+65535,E=Math.floor(m/65536),O=m-E*65536,m=U+E+65535,E=Math.floor(m/65536),U=m-E*65536,m=ee+E+65535,E=Math.floor(m/65536),ee=m-E*65536,m=Ie+E+65535,E=Math.floor(m/65536),Ie=m-E*65536,m=Qe+E+65535,E=Math.floor(m/65536),Qe=m-E*65536,m=He+E+65535,E=Math.floor(m/65536),He=m-E*65536,m=Jt+E+65535,E=Math.floor(m/65536),Jt=m-E*65536,m=We+E+65535,E=Math.floor(m/65536),We=m-E*65536,m=lt+E+65535,E=Math.floor(m/65536),lt=m-E*65536,m=ht+E+65535,E=Math.floor(m/65536),ht=m-E*65536,m=Et+E+65535,E=Math.floor(m/65536),Et=m-E*65536,m=bt+E+65535,E=Math.floor(m/65536),bt=m-E*65536,m=gt+E+65535,E=Math.floor(m/65536),gt=m-E*65536,m=vt+E+65535,E=Math.floor(m/65536),vt=m-E*65536,m=yt+E+65535,E=Math.floor(m/65536),yt=m-E*65536,m=ze+E+65535,E=Math.floor(m/65536),ze=m-E*65536,O+=E-1+37*(E-1),y[0]=O,y[1]=U,y[2]=ee,y[3]=Ie,y[4]=Qe,y[5]=He,y[6]=Jt,y[7]=We,y[8]=lt,y[9]=ht,y[10]=Et,y[11]=bt,y[12]=gt,y[13]=vt,y[14]=yt,y[15]=ze}function be(y,I){ye(y,I,I)}function ct(y,I){var w=e(),m;for(m=0;m<16;m++)w[m]=I[m];for(m=253;m>=0;m--)be(w,w),m!==2&&m!==4&&ye(w,w,I);for(m=0;m<16;m++)y[m]=w[m]}function It(y,I){var w=e(),m;for(m=0;m<16;m++)w[m]=I[m];for(m=250;m>=0;m--)be(w,w),m!==1&&ye(w,w,I);for(m=0;m<16;m++)y[m]=w[m]}function Zt(y,I,w){var m=new Uint8Array(32),E=new Float64Array(80),O,U,ee=e(),Ie=e(),Qe=e(),He=e(),Jt=e(),We=e();for(U=0;U<31;U++)m[U]=I[U];for(m[31]=I[31]&127|64,m[0]&=248,K(E,w),U=0;U<16;U++)Ie[U]=E[U],He[U]=ee[U]=Qe[U]=0;for(ee[0]=He[0]=1,U=254;U>=0;--U)O=m[U>>>3]>>>(U&7)&1,Pe(ee,Ie,O),Pe(Qe,He,O),T(Jt,ee,Qe),$(ee,ee,Qe),T(Qe,Ie,He),$(Ie,Ie,He),be(He,Jt),be(We,ee),ye(ee,Qe,ee),ye(Qe,Ie,Jt),T(Jt,ee,Qe),$(ee,ee,Qe),be(Ie,ee),$(Qe,He,We),ye(ee,Qe,a),T(ee,ee,He),ye(Qe,Qe,ee),ye(ee,He,We),ye(He,Ie,E),be(Ie,Jt),Pe(ee,Ie,O),Pe(Qe,He,O);for(U=0;U<16;U++)E[U+16]=ee[U],E[U+32]=Qe[U],E[U+48]=Ie[U],E[U+64]=He[U];var lt=E.subarray(32),ht=E.subarray(16);return ct(lt,lt),ye(ht,ht,lt),Te(y,ht),0}function Dt(y,I){return Zt(y,I,i)}function _t(y,I){return r(I,32),Dt(y,I)}function lo(y,I,w){var m=new Uint8Array(32);return Zt(m,w,I),F(y,n,m,he)}var fo=H,jd=G;function QR(y,I,w,m,E,O){var U=new Uint8Array(32);return lo(U,E,O),fo(y,I,w,m,U)}function Vh(y,I,w,m,E,O){var U=new Uint8Array(32);return lo(U,E,O),jd(y,I,w,m,U)}var Gh=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function zh(y,I,w,m){for(var E=new Int32Array(16),O=new Int32Array(16),U,ee,Ie,Qe,He,Jt,We,lt,ht,Et,bt,gt,vt,yt,ze,nt,$e,Ke,Ye,Oe,J,X,pe,Z,te,ve,st=y[0],kt=y[1],Ct=y[2],Rt=y[3],A=y[4],Bt=y[5],Xt=y[6],Yt=y[7],Tt=I[0],Wt=I[1],Vt=I[2],zr=I[3],ir=I[4],Lr=I[5],Hr=I[6],Ur=I[7],cn=0;m>=128;){for(Ye=0;Ye<16;Ye++)Oe=8*Ye+cn,E[Ye]=w[Oe+0]<<24|w[Oe+1]<<16|w[Oe+2]<<8|w[Oe+3],O[Ye]=w[Oe+4]<<24|w[Oe+5]<<16|w[Oe+6]<<8|w[Oe+7];for(Ye=0;Ye<80;Ye++)if(U=st,ee=kt,Ie=Ct,Qe=Rt,He=A,Jt=Bt,We=Xt,lt=Yt,ht=Tt,Et=Wt,bt=Vt,gt=zr,vt=ir,yt=Lr,ze=Hr,nt=Ur,J=Yt,X=Ur,pe=X&65535,Z=X>>>16,te=J&65535,ve=J>>>16,J=(A>>>14|ir<<18)^(A>>>18|ir<<14)^(ir>>>9|A<<23),X=(ir>>>14|A<<18)^(ir>>>18|A<<14)^(A>>>9|ir<<23),pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,J=A&Bt^~A&Xt,X=ir&Lr^~ir&Hr,pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,J=Gh[Ye*2],X=Gh[Ye*2+1],pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,J=E[Ye%16],X=O[Ye%16],pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,Z+=pe>>>16,te+=Z>>>16,ve+=te>>>16,$e=te&65535|ve<<16,Ke=pe&65535|Z<<16,J=$e,X=Ke,pe=X&65535,Z=X>>>16,te=J&65535,ve=J>>>16,J=(st>>>28|Tt<<4)^(Tt>>>2|st<<30)^(Tt>>>7|st<<25),X=(Tt>>>28|st<<4)^(st>>>2|Tt<<30)^(st>>>7|Tt<<25),pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,J=st&kt^st&Ct^kt&Ct,X=Tt&Wt^Tt&Vt^Wt&Vt,pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,Z+=pe>>>16,te+=Z>>>16,ve+=te>>>16,lt=te&65535|ve<<16,nt=pe&65535|Z<<16,J=Qe,X=gt,pe=X&65535,Z=X>>>16,te=J&65535,ve=J>>>16,J=$e,X=Ke,pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,Z+=pe>>>16,te+=Z>>>16,ve+=te>>>16,Qe=te&65535|ve<<16,gt=pe&65535|Z<<16,kt=U,Ct=ee,Rt=Ie,A=Qe,Bt=He,Xt=Jt,Yt=We,st=lt,Wt=ht,Vt=Et,zr=bt,ir=gt,Lr=vt,Hr=yt,Ur=ze,Tt=nt,Ye%16===15)for(Oe=0;Oe<16;Oe++)J=E[Oe],X=O[Oe],pe=X&65535,Z=X>>>16,te=J&65535,ve=J>>>16,J=E[(Oe+9)%16],X=O[(Oe+9)%16],pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,$e=E[(Oe+1)%16],Ke=O[(Oe+1)%16],J=($e>>>1|Ke<<31)^($e>>>8|Ke<<24)^$e>>>7,X=(Ke>>>1|$e<<31)^(Ke>>>8|$e<<24)^(Ke>>>7|$e<<25),pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,$e=E[(Oe+14)%16],Ke=O[(Oe+14)%16],J=($e>>>19|Ke<<13)^(Ke>>>29|$e<<3)^$e>>>6,X=(Ke>>>19|$e<<13)^($e>>>29|Ke<<3)^(Ke>>>6|$e<<26),pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,Z+=pe>>>16,te+=Z>>>16,ve+=te>>>16,E[Oe]=te&65535|ve<<16,O[Oe]=pe&65535|Z<<16;J=st,X=Tt,pe=X&65535,Z=X>>>16,te=J&65535,ve=J>>>16,J=y[0],X=I[0],pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,Z+=pe>>>16,te+=Z>>>16,ve+=te>>>16,y[0]=st=te&65535|ve<<16,I[0]=Tt=pe&65535|Z<<16,J=kt,X=Wt,pe=X&65535,Z=X>>>16,te=J&65535,ve=J>>>16,J=y[1],X=I[1],pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,Z+=pe>>>16,te+=Z>>>16,ve+=te>>>16,y[1]=kt=te&65535|ve<<16,I[1]=Wt=pe&65535|Z<<16,J=Ct,X=Vt,pe=X&65535,Z=X>>>16,te=J&65535,ve=J>>>16,J=y[2],X=I[2],pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,Z+=pe>>>16,te+=Z>>>16,ve+=te>>>16,y[2]=Ct=te&65535|ve<<16,I[2]=Vt=pe&65535|Z<<16,J=Rt,X=zr,pe=X&65535,Z=X>>>16,te=J&65535,ve=J>>>16,J=y[3],X=I[3],pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,Z+=pe>>>16,te+=Z>>>16,ve+=te>>>16,y[3]=Rt=te&65535|ve<<16,I[3]=zr=pe&65535|Z<<16,J=A,X=ir,pe=X&65535,Z=X>>>16,te=J&65535,ve=J>>>16,J=y[4],X=I[4],pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,Z+=pe>>>16,te+=Z>>>16,ve+=te>>>16,y[4]=A=te&65535|ve<<16,I[4]=ir=pe&65535|Z<<16,J=Bt,X=Lr,pe=X&65535,Z=X>>>16,te=J&65535,ve=J>>>16,J=y[5],X=I[5],pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,Z+=pe>>>16,te+=Z>>>16,ve+=te>>>16,y[5]=Bt=te&65535|ve<<16,I[5]=Lr=pe&65535|Z<<16,J=Xt,X=Hr,pe=X&65535,Z=X>>>16,te=J&65535,ve=J>>>16,J=y[6],X=I[6],pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,Z+=pe>>>16,te+=Z>>>16,ve+=te>>>16,y[6]=Xt=te&65535|ve<<16,I[6]=Hr=pe&65535|Z<<16,J=Yt,X=Ur,pe=X&65535,Z=X>>>16,te=J&65535,ve=J>>>16,J=y[7],X=I[7],pe+=X&65535,Z+=X>>>16,te+=J&65535,ve+=J>>>16,Z+=pe>>>16,te+=Z>>>16,ve+=te>>>16,y[7]=Yt=te&65535|ve<<16,I[7]=Ur=pe&65535|Z<<16,cn+=128,m-=128}return m}function Ts(y,I,w){var m=new Int32Array(8),E=new Int32Array(8),O=new Uint8Array(256),U,ee=w;for(m[0]=1779033703,m[1]=3144134277,m[2]=1013904242,m[3]=2773480762,m[4]=1359893119,m[5]=2600822924,m[6]=528734635,m[7]=1541459225,E[0]=4089235720,E[1]=2227873595,E[2]=4271175723,E[3]=1595750129,E[4]=2917565137,E[5]=725511199,E[6]=4215389547,E[7]=327033209,zh(m,E,I,w),w%=128,U=0;U<w;U++)O[U]=I[ee-w+U];for(O[w]=128,w=256-128*(w<112?1:0),O[w-9]=0,p(O,w-8,ee/536870912|0,ee<<3),zh(m,E,O,w),U=0;U<8;U++)p(y,8*U,m[U],E[U]);return 0}function qd(y,I){var w=e(),m=e(),E=e(),O=e(),U=e(),ee=e(),Ie=e(),Qe=e(),He=e();$(w,y[1],y[0]),$(He,I[1],I[0]),ye(w,w,He),T(m,y[0],y[1]),T(He,I[0],I[1]),ye(m,m,He),ye(E,y[3],I[3]),ye(E,E,u),ye(O,y[2],I[2]),T(O,O,O),$(U,m,w),$(ee,O,E),T(Ie,O,E),T(Qe,m,w),ye(y[0],U,ee),ye(y[1],Qe,Ie),ye(y[2],Ie,ee),ye(y[3],U,Qe)}function Kh(y,I,w){var m;for(m=0;m<4;m++)Pe(y[m],I[m],w)}function Wd(y,I){var w=e(),m=e(),E=e();ct(E,I[2]),ye(w,I[0],E),ye(m,I[1],E),Te(y,m),y[31]^=B(w)<<7}function Jh(y,I,w){var m,E;for(j(y[0],o),j(y[1],s),j(y[2],s),j(y[3],o),E=255;E>=0;--E)m=w[E/8|0]>>(E&7)&1,Kh(y,I,m),qd(I,y),qd(y,y),Kh(y,I,m)}function Kf(y,I){var w=[e(),e(),e(),e()];j(w[0],d),j(w[1],l),j(w[2],s),ye(w[3],d,l),Jh(y,w,I)}function Xh(y,I,w){var m=new Uint8Array(64),E=[e(),e(),e(),e()],O;for(w||r(I,32),Ts(m,I,32),m[0]&=248,m[31]&=127,m[31]|=64,Kf(E,m),Wd(y,E),O=0;O<32;O++)I[O+32]=y[O];return 0}var Jf=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function _a(y,I){var w,m,E,O;for(m=63;m>=32;--m){for(w=0,E=m-32,O=m-12;E<O;++E)I[E]+=w-16*I[m]*Jf[E-(m-32)],w=Math.floor((I[E]+128)/256),I[E]-=w*256;I[E]+=w,I[m]=0}for(w=0,E=0;E<32;E++)I[E]+=w-(I[31]>>4)*Jf[E],w=I[E]>>8,I[E]&=255;for(E=0;E<32;E++)I[E]-=w*Jf[E];for(m=0;m<32;m++)I[m+1]+=I[m]>>8,y[m]=I[m]&255}function Yh(y){var I=new Float64Array(64),w;for(w=0;w<64;w++)I[w]=y[w];for(w=0;w<64;w++)y[w]=0;_a(y,I)}function gS(y,I,w,m){var E=new Uint8Array(64),O=new Uint8Array(64),U=new Uint8Array(64),ee,Ie,Qe=new Float64Array(64),He=[e(),e(),e(),e()];Ts(E,m,32),E[0]&=248,E[31]&=127,E[31]|=64;var Jt=w+64;for(ee=0;ee<w;ee++)y[64+ee]=I[ee];for(ee=0;ee<32;ee++)y[32+ee]=E[32+ee];for(Ts(U,y.subarray(32),w+32),Yh(U),Kf(He,U),Wd(y,He),ee=32;ee<64;ee++)y[ee]=m[ee];for(Ts(O,y,w+64),Yh(O),ee=0;ee<64;ee++)Qe[ee]=0;for(ee=0;ee<32;ee++)Qe[ee]=U[ee];for(ee=0;ee<32;ee++)for(Ie=0;Ie<32;Ie++)Qe[ee+Ie]+=O[ee]*E[Ie];return _a(y.subarray(32),Qe),Jt}function ZR(y,I){var w=e(),m=e(),E=e(),O=e(),U=e(),ee=e(),Ie=e();return j(y[2],s),K(y[1],I),be(E,y[1]),ye(O,E,c),$(E,E,y[2]),T(O,y[2],O),be(U,O),be(ee,U),ye(Ie,ee,U),ye(w,Ie,E),ye(w,w,O),It(w,w),ye(w,w,E),ye(w,w,O),ye(w,w,O),ye(y[0],w,O),be(m,y[0]),ye(m,m,O),P(m,E)&&ye(y[0],y[0],f),be(m,y[0]),ye(m,m,O),P(m,E)?-1:(B(y[0])===I[31]>>7&&$(y[0],o,y[0]),ye(y[3],y[0],y[1]),0)}function Vd(y,I,w,m){var E,O=new Uint8Array(32),U=new Uint8Array(64),ee=[e(),e(),e(),e()],Ie=[e(),e(),e(),e()];if(w<64||ZR(Ie,m))return-1;for(E=0;E<w;E++)y[E]=I[E];for(E=0;E<32;E++)y[E+32]=m[E];if(Ts(U,y,w),Yh(U),Jh(ee,Ie,U),Kf(Ie,I.subarray(32)),qd(ee,Ie),Wd(O,ee),w-=64,b(I,0,O,0)){for(E=0;E<w;E++)y[E]=0;return-1}for(E=0;E<w;E++)y[E]=I[E+64];return w}var M=32,q=24,Y=32,we=16,et=32,vr=32,wr=32,St=32,Be=32,Fe=q,Ge=Y,Xe=we,mt=64,Kt=32,dr=64,ii=32,Xf=64;t.lowlevel={crypto_core_hsalsa20:F,crypto_stream_xor:R,crypto_stream:de,crypto_stream_salsa20_xor:z,crypto_stream_salsa20:Ce,crypto_onetimeauth:le,crypto_onetimeauth_verify:se,crypto_verify_16:v,crypto_verify_32:b,crypto_secretbox:H,crypto_secretbox_open:G,crypto_scalarmult:Zt,crypto_scalarmult_base:Dt,crypto_box_beforenm:lo,crypto_box_afternm:fo,crypto_box:QR,crypto_box_open:Vh,crypto_box_keypair:_t,crypto_hash:Ts,crypto_sign:gS,crypto_sign_keypair:Xh,crypto_sign_open:Vd,crypto_secretbox_KEYBYTES:M,crypto_secretbox_NONCEBYTES:q,crypto_secretbox_ZEROBYTES:Y,crypto_secretbox_BOXZEROBYTES:we,crypto_scalarmult_BYTES:et,crypto_scalarmult_SCALARBYTES:vr,crypto_box_PUBLICKEYBYTES:wr,crypto_box_SECRETKEYBYTES:St,crypto_box_BEFORENMBYTES:Be,crypto_box_NONCEBYTES:Fe,crypto_box_ZEROBYTES:Ge,crypto_box_BOXZEROBYTES:Xe,crypto_sign_BYTES:mt,crypto_sign_PUBLICKEYBYTES:Kt,crypto_sign_SECRETKEYBYTES:dr,crypto_sign_SEEDBYTES:ii,crypto_hash_BYTES:Xf,gf:e,D:c,L:Jf,pack25519:Te,unpack25519:K,M:ye,A:T,S:be,Z:$,pow2523:It,add:qd,set25519:j,modL:_a,scalarmult:Jh,scalarbase:Kf};function yS(y,I){if(y.length!==M)throw new Error("bad key size");if(I.length!==q)throw new Error("bad nonce size")}function e1(y,I){if(y.length!==wr)throw new Error("bad public key size");if(I.length!==St)throw new Error("bad secret key size")}function Wi(){for(var y=0;y<arguments.length;y++)if(!(arguments[y]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function I3(y){for(var I=0;I<y.length;I++)y[I]=0}t.randomBytes=function(y){var I=new Uint8Array(y);return r(I,y),I},t.secretbox=function(y,I,w){Wi(y,I,w),yS(w,I);for(var m=new Uint8Array(Y+y.length),E=new Uint8Array(m.length),O=0;O<y.length;O++)m[O+Y]=y[O];return H(E,m,m.length,I,w),E.subarray(we)},t.secretbox.open=function(y,I,w){Wi(y,I,w),yS(w,I);for(var m=new Uint8Array(we+y.length),E=new Uint8Array(m.length),O=0;O<y.length;O++)m[O+we]=y[O];return m.length<32||G(E,m,m.length,I,w)!==0?null:E.subarray(Y)},t.secretbox.keyLength=M,t.secretbox.nonceLength=q,t.secretbox.overheadLength=we,t.scalarMult=function(y,I){if(Wi(y,I),y.length!==vr)throw new Error("bad n size");if(I.length!==et)throw new Error("bad p size");var w=new Uint8Array(et);return Zt(w,y,I),w},t.scalarMult.base=function(y){if(Wi(y),y.length!==vr)throw new Error("bad n size");var I=new Uint8Array(et);return Dt(I,y),I},t.scalarMult.scalarLength=vr,t.scalarMult.groupElementLength=et,t.box=function(y,I,w,m){var E=t.box.before(w,m);return t.secretbox(y,I,E)},t.box.before=function(y,I){Wi(y,I),e1(y,I);var w=new Uint8Array(Be);return lo(w,y,I),w},t.box.after=t.secretbox,t.box.open=function(y,I,w,m){var E=t.box.before(w,m);return t.secretbox.open(y,I,E)},t.box.open.after=t.secretbox.open,t.box.keyPair=function(){var y=new Uint8Array(wr),I=new Uint8Array(St);return _t(y,I),{publicKey:y,secretKey:I}},t.box.keyPair.fromSecretKey=function(y){if(Wi(y),y.length!==St)throw new Error("bad secret key size");var I=new Uint8Array(wr);return Dt(I,y),{publicKey:I,secretKey:new Uint8Array(y)}},t.box.publicKeyLength=wr,t.box.secretKeyLength=St,t.box.sharedKeyLength=Be,t.box.nonceLength=Fe,t.box.overheadLength=t.secretbox.overheadLength,t.sign=function(y,I){if(Wi(y,I),I.length!==dr)throw new Error("bad secret key size");var w=new Uint8Array(mt+y.length);return gS(w,y,y.length,I),w},t.sign.open=function(y,I){if(Wi(y,I),I.length!==Kt)throw new Error("bad public key size");var w=new Uint8Array(y.length),m=Vd(w,y,y.length,I);if(m<0)return null;for(var E=new Uint8Array(m),O=0;O<E.length;O++)E[O]=w[O];return E},t.sign.detached=function(y,I){for(var w=t.sign(y,I),m=new Uint8Array(mt),E=0;E<m.length;E++)m[E]=w[E];return m},t.sign.detached.verify=function(y,I,w){if(Wi(y,I,w),I.length!==mt)throw new Error("bad signature size");if(w.length!==Kt)throw new Error("bad public key size");var m=new Uint8Array(mt+y.length),E=new Uint8Array(mt+y.length),O;for(O=0;O<mt;O++)m[O]=I[O];for(O=0;O<y.length;O++)m[O+mt]=y[O];return Vd(E,m,m.length,w)>=0},t.sign.keyPair=function(){var y=new Uint8Array(Kt),I=new Uint8Array(dr);return Xh(y,I),{publicKey:y,secretKey:I}},t.sign.keyPair.fromSecretKey=function(y){if(Wi(y),y.length!==dr)throw new Error("bad secret key size");for(var I=new Uint8Array(Kt),w=0;w<I.length;w++)I[w]=y[32+w];return{publicKey:I,secretKey:new Uint8Array(y)}},t.sign.keyPair.fromSeed=function(y){if(Wi(y),y.length!==ii)throw new Error("bad seed size");for(var I=new Uint8Array(Kt),w=new Uint8Array(dr),m=0;m<32;m++)w[m]=y[m];return Xh(I,w,!0),{publicKey:I,secretKey:w}},t.sign.publicKeyLength=Kt,t.sign.secretKeyLength=dr,t.sign.seedLength=ii,t.sign.signatureLength=mt,t.hash=function(y){Wi(y);var I=new Uint8Array(Xf);return Ts(I,y,y.length),I},t.hash.hashLength=Xf,t.verify=function(y,I){return Wi(y,I),y.length===0||I.length===0||y.length!==I.length?!1:g(y,0,I,0,y.length)===0},t.setPRNG=function(y){r=y},(function(){var y=typeof self<"u"?self.crypto||self.msCrypto:null;if(y&&y.getRandomValues){var I=65536;t.setPRNG(function(w,m){var E,O=new Uint8Array(m);for(E=0;E<m;E+=I)y.getRandomValues(O.subarray(E,E+Math.min(m-E,I)));for(E=0;E<m;E++)w[E]=O[E];I3(O)})}else typeof Nt<"u"&&(y=Nt("node:crypto"),y&&y.randomBytes&&t.setPRNG(function(w,m){var E,O=y.randomBytes(m);for(E=0;E<m;E++)w[E]=O[E];I3(O)}))})()})(typeof Mw<"u"&&Mw.exports?Mw.exports:self.nacl=self.nacl||{})});var ZP=ce(QP=>{"use strict";Object.defineProperty(QP,"__esModule",{value:!0});var YP=class{constructor(e,r=0,n=0){this.start=r,this.end=n>r?n:r,this.buf=e}get length(){return this.buf.length}reset(e=0,r=0){return this.start=e,r>=this.start?this.end=r:this.end<this.start&&(this.end=this.start),this}walk(e){return this.start=this.end,this.end+=e,this}mustHas(e,r="Too few bytes to parse."){let n=this.end+e;if(n>this.buf.length){let i=new Error(r);throw i.available=this.buf.length,i.requested=n,i}return this.walk(0),this}mustWalk(e,r){return this.mustHas(e,r),this.walk(e),this}};QP.BufferVisitor=YP});var p9=ce(n_=>{"use strict";Object.defineProperty(n_,"__esModule",{value:!0});var l9=Nt("node:util"),f9=64,t_="-----BEGIN ",r_="-----END ",S0="-----",e_="Proc-Type",Hw=class{static parse(e){let r=[],n=e.toString("utf8").split(`
7
+ `).map(i=>i.trim()).filter(i=>i!==""&&!i.startsWith("#"));for(;n.length>0;)r.push(Ahe(n));if(r.length===0)throw new Error("PEM: no block");return r}constructor(e,r){this.type=e,this.body=r,this.headers=Object.create(null)}get procType(){return this.getHeader(e_)}getHeader(e){let r=this.headers[e];return r??""}setHeader(e,r){if(e.includes(":"))throw new Error("pem: cannot encode a header key that contains a colon");if(e===""||r==="")throw new Error("pem: invalid header key or value");this.headers[e]=r}toString(){let e=t_+this.type+S0+`
8
+ `,r=Object.keys(this.headers);if(r.length>0){let o=this.procType;o!==""&&(e+=`${e_}: ${o}
9
+ `),r.sort();for(let s of r)s!==e_&&(e+=`${s}: ${this.headers[s]}
10
+ `);e+=`
11
+ `}let n=this.body.toString("base64"),i=0;for(;i<n.length;)e+=n.slice(i,i+f9)+`
12
+ `,i+=f9;return e+=r_+this.type+S0+`
13
+ `,e}toBuffer(){return Buffer.from(this.toString(),"utf8")}valueOf(){return this.body}toJSON(){return{type:this.type,body:this.body,headers:this.headers}}[l9.inspect.custom](e,r){return`<${this.constructor.name} ${l9.inspect(this.toJSON(),r)}>`}};n_.PEM=Hw;function Ahe(t){let e=t.shift();if(e==null||!e.startsWith(t_)||!e.endsWith(S0))throw new Error("pem: invalid BEGIN line");let r=e.slice(t_.length,e.length-S0.length);if(r==="")throw new Error("pem: invalid type");let n=[];for(e=t.shift();e!=null&&e.includes(": ");){let s=e.split(": ");if(s.length!==2||s[0]===""||s[1]==="")throw new Error("pem: invalid Header line");n.push(s),e=t.shift()}let i="";for(;e!=null&&!e.startsWith(r_);)i+=e,e=t.shift();if(e==null||e!==`${r_}${r}${S0}`)throw new Error("pem: invalid END line");let o=new Hw(r,Buffer.from(i,"base64"));if(i===""||o.body.toString("base64")!==i)throw new Error("pem: invalid base64 body");for(let s of n)o.setHeader(s[0],s[1]);return o}});var y9=ce(Lu=>{"use strict";Object.defineProperty(Lu,"__esModule",{value:!0});var m9=Nt("node:util"),Uw=ZP(),qr;(function(t){t[t.UNIVERSAL=0]="UNIVERSAL",t[t.APPLICATION=64]="APPLICATION",t[t.CONTEXT_SPECIFIC=128]="CONTEXT_SPECIFIC",t[t.PRIVATE=192]="PRIVATE"})(qr=Lu.Class||(Lu.Class={}));var Ht;(function(t){t[t.NONE=0]="NONE",t[t.BOOLEAN=1]="BOOLEAN",t[t.INTEGER=2]="INTEGER",t[t.BITSTRING=3]="BITSTRING",t[t.OCTETSTRING=4]="OCTETSTRING",t[t.NULL=5]="NULL",t[t.OID=6]="OID",t[t.ENUMERATED=10]="ENUMERATED",t[t.UTF8=12]="UTF8",t[t.SEQUENCE=16]="SEQUENCE",t[t.SET=17]="SET",t[t.NUMERICSTRING=18]="NUMERICSTRING",t[t.PRINTABLESTRING=19]="PRINTABLESTRING",t[t.T61STRING=20]="T61STRING",t[t.IA5STRING=22]="IA5STRING",t[t.UTCTIME=23]="UTCTIME",t[t.GENERALIZEDTIME=24]="GENERALIZEDTIME",t[t.GENERALSTRING=27]="GENERALSTRING"})(Ht=Lu.Tag||(Lu.Tag={}));var b0=class{constructor(e,r){this.buf=e,this.bitLen=r}at(e){if(e<0||e>=this.bitLen||!Number.isInteger(e))return 0;let r=Math.floor(e/8),n=7-e%8;return this.buf[r]>>n&1}rightAlign(){let e=8-this.bitLen%8;if(e===8||this.buf.length===0)return this.buf;let r=Buffer.alloc(this.buf.length);r[0]=this.buf[0]>>e;for(let n=1;n<this.buf.length;n++)r[n]=this.buf[n-1]<<8-e,r[n]|=this.buf[n]>>e;return r}};Lu.BitString=b0;var i_=class t{static Bool(e){let r=new t(qr.UNIVERSAL,Ht.BOOLEAN,Buffer.from([e?255:0]));return r._value=e,r}static parseBool(e){if(!(e instanceof Buffer)||e.length!==1)throw new Error("ASN1 syntax error: invalid boolean");switch(e[0]){case 0:return!1;case 255:return!0;default:throw new Error("ASN1 syntax error: invalid boolean")}}static Integer(e){if(e instanceof Buffer){let i=new t(qr.UNIVERSAL,Ht.INTEGER,e);return i._value=e.toString("hex"),i}if(!Number.isSafeInteger(e))throw new Error("ASN1 syntax error: invalid integer");let r;if(e>=-128&&e<128)r=Buffer.alloc(1),r.writeInt8(e,0);else if(e>=-32768&&e<32768)r=Buffer.alloc(2),r.writeIntBE(e,0,2);else if(e>=-8388608&&e<8388608)r=Buffer.alloc(3),r.writeIntBE(e,0,3);else if(e>=-2147483648&&e<2147483648)r=Buffer.alloc(4),r.writeIntBE(e,0,4);else if(e>=-549755813888&&e<549755813888)r=Buffer.alloc(5),r.writeIntBE(e,0,5);else if(e>=-0x800000000000&&e<0x800000000000)r=Buffer.alloc(6),r.writeIntBE(e,0,6);else throw new Error("ASN1 syntax error: invalid Integer");let n=new t(qr.UNIVERSAL,Ht.INTEGER,r);return n._value=e,n}static parseInteger(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid Integer");return e.length>6?e.toString("hex"):e.readIntBE(0,e.length)}static parseIntegerNum(e){let r=t.parseInteger(e);if(typeof r!="number")throw new Error("ASN1 syntax error: invalid Integer number");return r}static parseIntegerStr(e){let r=t.parseInteger(e);return typeof r=="number"?r.toString(16):r}static BitString(e){e instanceof Buffer&&(e=new b0(e,e.length*8));let r=e.buf.length*8-e.bitLen,n=Buffer.alloc(e.buf.length+1);return n.writeInt8(r,0),e.buf.copy(n,1),new t(qr.UNIVERSAL,Ht.BITSTRING,n)}static parseBitString(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid BitString");let r=e[0];if(r>7||e.length===1&&r>0||(e[e.length-1]&(1<<e[0])-1)!==0)throw new Error("ASN1 syntax error: invalid padding bits in BIT STRING");return new b0(e.slice(1),(e.length-1)*8-r)}static Null(){let e=new t(qr.UNIVERSAL,Ht.NULL,Buffer.alloc(0));return e._value=null,e}static parseNull(e){if(!(e instanceof Buffer)||e.length!==0)throw new Error("ASN1 syntax error: invalid null");return null}static OID(e){let r=e.split(".");if(r.length===0)throw new Error("ASN1 syntax error: invalid Object Identifier");let n=[];n.push(40*ln(r[0])+ln(r[1]));let i=[];for(let s=2;s<r.length;++s){let a=ln(r[s]);for(i.length=0,i.push(a&127);a>127;)a=a>>>7,i.unshift(a&127|128);n.push(...i)}let o=new t(qr.UNIVERSAL,Ht.OID,Buffer.from(n));return o._value=e,o}static parseOID(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid OID");let r=Math.floor(e[0]/40)+"."+e[0]%40,n=0;for(let i=1;i<e.length;i++)e[i]>=128?(n+=e[i]&127,n=n<<7):(r+="."+(n+e[i]),n=0);return r}static UTF8(e){let r=new t(qr.UNIVERSAL,Ht.UTF8,Buffer.from(e,"utf8"));return r._value=e,r}static parseUTF8(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static NumericString(e){if(!h9(e))throw new Error("ASN1 syntax error: invalid NumericString");let r=new t(qr.UNIVERSAL,Ht.NUMERICSTRING,Buffer.from(e,"utf8"));return r._value=e,r}static parseNumericString(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");let r=e.toString("utf8");if(!h9(r))throw new Error("ASN1 syntax error: invalid NumericString");return r}static PrintableString(e){let r=new t(qr.UNIVERSAL,Ht.PRINTABLESTRING,Buffer.from(e,"utf8"));return r._value=e,r}static parsePrintableString(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static IA5String(e){if(!g9(e))throw new Error("ASN1 syntax error: invalid IA5String");let r=new t(qr.UNIVERSAL,Ht.IA5STRING,Buffer.from(e,"utf8"));return r._value=e,r}static parseIA5String(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");let r=e.toString("utf8");if(!g9(r))throw new Error("ASN1 syntax error: invalid IA5String");return r}static T61String(e){let r=new t(qr.UNIVERSAL,Ht.T61STRING,Buffer.from(e,"utf8"));return r._value=e,r}static parseT61String(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static GeneralString(e){let r=new t(qr.UNIVERSAL,Ht.GENERALSTRING,Buffer.from(e,"utf8"));return r._value=e,r}static parseGeneralString(e){if(!(e instanceof Buffer))throw new Error("parse ASN1 error: invalid Buffer");return e.toString("utf8")}static UTCTime(e){let r="",n=[];n.push((""+e.getUTCFullYear()).substr(2)),n.push(""+(e.getUTCMonth()+1)),n.push(""+e.getUTCDate()),n.push(""+e.getUTCHours()),n.push(""+e.getUTCMinutes()),n.push(""+e.getUTCSeconds());for(let o of n)o.length<2&&(r+="0"),r+=o;r+="Z";let i=new t(qr.UNIVERSAL,Ht.UTCTIME,Buffer.from(r,"utf8"));return i._value=e,i}static parseUTCTime(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid UTC Time");let r=e.toString("utf8"),n=new Date,i=ln(r.substr(0,2));i=i>=50?1900+i:2e3+i;let o=ln(r.substr(2,2))-1,s=ln(r.substr(4,2)),a=ln(r.substr(6,2)),c=ln(r.substr(8,2)),u=0,d=0,l="";if(r.length>11&&(d=10,l=r.charAt(d),l!=="+"&&l!=="-"&&(u=ln(r.substr(10,2)),d+=2)),n.setUTCFullYear(i,o,s),n.setUTCHours(a,c,u,0),d>0&&(l=r.charAt(d),l==="+"||l==="-")){let f=ln(r.substr(d+1,2)),p=ln(r.substr(d+4,2)),g=f*60+p;g*=6e4,l==="+"?n.setTime(+n-g):n.setTime(+n+g)}return n}static GeneralizedTime(e){let r="",n=[];n.push(""+e.getUTCFullYear()),n.push(""+(e.getUTCMonth()+1)),n.push(""+e.getUTCDate()),n.push(""+e.getUTCHours()),n.push(""+e.getUTCMinutes()),n.push(""+e.getUTCSeconds());for(let o of n)o.length<2&&(r+="0"),r+=o;r+="Z";let i=new t(qr.UNIVERSAL,Ht.GENERALIZEDTIME,Buffer.from(r,"utf8"));return i._value=e,i}static parseGeneralizedTime(e){if(!(e instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid Generalized Time");let r=e.toString("utf8"),n=new Date,i=ln(r.substr(0,4)),o=ln(r.substr(4,2))-1,s=ln(r.substr(6,2)),a=ln(r.substr(8,2)),c=ln(r.substr(10,2)),u=ln(r.substr(12,2)),d=0,l=0,f=!1;r.charAt(r.length-1)==="Z"&&(f=!0);let p=r.length-5,g=r.charAt(p);if(g==="+"||g==="-"){let v=ln(r.substr(p+1,2)),b=ln(r.substr(p+4,2));l=v*60+b,l*=6e4,g==="+"&&(l*=-1),f=!0}return r.charAt(14)==="."&&(d=parseFloat(r.substr(14))*1e3),f?(n.setUTCFullYear(i,o,s),n.setUTCHours(a,c,u,d),n.setTime(+n+l)):(n.setFullYear(i,o,s),n.setHours(a,c,u,d)),n}static parseTime(e,r){switch(e){case Ht.UTCTIME:return t.parseUTCTime(r);case Ht.GENERALIZEDTIME:return t.parseGeneralizedTime(r);default:throw new Error("Invalid ASN1 time tag")}}static Set(e){let r=new t(qr.UNIVERSAL,Ht.SET,Buffer.concat(e.map(n=>n.toDER())));return r._value=e,r}static Seq(e){let r=new t(qr.UNIVERSAL,Ht.SEQUENCE,Buffer.concat(e.map(n=>n.toDER())));return r._value=e,r}static Spec(e,r,n=!0){let i=Array.isArray(r)?Buffer.concat(r.map(s=>s.toDER())):r.toDER();Array.isArray(r)&&(n=!0);let o=new t(qr.CONTEXT_SPECIFIC,e,i,n);return o._value=r,o}static fromDER(e,r=!1){return t._fromDER(new Uw.BufferVisitor(e),r)}static parseDER(e,r,n){let i=t._fromDER(new Uw.BufferVisitor(e),!1);if(i.class!==r&&i.tag!==n)throw new Error(`invalid ASN.1 DER for class ${r} and tag ${n}`);return i}static parseDERWithTemplate(e,r){let n=t._fromDER(new Uw.BufferVisitor(e),!0),i={},o=n.validate(r,i);if(o!=null)throw o.data=n,o;return i}static _parseCompound(e,r){let n=[],i=e.length,o=new Uw.BufferVisitor(e),s=0;for(;s<i;){let a=o.end;n.push(t._fromDER(o,r)),s+=o.end-a}return n}static _fromDER(e,r){if(!(e.buf instanceof Buffer)||e.length===0)throw new Error("ASN1 syntax error: invalid Generalized Time");e.mustWalk(1,"Too few bytes to read ASN.1 tag.");let n=e.start,i=e.buf[n],o=i&192,s=i&31,a=Che(e);if(e.mustHas(a),a!==0&&s===Ht.NULL)throw new Error("invalid value length or NULL tag.");e.mustWalk(a);let c=(i&32)===32,u=new t(o,s,e.buf.slice(e.start,e.end),c);return c&&r&&(u._value=t._parseCompound(u.bytes,r)),u._der=e.buf.slice(n,e.end),u}constructor(e,r,n,i=!1){this.class=e,this.tag=r,this.bytes=n,this.isCompound=i||r===Ht.SEQUENCE||r===Ht.SET,this._value=void 0,this._der=null}get value(){return this._value===void 0&&(this._value=this.valueOf()),this._value}get DER(){return this._der==null&&(this._der=this.toDER()),this._der}mustCompound(e="asn1 object value is not compound"){if(!this.isCompound||!Array.isArray(this.value)){let r=new Error(e);throw r.data=this.toJSON(),r}return this.value}equals(e){return!(!(e instanceof t)||this.class!==e.class||this.tag!==e.tag||this.isCompound!==e.isCompound||!this.bytes.equals(e.bytes))}toDER(){let e=this.class|this.tag;this.isCompound&&(e|=32);let r=Phe(this.bytes.length),n=Buffer.allocUnsafe(2+r+this.bytes.length);return n.writeInt8(e,0),r===0?(n.writeUInt8(this.bytes.length,1),this.bytes.copy(n,2)):(n.writeUInt8(r|128,1),n.writeUIntBE(this.bytes.length,2,r),this.bytes.copy(n,2+r)),n}valueOf(){if(this.isCompound)return t._parseCompound(this.bytes,!1);if(this.class!==qr.UNIVERSAL)return this.bytes;switch(this.tag){case Ht.BOOLEAN:return t.parseBool(this.bytes);case Ht.INTEGER:return t.parseInteger(this.bytes);case Ht.BITSTRING:return t.parseBitString(this.bytes);case Ht.NULL:return t.parseNull(this.bytes);case Ht.OID:return t.parseOID(this.bytes);case Ht.UTF8:return t.parseUTF8(this.bytes);case Ht.NUMERICSTRING:return t.parseNumericString(this.bytes);case Ht.PRINTABLESTRING:return t.parsePrintableString(this.bytes);case Ht.T61STRING:return t.parseT61String(this.bytes);case Ht.IA5STRING:return t.parseIA5String(this.bytes);case Ht.GENERALSTRING:return t.parseGeneralString(this.bytes);case Ht.UTCTIME:return t.parseUTCTime(this.bytes);case Ht.GENERALIZEDTIME:return t.parseGeneralizedTime(this.bytes);default:return this.bytes}}validate(e,r={}){if(this.class!==e.class)return new Error(`ASN.1 object validate failure for ${e.name} : error class ${qr[this.class]}`);if(!(Array.isArray(e.tag)?e.tag:[e.tag]).includes(this.tag))return new Error(`ASN.1 object validate failure for ${e.name}: error tag ${Ht[this.tag]}`);if(e.capture!=null&&(r[e.capture]=this),Array.isArray(e.value)){let i=this.mustCompound(`${e.name} need compound ASN1 value`);for(let o=0,s=0;o<e.value.length;o++)if(i[s]!=null){let a=i[s].validate(e.value[o],r);if(a==null)s++;else if(e.value[o].optional!==!0)return a}else if(e.value[o].optional!==!0)return new Error(`ASN.1 object validate failure for ${e.value[o].name}: not exists`)}else if(e.value!=null){let i=this.tag===Ht.BITSTRING?this.bytes.slice(1):this.bytes;return t.fromDER(i).validate(e.value,r)}return null}toJSON(){let e=this.value;return Array.isArray(e)&&(e=e.map(r=>r.toJSON())),{class:qr[this.class],tag:this.class===qr.UNIVERSAL?Ht[this.tag]:this.tag,value:e}}[m9.inspect.custom](e,r){return r.depth<=2&&(r.depth=10),`<${this.constructor.name} ${m9.inspect(this.toJSON(),r)}>`}};Lu.ASN1=i_;function Che(t){t.mustWalk(1,"Too few bytes to read ASN.1 value length.");let e=t.buf[t.start];if((e&128)===0)return e;let r=e&127;return t.mustWalk(r,"Too few bytes to read ASN.1 value length."),t.buf.readUIntBE(t.start,r)}function Phe(t){if(t<=127)return 0;if(t<=255)return 1;if(t<=65535)return 2;if(t<=16777215)return 3;if(t<=4294967295)return 4;if(t<=0xffffffffff)return 5;if(t<=0xffffffffffff)return 6;throw new Error("invalid value length")}function h9(t){for(let e of t){let r=e.charCodeAt(0);if(r!==32&&(r<48||r>57))return!1}return!0}function g9(t){for(let e of t)if(e.charCodeAt(0)>=128)return!1;return!0}function ln(t,e=10){let r=parseInt(t,e);if(Number.isNaN(r))throw new Error(`Invalid numeric string "${t}" in radix ${e}.`);return r}});var o_=ce(Hu=>{"use strict";Object.defineProperty(Hu,"__esModule",{value:!0});var _he=ZP();Hu.BufferVisitor=_he.BufferVisitor;var The=p9();Hu.PEM=The.PEM;var $w=y9();Hu.ASN1=$w.ASN1;Hu.Class=$w.Class;Hu.Tag=$w.Tag;Hu.BitString=$w.BitString});var u_=ce(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var $u=Nt("node:util"),w0=Nt("node:crypto"),c_=Lw(),Ae=o_(),Qn=Ow();Ks.publicKeyValidator={name:"PublicKeyInfo",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.SEQUENCE,capture:"publicKeyInfo",value:[{name:"PublicKeyInfo.AlgorithmIdentifier",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.SEQUENCE,value:[{name:"PublicKeyAlgorithmIdentifier.algorithm",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.OID,capture:"publicKeyOID"}]},{name:"PublicKeyInfo.PublicKey",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.BITSTRING,capture:"publicKey"}]};Ks.privateKeyValidator={name:"PrivateKeyInfo",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.SEQUENCE,capture:"privateKeyInfo",value:[{name:"PrivateKeyInfo.Version",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.INTEGER,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.AlgorithmIdentifier",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.SEQUENCE,value:[{name:"PrivateKeyAlgorithmIdentifier.algorithm",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.OID,capture:"privateKeyOID"}]},{name:"PrivateKeyInfo.PrivateKey",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.OCTETSTRING,capture:"privateKey"}]};var Dhe={name:"RSAPublicKey",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.SEQUENCE,value:[{name:"RSAPublicKey.modulus",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.INTEGER,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.INTEGER,capture:"publicKeyExponent"}]},Bhe={name:"RSAPrivateKey",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.SEQUENCE,value:[{name:"RSAPrivateKey.version",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.INTEGER,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.INTEGER,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.INTEGER,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.INTEGER,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.INTEGER,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.INTEGER,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.INTEGER,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.INTEGER,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",class:Ae.Class.UNIVERSAL,tag:Ae.Tag.INTEGER,capture:"privateKeyCoefficient"}]},Nhe=[Qn.getOID("X25519"),Qn.getOID("X448"),Qn.getOID("Ed25519"),Qn.getOID("Ed448")],Op=class t{constructor(e){let r={},n=e.validate(Ks.publicKeyValidator,r);if(n!=null)throw new Error("Cannot read X.509 public key: "+n.message);this.oid=Ae.ASN1.parseOID(r.publicKeyOID.bytes),this.algo=Qn.getOIDName(this.oid),this._pkcs8=e,this._keyRaw=Ae.ASN1.parseBitString(r.publicKey.bytes).buf,this._finalKey=this._keyRaw,this._finalPEM=""}static fromPEM(e){let r=Ae.PEM.parse(e)[0];if(r.procType.includes("ENCRYPTED"))throw new Error("Could not convert public key from PEM, PEM is encrypted.");let n=Ae.ASN1.fromDER(r.body,!0);switch(r.type){case"PUBLIC KEY":return new t(n);case"RSA PUBLIC KEY":let i=Ae.ASN1.Seq([Ae.ASN1.Seq([Ae.ASN1.OID(Qn.getOID("rsaEncryption")),Ae.ASN1.Null()]),Ae.ASN1.BitString(n.DER)]);return new t(i);default:throw new Error("Could not convert public key from PEM, recommend PKCS#8 PEM")}}static addVerifier(e,r){if(e=Qn.getOID(e),e==="")throw new Error(`Invalid object identifier: ${e}`);if(t._verifiers[e]!=null)throw new Error(`Verifier ${e} exists`);t._verifiers[e]=r}get keyRaw(){return this._finalKey}verify(e,r,n){let i=t._verifiers[this.oid];if(i!=null){let s=w0.createHash(n).update(e).digest();return i.call(this,s,r)}let o=w0.createVerify(n);return o.update(e),o.verify(this.toPEM(),r)}getFingerprint(e,r="PublicKey"){let n;switch(r){case"PublicKeyInfo":n=this._pkcs8.DER;break;case"PublicKey":n=this._keyRaw;break;default:throw new Error(`Unknown fingerprint type "${r}".`)}let i=w0.createHash(e);return i.update(n),i.digest()}toASN1(){return this._pkcs8}toDER(){return this._pkcs8.DER}toPEM(){return this._finalPEM===""&&(this._finalPEM=new Ae.PEM("PUBLIC KEY",this._pkcs8.DER).toString()),this._finalPEM}toJSON(){return{oid:this.oid,algo:this.algo,publicKey:this._keyRaw}}[$u.inspect.custom](e,r){return`<${this.constructor.name} ${$u.inspect(this.toJSON(),r)}>`}};Op._verifiers=Object.create(null);Ks.PublicKey=Op;var Mp=class t{constructor(e){let r=Object.create(null),n=e.validate(Ks.privateKeyValidator,r);if(n!=null)throw new Error("Cannot read X.509 private key: "+n.message);if(this.version=Ae.ASN1.parseIntegerNum(r.privateKeyVersion.bytes)+1,this.oid=Ae.ASN1.parseOID(r.privateKeyOID.bytes),this.algo=Qn.getOIDName(this.oid),this._pkcs8=e,this._keyRaw=r.privateKey.bytes,this._publicKeyRaw=null,this._finalKey=this._keyRaw,this._finalPEM="",Nhe.includes(this.oid)){if(this._finalKey=this._keyRaw=Ae.ASN1.parseDER(this._keyRaw,Ae.Class.UNIVERSAL,Ae.Tag.OCTETSTRING).bytes,this.oid==="1.3.101.112"){let i=c_.sign.keyPair.fromSeed(this._keyRaw);this._publicKeyRaw=Buffer.from(i.publicKey),this._finalKey=Buffer.from(i.secretKey)}else if(this.version===2)for(let i of e.mustCompound())i.class===Ae.Class.CONTEXT_SPECIFIC&&i.tag===1&&(this._publicKeyRaw=Ae.ASN1.parseBitString(i.bytes).buf,this._finalKey=Buffer.concat([this._keyRaw,this._publicKeyRaw]))}}static fromPEM(e){let r=Ae.PEM.parse(e)[0];if(r.procType.includes("ENCRYPTED"))throw new Error("Could not convert private key from PEM, PEM is encrypted.");let n=Ae.ASN1.fromDER(r.body,!0);switch(r.type){case"PRIVATE KEY":return new t(n);case"RSA PRIVATE KEY":return n=Ae.ASN1.Seq([n.value[0],Ae.ASN1.Seq([Ae.ASN1.OID(Qn.getOID("rsaEncryption")),Ae.ASN1.Null()]),new Ae.ASN1(Ae.Class.UNIVERSAL,Ae.Tag.OCTETSTRING,n.DER)]),new t(n);default:throw new Error("Could not convert private key from PEM, recommend PKCS#8 PEM")}}static addSigner(e,r){if(e=Qn.getOID(e),e==="")throw new Error(`Invalid object identifier: ${e}`);if(t._signers[e]!=null)throw new Error(`Signer ${e} exists`);t._signers[e]=r}get keyRaw(){return this._finalKey}get publicKeyRaw(){return this._publicKeyRaw}sign(e,r){let n=t._signers[this.oid];if(n!=null){let o=w0.createHash(r).update(e).digest();return n.call(this,o)}let i=w0.createSign(r);return i.update(e),i.sign(this.toPEM())}toASN1(){return this._pkcs8}toDER(){return this._pkcs8.DER}toPEM(){return this._finalPEM===""&&(this._finalPEM=new Ae.PEM("PRIVATE KEY",this._pkcs8.DER).toString()),this._finalPEM}toJSON(){return{version:this.version,oid:this.oid,algo:this.algo,privateKey:this._keyRaw,publicKey:this._publicKeyRaw}}[$u.inspect.custom](e,r){return`<${this.constructor.name} ${$u.inspect(this.toJSON(),r)}>`}};Mp._signers=Object.create(null);Ks.PrivateKey=Mp;var s_=class t extends Op{static fromPublicKey(e){return new t(e.toASN1())}constructor(e){if(super(e),Qn.getOID(this.oid)!==Qn.getOID("rsaEncryption"))throw new Error(`Invalid RSA public key, unknown OID: ${this.oid}`);let r=Object.create(null);this._pkcs1=Ae.ASN1.fromDER(this._keyRaw,!0);let n=this._pkcs1.validate(Dhe,r);if(n!=null)throw new Error("Cannot read RSA public key: "+n.message);this.modulus=Ae.ASN1.parseIntegerStr(r.publicKeyModulus.bytes),this.exponent=Ae.ASN1.parseIntegerNum(r.publicKeyExponent.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){return this._finalPEM===""&&(this._finalPEM=new Ae.PEM("RSA PUBLIC KEY",this._keyRaw).toString()),this._finalPEM}toPublicKeyPEM(){return new Ae.PEM("PUBLIC KEY",this._pkcs8.DER).toString()}toJSON(){return{oid:this.oid,algo:this.algo,modulus:Uu(this.modulus),exponent:this.exponent}}[$u.inspect.custom](e,r){return`<${this.constructor.name} ${$u.inspect(this.toJSON(),r)}>`}};Ks.RSAPublicKey=s_;var a_=class t extends Mp{static fromPrivateKey(e){return new t(e.toASN1())}constructor(e){if(super(e),Qn.getOID(this.oid)!==Qn.getOID("rsaEncryption"))throw new Error(`Invalid RSA private key, unknown OID: ${this.oid}`);let r=Object.create(null);this._pkcs1=Ae.ASN1.fromDER(this._keyRaw,!0);let n=this._pkcs1.validate(Bhe,r);if(n!=null)throw new Error("Cannot read RSA private key: "+n.message);this.publicExponent=Ae.ASN1.parseIntegerNum(r.privateKeyPublicExponent.bytes),this.privateExponent=Ae.ASN1.parseIntegerStr(r.privateKeyPrivateExponent.bytes),this.modulus=Ae.ASN1.parseIntegerStr(r.privateKeyModulus.bytes),this.prime1=Ae.ASN1.parseIntegerStr(r.privateKeyPrime1.bytes),this.prime2=Ae.ASN1.parseIntegerStr(r.privateKeyPrime2.bytes),this.exponent1=Ae.ASN1.parseIntegerStr(r.privateKeyExponent1.bytes),this.exponent2=Ae.ASN1.parseIntegerStr(r.privateKeyExponent2.bytes),this.coefficient=Ae.ASN1.parseIntegerStr(r.privateKeyCoefficient.bytes)}toASN1(){return this._pkcs1}toDER(){return this._keyRaw}toPEM(){return this._finalPEM===""&&(this._finalPEM=new Ae.PEM("RSA PRIVATE KEY",this._keyRaw).toString()),this._finalPEM}toPrivateKeyPEM(){return new Ae.PEM("PRIVATE KEY",this._pkcs8.DER).toString()}toJSON(){return{version:this.version,oid:this.oid,algo:this.algo,publicExponent:this.publicExponent,privateExponent:Uu(this.privateExponent),modulus:Uu(this.modulus),prime1:Uu(this.prime1),prime2:Uu(this.prime2),exponent1:Uu(this.exponent1),exponent2:Uu(this.exponent2),coefficient:Uu(this.coefficient)}}[$u.inspect.custom](e,r){return`<${this.constructor.name} ${$u.inspect(this.toJSON(),r)}>`}};Ks.RSAPrivateKey=a_;function Uu(t){return t.length%8!==0&&t.startsWith("00")?t.slice(2):t}Op.addVerifier(Qn.getOID("Ed25519"),function(t,e){return c_.sign.detached.verify(t,e,this.keyRaw)});Mp.addSigner(Qn.getOID("Ed25519"),function(t){let e=this.keyRaw;if(e.length!==64)throw new Error("Invalid signing key.");return Buffer.from(c_.sign.detached(t,e))})});var I9=ce(Fw=>{"use strict";Object.defineProperty(Fw,"__esModule",{value:!0});var v9=Nt("node:util"),Ohe=Nt("node:crypto"),ge=o_(),Zn=Ow(),w9=u_(),fn=Object.create(null);fn.CN=Zn.getOID("commonName");fn.commonName="CN";fn.C=Zn.getOID("countryName");fn.countryName="C";fn.L=Zn.getOID("localityName");fn.localityName="L";fn.ST=Zn.getOID("stateOrProvinceName");fn.stateOrProvinceName="ST";fn.O=Zn.getOID("organizationName");fn.organizationName="O";fn.OU=Zn.getOID("organizationalUnitName");fn.organizationalUnitName="OU";fn.E=Zn.getOID("emailAddress");fn.emailAddress="E";function Mhe(t){return fn[t]==null?"":fn[t]}var Lhe={name:"Certificate",class:ge.Class.UNIVERSAL,tag:ge.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate",class:ge.Class.UNIVERSAL,tag:ge.Tag.SEQUENCE,capture:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",class:ge.Class.CONTEXT_SPECIFIC,tag:ge.Tag.NONE,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",class:ge.Class.UNIVERSAL,tag:ge.Tag.INTEGER,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",class:ge.Class.UNIVERSAL,tag:ge.Tag.INTEGER,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",class:ge.Class.UNIVERSAL,tag:ge.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate.signature.algorithm",class:ge.Class.UNIVERSAL,tag:ge.Tag.OID,capture:"certinfoSignatureOID"},{name:"Certificate.TBSCertificate.signature.parameters",class:ge.Class.UNIVERSAL,tag:ge.Tag.OCTETSTRING,optional:!0,capture:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",class:ge.Class.UNIVERSAL,tag:ge.Tag.SEQUENCE,capture:"certIssuer"},{name:"Certificate.TBSCertificate.validity",class:ge.Class.UNIVERSAL,tag:ge.Tag.SEQUENCE,value:[{name:"Certificate.TBSCertificate.validity.notBefore",class:ge.Class.UNIVERSAL,tag:[ge.Tag.UTCTIME,ge.Tag.GENERALIZEDTIME],capture:"certValidityNotBefore"},{name:"Certificate.TBSCertificate.validity.notAfter",class:ge.Class.UNIVERSAL,tag:[ge.Tag.UTCTIME,ge.Tag.GENERALIZEDTIME],capture:"certValidityNotAfter"}]},{name:"Certificate.TBSCertificate.subject",class:ge.Class.UNIVERSAL,tag:ge.Tag.SEQUENCE,capture:"certSubject"},w9.publicKeyValidator,{name:"Certificate.TBSCertificate.issuerUniqueID",class:ge.Class.CONTEXT_SPECIFIC,tag:ge.Tag.BOOLEAN,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",class:ge.Class.UNIVERSAL,tag:ge.Tag.BITSTRING,capture:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",class:ge.Class.CONTEXT_SPECIFIC,tag:ge.Tag.INTEGER,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",class:ge.Class.UNIVERSAL,tag:ge.Tag.BITSTRING,capture:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",class:ge.Class.CONTEXT_SPECIFIC,tag:ge.Tag.BITSTRING,capture:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",class:ge.Class.UNIVERSAL,tag:ge.Tag.SEQUENCE,value:[{name:"Certificate.signatureAlgorithm.algorithm",class:ge.Class.UNIVERSAL,tag:ge.Tag.OID,capture:"certSignatureOID"},{name:"Certificate.TBSCertificate.signature.parameters",class:ge.Class.UNIVERSAL,tag:ge.Tag.OCTETSTRING,optional:!0,capture:"certSignatureParams"}]},{name:"Certificate.signatureValue",class:ge.Class.UNIVERSAL,tag:ge.Tag.BITSTRING,capture:"certSignature"}]},I0=class{constructor(){this.attributes=[],this.uniqueId=null}get commonName(){return this.getFieldValue("commonName")}get organizationName(){return this.getFieldValue("organizationName")}get organizationalUnitName(){return this.getFieldValue("organizationalUnitName")}get countryName(){return this.getFieldValue("countryName")}get localityName(){return this.getFieldValue("localityName")}get serialName(){return this.getFieldValue("serialName")}getHash(){let e=Ohe.createHash("sha1");for(let r of this.attributes)e.update(r.oid),e.update(r.value);return e.digest()}getField(e){for(let r of this.attributes)if(e===r.oid||e===r.name||e===r.shortName)return r;return null}addField(e){S9([e]),this.attributes.push(e)}setAttrs(e){S9(e),this.attributes=e}toJSON(){let e={};for(let r of this.attributes){let n=r.shortName;typeof n=="string"&&n!==""&&(e[n]=r.value)}return e.uniqueId=this.uniqueId,e.attributes=this.attributes,e}getFieldValue(e){let r=this.getField(e);return r!=null?r.value:""}};Fw.DistinguishedName=I0;var d_=class t{static fromPEMs(e){let r=[],n=ge.PEM.parse(e);for(let i of n){if(i.type!=="CERTIFICATE"&&i.type!=="X509 CERTIFICATE"&&i.type!=="TRUSTED CERTIFICATE")throw new Error("Could not convert certificate from PEM: invalid type");if(i.procType.includes("ENCRYPTED"))throw new Error("Could not convert certificate from PEM: PEM is encrypted.");let o=ge.ASN1.fromDER(i.body);r.push(new t(o))}if(r.length===0)throw new Error("No Certificate");return r}static fromPEM(e){return t.fromPEMs(e)[0]}constructor(e){let r=Object.create(null),n=e.validate(Lhe,r);if(n!=null)throw new Error("Cannot read X.509 certificate: "+n.message);if(this.raw=e.DER,this.version=r.certVersion==null?0:ge.ASN1.parseIntegerNum(r.certVersion.bytes)+1,this.serialNumber=ge.ASN1.parseIntegerStr(r.certSerialNumber.bytes),this.signatureOID=ge.ASN1.parseOID(r.certSignatureOID.bytes),this.signatureAlgorithm=Zn.getOIDName(this.signatureOID),this.infoSignatureOID=ge.ASN1.parseOID(r.certinfoSignatureOID.bytes),this.signature=ge.ASN1.parseBitString(r.certSignature.bytes).buf,this.validFrom=ge.ASN1.parseTime(r.certValidityNotBefore.tag,r.certValidityNotBefore.bytes),this.validTo=ge.ASN1.parseTime(r.certValidityNotAfter.tag,r.certValidityNotAfter.bytes),this.issuer=new I0,this.issuer.setAttrs(b9(r.certIssuer)),r.certIssuerUniqueId!=null&&(this.issuer.uniqueId=ge.ASN1.parseBitString(r.certIssuerUniqueId.bytes)),this.subject=new I0,this.subject.setAttrs(b9(r.certSubject)),r.certSubjectUniqueId!=null&&(this.subject.uniqueId=ge.ASN1.parseBitString(r.certSubjectUniqueId.bytes)),this.extensions=[],this.subjectKeyIdentifier="",this.authorityKeyIdentifier="",this.ocspServer="",this.issuingCertificateURL="",this.isCA=!1,this.maxPathLen=-1,this.basicConstraintsValid=!1,this.keyUsage=0,this.dnsNames=[],this.emailAddresses=[],this.ipAddresses=[],this.uris=[],r.certExtensions!=null){this.extensions=Hhe(r.certExtensions);for(let i of this.extensions)if(typeof i.subjectKeyIdentifier=="string"&&(this.subjectKeyIdentifier=i.subjectKeyIdentifier),typeof i.authorityKeyIdentifier=="string"&&(this.authorityKeyIdentifier=i.authorityKeyIdentifier),typeof i.authorityInfoAccessOcsp=="string"&&(this.ocspServer=i.authorityInfoAccessOcsp),typeof i.authorityInfoAccessIssuers=="string"&&(this.issuingCertificateURL=i.authorityInfoAccessIssuers),typeof i.basicConstraintsValid=="boolean"&&(this.isCA=i.isCA,this.maxPathLen=i.maxPathLen,this.basicConstraintsValid=i.basicConstraintsValid),typeof i.keyUsage=="number"&&(this.keyUsage=i.keyUsage),Array.isArray(i.altNames))for(let o of i.altNames)o.dnsName!=null&&this.dnsNames.push(o.dnsName),o.email!=null&&this.emailAddresses.push(o.email),o.ip!=null&&this.ipAddresses.push(o.ip),o.uri!=null&&this.uris.push(o.uri)}this.publicKey=new w9.PublicKey(r.publicKeyInfo),this.publicKeyRaw=this.publicKey.toDER(),this.tbsCertificate=r.tbsCertificate}getExtension(e,r=""){for(let n of this.extensions)if(e===n.oid||e===n.name)return r===""?n:n[r];return null}checkSignature(e){if(this.version===3&&!this.basicConstraintsValid||this.basicConstraintsValid&&!this.isCA)return new Error("The parent constraint violation error");if(this.getExtension("keyUsage","keyCertSign")!==!0)return new Error("The parent constraint violation error");if(!e.isIssuer(this))return new Error("The parent certificate did not issue the given child certificate");let r=Xhe(e.signatureOID);return r===""?new Error("Unknown child signature OID."):this.publicKey.verify(e.tbsCertificate.DER,e.signature,r)===!1?new Error("Child signature not matched"):null}isIssuer(e){return this.issuer.getHash().equals(e.subject.getHash())}verifySubjectKeyIdentifier(){return this.publicKey.getFingerprint("sha1","PublicKey").toString("hex")===this.subjectKeyIdentifier}toJSON(){let e={};for(let r of Object.keys(this))e[r]=Yhe(this[r]);return delete e.tbsCertificate,e}[v9.inspect.custom](e,r){return r.depth<=2&&(r.depth=10),`<${this.constructor.name} ${v9.inspect(this.toJSON(),r)}>`}};Fw.Certificate=d_;function Hhe(t){let e=[];for(let r of t.mustCompound())for(let n of r.mustCompound())e.push(Uhe(n));return e}function Uhe(t){let e={};switch(e.oid=ge.ASN1.parseOID(t.value[0].bytes),e.critical=!1,t.value[1].tag===ge.Tag.BOOLEAN?(e.critical=ge.ASN1.parseBool(t.value[1].bytes),e.value=t.value[2].bytes):e.value=t.value[1].bytes,e.name=Zn.getOIDName(e.oid),e.name){case"keyUsage":$he(e);break;case"basicConstraints":Fhe(e);break;case"extKeyUsage":jhe(e);break;case"nsCertType":qhe(e);break;case"subjectAltName":x9(e);break;case"issuerAltName":x9(e);break;case"subjectKeyIdentifier":Vhe(e);break;case"authorityKeyIdentifier":zhe(e);break;case"authorityInfoAccess":Jhe(e);break}return e}function $he(t){let e=ge.ASN1.parseBitString(ge.ASN1.fromDER(t.value).bytes),r=0,n=0;t.keyUsage=0;for(let i=0;i<9;i++)e.at(i)!==0&&(t.keyUsage|=1<<i);e.buf.length>0&&(r=e.buf[0],n=e.buf.length>1?e.buf[1]:0),t.digitalSignature=(r&128)===128,t.nonRepudiation=(r&64)===64,t.keyEncipherment=(r&32)===32,t.dataEncipherment=(r&16)===16,t.keyAgreement=(r&8)===8,t.keyCertSign=(r&4)===4,t.cRLSign=(r&2)===2,t.encipherOnly=(r&1)===1,t.decipherOnly=(n&128)===128}function Fhe(t){let r=ge.ASN1.fromDER(t.value).mustCompound();r.length>0&&r[0].tag===ge.Tag.BOOLEAN?t.isCA=ge.ASN1.parseBool(r[0].bytes):t.isCA=!1;let n=null;r.length>0&&r[0].tag===ge.Tag.INTEGER?n=r[0].bytes:r.length>1&&(n=r[1].bytes),n!==null?t.maxPathLen=ge.ASN1.parseInteger(n):t.maxPathLen=-1,t.basicConstraintsValid=!0}function jhe(t){let r=ge.ASN1.fromDER(t.value).mustCompound();for(let n of r)t[Zn.getOIDName(ge.ASN1.parseOID(n.bytes))]=!0}function qhe(t){let e=ge.ASN1.parseBitString(ge.ASN1.fromDER(t.value).bytes),r=0;e.buf.length>0&&(r=e.buf[0]),t.client=(r&128)===128,t.server=(r&64)===64,t.email=(r&32)===32,t.objsign=(r&16)===16,t.reserved=(r&8)===8,t.sslCA=(r&4)===4,t.emailCA=(r&2)===2,t.objCA=(r&1)===1}function x9(t){t.altNames=[];let r=ge.ASN1.fromDER(t.value).mustCompound();for(let n of r){let i={tag:n.tag,value:n.bytes};switch(t.altNames.push(i),n.tag){case 1:i.email=n.bytes.toString();break;case 2:i.dnsName=n.bytes.toString();break;case 6:i.uri=n.bytes.toString();break;case 7:i.ip=Zn.bytesToIP(n.bytes);break;case 8:i.oid=ge.ASN1.parseOID(n.bytes);break;default:}}}var Whe={name:"subjectKeyIdentifier",class:ge.Class.UNIVERSAL,tag:ge.Tag.OCTETSTRING,capture:"subjectKeyIdentifier"};function Vhe(t){let e=ge.ASN1.parseDERWithTemplate(t.value,Whe);t.subjectKeyIdentifier=e.subjectKeyIdentifier.bytes.toString("hex")}var Ghe={name:"authorityKeyIdentifier",class:ge.Class.UNIVERSAL,tag:ge.Tag.SEQUENCE,value:[{name:"authorityKeyIdentifier.value",class:ge.Class.CONTEXT_SPECIFIC,tag:ge.Tag.NONE,capture:"authorityKeyIdentifier"}]};function zhe(t){let e=ge.ASN1.parseDERWithTemplate(t.value,Ghe);t.authorityKeyIdentifier=e.authorityKeyIdentifier.bytes.toString("hex")}var Khe={name:"authorityInfoAccess",class:ge.Class.UNIVERSAL,tag:ge.Tag.SEQUENCE,value:[{name:"authorityInfoAccess.authorityInfoAccessOcsp",class:ge.Class.UNIVERSAL,tag:ge.Tag.SEQUENCE,optional:!0,value:[{name:"authorityInfoAccess.authorityInfoAccessOcsp.oid",class:ge.Class.UNIVERSAL,tag:ge.Tag.OID},{name:"authorityInfoAccess.authorityInfoAccessOcsp.value",class:ge.Class.CONTEXT_SPECIFIC,tag:ge.Tag.OID,capture:"authorityInfoAccessOcsp"}]},{name:"authorityInfoAccess.authorityInfoAccessIssuers",class:ge.Class.UNIVERSAL,tag:ge.Tag.SEQUENCE,optional:!0,value:[{name:"authorityInfoAccess.authorityInfoAccessIssuers.oid",class:ge.Class.UNIVERSAL,tag:ge.Tag.OID},{name:"authorityInfoAccess.authorityInfoAccessIssuers.value",class:ge.Class.CONTEXT_SPECIFIC,tag:ge.Tag.OID,capture:"authorityInfoAccessIssuers"}]}]};function Jhe(t){let e=ge.ASN1.parseDERWithTemplate(t.value,Khe);e.authorityInfoAccessOcsp!=null&&(t.authorityInfoAccessOcsp=e.authorityInfoAccessOcsp.bytes.toString()),e.authorityInfoAccessIssuers!=null&&(t.authorityInfoAccessIssuers=e.authorityInfoAccessIssuers.bytes.toString())}function S9(t){for(let e of t){if((e.name==null||e.name==="")&&(e.oid!=null&&(e.name=Zn.getOIDName(e.oid)),e.name===""&&e.shortName!=null&&(e.name=Zn.getOIDName(fn[e.shortName]))),e.oid==null||e.oid==="")if(e.name!=="")e.oid=Zn.getOID(e.name);else throw new Error("Attribute oid not specified.");if((e.shortName==null||e.shortName==="")&&(e.shortName=fn[e.name]==null?"":fn[e.name]),e.value==null)throw new Error("Attribute value not specified.")}}function Xhe(t){switch(Zn.getOIDName(t)){case"sha1WithRsaEncryption":return"sha1";case"md5WithRsaEncryption":return"md5";case"sha256WithRsaEncryption":return"sha256";case"sha384WithRsaEncryption":return"sha384";case"sha512WithRsaEncryption":return"sha512";case"RSASSA-PSS":return"sha256";case"ecdsaWithSha1":return"sha1";case"ecdsaWithSha256":return"sha256";case"ecdsaWithSha384":return"sha384";case"ecdsaWithSha512":return"sha512";case"dsaWithSha1":return"sha1";case"dsaWithSha256":return"sha256";default:return""}}function b9(t){let e=[];for(let r of t.mustCompound())for(let n of r.mustCompound()){let i=n.mustCompound(),o={};o.oid=ge.ASN1.parseOID(i[0].bytes),o.value=i[1].value,o.valueTag=i[1].tag,o.name=Zn.getOIDName(o.oid),o.shortName=Mhe(o.name),e.push(o)}return e}function Yhe(t){return t!=null&&!(t instanceof Buffer)&&typeof t.toJSON=="function"?t.toJSON():t}});var l_=ce(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});var jw=Ow();Io.bytesFromIP=jw.bytesFromIP;Io.bytesToIP=jw.bytesToIP;Io.getOID=jw.getOID;Io.getOIDName=jw.getOIDName;var qw=u_();Io.PublicKey=qw.PublicKey;Io.PrivateKey=qw.PrivateKey;Io.RSAPublicKey=qw.RSAPublicKey;Io.RSAPrivateKey=qw.RSAPrivateKey;var E9=I9();Io.Certificate=E9.Certificate;Io.DistinguishedName=E9.DistinguishedName});var R9=ce(()=>{var k9;(function(t){(function(e){var r=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:a(),n=i(t);typeof r.Reflect<"u"&&(n=i(r.Reflect,n)),e(n,r),typeof r.Reflect>"u"&&(r.Reflect=t);function i(c,u){return function(d,l){Object.defineProperty(c,d,{configurable:!0,writable:!0,value:l}),u&&u(d,l)}}function o(){try{return Function("return this;")()}catch{}}function s(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return o()||s()}})(function(e,r){var n=Object.prototype.hasOwnProperty,i=typeof Symbol=="function",o=i&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",s=i&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",c={__proto__:[]}instanceof Array,u=!a&&!c,d={create:a?function(){return Vd(Object.create(null))}:c?function(){return Vd({__proto__:null})}:function(){return Vd({})},has:u?function(M,q){return n.call(M,q)}:function(M,q){return q in M},get:u?function(M,q){return n.call(M,q)?M[q]:void 0}:function(M,q){return M[q]}},l=Object.getPrototypeOf(Function),f=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Yh(),p=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:gS(),g=typeof WeakMap=="function"?WeakMap:ZR(),v=i?Symbol.for("@reflect-metadata:registry"):void 0,b=Kf(),C=Xh(b);function D(M,q,Y,we){if(T(Y)){if(!lo(M))throw new TypeError;if(!jd(q))throw new TypeError;return se(M,q)}else{if(!lo(M))throw new TypeError;if(!be(q))throw new TypeError;if(!be(we)&&!T(we)&&!$(we))throw new TypeError;return $(we)&&(we=void 0),Y=_t(Y),H(M,q,Y,we)}}e("decorate",D);function _(M,q){function Y(we,et){if(!be(we))throw new TypeError;if(!T(et)&&!QR(et))throw new TypeError;Te(M,q,we,et)}return Y}e("metadata",_);function F(M,q,Y,we){if(!be(Y))throw new TypeError;return T(we)||(we=_t(we)),Te(M,q,Y,we)}e("defineMetadata",F);function he(M,q,Y){if(!be(q))throw new TypeError;return T(Y)||(Y=_t(Y)),G(M,q,Y)}e("hasMetadata",he);function z(M,q,Y){if(!be(q))throw new TypeError;return T(Y)||(Y=_t(Y)),j(M,q,Y)}e("hasOwnMetadata",z);function Ce(M,q,Y){if(!be(q))throw new TypeError;return T(Y)||(Y=_t(Y)),me(M,q,Y)}e("getMetadata",Ce);function de(M,q,Y){if(!be(q))throw new TypeError;return T(Y)||(Y=_t(Y)),Pe(M,q,Y)}e("getOwnMetadata",de);function R(M,q){if(!be(M))throw new TypeError;return T(q)||(q=_t(q)),P(M,q)}e("getMetadataKeys",R);function V(M,q){if(!be(M))throw new TypeError;return T(q)||(q=_t(q)),B(M,q)}e("getOwnMetadataKeys",V);function le(M,q,Y){if(!be(q))throw new TypeError;if(T(Y)||(Y=_t(Y)),!be(q))throw new TypeError;T(Y)||(Y=_t(Y));var we=_a(q,Y,!1);return T(we)?!1:we.OrdinaryDeleteMetadata(M,q,Y)}e("deleteMetadata",le);function se(M,q){for(var Y=M.length-1;Y>=0;--Y){var we=M[Y],et=we(q);if(!T(et)&&!$(et)){if(!jd(et))throw new TypeError;q=et}}return q}function H(M,q,Y,we){for(var et=M.length-1;et>=0;--et){var vr=M[et],wr=vr(q,Y,we);if(!T(wr)&&!$(wr)){if(!be(wr))throw new TypeError;we=wr}}return we}function G(M,q,Y){var we=j(M,q,Y);if(we)return!0;var et=Wd(q);return $(et)?!1:G(M,et,Y)}function j(M,q,Y){var we=_a(q,Y,!1);return T(we)?!1:Zt(we.OrdinaryHasOwnMetadata(M,q,Y))}function me(M,q,Y){var we=j(M,q,Y);if(we)return Pe(M,q,Y);var et=Wd(q);if(!$(et))return me(M,et,Y)}function Pe(M,q,Y){var we=_a(q,Y,!1);if(!T(we))return we.OrdinaryGetOwnMetadata(M,q,Y)}function Te(M,q,Y,we){var et=_a(Y,we,!0);et.OrdinaryDefineOwnMetadata(M,q,Y,we)}function P(M,q){var Y=B(M,q),we=Wd(M);if(we===null)return Y;var et=P(we,q);if(et.length<=0)return Y;if(Y.length<=0)return et;for(var vr=new p,wr=[],St=0,Be=Y;St<Be.length;St++){var Fe=Be[St],Ge=vr.has(Fe);Ge||(vr.add(Fe),wr.push(Fe))}for(var Xe=0,mt=et;Xe<mt.length;Xe++){var Fe=mt[Xe],Ge=vr.has(Fe);Ge||(vr.add(Fe),wr.push(Fe))}return wr}function B(M,q){var Y=_a(M,q,!1);return Y?Y.OrdinaryOwnMetadataKeys(M,q):[]}function K(M){if(M===null)return 1;switch(typeof M){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return M===null?1:6;default:return 6}}function T(M){return M===void 0}function $(M){return M===null}function ye(M){return typeof M=="symbol"}function be(M){return typeof M=="object"?M!==null:typeof M=="function"}function ct(M,q){switch(K(M)){case 0:return M;case 1:return M;case 2:return M;case 3:return M;case 4:return M;case 5:return M}var Y=q===3?"string":q===5?"number":"default",we=Gh(M,o);if(we!==void 0){var et=we.call(M,Y);if(be(et))throw new TypeError;return et}return It(M,Y==="default"?"number":Y)}function It(M,q){if(q==="string"){var Y=M.toString;if(fo(Y)){var we=Y.call(M);if(!be(we))return we}var et=M.valueOf;if(fo(et)){var we=et.call(M);if(!be(we))return we}}else{var et=M.valueOf;if(fo(et)){var we=et.call(M);if(!be(we))return we}var vr=M.toString;if(fo(vr)){var we=vr.call(M);if(!be(we))return we}}throw new TypeError}function Zt(M){return!!M}function Dt(M){return""+M}function _t(M){var q=ct(M,3);return ye(q)?q:Dt(q)}function lo(M){return Array.isArray?Array.isArray(M):M instanceof Object?M instanceof Array:Object.prototype.toString.call(M)==="[object Array]"}function fo(M){return typeof M=="function"}function jd(M){return typeof M=="function"}function QR(M){switch(K(M)){case 3:return!0;case 4:return!0;default:return!1}}function Vh(M,q){return M===q||M!==M&&q!==q}function Gh(M,q){var Y=M[q];if(Y!=null){if(!fo(Y))throw new TypeError;return Y}}function zh(M){var q=Gh(M,s);if(!fo(q))throw new TypeError;var Y=q.call(M);if(!be(Y))throw new TypeError;return Y}function Ts(M){return M.value}function qd(M){var q=M.next();return q.done?!1:q}function Kh(M){var q=M.return;q&&q.call(M)}function Wd(M){var q=Object.getPrototypeOf(M);if(typeof M!="function"||M===l||q!==l)return q;var Y=M.prototype,we=Y&&Object.getPrototypeOf(Y);if(we==null||we===Object.prototype)return q;var et=we.constructor;return typeof et!="function"||et===M?q:et}function Jh(){var M;!T(v)&&typeof r.Reflect<"u"&&!(v in r.Reflect)&&typeof r.Reflect.defineMetadata=="function"&&(M=Jf(r.Reflect));var q,Y,we,et=new g,vr={registerProvider:wr,getProvider:Be,setProvider:Ge};return vr;function wr(Xe){if(!Object.isExtensible(vr))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case M===Xe:break;case T(q):q=Xe;break;case q===Xe:break;case T(Y):Y=Xe;break;case Y===Xe:break;default:we===void 0&&(we=new p),we.add(Xe);break}}function St(Xe,mt){if(!T(q)){if(q.isProviderFor(Xe,mt))return q;if(!T(Y)){if(Y.isProviderFor(Xe,mt))return q;if(!T(we))for(var Kt=zh(we);;){var dr=qd(Kt);if(!dr)return;var ii=Ts(dr);if(ii.isProviderFor(Xe,mt))return Kh(Kt),ii}}}if(!T(M)&&M.isProviderFor(Xe,mt))return M}function Be(Xe,mt){var Kt=et.get(Xe),dr;return T(Kt)||(dr=Kt.get(mt)),T(dr)&&(dr=St(Xe,mt),T(dr)||(T(Kt)&&(Kt=new f,et.set(Xe,Kt)),Kt.set(mt,dr))),dr}function Fe(Xe){if(T(Xe))throw new TypeError;return q===Xe||Y===Xe||!T(we)&&we.has(Xe)}function Ge(Xe,mt,Kt){if(!Fe(Kt))throw new Error("Metadata provider not registered.");var dr=Be(Xe,mt);if(dr!==Kt){if(!T(dr))return!1;var ii=et.get(Xe);T(ii)&&(ii=new f,et.set(Xe,ii)),ii.set(mt,Kt)}return!0}}function Kf(){var M;return!T(v)&&be(r.Reflect)&&Object.isExtensible(r.Reflect)&&(M=r.Reflect[v]),T(M)&&(M=Jh()),!T(v)&&be(r.Reflect)&&Object.isExtensible(r.Reflect)&&Object.defineProperty(r.Reflect,v,{enumerable:!1,configurable:!1,writable:!1,value:M}),M}function Xh(M){var q=new g,Y={isProviderFor:function(Fe,Ge){var Xe=q.get(Fe);return T(Xe)?!1:Xe.has(Ge)},OrdinaryDefineOwnMetadata:wr,OrdinaryHasOwnMetadata:et,OrdinaryGetOwnMetadata:vr,OrdinaryOwnMetadataKeys:St,OrdinaryDeleteMetadata:Be};return b.registerProvider(Y),Y;function we(Fe,Ge,Xe){var mt=q.get(Fe),Kt=!1;if(T(mt)){if(!Xe)return;mt=new f,q.set(Fe,mt),Kt=!0}var dr=mt.get(Ge);if(T(dr)){if(!Xe)return;if(dr=new f,mt.set(Ge,dr),!M.setProvider(Fe,Ge,Y))throw mt.delete(Ge),Kt&&q.delete(Fe),new Error("Wrong provider for target.")}return dr}function et(Fe,Ge,Xe){var mt=we(Ge,Xe,!1);return T(mt)?!1:Zt(mt.has(Fe))}function vr(Fe,Ge,Xe){var mt=we(Ge,Xe,!1);if(!T(mt))return mt.get(Fe)}function wr(Fe,Ge,Xe,mt){var Kt=we(Xe,mt,!0);Kt.set(Fe,Ge)}function St(Fe,Ge){var Xe=[],mt=we(Fe,Ge,!1);if(T(mt))return Xe;for(var Kt=mt.keys(),dr=zh(Kt),ii=0;;){var Xf=qd(dr);if(!Xf)return Xe.length=ii,Xe;var yS=Ts(Xf);try{Xe[ii]=yS}catch(e1){try{Kh(dr)}finally{throw e1}}ii++}}function Be(Fe,Ge,Xe){var mt=we(Ge,Xe,!1);if(T(mt)||!mt.delete(Fe))return!1;if(mt.size===0){var Kt=q.get(Ge);T(Kt)||(Kt.delete(Xe),Kt.size===0&&q.delete(Kt))}return!0}}function Jf(M){var q=M.defineMetadata,Y=M.hasOwnMetadata,we=M.getOwnMetadata,et=M.getOwnMetadataKeys,vr=M.deleteMetadata,wr=new g,St={isProviderFor:function(Be,Fe){var Ge=wr.get(Be);return!T(Ge)&&Ge.has(Fe)?!0:et(Be,Fe).length?(T(Ge)&&(Ge=new p,wr.set(Be,Ge)),Ge.add(Fe),!0):!1},OrdinaryDefineOwnMetadata:q,OrdinaryHasOwnMetadata:Y,OrdinaryGetOwnMetadata:we,OrdinaryOwnMetadataKeys:et,OrdinaryDeleteMetadata:vr};return St}function _a(M,q,Y){var we=b.getProvider(M,q);if(!T(we))return we;if(Y){if(b.setProvider(M,q,C))return C;throw new Error("Illegal state.")}}function Yh(){var M={},q=[],Y=(function(){function St(Be,Fe,Ge){this._index=0,this._keys=Be,this._values=Fe,this._selector=Ge}return St.prototype["@@iterator"]=function(){return this},St.prototype[s]=function(){return this},St.prototype.next=function(){var Be=this._index;if(Be>=0&&Be<this._keys.length){var Fe=this._selector(this._keys[Be],this._values[Be]);return Be+1>=this._keys.length?(this._index=-1,this._keys=q,this._values=q):this._index++,{value:Fe,done:!1}}return{value:void 0,done:!0}},St.prototype.throw=function(Be){throw this._index>=0&&(this._index=-1,this._keys=q,this._values=q),Be},St.prototype.return=function(Be){return this._index>=0&&(this._index=-1,this._keys=q,this._values=q),{value:Be,done:!0}},St})(),we=(function(){function St(){this._keys=[],this._values=[],this._cacheKey=M,this._cacheIndex=-2}return Object.defineProperty(St.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),St.prototype.has=function(Be){return this._find(Be,!1)>=0},St.prototype.get=function(Be){var Fe=this._find(Be,!1);return Fe>=0?this._values[Fe]:void 0},St.prototype.set=function(Be,Fe){var Ge=this._find(Be,!0);return this._values[Ge]=Fe,this},St.prototype.delete=function(Be){var Fe=this._find(Be,!1);if(Fe>=0){for(var Ge=this._keys.length,Xe=Fe+1;Xe<Ge;Xe++)this._keys[Xe-1]=this._keys[Xe],this._values[Xe-1]=this._values[Xe];return this._keys.length--,this._values.length--,Vh(Be,this._cacheKey)&&(this._cacheKey=M,this._cacheIndex=-2),!0}return!1},St.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=M,this._cacheIndex=-2},St.prototype.keys=function(){return new Y(this._keys,this._values,et)},St.prototype.values=function(){return new Y(this._keys,this._values,vr)},St.prototype.entries=function(){return new Y(this._keys,this._values,wr)},St.prototype["@@iterator"]=function(){return this.entries()},St.prototype[s]=function(){return this.entries()},St.prototype._find=function(Be,Fe){if(!Vh(this._cacheKey,Be)){this._cacheIndex=-1;for(var Ge=0;Ge<this._keys.length;Ge++)if(Vh(this._keys[Ge],Be)){this._cacheIndex=Ge;break}}return this._cacheIndex<0&&Fe&&(this._cacheIndex=this._keys.length,this._keys.push(Be),this._values.push(void 0)),this._cacheIndex},St})();return we;function et(St,Be){return St}function vr(St,Be){return Be}function wr(St,Be){return[St,Be]}}function gS(){var M=(function(){function q(){this._map=new f}return Object.defineProperty(q.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),q.prototype.has=function(Y){return this._map.has(Y)},q.prototype.add=function(Y){return this._map.set(Y,Y),this},q.prototype.delete=function(Y){return this._map.delete(Y)},q.prototype.clear=function(){this._map.clear()},q.prototype.keys=function(){return this._map.keys()},q.prototype.values=function(){return this._map.keys()},q.prototype.entries=function(){return this._map.entries()},q.prototype["@@iterator"]=function(){return this.keys()},q.prototype[s]=function(){return this.keys()},q})();return M}function ZR(){var M=16,q=d.create(),Y=we();return(function(){function Be(){this._key=we()}return Be.prototype.has=function(Fe){var Ge=et(Fe,!1);return Ge!==void 0?d.has(Ge,this._key):!1},Be.prototype.get=function(Fe){var Ge=et(Fe,!1);return Ge!==void 0?d.get(Ge,this._key):void 0},Be.prototype.set=function(Fe,Ge){var Xe=et(Fe,!0);return Xe[this._key]=Ge,this},Be.prototype.delete=function(Fe){var Ge=et(Fe,!1);return Ge!==void 0?delete Ge[this._key]:!1},Be.prototype.clear=function(){this._key=we()},Be})();function we(){var Be;do Be="@@WeakMap@@"+St();while(d.has(q,Be));return q[Be]=!0,Be}function et(Be,Fe){if(!n.call(Be,Y)){if(!Fe)return;Object.defineProperty(Be,Y,{value:d.create()})}return Be[Y]}function vr(Be,Fe){for(var Ge=0;Ge<Fe;++Ge)Be[Ge]=Math.random()*255|0;return Be}function wr(Be){if(typeof Uint8Array=="function"){var Fe=new Uint8Array(Be);return typeof crypto<"u"?crypto.getRandomValues(Fe):typeof msCrypto<"u"?msCrypto.getRandomValues(Fe):vr(Fe,Be),Fe}return vr(new Array(Be),Be)}function St(){var Be=wr(M);Be[6]=Be[6]&79|64,Be[8]=Be[8]&191|128;for(var Fe="",Ge=0;Ge<M;++Ge){var Xe=Be[Ge];(Ge===4||Ge===6||Ge===8)&&(Fe+="-"),Xe<16&&(Fe+="0"),Fe+=Xe.toString(16).toLowerCase()}return Fe}}function Vd(M){return M.__=void 0,delete M.__,M}})})(k9||(k9={}))});var p_=ce(Lp=>{"use strict";var Qhe="[object ArrayBuffer]",tc=class t{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Qhe}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,r){if(e.constructor===r)return e;if(this.isArrayBuffer(e))return new r(e);if(this.isArrayBufferView(e))return new r(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,r){let n=t.toUint8Array(e),i=t.toUint8Array(r);if(n.length!==i.byteLength)return!1;for(let o=0;o<n.length;o++)if(n[o]!==i[o])return!1;return!0}static concat(...e){let r;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?r=e[0]:e[e.length-1]instanceof Function?r=e.slice(0,e.length-1):r=e;let n=0;for(let s of r)n+=s.byteLength;let i=new Uint8Array(n),o=0;for(let s of r){let a=this.toUint8Array(s);i.set(a,o),o+=a.length}return e[e.length-1]instanceof Function?this.toView(i,e[e.length-1]):i.buffer}},f_="string",Zhe=/^[0-9a-f\s]+$/i,ege=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,tge=/^[a-zA-Z0-9-_]+$/,Ww=class{static fromString(e){let r=unescape(encodeURIComponent(e)),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return n.buffer}static toString(e){let r=tc.toUint8Array(e),n="";for(let o=0;o<r.length;o++)n+=String.fromCharCode(r[o]);return decodeURIComponent(escape(n))}},Eo=class{static toString(e,r=!1){let n=tc.toArrayBuffer(e),i=new DataView(n),o="";for(let s=0;s<n.byteLength;s+=2){let a=i.getUint16(s,r);o+=String.fromCharCode(a)}return o}static fromString(e,r=!1){let n=new ArrayBuffer(e.length*2),i=new DataView(n);for(let o=0;o<e.length;o++)i.setUint16(o*2,e.charCodeAt(o),r);return n}},Vw=class t{static isHex(e){return typeof e===f_&&Zhe.test(e)}static isBase64(e){return typeof e===f_&&ege.test(e)}static isBase64Url(e){return typeof e===f_&&tge.test(e)}static ToString(e,r="utf8"){let n=tc.toUint8Array(e);switch(r.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Eo.toString(n,!0);case"utf16":case"utf16be":return Eo.toString(n);default:throw new Error(`Unknown type of encoding '${r}'`)}}static FromString(e,r="utf8"){if(!e)return new ArrayBuffer(0);switch(r.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Eo.fromString(e,!0);case"utf16":case"utf16be":return Eo.fromString(e);default:throw new Error(`Unknown type of encoding '${r}'`)}}static ToBase64(e){let r=tc.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(r,"binary");return btoa(n)}else return Buffer.from(r).toString("base64")}static FromBase64(e){let r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!t.isBase64(r))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(r)):new Uint8Array(Buffer.from(r,"base64")).buffer}static FromBase64Url(e){let r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!t.isBase64Url(r))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(r.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,r=t.DEFAULT_UTF8_ENCODING){switch(r){case"ascii":return this.FromBinary(e);case"utf8":return Ww.fromString(e);case"utf16":case"utf16be":return Eo.fromString(e);case"utf16le":case"usc2":return Eo.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${r}'`)}}static ToUtf8String(e,r=t.DEFAULT_UTF8_ENCODING){switch(r){case"ascii":return this.ToBinary(e);case"utf8":return Ww.toString(e);case"utf16":case"utf16be":return Eo.toString(e);case"utf16le":case"usc2":return Eo.toString(e,!0);default:throw new Error(`Unknown type of encoding '${r}'`)}}static FromBinary(e){let r=e.length,n=new Uint8Array(r);for(let i=0;i<r;i++)n[i]=e.charCodeAt(i);return n.buffer}static ToBinary(e){let r=tc.toUint8Array(e),n="";for(let i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return n}static ToHex(e){let r=tc.toUint8Array(e),n="",i=r.length;for(let o=0;o<i;o++){let s=r[o];s<16&&(n+="0"),n+=s.toString(16)}return n}static FromHex(e){let r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!t.isHex(r))throw new TypeError("Argument 'hexString' is not HEX encoded");r.length%2&&(r=`0${r}`);let n=new Uint8Array(r.length/2);for(let i=0;i<r.length;i=i+2){let o=r.slice(i,i+2);n[i/2]=parseInt(o,16)}return n.buffer}static ToUtf16String(e,r=!1){return Eo.toString(e,r)}static FromUtf16String(e,r=!1){return Eo.fromString(e,r)}static Base64Padding(e){let r=4-e.length%4;if(r<4)for(let n=0;n<r;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};Vw.DEFAULT_UTF8_ENCODING="utf8";function rge(t,...e){let r=arguments[0];for(let n=1;n<arguments.length;n++){let i=arguments[n];for(let o in i)r[o]=i[o]}return r}function nge(...t){let e=t.map(i=>i.byteLength).reduce((i,o)=>i+o),r=new Uint8Array(e),n=0;return t.map(i=>new Uint8Array(i)).forEach(i=>{for(let o of i)r[n++]=o}),r.buffer}function ige(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;let r=new Uint8Array(t),n=new Uint8Array(e);for(let i=0;i<t.byteLength;i++)if(r[i]!==n[i])return!1;return!0}Lp.BufferSourceConverter=tc;Lp.Convert=Vw;Lp.assign=rge;Lp.combine=nge;Lp.isEqual=ige});var P9=ce(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});function oge(t){return new Date(t.getTime()+t.getTimezoneOffset()*6e4)}function sge(t,e,r){var n;return t instanceof Object&&(n=t[e])!==null&&n!==void 0?n:r}function age(t,e=0,r=t.byteLength-e,n=!1){let i="";for(let o of new Uint8Array(t,e,r)){let s=o.toString(16).toUpperCase();s.length===1&&(i+="0"),i+=s,n&&(i+=" ")}return i.trim()}function cge(t,e,r,n){return e instanceof ArrayBuffer?e.byteLength?r<0?(t.error="Wrong parameter: inputOffset less than zero",!1):n<0?(t.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-r-n<0?(t.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(t.error="Wrong parameter: inputBuffer has zero length",!1):(t.error='Wrong parameter: inputBuffer must be "ArrayBuffer"',!1)}function m_(t,e){let r=0;if(t.length===1)return t[0];for(let n=t.length-1;n>=0;n--)r+=t[t.length-1-n]*Math.pow(2,e*n);return r}function h_(t,e,r=-1){let n=r,i=t,o=0,s=Math.pow(2,e);for(let a=1;a<8;a++){if(t<s){let c;if(n<0)c=new ArrayBuffer(a),o=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),o=n}let u=new Uint8Array(c);for(let d=a-1;d>=0;d--){let l=Math.pow(2,d*e);u[o-d-1]=Math.floor(i/l),i-=u[o-d-1]*l}return c}s*=Math.pow(2,e)}return new ArrayBuffer(0)}function uge(...t){let e=0,r=0;for(let o of t)e+=o.byteLength;let n=new ArrayBuffer(e),i=new Uint8Array(n);for(let o of t)i.set(new Uint8Array(o),r),r+=o.byteLength;return n}function dge(...t){let e=0,r=0;for(let o of t)e+=o.length;let n=new ArrayBuffer(e),i=new Uint8Array(n);for(let o of t)i.set(o,r),r+=o.length;return i}function lge(){let t=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=t[0]===255&&t[1]&128,c=t[0]===0&&(t[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)r[a]=0;r[0]=t[0]&128;let n=m_(r,8),i=new ArrayBuffer(this.valueHex.byteLength),o=new Uint8Array(i);for(let a=0;a<this.valueHex.byteLength;a++)o[a]=t[a];return o[0]&=127,m_(o,8)-n}function fge(t){let e=t<0?t*-1:t,r=128;for(let n=1;n<8;n++){if(e<=r){if(t<0){let s=r-e,a=h_(s,8,n),c=new Uint8Array(a);return c[0]|=128,a}let i=h_(e,8,n),o=new Uint8Array(i);if(o[0]&128){let s=i.slice(0),a=new Uint8Array(s);i=new ArrayBuffer(i.byteLength+1),o=new Uint8Array(i);for(let c=0;c<s.byteLength;c++)o[c+1]=a[c];o[0]=0}return i}r*=Math.pow(2,8)}return new ArrayBuffer(0)}function pge(t,e){if(t.byteLength!==e.byteLength)return!1;let r=new Uint8Array(t),n=new Uint8Array(e);for(let i=0;i<r.length;i++)if(r[i]!==n[i])return!1;return!0}function mge(t,e){let r=t.toString(10);if(e<r.length)return"";let n=e-r.length,i=new Array(n);for(let s=0;s<n;s++)i[s]="0";return i.join("").concat(r)}var A9="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",C9="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=";function hge(t,e=!1,r=!1,n=!1){let i=0,o=0,s=0,a="",c=e?C9:A9;if(n){let u=0;for(let d=0;d<t.length;d++)if(t.charCodeAt(d)!==0){u=d;break}t=t.slice(u)}for(;i<t.length;){let u=t.charCodeAt(i++);i>=t.length&&(o=1);let d=t.charCodeAt(i++);i>=t.length&&(s=1);let l=t.charCodeAt(i++),f=u>>2,p=(u&3)<<4|d>>4,g=(d&15)<<2|l>>6,v=l&63;o===1?g=v=64:s===1&&(v=64),r?g===64?a+=`${c.charAt(f)}${c.charAt(p)}`:v===64?a+=`${c.charAt(f)}${c.charAt(p)}${c.charAt(g)}`:a+=`${c.charAt(f)}${c.charAt(p)}${c.charAt(g)}${c.charAt(v)}`:a+=`${c.charAt(f)}${c.charAt(p)}${c.charAt(g)}${c.charAt(v)}`}return a}function gge(t,e=!1,r=!1){let n=e?C9:A9;function i(c){for(let u=0;u<64;u++)if(n.charAt(u)===c)return u;return 64}function o(c){return c===64?0:c}let s=0,a="";for(;s<t.length;){let c=i(t.charAt(s++)),u=s>=t.length?0:i(t.charAt(s++)),d=s>=t.length?0:i(t.charAt(s++)),l=s>=t.length?0:i(t.charAt(s++)),f=o(c)<<2|o(u)>>4,p=(o(u)&15)<<4|o(d)>>2,g=(o(d)&3)<<6|o(l);a+=String.fromCharCode(f),d!==64&&(a+=String.fromCharCode(p)),l!==64&&(a+=String.fromCharCode(g))}if(r){let c=a.length,u=-1;for(let d=c-1;d>=0;d--)if(a.charCodeAt(d)!==0){u=d;break}u!==-1?a=a.slice(0,u+1):a=""}return a}function yge(t){let e="",r=new Uint8Array(t);for(let n of r)e+=String.fromCharCode(n);return e}function vge(t){let e=t.length,r=new ArrayBuffer(e),n=new Uint8Array(r);for(let i=0;i<e;i++)n[i]=t.charCodeAt(i);return r}var xge=Math.log(2);function Sge(t){let e=Math.log(t)/xge,r=Math.floor(e),n=Math.round(e);return r===n?r:n}function bge(t,e){for(let r of e)delete t[r]}tn.arrayBufferToString=yge;tn.bufferToHexCodes=age;tn.checkBufferParams=cge;tn.clearProps=bge;tn.fromBase64=gge;tn.getParametersValue=sge;tn.getUTCDate=oge;tn.isEqualBuffer=pge;tn.nearestPowerOf2=Sge;tn.padNumber=mge;tn.stringToArrayBuffer=vge;tn.toBase64=hge;tn.utilConcatBuf=uge;tn.utilConcatView=dge;tn.utilDecodeTC=lge;tn.utilEncodeTC=fge;tn.utilFromBase=m_;tn.utilToBase=h_});var Fu=ce(ut=>{"use strict";var wge=p_(),Ige=P9();function B9(t){var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var Ft=B9(wge),cr=B9(Ige);function Gw(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function v_(t){let e=0,r=0;for(let i=0;i<t.length;i++){let o=t[i];e+=o.byteLength}let n=new Uint8Array(e);for(let i=0;i<t.length;i++){let o=t[i];n.set(new Uint8Array(o),r),r+=o.byteLength}return n.buffer}function ic(t,e,r,n){return e instanceof Uint8Array?e.byteLength?r<0?(t.error="Wrong parameter: inputOffset less than zero",!1):n<0?(t.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-r-n<0?(t.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(t.error="Wrong parameter: inputBuffer has zero length",!1):(t.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var Up=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return v_(this.items)}},E0=[new Uint8Array([1])],_9="0123456789",g_="name",T9="valueHexView",Ege="isHexOnly",kge="idBlock",Rge="tagClass",Age="tagNumber",Cge="isConstructed",Pge="fromBER",_ge="toBER",Tge="local",_i="",Ys=new ArrayBuffer(0),cI=new Uint8Array(0),R0="EndOfContent",N9="OCTET STRING",O9="BIT STRING";function Qs(t){var e;return e=class extends t{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var i;super(...n);let o=n[0]||{};this.isHexOnly=(i=o.isHexOnly)!==null&&i!==void 0?i:!1,this.valueHexView=o.valueHex?Ft.BufferSourceConverter.toUint8Array(o.valueHex):cI}fromBER(n,i,o,s){let a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!ic(this,a,i,o))return-1;let c=i+o;return this.valueHexView=a.subarray(i,c),this.valueHexView.length?(this.blockLength=o,c):(this.warnings.push("Zero buffer length"),i)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Ys)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:Ft.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var rc=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:r=_i,warnings:n=[],valueBeforeDecode:i=cI}={}){this.blockLength=e,this.error=r,this.warnings=n,this.valueBeforeDecodeView=Ft.BufferSourceConverter.toUint8Array(i)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:Ft.Convert.ToHex(this.valueBeforeDecodeView)}}};rc.NAME="baseBlock";var En=class extends rc{fromBER(e,r,n,i){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};En.NAME="valueBlock";var zw=class extends Qs(rc){constructor({idBlock:e={}}={}){var r,n,i,o;super(),e?(this.isHexOnly=(r=e.isHexOnly)!==null&&r!==void 0?r:!1,this.valueHexView=e.valueHex?Ft.BufferSourceConverter.toUint8Array(e.valueHex):cI,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(i=e.tagNumber)!==null&&i!==void 0?i:-1,this.isConstructed=(o=e.isConstructed)!==null&&o!==void 0?o:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let r=0;switch(this.tagClass){case 1:r|=0;break;case 2:r|=64;break;case 3:r|=128;break;case 4:r|=192;break;default:return this.error="Unknown tag class",Ys}if(this.isConstructed&&(r|=32),this.tagNumber<31&&!this.isHexOnly){let i=new Uint8Array(1);if(!e){let o=this.tagNumber;o&=31,r|=o,i[0]=r}return i.buffer}if(!this.isHexOnly){let i=cr.utilToBase(this.tagNumber,7),o=new Uint8Array(i),s=i.byteLength,a=new Uint8Array(s+1);if(a[0]=r|31,!e){for(let c=0;c<s-1;c++)a[c+1]=o[c]|128;a[s]=o[s-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=r|31,!e){let i=this.valueHexView;for(let o=0;o<i.length-1;o++)n[o+1]=i[o]|128;n[this.valueHexView.byteLength]=i[i.length-1]}return n.buffer}fromBER(e,r,n){let i=Ft.BufferSourceConverter.toUint8Array(e);if(!ic(this,i,r,n))return-1;let o=i.subarray(r,r+n);if(o.length===0)return this.error="Zero buffer length",-1;switch(o[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(o[0]&32)===32,this.isHexOnly=!1;let a=o[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=0;for(;;){let d=c+1;if(d>=o.length)return this.error="End of input reached before message was fully decoded",-1;if(c++,(o[d]&128)===0)break}this.blockLength=c+1;let u=this.valueHexView=new Uint8Array(c);for(let d=0;d<c;d++)u[d]=o[d+1]&127;this.blockLength<=9?this.tagNumber=cr.utilFromBase(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return r+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};zw.NAME="identificationBlock";var Kw=class extends rc{constructor({lenBlock:e={}}={}){var r,n,i;super(),this.isIndefiniteForm=(r=e.isIndefiniteForm)!==null&&r!==void 0?r:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(i=e.length)!==null&&i!==void 0?i:0}fromBER(e,r,n){let i=Ft.BufferSourceConverter.toUint8Array(e);if(!ic(this,i,r,n))return-1;let o=i.subarray(r,r+n);if(o.length===0)return this.error="Zero buffer length",-1;if(o[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=o[0]===128,this.isIndefiniteForm)return this.blockLength=1,r+this.blockLength;if(this.longFormUsed=!!(o[0]&128),this.longFormUsed===!1)return this.length=o[0],this.blockLength=1,r+this.blockLength;let s=o[0]&127;if(s>8)return this.error="Too big integer",-1;if(s+1>o.length)return this.error="End of input reached before message was fully decoded",-1;let a=r+1,c=i.subarray(a,a+s);return c[s-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=cr.utilFromBase(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=s+1,r+this.blockLength}toBER(e=!1){let r,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return r=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(r),n[0]=128),r;if(this.longFormUsed){let i=cr.utilToBase(this.length,8);if(i.byteLength>127)return this.error="Too big length",Ys;if(r=new ArrayBuffer(i.byteLength+1),e)return r;let o=new Uint8Array(i);n=new Uint8Array(r),n[0]=i.byteLength|128;for(let s=0;s<i.byteLength;s++)n[s+1]=o[s];return r}return r=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(r),n[0]=this.length),r}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Kw.NAME="lengthBlock";var je={},pn=class extends rc{constructor({name:e=_i,optional:r=!1,primitiveSchema:n,...i}={},o){super(i),this.name=e,this.optional=r,n&&(this.primitiveSchema=n),this.idBlock=new zw(i),this.lenBlock=new Kw(i),this.valueBlock=o?new o(i):new En(i)}fromBER(e,r,n,i){let o=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,i);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,r){let n=r||new Up;r||M9(this);let i=this.idBlock.toBER(e);if(n.write(i),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let o=this.valueBlock.toBER(e);this.lenBlock.length=o.byteLength;let s=this.lenBlock.toBER(e);n.write(s),n.write(o)}return r?Ys:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():Ft.Convert.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,r=Ft.Convert.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${r}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let r=this.toBER(),n=e.toBER();return cr.isEqualBuffer(r,n)}};pn.NAME="BaseBlock";function M9(t){var e;if(t instanceof je.Constructed)for(let r of t.valueBlock.value)M9(r)&&(t.lenBlock.isIndefiniteForm=!0);return!!(!((e=t.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}var A0=class extends pn{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=_i,...r}={},n){super(r,n),e&&this.fromString(e)}fromBER(e,r,n){let i=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return i===-1?(this.error=this.valueBlock.error,i):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};A0.NAME="BaseStringBlock";var Jw=class extends Qs(En){constructor({isHexOnly:e=!0,...r}={}){super(r),this.isHexOnly=e}};Jw.NAME="PrimitiveValueBlock";var L9,C0=class extends pn{constructor(e={}){super(e,Jw),this.idBlock.isConstructed=!1}};L9=C0;je.Primitive=L9;C0.NAME="PRIMITIVE";var H9=100,U9=1e4,$9=16*1024*1024,Dge="Maximum ASN.1 nesting depth exceeded",Bge="Maximum ASN.1 node count exceeded",Nge="Maximum ASN.1 content length exceeded";function oy(t={}){var e,r,n;return{depth:0,maxDepth:(e=t.maxDepth)!==null&&e!==void 0?e:H9,nodesCount:0,maxNodes:(r=t.maxNodes)!==null&&r!==void 0?r:U9,maxContentLength:(n=t.maxContentLength)!==null&&n!==void 0?n:$9}}function Oge(t){let e=new pn({},En);return e.error=t,{offset:-1,result:e}}function Mge(t){if(t.nodesCount+=1,t.nodesCount>t.maxNodes)return Bge}function Lge(t,e){if(t>e.maxContentLength)return Nge}function x_(t,e,r,n){let i=n.depth+1;if(i>n.maxDepth)return Oge(Dge);n.depth=i;try{return uI(t,e,r,n)}finally{n.depth-=1}}function Hge(t,e){if(t instanceof e)return t;let r=new e;return r.idBlock=t.idBlock,r.lenBlock=t.lenBlock,r.warnings=t.warnings,r.valueBeforeDecodeView=t.valueBeforeDecodeView,r}function uI(t,e=0,r=t.length,n=oy()){let i=e,o=new pn({},En),s=new rc;if(!ic(s,t,e,r))return o.error=s.error,{offset:-1,result:o};if(!t.subarray(e,e+r).length)return o.error="Zero buffer length",{offset:-1,result:o};let c=Mge(n);if(c)return o.error=c,{offset:-1,result:o};let u=o.idBlock.fromBER(t,e,r);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),u===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=u,r-=o.idBlock.blockLength,u=o.lenBlock.fromBER(t,e,r),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),u===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};e=u,r-=o.lenBlock.blockLength;let d=o.lenBlock.isIndefiniteForm?r:o.lenBlock.length,l=Lge(d,n);if(l)return o.error=l,{offset:-1,result:o};if(!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let f=pn;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};f=je.EndOfContent;break;case 1:f=je.Boolean;break;case 2:f=je.Integer;break;case 3:f=je.BitString;break;case 4:f=je.OctetString;break;case 5:f=je.Null;break;case 6:f=je.ObjectIdentifier;break;case 10:f=je.Enumerated;break;case 12:f=je.Utf8String;break;case 13:f=je.RelativeObjectIdentifier;break;case 14:f=je.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:f=je.Sequence;break;case 17:f=je.Set;break;case 18:f=je.NumericString;break;case 19:f=je.PrintableString;break;case 20:f=je.TeletexString;break;case 21:f=je.VideotexString;break;case 22:f=je.IA5String;break;case 23:f=je.UTCTime;break;case 24:f=je.GeneralizedTime;break;case 25:f=je.GraphicString;break;case 26:f=je.VisibleString;break;case 27:f=je.GeneralString;break;case 28:f=je.UniversalString;break;case 29:f=je.CharacterString;break;case 30:f=je.BmpString;break;case 31:f=je.DATE;break;case 32:f=je.TimeOfDay;break;case 33:f=je.DateTime;break;case 34:f=je.Duration;break;default:{let p=o.idBlock.isConstructed?new je.Constructed:new je.Primitive;p.idBlock=o.idBlock,p.lenBlock=o.lenBlock,p.warnings=o.warnings,o=p}}break;default:f=o.idBlock.isConstructed?je.Constructed:je.Primitive}return o=Hge(o,f),u=o.fromBER(t,e,d,n),o.valueBeforeDecodeView=t.subarray(i,i+o.blockLength),{offset:u,result:o}}function Uge(t,e={}){if(!t.byteLength){let r=new pn({},En);return r.error="Input buffer has zero length",{offset:-1,result:r}}return uI(Ft.BufferSourceConverter.toUint8Array(t).slice(),0,t.byteLength,oy(e))}function $ge(t,e){return t?1:e}var Js=class extends En{constructor({value:e=[],isIndefiniteForm:r=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=r}fromBER(e,r,n,i){let o=Ft.BufferSourceConverter.toUint8Array(e),s=i??oy();if(!ic(this,o,r,n))return-1;if(this.valueBeforeDecodeView=o.subarray(r,r+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),r;let a=r;for(;$ge(this.isIndefiniteForm,n)>0;){let c=x_(o,a,n,s);if(c.offset===-1)return this.error=c.result.error,this.warnings.concat(c.result.warnings),-1;if(a=c.offset,this.blockLength+=c.result.blockLength,n-=c.result.blockLength,this.value.push(c.result),this.isIndefiniteForm&&c.result.constructor.NAME===R0)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===R0?this.value.pop():this.warnings.push("No EndOfContent block encoded")),a}toBER(e,r){let n=r||new Up;for(let i=0;i<this.value.length;i++)this.value[i].toBER(e,n);return r?Ys:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let r of this.value)e.value.push(r.toJSON());return e}};Js.NAME="ConstructedValueBlock";var F9,nc=class extends pn{constructor(e={}){super(e,Js),this.idBlock.isConstructed=!0}fromBER(e,r,n,i){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,i);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
14
+ `).map(i=>` ${i}`).join(`
15
+ `));let r=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${r} :
16
+ ${e.join(`
17
+ `)}`:`${r} :`}};F9=nc;je.Constructed=F9;nc.NAME="CONSTRUCTED";var Xw=class extends En{fromBER(e,r,n){return r}toBER(e){return Ys}};Xw.override="EndOfContentValueBlock";var j9,P0=class extends pn{constructor(e={}){super(e,Xw),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};j9=P0;je.EndOfContent=j9;P0.NAME=R0;var q9,_0=class extends pn{constructor(e={}){super(e,En),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,r,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,r+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):r+n}toBER(e,r){let n=new ArrayBuffer(2);if(!e){let i=new Uint8Array(n);i[0]=5,i[1]=0}return r&&r.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};q9=_0;je.Null=q9;_0.NAME="NULL";var Yw=class extends Qs(En){get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...r}={}){super(r),r.valueHex?this.valueHexView=Ft.BufferSourceConverter.toUint8Array(r.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,r,n){let i=Ft.BufferSourceConverter.toUint8Array(e);return ic(this,i,r,n)?(this.valueHexView=i.subarray(r,r+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,cr.utilDecodeTC.call(this),this.blockLength=n,r+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Yw.NAME="BooleanValueBlock";var W9,T0=class extends pn{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,Yw),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};W9=T0;je.Boolean=W9;T0.NAME="BOOLEAN";var Qw=class extends Qs(Js){constructor({isConstructed:e=!1,...r}={}){super(r),this.isConstructed=e}fromBER(e,r,n,i){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=Js.prototype.fromBER.call(this,e,r,n,i),o===-1)return o;for(let s=0;s<this.value.length;s++){let a=this.value[s].constructor.NAME;if(a===R0){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==N9)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,r,n),this.blockLength=n;return o}toBER(e,r){return this.isConstructed?Js.prototype.toBER.call(this,e,r):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Qw.NAME="OctetStringValueBlock";var S_,D0=class extends pn{constructor({idBlock:e={},lenBlock:r={},...n}={}){var i,o;(i=n.isConstructed)!==null&&i!==void 0||(n.isConstructed=!!(!((o=n.value)===null||o===void 0)&&o.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...r,isIndefiniteForm:!!n.isIndefiniteForm},...n},Qw),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,r,n,i){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),r;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(r,r+n);try{if(s.byteLength){let a=i??oy(),c=x_(s,0,s.byteLength,a);c.offset!==-1&&c.offset===n&&(this.valueBlock.value=[c.result])}}catch{}}return super.fromBER(e,r,n,i)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return nc.prototype.onAsciiEncoding.call(this);let e=this.constructor.NAME,r=Ft.Convert.ToHex(this.valueBlock.valueHexView);return`${e} : ${r}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let r of this.valueBlock.value)r instanceof S_&&e.push(r.valueBlock.valueHexView);return Ft.BufferSourceConverter.concat(e)}};S_=D0;je.OctetString=S_;D0.NAME=N9;var Zw=class extends Qs(Js){constructor({unusedBits:e=0,isConstructed:r=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=r,this.blockLength=this.valueHexView.byteLength}fromBER(e,r,n,i){if(!n)return r;let o=-1;if(this.isConstructed){if(o=Js.prototype.fromBER.call(this,e,r,n,i),o===-1)return o;for(let c of this.value){let u=c.constructor.NAME;if(u===R0){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(u!==O9)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let d=c.valueBlock;if(this.unusedBits>0&&d.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=d.unusedBits}return o}let s=Ft.BufferSourceConverter.toUint8Array(e);if(!ic(this,s,r,n))return-1;let a=s.subarray(r,r+n);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let c=a.subarray(1);try{if(c.byteLength){let u=i??oy(),d=x_(c,0,c.byteLength,u);d.offset!==-1&&d.offset===n-1&&(this.value=[d.result])}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,r+n}toBER(e,r){if(this.isConstructed)return Js.prototype.toBER.call(this,e,r);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){let i=new Uint8Array(1);return i[0]=0,i.buffer}let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Zw.NAME="BitStringValueBlock";var V9,B0=class extends pn{constructor({idBlock:e={},lenBlock:r={},...n}={}){var i,o;(i=n.isConstructed)!==null&&i!==void 0||(n.isConstructed=!!(!((o=n.value)===null||o===void 0)&&o.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...r,isIndefiniteForm:!!n.isIndefiniteForm},...n},Zw),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,r,n,i){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,r,n,i)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return nc.prototype.onAsciiEncoding.call(this);{let e=[],r=this.valueBlock.valueHexView;for(let s of r)e.push(s.toString(2).padStart(8,"0"));let n=e.join(""),i=this.constructor.NAME,o=n.substring(0,n.length-this.valueBlock.unusedBits);return`${i} : ${o}`}}};V9=B0;je.BitString=V9;B0.NAME=O9;var G9;function Fge(t,e){let r=new Uint8Array([0]),n=new Uint8Array(t),i=new Uint8Array(e),o=n.slice(0),s=o.length-1,a=i.slice(0),c=a.length-1,u=0,d=c<s?s:c,l=0;for(let f=d;f>=0;f--,l++)!0===l<a.length?u=o[s-l]+a[c-l]+r[0]:u=o[s-l]+r[0],r[0]=u/10,!0===l>=o.length?o=cr.utilConcatView(new Uint8Array([u%10]),o):o[s-l]=u%10;return r[0]>0&&(o=cr.utilConcatView(r,o)),o}function D9(t){if(t>=E0.length)for(let e=E0.length;e<=t;e++){let r=new Uint8Array([0]),n=E0[e-1].slice(0);for(let i=n.length-1;i>=0;i--){let o=new Uint8Array([(n[i]<<1)+r[0]]);r[0]=o[0]/10,n[i]=o[0]%10}r[0]>0&&(n=cr.utilConcatView(r,n)),E0.push(n)}return E0[t]}function jge(t,e){let r=0,n=new Uint8Array(t),i=new Uint8Array(e),o=n.slice(0),s=o.length-1,a=i.slice(0),c=a.length-1,u,d=0;for(let l=c;l>=0;l--,d++)u=o[s-d]-a[c-d]-r,!0===u<0?(r=1,o[s-d]=u+10):(r=0,o[s-d]=u);if(r>0)for(let l=s-c+1;l>=0;l--,d++)if(u=o[s-d]-r,u<0)r=1,o[s-d]=u+10;else{r=0,o[s-d]=u;break}return o.slice()}var N0=class extends Qs(En){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=cr.utilDecodeTC.call(this)))}constructor({value:e,...r}={}){super(r),this._valueDec=0,r.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(cr.utilEncodeTC(e))}get valueDec(){return this._valueDec}fromDER(e,r,n,i=0){let o=this.fromBER(e,r,n);if(o===-1)return o;let s=this.valueHexView;return s[0]===0&&(s[1]&128)!==0?this.valueHexView=s.subarray(1):i!==0&&s.length<i&&(i-s.length>1&&(i=s.length+1),this.valueHexView=s.subarray(i-s.length)),o}toDER(e=!1){let r=this.valueHexView;switch(!0){case(r[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(r,1),this.valueHexView=n}break;case(r[0]===0&&(r[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,r,n){let i=super.fromBER(e,r,n);return i===-1||this.setValueHex(),i}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,r=new Uint8Array(this.valueHexView.length*8/3),n=0,i,o=this.valueHexView,s="",a=!1;for(let c=o.byteLength-1;c>=0;c--){i=o[c];for(let u=0;u<8;u++)(i&1)===1&&(n===e?(r=jge(D9(n),r),s="-"):r=Fge(r,D9(n))),n++,i>>=1}for(let c=0;c<r.length;c++)r[c]&&(a=!0),a&&(s+=_9.charAt(r[c]));return a===!1&&(s+=_9.charAt(0)),s}};G9=N0;N0.NAME="IntegerValueBlock";Object.defineProperty(G9.prototype,"valueHex",{set:function(t){this.valueHexView=new Uint8Array(t),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var k0,$p=class extends pn{constructor(e={}){super(e,N0),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Gw(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Gw();let r=BigInt(e),n=new Up,i=r.toString(16).replace(/^-/,""),o=new Uint8Array(Ft.Convert.FromHex(i));if(r<0){let a=new Uint8Array(o.length+(o[0]&128?1:0));a[0]|=128;let u=BigInt(`0x${Ft.Convert.ToHex(a)}`)+r,d=Ft.BufferSourceConverter.toUint8Array(Ft.Convert.FromHex(u.toString(16)));d[0]|=128,n.write(d)}else o[0]&128&&n.write(new Uint8Array([0])),n.write(o);return new k0({valueHex:n.final()})}convertToDER(){let e=new k0({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new k0({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};k0=$p;je.Integer=k0;$p.NAME="INTEGER";var z9,O0=class extends $p{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};z9=O0;je.Enumerated=z9;O0.NAME="ENUMERATED";var M0=class extends Qs(En){constructor({valueDec:e=-1,isFirstSid:r=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=r}fromBER(e,r,n){if(!n)return r;let i=Ft.BufferSourceConverter.toUint8Array(e);if(!ic(this,i,r,n))return-1;let o=i.subarray(r,r+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=o[a]&127,this.blockLength++,(o[a]&128)!==0);a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,(o[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=cr.utilFromBase(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),r+this.blockLength)}set valueBigInt(e){Gw();let r=BigInt(e).toString(2);for(;r.length%7;)r="0"+r;let n=new Uint8Array(r.length/7);for(let i=0;i<n.length;i++)n[i]=parseInt(r.slice(i*7,i*7+7),2)+(i+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let i=this.valueHexView,o=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)o[s]=i[s]|128;return o[this.blockLength-1]=i[this.blockLength-1],o.buffer}let r=cr.utilToBase(this.valueDec,7);if(r.byteLength===0)return this.error="Error during encoding SID value",Ys;let n=new Uint8Array(r.byteLength);if(!e){let i=new Uint8Array(r),o=r.byteLength-1;for(let s=0;s<o;s++)n[s]=i[s]|128;n[o]=i[o]}return n}toString(){let e="";if(this.isHexOnly)e=Ft.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let r=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",r-=40):(e="2.",r-=80),e+=r.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};M0.NAME="sidBlock";var eI=class extends En{constructor({value:e=_i,...r}={}){super(r),this.value=[],e&&this.fromString(e)}fromBER(e,r,n){let i=r;for(;n>0;){let o=new M0;if(i=o.fromBER(e,i,n),i===-1)return this.blockLength=0,this.error=o.error,i;this.value.length===0&&(o.isFirstSid=!0),this.blockLength+=o.blockLength,n-=o.blockLength,this.value.push(o)}return i}toBER(e){let r=[];for(let n=0;n<this.value.length;n++){let i=this.value[n].toBER(e);if(i.byteLength===0)return this.error=this.value[n].error,Ys;r.push(i)}return v_(r)}fromString(e){this.value=[];let r=0,n=0,i="",o=!1;do if(n=e.indexOf(".",r),n===-1?i=e.substring(r):i=e.substring(r,n),r=n+1,o){let s=this.value[0],a=0;switch(s.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(i,10);if(isNaN(c))return;s.valueDec=c+a,o=!1}else{let s=new M0;if(i>Number.MAX_SAFE_INTEGER){Gw();let a=BigInt(i);s.valueBigInt=a}else if(s.valueDec=parseInt(i,10),isNaN(s.valueDec))return;this.value.length||(s.isFirstSid=!0,o=!0),this.value.push(s)}while(n!==-1)}toString(){let e="",r=!1;for(let n=0;n<this.value.length;n++){r=this.value[n].isHexOnly;let i=this.value[n].toString();n!==0&&(e=`${e}.`),r?(i=`{${i}}`,this.value[n].isFirstSid?e=`2.{${i} - 80}`:e+=i):e+=i}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}};eI.NAME="ObjectIdentifierValueBlock";var K9,L0=class extends pn{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,eI),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};K9=L0;je.ObjectIdentifier=K9;L0.NAME="OBJECT IDENTIFIER";var H0=class extends Qs(rc){constructor({valueDec:e=0,...r}={}){super(r),this.valueDec=e}fromBER(e,r,n){if(n===0)return r;let i=Ft.BufferSourceConverter.toUint8Array(e);if(!ic(this,i,r,n))return-1;let o=i.subarray(r,r+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=o[a]&127,this.blockLength++,(o[a]&128)!==0);a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,(o[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=cr.utilFromBase(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),r+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let i=this.valueHexView,o=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)o[s]=i[s]|128;return o[this.blockLength-1]=i[this.blockLength-1],o.buffer}let r=cr.utilToBase(this.valueDec,7);if(r.byteLength===0)return this.error="Error during encoding SID value",Ys;let n=new Uint8Array(r.byteLength);if(!e){let i=new Uint8Array(r),o=r.byteLength-1;for(let s=0;s<o;s++)n[s]=i[s]|128;n[o]=i[o]}return n.buffer}toString(){let e="";return this.isHexOnly?e=Ft.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};H0.NAME="relativeSidBlock";var tI=class extends En{constructor({value:e=_i,...r}={}){super(r),this.value=[],e&&this.fromString(e)}fromBER(e,r,n){let i=r;for(;n>0;){let o=new H0;if(i=o.fromBER(e,i,n),i===-1)return this.blockLength=0,this.error=o.error,i;this.blockLength+=o.blockLength,n-=o.blockLength,this.value.push(o)}return i}toBER(e,r){let n=[];for(let i=0;i<this.value.length;i++){let o=this.value[i].toBER(e);if(o.byteLength===0)return this.error=this.value[i].error,Ys;n.push(o)}return v_(n)}fromString(e){this.value=[];let r=0,n=0,i="";do{n=e.indexOf(".",r),n===-1?i=e.substring(r):i=e.substring(r,n),r=n+1;let o=new H0;if(o.valueDec=parseInt(i,10),isNaN(o.valueDec))return!0;this.value.push(o)}while(n!==-1);return!0}toString(){let e="",r=!1;for(let n=0;n<this.value.length;n++){r=this.value[n].isHexOnly;let i=this.value[n].toString();n!==0&&(e=`${e}.`),r&&(i=`{${i}}`),e+=i}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}};tI.NAME="RelativeObjectIdentifierValueBlock";var J9,U0=class extends pn{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,tI),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};J9=U0;je.RelativeObjectIdentifier=J9;U0.NAME="RelativeObjectIdentifier";var X9,$0=class extends nc{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};X9=$0;je.Sequence=X9;$0.NAME="SEQUENCE";var Y9,F0=class extends nc{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Y9=F0;je.Set=Y9;F0.NAME="SET";var rI=class extends Qs(En){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=_i}toJSON(){return{...super.toJSON(),value:this.value}}};rI.NAME="StringValueBlock";var nI=class extends rI{};nI.NAME="SimpleStringValueBlock";var di=class extends A0{constructor({...e}={}){super(e,nI)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,Ft.BufferSourceConverter.toUint8Array(e))}fromString(e){let r=e.length,n=this.valueBlock.valueHexView=new Uint8Array(r);for(let i=0;i<r;i++)n[i]=e.charCodeAt(i);this.valueBlock.value=e}};di.NAME="SIMPLE STRING";var iI=class extends di{fromBuffer(e){this.valueBlock.valueHexView=Ft.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=Ft.Convert.ToUtf8String(e)}catch(r){this.warnings.push(`Error during "decodeURIComponent": ${r}, using raw string`),this.valueBlock.value=Ft.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(Ft.Convert.FromUtf8String(e)),this.valueBlock.value=e}};iI.NAME="Utf8StringValueBlock";var Q9,Xs=class extends iI{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Q9=Xs;je.Utf8String=Q9;Xs.NAME="UTF8String";var oI=class extends di{fromBuffer(e){this.valueBlock.value=Ft.Convert.ToUtf16String(e),this.valueBlock.valueHexView=Ft.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Ft.Convert.FromUtf16String(e))}};oI.NAME="BmpStringValueBlock";var Z9,j0=class extends oI{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Z9=j0;je.BmpString=Z9;j0.NAME="BMPString";var sI=class extends di{fromBuffer(e){let r=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(r);for(let i=0;i<n.length;i+=4)n[i]=n[i+3],n[i+1]=n[i+2],n[i+2]=0,n[i+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(r))}fromString(e){let r=e.length,n=this.valueBlock.valueHexView=new Uint8Array(r*4);for(let i=0;i<r;i++){let o=cr.utilToBase(e.charCodeAt(i),8),s=new Uint8Array(o);if(s.length>4)continue;let a=4-s.length;for(let c=s.length-1;c>=0;c--)n[i*4+c+a]=s[c]}this.valueBlock.value=e}};sI.NAME="UniversalStringValueBlock";var e$,q0=class extends sI{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};e$=q0;je.UniversalString=e$;q0.NAME="UniversalString";var t$,W0=class extends di{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};t$=W0;je.NumericString=t$;W0.NAME="NumericString";var r$,V0=class extends di{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};r$=V0;je.PrintableString=r$;V0.NAME="PrintableString";var n$,G0=class extends di{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};n$=G0;je.TeletexString=n$;G0.NAME="TeletexString";var i$,z0=class extends di{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};i$=z0;je.VideotexString=i$;z0.NAME="VideotexString";var o$,K0=class extends di{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};o$=K0;je.IA5String=o$;K0.NAME="IA5String";var s$,J0=class extends di{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};s$=J0;je.GraphicString=s$;J0.NAME="GraphicString";var a$,Fp=class extends di{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};a$=Fp;je.VisibleString=a$;Fp.NAME="VisibleString";var c$,X0=class extends di{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};c$=X0;je.GeneralString=c$;X0.NAME="GeneralString";var u$,Y0=class extends di{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};u$=Y0;je.CharacterString=u$;Y0.NAME="CharacterString";var d$,jp=class extends Fp{constructor({value:e,valueDate:r,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let i=0;i<e.length;i++)this.valueBlock.valueHexView[i]=e.charCodeAt(i)}r&&(this.fromDate(r),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,Ft.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),r=new ArrayBuffer(e.length),n=new Uint8Array(r);for(let i=0;i<e.length;i++)n[i]=e.charCodeAt(i);return r}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let i=parseInt(n[1],10);i>=50?this.year=1900+i:this.year=2e3+i,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let r=new Array(7);return r[0]=cr.padNumber(this.year<2e3?this.year-1900:this.year-2e3,2),r[1]=cr.padNumber(this.month,2),r[2]=cr.padNumber(this.day,2),r[3]=cr.padNumber(this.hour,2),r[4]=cr.padNumber(this.minute,2),r[5]=cr.padNumber(this.second,2),r[6]="Z",r.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};d$=jp;je.UTCTime=d$;jp.NAME="UTCTime";var l$,Q0=class extends jp{constructor(e={}){var r;super(e),(r=this.millisecond)!==null&&r!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){let e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let r=!1,n="",i="",o=0,s,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),r=!0;else{let l=new Number(e[e.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(r){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let l=1,f=n.indexOf("+"),p="";if(f===-1&&(f=n.indexOf("-"),l=-1),f!==-1){if(p=n.substring(f+1),n=n.substring(0,f),p.length!==2&&p.length!==4)throw new Error("Wrong input string for conversion");let g=parseInt(p.substring(0,2),10);if(isNaN(g.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*g,p.length===4){if(g=parseInt(p.substring(2,4),10),isNaN(g.valueOf()))throw new Error("Wrong input string for conversion");c=l*g}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){let l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");o=l.valueOf(),i=n.substring(0,u)}else i=n;switch(!0){case i.length===8:if(s=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case i.length===10:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*o;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case i.length===12:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*o;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case i.length===14:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=1e3*o;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}let d=s.exec(i);if(d===null)throw new Error("Wrong input string for conversion");for(let l=1;l<d.length;l++)switch(l){case 1:this.year=parseInt(d[l],10);break;case 2:this.month=parseInt(d[l],10);break;case 3:this.day=parseInt(d[l],10);break;case 4:this.hour=parseInt(d[l],10)+a;break;case 5:this.minute=parseInt(d[l],10)+c;break;case 6:this.second=parseInt(d[l],10);break;default:throw new Error("Wrong input string for conversion")}if(r===!1){let l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let r=[];return r.push(cr.padNumber(this.year,4)),r.push(cr.padNumber(this.month,2)),r.push(cr.padNumber(this.day,2)),r.push(cr.padNumber(this.hour,2)),r.push(cr.padNumber(this.minute,2)),r.push(cr.padNumber(this.second,2)),this.millisecond!==0&&(r.push("."),r.push(cr.padNumber(this.millisecond,3))),r.push("Z"),r.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};l$=Q0;je.GeneralizedTime=l$;Q0.NAME="GeneralizedTime";var f$,Z0=class extends Xs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};f$=Z0;je.DATE=f$;Z0.NAME="DATE";var p$,ey=class extends Xs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};p$=ey;je.TimeOfDay=p$;ey.NAME="TimeOfDay";var m$,ty=class extends Xs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};m$=ty;je.DateTime=m$;ty.NAME="DateTime";var h$,ry=class extends Xs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};h$=ry;je.Duration=h$;ry.NAME="Duration";var g$,ny=class extends Xs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};g$=ny;je.TIME=g$;ny.NAME="TIME";var Cl=class{constructor({name:e=_i,optional:r=!1}={}){this.name=e,this.optional=r}},aI=class extends Cl{constructor({value:e=[],...r}={}){super(r),this.value=e}},iy=class extends Cl{constructor({value:e=new Cl,local:r=!1,...n}={}){super(n),this.value=e,this.local=r}},y_=class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=Ft.BufferSourceConverter.toUint8Array(e)}constructor({data:e=cI}={}){this.dataView=Ft.BufferSourceConverter.toUint8Array(e)}fromBER(e,r,n){let i=r+n;return this.dataView=Ft.BufferSourceConverter.toUint8Array(e).subarray(r,i),i}toBER(e){return this.dataView.slice().buffer}};function Hp(t,e,r){if(r instanceof aI){for(let o of r.value)if(Hp(t,e,o).verified)return{verified:!0,result:t};{let o={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(g_)&&(o.name=r.name),o}}if(r instanceof Cl)return r.hasOwnProperty(g_)&&(t[r.name]=e),{verified:!0,result:t};if(!(t instanceof Object))return{verified:!1,result:{error:"Wrong root object"}};if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(!(r instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(kge in r))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(Pge in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(_ge in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};let n=r.idBlock.toBER(!1);if(n.byteLength===0)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(r.idBlock.fromBER(n,0,n.byteLength)===-1)return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(r.idBlock.hasOwnProperty(Rge)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagClass!==e.idBlock.tagClass)return{verified:!1,result:t};if(r.idBlock.hasOwnProperty(Age)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagNumber!==e.idBlock.tagNumber)return{verified:!1,result:t};if(r.idBlock.hasOwnProperty(Cge)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==e.idBlock.isConstructed)return{verified:!1,result:t};if(!(Ege in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isHexOnly!==e.idBlock.isHexOnly)return{verified:!1,result:t};if(r.idBlock.isHexOnly){if(!(T9 in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};let o=r.idBlock.valueHexView,s=e.idBlock.valueHexView;if(o.length!==s.length)return{verified:!1,result:t};for(let a=0;a<o.length;a++)if(o[a]!==s[1])return{verified:!1,result:t}}if(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,_i),r.name&&(t[r.name]=e)),r instanceof je.Constructed){let o=0,s={verified:!1,result:{error:"Unknown error"}},a=r.valueBlock.value.length;if(a>0&&r.valueBlock.value[0]instanceof iy&&(a=e.valueBlock.value.length),a===0)return{verified:!0,result:t};if(e.valueBlock.value.length===0&&r.valueBlock.value.length!==0){let c=!0;for(let u=0;u<r.valueBlock.value.length;u++)c=c&&(r.valueBlock.value[u].optional||!1);return c?{verified:!0,result:t}:(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,_i),r.name&&delete t[r.name]),t.error="Inconsistent object length",{verified:!1,result:t})}for(let c=0;c<a;c++)if(c-o>=e.valueBlock.value.length){if(r.valueBlock.value[c].optional===!1){let u={verified:!1,result:t};return t.error="Inconsistent length between ASN.1 data and schema",r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,_i),r.name&&(delete t[r.name],u.name=r.name)),u}}else if(r.valueBlock.value[0]instanceof iy){if(s=Hp(t,e.valueBlock.value[c],r.valueBlock.value[0].value),s.verified===!1)if(r.valueBlock.value[0].optional)o++;else return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,_i),r.name&&delete t[r.name]),s;if(g_ in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let u={};Tge in r.valueBlock.value[0]&&r.valueBlock.value[0].local?u=e:u=t,typeof u[r.valueBlock.value[0].name]>"u"&&(u[r.valueBlock.value[0].name]=[]),u[r.valueBlock.value[0].name].push(e.valueBlock.value[c])}}else if(s=Hp(t,e.valueBlock.value[c-o],r.valueBlock.value[c]),s.verified===!1)if(r.valueBlock.value[c].optional)o++;else return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,_i),r.name&&delete t[r.name]),s;if(s.verified===!1){let c={verified:!1,result:t};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,_i),r.name&&(delete t[r.name],c.name=r.name)),c}return{verified:!0,result:t}}if(r.primitiveSchema&&T9 in e.valueBlock){let o=uI(e.valueBlock.valueHexView);if(o.offset===-1){let s={verified:!1,result:o.result};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,_i),r.name&&(delete t[r.name],s.name=r.name)),s}return Hp(t,o.result,r.primitiveSchema)}return{verified:!0,result:t}}function qge(t,e){if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};let r=uI(Ft.BufferSourceConverter.toUint8Array(t));return r.offset===-1?{verified:!1,result:r.result}:Hp(r.result,r.result,e)}ut.Any=Cl;ut.BaseBlock=pn;ut.BaseStringBlock=A0;ut.BitString=B0;ut.BmpString=j0;ut.Boolean=T0;ut.CharacterString=Y0;ut.Choice=aI;ut.Constructed=nc;ut.DATE=Z0;ut.DEFAULT_MAX_CONTENT_LENGTH=$9;ut.DEFAULT_MAX_DEPTH=H9;ut.DEFAULT_MAX_NODES=U9;ut.DateTime=ty;ut.Duration=ry;ut.EndOfContent=P0;ut.Enumerated=O0;ut.GeneralString=X0;ut.GeneralizedTime=Q0;ut.GraphicString=J0;ut.HexBlock=Qs;ut.IA5String=K0;ut.Integer=$p;ut.Null=_0;ut.NumericString=W0;ut.ObjectIdentifier=L0;ut.OctetString=D0;ut.Primitive=C0;ut.PrintableString=V0;ut.RawData=y_;ut.RelativeObjectIdentifier=U0;ut.Repeated=iy;ut.Sequence=$0;ut.Set=F0;ut.TIME=ny;ut.TeletexString=G0;ut.TimeOfDay=ey;ut.UTCTime=jp;ut.UniversalString=q0;ut.Utf8String=Xs;ut.ValueBlock=En;ut.VideotexString=z0;ut.ViewWriter=Up;ut.VisibleString=Fp;ut.compareSchema=Hp;ut.fromBER=Uge;ut.verifySchema=qge});function y$(t){return Object.prototype.toString.call(t)}function Gge(t){if(ArrayBuffer.isView(t))return!0;if(!t||typeof t!="object")return!1;let e=t;return typeof e.byteOffset=="number"&&typeof e.byteLength=="number"&&dI(e.buffer)}function b_(t){return y$(t)===Wge}function v$(t){return typeof SharedArrayBuffer<"u"&&y$(t)===Vge}function dI(t){return b_(t)||v$(t)}function x$(t){return Gge(t)}function oc(t){return dI(t)||x$(t)}function w_(t){if(!oc(t))throw new TypeError("Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView")}function ko(t){return w_(t),dI(t)?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function mn(t){if(w_(t),b_(t))return t;let e=new ArrayBuffer(t.byteLength);return new Uint8Array(e).set(ko(t)),e}var Wge,Vge,sy=N(()=>{Wge="[object ArrayBuffer]",Vge="[object SharedArrayBuffer]"});var S$=N(()=>{sy()});function I_(t,e,r={}){let n=ko(t),i=ko(e);if(!r.constantTime&&n.byteLength!==i.byteLength)return!1;let o=Math.max(n.byteLength,i.byteLength),s=n.byteLength^i.byteLength;for(let a=0;a<o;a++)s|=(n[a]??0)^(i[a]??0);return s===0}var b$=N(()=>{sy()});var w$=N(()=>{sy()});var ro=N(()=>{sy();S$();b$();w$()});var L,k,Pl=N(()=>{(function(t){t[t.Sequence=0]="Sequence",t[t.Set=1]="Set",t[t.Choice=2]="Choice"})(L||(L={}));(function(t){t[t.Any=1]="Any",t[t.Boolean=2]="Boolean",t[t.OctetString=3]="OctetString",t[t.BitString=4]="BitString",t[t.Integer=5]="Integer",t[t.Enumerated=6]="Enumerated",t[t.ObjectIdentifier=7]="ObjectIdentifier",t[t.Utf8String=8]="Utf8String",t[t.BmpString=9]="BmpString",t[t.UniversalString=10]="UniversalString",t[t.NumericString=11]="NumericString",t[t.PrintableString=12]="PrintableString",t[t.TeletexString=13]="TeletexString",t[t.VideotexString=14]="VideotexString",t[t.IA5String=15]="IA5String",t[t.GraphicString=16]="GraphicString",t[t.VisibleString=17]="VisibleString",t[t.GeneralString=18]="GeneralString",t[t.CharacterString=19]="CharacterString",t[t.UTCTime=20]="UTCTime",t[t.GeneralizedTime=21]="GeneralizedTime",t[t.DATE=22]="DATE",t[t.TimeOfDay=23]="TimeOfDay",t[t.DateTime=24]="DateTime",t[t.Duration=25]="Duration",t[t.TIME=26]="TIME",t[t.Null=27]="Null"})(k||(k={}))});var lI,rs,I$=N(()=>{lI=tt(Fu(),1);ro();rs=class{unusedBits=0;value=new ArrayBuffer(0);constructor(e,r=0){if(e)if(typeof e=="number")this.fromNumber(e);else if(oc(e))this.unusedBits=r,this.value=mn(e);else throw TypeError("Unsupported type of 'params' argument for BitString")}fromASN(e){if(!(e instanceof lI.BitString))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=mn(e.valueBlock.valueHex),this}toASN(){return new lI.BitString({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new lI.BitString({name:e})}toNumber(){let e="",r=new Uint8Array(this.value);for(let n of r)e+=n.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){let r=e.toString(2),n=r.length+7>>3;this.unusedBits=(n<<3)-r.length;let i=new Uint8Array(n);r=r.padStart(n<<3,"0").split("").reverse().join("");let o=0;for(;o<n;)i[o]=parseInt(r.slice(o<<3,(o<<3)+8),2),o++;this.value=i.buffer}}});var fI,rt,E$=N(()=>{fI=tt(Fu(),1);ro();rt=class{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){typeof e=="number"?this.buffer=new ArrayBuffer(e):oc(e)?this.buffer=mn(e):Array.isArray(e)?this.buffer=new Uint8Array(e).buffer:this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof fI.OctetString))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=mn(e.valueBlock.valueHex),this}toASN(){return new fI.OctetString({valueHex:this.buffer})}toSchema(e){return new fI.OctetString({name:e})}}});var E_=N(()=>{I$();E$()});function Ro(t){return{fromASN:e=>e.valueBlock.value,toASN:e=>new t({value:e})}}function sc(t){switch(t){case k.Any:return k$;case k.BitString:return C$;case k.BmpString:return D$;case k.Boolean:return _$;case k.CharacterString:return j$;case k.Enumerated:return A$;case k.GeneralString:return F$;case k.GeneralizedTime:return W$;case k.GraphicString:return U$;case k.IA5String:return H$;case k.Integer:return R$;case k.Null:return V$;case k.NumericString:return N$;case k.ObjectIdentifier:return P$;case k.OctetString:return _l;case k.PrintableString:return O$;case k.TeletexString:return M$;case k.UTCTime:return q$;case k.UniversalString:return B$;case k.Utf8String:return T$;case k.VideotexString:return L$;case k.VisibleString:return $$;default:return null}}var dt,k$,R$,A$,Mt,Jge,C$,P$,_$,_l,k_,T$,D$,B$,N$,O$,M$,L$,H$,U$,$$,F$,j$,q$,W$,V$,ay=N(()=>{dt=tt(Fu(),1);ro();Pl();E_();k$={fromASN:t=>t instanceof dt.Null?null:mn(t.valueBeforeDecodeView),toASN:t=>{if(t===null)return new dt.Null;let e=dt.fromBER(t);if(e.result.error)throw new Error(e.result.error);return e.result}},R$={fromASN:t=>t.valueBlock.valueHexView.byteLength>=4?t.valueBlock.toString():t.valueBlock.valueDec,toASN:t=>new dt.Integer({value:+t})},A$={fromASN:t=>t.valueBlock.valueDec,toASN:t=>new dt.Enumerated({value:t})},Mt={fromASN:t=>mn(t.valueBlock.valueHexView),toASN:t=>new dt.Integer({valueHex:t})},Jge={fromASN:t=>t.toBigInt(),toASN:t=>dt.Integer.fromBigInt(t)},C$={fromASN:t=>mn(t.valueBlock.valueHexView),toASN:t=>new dt.BitString({valueHex:t})},P$={fromASN:t=>t.valueBlock.toString(),toASN:t=>new dt.ObjectIdentifier({value:t})},_$={fromASN:t=>t.valueBlock.value,toASN:t=>new dt.Boolean({value:t})},_l={fromASN:t=>mn(t.valueBlock.valueHexView),toASN:t=>new dt.OctetString({valueHex:t})},k_={fromASN:t=>new rt(t.getValue()),toASN:t=>t.toASN()};T$=Ro(dt.Utf8String),D$=Ro(dt.BmpString),B$=Ro(dt.UniversalString),N$=Ro(dt.NumericString),O$=Ro(dt.PrintableString),M$=Ro(dt.TeletexString),L$=Ro(dt.VideotexString),H$=Ro(dt.IA5String),U$=Ro(dt.GraphicString),$$=Ro(dt.VisibleString),F$=Ro(dt.GeneralString),j$=Ro(dt.CharacterString),q$={fromASN:t=>t.toDate(),toASN:t=>new dt.UTCTime({valueDate:t})},W$={fromASN:t=>t.toDate(),toASN:t=>new dt.GeneralizedTime({valueDate:t})},V$={fromASN:()=>null,toASN:()=>new dt.Null}});function Ao(t){return typeof t=="function"&&t.prototype?t.prototype.toASN&&t.prototype.fromASN?!0:Ao(t.prototype):!!(t&&typeof t=="object"&&"toASN"in t&&"fromASN"in t)}function A_(t){if(t){let e=Object.getPrototypeOf(t);return e?.prototype?.constructor===Array?!0:A_(e)}return!1}function G$(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;let r=new Uint8Array(t),n=new Uint8Array(e);for(let i=0;i<t.byteLength;i++)if(r[i]!==n[i])return!1;return!0}var pI=N(()=>{});var rn,mI,z$=N(()=>{rn=tt(Fu(),1);Pl();pI();mI=class{items=new WeakMap;has(e){return this.items.has(e)}get(e,r=!1){let n=this.items.get(e);if(!n)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(r&&!n.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return n}cache(e){let r=this.get(e);r.schema||(r.schema=this.create(e,!0))}createDefault(e){let r={type:L.Sequence,items:{}},n=this.findParentSchema(e);return n&&(Object.assign(r,n),r.items=Object.assign({},r.items,n.items)),r}create(e,r){let n=this.items.get(e)||this.createDefault(e),i=[];for(let o in n.items){let s=n.items[o],a=r?o:"",c;if(typeof s.type=="number"){let d=k[s.type],l=rn[d];if(!l)throw new Error(`Cannot get ASN1 class by name '${d}'`);c=new l({name:a})}else Ao(s.type)?c=new s.type().toSchema(a):s.optional?this.get(s.type).type===L.Choice?c=new rn.Any({name:a}):(c=this.create(s.type,!1),c.name=a):c=new rn.Any({name:a});let u=!!s.optional||s.defaultValue!==void 0;if(s.repeated){c.name="";let d=s.repeated==="set"?rn.Set:rn.Sequence;c=new d({name:"",value:[new rn.Repeated({name:a,value:c})]})}if(s.context!==null&&s.context!==void 0)if(s.implicit)if(typeof s.type=="number"||Ao(s.type)){let d=s.repeated?rn.Constructed:rn.Primitive;i.push(new d({name:a,optional:u,idBlock:{tagClass:3,tagNumber:s.context}}))}else{this.cache(s.type);let d=!!s.repeated,l=d?c:this.get(s.type,!0).schema;l="valueBlock"in l?l.valueBlock.value:l.value,i.push(new rn.Constructed({name:d?"":a,optional:u,idBlock:{tagClass:3,tagNumber:s.context},value:l}))}else i.push(new rn.Constructed({optional:u,idBlock:{tagClass:3,tagNumber:s.context},value:[c]}));else c.optional=u,i.push(c)}switch(n.type){case L.Sequence:return new rn.Sequence({value:i,name:""});case L.Set:return new rn.Set({value:i,name:""});case L.Choice:return new rn.Choice({value:i,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,r){return this.items.set(e,r),this}findParentSchema(e){let r=Object.getPrototypeOf(e);return r?this.items.get(r)||this.findParentSchema(r):null}}});var nn,hI=N(()=>{z$();nn=new mI});var W,K$,J$,X$,x,Y$=N(()=>{ay();Pl();hI();W=t=>e=>{let r;nn.has(e)?r=nn.get(e):(r=nn.createDefault(e),nn.set(e,r)),Object.assign(r,t)},K$=()=>W({type:L.Choice}),J$=t=>W({type:L.Set,...t}),X$=t=>W({type:L.Sequence,...t}),x=t=>(e,r)=>{let n;nn.has(e.constructor)?n=nn.get(e.constructor):(n=nn.createDefault(e.constructor),nn.set(e.constructor,n));let i=Object.assign({},t);if(typeof i.type=="number"&&!i.converter){let o=sc(t.type);if(!o)throw new Error(`Cannot get default converter for property '${r}' of ${e.constructor.name}`);i.converter=o}i.raw=t.raw,n.items[r]=i}});var ac,Q$=N(()=>{ac=class extends Error{schemas=[]}});var C_=N(()=>{Q$()});var hn,qp,P_=N(()=>{hn=tt(Fu(),1);ro();Pl();ay();C_();pI();hI();qp=class{static parse(e,r,n){let i=hn.fromBER(mn(e),n?.berOptions);if(i.result.error)throw new Error(i.result.error);return this.fromASN(i.result,r,n)}static fromASN(e,r,n){try{if(Ao(r))return new r().fromASN(e);let i=nn.get(r);nn.cache(r);let o=i.schema,s=this.handleChoiceTypes(e,i,r,o,n);if(s?.result)return s.result;s?.targetSchema&&(o=s.targetSchema);let a=this.handleSequenceTypes(e,i,r,o),c=new r;return A_(r)?this.handleArrayTypes(e,i,r,n):(this.processSchemaItems(i,a,c,n),c)}catch(i){throw i instanceof ac&&i.schemas.push(r.name),i}}static handleChoiceTypes(e,r,n,i,o){if(e.constructor===hn.Constructed&&r.type===L.Choice&&e.idBlock.tagClass===3)for(let s in r.items){let a=r.items[s];if(a.context===e.idBlock.tagNumber&&a.implicit&&typeof a.type=="function"&&nn.has(a.type)){let c=nn.get(a.type);if(c&&c.type===L.Sequence){let u=new hn.Sequence;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in u.valueBlock){u.valueBlock.value=e.valueBlock.value;let d=this.fromASN(u,a.type,o),l=new n;return l[s]=d,{result:l}}}}}else if(e.constructor===hn.Constructed&&r.type!==L.Choice){let s=new hn.Constructed({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:r.schema.valueBlock.value});for(let a in r.items)delete e[a];return{targetSchema:s}}return null}static handleSequenceTypes(e,r,n,i){if(r.type===L.Sequence){let o=hn.compareSchema({},e,i);if(!o.verified)throw new ac(`Data does not match to ${n.name} ASN1 schema.${o.result.error?` ${o.result.error}`:""}`);return o}else{let o=hn.compareSchema({},e,i);if(!o.verified)throw new ac(`Data does not match to ${n.name} ASN1 schema.${o.result.error?` ${o.result.error}`:""}`);return o}}static processRepeatedField(e,r,n){let i=e.slice(r);if(i.length===1&&i[0].constructor.name==="Sequence"){let o=i[0];o.valueBlock&&o.valueBlock.value&&Array.isArray(o.valueBlock.value)&&(i=o.valueBlock.value)}if(typeof n.type=="number"){let o=sc(n.type);if(!o)throw new Error(`No converter for ASN.1 type ${n.type}`);return i.filter(s=>s&&s.valueBlock).map(s=>{try{return o.fromASN(s)}catch{return}}).filter(s=>s!==void 0)}else return i.filter(o=>o&&o.valueBlock).map(o=>{try{return this.fromASN(o,n.type)}catch{return}}).filter(o=>o!==void 0)}static processPrimitiveField(e,r){let n=sc(r.type);if(!n)throw new Error(`No converter for ASN.1 type ${r.type}`);return n.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&typeof e.type=="function"&&nn.has(e.type)&&nn.get(e.type).type===L.Choice}static processOptionalChoiceField(e,r){try{return{processed:!0,value:this.fromASN(e,r.type)}}catch(n){if(n instanceof ac&&/Wrong values for Choice type/.test(n.message))return{processed:!1};throw n}}static handleArrayTypes(e,r,n,i){if(!("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");let o=r.itemType;if(typeof o=="number"){let s=sc(o);if(!s)throw new Error(`Cannot get default converter for array item of ${n.name} ASN1 schema`);return n.from(e.valueBlock.value,a=>s.fromASN(a))}else return n.from(e.valueBlock.value,s=>this.fromASN(s,o,i))}static processSchemaItems(e,r,n,i){for(let o in e.items){let s=r.result[o];if(!s)continue;let a=e.items[o],c=a.type,u;typeof c=="number"||Ao(c)?u=this.processPrimitiveSchemaItem(s,a,c,i):u=this.processComplexSchemaItem(s,a,c,i),u&&typeof u=="object"&&"value"in u&&"raw"in u?(n[o]=u.value,n[`${o}Raw`]=u.raw):n[o]=u}}static processPrimitiveSchemaItem(e,r,n,i){let o=r.converter??(Ao(n)?new n:null);if(!o)throw new Error("Converter is empty");return r.repeated?this.processRepeatedPrimitiveItem(e,r,o,i):this.processSinglePrimitiveItem(e,r,n,o,i)}static processRepeatedPrimitiveItem(e,r,n,i){if(r.implicit){let o=r.repeated==="sequence"?hn.Sequence:hn.Set,s=new o;s.valueBlock=e.valueBlock;let a=hn.fromBER(s.toBER(!1),i?.berOptions);if(a.offset===-1)throw new Error(`Cannot parse the child item. ${a.result.error}`);if(!("value"in a.result.valueBlock&&Array.isArray(a.result.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");let c=a.result.valueBlock.value;return Array.from(c,u=>n.fromASN(u))}else return Array.from(e,o=>n.fromASN(o))}static processSinglePrimitiveItem(e,r,n,i,o){let s=e;if(r.implicit){let a;if(Ao(n))a=new n().toSchema("");else{let c=k[n],u=hn[c];if(!u)throw new Error(`Cannot get '${c}' class from asn1js module`);a=new u}a.valueBlock=s.valueBlock,s=hn.fromBER(a.toBER(!1),o?.berOptions).result}return i.fromASN(s)}static processComplexSchemaItem(e,r,n,i){if(r.repeated){if(!Array.isArray(e))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");return Array.from(e,o=>this.fromASN(o,n,i))}else{let o=this.handleImplicitTagging(e,r,n);if(this.isOptionalChoiceField(r))try{return this.fromASN(o,n,i)}catch(s){if(s instanceof ac&&/Wrong values for Choice type/.test(s.message))return;throw s}else{let s=this.fromASN(o,n,i);return r.raw?{value:s,raw:e.valueBeforeDecodeView}:s}}}static handleImplicitTagging(e,r,n){if(r.implicit&&typeof r.context=="number"){let i=nn.get(n);if(i.type===L.Sequence){let o=new hn.Sequence;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in o.valueBlock)return o.valueBlock.value=e.valueBlock.value,o}else if(i.type===L.Set){let o=new hn.Set;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in o.valueBlock)return o.valueBlock.value=e.valueBlock.value,o}}return e}}});var Nn,Wp,__=N(()=>{Nn=tt(Fu(),1);ro();ay();Pl();pI();hI();Wp=class t{static serialize(e){return e instanceof Nn.BaseBlock?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&typeof e=="object"&&Ao(e))return e.toASN();if(!(e&&typeof e=="object"))throw new TypeError("Parameter 1 should be type of Object.");let r=e.constructor,n=nn.get(r);nn.cache(r);let i=[];if(n.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if(typeof n.itemType=="number"){let s=sc(n.itemType);if(!s)throw new Error(`Cannot get default converter for array item of ${r.name} ASN1 schema`);i=e.map(a=>s.toASN(a))}else i=e.map(s=>this.toAsnItem({type:n.itemType},"[]",r,s))}else for(let s in n.items){let a=n.items[s],c=e[s];if(c===void 0||a.defaultValue===c||typeof a.defaultValue=="object"&&typeof c=="object"&&G$(this.serialize(a.defaultValue),this.serialize(c)))continue;let u=t.toAsnItem(a,s,r,c);if(typeof a.context=="number")if(a.implicit)if(!a.repeated&&(typeof a.type=="number"||Ao(a.type))){let d={};d.valueHex=u instanceof Nn.Null?mn(u.valueBeforeDecodeView):u.valueBlock.toBER(),i.push(new Nn.Primitive({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},...d}))}else i.push(new Nn.Constructed({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:u.valueBlock.value}));else i.push(new Nn.Constructed({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:[u]}));else a.repeated?i=i.concat(u):i.push(u)}let o;switch(n.type){case L.Sequence:o=new Nn.Sequence({value:i});break;case L.Set:o=new Nn.Set({value:i});break;case L.Choice:if(!i[0])throw new Error(`Schema '${r.name}' has wrong data. Choice cannot be empty.`);o=i[0];break}return o}static toAsnItem(e,r,n,i){let o;if(typeof e.type=="number"){let s=e.converter;if(!s)throw new Error(`Property '${r}' doesn't have converter for type ${k[e.type]} in schema '${n.name}'`);if(e.repeated){if(!Array.isArray(i))throw new TypeError("Parameter 'objProp' should be type of Array.");let a=Array.from(i,u=>s.toASN(u)),c=e.repeated==="sequence"?Nn.Sequence:Nn.Set;o=new c({value:a})}else o=s.toASN(i)}else if(e.repeated){if(!Array.isArray(i))throw new TypeError("Parameter 'objProp' should be type of Array.");let s=Array.from(i,c=>this.toASN(c)),a=e.repeated==="sequence"?Nn.Sequence:Nn.Set;o=new a({value:s})}else o=this.toASN(i);return o}}});var Ze,Z$=N(()=>{Ze=class extends Array{constructor(e=[]){if(typeof e=="number")super(e);else{super();for(let r of e)this.push(r)}}}});var e7,Co,t7=N(()=>{e7=tt(Fu(),1);ro();P_();__();Co=class t{static serialize(e){return Wp.serialize(e)}static parse(e,r,n){return qp.parse(e,r,n)}static toString(e,r){let n=oc(e)?mn(e):t.serialize(e),i=e7.fromBER(n,r?.berOptions);if(i.offset===-1)throw new Error(`Cannot decode ASN.1 data. ${i.result.error}`);return i.result.toString()}}});var r7={};wi(r7,{AsnAnyConverter:()=>k$,AsnArray:()=>Ze,AsnBitStringConverter:()=>C$,AsnBmpStringConverter:()=>D$,AsnBooleanConverter:()=>_$,AsnCharacterStringConverter:()=>j$,AsnChoiceType:()=>K$,AsnConstructedOctetStringConverter:()=>k_,AsnConvert:()=>Co,AsnEnumeratedConverter:()=>A$,AsnGeneralStringConverter:()=>F$,AsnGeneralizedTimeConverter:()=>W$,AsnGraphicStringConverter:()=>U$,AsnIA5StringConverter:()=>H$,AsnIntegerArrayBufferConverter:()=>Mt,AsnIntegerBigIntConverter:()=>Jge,AsnIntegerConverter:()=>R$,AsnNullConverter:()=>V$,AsnNumericStringConverter:()=>N$,AsnObjectIdentifierConverter:()=>P$,AsnOctetStringConverter:()=>_l,AsnParser:()=>qp,AsnPrintableStringConverter:()=>O$,AsnProp:()=>x,AsnPropTypes:()=>k,AsnSchemaValidationError:()=>ac,AsnSequenceType:()=>X$,AsnSerializer:()=>Wp,AsnSetType:()=>J$,AsnTeletexStringConverter:()=>M$,AsnType:()=>W,AsnTypeTypes:()=>L,AsnUTCTimeConverter:()=>q$,AsnUniversalStringConverter:()=>B$,AsnUtf8StringConverter:()=>T$,AsnVideotexStringConverter:()=>L$,AsnVisibleStringConverter:()=>$$,BitString:()=>rs,OctetString:()=>rt,defaultConverter:()=>sc});var ae=N(()=>{ay();E_();Y$();Pl();P_();__();C_();Z$();t7()});var T7=ce((_8e,vI)=>{var n7,i7,o7,s7,a7,c7,u7,d7,l7,f7,p7,m7,h7,gI,T_,g7,y7,v7,Vp,x7,S7,b7,w7,I7,E7,k7,R7,A7,yI,C7,P7,_7;(function(t){var e=typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:{};typeof define=="function"&&define.amd?define("tslib",["exports"],function(n){t(r(e,r(n)))}):typeof vI=="object"&&typeof vI.exports=="object"?t(r(e,r(vI.exports))):t(r(e));function r(n,i){return n!==e&&(typeof Object.create=="function"?Object.defineProperty(n,"__esModule",{value:!0}):n.__esModule=!0),function(o,s){return n[o]=i?i(o,s):s}}})(function(t){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,s){o.__proto__=s}||function(o,s){for(var a in s)Object.prototype.hasOwnProperty.call(s,a)&&(o[a]=s[a])};n7=function(o,s){if(typeof s!="function"&&s!==null)throw new TypeError("Class extends value "+String(s)+" is not a constructor or null");e(o,s);function a(){this.constructor=o}o.prototype=s===null?Object.create(s):(a.prototype=s.prototype,new a)},i7=Object.assign||function(o){for(var s,a=1,c=arguments.length;a<c;a++){s=arguments[a];for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&(o[u]=s[u])}return o},o7=function(o,s){var a={};for(var c in o)Object.prototype.hasOwnProperty.call(o,c)&&s.indexOf(c)<0&&(a[c]=o[c]);if(o!=null&&typeof Object.getOwnPropertySymbols=="function")for(var u=0,c=Object.getOwnPropertySymbols(o);u<c.length;u++)s.indexOf(c[u])<0&&Object.prototype.propertyIsEnumerable.call(o,c[u])&&(a[c[u]]=o[c[u]]);return a},s7=function(o,s,a,c){var u=arguments.length,d=u<3?s:c===null?c=Object.getOwnPropertyDescriptor(s,a):c,l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")d=Reflect.decorate(o,s,a,c);else for(var f=o.length-1;f>=0;f--)(l=o[f])&&(d=(u<3?l(d):u>3?l(s,a,d):l(s,a))||d);return u>3&&d&&Object.defineProperty(s,a,d),d},a7=function(o,s){return function(a,c){s(a,c,o)}},c7=function(o,s,a,c,u,d){function l(z){if(z!==void 0&&typeof z!="function")throw new TypeError("Function expected");return z}for(var f=c.kind,p=f==="getter"?"get":f==="setter"?"set":"value",g=!s&&o?c.static?o:o.prototype:null,v=s||(g?Object.getOwnPropertyDescriptor(g,c.name):{}),b,C=!1,D=a.length-1;D>=0;D--){var _={};for(var F in c)_[F]=F==="access"?{}:c[F];for(var F in c.access)_.access[F]=c.access[F];_.addInitializer=function(z){if(C)throw new TypeError("Cannot add initializers after decoration has completed");d.push(l(z||null))};var he=(0,a[D])(f==="accessor"?{get:v.get,set:v.set}:v[p],_);if(f==="accessor"){if(he===void 0)continue;if(he===null||typeof he!="object")throw new TypeError("Object expected");(b=l(he.get))&&(v.get=b),(b=l(he.set))&&(v.set=b),(b=l(he.init))&&u.unshift(b)}else(b=l(he))&&(f==="field"?u.unshift(b):v[p]=b)}g&&Object.defineProperty(g,c.name,v),C=!0},u7=function(o,s,a){for(var c=arguments.length>2,u=0;u<s.length;u++)a=c?s[u].call(o,a):s[u].call(o);return c?a:void 0},d7=function(o){return typeof o=="symbol"?o:"".concat(o)},l7=function(o,s,a){return typeof s=="symbol"&&(s=s.description?"[".concat(s.description,"]"):""),Object.defineProperty(o,"name",{configurable:!0,value:a?"".concat(a," ",s):s})},f7=function(o,s){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,s)},p7=function(o,s,a,c){function u(d){return d instanceof a?d:new a(function(l){l(d)})}return new(a||(a=Promise))(function(d,l){function f(v){try{g(c.next(v))}catch(b){l(b)}}function p(v){try{g(c.throw(v))}catch(b){l(b)}}function g(v){v.done?d(v.value):u(v.value).then(f,p)}g((c=c.apply(o,s||[])).next())})},m7=function(o,s){var a={label:0,sent:function(){if(d[0]&1)throw d[1];return d[1]},trys:[],ops:[]},c,u,d,l=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return l.next=f(0),l.throw=f(1),l.return=f(2),typeof Symbol=="function"&&(l[Symbol.iterator]=function(){return this}),l;function f(g){return function(v){return p([g,v])}}function p(g){if(c)throw new TypeError("Generator is already executing.");for(;l&&(l=0,g[0]&&(a=0)),a;)try{if(c=1,u&&(d=g[0]&2?u.return:g[0]?u.throw||((d=u.return)&&d.call(u),0):u.next)&&!(d=d.call(u,g[1])).done)return d;switch(u=0,d&&(g=[g[0]&2,d.value]),g[0]){case 0:case 1:d=g;break;case 4:return a.label++,{value:g[1],done:!1};case 5:a.label++,u=g[1],g=[0];continue;case 7:g=a.ops.pop(),a.trys.pop();continue;default:if(d=a.trys,!(d=d.length>0&&d[d.length-1])&&(g[0]===6||g[0]===2)){a=0;continue}if(g[0]===3&&(!d||g[1]>d[0]&&g[1]<d[3])){a.label=g[1];break}if(g[0]===6&&a.label<d[1]){a.label=d[1],d=g;break}if(d&&a.label<d[2]){a.label=d[2],a.ops.push(g);break}d[2]&&a.ops.pop(),a.trys.pop();continue}g=s.call(o,a)}catch(v){g=[6,v],u=0}finally{c=d=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},h7=function(o,s){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(s,a)&&yI(s,o,a)},yI=Object.create?(function(o,s,a,c){c===void 0&&(c=a);var u=Object.getOwnPropertyDescriptor(s,a);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[a]}}),Object.defineProperty(o,c,u)}):(function(o,s,a,c){c===void 0&&(c=a),o[c]=s[a]}),gI=function(o){var s=typeof Symbol=="function"&&Symbol.iterator,a=s&&o[s],c=0;if(a)return a.call(o);if(o&&typeof o.length=="number")return{next:function(){return o&&c>=o.length&&(o=void 0),{value:o&&o[c++],done:!o}}};throw new TypeError(s?"Object is not iterable.":"Symbol.iterator is not defined.")},T_=function(o,s){var a=typeof Symbol=="function"&&o[Symbol.iterator];if(!a)return o;var c=a.call(o),u,d=[],l;try{for(;(s===void 0||s-- >0)&&!(u=c.next()).done;)d.push(u.value)}catch(f){l={error:f}}finally{try{u&&!u.done&&(a=c.return)&&a.call(c)}finally{if(l)throw l.error}}return d},g7=function(){for(var o=[],s=0;s<arguments.length;s++)o=o.concat(T_(arguments[s]));return o},y7=function(){for(var o=0,s=0,a=arguments.length;s<a;s++)o+=arguments[s].length;for(var c=Array(o),u=0,s=0;s<a;s++)for(var d=arguments[s],l=0,f=d.length;l<f;l++,u++)c[u]=d[l];return c},v7=function(o,s,a){if(a||arguments.length===2)for(var c=0,u=s.length,d;c<u;c++)(d||!(c in s))&&(d||(d=Array.prototype.slice.call(s,0,c)),d[c]=s[c]);return o.concat(d||Array.prototype.slice.call(s))},Vp=function(o){return this instanceof Vp?(this.v=o,this):new Vp(o)},x7=function(o,s,a){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var c=a.apply(o,s||[]),u,d=[];return u=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),f("next"),f("throw"),f("return",l),u[Symbol.asyncIterator]=function(){return this},u;function l(D){return function(_){return Promise.resolve(_).then(D,b)}}function f(D,_){c[D]&&(u[D]=function(F){return new Promise(function(he,z){d.push([D,F,he,z])>1||p(D,F)})},_&&(u[D]=_(u[D])))}function p(D,_){try{g(c[D](_))}catch(F){C(d[0][3],F)}}function g(D){D.value instanceof Vp?Promise.resolve(D.value.v).then(v,b):C(d[0][2],D)}function v(D){p("next",D)}function b(D){p("throw",D)}function C(D,_){D(_),d.shift(),d.length&&p(d[0][0],d[0][1])}},S7=function(o){var s,a;return s={},c("next"),c("throw",function(u){throw u}),c("return"),s[Symbol.iterator]=function(){return this},s;function c(u,d){s[u]=o[u]?function(l){return(a=!a)?{value:Vp(o[u](l)),done:!1}:d?d(l):l}:d}},b7=function(o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=o[Symbol.asyncIterator],a;return s?s.call(o):(o=typeof gI=="function"?gI(o):o[Symbol.iterator](),a={},c("next"),c("throw"),c("return"),a[Symbol.asyncIterator]=function(){return this},a);function c(d){a[d]=o[d]&&function(l){return new Promise(function(f,p){l=o[d](l),u(f,p,l.done,l.value)})}}function u(d,l,f,p){Promise.resolve(p).then(function(g){d({value:g,done:f})},l)}},w7=function(o,s){return Object.defineProperty?Object.defineProperty(o,"raw",{value:s}):o.raw=s,o};var r=Object.create?(function(o,s){Object.defineProperty(o,"default",{enumerable:!0,value:s})}):function(o,s){o.default=s},n=function(o){return n=Object.getOwnPropertyNames||function(s){var a=[];for(var c in s)Object.prototype.hasOwnProperty.call(s,c)&&(a[a.length]=c);return a},n(o)};I7=function(o){if(o&&o.__esModule)return o;var s={};if(o!=null)for(var a=n(o),c=0;c<a.length;c++)a[c]!=="default"&&yI(s,o,a[c]);return r(s,o),s},E7=function(o){return o&&o.__esModule?o:{default:o}},k7=function(o,s,a,c){if(a==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof s=="function"?o!==s||!c:!s.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return a==="m"?c:a==="a"?c.call(o):c?c.value:s.get(o)},R7=function(o,s,a,c,u){if(c==="m")throw new TypeError("Private method is not writable");if(c==="a"&&!u)throw new TypeError("Private accessor was defined without a setter");if(typeof s=="function"?o!==s||!u:!s.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?u.call(o,a):u?u.value=a:s.set(o,a),a},A7=function(o,s){if(s===null||typeof s!="object"&&typeof s!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof o=="function"?s===o:o.has(s)},C7=function(o,s,a){if(s!=null){if(typeof s!="object"&&typeof s!="function")throw new TypeError("Object expected.");var c,u;if(a){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");c=s[Symbol.asyncDispose]}if(c===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");c=s[Symbol.dispose],a&&(u=c)}if(typeof c!="function")throw new TypeError("Object not disposable.");u&&(c=function(){try{u.call(this)}catch(d){return Promise.reject(d)}}),o.stack.push({value:s,dispose:c,async:a})}else a&&o.stack.push({async:!0});return s};var i=typeof SuppressedError=="function"?SuppressedError:function(o,s,a){var c=new Error(a);return c.name="SuppressedError",c.error=o,c.suppressed=s,c};P7=function(o){function s(d){o.error=o.hasError?new i(d,o.error,"An error was suppressed during disposal."):d,o.hasError=!0}var a,c=0;function u(){for(;a=o.stack.pop();)try{if(!a.async&&c===1)return c=0,o.stack.push(a),Promise.resolve().then(u);if(a.dispose){var d=a.dispose.call(a.value);if(a.async)return c|=2,Promise.resolve(d).then(u,function(l){return s(l),u()})}else c|=1}catch(l){s(l)}if(c===1)return o.hasError?Promise.reject(o.error):Promise.resolve();if(o.hasError)throw o.error}return u()},_7=function(o,s){return typeof o=="string"&&/^\.\.?\//.test(o)?o.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(a,c,u,d,l){return c?s?".jsx":".js":u&&(!d||!l)?a:u+d+"."+l.toLowerCase()+"js"}):o},t("__extends",n7),t("__assign",i7),t("__rest",o7),t("__decorate",s7),t("__param",a7),t("__esDecorate",c7),t("__runInitializers",u7),t("__propKey",d7),t("__setFunctionName",l7),t("__metadata",f7),t("__awaiter",p7),t("__generator",m7),t("__exportStar",h7),t("__createBinding",yI),t("__values",gI),t("__read",T_),t("__spread",g7),t("__spreadArrays",y7),t("__spreadArray",v7),t("__await",Vp),t("__asyncGenerator",x7),t("__asyncDelegator",S7),t("__asyncValues",b7),t("__makeTemplateObject",w7),t("__importStar",I7),t("__importDefault",E7),t("__classPrivateFieldGet",k7),t("__classPrivateFieldSet",R7),t("__classPrivateFieldIn",A7),t("__addDisposableResource",C7),t("__disposeResources",P7),t("__rewriteRelativeImportExtension",_7)})});var D7={};wi(D7,{__addDisposableResource:()=>E0e,__assign:()=>Yge,__asyncDelegator:()=>g0e,__asyncGenerator:()=>h0e,__asyncValues:()=>y0e,__await:()=>m0e,__awaiter:()=>o0e,__classPrivateFieldGet:()=>b0e,__classPrivateFieldIn:()=>I0e,__classPrivateFieldSet:()=>w0e,__createBinding:()=>c0e,__decorate:()=>h,__disposeResources:()=>k0e,__esDecorate:()=>e0e,__exportStar:()=>a0e,__extends:()=>Xge,__generator:()=>s0e,__importDefault:()=>S0e,__importStar:()=>x0e,__makeTemplateObject:()=>v0e,__metadata:()=>i0e,__param:()=>Zge,__propKey:()=>r0e,__read:()=>d0e,__rest:()=>Qge,__rewriteRelativeImportExtension:()=>R0e,__runInitializers:()=>t0e,__setFunctionName:()=>n0e,__spread:()=>l0e,__spreadArray:()=>p0e,__spreadArrays:()=>f0e,__values:()=>u0e,default:()=>A0e});var D_,Xge,Yge,Qge,h,Zge,e0e,t0e,r0e,n0e,i0e,o0e,s0e,a0e,c0e,u0e,d0e,l0e,f0e,p0e,m0e,h0e,g0e,y0e,v0e,x0e,S0e,b0e,w0e,I0e,E0e,k0e,R0e,A0e,fe=N(()=>{D_=tt(T7(),1),{__extends:Xge,__assign:Yge,__rest:Qge,__decorate:h,__param:Zge,__esDecorate:e0e,__runInitializers:t0e,__propKey:r0e,__setFunctionName:n0e,__metadata:i0e,__awaiter:o0e,__generator:s0e,__exportStar:a0e,__createBinding:c0e,__values:u0e,__read:d0e,__spread:l0e,__spreadArrays:f0e,__spreadArray:p0e,__await:m0e,__asyncGenerator:h0e,__asyncDelegator:g0e,__asyncValues:y0e,__makeTemplateObject:v0e,__importStar:x0e,__importDefault:S0e,__classPrivateFieldGet:b0e,__classPrivateFieldSet:w0e,__classPrivateFieldIn:I0e,__addDisposableResource:E0e,__disposeResources:k0e,__rewriteRelativeImportExtension:R0e}=D_.default,A0e=D_.default});var B_=N(()=>{ro()});var Gp={};wi(Gp,{decode:()=>O_,encode:()=>N_,format:()=>L7,formats:()=>H7,hex:()=>U0e,is:()=>O7,normalize:()=>cy,parse:()=>M7});function T0e(t){return t.separators==="none"?[]:!t.separators||t.separators==="common"?_0e:t.separators}function D0e(t){if(!t)throw new TypeError("Hex separators must be non-empty strings")}function B0e(t,e,r){for(let n of r)if(t.startsWith(n,e))return n}function N0e(t){let e=/[A-F]/.test(t),r=/[a-f]/.test(t);return e&&!r?"upper":"lower"}function O0e(t){let e=/\r\n|\n/.exec(t);if(e)return e[0]===`\r
18
+ `?`\r
19
+ `:`
20
+ `}function B7(t){return t.replace(/[^0-9a-f]/gi,"")}function M0e(t){let e=t.match(/[0-9A-Fa-f]+|[^0-9A-Fa-f]+/g)??[];if(e.length<3)return;let r=e.filter((s,a)=>a%2===0),n=e.filter((s,a)=>a%2===1),i=n[0];if(!i||n.some(s=>s!==i)||r.some(s=>s.length===0||s.length%2!==0))return;let o=r[0]?.length??0;if(o&&!r.slice(0,-1).some(s=>s.length!==o)&&!((r[r.length-1]?.length??0)>o))return{size:o/2,separator:i}}function L0e(t){let e=t.trim(),r=/^0x/i.test(e)?"0x":"",n=r?e.slice(2):e,i=O0e(n),o=n.split(/\r\n|\n/).filter(u=>u.length>0),s=o[0]?.trim()??"",a=M0e(s),c={case:N0e(e),prefix:r};if(a&&(c.group=a),i&&o.length>1){let u=B7(o[0]??"").length/2;u>0&&o.slice(0,-1).every(d=>B7(d).length/2===u)&&(c.line={bytesPerLine:u,separator:i})}return c}function H0e(t,e){let r=e.allowPrefix??!0,n=[...T0e(e)].sort((a,c)=>c.length-a.length);for(let a of n)D0e(a);let i=t.trim();if(/^0x/i.test(i)){if(!r)throw new TypeError("Hexadecimal text must not include a 0x prefix");i=i.slice(2)}let o="",s=!1;for(let a=0;a<i.length;){let c=i[a]??"";if(P0e.test(c)){o+=c,s=!1,a+=1;continue}let u=B0e(i,a,n);if(!u)throw new TypeError("Input is not valid hexadecimal text");if(e.strict&&(s||o.length===0))throw new TypeError("Hexadecimal text contains misplaced separators");s=!0,a+=u.length}if(e.strict&&s&&o.length>0)throw new TypeError("Hexadecimal text must not end with a separator");if(o.length%2!==0){if(!e.allowOddLength)throw new TypeError("Hexadecimal text must contain an even number of characters");o=`0${o}`}return o.toLowerCase()}function N7(t,e){if(!e)return t.join("");if(!Number.isInteger(e.size)||e.size<1)throw new RangeError("Hex group size must be a positive integer");let r=[];for(let n=0;n<t.length;n+=e.size)r.push(t.slice(n,n+e.size).join(""));return r.join(e.separator)}function cy(t,e={}){return H0e(t,e)}function O7(t,e={}){if(typeof t!="string")return!1;try{return cy(t,e),!0}catch{return!1}}function N_(t,e={}){let r=ko(t),n=e.case??"lower",i=Array.from(r,s=>{let a=s.toString(16).padStart(2,"0");return n==="upper"?a.toUpperCase():a}),o="";if(e.line){let s=e.line.bytesPerLine;if(!Number.isInteger(s)||s<1)throw new RangeError("Hex bytesPerLine must be a positive integer");let a=e.line.separator??`
21
+ `,c=[];for(let u=0;u<i.length;u+=s)c.push(N7(i.slice(u,u+s),e.group));o=c.join(a)}else o=N7(i,e.group);return`${e.prefix??""}${o}`}function O_(t,e={}){let r=cy(t,e),n=new Uint8Array(r.length/2);for(let i=0;i<r.length;i+=2)n[i/2]=Number.parseInt(r.slice(i,i+2),16);return n}function M7(t,e={}){let r=cy(t,e);return{bytes:O_(r),format:L0e(t),normalized:r}}function L7(t,e){return N_(t,e)}var P0e,_0e,H7,U0e,U7=N(()=>{ro();P0e=/^[0-9a-f]$/i,_0e=[" "," ",`
22
+ `,"\r",":","-","."];H7={compact:Object.freeze({}),upper:Object.freeze({case:"upper"}),colon:Object.freeze({group:{size:1,separator:":"}}),colonUpper:Object.freeze({case:"upper",group:{size:1,separator:":"}}),groupsOf4:Object.freeze({group:{size:4,separator:" "}}),prefixed:Object.freeze({prefix:"0x"})},U0e={encode:N_,decode:O_,format:L7,formats:H7,is:O7,normalize:cy,parse:M7}});var $7=N(()=>{ro()});var F7=N(()=>{ro()});var M_=N(()=>{ro();B_()});var j7=N(()=>{M_()});var L_=N(()=>{B_();U7();$7();F7();M_();j7()});var uy,q7=N(()=>{L_();uy=class{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){let r=e.split(".");if(r.length!==4)throw new Error("Invalid IPv4 address");return r.map(n=>{let i=parseInt(n,10);if(isNaN(i)||i<0||i>255)throw new Error("Invalid IPv4 address part");return i})}static parseIPv6(e){let n=this.expandIPv6(e).split(":");if(n.length!==8)throw new Error("Invalid IPv6 address");return n.reduce((i,o)=>{let s=parseInt(o,16);if(isNaN(s)||s<0||s>65535)throw new Error("Invalid IPv6 address part");return i.push(s>>8&255),i.push(s&255),i},[])}static expandIPv6(e){if(!e.includes("::"))return e;let r=e.split("::");if(r.length>2)throw new Error("Invalid IPv6 address");let n=r[0]?r[0].split(":"):[],i=r[1]?r[1].split(":"):[],o=8-(n.length+i.length);if(o<0)throw new Error("Invalid IPv6 address");return[...n,...Array(o).fill("0"),...i].join(":")}static formatIPv6(e){let r=[];for(let n=0;n<16;n+=2)r.push((e[n]<<8|e[n+1]).toString(16));return this.compressIPv6(r.join(":"))}static compressIPv6(e){let r=e.split(":"),n=-1,i=0,o=-1,s=0;for(let a=0;a<r.length;a++)r[a]==="0"?(o===-1&&(o=a),s++):(s>i&&(n=o,i=s),o=-1,s=0);if(s>i&&(n=o,i=s),i>1){let a=r.slice(0,n).join(":"),c=r.slice(n+i).join(":");return`${a}::${c}`}return e}static parseCIDR(e){let[r,n]=e.split("/"),i=parseInt(n,10);if(this.isIPv4(r)){if(i<0||i>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(r),i]}else{if(i<0||i>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(r),i]}}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return"::/0";if(e.length!==16)return e;let r=parseInt(e.slice(8),16).toString(2).split("").reduce((i,o)=>i+ +o,0),n=e.slice(0,8).replace(/(.{2})/g,i=>`${parseInt(i,16)}.`);return n=n.slice(0,-1),`${n}/${r}`}static toString(e){let r=new Uint8Array(e);if(r.length===4)return Array.from(r).join(".");if(r.length===16)return this.formatIPv6(r);if(r.length===8||r.length===32){let n=r.length/2,i=r.slice(0,n),o=r.slice(n);if(r.every(c=>c===0))return r.length===8?"0.0.0.0/0":"::/0";let a=o.reduce((c,u)=>c+(u.toString(2).match(/1/g)||[]).length,0);return r.length===8?`${Array.from(i).join(".")}/${a}`:`${this.formatIPv6(i)}/${a}`}return this.decodeIP(Gp.encode(e))}static fromString(e){if(e.includes("/")){let[n,i]=this.parseCIDR(e),o=new Uint8Array(n.length),s=i;for(let c=0;c<o.length;c++)s>=8?(o[c]=255,s-=8):s>0&&(o[c]=255<<8-s,s=0);let a=new Uint8Array(n.length*2);return a.set(n,0),a.set(o,n.length),a.buffer}let r=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(r).buffer}}});var H_,U_,$_,on,Tl,zp,Kp,xI,gn,Jp=N(()=>{fe();ae();L_();on=class{teletexString;printableString;universalString;utf8String;bmpString;constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};h([x({type:k.TeletexString})],on.prototype,"teletexString",void 0);h([x({type:k.PrintableString})],on.prototype,"printableString",void 0);h([x({type:k.UniversalString})],on.prototype,"universalString",void 0);h([x({type:k.Utf8String})],on.prototype,"utf8String",void 0);h([x({type:k.BmpString})],on.prototype,"bmpString",void 0);on=h([W({type:L.Choice})],on);Tl=class extends on{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Gp.encode(this.anyValue):super.toString())}};h([x({type:k.IA5String})],Tl.prototype,"ia5String",void 0);h([x({type:k.Any})],Tl.prototype,"anyValue",void 0);Tl=h([W({type:L.Choice})],Tl);zp=class{type="";value=new Tl;constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],zp.prototype,"type",void 0);h([x({type:Tl})],zp.prototype,"value",void 0);Kp=H_=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,H_.prototype)}};Kp=H_=h([W({type:L.Set,itemType:zp})],Kp);xI=U_=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,U_.prototype)}};xI=U_=h([W({type:L.Sequence,itemType:Kp})],xI);gn=$_=class extends xI{constructor(e){super(e),Object.setPrototypeOf(this,$_.prototype)}};gn=$_=h([W({type:L.Sequence})],gn)});var W7,Xp,Yp,Pt,Dl=N(()=>{fe();ae();q7();Jp();W7={fromASN:t=>uy.toString(_l.fromASN(t)),toASN:t=>_l.toASN(uy.fromString(t))},Xp=class{typeId="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],Xp.prototype,"typeId",void 0);h([x({type:k.Any,context:0})],Xp.prototype,"value",void 0);Yp=class{nameAssigner;partyName=new on;constructor(e={}){Object.assign(this,e)}};h([x({type:on,optional:!0,context:0,implicit:!0})],Yp.prototype,"nameAssigner",void 0);h([x({type:on,context:1,implicit:!0})],Yp.prototype,"partyName",void 0);Pt=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};h([x({type:Xp,context:0,implicit:!0})],Pt.prototype,"otherName",void 0);h([x({type:k.IA5String,context:1,implicit:!0})],Pt.prototype,"rfc822Name",void 0);h([x({type:k.IA5String,context:2,implicit:!0})],Pt.prototype,"dNSName",void 0);h([x({type:k.Any,context:3,implicit:!0})],Pt.prototype,"x400Address",void 0);h([x({type:gn,context:4,implicit:!1})],Pt.prototype,"directoryName",void 0);h([x({type:Yp,context:5})],Pt.prototype,"ediPartyName",void 0);h([x({type:k.IA5String,context:6,implicit:!0})],Pt.prototype,"uniformResourceIdentifier",void 0);h([x({type:k.OctetString,context:7,implicit:!0,converter:W7})],Pt.prototype,"iPAddress",void 0);h([x({type:k.ObjectIdentifier,context:8,implicit:!0})],Pt.prototype,"registeredID",void 0);Pt=h([W({type:L.Choice})],Pt)});var cc,uc,F_,ju,dy,W0e,V0e,G0e,z0e,K0e,J0e,pt,br=N(()=>{cc="1.3.6.1.5.5.7",uc=`${cc}.1`,F_=`${cc}.2`,ju=`${cc}.3`,dy=`${cc}.48`,W0e=`${F_}.1`,V0e=`${F_}.2`,G0e=`${dy}.1`,z0e=`${dy}.2`,K0e=`${dy}.3`,J0e=`${dy}.5`,pt="2.5.29"});var j_,X0e,qu,q_,W_=N(()=>{fe();ae();Dl();br();X0e=`${uc}.1`,qu=class{accessMethod="";accessLocation=new Pt;constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],qu.prototype,"accessMethod",void 0);h([x({type:Pt})],qu.prototype,"accessLocation",void 0);q_=j_=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,j_.prototype)}};q_=j_=h([W({type:L.Sequence,itemType:qu})],q_)});var Y0e,Qp,Zp,V_=N(()=>{fe();ae();Dl();br();Y0e=`${pt}.35`,Qp=class extends rt{},Zp=class{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}};h([x({type:Qp,context:0,optional:!0,implicit:!0})],Zp.prototype,"keyIdentifier",void 0);h([x({type:Pt,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Zp.prototype,"authorityCertIssuer",void 0);h([x({type:k.Integer,context:2,optional:!0,implicit:!0,converter:Mt})],Zp.prototype,"authorityCertSerialNumber",void 0)});var Q0e,ly,V7=N(()=>{fe();ae();br();Q0e=`${pt}.19`,ly=class{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Boolean,defaultValue:!1})],ly.prototype,"cA",void 0);h([x({type:k.Integer,optional:!0})],ly.prototype,"pathLenConstraint",void 0)});var G_,sn,fy=N(()=>{fe();ae();Dl();sn=G_=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,G_.prototype)}};sn=G_=h([W({type:L.Sequence,itemType:Pt})],sn)});var z_,Z0e,K_,G7=N(()=>{fe();ae();fy();br();Z0e=`${pt}.29`,K_=z_=class extends sn{constructor(e){super(e),Object.setPrototypeOf(this,z_.prototype)}};K_=z_=h([W({type:L.Sequence})],K_)});var J_,z7,eye,Zs,em,tm,py,rm,nm,X_,K7=N(()=>{fe();ae();br();z7=`${pt}.32`,eye=`${z7}.0`,Zs=class{ia5String;visibleString;bmpString;utf8String;constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};h([x({type:k.IA5String})],Zs.prototype,"ia5String",void 0);h([x({type:k.VisibleString})],Zs.prototype,"visibleString",void 0);h([x({type:k.BmpString})],Zs.prototype,"bmpString",void 0);h([x({type:k.Utf8String})],Zs.prototype,"utf8String",void 0);Zs=h([W({type:L.Choice})],Zs);em=class{organization=new Zs;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}};h([x({type:Zs})],em.prototype,"organization",void 0);h([x({type:k.Integer,repeated:"sequence"})],em.prototype,"noticeNumbers",void 0);tm=class{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}};h([x({type:em,optional:!0})],tm.prototype,"noticeRef",void 0);h([x({type:Zs,optional:!0})],tm.prototype,"explicitText",void 0);py=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};h([x({type:k.IA5String})],py.prototype,"cPSuri",void 0);h([x({type:tm})],py.prototype,"userNotice",void 0);py=h([W({type:L.Choice})],py);rm=class{policyQualifierId="";qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],rm.prototype,"policyQualifierId",void 0);h([x({type:k.Any})],rm.prototype,"qualifier",void 0);nm=class{policyIdentifier="";policyQualifiers;constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],nm.prototype,"policyIdentifier",void 0);h([x({type:rm,repeated:"sequence",optional:!0})],nm.prototype,"policyQualifiers",void 0);X_=J_=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,J_.prototype)}};X_=J_=h([W({type:L.Sequence,itemType:nm})],X_)});var tye,im,Y_=N(()=>{fe();ae();br();tye=`${pt}.20`,im=class{value;constructor(e=0){this.value=e}};h([x({type:k.Integer})],im.prototype,"value",void 0);im=h([W({type:L.Choice})],im)});var rye,Q_,J7=N(()=>{fe();ae();br();Y_();rye=`${pt}.27`,Q_=class extends im{};Q_=h([W({type:L.Choice})],Q_)});var Z_,nye,Po,om,Wu,dc,my,SI=N(()=>{fe();ae();Jp();Dl();br();nye=`${pt}.31`;(function(t){t[t.unused=1]="unused",t[t.keyCompromise=2]="keyCompromise",t[t.cACompromise=4]="cACompromise",t[t.affiliationChanged=8]="affiliationChanged",t[t.superseded=16]="superseded",t[t.cessationOfOperation=32]="cessationOfOperation",t[t.certificateHold=64]="certificateHold",t[t.privilegeWithdrawn=128]="privilegeWithdrawn",t[t.aACompromise=256]="aACompromise"})(Po||(Po={}));om=class extends rs{toJSON(){let e=[],r=this.toNumber();return r&Po.aACompromise&&e.push("aACompromise"),r&Po.affiliationChanged&&e.push("affiliationChanged"),r&Po.cACompromise&&e.push("cACompromise"),r&Po.certificateHold&&e.push("certificateHold"),r&Po.cessationOfOperation&&e.push("cessationOfOperation"),r&Po.keyCompromise&&e.push("keyCompromise"),r&Po.privilegeWithdrawn&&e.push("privilegeWithdrawn"),r&Po.superseded&&e.push("superseded"),r&Po.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}},Wu=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};h([x({type:Pt,context:0,repeated:"sequence",implicit:!0})],Wu.prototype,"fullName",void 0);h([x({type:Kp,context:1,implicit:!0})],Wu.prototype,"nameRelativeToCRLIssuer",void 0);Wu=h([W({type:L.Choice})],Wu);dc=class{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}};h([x({type:Wu,context:0,optional:!0})],dc.prototype,"distributionPoint",void 0);h([x({type:om,context:1,optional:!0,implicit:!0})],dc.prototype,"reasons",void 0);h([x({type:Pt,context:2,optional:!0,repeated:"sequence",implicit:!0})],dc.prototype,"cRLIssuer",void 0);my=Z_=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,Z_.prototype)}};my=Z_=h([W({type:L.Sequence,itemType:dc})],my)});var eT,iye,tT,X7=N(()=>{fe();ae();br();SI();iye=`${pt}.46`,tT=eT=class extends my{constructor(e){super(e),Object.setPrototypeOf(this,eT.prototype)}};tT=eT=h([W({type:L.Sequence,itemType:dc})],tT)});var oye,no,Y7=N(()=>{fe();ae();br();SI();oye=`${pt}.28`,no=class t{static ONLY=!1;distributionPoint;onlyContainsUserCerts=t.ONLY;onlyContainsCACerts=t.ONLY;onlySomeReasons;indirectCRL=t.ONLY;onlyContainsAttributeCerts=t.ONLY;constructor(e={}){Object.assign(this,e)}};h([x({type:Wu,context:0,optional:!0})],no.prototype,"distributionPoint",void 0);h([x({type:k.Boolean,context:1,defaultValue:no.ONLY,implicit:!0})],no.prototype,"onlyContainsUserCerts",void 0);h([x({type:k.Boolean,context:2,defaultValue:no.ONLY,implicit:!0})],no.prototype,"onlyContainsCACerts",void 0);h([x({type:om,context:3,optional:!0,implicit:!0})],no.prototype,"onlySomeReasons",void 0);h([x({type:k.Boolean,context:4,defaultValue:no.ONLY,implicit:!0})],no.prototype,"indirectCRL",void 0);h([x({type:k.Boolean,context:5,defaultValue:no.ONLY,implicit:!0})],no.prototype,"onlyContainsAttributeCerts",void 0)});var sye,sm,bI,Q7=N(()=>{fe();ae();br();sye=`${pt}.21`;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(sm||(sm={}));bI=class{reason=sm.unspecified;constructor(e=sm.unspecified){this.reason=e}toJSON(){return sm[this.reason]}toString(){return this.toJSON()}};h([x({type:k.Enumerated})],bI.prototype,"reason",void 0);bI=h([W({type:L.Choice})],bI)});var rT,Z7,nT,aye,cye,uye,dye,lye,fye,pye,eF=N(()=>{fe();ae();br();Z7=`${pt}.37`,nT=rT=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,rT.prototype)}};nT=rT=h([W({type:L.Sequence,itemType:k.ObjectIdentifier})],nT);aye=`${Z7}.0`,cye=`${ju}.1`,uye=`${ju}.2`,dye=`${ju}.3`,lye=`${ju}.4`,fye=`${ju}.8`,pye=`${ju}.9`});var mye,wI,tF=N(()=>{fe();ae();br();mye=`${pt}.54`,wI=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};h([x({type:k.Integer,converter:Mt})],wI.prototype,"value",void 0);wI=h([W({type:L.Choice})],wI)});var hye,II,rF=N(()=>{fe();ae();br();hye=`${pt}.24`,II=class{value=new Date;constructor(e){e&&(this.value=e)}};h([x({type:k.GeneralizedTime})],II.prototype,"value",void 0);II=h([W({type:L.Choice})],II)});var iT,gye,oT,nF=N(()=>{fe();ae();fy();br();gye=`${pt}.18`,oT=iT=class extends sn{constructor(e){super(e),Object.setPrototypeOf(this,iT.prototype)}};oT=iT=h([W({type:L.Sequence})],oT)});var yye,_o,sT,iF=N(()=>{ae();br();yye=`${pt}.15`;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(_o||(_o={}));sT=class extends rs{toJSON(){let e=this.toNumber(),r=[];return e&_o.cRLSign&&r.push("crlSign"),e&_o.dataEncipherment&&r.push("dataEncipherment"),e&_o.decipherOnly&&r.push("decipherOnly"),e&_o.digitalSignature&&r.push("digitalSignature"),e&_o.encipherOnly&&r.push("encipherOnly"),e&_o.keyAgreement&&r.push("keyAgreement"),e&_o.keyCertSign&&r.push("keyCertSign"),e&_o.keyEncipherment&&r.push("keyEncipherment"),e&_o.nonRepudiation&&r.push("nonRepudiation"),r}toString(){return`[${this.toJSON().join(", ")}]`}}});var aT,vye,Bl,hy,gy,oF=N(()=>{fe();ae();Dl();br();vye=`${pt}.30`,Bl=class{base=new Pt;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}};h([x({type:Pt})],Bl.prototype,"base",void 0);h([x({type:k.Integer,context:0,defaultValue:0,implicit:!0})],Bl.prototype,"minimum",void 0);h([x({type:k.Integer,context:1,optional:!0,implicit:!0})],Bl.prototype,"maximum",void 0);hy=aT=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,aT.prototype)}};hy=aT=h([W({type:L.Sequence,itemType:Bl})],hy);gy=class{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}};h([x({type:hy,context:0,optional:!0,implicit:!0})],gy.prototype,"permittedSubtrees",void 0);h([x({type:hy,context:1,optional:!0,implicit:!0})],gy.prototype,"excludedSubtrees",void 0)});var xye,yy,sF=N(()=>{fe();ae();br();xye=`${pt}.36`,yy=class{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer,context:0,implicit:!0,optional:!0,converter:Mt})],yy.prototype,"requireExplicitPolicy",void 0);h([x({type:k.Integer,context:1,implicit:!0,optional:!0,converter:Mt})],yy.prototype,"inhibitPolicyMapping",void 0)});var cT,Sye,am,uT,aF=N(()=>{fe();ae();br();Sye=`${pt}.33`,am=class{issuerDomainPolicy="";subjectDomainPolicy="";constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],am.prototype,"issuerDomainPolicy",void 0);h([x({type:k.ObjectIdentifier})],am.prototype,"subjectDomainPolicy",void 0);uT=cT=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,cT.prototype)}};uT=cT=h([W({type:L.Sequence,itemType:am})],uT)});var dT,bye,lT,cF=N(()=>{fe();ae();fy();br();bye=`${pt}.17`,lT=dT=class extends sn{constructor(e){super(e),Object.setPrototypeOf(this,dT.prototype)}};lT=dT=h([W({type:L.Sequence})],lT)});var li,fT=N(()=>{fe();ae();li=class{type="";values=[];constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],li.prototype,"type",void 0);h([x({type:k.Any,repeated:"set"})],li.prototype,"values",void 0)});var pT,wye,mT,uF=N(()=>{fe();ae();fT();br();wye=`${pt}.9`,mT=pT=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,pT.prototype)}};mT=pT=h([W({type:L.Sequence,itemType:li})],mT)});var Iye,ns,dF=N(()=>{br();V_();Iye=`${pt}.14`,ns=class extends Qp{}});var Eye,vy,lF=N(()=>{fe();ae();br();Eye=`${pt}.16`,vy=class{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}};h([x({type:k.GeneralizedTime,context:0,implicit:!0,optional:!0})],vy.prototype,"notBefore",void 0);h([x({type:k.GeneralizedTime,context:1,implicit:!0,optional:!0})],vy.prototype,"notAfter",void 0)});var kye,cm,xy,Sy,fF=N(()=>{fe();ae();kye="1.2.840.113533.7.65.0";(function(t){t[t.keyUpdateAllowed=1]="keyUpdateAllowed",t[t.newExtensions=2]="newExtensions",t[t.pKIXCertificate=4]="pKIXCertificate"})(cm||(cm={}));xy=class extends rs{toJSON(){let e=[],r=this.toNumber();return r&cm.pKIXCertificate&&e.push("pKIXCertificate"),r&cm.newExtensions&&e.push("newExtensions"),r&cm.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}},Sy=class{entrustVers="";entrustInfoFlags=new xy;constructor(e={}){Object.assign(this,e)}};h([x({type:k.GeneralString})],Sy.prototype,"entrustVers",void 0);h([x({type:xy})],Sy.prototype,"entrustInfoFlags",void 0)});var hT,Rye,gT,pF=N(()=>{fe();ae();br();W_();Rye=`${uc}.11`,gT=hT=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,hT.prototype)}};gT=hT=h([W({type:L.Sequence,itemType:qu})],gT)});var mF=N(()=>{W_();V_();V7();G7();K7();J7();SI();X7();Y7();Y_();Q7();eF();tF();rF();nF();iF();oF();sF();aF();cF();uF();dF();lF();fF();pF()});var Me,Nl=N(()=>{fe();ae();ro();Me=class t{algorithm="";parameters;constructor(e={}){Object.assign(this,e)}isEqual(e){return e instanceof t&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&I_(e.parameters,this.parameters)||e.parameters===this.parameters)}};h([x({type:k.ObjectIdentifier})],Me.prototype,"algorithm",void 0);h([x({type:k.Any,optional:!0})],Me.prototype,"parameters",void 0)});var is,yT=N(()=>{fe();ae();Nl();is=class{algorithm=new Me;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:Me})],is.prototype,"algorithm",void 0);h([x({type:k.BitString})],is.prototype,"subjectPublicKey",void 0)});var Wr,EI=N(()=>{fe();ae();Wr=class{utcTime;generalTime;constructor(e){if(e)if(typeof e=="string"||typeof e=="number"||e instanceof Date){let r=new Date(e);r.setMilliseconds(0),r.getUTCFullYear()>2049?this.generalTime=r:this.utcTime=r}else Object.assign(this,e)}getTime(){let e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};h([x({type:k.UTCTime})],Wr.prototype,"utcTime",void 0);h([x({type:k.GeneralizedTime})],Wr.prototype,"generalTime",void 0);Wr=h([W({type:L.Choice})],Wr)});var Vu,vT=N(()=>{fe();ae();EI();Vu=class{notBefore=new Wr(new Date);notAfter=new Wr(new Date);constructor(e){e&&(this.notBefore=new Wr(e.notBefore),this.notAfter=new Wr(e.notAfter))}};h([x({type:Wr})],Vu.prototype,"notBefore",void 0);h([x({type:Wr})],Vu.prototype,"notAfter",void 0)});var xT,os,lc,kI=N(()=>{fe();ae();os=class t{static CRITICAL=!1;extnID="";critical=t.CRITICAL;extnValue=new rt;constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],os.prototype,"extnID",void 0);h([x({type:k.Boolean,defaultValue:os.CRITICAL})],os.prototype,"critical",void 0);h([x({type:rt})],os.prototype,"extnValue",void 0);lc=xT=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,xT.prototype)}};lc=xT=h([W({type:L.Sequence,itemType:os})],lc)});var um,ST=N(()=>{(function(t){t[t.v1=0]="v1",t[t.v2=1]="v2",t[t.v3=2]="v3"})(um||(um={}))});var ei,bT=N(()=>{fe();ae();Nl();Jp();yT();vT();kI();ST();ei=class{version=um.v1;serialNumber=new ArrayBuffer(0);signature=new Me;issuer=new gn;validity=new Vu;subject=new gn;subjectPublicKeyInfo=new is;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer,context:0,defaultValue:um.v1})],ei.prototype,"version",void 0);h([x({type:k.Integer,converter:Mt})],ei.prototype,"serialNumber",void 0);h([x({type:Me})],ei.prototype,"signature",void 0);h([x({type:gn})],ei.prototype,"issuer",void 0);h([x({type:Vu})],ei.prototype,"validity",void 0);h([x({type:gn})],ei.prototype,"subject",void 0);h([x({type:is})],ei.prototype,"subjectPublicKeyInfo",void 0);h([x({type:k.BitString,context:1,implicit:!0,optional:!0})],ei.prototype,"issuerUniqueID",void 0);h([x({type:k.BitString,context:2,implicit:!0,optional:!0})],ei.prototype,"subjectUniqueID",void 0);h([x({type:lc,context:3,optional:!0})],ei.prototype,"extensions",void 0)});var Gu,hF=N(()=>{fe();ae();Nl();bT();Gu=class{tbsCertificate=new ei;tbsCertificateRaw;signatureAlgorithm=new Me;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:ei,raw:!0})],Gu.prototype,"tbsCertificate",void 0);h([x({type:Me})],Gu.prototype,"signatureAlgorithm",void 0);h([x({type:k.BitString})],Gu.prototype,"signatureValue",void 0)});var Ol,io,wT=N(()=>{fe();ae();Nl();Jp();EI();kI();Ol=class{userCertificate=new ArrayBuffer(0);revocationDate=new Wr;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer,converter:Mt})],Ol.prototype,"userCertificate",void 0);h([x({type:Wr})],Ol.prototype,"revocationDate",void 0);h([x({type:os,optional:!0,repeated:"sequence"})],Ol.prototype,"crlEntryExtensions",void 0);io=class{version;signature=new Me;issuer=new gn;thisUpdate=new Wr;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer,optional:!0})],io.prototype,"version",void 0);h([x({type:Me})],io.prototype,"signature",void 0);h([x({type:gn})],io.prototype,"issuer",void 0);h([x({type:Wr})],io.prototype,"thisUpdate",void 0);h([x({type:Wr,optional:!0})],io.prototype,"nextUpdate",void 0);h([x({type:Ol,repeated:"sequence",optional:!0})],io.prototype,"revokedCertificates",void 0);h([x({type:os,optional:!0,context:0,repeated:"sequence"})],io.prototype,"crlExtensions",void 0)});var dm,gF=N(()=>{fe();ae();Nl();wT();dm=class{tbsCertList=new io;tbsCertListRaw;signatureAlgorithm=new Me;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:io,raw:!0})],dm.prototype,"tbsCertList",void 0);h([x({type:Me})],dm.prototype,"signatureAlgorithm",void 0);h([x({type:k.BitString})],dm.prototype,"signature",void 0)});var IT={};wi(IT,{AccessDescription:()=>qu,AlgorithmIdentifier:()=>Me,AsnIpConverter:()=>W7,Attribute:()=>li,AttributeTypeAndValue:()=>zp,AttributeValue:()=>Tl,AuthorityInfoAccessSyntax:()=>q_,AuthorityKeyIdentifier:()=>Zp,BaseCRLNumber:()=>Q_,BasicConstraints:()=>ly,CRLDistributionPoints:()=>my,CRLNumber:()=>im,CRLReason:()=>bI,CRLReasons:()=>sm,Certificate:()=>Gu,CertificateIssuer:()=>K_,CertificateList:()=>dm,CertificatePolicies:()=>X_,DirectoryString:()=>on,DisplayText:()=>Zs,DistributionPoint:()=>dc,DistributionPointName:()=>Wu,EDIPartyName:()=>Yp,EntrustInfo:()=>xy,EntrustInfoFlags:()=>cm,EntrustVersionInfo:()=>Sy,ExtendedKeyUsage:()=>nT,Extension:()=>os,Extensions:()=>lc,FreshestCRL:()=>tT,GeneralName:()=>Pt,GeneralNames:()=>sn,GeneralSubtree:()=>Bl,GeneralSubtrees:()=>hy,InhibitAnyPolicy:()=>wI,InvalidityDate:()=>II,IssueAlternativeName:()=>oT,IssuingDistributionPoint:()=>no,KeyIdentifier:()=>Qp,KeyUsage:()=>sT,KeyUsageFlags:()=>_o,Name:()=>gn,NameConstraints:()=>gy,NoticeReference:()=>em,OtherName:()=>Xp,PolicyConstraints:()=>yy,PolicyInformation:()=>nm,PolicyMapping:()=>am,PolicyMappings:()=>uT,PolicyQualifierInfo:()=>rm,PrivateKeyUsagePeriod:()=>vy,Qualifier:()=>py,RDNSequence:()=>xI,Reason:()=>om,ReasonFlags:()=>Po,RelativeDistinguishedName:()=>Kp,RevokedCertificate:()=>Ol,SubjectAlternativeName:()=>lT,SubjectDirectoryAttributes:()=>mT,SubjectInfoAccessSyntax:()=>gT,SubjectKeyIdentifier:()=>ns,SubjectPublicKeyInfo:()=>is,TBSCertList:()=>io,TBSCertificate:()=>ei,Time:()=>Wr,UserNotice:()=>tm,Validity:()=>Vu,Version:()=>um,anyExtendedKeyUsage:()=>aye,id_ad:()=>dy,id_ad_caIssuers:()=>z0e,id_ad_caRepository:()=>J0e,id_ad_ocsp:()=>G0e,id_ad_timeStamping:()=>K0e,id_ce:()=>pt,id_ce_authorityKeyIdentifier:()=>Y0e,id_ce_basicConstraints:()=>Q0e,id_ce_cRLDistributionPoints:()=>nye,id_ce_cRLNumber:()=>tye,id_ce_cRLReasons:()=>sye,id_ce_certificateIssuer:()=>Z0e,id_ce_certificatePolicies:()=>z7,id_ce_certificatePolicies_anyPolicy:()=>eye,id_ce_deltaCRLIndicator:()=>rye,id_ce_extKeyUsage:()=>Z7,id_ce_freshestCRL:()=>iye,id_ce_inhibitAnyPolicy:()=>mye,id_ce_invalidityDate:()=>hye,id_ce_issuerAltName:()=>gye,id_ce_issuingDistributionPoint:()=>oye,id_ce_keyUsage:()=>yye,id_ce_nameConstraints:()=>vye,id_ce_policyConstraints:()=>xye,id_ce_policyMappings:()=>Sye,id_ce_privateKeyUsagePeriod:()=>Eye,id_ce_subjectAltName:()=>bye,id_ce_subjectDirectoryAttributes:()=>wye,id_ce_subjectKeyIdentifier:()=>Iye,id_entrust_entrustVersInfo:()=>kye,id_kp:()=>ju,id_kp_OCSPSigning:()=>pye,id_kp_clientAuth:()=>uye,id_kp_codeSigning:()=>dye,id_kp_emailProtection:()=>lye,id_kp_serverAuth:()=>cye,id_kp_timeStamping:()=>fye,id_pe:()=>uc,id_pe_authorityInfoAccess:()=>X0e,id_pe_subjectInfoAccess:()=>Rye,id_pkix:()=>cc,id_qt:()=>F_,id_qt_csp:()=>W0e,id_qt_unotice:()=>V0e});var zt=N(()=>{mF();Nl();fT();hF();gF();kI();Dl();fy();Jp();br();yT();wT();bT();EI();ST();vT()});var To,by=N(()=>{fe();ae();zt();To=class{issuer=new gn;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:gn})],To.prototype,"issuer",void 0);h([x({type:k.Integer,converter:Mt})],To.prototype,"serialNumber",void 0)});var zu,ET=N(()=>{fe();ae();zt();by();zu=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};h([x({type:ns,context:0,implicit:!0})],zu.prototype,"subjectKeyIdentifier",void 0);h([x({type:To})],zu.prototype,"issuerAndSerialNumber",void 0);zu=h([W({type:L.Choice})],zu)});var On,Ku,lm,fi,fm,kT,wy,ea=N(()=>{fe();zt();ae();(function(t){t[t.v0=0]="v0",t[t.v1=1]="v1",t[t.v2=2]="v2",t[t.v3=3]="v3",t[t.v4=4]="v4",t[t.v5=5]="v5"})(On||(On={}));Ku=class extends Me{};Ku=h([W({type:L.Sequence})],Ku);lm=class extends Me{};lm=h([W({type:L.Sequence})],lm);fi=class extends Me{};fi=h([W({type:L.Sequence})],fi);fm=class extends Me{};fm=h([W({type:L.Sequence})],fm);kT=class extends Me{};kT=h([W({type:L.Sequence})],kT);wy=class extends Me{};wy=h([W({type:L.Sequence})],wy)});var Do,RI=N(()=>{fe();ae();Do=class{attrType="";attrValues=[];constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],Do.prototype,"attrType",void 0);h([x({type:k.Any,repeated:"set"})],Do.prototype,"attrValues",void 0)});var RT,pi,pm,AI=N(()=>{fe();ae();ET();ea();RI();pi=class{version=On.v0;sid=new zu;digestAlgorithm=new Ku;signedAttrs;signedAttrsRaw;signatureAlgorithm=new lm;signature=new rt;unsignedAttrs;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer})],pi.prototype,"version",void 0);h([x({type:zu})],pi.prototype,"sid",void 0);h([x({type:Ku})],pi.prototype,"digestAlgorithm",void 0);h([x({type:Do,repeated:"set",context:0,implicit:!0,optional:!0,raw:!0})],pi.prototype,"signedAttrs",void 0);h([x({type:lm})],pi.prototype,"signatureAlgorithm",void 0);h([x({type:rt})],pi.prototype,"signature",void 0);h([x({type:Do,repeated:"set",context:1,implicit:!0,optional:!0})],pi.prototype,"unsignedAttrs",void 0);pm=RT=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,RT.prototype)}};pm=RT=h([W({type:L.Set,itemType:pi})],pm)});var Aye,AT,yF=N(()=>{fe();ae();AI();Aye="1.2.840.113549.1.9.6",AT=class extends pi{};AT=h([W({type:L.Sequence})],AT)});var Cye,CT,vF=N(()=>{ae();Cye="1.2.840.113549.1.9.4",CT=class extends rt{}});var Pye,PT,xF=N(()=>{fe();zt();ae();Pye="1.2.840.113549.1.9.5",PT=class extends Wr{};PT=h([W({type:L.Choice})],PT)});var _ye,SF=N(()=>{yF();vF();xF();_ye="1.2.840.113549.1.9.3"});var Iy,bF=N(()=>{fe();ae();zt();Iy=class{acIssuer=new Pt;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}};h([x({type:Pt})],Iy.prototype,"acIssuer",void 0);h([x({type:k.Integer})],Iy.prototype,"acSerial",void 0);h([x({type:li,repeated:"sequence"})],Iy.prototype,"attrs",void 0)});var _T,Ey,TT=N(()=>{fe();ae();Ey=_T=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,_T.prototype)}};Ey=_T=h([W({type:L.Sequence,itemType:k.ObjectIdentifier})],Ey)});var mm,wF=N(()=>{fe();ae();TT();mm=class{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer,optional:!0})],mm.prototype,"pathLenConstraint",void 0);h([x({type:Ey,implicit:!0,context:0,optional:!0})],mm.prototype,"permittedAttrs",void 0);h([x({type:Ey,implicit:!0,context:1,optional:!0})],mm.prototype,"excludedAttrs",void 0);h([x({type:k.Boolean,defaultValue:!0})],mm.prototype,"permitUnSpecified",void 0)});var Bo,ky=N(()=>{fe();ae();zt();Bo=class{issuer=new sn;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:sn})],Bo.prototype,"issuer",void 0);h([x({type:k.Integer,converter:Mt})],Bo.prototype,"serial",void 0);h([x({type:k.BitString,optional:!0})],Bo.prototype,"issuerUID",void 0)});var DT,No,Ry=N(()=>{fe();ae();zt();(function(t){t[t.publicKey=0]="publicKey",t[t.publicKeyCert=1]="publicKeyCert",t[t.otherObjectTypes=2]="otherObjectTypes"})(DT||(DT={}));No=class{digestedObjectType=DT.publicKey;otherObjectTypeID;digestAlgorithm=new Me;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:k.Enumerated})],No.prototype,"digestedObjectType",void 0);h([x({type:k.ObjectIdentifier,optional:!0})],No.prototype,"otherObjectTypeID",void 0);h([x({type:Me})],No.prototype,"digestAlgorithm",void 0);h([x({type:k.BitString})],No.prototype,"objectDigest",void 0)});var Ml,BT=N(()=>{fe();ae();zt();ky();Ry();Ml=class{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};h([x({type:sn,optional:!0})],Ml.prototype,"issuerName",void 0);h([x({type:Bo,context:0,implicit:!0,optional:!0})],Ml.prototype,"baseCertificateID",void 0);h([x({type:No,context:1,implicit:!0,optional:!0})],Ml.prototype,"objectDigestInfo",void 0)});var Ll,NT=N(()=>{fe();ae();zt();BT();Ll=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};h([x({type:Pt,repeated:"sequence"})],Ll.prototype,"v1Form",void 0);h([x({type:Ml,context:0,implicit:!0})],Ll.prototype,"v2Form",void 0);Ll=h([W({type:L.Choice})],Ll)});var Hl,OT=N(()=>{fe();ae();Hl=class{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}};h([x({type:k.GeneralizedTime})],Hl.prototype,"notBeforeTime",void 0);h([x({type:k.GeneralizedTime})],Hl.prototype,"notAfterTime",void 0)});var Ju,MT=N(()=>{fe();ae();zt();ky();Ry();Ju=class{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}};h([x({type:Bo,implicit:!0,context:0,optional:!0})],Ju.prototype,"baseCertificateID",void 0);h([x({type:sn,implicit:!0,context:1,optional:!0})],Ju.prototype,"entityName",void 0);h([x({type:No,implicit:!0,context:2,optional:!0})],Ju.prototype,"objectDigestInfo",void 0)});var LT,Ti,HT=N(()=>{fe();ae();zt();MT();NT();OT();(function(t){t[t.v2=1]="v2"})(LT||(LT={}));Ti=class{version=LT.v2;holder=new Ju;issuer=new Ll;signature=new Me;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new Hl;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer})],Ti.prototype,"version",void 0);h([x({type:Ju})],Ti.prototype,"holder",void 0);h([x({type:Ll})],Ti.prototype,"issuer",void 0);h([x({type:Me})],Ti.prototype,"signature",void 0);h([x({type:k.Integer,converter:Mt})],Ti.prototype,"serialNumber",void 0);h([x({type:Hl})],Ti.prototype,"attrCertValidityPeriod",void 0);h([x({type:li,repeated:"sequence"})],Ti.prototype,"attributes",void 0);h([x({type:k.BitString,optional:!0})],Ti.prototype,"issuerUniqueID",void 0);h([x({type:lc,optional:!0})],Ti.prototype,"extensions",void 0)});var Ul,IF=N(()=>{fe();ae();zt();HT();Ul=class{acinfo=new Ti;signatureAlgorithm=new Me;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:Ti})],Ul.prototype,"acinfo",void 0);h([x({type:Me})],Ul.prototype,"signatureAlgorithm",void 0);h([x({type:k.BitString})],Ul.prototype,"signatureValue",void 0)});var Ay,hm,UT=N(()=>{ae();(function(t){t[t.unmarked=1]="unmarked",t[t.unclassified=2]="unclassified",t[t.restricted=4]="restricted",t[t.confidential=8]="confidential",t[t.secret=16]="secret",t[t.topSecret=32]="topSecret"})(Ay||(Ay={}));hm=class extends rs{}});var gm,$T=N(()=>{fe();ae();gm=class{type="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier,implicit:!0,context:0})],gm.prototype,"type",void 0);h([x({type:k.Any,implicit:!0,context:1})],gm.prototype,"value",void 0)});var Cy,EF=N(()=>{fe();ae();UT();$T();Cy=class{policyId="";classList=new hm(Ay.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],Cy.prototype,"policyId",void 0);h([x({type:hm,defaultValue:new hm(Ay.unclassified)})],Cy.prototype,"classList",void 0);h([x({type:gm,repeated:"set"})],Cy.prototype,"securityCategories",void 0)});var ym,CI,kF=N(()=>{fe();ae();zt();ym=class{cotets;oid;string;constructor(e={}){Object.assign(this,e)}};h([x({type:rt})],ym.prototype,"cotets",void 0);h([x({type:k.ObjectIdentifier})],ym.prototype,"oid",void 0);h([x({type:k.Utf8String})],ym.prototype,"string",void 0);CI=class{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}};h([x({type:sn,implicit:!0,context:0,optional:!0})],CI.prototype,"policyAuthority",void 0);h([x({type:ym,repeated:"sequence"})],CI.prototype,"values",void 0)});var I$e,E$e,k$e,R$e,Py,A$e,C$e,P$e,_$e,T$e,FT,D$e,RF=N(()=>{zt();I$e=`${uc}.4`,E$e=`${uc}.6`,k$e=`${uc}.10`,R$e=`${pt}.55`,Py=`${cc}.10`,A$e=`${Py}.1`,C$e=`${Py}.2`,P$e=`${Py}.3`,_$e=`${Py}.4`,T$e=`${Py}.6`,FT="2.5.4",D$e=`${FT}.72`});var jT,vm,xm,PI,qT=N(()=>{fe();ae();zt();ky();Ry();vm=class{targetCertificate=new Bo;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}};h([x({type:Bo})],vm.prototype,"targetCertificate",void 0);h([x({type:Pt,optional:!0})],vm.prototype,"targetName",void 0);h([x({type:No,optional:!0})],vm.prototype,"certDigestInfo",void 0);xm=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};h([x({type:Pt,context:0,implicit:!0})],xm.prototype,"targetName",void 0);h([x({type:Pt,context:1,implicit:!0})],xm.prototype,"targetGroup",void 0);h([x({type:vm,context:2,implicit:!0})],xm.prototype,"targetCert",void 0);xm=h([W({type:L.Choice})],xm);PI=jT=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,jT.prototype)}};PI=jT=h([W({type:L.Sequence,itemType:xm})],PI)});var WT,AF,CF=N(()=>{fe();ae();qT();AF=WT=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,WT.prototype)}};AF=WT=h([W({type:L.Sequence,itemType:PI})],AF)});var _I,PF=N(()=>{fe();ae();zt();_I=class{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}};h([x({type:sn,implicit:!0,context:0,optional:!0})],_I.prototype,"roleAuthority",void 0);h([x({type:Pt,implicit:!0,context:1})],_I.prototype,"roleName",void 0)});var _y,_F=N(()=>{fe();ae();zt();_y=class{service=new Pt;ident=new Pt;authInfo;constructor(e={}){Object.assign(this,e)}};h([x({type:Pt})],_y.prototype,"service",void 0);h([x({type:Pt})],_y.prototype,"ident",void 0);h([x({type:rt,optional:!0})],_y.prototype,"authInfo",void 0)});var VT=N(()=>{bF();wF();NT();OT();TT();IF();HT();UT();EF();MT();kF();ky();Ry();RF();CF();PF();$T();_F();qT();BT()});var GT,Sm,$l,Fl,TI=N(()=>{fe();ae();zt();VT();Sm=class{otherCertFormat="";otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],Sm.prototype,"otherCertFormat",void 0);h([x({type:k.Any})],Sm.prototype,"otherCert",void 0);$l=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};h([x({type:Gu})],$l.prototype,"certificate",void 0);h([x({type:Ul,context:2,implicit:!0})],$l.prototype,"v2AttrCert",void 0);h([x({type:Sm,context:3,implicit:!0})],$l.prototype,"other",void 0);$l=h([W({type:L.Choice})],$l);Fl=GT=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,GT.prototype)}};Fl=GT=h([W({type:L.Set,itemType:$l})],Fl)});var Oo,TF=N(()=>{fe();ae();Oo=class{contentType="";content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],Oo.prototype,"contentType",void 0);h([x({type:k.Any,context:0})],Oo.prototype,"content",void 0)});var bm,Xu,zT=N(()=>{fe();ae();bm=class{single;any;constructor(e={}){Object.assign(this,e)}};h([x({type:rt})],bm.prototype,"single",void 0);h([x({type:k.Any})],bm.prototype,"any",void 0);bm=h([W({type:L.Choice})],bm);Xu=class{eContentType="";eContent;constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],Xu.prototype,"eContentType",void 0);h([x({type:bm,context:0,optional:!0})],Xu.prototype,"eContent",void 0)});var wm,fc,KT=N(()=>{fe();ae();ea();wm=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};h([x({type:rt,context:0,implicit:!0,optional:!0})],wm.prototype,"value",void 0);h([x({type:rt,converter:k_,context:0,implicit:!0,optional:!0,repeated:"sequence"})],wm.prototype,"constructedValue",void 0);wm=h([W({type:L.Choice})],wm);fc=class{contentType="";contentEncryptionAlgorithm=new fm;encryptedContent;constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],fc.prototype,"contentType",void 0);h([x({type:fm})],fc.prototype,"contentEncryptionAlgorithm",void 0);h([x({type:wm,optional:!0})],fc.prototype,"encryptedContent",void 0)});var Yu,JT=N(()=>{fe();ae();Yu=class{keyAttrId="";keyAttr;constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],Yu.prototype,"keyAttrId",void 0);h([x({type:k.Any,optional:!0})],Yu.prototype,"keyAttr",void 0)});var XT,jl,ql,Im,Ty,Em,Qu,ta,YT=N(()=>{fe();ae();zt();ea();by();JT();jl=class{subjectKeyIdentifier=new ns;date;other;constructor(e={}){Object.assign(this,e)}};h([x({type:ns})],jl.prototype,"subjectKeyIdentifier",void 0);h([x({type:k.GeneralizedTime,optional:!0})],jl.prototype,"date",void 0);h([x({type:Yu,optional:!0})],jl.prototype,"other",void 0);ql=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};h([x({type:jl,context:0,implicit:!0,optional:!0})],ql.prototype,"rKeyId",void 0);h([x({type:To,optional:!0})],ql.prototype,"issuerAndSerialNumber",void 0);ql=h([W({type:L.Choice})],ql);Im=class{rid=new ql;encryptedKey=new rt;constructor(e={}){Object.assign(this,e)}};h([x({type:ql})],Im.prototype,"rid",void 0);h([x({type:rt})],Im.prototype,"encryptedKey",void 0);Ty=XT=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,XT.prototype)}};Ty=XT=h([W({type:L.Sequence,itemType:Im})],Ty);Em=class{algorithm=new Me;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:Me})],Em.prototype,"algorithm",void 0);h([x({type:k.BitString})],Em.prototype,"publicKey",void 0);Qu=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};h([x({type:ns,context:0,implicit:!0,optional:!0})],Qu.prototype,"subjectKeyIdentifier",void 0);h([x({type:Em,context:1,implicit:!0,optional:!0})],Qu.prototype,"originatorKey",void 0);h([x({type:To,optional:!0})],Qu.prototype,"issuerAndSerialNumber",void 0);Qu=h([W({type:L.Choice})],Qu);ta=class{version=On.v3;originator=new Qu;ukm;keyEncryptionAlgorithm=new fi;recipientEncryptedKeys=new Ty;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer})],ta.prototype,"version",void 0);h([x({type:Qu,context:0})],ta.prototype,"originator",void 0);h([x({type:rt,context:1,optional:!0})],ta.prototype,"ukm",void 0);h([x({type:fi})],ta.prototype,"keyEncryptionAlgorithm",void 0);h([x({type:Ty})],ta.prototype,"recipientEncryptedKeys",void 0)});var Wl,pc,QT=N(()=>{fe();ae();zt();ea();by();Wl=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};h([x({type:ns,context:0,implicit:!0})],Wl.prototype,"subjectKeyIdentifier",void 0);h([x({type:To})],Wl.prototype,"issuerAndSerialNumber",void 0);Wl=h([W({type:L.Choice})],Wl);pc=class{version=On.v0;rid=new Wl;keyEncryptionAlgorithm=new fi;encryptedKey=new rt;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer})],pc.prototype,"version",void 0);h([x({type:Wl})],pc.prototype,"rid",void 0);h([x({type:fi})],pc.prototype,"keyEncryptionAlgorithm",void 0);h([x({type:rt})],pc.prototype,"encryptedKey",void 0)});var Zu,mc,ZT=N(()=>{fe();ae();JT();ea();Zu=class{keyIdentifier=new rt;date;other;constructor(e={}){Object.assign(this,e)}};h([x({type:rt})],Zu.prototype,"keyIdentifier",void 0);h([x({type:k.GeneralizedTime,optional:!0})],Zu.prototype,"date",void 0);h([x({type:Yu,optional:!0})],Zu.prototype,"other",void 0);mc=class{version=On.v4;kekid=new Zu;keyEncryptionAlgorithm=new fi;encryptedKey=new rt;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer})],mc.prototype,"version",void 0);h([x({type:Zu})],mc.prototype,"kekid",void 0);h([x({type:fi})],mc.prototype,"keyEncryptionAlgorithm",void 0);h([x({type:rt})],mc.prototype,"encryptedKey",void 0)});var hc,e2=N(()=>{fe();ae();ea();hc=class{version=On.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new fi;encryptedKey=new rt;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer})],hc.prototype,"version",void 0);h([x({type:wy,context:0,optional:!0})],hc.prototype,"keyDerivationAlgorithm",void 0);h([x({type:fi})],hc.prototype,"keyEncryptionAlgorithm",void 0);h([x({type:rt})],hc.prototype,"encryptedKey",void 0)});var km,ra,t2=N(()=>{fe();ae();YT();QT();ZT();e2();km=class{oriType="";oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],km.prototype,"oriType",void 0);h([x({type:k.Any})],km.prototype,"oriValue",void 0);ra=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};h([x({type:pc,optional:!0})],ra.prototype,"ktri",void 0);h([x({type:ta,context:1,implicit:!0,optional:!0})],ra.prototype,"kari",void 0);h([x({type:mc,context:2,implicit:!0,optional:!0})],ra.prototype,"kekri",void 0);h([x({type:hc,context:3,implicit:!0,optional:!0})],ra.prototype,"pwri",void 0);h([x({type:km,context:4,implicit:!0,optional:!0})],ra.prototype,"ori",void 0);ra=h([W({type:L.Choice})],ra)});var r2,Rm,n2=N(()=>{fe();ae();t2();Rm=r2=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,r2.prototype)}};Rm=r2=h([W({type:L.Set,itemType:ra})],Rm)});var i2,o2,Dye,Bye,Vl,Dy,Gl,DI=N(()=>{fe();ae();zt();o2=`${cc}.16`,Dye=`${o2}.2`,Bye=`${o2}.4`,Vl=class{otherRevInfoFormat="";otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],Vl.prototype,"otherRevInfoFormat",void 0);h([x({type:k.Any})],Vl.prototype,"otherRevInfo",void 0);Dy=class{other=new Vl;constructor(e={}){Object.assign(this,e)}};h([x({type:Vl,context:1,implicit:!0})],Dy.prototype,"other",void 0);Dy=h([W({type:L.Choice})],Dy);Gl=i2=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,i2.prototype)}};Gl=i2=h([W({type:L.Set,itemType:Dy})],Gl)});var zl,s2=N(()=>{fe();ae();TI();DI();zl=class{certs;crls;constructor(e={}){Object.assign(this,e)}};h([x({type:Fl,context:0,implicit:!0,optional:!0})],zl.prototype,"certs",void 0);h([x({type:Gl,context:1,implicit:!0,optional:!0})],zl.prototype,"crls",void 0)});var a2,BI,ed,DF=N(()=>{fe();ae();ea();RI();n2();s2();KT();BI=a2=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,a2.prototype)}};BI=a2=h([W({type:L.Set,itemType:Do})],BI);ed=class{version=On.v0;originatorInfo;recipientInfos=new Rm;encryptedContentInfo=new fc;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer})],ed.prototype,"version",void 0);h([x({type:zl,context:0,implicit:!0,optional:!0})],ed.prototype,"originatorInfo",void 0);h([x({type:Rm})],ed.prototype,"recipientInfos",void 0);h([x({type:fc})],ed.prototype,"encryptedContentInfo",void 0);h([x({type:BI,context:1,implicit:!0,optional:!0})],ed.prototype,"unprotectedAttrs",void 0)});var Nye,Oye,Mye,Lye,Hye,Uye,$ye,BF=N(()=>{Nye="1.2.840.113549.1.9.16.1.6",Oye="1.2.840.113549.1.7.1",Mye="1.2.840.113549.1.7.2",Lye="1.2.840.113549.1.7.3",Hye="1.2.840.113549.1.7.5",Uye="1.2.840.113549.1.7.6",$ye="1.2.840.113549.1.9.16.1.2"});var c2,By,gc,NF=N(()=>{fe();ae();TI();ea();zT();DI();AI();By=c2=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,c2.prototype)}};By=c2=h([W({type:L.Set,itemType:Ku})],By);gc=class{version=On.v0;digestAlgorithms=new By;encapContentInfo=new Xu;certificates;crls;signerInfos=new pm;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer})],gc.prototype,"version",void 0);h([x({type:By})],gc.prototype,"digestAlgorithms",void 0);h([x({type:Xu})],gc.prototype,"encapContentInfo",void 0);h([x({type:Fl,context:0,implicit:!0,optional:!0})],gc.prototype,"certificates",void 0);h([x({type:Gl,context:1,implicit:!0,optional:!0})],gc.prototype,"crls",void 0);h([x({type:pm})],gc.prototype,"signerInfos",void 0)});var u2={};wi(u2,{Attribute:()=>Do,CMSVersion:()=>On,CertificateChoices:()=>$l,CertificateSet:()=>Fl,ContentEncryptionAlgorithmIdentifier:()=>fm,ContentInfo:()=>Oo,CounterSignature:()=>AT,DigestAlgorithmIdentifier:()=>Ku,DigestAlgorithmIdentifiers:()=>By,EncapsulatedContent:()=>bm,EncapsulatedContentInfo:()=>Xu,EncryptedContent:()=>wm,EncryptedContentInfo:()=>fc,EnvelopedData:()=>ed,IssuerAndSerialNumber:()=>To,KEKIdentifier:()=>Zu,KEKRecipientInfo:()=>mc,KeyAgreeRecipientIdentifier:()=>ql,KeyAgreeRecipientInfo:()=>ta,KeyDerivationAlgorithmIdentifier:()=>wy,KeyEncryptionAlgorithmIdentifier:()=>fi,KeyTransRecipientInfo:()=>pc,MessageAuthenticationCodeAlgorithm:()=>kT,MessageDigest:()=>CT,OriginatorIdentifierOrKey:()=>Qu,OriginatorInfo:()=>zl,OriginatorPublicKey:()=>Em,OtherCertificateFormat:()=>Sm,OtherRecipientInfo:()=>km,OtherRevocationInfoFormat:()=>Vl,PasswordRecipientInfo:()=>hc,RecipientEncryptedKey:()=>Im,RecipientEncryptedKeys:()=>Ty,RecipientIdentifier:()=>Wl,RecipientInfo:()=>ra,RecipientInfos:()=>Rm,RecipientKeyIdentifier:()=>jl,RevocationInfoChoice:()=>Dy,RevocationInfoChoices:()=>Gl,SignatureAlgorithmIdentifier:()=>lm,SignedData:()=>gc,SignerIdentifier:()=>zu,SignerInfo:()=>pi,SignerInfos:()=>pm,SigningTime:()=>PT,UnprotectedAttributes:()=>BI,id_authData:()=>$ye,id_contentType:()=>_ye,id_counterSignature:()=>Aye,id_ct_contentInfo:()=>Nye,id_data:()=>Oye,id_digestedData:()=>Hye,id_encryptedData:()=>Uye,id_envelopedData:()=>Lye,id_messageDigest:()=>Cye,id_ri:()=>o2,id_ri_ocsp_response:()=>Dye,id_ri_scvp:()=>Bye,id_signedData:()=>Mye,id_signingTime:()=>Pye});var Ny=N(()=>{SF();RI();TI();TF();zT();KT();DF();by();ZT();YT();QT();BF();s2();e2();t2();n2();DI();NF();ET();AI();ea()});var Fye,jye,qye,d2,l2,f2,p2,m2,Wye,Vye,Gye,zye,Kye,Jye,Xye,Yye,Qye,Zye,eve,tve,rve,nve,ive,h2=N(()=>{Fye="1.2.840.10045.2.1",jye="1.3.132.1.12",qye="1.3.132.1.13",d2="1.2.840.10045.4.1",l2="1.2.840.10045.4.3.1",f2="1.2.840.10045.4.3.2",p2="1.2.840.10045.4.3.3",m2="1.2.840.10045.4.3.4",Wye="1.2.840.10045.3.1.1",Vye="1.3.132.0.1",Gye="1.3.132.0.15",zye="1.3.132.0.33",Kye="1.3.132.0.26",Jye="1.3.132.0.27",Xye="1.2.840.10045.3.1.7",Yye="1.3.132.0.16",Qye="1.3.132.0.17",Zye="1.3.132.0.34",eve="1.3.132.0.36",tve="1.3.132.0.37",rve="1.3.132.0.35",nve="1.3.132.0.38",ive="1.3.132.0.39"});function Oy(t){return new Me({algorithm:t})}var sve,ave,cve,uve,dve,OF=N(()=>{zt();h2();sve=Oy(d2),ave=Oy(l2),cve=Oy(f2),uve=Oy(p2),dve=Oy(m2)});var Am,NI,g2,Kl,OI,ss,y2=N(()=>{fe();ae();Am=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],Am.prototype,"fieldType",void 0);h([x({type:k.Any})],Am.prototype,"parameters",void 0);Am=h([W({type:L.Sequence})],Am);NI=class extends rt{},g2=class extends rt{},Kl=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};h([x({type:k.OctetString})],Kl.prototype,"a",void 0);h([x({type:k.OctetString})],Kl.prototype,"b",void 0);h([x({type:k.BitString,optional:!0})],Kl.prototype,"seed",void 0);Kl=h([W({type:L.Sequence})],Kl);(function(t){t[t.ecpVer1=1]="ecpVer1"})(OI||(OI={}));ss=class{version=OI.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer})],ss.prototype,"version",void 0);h([x({type:Am})],ss.prototype,"fieldID",void 0);h([x({type:Kl})],ss.prototype,"curve",void 0);h([x({type:NI})],ss.prototype,"base",void 0);h([x({type:k.Integer,converter:Mt})],ss.prototype,"order",void 0);h([x({type:k.Integer,optional:!0})],ss.prototype,"cofactor",void 0);ss=h([W({type:L.Sequence})],ss)});var td,v2=N(()=>{fe();ae();y2();td=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],td.prototype,"namedCurve",void 0);h([x({type:k.Null})],td.prototype,"implicitCurve",void 0);h([x({type:ss})],td.prototype,"specifiedCurve",void 0);td=h([W({type:L.Choice})],td)});var Jl,MF=N(()=>{fe();ae();v2();Jl=class{version=1;privateKey=new rt;parameters;publicKey;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer})],Jl.prototype,"version",void 0);h([x({type:rt})],Jl.prototype,"privateKey",void 0);h([x({type:td,context:0,optional:!0})],Jl.prototype,"parameters",void 0);h([x({type:k.BitString,context:1,optional:!0})],Jl.prototype,"publicKey",void 0)});var My,LF=N(()=>{fe();ae();My=class{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer,converter:Mt})],My.prototype,"r",void 0);h([x({type:k.Integer,converter:Mt})],My.prototype,"s",void 0)});var HF={};wi(HF,{Curve:()=>Kl,ECDSASigValue:()=>My,ECPVer:()=>OI,ECParameters:()=>td,ECPoint:()=>NI,ECPrivateKey:()=>Jl,FieldElement:()=>g2,FieldID:()=>Am,SpecifiedECDomain:()=>ss,ecdsaWithSHA1:()=>sve,ecdsaWithSHA224:()=>ave,ecdsaWithSHA256:()=>cve,ecdsaWithSHA384:()=>uve,ecdsaWithSHA512:()=>dve,id_ecDH:()=>jye,id_ecMQV:()=>qye,id_ecPublicKey:()=>Fye,id_ecdsaWithSHA1:()=>d2,id_ecdsaWithSHA224:()=>l2,id_ecdsaWithSHA256:()=>f2,id_ecdsaWithSHA384:()=>p2,id_ecdsaWithSHA512:()=>m2,id_secp192r1:()=>Wye,id_secp224r1:()=>zye,id_secp256r1:()=>Xye,id_secp384r1:()=>Zye,id_secp521r1:()=>rve,id_sect163k1:()=>Vye,id_sect163r2:()=>Gye,id_sect233k1:()=>Kye,id_sect233r1:()=>Jye,id_sect283k1:()=>Yye,id_sect283r1:()=>Qye,id_sect409k1:()=>eve,id_sect409r1:()=>tve,id_sect571k1:()=>nve,id_sect571r1:()=>ive});var UF=N(()=>{OF();v2();MF();LF();h2();y2()});var mi,x2,S2,b2,w2,I2,E2,k2,$F,lve,fve,R2,A2,MI,LI,C2,P2,_2,T2,D2,B2,N2,O2,M2,Xl,Ly=N(()=>{mi="1.2.840.113549.1.1",x2=`${mi}.1`,S2=`${mi}.7`,b2=`${mi}.9`,w2=`${mi}.10`,I2=`${mi}.2`,E2=`${mi}.4`,k2=`${mi}.5`,$F=`${mi}.14`,lve=$F,fve=`${mi}.11`,R2=`${mi}.12`,A2=`${mi}.13`,MI=`${mi}.15`,LI=`${mi}.16`,C2="1.3.14.3.2.26",P2="2.16.840.1.101.3.4.2.4",_2="2.16.840.1.101.3.4.2.1",T2="2.16.840.1.101.3.4.2.2",D2="2.16.840.1.101.3.4.2.3",B2="2.16.840.1.101.3.4.2.5",N2="2.16.840.1.101.3.4.2.6",O2="1.2.840.113549.2.2",M2="1.2.840.113549.2.5",Xl=`${mi}.8`});function yn(t){return new Me({algorithm:t,parameters:null})}var mve,hve,na,gve,yve,vve,xve,Sve,bve,Hy,HI,wve,Ive,Eve,kve,Rve,Ave,Cve,Pve,_ve,Tve,UI=N(()=>{ae();zt();Ly();mve=yn(O2),hve=yn(M2),na=yn(C2),gve=yn(P2),yve=yn(_2),vve=yn(T2),xve=yn(D2),Sve=yn(B2),bve=yn(N2),Hy=new Me({algorithm:Xl,parameters:Co.serialize(na)}),HI=new Me({algorithm:b2,parameters:Co.serialize(_l.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))}),wve=yn(x2),Ive=yn(I2),Eve=yn(E2),kve=yn(k2),Rve=yn(MI),Ave=yn(LI),Cve=yn(R2),Pve=yn(A2),_ve=yn(MI),Tve=yn(LI)});var Yl,Dve,FF=N(()=>{fe();ae();zt();Ly();UI();Yl=class{hashAlgorithm=new Me(na);maskGenAlgorithm=new Me({algorithm:Xl,parameters:Co.serialize(na)});pSourceAlgorithm=new Me(HI);constructor(e={}){Object.assign(this,e)}};h([x({type:Me,context:0,defaultValue:na})],Yl.prototype,"hashAlgorithm",void 0);h([x({type:Me,context:1,defaultValue:Hy})],Yl.prototype,"maskGenAlgorithm",void 0);h([x({type:Me,context:2,defaultValue:HI})],Yl.prototype,"pSourceAlgorithm",void 0);Dve=new Me({algorithm:S2,parameters:Co.serialize(new Yl)})});var rd,Bve,jF=N(()=>{fe();ae();zt();Ly();UI();rd=class{hashAlgorithm=new Me(na);maskGenAlgorithm=new Me({algorithm:Xl,parameters:Co.serialize(na)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}};h([x({type:Me,context:0,defaultValue:na})],rd.prototype,"hashAlgorithm",void 0);h([x({type:Me,context:1,defaultValue:Hy})],rd.prototype,"maskGenAlgorithm",void 0);h([x({type:k.Integer,context:2,defaultValue:20})],rd.prototype,"saltLength",void 0);h([x({type:k.Integer,context:3,defaultValue:1})],rd.prototype,"trailerField",void 0);Bve=new Me({algorithm:w2,parameters:Co.serialize(new rd)})});var nd,qF=N(()=>{fe();zt();ae();nd=class{digestAlgorithm=new Me;digest=new rt;constructor(e={}){Object.assign(this,e)}};h([x({type:Me})],nd.prototype,"digestAlgorithm",void 0);h([x({type:rt})],nd.prototype,"digest",void 0)});var WF=N(()=>{FF();jF();qF()});var L2,Ql,Uy,H2=N(()=>{fe();ae();Ql=class{prime=new ArrayBuffer(0);exponent=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer,converter:Mt})],Ql.prototype,"prime",void 0);h([x({type:k.Integer,converter:Mt})],Ql.prototype,"exponent",void 0);h([x({type:k.Integer,converter:Mt})],Ql.prototype,"coefficient",void 0);Uy=L2=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,L2.prototype)}};Uy=L2=h([W({type:L.Sequence,itemType:Ql})],Uy)});var oo,VF=N(()=>{fe();ae();H2();oo=class{version=0;modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);privateExponent=new ArrayBuffer(0);prime1=new ArrayBuffer(0);prime2=new ArrayBuffer(0);exponent1=new ArrayBuffer(0);exponent2=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);otherPrimeInfos;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer})],oo.prototype,"version",void 0);h([x({type:k.Integer,converter:Mt})],oo.prototype,"modulus",void 0);h([x({type:k.Integer,converter:Mt})],oo.prototype,"publicExponent",void 0);h([x({type:k.Integer,converter:Mt})],oo.prototype,"privateExponent",void 0);h([x({type:k.Integer,converter:Mt})],oo.prototype,"prime1",void 0);h([x({type:k.Integer,converter:Mt})],oo.prototype,"prime2",void 0);h([x({type:k.Integer,converter:Mt})],oo.prototype,"exponent1",void 0);h([x({type:k.Integer,converter:Mt})],oo.prototype,"exponent2",void 0);h([x({type:k.Integer,converter:Mt})],oo.prototype,"coefficient",void 0);h([x({type:Uy,optional:!0})],oo.prototype,"otherPrimeInfos",void 0)});var $y,GF=N(()=>{fe();ae();$y=class{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer,converter:Mt})],$y.prototype,"modulus",void 0);h([x({type:k.Integer,converter:Mt})],$y.prototype,"publicExponent",void 0)});var zF={};wi(zF,{DigestInfo:()=>nd,OtherPrimeInfo:()=>Ql,OtherPrimeInfos:()=>Uy,RSAES_OAEP:()=>Dve,RSAPrivateKey:()=>oo,RSAPublicKey:()=>$y,RSASSA_PSS:()=>Bve,RsaEsOaepParams:()=>Yl,RsaSaPssParams:()=>rd,id_RSAES_OAEP:()=>S2,id_RSASSA_PSS:()=>w2,id_md2:()=>O2,id_md2WithRSAEncryption:()=>I2,id_md5:()=>M2,id_md5WithRSAEncryption:()=>E2,id_mgf1:()=>Xl,id_pSpecified:()=>b2,id_pkcs_1:()=>mi,id_rsaEncryption:()=>x2,id_sha1:()=>C2,id_sha1WithRSAEncryption:()=>k2,id_sha224:()=>P2,id_sha224WithRSAEncryption:()=>$F,id_sha256:()=>_2,id_sha256WithRSAEncryption:()=>fve,id_sha384:()=>T2,id_sha384WithRSAEncryption:()=>R2,id_sha512:()=>D2,id_sha512WithRSAEncryption:()=>A2,id_sha512_224:()=>B2,id_sha512_224WithRSAEncryption:()=>MI,id_sha512_256:()=>N2,id_sha512_256WithRSAEncryption:()=>LI,id_ssha224WithRSAEncryption:()=>lve,md2:()=>mve,md2WithRSAEncryption:()=>Ive,md4:()=>hve,md5WithRSAEncryption:()=>Eve,mgf1SHA1:()=>Hy,pSpecifiedEmpty:()=>HI,rsaEncryption:()=>wve,sha1:()=>na,sha1WithRSAEncryption:()=>kve,sha224:()=>gve,sha224WithRSAEncryption:()=>Rve,sha256:()=>yve,sha256WithRSAEncryption:()=>Ave,sha384:()=>vve,sha384WithRSAEncryption:()=>Cve,sha512:()=>xve,sha512WithRSAEncryption:()=>Pve,sha512_224:()=>Sve,sha512_224WithRSAEncryption:()=>_ve,sha512_256:()=>bve,sha512_256WithRSAEncryption:()=>Tve});var U2=N(()=>{WF();UI();Ly();H2();VF();GF()});var mj=ce((Lqe,FI)=>{var KF,JF,XF,YF,QF,ZF,ej,tj,rj,$I,$2,nj,ij,Cm,oj,sj,aj,cj,uj,dj,lj,fj,pj;(function(t){var e=typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:{};typeof define=="function"&&define.amd?define("tslib",["exports"],function(n){t(r(e,r(n)))}):typeof FI=="object"&&typeof FI.exports=="object"?t(r(e,r(FI.exports))):t(r(e));function r(n,i){return n!==e&&(typeof Object.create=="function"?Object.defineProperty(n,"__esModule",{value:!0}):n.__esModule=!0),function(o,s){return n[o]=i?i(o,s):s}}})(function(t){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])};KF=function(r,n){e(r,n);function i(){this.constructor=r}r.prototype=n===null?Object.create(n):(i.prototype=n.prototype,new i)},JF=Object.assign||function(r){for(var n,i=1,o=arguments.length;i<o;i++){n=arguments[i];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[s]=n[s])}return r},XF=function(r,n){var i={};for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&n.indexOf(o)<0&&(i[o]=r[o]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,o=Object.getOwnPropertySymbols(r);s<o.length;s++)n.indexOf(o[s])<0&&Object.prototype.propertyIsEnumerable.call(r,o[s])&&(i[o[s]]=r[o[s]]);return i},YF=function(r,n,i,o){var s=arguments.length,a=s<3?n:o===null?o=Object.getOwnPropertyDescriptor(n,i):o,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(r,n,i,o);else for(var u=r.length-1;u>=0;u--)(c=r[u])&&(a=(s<3?c(a):s>3?c(n,i,a):c(n,i))||a);return s>3&&a&&Object.defineProperty(n,i,a),a},QF=function(r,n){return function(i,o){n(i,o,r)}},ZF=function(r,n){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,n)},ej=function(r,n,i,o){function s(a){return a instanceof i?a:new i(function(c){c(a)})}return new(i||(i=Promise))(function(a,c){function u(f){try{l(o.next(f))}catch(p){c(p)}}function d(f){try{l(o.throw(f))}catch(p){c(p)}}function l(f){f.done?a(f.value):s(f.value).then(u,d)}l((o=o.apply(r,n||[])).next())})},tj=function(r,n){var i={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},o,s,a,c;return c={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(c[Symbol.iterator]=function(){return this}),c;function u(l){return function(f){return d([l,f])}}function d(l){if(o)throw new TypeError("Generator is already executing.");for(;i;)try{if(o=1,s&&(a=l[0]&2?s.return:l[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,l[1])).done)return a;switch(s=0,a&&(l=[l[0]&2,a.value]),l[0]){case 0:case 1:a=l;break;case 4:return i.label++,{value:l[1],done:!1};case 5:i.label++,s=l[1],l=[0];continue;case 7:l=i.ops.pop(),i.trys.pop();continue;default:if(a=i.trys,!(a=a.length>0&&a[a.length-1])&&(l[0]===6||l[0]===2)){i=0;continue}if(l[0]===3&&(!a||l[1]>a[0]&&l[1]<a[3])){i.label=l[1];break}if(l[0]===6&&i.label<a[1]){i.label=a[1],a=l;break}if(a&&i.label<a[2]){i.label=a[2],i.ops.push(l);break}a[2]&&i.ops.pop(),i.trys.pop();continue}l=n.call(r,i)}catch(f){l=[6,f],s=0}finally{o=a=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},pj=function(r,n,i,o){o===void 0&&(o=i),r[o]=n[i]},rj=function(r,n){for(var i in r)i!=="default"&&!n.hasOwnProperty(i)&&(n[i]=r[i])},$I=function(r){var n=typeof Symbol=="function"&&Symbol.iterator,i=n&&r[n],o=0;if(i)return i.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&o>=r.length&&(r=void 0),{value:r&&r[o++],done:!r}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")},$2=function(r,n){var i=typeof Symbol=="function"&&r[Symbol.iterator];if(!i)return r;var o=i.call(r),s,a=[],c;try{for(;(n===void 0||n-- >0)&&!(s=o.next()).done;)a.push(s.value)}catch(u){c={error:u}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(c)throw c.error}}return a},nj=function(){for(var r=[],n=0;n<arguments.length;n++)r=r.concat($2(arguments[n]));return r},ij=function(){for(var r=0,n=0,i=arguments.length;n<i;n++)r+=arguments[n].length;for(var o=Array(r),s=0,n=0;n<i;n++)for(var a=arguments[n],c=0,u=a.length;c<u;c++,s++)o[s]=a[c];return o},Cm=function(r){return this instanceof Cm?(this.v=r,this):new Cm(r)},oj=function(r,n,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o=i.apply(r,n||[]),s,a=[];return s={},c("next"),c("throw"),c("return"),s[Symbol.asyncIterator]=function(){return this},s;function c(g){o[g]&&(s[g]=function(v){return new Promise(function(b,C){a.push([g,v,b,C])>1||u(g,v)})})}function u(g,v){try{d(o[g](v))}catch(b){p(a[0][3],b)}}function d(g){g.value instanceof Cm?Promise.resolve(g.value.v).then(l,f):p(a[0][2],g)}function l(g){u("next",g)}function f(g){u("throw",g)}function p(g,v){g(v),a.shift(),a.length&&u(a[0][0],a[0][1])}},sj=function(r){var n,i;return n={},o("next"),o("throw",function(s){throw s}),o("return"),n[Symbol.iterator]=function(){return this},n;function o(s,a){n[s]=r[s]?function(c){return(i=!i)?{value:Cm(r[s](c)),done:s==="return"}:a?a(c):c}:a}},aj=function(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r[Symbol.asyncIterator],i;return n?n.call(r):(r=typeof $I=="function"?$I(r):r[Symbol.iterator](),i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i);function o(a){i[a]=r[a]&&function(c){return new Promise(function(u,d){c=r[a](c),s(u,d,c.done,c.value)})}}function s(a,c,u,d){Promise.resolve(d).then(function(l){a({value:l,done:u})},c)}},cj=function(r,n){return Object.defineProperty?Object.defineProperty(r,"raw",{value:n}):r.raw=n,r},uj=function(r){if(r&&r.__esModule)return r;var n={};if(r!=null)for(var i in r)Object.hasOwnProperty.call(r,i)&&(n[i]=r[i]);return n.default=r,n},dj=function(r){return r&&r.__esModule?r:{default:r}},lj=function(r,n){if(!n.has(r))throw new TypeError("attempted to get private field on non-instance");return n.get(r)},fj=function(r,n,i){if(!n.has(r))throw new TypeError("attempted to set private field on non-instance");return n.set(r,i),i},t("__extends",KF),t("__assign",JF),t("__rest",XF),t("__decorate",YF),t("__param",QF),t("__metadata",ZF),t("__awaiter",ej),t("__generator",tj),t("__exportStar",rj),t("__createBinding",pj),t("__values",$I),t("__read",$2),t("__spread",nj),t("__spreadArrays",ij),t("__await",Cm),t("__asyncGenerator",oj),t("__asyncDelegator",sj),t("__asyncValues",aj),t("__makeTemplateObject",cj),t("__importStar",uj),t("__importDefault",dj),t("__classPrivateFieldGet",lj),t("__classPrivateFieldSet",fj)})});var jI={};wi(jI,{__assign:()=>Ove,__asyncDelegator:()=>Xve,__asyncGenerator:()=>Jve,__asyncValues:()=>Yve,__await:()=>Kve,__awaiter:()=>$ve,__classPrivateFieldGet:()=>txe,__classPrivateFieldSet:()=>rxe,__createBinding:()=>qve,__decorate:()=>Lve,__exportStar:()=>jve,__extends:()=>Nve,__generator:()=>Fve,__importDefault:()=>exe,__importStar:()=>Zve,__makeTemplateObject:()=>Qve,__metadata:()=>Uve,__param:()=>Hve,__read:()=>Vve,__rest:()=>Mve,__spread:()=>Gve,__spreadArrays:()=>zve,__values:()=>Wve});var hj,Nve,Ove,Mve,Lve,Hve,Uve,$ve,Fve,jve,qve,Wve,Vve,Gve,zve,Kve,Jve,Xve,Yve,Qve,Zve,exe,txe,rxe,qI=N(()=>{hj=tt(mj(),1),{__extends:Nve,__assign:Ove,__rest:Mve,__decorate:Lve,__param:Hve,__metadata:Uve,__awaiter:$ve,__generator:Fve,__exportStar:jve,__createBinding:qve,__values:Wve,__read:Vve,__spread:Gve,__spreadArrays:zve,__await:Kve,__asyncGenerator:Jve,__asyncDelegator:Xve,__asyncValues:Yve,__makeTemplateObject:Qve,__importStar:Zve,__importDefault:exe,__classPrivateFieldGet:txe,__classPrivateFieldSet:rxe}=hj.default});var q2=ce(j2=>{"use strict";Object.defineProperty(j2,"__esModule",{value:!0});var F2;(function(t){t[t.Transient=0]="Transient",t[t.Singleton=1]="Singleton",t[t.ResolutionScoped=2]="ResolutionScoped",t[t.ContainerScoped=3]="ContainerScoped"})(F2||(F2={}));j2.default=F2});var gj=ce(W2=>{"use strict";Object.defineProperty(W2,"__esModule",{value:!0});var nxe=q2();Object.defineProperty(W2,"Lifecycle",{enumerable:!0,get:function(){return nxe.default}})});var Zl=ce(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.defineInjectionTokenMetadata=as.getParamInfo=as.INJECTION_TOKEN_METADATA_KEY=void 0;as.INJECTION_TOKEN_METADATA_KEY="injectionTokens";function ixe(t){let e=Reflect.getMetadata("design:paramtypes",t)||[],r=Reflect.getOwnMetadata(as.INJECTION_TOKEN_METADATA_KEY,t)||{};return Object.keys(r).forEach(n=>{e[+n]=r[n]}),e}as.getParamInfo=ixe;function oxe(t,e){return function(r,n,i){let o=Reflect.getOwnMetadata(as.INJECTION_TOKEN_METADATA_KEY,r)||{};o[i]=e?{token:t,transform:e.transformToken,transformArgs:e.args||[]}:t,Reflect.defineMetadata(as.INJECTION_TOKEN_METADATA_KEY,o,r)}}as.defineInjectionTokenMetadata=oxe});var V2=ce(WI=>{"use strict";Object.defineProperty(WI,"__esModule",{value:!0});WI.isClassProvider=void 0;function sxe(t){return!!t.useClass}WI.isClassProvider=sxe});var G2=ce(VI=>{"use strict";Object.defineProperty(VI,"__esModule",{value:!0});VI.isFactoryProvider=void 0;function axe(t){return!!t.useFactory}VI.isFactoryProvider=axe});var zI=ce(Pm=>{"use strict";Object.defineProperty(Pm,"__esModule",{value:!0});Pm.delay=Pm.DelayedConstructor=void 0;var GI=class{constructor(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}createProxy(e){let r={},n=!1,i,o=()=>(n||(i=e(this.wrap()),n=!0),i);return new Proxy(r,this.createHandler(o))}createHandler(e){let r={},n=i=>{r[i]=(...o)=>{o[0]=e();let s=Reflect[i];return s(...o)}};return this.reflectMethods.forEach(n),r}};Pm.DelayedConstructor=GI;function cxe(t){if(typeof t>"u")throw new Error("Attempt to `delay` undefined. Constructor must be wrapped in a callback");return new GI(t)}Pm.delay=cxe});var KI=ce(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.isConstructorToken=ia.isTransformDescriptor=ia.isTokenDescriptor=ia.isNormalToken=void 0;var uxe=zI();function dxe(t){return typeof t=="string"||typeof t=="symbol"}ia.isNormalToken=dxe;function lxe(t){return typeof t=="object"&&"token"in t&&"multiple"in t}ia.isTokenDescriptor=lxe;function fxe(t){return typeof t=="object"&&"token"in t&&"transform"in t}ia.isTransformDescriptor=fxe;function pxe(t){return typeof t=="function"||t instanceof uxe.DelayedConstructor}ia.isConstructorToken=pxe});var z2=ce(JI=>{"use strict";Object.defineProperty(JI,"__esModule",{value:!0});JI.isTokenProvider=void 0;function mxe(t){return!!t.useToken}JI.isTokenProvider=mxe});var K2=ce(XI=>{"use strict";Object.defineProperty(XI,"__esModule",{value:!0});XI.isValueProvider=void 0;function hxe(t){return t.useValue!=null}XI.isValueProvider=hxe});var J2=ce(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var gxe=V2();Object.defineProperty(ef,"isClassProvider",{enumerable:!0,get:function(){return gxe.isClassProvider}});var yxe=G2();Object.defineProperty(ef,"isFactoryProvider",{enumerable:!0,get:function(){return yxe.isFactoryProvider}});var vxe=KI();Object.defineProperty(ef,"isNormalToken",{enumerable:!0,get:function(){return vxe.isNormalToken}});var xxe=z2();Object.defineProperty(ef,"isTokenProvider",{enumerable:!0,get:function(){return xxe.isTokenProvider}});var Sxe=K2();Object.defineProperty(ef,"isValueProvider",{enumerable:!0,get:function(){return Sxe.isValueProvider}})});var yj=ce(YI=>{"use strict";Object.defineProperty(YI,"__esModule",{value:!0});YI.isProvider=void 0;var bxe=V2(),wxe=K2(),Ixe=z2(),Exe=G2();function kxe(t){return bxe.isClassProvider(t)||wxe.isValueProvider(t)||Ixe.isTokenProvider(t)||Exe.isFactoryProvider(t)}YI.isProvider=kxe});var Q2=ce(Y2=>{"use strict";Object.defineProperty(Y2,"__esModule",{value:!0});var X2=class{constructor(){this._registryMap=new Map}entries(){return this._registryMap.entries()}getAll(e){return this.ensure(e),this._registryMap.get(e)}get(e){this.ensure(e);let r=this._registryMap.get(e);return r[r.length-1]||null}set(e,r){this.ensure(e),this._registryMap.get(e).push(r)}setAll(e,r){this._registryMap.set(e,r)}has(e){return this.ensure(e),this._registryMap.get(e).length>0}clear(){this._registryMap.clear()}ensure(e){this._registryMap.has(e)||this._registryMap.set(e,[])}};Y2.default=X2});var vj=ce(eD=>{"use strict";Object.defineProperty(eD,"__esModule",{value:!0});var Rxe=Q2(),Z2=class extends Rxe.default{};eD.default=Z2});var xj=ce(rD=>{"use strict";Object.defineProperty(rD,"__esModule",{value:!0});var tD=class{constructor(){this.scopedResolutions=new Map}};rD.default=tD});var nD=ce(QI=>{"use strict";Object.defineProperty(QI,"__esModule",{value:!0});QI.formatErrorCtor=void 0;function Axe(t,e){return t===null?`at position #${e}`:`"${t.split(",")[e].trim()}" at position #${e}`}function Cxe(t,e,r=" "){return[t,...e.message.split(`
23
+ `).map(n=>r+n)].join(`
24
+ `)}function Pxe(t,e,r){let[,n=null]=t.toString().match(/constructor\(([\w, ]+)\)/)||[],i=Axe(n,e);return Cxe(`Cannot inject the dependency ${i} of "${t.name}" constructor. Reason:`,r)}QI.formatErrorCtor=Pxe});var Sj=ce(ZI=>{"use strict";Object.defineProperty(ZI,"__esModule",{value:!0});ZI.isDisposable=void 0;function _xe(t){return!(typeof t.dispose!="function"||t.dispose.length>0)}ZI.isDisposable=_xe});var wj=ce(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});tf.PostResolutionInterceptors=tf.PreResolutionInterceptors=void 0;var bj=Q2(),eE=class extends bj.default{};tf.PreResolutionInterceptors=eE;var tE=class extends bj.default{};tf.PostResolutionInterceptors=tE;var iD=class{constructor(){this.preResolution=new eE,this.postResolution=new tE}};tf.default=iD});var id=ce(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.instance=yc.typeInfo=void 0;var Txe=(qI(),Vi(jI)),hi=J2(),Dxe=yj(),rE=KI(),Bxe=vj(),Di=q2(),nE=xj(),Nxe=nD(),Oxe=zI(),Mxe=Sj(),Lxe=wj();yc.typeInfo=new Map;var oD=class t{constructor(e){this.parent=e,this._registry=new Bxe.default,this.interceptors=new Lxe.default,this.disposed=!1,this.disposables=new Set}register(e,r,n={lifecycle:Di.default.Transient}){this.ensureNotDisposed();let i;if(Dxe.isProvider(r)?i=r:i={useClass:r},hi.isTokenProvider(i)){let o=[e],s=i;for(;s!=null;){let a=s.useToken;if(o.includes(a))throw new Error(`Token registration cycle detected! ${[...o,a].join(" -> ")}`);o.push(a);let c=this._registry.get(a);c&&hi.isTokenProvider(c.provider)?s=c.provider:s=null}}if((n.lifecycle===Di.default.Singleton||n.lifecycle==Di.default.ContainerScoped||n.lifecycle==Di.default.ResolutionScoped)&&(hi.isValueProvider(i)||hi.isFactoryProvider(i)))throw new Error(`Cannot use lifecycle "${Di.default[n.lifecycle]}" with ValueProviders or FactoryProviders`);return this._registry.set(e,{provider:i,options:n}),this}registerType(e,r){return this.ensureNotDisposed(),hi.isNormalToken(r)?this.register(e,{useToken:r}):this.register(e,{useClass:r})}registerInstance(e,r){return this.ensureNotDisposed(),this.register(e,{useValue:r})}registerSingleton(e,r){if(this.ensureNotDisposed(),hi.isNormalToken(e)){if(hi.isNormalToken(r))return this.register(e,{useToken:r},{lifecycle:Di.default.Singleton});if(r)return this.register(e,{useClass:r},{lifecycle:Di.default.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}let n=e;return r&&!hi.isNormalToken(r)&&(n=r),this.register(e,{useClass:n},{lifecycle:Di.default.Singleton})}resolve(e,r=new nE.default,n=!1){this.ensureNotDisposed();let i=this.getRegistration(e);if(!i&&hi.isNormalToken(e)){if(n)return;throw new Error(`Attempted to resolve unregistered dependency token: "${e.toString()}"`)}if(this.executePreResolutionInterceptor(e,"Single"),i){let o=this.resolveRegistration(i,r);return this.executePostResolutionInterceptor(e,o,"Single"),o}if(rE.isConstructorToken(e)){let o=this.construct(e,r);return this.executePostResolutionInterceptor(e,o,"Single"),o}throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")}executePreResolutionInterceptor(e,r){if(this.interceptors.preResolution.has(e)){let n=[];for(let i of this.interceptors.preResolution.getAll(e))i.options.frequency!="Once"&&n.push(i),i.callback(e,r);this.interceptors.preResolution.setAll(e,n)}}executePostResolutionInterceptor(e,r,n){if(this.interceptors.postResolution.has(e)){let i=[];for(let o of this.interceptors.postResolution.getAll(e))o.options.frequency!="Once"&&i.push(o),o.callback(e,r,n);this.interceptors.postResolution.setAll(e,i)}}resolveRegistration(e,r){if(this.ensureNotDisposed(),e.options.lifecycle===Di.default.ResolutionScoped&&r.scopedResolutions.has(e))return r.scopedResolutions.get(e);let n=e.options.lifecycle===Di.default.Singleton,i=e.options.lifecycle===Di.default.ContainerScoped,o=n||i,s;return hi.isValueProvider(e.provider)?s=e.provider.useValue:hi.isTokenProvider(e.provider)?s=o?e.instance||(e.instance=this.resolve(e.provider.useToken,r)):this.resolve(e.provider.useToken,r):hi.isClassProvider(e.provider)?s=o?e.instance||(e.instance=this.construct(e.provider.useClass,r)):this.construct(e.provider.useClass,r):hi.isFactoryProvider(e.provider)?s=e.provider.useFactory(this):s=this.construct(e.provider,r),e.options.lifecycle===Di.default.ResolutionScoped&&r.scopedResolutions.set(e,s),s}resolveAll(e,r=new nE.default,n=!1){this.ensureNotDisposed();let i=this.getAllRegistrations(e);if(!i&&hi.isNormalToken(e)){if(n)return[];throw new Error(`Attempted to resolve unregistered dependency token: "${e.toString()}"`)}if(this.executePreResolutionInterceptor(e,"All"),i){let s=i.map(a=>this.resolveRegistration(a,r));return this.executePostResolutionInterceptor(e,s,"All"),s}let o=[this.construct(e,r)];return this.executePostResolutionInterceptor(e,o,"All"),o}isRegistered(e,r=!1){return this.ensureNotDisposed(),this._registry.has(e)||r&&(this.parent||!1)&&this.parent.isRegistered(e,!0)}reset(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()}clearInstances(){this.ensureNotDisposed();for(let[e,r]of this._registry.entries())this._registry.setAll(e,r.filter(n=>!hi.isValueProvider(n.provider)).map(n=>(n.instance=void 0,n)))}createChildContainer(){this.ensureNotDisposed();let e=new t(this);for(let[r,n]of this._registry.entries())n.some(({options:i})=>i.lifecycle===Di.default.ContainerScoped)&&e._registry.setAll(r,n.map(i=>i.options.lifecycle===Di.default.ContainerScoped?{provider:i.provider,options:i.options}:i));return e}beforeResolution(e,r,n={frequency:"Always"}){this.interceptors.preResolution.set(e,{callback:r,options:n})}afterResolution(e,r,n={frequency:"Always"}){this.interceptors.postResolution.set(e,{callback:r,options:n})}dispose(){return Txe.__awaiter(this,void 0,void 0,function*(){this.disposed=!0;let e=[];this.disposables.forEach(r=>{let n=r.dispose();n&&e.push(n)}),yield Promise.all(e)})}getRegistration(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null}getAllRegistrations(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null}construct(e,r){if(e instanceof Oxe.DelayedConstructor)return e.createProxy(i=>this.resolve(i,r));let n=(()=>{let i=yc.typeInfo.get(e);if(!i||i.length===0){if(e.length===0)return new e;throw new Error(`TypeInfo not known for "${e.name}"`)}let o=i.map(this.resolveParams(r,e));return new e(...o)})();return Mxe.isDisposable(n)&&this.disposables.add(n),n}resolveParams(e,r){return(n,i)=>{try{return rE.isTokenDescriptor(n)?rE.isTransformDescriptor(n)?n.multiple?this.resolve(n.transform).transform(this.resolveAll(n.token,new nE.default,n.isOptional),...n.transformArgs):this.resolve(n.transform).transform(this.resolve(n.token,e,n.isOptional),...n.transformArgs):n.multiple?this.resolveAll(n.token,new nE.default,n.isOptional):this.resolve(n.token,e,n.isOptional):rE.isTransformDescriptor(n)?this.resolve(n.transform,e).transform(this.resolve(n.token,e),...n.transformArgs):this.resolve(n,e)}catch(o){throw new Error(Nxe.formatErrorCtor(r,i,o))}}}ensureNotDisposed(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")}};yc.instance=new oD;yc.default=yc.instance});var Ij=ce(aD=>{"use strict";Object.defineProperty(aD,"__esModule",{value:!0});var Hxe=Zl(),vc=id(),sD=KI(),Uxe=nD();function $xe(){return function(t){let e=Hxe.getParamInfo(t);return class extends t{constructor(...r){super(...r.concat(e.slice(r.length).map((n,i)=>{try{return sD.isTokenDescriptor(n)?sD.isTransformDescriptor(n)?n.multiple?vc.instance.resolve(n.transform).transform(vc.instance.resolveAll(n.token),...n.transformArgs):vc.instance.resolve(n.transform).transform(vc.instance.resolve(n.token),...n.transformArgs):n.multiple?vc.instance.resolveAll(n.token):vc.instance.resolve(n.token):sD.isTransformDescriptor(n)?vc.instance.resolve(n.transform).transform(vc.instance.resolve(n.token),...n.transformArgs):vc.instance.resolve(n)}catch(o){let s=i+r.length;throw new Error(Uxe.formatErrorCtor(t,s,o))}})))}}}}aD.default=$xe});var Ej=ce(cD=>{"use strict";Object.defineProperty(cD,"__esModule",{value:!0});var Fxe=Zl();function jxe(t,e){let r={token:t,multiple:!1,isOptional:e&&e.isOptional};return Fxe.defineInjectionTokenMetadata(r)}cD.default=jxe});var iE=ce(uD=>{"use strict";Object.defineProperty(uD,"__esModule",{value:!0});var qxe=Zl(),Wxe=id(),kj=id();function Vxe(t){return function(e){Wxe.typeInfo.set(e,qxe.getParamInfo(e)),t&&t.token&&(Array.isArray(t.token)?t.token.forEach(r=>{kj.instance.register(r,e)}):kj.instance.register(t.token,e))}}uD.default=Vxe});var Rj=ce(dD=>{"use strict";Object.defineProperty(dD,"__esModule",{value:!0});var Gxe=(qI(),Vi(jI)),zxe=id();function Kxe(t=[]){return function(e){return t.forEach(r=>{var{token:n,options:i}=r,o=Gxe.__rest(r,["token","options"]);return zxe.instance.register(n,o,i)}),e}}dD.default=Kxe});var Aj=ce(lD=>{"use strict";Object.defineProperty(lD,"__esModule",{value:!0});var Jxe=iE(),Xxe=id();function Yxe(){return function(t){Jxe.default()(t),Xxe.instance.registerSingleton(t)}}lD.default=Yxe});var Cj=ce(fD=>{"use strict";Object.defineProperty(fD,"__esModule",{value:!0});var Qxe=Zl();function Zxe(t,e){let r={token:t,multiple:!0,isOptional:e&&e.isOptional};return Qxe.defineInjectionTokenMetadata(r)}fD.default=Zxe});var Pj=ce(pD=>{"use strict";Object.defineProperty(pD,"__esModule",{value:!0});var eSe=Zl();function tSe(t,e,...r){let n={token:t,multiple:!0,transform:e,transformArgs:r};return eSe.defineInjectionTokenMetadata(n)}pD.default=tSe});var _j=ce(mD=>{"use strict";Object.defineProperty(mD,"__esModule",{value:!0});var rSe=Zl();function nSe(t,e,...r){return rSe.defineInjectionTokenMetadata(t,{transformToken:e,args:r})}mD.default=nSe});var Tj=ce(hD=>{"use strict";Object.defineProperty(hD,"__esModule",{value:!0});var iSe=iE(),oSe=id();function sSe(t,e){return function(r){iSe.default()(r),oSe.instance.register(e||r,r,{lifecycle:t})}}hD.default=sSe});var Dj=ce(cs=>{"use strict";Object.defineProperty(cs,"__esModule",{value:!0});var aSe=Ij();Object.defineProperty(cs,"autoInjectable",{enumerable:!0,get:function(){return aSe.default}});var cSe=Ej();Object.defineProperty(cs,"inject",{enumerable:!0,get:function(){return cSe.default}});var uSe=iE();Object.defineProperty(cs,"injectable",{enumerable:!0,get:function(){return uSe.default}});var dSe=Rj();Object.defineProperty(cs,"registry",{enumerable:!0,get:function(){return dSe.default}});var lSe=Aj();Object.defineProperty(cs,"singleton",{enumerable:!0,get:function(){return lSe.default}});var fSe=Cj();Object.defineProperty(cs,"injectAll",{enumerable:!0,get:function(){return fSe.default}});var pSe=Pj();Object.defineProperty(cs,"injectAllWithTransform",{enumerable:!0,get:function(){return pSe.default}});var mSe=_j();Object.defineProperty(cs,"injectWithTransform",{enumerable:!0,get:function(){return mSe.default}});var hSe=Tj();Object.defineProperty(cs,"scoped",{enumerable:!0,get:function(){return hSe.default}})});var Bj=ce(gD=>{"use strict";Object.defineProperty(gD,"__esModule",{value:!0});function gSe(t){let e;return r=>(e==null&&(e=t(r)),e)}gD.default=gSe});var Nj=ce(yD=>{"use strict";Object.defineProperty(yD,"__esModule",{value:!0});function ySe(t){let e=new WeakMap;return r=>{let n=e.get(r);return n==null&&(n=t(r),e.set(r,n)),n}}yD.default=ySe});var Oj=ce(vD=>{"use strict";Object.defineProperty(vD,"__esModule",{value:!0});function vSe(t,e,r,n=!0){let i,o;return s=>{let a=t(s);return(!n||o!==a)&&((o=a)?i=s.resolve(e):i=s.resolve(r)),i}}vD.default=vSe});var Mj=ce(Fy=>{"use strict";Object.defineProperty(Fy,"__esModule",{value:!0});var xSe=Bj();Object.defineProperty(Fy,"instanceCachingFactory",{enumerable:!0,get:function(){return xSe.default}});var SSe=Nj();Object.defineProperty(Fy,"instancePerContainerCachingFactory",{enumerable:!0,get:function(){return SSe.default}});var bSe=Oj();Object.defineProperty(Fy,"predicateAwareClassFactory",{enumerable:!0,get:function(){return bSe.default}})});var Lj=ce(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var xD=(qI(),Vi(jI));if(typeof Reflect>"u"||!Reflect.getMetadata)throw new Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`);var wSe=gj();Object.defineProperty(od,"Lifecycle",{enumerable:!0,get:function(){return wSe.Lifecycle}});xD.__exportStar(Dj(),od);xD.__exportStar(Mj(),od);xD.__exportStar(J2(),od);var ISe=zI();Object.defineProperty(od,"delay",{enumerable:!0,get:function(){return ISe.delay}});var ESe=id();Object.defineProperty(od,"container",{enumerable:!0,get:function(){return ESe.instance}})});var SD,rf,Hj,bD=N(()=>{fe();ae();rf=class{attrId="";attrValues=[];constructor(e={}){Object.assign(e)}};h([x({type:k.ObjectIdentifier})],rf.prototype,"attrId",void 0);h([x({type:k.Any,repeated:"set"})],rf.prototype,"attrValues",void 0);Hj=SD=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,SD.prototype)}};Hj=SD=h([W({type:L.Sequence,itemType:rf})],Hj)});var wD,Uj,$j=N(()=>{fe();ae();Ny();Uj=wD=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,wD.prototype)}};Uj=wD=h([W({type:L.Sequence,itemType:Oo})],Uj)});var kSe,RSe,Fj,_m,AWe,CWe,PWe,_We,TWe,DWe,nf,ID=N(()=>{kSe="1.2.840.113549",RSe=`${kSe}.1`,Fj=`${RSe}.12`,_m=`${Fj}.1`,AWe=`${_m}.1`,CWe=`${_m}.2`,PWe=`${_m}.3`,_We=`${_m}.4`,TWe=`${_m}.5`,DWe=`${_m}.6`,nf=`${Fj}.10.1`});var OWe,MWe,LWe,HWe,UWe,$We,oE,sE=N(()=>{ID();OWe=`${nf}.1`,MWe=`${nf}.2`,LWe=`${nf}.3`,HWe=`${nf}.4`,UWe=`${nf}.5`,$We=`${nf}.6`,oE="1.2.840.113549.1.9"});var aE,jj,VWe,GWe,qj=N(()=>{fe();ae();sE();aE=class{certId="";certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],aE.prototype,"certId",void 0);h([x({type:k.Any,context:0})],aE.prototype,"certValue",void 0);jj=`${oE}.22`,VWe=`${jj}.1`,GWe=`${jj}.2`});var cE,ASe,YWe,Wj=N(()=>{fe();ae();sE();cE=class{crlId="";crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],cE.prototype,"crlId",void 0);h([x({type:k.Any,context:0})],cE.prototype,"crltValue",void 0);ASe=`${oE}.23`,YWe=`${ASe}.1`});var uE,sd,Vj=N(()=>{fe();ae();zt();uE=class extends rt{},sd=class{encryptionAlgorithm=new Me;encryptedData=new uE;constructor(e={}){Object.assign(this,e)}};h([x({type:Me})],sd.prototype,"encryptionAlgorithm",void 0);h([x({type:uE})],sd.prototype,"encryptedData",void 0)});var ED,kD,dE,RD,ad,Gj=N(()=>{fe();ae();zt();(function(t){t[t.v1=0]="v1"})(kD||(kD={}));dE=class extends rt{},RD=ED=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,ED.prototype)}};RD=ED=h([W({type:L.Sequence,itemType:li})],RD);ad=class{version=kD.v1;privateKeyAlgorithm=new Me;privateKey=new dE;attributes;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer})],ad.prototype,"version",void 0);h([x({type:Me})],ad.prototype,"privateKeyAlgorithm",void 0);h([x({type:dE})],ad.prototype,"privateKey",void 0);h([x({type:RD,implicit:!0,context:0,optional:!0})],ad.prototype,"attributes",void 0)});var lE=N(()=>{Vj();Gj()});var zj,Kj=N(()=>{fe();lE();ae();zj=class extends ad{};zj=h([W({type:L.Sequence})],zj)});var Jj,Xj=N(()=>{fe();lE();ae();Jj=class extends sd{};Jj=h([W({type:L.Sequence})],Jj)});var fE,Yj=N(()=>{fe();ae();fE=class{secretTypeId="";secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],fE.prototype,"secretTypeId",void 0);h([x({type:k.Any,context:0})],fE.prototype,"secretValue",void 0)});var Qj=N(()=>{qj();Wj();Kj();Xj();Yj();sE()});var cd,AD=N(()=>{fe();U2();ae();cd=class{mac=new nd;macSalt=new rt;iterations=1;constructor(e={}){Object.assign(this,e)}};h([x({type:nd})],cd.prototype,"mac",void 0);h([x({type:rt})],cd.prototype,"macSalt",void 0);h([x({type:k.Integer,defaultValue:1})],cd.prototype,"iterations",void 0)});var of,Zj=N(()=>{fe();ae();Ny();AD();of=class{version=3;authSafe=new Oo;macData=new cd;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer})],of.prototype,"version",void 0);h([x({type:Oo})],of.prototype,"authSafe",void 0);h([x({type:cd,optional:!0})],of.prototype,"macData",void 0)});var CD,Tm,eq,tq=N(()=>{fe();ae();bD();Tm=class{bagId="";bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}};h([x({type:k.ObjectIdentifier})],Tm.prototype,"bagId",void 0);h([x({type:k.Any,context:0})],Tm.prototype,"bagValue",void 0);h([x({type:rf,repeated:"set",optional:!0})],Tm.prototype,"bagAttributes",void 0);eq=CD=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,CD.prototype)}};eq=CD=h([W({type:L.Sequence,itemType:Tm})],eq)});var rq=N(()=>{bD();$j();Qj();AD();ID();Zj();tq()});var nq={};wi(nq,{ChallengePassword:()=>WD,ContentType:()=>gE,CounterSignature:()=>qD,CountryOfCitizenship:()=>qy,CountryOfResidence:()=>HD,DateOfBirth:()=>mE,EmailAddress:()=>pE,EncryptedPrivateKeyInfo:()=>ND,ExtendedCertificateAttributes:()=>GD,ExtensionRequest:()=>VD,FriendlyName:()=>vE,Gender:()=>hE,LocalKeyId:()=>zD,MessageDigest:()=>$D,PKCS9String:()=>jy,Pkcs7PDU:()=>DD,PlaceOfBirth:()=>LD,Pseudonym:()=>UD,RandomNonce:()=>jD,SMIMECapabilities:()=>JD,SMIMECapability:()=>xE,SequenceNumber:()=>yE,SigningDescription:()=>KD,SigningTime:()=>FD,UnstructuredAddress:()=>MD,UnstructuredName:()=>OD,UserPKCS12:()=>BD,crlTypes:()=>dbe,id_at_pseudonym:()=>lbe,id_certTypes:()=>ube,id_ietf_at:()=>Bm,id_pkcs9:()=>Nr,id_pkcs9_at:()=>Dm,id_pkcs9_at_challengePassword:()=>USe,id_pkcs9_at_contentType:()=>OSe,id_pkcs9_at_counterSignature:()=>HSe,id_pkcs9_at_countryOfCitizenship:()=>rbe,id_pkcs9_at_countryOfResidence:()=>nbe,id_pkcs9_at_dateOfBirth:()=>ZSe,id_pkcs9_at_emailAddress:()=>BSe,id_pkcs9_at_encryptedPrivateKeyInfo:()=>JSe,id_pkcs9_at_extendedCertificateAttributes:()=>FSe,id_pkcs9_at_extensionRequest:()=>qSe,id_pkcs9_at_friendlyName:()=>VSe,id_pkcs9_at_gender:()=>tbe,id_pkcs9_at_localKeyId:()=>GSe,id_pkcs9_at_messageDigest:()=>MSe,id_pkcs9_at_pkcs15Token:()=>KSe,id_pkcs9_at_pkcs7PDU:()=>QSe,id_pkcs9_at_placeOfBirth:()=>ebe,id_pkcs9_at_randomNonce:()=>XSe,id_pkcs9_at_sequenceNumber:()=>YSe,id_pkcs9_at_signingDescription:()=>jSe,id_pkcs9_at_signingTime:()=>LSe,id_pkcs9_at_smimeCapabilities:()=>WSe,id_pkcs9_at_unstructuredAddress:()=>$Se,id_pkcs9_at_unstructuredName:()=>NSe,id_pkcs9_at_userPKCS12:()=>zSe,id_pkcs9_mo:()=>_Se,id_pkcs9_mr:()=>QD,id_pkcs9_mr_caseIgnoreMatch:()=>sbe,id_pkcs9_mr_signingTimeMatch:()=>abe,id_pkcs9_oc:()=>XD,id_pkcs9_oc_naturalPerson:()=>DSe,id_pkcs9_oc_pkcsEntity:()=>TSe,id_pkcs9_sx:()=>YD,id_pkcs9_sx_pkcs9String:()=>ibe,id_pkcs9_sx_signingTime:()=>obe,id_smime:()=>cbe});var PD,_D,TD,Nr,_Se,XD,Dm,YD,QD,TSe,DSe,BSe,NSe,OSe,MSe,LSe,HSe,USe,$Se,FSe,jSe,qSe,WSe,VSe,GSe,zSe,KSe,JSe,XSe,YSe,QSe,Bm,ZSe,ebe,tbe,rbe,nbe,ibe,obe,sbe,abe,cbe,ube,dbe,lbe,jy,DD,BD,ND,pE,OD,MD,mE,LD,hE,qy,HD,UD,gE,$D,FD,jD,yE,qD,WD,VD,GD,vE,zD,KD,xE,JD,iq=N(()=>{fe();ae();Ny();rq();lE();zt();VT();Nr="1.2.840.113549.1.9",_Se=`${Nr}.0`,XD=`${Nr}.24`,Dm=`${Nr}.25`,YD=`${Nr}.26`,QD=`${Nr}.27`,TSe=`${XD}.1`,DSe=`${XD}.2`,BSe=`${Nr}.1`,NSe=`${Nr}.2`,OSe=`${Nr}.3`,MSe=`${Nr}.4`,LSe=`${Nr}.5`,HSe=`${Nr}.6`,USe=`${Nr}.7`,$Se=`${Nr}.8`,FSe=`${Nr}.9`,jSe=`${Nr}.13`,qSe=`${Nr}.14`,WSe=`${Nr}.15`,VSe=`${Nr}.20`,GSe=`${Nr}.21`,zSe="2.16.840.1.113730.3.1.216",KSe=`${Dm}.1`,JSe=`${Dm}.2`,XSe=`${Dm}.3`,YSe=`${Dm}.4`,QSe=`${Dm}.5`,Bm="1.3.6.1.5.5.7.9",ZSe=`${Bm}.1`,ebe=`${Bm}.2`,tbe=`${Bm}.3`,rbe=`${Bm}.4`,nbe=`${Bm}.5`,ibe=`${YD}.1`,obe=`${YD}.2`,sbe=`${QD}.1`,abe=`${QD}.2`,cbe=`${Nr}.16`,ube=`${Nr}.22`,dbe=`${Nr}.23`,lbe=`${FT}.65`,jy=class extends on{ia5String;constructor(e={}){super(e)}toString(){return{}.toString(),this.ia5String||super.toString()}};h([x({type:k.IA5String})],jy.prototype,"ia5String",void 0);jy=h([W({type:L.Choice})],jy);DD=class extends Oo{};DD=h([W({type:L.Sequence})],DD);BD=class extends of{};BD=h([W({type:L.Sequence})],BD);ND=class extends sd{};ND=h([W({type:L.Sequence})],ND);pE=class{value;constructor(e=""){this.value=e}toString(){return this.value}};h([x({type:k.IA5String})],pE.prototype,"value",void 0);pE=h([W({type:L.Choice})],pE);OD=class extends jy{};OD=h([W({type:L.Choice})],OD);MD=class extends on{};MD=h([W({type:L.Choice})],MD);mE=class{value;constructor(e=new Date){this.value=e}};h([x({type:k.GeneralizedTime})],mE.prototype,"value",void 0);mE=h([W({type:L.Choice})],mE);LD=class extends on{};LD=h([W({type:L.Choice})],LD);hE=class{value;constructor(e="M"){this.value=e}toString(){return this.value}};h([x({type:k.PrintableString})],hE.prototype,"value",void 0);hE=h([W({type:L.Choice})],hE);qy=class{value;constructor(e=""){this.value=e}toString(){return this.value}};h([x({type:k.PrintableString})],qy.prototype,"value",void 0);qy=h([W({type:L.Choice})],qy);HD=class extends qy{};HD=h([W({type:L.Choice})],HD);UD=class extends on{};UD=h([W({type:L.Choice})],UD);gE=class{value;constructor(e=""){this.value=e}toString(){return this.value}};h([x({type:k.ObjectIdentifier})],gE.prototype,"value",void 0);gE=h([W({type:L.Choice})],gE);$D=class extends rt{},FD=class extends Wr{};FD=h([W({type:L.Choice})],FD);jD=class extends rt{},yE=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};h([x({type:k.Integer})],yE.prototype,"value",void 0);yE=h([W({type:L.Choice})],yE);qD=class extends pi{};qD=h([W({type:L.Sequence})],qD);WD=class extends on{};WD=h([W({type:L.Choice})],WD);VD=PD=class extends lc{constructor(e){super(e),Object.setPrototypeOf(this,PD.prototype)}};VD=PD=h([W({type:L.Sequence})],VD);GD=_D=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,_D.prototype)}};GD=_D=h([W({type:L.Set,itemType:Do})],GD);vE=class{value;constructor(e=""){this.value=e}toString(){return this.value}};h([x({type:k.BmpString})],vE.prototype,"value",void 0);vE=h([W({type:L.Choice})],vE);zD=class extends rt{},KD=class extends on{},xE=class extends Me{};xE=h([W({type:L.Sequence})],xE);JD=TD=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,TD.prototype)}};JD=TD=h([W({type:L.Sequence,itemType:xE})],JD)});var ZD,Nm,eB=N(()=>{fe();ae();zt();Nm=ZD=class extends Ze{constructor(e){super(e),Object.setPrototypeOf(this,ZD.prototype)}};Nm=ZD=h([W({type:L.Sequence,itemType:li})],Nm)});var oa,tB=N(()=>{fe();ae();zt();eB();oa=class{version=0;subject=new gn;subjectPKInfo=new is;attributes=new Nm;constructor(e={}){Object.assign(this,e)}};h([x({type:k.Integer})],oa.prototype,"version",void 0);h([x({type:gn})],oa.prototype,"subject",void 0);h([x({type:is})],oa.prototype,"subjectPKInfo",void 0);h([x({type:Nm,implicit:!0,context:0,optional:!0})],oa.prototype,"attributes",void 0)});var Om,oq=N(()=>{fe();ae();zt();tB();Om=class{certificationRequestInfo=new oa;certificationRequestInfoRaw;signatureAlgorithm=new Me;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}};h([x({type:oa,raw:!0})],Om.prototype,"certificationRequestInfo",void 0);h([x({type:Me})],Om.prototype,"signatureAlgorithm",void 0);h([x({type:k.BitString})],Om.prototype,"signature",void 0)});var sq={};wi(sq,{Attributes:()=>Nm,CertificationRequest:()=>Om,CertificationRequestInfo:()=>oa});var aq=N(()=>{eB();oq();tB()});var Vq=ce(_e=>{"use strict";R9();var ne=(ae(),Vi(r7)),Je=(zt(),Vi(IT)),Se=p_(),ie=(fe(),Vi(D7)),fbe=(Ny(),Vi(u2)),BE=(UF(),Vi(HF)),Ni=(U2(),Vi(zF)),yr=Lj(),cB=(iq(),Vi(nq)),NE=(aq(),Vi(sq));function Dv(t){var e=Object.create(null);return t&&Object.keys(t).forEach(function(r){if(r!=="default"){var n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}),e.default=t,Object.freeze(e)}var re=Dv(Je),Bi=Dv(fbe),Er=Dv(BE),gr=Dv(Ni),qm=Dv(cB),Km="crypto.algorithm",OE=class{getAlgorithms(){return yr.container.resolveAll(Km)}toAsnAlgorithm(e){({...e});for(let r of this.getAlgorithms()){let n=r.toAsnAlgorithm(e);if(n)return n}if(/^[0-9.]+$/.test(e.name)){let r=new Je.AlgorithmIdentifier({algorithm:e.name});if("parameters"in e){let n=e;r.parameters=n.parameters}return r}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(let n of this.getAlgorithms()){let i=n.toWebAlgorithm(e);if(i)return i}return{name:e.algorithm,parameters:e.parameters}}},ls="crypto.algorithmProvider";yr.container.registerSingleton(ls,OE);var wE,Hi="1.3.36.3.3.2.8.1.1",cq=`${Hi}.1`,uq=`${Hi}.2`,dq=`${Hi}.3`,lq=`${Hi}.4`,fq=`${Hi}.5`,pq=`${Hi}.6`,mq=`${Hi}.7`,hq=`${Hi}.8`,gq=`${Hi}.9`,yq=`${Hi}.10`,vq=`${Hi}.11`,xq=`${Hi}.12`,Sq=`${Hi}.13`,bq=`${Hi}.14`,wq="brainpoolP160r1",Iq="brainpoolP160t1",Eq="brainpoolP192r1",kq="brainpoolP192t1",Rq="brainpoolP224r1",Aq="brainpoolP224t1",Cq="brainpoolP256r1",Pq="brainpoolP256t1",_q="brainpoolP320r1",Tq="brainpoolP320t1",Dq="brainpoolP384r1",Bq="brainpoolP384t1",Nq="brainpoolP512r1",Oq="brainpoolP512t1",Or="ECDSA";_e.EcAlgorithm=wE=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case Or.toLowerCase():if("hash"in e)switch((typeof e.hash=="string"?e.hash:e.hash.name).toLowerCase()){case"sha-1":return Er.ecdsaWithSHA1;case"sha-256":return Er.ecdsaWithSHA256;case"sha-384":return Er.ecdsaWithSHA384;case"sha-512":return Er.ecdsaWithSHA512}else if("namedCurve"in e){let r="";switch(e.namedCurve){case"P-256":r=Er.id_secp256r1;break;case"K-256":r=wE.SECP256K1;break;case"P-384":r=Er.id_secp384r1;break;case"P-521":r=Er.id_secp521r1;break;case wq:r=cq;break;case Iq:r=uq;break;case Eq:r=dq;break;case kq:r=lq;break;case Rq:r=fq;break;case Aq:r=pq;break;case Cq:r=mq;break;case Pq:r=hq;break;case _q:r=gq;break;case Tq:r=yq;break;case Dq:r=vq;break;case Bq:r=xq;break;case Nq:r=Sq;break;case Oq:r=bq;break}if(r)return new Je.AlgorithmIdentifier({algorithm:Er.id_ecPublicKey,parameters:ne.AsnConvert.serialize(new Er.ECParameters({namedCurve:r}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case Er.id_ecdsaWithSHA1:return{name:Or,hash:{name:"SHA-1"}};case Er.id_ecdsaWithSHA256:return{name:Or,hash:{name:"SHA-256"}};case Er.id_ecdsaWithSHA384:return{name:Or,hash:{name:"SHA-384"}};case Er.id_ecdsaWithSHA512:return{name:Or,hash:{name:"SHA-512"}};case Er.id_ecPublicKey:{if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(ne.AsnConvert.parse(e.parameters,Er.ECParameters).namedCurve){case Er.id_secp256r1:return{name:Or,namedCurve:"P-256"};case wE.SECP256K1:return{name:Or,namedCurve:"K-256"};case Er.id_secp384r1:return{name:Or,namedCurve:"P-384"};case Er.id_secp521r1:return{name:Or,namedCurve:"P-521"};case cq:return{name:Or,namedCurve:wq};case uq:return{name:Or,namedCurve:Iq};case dq:return{name:Or,namedCurve:Eq};case lq:return{name:Or,namedCurve:kq};case fq:return{name:Or,namedCurve:Rq};case pq:return{name:Or,namedCurve:Aq};case mq:return{name:Or,namedCurve:Cq};case hq:return{name:Or,namedCurve:Pq};case gq:return{name:Or,namedCurve:_q};case yq:return{name:Or,namedCurve:Tq};case vq:return{name:Or,namedCurve:Dq};case xq:return{name:Or,namedCurve:Bq};case Sq:return{name:Or,namedCurve:Nq};case bq:return{name:Or,namedCurve:Oq}}}}return null}};_e.EcAlgorithm.SECP256K1="1.3.132.0.10";_e.EcAlgorithm=wE=ie.__decorate([yr.injectable()],_e.EcAlgorithm);yr.container.registerSingleton(Km,_e.EcAlgorithm);var Fq=Symbol("name"),jq=Symbol("value"),Ut=class{constructor(e,r={},n=""){this[Fq]=e,this[jq]=n;for(let i in r)this[i]=r[i]}};Ut.NAME=Fq;Ut.VALUE=jq;var ME=class{static toTextObject(e){let r=new Ut("Algorithm Identifier",{},Mo.toString(e.algorithm));if(e.parameters)if(e.algorithm===Er.id_ecPublicKey){let n=new _e.EcAlgorithm().toWebAlgorithm(e);n&&"namedCurve"in n?r["Named Curve"]=n.namedCurve:r.Parameters=e.parameters}else r.Parameters=e.parameters;return r}},Mo=class{static toString(e){let r=this.items[e];return r||e}};Mo.items={[gr.id_sha1]:"sha1",[gr.id_sha224]:"sha224",[gr.id_sha256]:"sha256",[gr.id_sha384]:"sha384",[gr.id_sha512]:"sha512",[gr.id_rsaEncryption]:"rsaEncryption",[gr.id_sha1WithRSAEncryption]:"sha1WithRSAEncryption",[gr.id_sha224WithRSAEncryption]:"sha224WithRSAEncryption",[gr.id_sha256WithRSAEncryption]:"sha256WithRSAEncryption",[gr.id_sha384WithRSAEncryption]:"sha384WithRSAEncryption",[gr.id_sha512WithRSAEncryption]:"sha512WithRSAEncryption",[Er.id_ecPublicKey]:"ecPublicKey",[Er.id_ecdsaWithSHA1]:"ecdsaWithSHA1",[Er.id_ecdsaWithSHA224]:"ecdsaWithSHA224",[Er.id_ecdsaWithSHA256]:"ecdsaWithSHA256",[Er.id_ecdsaWithSHA384]:"ecdsaWithSHA384",[Er.id_ecdsaWithSHA512]:"ecdsaWithSHA512",[re.id_kp_serverAuth]:"TLS WWW server authentication",[re.id_kp_clientAuth]:"TLS WWW client authentication",[re.id_kp_codeSigning]:"Code Signing",[re.id_kp_emailProtection]:"E-mail Protection",[re.id_kp_timeStamping]:"Time Stamping",[re.id_kp_OCSPSigning]:"OCSP Signing",[Bi.id_signedData]:"Signed Data"};var fs=class{static serialize(e){return this.serializeObj(e).join(`
25
+ `)}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,r=0){let n=[],i=this.pad(r++),o="",s=e[Ut.VALUE];s&&(o=` ${s}`),n.push(`${i}${e[Ut.NAME]}:${o}`),i=this.pad(r);for(let a in e){if(typeof a=="symbol")continue;let c=e[a],u=a?`${a}: `:"";if(typeof c=="string"||typeof c=="number"||typeof c=="boolean")n.push(`${i}${u}${c}`);else if(c instanceof Date)n.push(`${i}${u}${c.toUTCString()}`);else if(Array.isArray(c))for(let d of c)d[Ut.NAME]=a,n.push(...this.serializeObj(d,r));else if(c instanceof Ut)c[Ut.NAME]=a,n.push(...this.serializeObj(c,r));else if(Se.BufferSourceConverter.isBufferSource(c))a?(n.push(`${i}${u}`),n.push(...this.serializeBufferSource(c,r+1))):n.push(...this.serializeBufferSource(c,r));else if("toTextObject"in c){let d=c.toTextObject();d[Ut.NAME]=a,n.push(...this.serializeObj(d,r))}else throw new TypeError("Cannot serialize data in text format. Unsupported type.")}return n}static serializeBufferSource(e,r=0){let n=this.pad(r),i=Se.BufferSourceConverter.toUint8Array(e),o=[];for(let s=0;s<i.length;){let a=[];for(let c=0;c<16&&s<i.length;c++){c===8&&a.push("");let u=i[s++].toString(16).padStart(2,"0");a.push(u)}o.push(`${n}${a.join(" ")}`)}return o}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}};fs.oidSerializer=Mo;fs.algorithmSerializer=ME;var Mm,sa=class t{get rawData(){return ie.__classPrivateFieldGet(this,Mm,"f")||ie.__classPrivateFieldSet(this,Mm,ne.AsnConvert.serialize(this.asn),"f"),ie.__classPrivateFieldGet(this,Mm,"f")}constructor(...e){Mm.set(this,void 0),Se.BufferSourceConverter.isBufferSource(e[0])?(this.asn=ne.AsnConvert.parse(e[0],e[1]),ie.__classPrivateFieldSet(this,Mm,Se.BufferSourceConverter.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof t?Se.isEqual(e.rawData,this.rawData):!1}toString(e="text"){switch(e){case"asn":return ne.AsnConvert.toString(this.rawData);case"text":return fs.serialize(this.toTextObject());case"hex":return Se.Convert.ToHex(this.rawData);case"base64":return Se.Convert.ToBase64(this.rawData);case"base64url":return Se.Convert.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){let e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new Ut(this.getTextName(),{},e)}};Mm=new WeakMap;sa.NAME="ASN";var Oi=class t extends sa{constructor(...e){let r;Se.BufferSourceConverter.isBufferSource(e[0])?r=Se.BufferSourceConverter.toArrayBuffer(e[0]):r=ne.AsnConvert.serialize(new Je.Extension({extnID:e[0],critical:e[1],extnValue:new ne.OctetString(Se.BufferSourceConverter.toArrayBuffer(e[2]))})),super(r,Je.Extension)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[Ut.NAME]===t.NAME&&(e[Ut.NAME]=Mo.toString(this.type)),e}},qq,Wm=class t{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&e.extractable!==void 0}constructor(){this.items=new Map,this[qq]="CryptoProvider",typeof self<"u"&&typeof crypto<"u"?this.set(t.DEFAULT,crypto):typeof global<"u"&&global.crypto&&global.crypto.subtle&&this.set(t.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,r){return this.items.forEach(e,r)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=t.DEFAULT){let r=this.items.get(e.toLowerCase());if(!r)throw new Error(`Cannot get Crypto by name '${e}'`);return r}set(e,r){if(typeof e=="string"){if(!r)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),r)}else this.items.set(t.DEFAULT,e);return this}};qq=Symbol.toStringTag;Wm.DEFAULT="default";var kr=new Wm,pbe=/^[0-2](?:\.[1-9][0-9]*)+$/;function mbe(t){return new RegExp(pbe).test(t)}var vv=class{constructor(e={}){this.items={};for(let r in e)this.register(r,e[r])}get(e){return this.items[e]||null}findId(e){return mbe(e)?e:this.get(e)}register(e,r){this.items[e]=r,this.items[r]=e}},Mi=new vv;Mi.register("CN","2.5.4.3");Mi.register("L","2.5.4.7");Mi.register("ST","2.5.4.8");Mi.register("O","2.5.4.10");Mi.register("OU","2.5.4.11");Mi.register("C","2.5.4.6");Mi.register("DC","0.9.2342.19200300.100.1.25");Mi.register("E","1.2.840.113549.1.9.1");Mi.register("G","2.5.4.42");Mi.register("I","2.5.4.43");Mi.register("SN","2.5.4.4");Mi.register("T","2.5.4.12");function hbe(t,e){return`\\${Se.Convert.ToHex(Se.Convert.FromUtf8String(e)).toUpperCase()}`}function gbe(t){return t.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,hbe)}var vn=class t{static isASCII(e){for(let r=0;r<e.length;r++)if(e.charCodeAt(r)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,r={}){this.extraNames=new vv,this.asn=new Je.Name;for(let n in r)if(Object.prototype.hasOwnProperty.call(r,n)){let i=r[n];this.extraNames.register(n,i)}typeof e=="string"?this.asn=this.fromString(e):e instanceof Je.Name?this.asn=e:Se.BufferSourceConverter.isBufferSource(e)?this.asn=ne.AsnConvert.parse(e,Je.Name):this.asn=this.fromJSON(e)}getField(e){let r=this.extraNames.findId(e)||Mi.findId(e),n=[];for(let i of this.asn)for(let o of i)o.type===r&&n.push(o.value.toString());return n}getName(e){return this.extraNames.get(e)||Mi.get(e)}toString(){return this.asn.map(e=>e.map(r=>{let n=this.getName(r.type)||r.type,i=r.value.anyValue?`#${Se.Convert.ToHex(r.value.anyValue)}`:gbe(r.value.toString());return`${n}=${i}`}).join("+")).join(", ")}toJSON(){var e;let r=[];for(let n of this.asn){let i={};for(let o of n){let s=this.getName(o.type)||o.type;(e=i[s])!==null&&e!==void 0||(i[s]=[]),i[s].push(o.value.anyValue?`#${Se.Convert.ToHex(o.value.anyValue)}`:o.value.toString())}r.push(i)}return r}fromString(e){let r=new Je.Name,n=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g,i=null,o=",";for(;i=n.exec(`${e},`);){let[,s,a]=i,c=a[a.length-1];(c===","||c==="+")&&(a=a.slice(0,a.length-1),i[3]=c);let u=i[3];s=this.getTypeOid(s);let d=this.createAttribute(s,a);o==="+"?r[r.length-1].push(d):r.push(new Je.RelativeDistinguishedName([d])),o=u}return r}fromJSON(e){let r=new Je.Name;for(let n of e){let i=new Je.RelativeDistinguishedName;for(let o in n){let s=this.getTypeOid(o),a=n[o];for(let c of a){let u=this.createAttribute(s,c);i.push(u)}}r.push(i)}return r}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,r){let n=new Je.AttributeTypeAndValue({type:e});if(typeof r=="object")for(let i in r)switch(i){case"ia5String":n.value.ia5String=r[i];break;case"utf8String":n.value.utf8String=r[i];break;case"universalString":n.value.universalString=r[i];break;case"bmpString":n.value.bmpString=r[i];break;case"printableString":n.value.printableString=r[i];break}else if(r[0]==="#")n.value.anyValue=Se.Convert.FromHex(r.slice(1));else{let i=this.processStringValue(r);e===this.getName("E")||e===this.getName("DC")?n.value.ia5String=i:t.isPrintableString(i)?n.value.printableString=i:n.value.utf8String=i}return n}processStringValue(e){let r=/"(.*?[^\\])?"/.exec(e);return r&&(e=r[1]),e.replace(/\\0a/ig,`
26
+ `).replace(/\\0d/ig,"\r").replace(/\\0g/ig," ").replace(/\\(.)/g,"$1")}toArrayBuffer(){return ne.AsnConvert.serialize(this.asn)}async getThumbprint(...e){var r;let n,i="SHA-1";return e.length>=1&&!(!((r=e[0])===null||r===void 0)&&r.subtle)?(i=e[0]||i,n=e[1]||kr.get()):n=e[0]||kr.get(),await n.subtle.digest(i,this.toArrayBuffer())}},Wq="Cannot initialize GeneralName from ASN.1 data.",Mq=`${Wq} Unsupported string format in use.`,ybe=`${Wq} Value doesn't match to GUID regular expression.`,Lq=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Hq="1.3.6.1.4.1.311.25.1",Uq="1.3.6.1.4.1.311.20.2.3",IE="dns",EE="dn",kE="email",RE="ip",AE="url",CE="guid",PE="upn",Wy="id",us=class extends sa{constructor(...e){let r;if(e.length===2)switch(e[0]){case EE:{let n=new vn(e[1]).toArrayBuffer(),i=ne.AsnConvert.parse(n,re.Name);r=new re.GeneralName({directoryName:i});break}case IE:r=new re.GeneralName({dNSName:e[1]});break;case kE:r=new re.GeneralName({rfc822Name:e[1]});break;case CE:{let n=new RegExp(Lq,"i").exec(e[1]);if(!n)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");let i=n.slice(1).map((o,s)=>s<3?Se.Convert.ToHex(new Uint8Array(Se.Convert.FromHex(o)).reverse()):o).join("");r=new re.GeneralName({otherName:new re.OtherName({typeId:Hq,value:ne.AsnConvert.serialize(new ne.OctetString(Se.Convert.FromHex(i)))})});break}case RE:r=new re.GeneralName({iPAddress:e[1]});break;case Wy:r=new re.GeneralName({registeredID:e[1]});break;case PE:{r=new re.GeneralName({otherName:new re.OtherName({typeId:Uq,value:ne.AsnConvert.serialize(ne.AsnUtf8StringConverter.toASN(e[1]))})});break}case AE:r=new re.GeneralName({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else Se.BufferSourceConverter.isBufferSource(e[0])?r=ne.AsnConvert.parse(e[0],re.GeneralName):r=e[0];super(r)}onInit(e){if(e.dNSName!=null)this.type=IE,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=kE,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=RE,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=AE,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=Wy,this.value=e.registeredID;else if(e.directoryName!=null)this.type=EE,this.value=new vn(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===Hq){this.type=CE;let r=ne.AsnConvert.parse(e.otherName.value,ne.OctetString),n=new RegExp(Lq,"i").exec(Se.Convert.ToHex(r));if(!n)throw new Error(ybe);this.value=n.slice(1).map((i,o)=>o<3?Se.Convert.ToHex(new Uint8Array(Se.Convert.FromHex(i)).reverse()):i).join("-")}else if(e.otherName.typeId===Uq)this.type=PE,this.value=ne.AsnConvert.parse(e.otherName.value,re.DirectoryString).toString();else throw new Error(Mq);else throw new Error(Mq)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case EE:case IE:case CE:case RE:case Wy:case PE:case AE:e=this.type.toUpperCase();break;case kE:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let r=this.value;return this.type===Wy&&(r=Mo.toString(r)),new Ut(e,void 0,r)}},aa=class extends sa{constructor(e){let r;if(e instanceof re.GeneralNames)r=e;else if(Array.isArray(e)){let n=[];for(let i of e)if(i instanceof re.GeneralName)n.push(i);else{let o=ne.AsnConvert.parse(new us(i.type,i.value).rawData,re.GeneralName);n.push(o)}r=new re.GeneralNames(n)}else if(Se.BufferSourceConverter.isBufferSource(e))r=ne.AsnConvert.parse(e,re.GeneralNames);else throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");super(r)}onInit(e){let r=[];for(let n of e){let i=null;try{i=new us(n)}catch{continue}r.push(i)}this.items=r}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){let e=super.toTextObjectEmpty();for(let r of this.items){let n=r.toTextObject(),i=e[n[Ut.NAME]];Array.isArray(i)||(i=[],e[n[Ut.NAME]]=i),i.push(n)}return e}};aa.NAME="GeneralNames";var yv="-{5}",xv="\\n",vbe=`[^${xv}]+`,xbe=`${yv}BEGIN (${vbe}(?=${yv}))${yv}`,Sbe=`${yv}END \\1${yv}`,Vm="\\n",bbe=`[^:${xv}]+`,wbe=`(?:[^${xv}]+${Vm}(?: +[^${xv}]+${Vm})*)`,Ibe="[a-zA-Z0-9=+/]+",Ebe=`(?:${Ibe}${Vm})+`,$q=`${xbe}${Vm}(?:((?:${bbe}: ${wbe})+))?${Vm}?(${Ebe})${Sbe}`,kn=class{static isPem(e){return typeof e=="string"&&new RegExp($q,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");let r=new RegExp($q,"g"),n=[],i=null;for(;i=r.exec(e);){let o=i[3].replace(new RegExp(`[${xv}]+`,"g"),""),s={type:i[1],headers:[],rawData:Se.Convert.FromBase64(o)},a=i[2];if(a){let c=a.split(new RegExp(Vm,"g")),u=null;for(let d of c){let[l,f]=d.split(/:(.*)/);if(f===void 0){if(!u)throw new Error("Cannot parse PEM string. Incorrect header value");u.value+=l.trim()}else u&&s.headers.push(u),u={key:l,value:f.trim()}}u&&s.headers.push(u)}n.push(s)}return n}static decode(e){return this.decodeWithHeaders(e).map(n=>n.rawData)}static decodeFirst(e){let r=this.decode(e);if(!r.length)throw new RangeError("PEM string doesn't contain any objects");return r[0]}static encode(e,r){if(Array.isArray(e)){let n=new Array;return r?e.forEach(i=>{if(!Se.BufferSourceConverter.isBufferSource(i))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");n.push(this.encodeStruct({type:r,rawData:Se.BufferSourceConverter.toArrayBuffer(i)}))}):e.forEach(i=>{if(!("type"in i))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");n.push(this.encodeStruct(i))}),n.join(`
27
+ `)}else{if(!r)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:r,rawData:Se.BufferSourceConverter.toArrayBuffer(e)})}}static encodeStruct(e){var r;let n=e.type.toLocaleUpperCase(),i=[];if(i.push(`-----BEGIN ${n}-----`),!((r=e.headers)===null||r===void 0)&&r.length){for(let u of e.headers)i.push(`${u.key}: ${u.value}`);i.push("")}let o=Se.Convert.ToBase64(e.rawData),s,a=0,c=Array();for(;a<o.length&&(o.length-a<64?s=o.substring(a):(s=o.substring(a,a+64),a+=64),s.length!==0);)if(c.push(s),s.length<64)break;return i.push(...c),i.push(`-----END ${n}-----`),i.join(`
28
+ `)}};kn.CertificateTag="CERTIFICATE";kn.CrlTag="CRL";kn.CertificateRequestTag="CERTIFICATE REQUEST";kn.PublicKeyTag="PUBLIC KEY";kn.PrivateKeyTag="PRIVATE KEY";var Li=class t extends sa{static isAsnEncoded(e){return Se.BufferSourceConverter.isBufferSource(e)||typeof e=="string"}static toArrayBuffer(e){if(typeof e=="string"){if(kn.isPem(e))return kn.decode(e)[0];if(Se.Convert.isHex(e))return Se.Convert.FromHex(e);if(Se.Convert.isBase64(e))return Se.Convert.FromBase64(e);if(Se.Convert.isBase64Url(e))return Se.Convert.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}else{let r=Se.BufferSourceConverter.toUint8Array(e);if(r.length>0&&r[0]===48)return Se.BufferSourceConverter.toArrayBuffer(e);let n=Se.Convert.ToBinary(e);if(kn.isPem(n))return kn.decode(n)[0];if(Se.Convert.isHex(n))return Se.Convert.FromHex(n);if(Se.Convert.isBase64(n))return Se.Convert.FromBase64(n);if(Se.Convert.isBase64Url(n))return Se.Convert.FromBase64Url(n);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){t.isAsnEncoded(e[0])?super(t.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return e==="pem"?kn.encode(this.rawData,this.tag):super.toString(e)}},ds=class t extends Li{static async create(e,r=kr.get()){if(e instanceof t)return e;if(Wm.isCryptoKey(e)){if(e.type!=="public")throw new TypeError("Public key is required");let n=await r.subtle.exportKey("spki",e);return new t(n)}else{if(e.publicKey)return e.publicKey;if(Se.BufferSourceConverter.isBufferSource(e))return new t(e);throw new TypeError("Unsupported PublicKeyType")}}constructor(e){Li.isAsnEncoded(e)?super(e,Je.SubjectPublicKeyInfo):super(e),this.tag=kn.PublicKeyTag}async export(...e){let r,n=["verify"],i={hash:"SHA-256",...this.algorithm};e.length>1?(i=e[0]||i,n=e[1]||n,r=e[2]||kr.get()):r=e[0]||kr.get();let o=this.rawData,s=ne.AsnConvert.parse(this.rawData,Je.SubjectPublicKeyInfo);return s.algorithm.algorithm===Ni.id_RSASSA_PSS&&(o=kbe(s,o)),r.subtle.importKey("spki",o,i,!0,n)}onInit(e){let r=yr.container.resolve(ls),n=this.algorithm=r.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===Ni.id_rsaEncryption){let i=ne.AsnConvert.parse(e.subjectPublicKey,Ni.RSAPublicKey),o=Se.BufferSourceConverter.toUint8Array(i.modulus);n.publicExponent=Se.BufferSourceConverter.toUint8Array(i.publicExponent),n.modulusLength=(o[0]?o:o.slice(1)).byteLength<<3}}async getThumbprint(...e){var r;let n,i="SHA-1";return e.length>=1&&!(!((r=e[0])===null||r===void 0)&&r.subtle)?(i=e[0]||i,n=e[1]||kr.get()):n=e[0]||kr.get(),await n.subtle.digest(i,this.rawData)}async getKeyIdentifier(...e){let r,n="SHA-1";e.length===1?typeof e[0]=="string"?(n=e[0],r=kr.get()):r=e[0]:e.length===2?(n=e[0],r=e[1]):r=kr.get();let i=ne.AsnConvert.parse(this.rawData,Je.SubjectPublicKeyInfo);return await r.subtle.digest(n,i.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),r=ne.AsnConvert.parse(this.rawData,Je.SubjectPublicKeyInfo);switch(e.Algorithm=fs.serializeAlgorithm(r.algorithm),r.algorithm.algorithm){case BE.id_ecPublicKey:e["EC Point"]=r.subjectPublicKey;break;case Ni.id_rsaEncryption:default:e["Raw Data"]=r.subjectPublicKey}return e}};function kbe(t,e){return t.algorithm=new Je.AlgorithmIdentifier({algorithm:Ni.id_rsaEncryption,parameters:null}),e=ne.AsnConvert.serialize(t),e}var Sv=class t extends Oi{static async create(e,r=!1,n=kr.get()){if("name"in e&&"serialNumber"in e)return new t(e,r);let o=await(await ds.create(e,n)).getKeyIdentifier(n);return new t(Se.Convert.ToHex(o),r)}constructor(...e){if(Se.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]=="string"){let r=new re.AuthorityKeyIdentifier({keyIdentifier:new re.KeyIdentifier(Se.Convert.FromHex(e[0]))});super(re.id_ce_authorityKeyIdentifier,e[1],ne.AsnConvert.serialize(r))}else{let r=e[0],n=r.name instanceof aa?ne.AsnConvert.parse(r.name.rawData,re.GeneralNames):r.name,i=new re.AuthorityKeyIdentifier({authorityCertIssuer:n,authorityCertSerialNumber:Se.Convert.FromHex(r.serialNumber)});super(re.id_ce_authorityKeyIdentifier,e[1],ne.AsnConvert.serialize(i))}}onInit(e){super.onInit(e);let r=ne.AsnConvert.parse(e.extnValue,re.AuthorityKeyIdentifier);r.keyIdentifier&&(this.keyId=Se.Convert.ToHex(r.keyIdentifier)),(r.authorityCertIssuer||r.authorityCertSerialNumber)&&(this.certId={name:r.authorityCertIssuer||[],serialNumber:r.authorityCertSerialNumber?Se.Convert.ToHex(r.authorityCertSerialNumber):""})}toTextObject(){let e=this.toTextObjectWithoutValue(),r=ne.AsnConvert.parse(this.value,re.AuthorityKeyIdentifier);return r.authorityCertIssuer&&(e["Authority Issuer"]=new aa(r.authorityCertIssuer).toTextObject()),r.authorityCertSerialNumber&&(e["Authority Serial Number"]=r.authorityCertSerialNumber),r.keyIdentifier&&(e[""]=r.keyIdentifier),e}};Sv.NAME="Authority Key Identifier";var bv=class extends Oi{constructor(...e){if(Se.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let r=ne.AsnConvert.parse(this.value,Je.BasicConstraints);this.ca=r.cA,this.pathLength=r.pathLenConstraint}else{let r=new Je.BasicConstraints({cA:e[0],pathLenConstraint:e[1]});super(Je.id_ce_basicConstraints,e[2],ne.AsnConvert.serialize(r)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),this.pathLength!==void 0&&(e["Path Length"]=this.pathLength),e}};bv.NAME="Basic Constraints";_e.ExtendedKeyUsage=void 0;(function(t){t.serverAuth="1.3.6.1.5.5.7.3.1",t.clientAuth="1.3.6.1.5.5.7.3.2",t.codeSigning="1.3.6.1.5.5.7.3.3",t.emailProtection="1.3.6.1.5.5.7.3.4",t.timeStamping="1.3.6.1.5.5.7.3.8",t.ocspSigning="1.3.6.1.5.5.7.3.9"})(_e.ExtendedKeyUsage||(_e.ExtendedKeyUsage={}));var wv=class extends Oi{constructor(...e){if(Se.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let r=ne.AsnConvert.parse(this.value,re.ExtendedKeyUsage);this.usages=r.map(n=>n)}else{let r=new re.ExtendedKeyUsage(e[0]);super(re.id_ce_extKeyUsage,e[1],ne.AsnConvert.serialize(r)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(r=>Mo.toString(r)).join(", "),e}};wv.NAME="Extended Key Usages";_e.KeyUsageFlags=void 0;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(_e.KeyUsageFlags||(_e.KeyUsageFlags={}));var Iv=class extends Oi{constructor(...e){if(Se.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let r=ne.AsnConvert.parse(this.value,Je.KeyUsage);this.usages=r.toNumber()}else{let r=new Je.KeyUsage(e[0]);super(Je.id_ce_keyUsage,e[1],ne.AsnConvert.serialize(r)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue(),r=ne.AsnConvert.parse(this.value,Je.KeyUsage);return e[""]=r.toJSON().join(", "),e}};Iv.NAME="Key Usages";var Ev=class t extends Oi{static async create(e,r=!1,n=kr.get()){let o=await(await ds.create(e,n)).getKeyIdentifier(n);return new t(Se.Convert.ToHex(o),r)}constructor(...e){if(Se.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let r=ne.AsnConvert.parse(this.value,re.SubjectKeyIdentifier);this.keyId=Se.Convert.ToHex(r)}else{let r=typeof e[0]=="string"?Se.Convert.FromHex(e[0]):e[0],n=new re.SubjectKeyIdentifier(r);super(re.id_ce_subjectKeyIdentifier,e[1],ne.AsnConvert.serialize(n)),this.keyId=Se.Convert.ToHex(r)}}toTextObject(){let e=this.toTextObjectWithoutValue(),r=ne.AsnConvert.parse(this.value,re.SubjectKeyIdentifier);return e[""]=r,e}};Ev.NAME="Subject Key Identifier";var kv=class extends Oi{constructor(...e){Se.BufferSourceConverter.isBufferSource(e[0])?super(e[0]):super(re.id_ce_subjectAltName,e[1],new aa(e[0]||[]).rawData)}onInit(e){super.onInit(e);let r=ne.AsnConvert.parse(e.extnValue,re.SubjectAlternativeName);this.names=new aa(r)}toTextObject(){let e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(let n in r)e[n]=r[n];return e}};kv.NAME="Subject Alternative Name";var Rn=class{static register(e,r){this.items.set(e,r)}static create(e){let r=new Oi(e),n=this.items.get(r.type);return n?new n(e):r}};Rn.items=new Map;var Rv=class extends Oi{constructor(...e){var r;if(Se.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let n=ne.AsnConvert.parse(this.value,re.CertificatePolicies);this.policies=n.map(i=>i.policyIdentifier)}else{let n=e[0],i=(r=e[1])!==null&&r!==void 0?r:!1,o=new re.CertificatePolicies(n.map(s=>new re.PolicyInformation({policyIdentifier:s})));super(re.id_ce_certificatePolicies,i,ne.AsnConvert.serialize(o)),this.policies=n}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(r=>new Ut("",{},Mo.toString(r))),e}};Rv.NAME="Certificate Policies";Rn.register(re.id_ce_certificatePolicies,Rv);var Av=class extends Oi{constructor(...e){var r;if(Se.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]=="string"){let i=e[0].map(s=>new re.DistributionPoint({distributionPoint:new re.DistributionPointName({fullName:[new re.GeneralName({uniformResourceIdentifier:s})]})})),o=new re.CRLDistributionPoints(i);super(re.id_ce_cRLDistributionPoints,e[1],ne.AsnConvert.serialize(o))}else{let n=new re.CRLDistributionPoints(e[0]);super(re.id_ce_cRLDistributionPoints,e[1],ne.AsnConvert.serialize(n))}(r=this.distributionPoints)!==null&&r!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);let r=ne.AsnConvert.parse(e.extnValue,re.CRLDistributionPoints);this.distributionPoints=r}toTextObject(){let e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(r=>{var n;let i={};return r.distributionPoint&&(i[""]=(n=r.distributionPoint.fullName)===null||n===void 0?void 0:n.map(o=>new us(o).toString()).join(", ")),r.reasons&&(i.Reasons=r.reasons.toString()),r.cRLIssuer&&(i["CRL Issuer"]=r.cRLIssuer.map(o=>o.toString()).join(", ")),i}),e}};Av.NAME="CRL Distribution Points";var Cv=class extends Oi{constructor(...e){var r,n,i,o;if(Se.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof re.AuthorityInfoAccessSyntax){let s=new re.AuthorityInfoAccessSyntax(e[0]);super(re.id_pe_authorityInfoAccess,e[1],ne.AsnConvert.serialize(s))}else{let s=e[0],a=new re.AuthorityInfoAccessSyntax;bE(a,s,re.id_ad_ocsp,"ocsp"),bE(a,s,re.id_ad_caIssuers,"caIssuers"),bE(a,s,re.id_ad_timeStamping,"timeStamping"),bE(a,s,re.id_ad_caRepository,"caRepository"),super(re.id_pe_authorityInfoAccess,e[1],ne.AsnConvert.serialize(a))}(r=this.ocsp)!==null&&r!==void 0||(this.ocsp=[]),(n=this.caIssuers)!==null&&n!==void 0||(this.caIssuers=[]),(i=this.timeStamping)!==null&&i!==void 0||(this.timeStamping=[]),(o=this.caRepository)!==null&&o!==void 0||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],ne.AsnConvert.parse(e.extnValue,re.AuthorityInfoAccessSyntax).forEach(n=>{switch(n.accessMethod){case re.id_ad_ocsp:this.ocsp.push(new us(n.accessLocation));break;case re.id_ad_caIssuers:this.caIssuers.push(new us(n.accessLocation));break;case re.id_ad_timeStamping:this.timeStamping.push(new us(n.accessLocation));break;case re.id_ad_caRepository:this.caRepository.push(new us(n.accessLocation));break}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&SE(e,"OCSP",this.ocsp),this.caIssuers.length&&SE(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&SE(e,"Time Stamping",this.timeStamping),this.caRepository.length&&SE(e,"CA Repository",this.caRepository),e}};Cv.NAME="Authority Info Access";function SE(t,e,r){if(r.length===1)t[e]=r[0].toTextObject();else{let n=new Ut("");r.forEach((i,o)=>{let s=i.toTextObject(),a=`${s[Ut.NAME]} ${o+1}`,c=n[a];Array.isArray(c)||(c=[],n[a]=c),c.push(s)}),t[e]=n}}function bE(t,e,r,n){let i=e[n];i&&(Array.isArray(i)?i:[i]).forEach(s=>{typeof s=="string"&&(s=new us("url",s)),t.push(new re.AccessDescription({accessMethod:r,accessLocation:ne.AsnConvert.parse(s.rawData,re.GeneralName)}))})}var Pv=class extends Oi{constructor(...e){Se.BufferSourceConverter.isBufferSource(e[0])?super(e[0]):super(re.id_ce_issuerAltName,e[1],new aa(e[0]||[]).rawData)}onInit(e){super.onInit(e);let r=ne.AsnConvert.parse(e.extnValue,re.GeneralNames);this.names=new aa(r)}toTextObject(){let e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(let n in r)e[n]=r[n];return e}};Pv.NAME="Issuer Alternative Name";var sf=class t extends sa{constructor(...e){let r;if(Se.BufferSourceConverter.isBufferSource(e[0]))r=Se.BufferSourceConverter.toArrayBuffer(e[0]);else{let n=e[0],i=Array.isArray(e[1])?e[1].map(o=>Se.BufferSourceConverter.toArrayBuffer(o)):[];r=ne.AsnConvert.serialize(new Je.Attribute({type:n,values:i}))}super(r,Je.Attribute)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map(r=>new Ut("",{"":r})),e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty();return e[Ut.NAME]===t.NAME&&(e[Ut.NAME]=Mo.toString(this.type)),e}};sf.NAME="Attribute";var _v=class extends sf{constructor(...e){var r;if(Se.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else{let n=new qm.ChallengePassword({printableString:e[0]});super(qm.id_pkcs9_at_challengePassword,[ne.AsnConvert.serialize(n)])}(r=this.password)!==null&&r!==void 0||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){let r=ne.AsnConvert.parse(this.values[0],qm.ChallengePassword);this.password=r.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[Ut.VALUE]=this.password,e}};_v.NAME="Challenge Password";var Gm=class extends sf{constructor(...e){var r;if(Se.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else{let n=e[0],i=new re.Extensions;for(let o of n)i.push(ne.AsnConvert.parse(o.rawData,re.Extension));super(qm.id_pkcs9_at_extensionRequest,[ne.AsnConvert.serialize(i)])}(r=this.items)!==null&&r!==void 0||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){let r=ne.AsnConvert.parse(this.values[0],re.Extensions);this.items=r.map(n=>Rn.create(ne.AsnConvert.serialize(n)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),r=this.items.map(n=>n.toTextObject());for(let n of r)e[n[Ut.NAME]]=n;return e}};Gm.NAME="Extensions";var af=class{static register(e,r){this.items.set(e,r)}static create(e){let r=new sf(e),n=this.items.get(r.type);return n?new n(e):r}};af.items=new Map;var xc="crypto.signatureFormatter",LE=class{toAsnSignature(e,r){return Se.BufferSourceConverter.toArrayBuffer(r)}toWebSignature(e,r){return Se.BufferSourceConverter.toArrayBuffer(r)}},_E;_e.RsaAlgorithm=_E=class{static createPssParams(e,r){let n=_E.getHashAlgorithm(e);return n?new gr.RsaSaPssParams({hashAlgorithm:n,maskGenAlgorithm:new Je.AlgorithmIdentifier({algorithm:gr.id_mgf1,parameters:ne.AsnConvert.serialize(n)}),saltLength:r}):null}static getHashAlgorithm(e){let r=yr.container.resolve(ls);return typeof e=="string"?r.toAsnAlgorithm({name:e}):typeof e=="object"&&e&&"name"in e?r.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if("hash"in e){let r;if(typeof e.hash=="string")r=e.hash;else if(e.hash&&typeof e.hash=="object"&&"name"in e.hash&&typeof e.hash.name=="string")r=e.hash.name.toUpperCase();else throw new Error("Cannot get hash algorithm name");switch(r.toLowerCase()){case"sha-1":return new Je.AlgorithmIdentifier({algorithm:gr.id_sha1WithRSAEncryption,parameters:null});case"sha-256":return new Je.AlgorithmIdentifier({algorithm:gr.id_sha256WithRSAEncryption,parameters:null});case"sha-384":return new Je.AlgorithmIdentifier({algorithm:gr.id_sha384WithRSAEncryption,parameters:null});case"sha-512":return new Je.AlgorithmIdentifier({algorithm:gr.id_sha512WithRSAEncryption,parameters:null})}}else return new Je.AlgorithmIdentifier({algorithm:gr.id_rsaEncryption,parameters:null});break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e&&typeof e.saltLength=="number"))throw new Error("Cannot get 'saltLength' from 'alg' argument");let r=_E.createPssParams(e.hash,e.saltLength);if(!r)throw new Error("Cannot create PSS parameters");return new Je.AlgorithmIdentifier({algorithm:gr.id_RSASSA_PSS,parameters:ne.AsnConvert.serialize(r)})}else return new Je.AlgorithmIdentifier({algorithm:gr.id_RSASSA_PSS,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case gr.id_rsaEncryption:return{name:"RSASSA-PKCS1-v1_5"};case gr.id_sha1WithRSAEncryption:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case gr.id_sha256WithRSAEncryption:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case gr.id_sha384WithRSAEncryption:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case gr.id_sha512WithRSAEncryption:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case gr.id_RSASSA_PSS:if(e.parameters){let r=ne.AsnConvert.parse(e.parameters,gr.RsaSaPssParams);return{name:"RSA-PSS",hash:yr.container.resolve(ls).toWebAlgorithm(r.hashAlgorithm),saltLength:r.saltLength}}else return{name:"RSA-PSS"}}return null}};_e.RsaAlgorithm=_E=ie.__decorate([yr.injectable()],_e.RsaAlgorithm);yr.container.registerSingleton(Km,_e.RsaAlgorithm);_e.ShaAlgorithm=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new Je.AlgorithmIdentifier({algorithm:Ni.id_sha1});case"sha-256":return new Je.AlgorithmIdentifier({algorithm:Ni.id_sha256});case"sha-384":return new Je.AlgorithmIdentifier({algorithm:Ni.id_sha384});case"sha-512":return new Je.AlgorithmIdentifier({algorithm:Ni.id_sha512})}return null}toWebAlgorithm(e){switch(e.algorithm){case Ni.id_sha1:return{name:"SHA-1"};case Ni.id_sha256:return{name:"SHA-256"};case Ni.id_sha384:return{name:"SHA-384"};case Ni.id_sha512:return{name:"SHA-512"}}return null}};_e.ShaAlgorithm=ie.__decorate([yr.injectable()],_e.ShaAlgorithm);yr.container.registerSingleton(Km,_e.ShaAlgorithm);var ca=class t{addPadding(e,r){let n=Se.BufferSourceConverter.toUint8Array(r),i=new Uint8Array(e);return i.set(n,e-n.length),i.buffer}removePadding(e,r=!1){let n=Se.BufferSourceConverter.toUint8Array(e);for(let i=0;i<n.length;i++)if(n[i]){n=n.slice(i);break}if(r&&n[0]>127){let i=new Uint8Array(n.length+1);return i.set(n,1),i.buffer}return n.buffer}toAsnSignature(e,r){if(e.name==="ECDSA"){let n=e.namedCurve,i=t.namedCurveSize.get(n)||t.defaultNamedCurveSize,o=new BE.ECDSASigValue,s=Se.BufferSourceConverter.toUint8Array(r);return o.r=this.removePadding(s.slice(0,i),!0),o.s=this.removePadding(s.slice(i,i+i),!0),ne.AsnConvert.serialize(o)}return null}toWebSignature(e,r){if(e.name==="ECDSA"){let n=ne.AsnConvert.parse(r,BE.ECDSASigValue),i=e.namedCurve,o=t.namedCurveSize.get(i)||t.defaultNamedCurveSize,s=this.addPadding(o,this.removePadding(n.r)),a=this.addPadding(o,this.removePadding(n.s));return Se.combine(s,a)}return null}};ca.namedCurveSize=new Map;ca.defaultNamedCurveSize=32;var TE="1.3.101.110",rB="1.3.101.111",DE="1.3.101.112",nB="1.3.101.113";_e.EdAlgorithm=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"ed25519":r=DE;break;case"x25519":r=TE;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":r=DE;break;case"ed448":r=nB;break}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":r=TE;break;case"x448":r=rB;break}}return r?new Je.AlgorithmIdentifier({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case DE:return{name:"Ed25519"};case nB:return{name:"EdDSA",namedCurve:"Ed448"};case TE:return{name:"X25519"};case rB:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};_e.EdAlgorithm=ie.__decorate([yr.injectable()],_e.EdAlgorithm);yr.container.registerSingleton(Km,_e.EdAlgorithm);var Vy,Gy,zy,Ky,Jy,Xy,Yy,Lm,Tv=class extends Li{get subjectName(){return ie.__classPrivateFieldGet(this,Gy,"f")||ie.__classPrivateFieldSet(this,Gy,new vn(this.asn.certificationRequestInfo.subject),"f"),ie.__classPrivateFieldGet(this,Gy,"f")}get subject(){return ie.__classPrivateFieldGet(this,zy,"f")||ie.__classPrivateFieldSet(this,zy,this.subjectName.toString(),"f"),ie.__classPrivateFieldGet(this,zy,"f")}get signatureAlgorithm(){if(!ie.__classPrivateFieldGet(this,Ky,"f")){let e=yr.container.resolve(ls);ie.__classPrivateFieldSet(this,Ky,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return ie.__classPrivateFieldGet(this,Ky,"f")}get signature(){return ie.__classPrivateFieldGet(this,Jy,"f")||ie.__classPrivateFieldSet(this,Jy,this.asn.signature,"f"),ie.__classPrivateFieldGet(this,Jy,"f")}get publicKey(){return ie.__classPrivateFieldGet(this,Xy,"f")||ie.__classPrivateFieldSet(this,Xy,new ds(this.asn.certificationRequestInfo.subjectPKInfo),"f"),ie.__classPrivateFieldGet(this,Xy,"f")}get attributes(){return ie.__classPrivateFieldGet(this,Yy,"f")||ie.__classPrivateFieldSet(this,Yy,this.asn.certificationRequestInfo.attributes.map(e=>af.create(ne.AsnConvert.serialize(e))),"f"),ie.__classPrivateFieldGet(this,Yy,"f")}get extensions(){if(!ie.__classPrivateFieldGet(this,Lm,"f")){ie.__classPrivateFieldSet(this,Lm,[],"f");let e=this.getAttribute(cB.id_pkcs9_at_extensionRequest);e instanceof Gm&&ie.__classPrivateFieldSet(this,Lm,e.items,"f")}return ie.__classPrivateFieldGet(this,Lm,"f")}get tbs(){return ie.__classPrivateFieldGet(this,Vy,"f")||ie.__classPrivateFieldSet(this,Vy,this.asn.certificationRequestInfoRaw||ne.AsnConvert.serialize(this.asn.certificationRequestInfo),"f"),ie.__classPrivateFieldGet(this,Vy,"f")}constructor(e){let r=Li.isAsnEncoded(e)?[e,NE.CertificationRequest]:[e];super(r[0],r[1]),Vy.set(this,void 0),Gy.set(this,void 0),zy.set(this,void 0),Ky.set(this,void 0),Jy.set(this,void 0),Xy.set(this,void 0),Yy.set(this,void 0),Lm.set(this,void 0),this.tag=kn.CertificateRequestTag}onInit(e){}getAttribute(e){for(let r of this.attributes)if(r.type===e)return r;return null}getAttributes(e){return this.attributes.filter(r=>r.type===e)}getExtension(e){for(let r of this.extensions)if(r.type===e)return r;return null}getExtensions(e){return this.extensions.filter(r=>r.type===e)}async verify(e=kr.get()){let r={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(r,["verify"],e),i=yr.container.resolveAll(xc).reverse(),o=null;for(let a of i)if(o=a.toWebSignature(r,this.signature),o)break;if(!o)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,n,o,this.tbs)}toTextObject(){let e=this.toTextObjectEmpty(),r=ne.AsnConvert.parse(this.rawData,NE.CertificationRequest),n=r.certificationRequestInfo,i=new Ut("",{Version:`${Je.Version[n.version]} (${n.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let o=new Ut("");for(let s of this.attributes){let a=s.toTextObject();o[a[Ut.NAME]]=a}i.Attributes=o}return e.Data=i,e.Signature=new Ut("",{Algorithm:fs.serializeAlgorithm(r.signatureAlgorithm),"":r.signature}),e}};Vy=new WeakMap,Gy=new WeakMap,zy=new WeakMap,Ky=new WeakMap,Jy=new WeakMap,Xy=new WeakMap,Yy=new WeakMap,Lm=new WeakMap;Tv.NAME="PKCS#10 Certificate Request";var iB=class{static async create(e,r=kr.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");let n=await r.subtle.exportKey("spki",e.keys.publicKey),i=new NE.CertificationRequest({certificationRequestInfo:new NE.CertificationRequestInfo({subjectPKInfo:ne.AsnConvert.parse(n,Je.SubjectPublicKeyInfo)})});if(e.name){let l=e.name instanceof vn?e.name:new vn(e.name);i.certificationRequestInfo.subject=ne.AsnConvert.parse(l.toArrayBuffer(),Je.Name)}if(e.attributes)for(let l of e.attributes)i.certificationRequestInfo.attributes.push(ne.AsnConvert.parse(l.rawData,Je.Attribute));if(e.extensions&&e.extensions.length){let l=new Je.Attribute({type:cB.id_pkcs9_at_extensionRequest}),f=new Je.Extensions;for(let p of e.extensions)f.push(ne.AsnConvert.parse(p.rawData,Je.Extension));l.values.push(ne.AsnConvert.serialize(f)),i.certificationRequestInfo.attributes.push(l)}let o={...e.signingAlgorithm,...e.keys.privateKey.algorithm},s=yr.container.resolve(ls);i.signatureAlgorithm=s.toAsnAlgorithm(o);let a=ne.AsnConvert.serialize(i.certificationRequestInfo),c=await r.subtle.sign(o,e.keys.privateKey,a),u=yr.container.resolveAll(xc).reverse(),d=null;for(let l of u)if(d=l.toAsnSignature(o,c),d)break;if(!d)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return i.signature=d,new Tv(ne.AsnConvert.serialize(i))}},Qy,Zy,ev,tv,rv,nv,iv,ov,sv,av,Hm,cv,ud=class extends Li{get publicKey(){return ie.__classPrivateFieldGet(this,cv,"f")||ie.__classPrivateFieldSet(this,cv,new ds(this.asn.tbsCertificate.subjectPublicKeyInfo),"f"),ie.__classPrivateFieldGet(this,cv,"f")}get serialNumber(){if(!ie.__classPrivateFieldGet(this,Zy,"f")){let e=this.asn.tbsCertificate,r=new Uint8Array(e.serialNumber);r.length>1&&r[0]===0&&r[1]>127&&(r=r.slice(1)),ie.__classPrivateFieldSet(this,Zy,Se.Convert.ToHex(r),"f")}return ie.__classPrivateFieldGet(this,Zy,"f")}get subjectName(){return ie.__classPrivateFieldGet(this,ev,"f")||ie.__classPrivateFieldSet(this,ev,new vn(this.asn.tbsCertificate.subject),"f"),ie.__classPrivateFieldGet(this,ev,"f")}get subject(){return ie.__classPrivateFieldGet(this,tv,"f")||ie.__classPrivateFieldSet(this,tv,this.subjectName.toString(),"f"),ie.__classPrivateFieldGet(this,tv,"f")}get issuerName(){return ie.__classPrivateFieldGet(this,rv,"f")||ie.__classPrivateFieldSet(this,rv,new vn(this.asn.tbsCertificate.issuer),"f"),ie.__classPrivateFieldGet(this,rv,"f")}get issuer(){return ie.__classPrivateFieldGet(this,nv,"f")||ie.__classPrivateFieldSet(this,nv,this.issuerName.toString(),"f"),ie.__classPrivateFieldGet(this,nv,"f")}get notBefore(){if(!ie.__classPrivateFieldGet(this,iv,"f")){let e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");ie.__classPrivateFieldSet(this,iv,e,"f")}return ie.__classPrivateFieldGet(this,iv,"f")}get notAfter(){if(!ie.__classPrivateFieldGet(this,ov,"f")){let e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");ie.__classPrivateFieldSet(this,ov,e,"f")}return ie.__classPrivateFieldGet(this,ov,"f")}get signatureAlgorithm(){if(!ie.__classPrivateFieldGet(this,sv,"f")){let e=yr.container.resolve(ls);ie.__classPrivateFieldSet(this,sv,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return ie.__classPrivateFieldGet(this,sv,"f")}get signature(){return ie.__classPrivateFieldGet(this,av,"f")||ie.__classPrivateFieldSet(this,av,this.asn.signatureValue,"f"),ie.__classPrivateFieldGet(this,av,"f")}get extensions(){return ie.__classPrivateFieldGet(this,Hm,"f")||(ie.__classPrivateFieldSet(this,Hm,[],"f"),this.asn.tbsCertificate.extensions&&ie.__classPrivateFieldSet(this,Hm,this.asn.tbsCertificate.extensions.map(e=>Rn.create(ne.AsnConvert.serialize(e))),"f")),ie.__classPrivateFieldGet(this,Hm,"f")}get tbs(){return ie.__classPrivateFieldGet(this,Qy,"f")||ie.__classPrivateFieldSet(this,Qy,this.asn.tbsCertificateRaw||ne.AsnConvert.serialize(this.asn.tbsCertificate),"f"),ie.__classPrivateFieldGet(this,Qy,"f")}constructor(e){let r=Li.isAsnEncoded(e)?[e,Je.Certificate]:[e];super(r[0],r[1]),Qy.set(this,void 0),Zy.set(this,void 0),ev.set(this,void 0),tv.set(this,void 0),rv.set(this,void 0),nv.set(this,void 0),iv.set(this,void 0),ov.set(this,void 0),sv.set(this,void 0),av.set(this,void 0),Hm.set(this,void 0),cv.set(this,void 0),this.tag=kn.CertificateTag}onInit(e){}getExtension(e){for(let r of this.extensions)if(typeof e=="string"){if(r.type===e)return r}else if(r instanceof e)return r;return null}getExtensions(e){return this.extensions.filter(r=>typeof e=="string"?r.type===e:r instanceof e)}async verify(e={},r=kr.get()){let n,i,o=e.publicKey;try{if(!o)n={...this.publicKey.algorithm,...this.signatureAlgorithm},i=await this.publicKey.export(n,["verify"],r);else if("publicKey"in o)n={...o.publicKey.algorithm,...this.signatureAlgorithm},i=await o.publicKey.export(n,["verify"],r);else if(o instanceof ds)n={...o.algorithm,...this.signatureAlgorithm},i=await o.export(n,["verify"],r);else if(Se.BufferSourceConverter.isBufferSource(o)){let u=new ds(o);n={...u.algorithm,...this.signatureAlgorithm},i=await u.export(n,["verify"],r)}else n={...o.algorithm,...this.signatureAlgorithm},i=o}catch{return!1}let s=yr.container.resolveAll(xc).reverse(),a=null;for(let u of s)if(a=u.toWebSignature(n,this.signature),a)break;if(!a)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");let c=await r.subtle.verify(this.signatureAlgorithm,i,a,this.tbs);if(e.signatureOnly)return c;{let d=(e.date||new Date).getTime();return c&&this.notBefore.getTime()<d&&d<this.notAfter.getTime()}}async getThumbprint(...e){let r,n="SHA-1";return e[0]&&(e[0].subtle?r=e[0]:(n=e[0]||n,r=e[1])),r??(r=kr.get()),await r.subtle.digest(n,this.rawData)}async isSelfSigned(e=kr.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),r=ne.AsnConvert.parse(this.rawData,Je.Certificate),n=r.tbsCertificate,i=new Ut("",{Version:`${Je.Version[n.version]} (${n.version})`,"Serial Number":n.serialNumber,"Signature Algorithm":fs.serializeAlgorithm(n.signature),Issuer:this.issuer,Validity:new Ut("",{"Not Before":n.validity.notBefore.getTime(),"Not After":n.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(n.issuerUniqueID&&(i["Issuer Unique ID"]=n.issuerUniqueID),n.subjectUniqueID&&(i["Subject Unique ID"]=n.subjectUniqueID),this.extensions.length){let o=new Ut("");for(let s of this.extensions){let a=s.toTextObject();o[a[Ut.NAME]]=a}i.Extensions=o}return e.Data=i,e.Signature=new Ut("",{Algorithm:fs.serializeAlgorithm(r.signatureAlgorithm),"":r.signatureValue}),e}};Qy=new WeakMap,Zy=new WeakMap,ev=new WeakMap,tv=new WeakMap,rv=new WeakMap,nv=new WeakMap,iv=new WeakMap,ov=new WeakMap,sv=new WeakMap,av=new WeakMap,Hm=new WeakMap,cv=new WeakMap;ud.NAME="Certificate";var HE=class extends Array{constructor(e){if(super(),Li.isAsnEncoded(e))this.import(e);else if(e instanceof ud)this.push(e);else if(Array.isArray(e))for(let r of e)this.push(r)}export(e){let r=new Bi.SignedData;r.version=1,r.encapContentInfo.eContentType=Bi.id_data,r.encapContentInfo.eContent=new Bi.EncapsulatedContent({single:new ne.OctetString}),r.certificates=new Bi.CertificateSet(this.map(o=>new Bi.CertificateChoices({certificate:ne.AsnConvert.parse(o.rawData,Je.Certificate)})));let n=new Bi.ContentInfo({contentType:Bi.id_signedData,content:ne.AsnConvert.serialize(r)}),i=ne.AsnConvert.serialize(n);return e==="raw"?i:this.toString(e)}import(e){let r=Li.toArrayBuffer(e),n=ne.AsnConvert.parse(r,Bi.ContentInfo);if(n.contentType!==Bi.id_signedData)throw new TypeError("Cannot parse CMS package. Incoming data is not a SignedData object.");let i=ne.AsnConvert.parse(n.content,Bi.SignedData);this.clear();for(let o of i.certificates||[])o.certificate&&this.push(new ud(o.certificate))}clear(){for(;this.pop(););}toString(e="pem"){let r=this.export("raw");switch(e){case"pem":return kn.encode(r,"CMS");case"pem-chain":return this.map(n=>n.toString("pem")).join(`
29
+ `);case"asn":return ne.AsnConvert.toString(r);case"hex":return Se.Convert.ToHex(r);case"base64":return Se.Convert.ToBase64(r);case"base64url":return Se.Convert.ToBase64Url(r);case"text":return fs.serialize(this.toTextObject());default:throw TypeError("Argument 'format' is unsupported value")}}toTextObject(){let e=ne.AsnConvert.parse(this.export("raw"),Bi.ContentInfo),r=ne.AsnConvert.parse(e.content,Bi.SignedData);return new Ut("X509Certificates",{"Content Type":Mo.toString(e.contentType),Content:new Ut("",{Version:`${Bi.CMSVersion[r.version]} (${r.version})`,Certificates:new Ut("",{Certificate:this.map(i=>i.toTextObject())})})})}},oB=class{constructor(e={}){this.certificates=[],e.certificates&&(this.certificates=e.certificates)}async build(e,r=kr.get()){let n=new HE(e),i=e;for(;i=await this.findIssuer(i,r);){let o=await i.getThumbprint(r);for(let s of n){let a=await s.getThumbprint(r);if(Se.isEqual(o,a))throw new Error("Cannot build a certificate chain. Circular dependency.")}n.push(i)}return n}async findIssuer(e,r=kr.get()){if(!await e.isSelfSigned(r)){let n=e.getExtension(re.id_ce_authorityKeyIdentifier);for(let i of this.certificates)if(i.subject===e.issuer){if(n){if(n.keyId){let o=i.getExtension(re.id_ce_subjectKeyIdentifier);if(o&&o.keyId!==n.keyId)continue}else if(n.certId){let o=i.getExtension(re.id_ce_subjectAltName);if(o&&!(n.certId.serialNumber===i.serialNumber&&Se.isEqual(ne.AsnConvert.serialize(n.certId.name),ne.AsnConvert.serialize(o))))continue}}try{let o={...i.publicKey.algorithm,...e.signatureAlgorithm},s=await i.publicKey.export(o,["verify"],r);if(!await e.verify({publicKey:s,signatureOnly:!0},r))continue}catch{continue}return i}}return null}};function uB(t,e=kr.get()){let r=Se.BufferSourceConverter.toUint8Array(Se.Convert.FromHex(t||"")),n=r&&r.length&&r.some(o=>o>0)?new Uint8Array(r):void 0;n||(n=e.getRandomValues(new Uint8Array(16)));let i=0;for(;i<n.length-1&&n[i]===0;)i++;if(n=n.slice(i),n[0]>127){let o=new Uint8Array(n.length+1);o[0]=0,o.set(n,1),n=o}return n.buffer}var sB=class{static async createSelfSigned(e,r=kr.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},r)}static async create(e,r=kr.get()){var n;let i;e.publicKey instanceof ds?i=e.publicKey.rawData:"publicKey"in e.publicKey?i=e.publicKey.publicKey.rawData:Se.BufferSourceConverter.isBufferSource(e.publicKey)?i=e.publicKey:i=await r.subtle.exportKey("spki",e.publicKey);let o=uB(e.serialNumber,r),s=e.notBefore||new Date,a=e.notAfter||new Date(s.getTime()+31536e6),c=new re.Certificate({tbsCertificate:new re.TBSCertificate({version:re.Version.v3,serialNumber:o,validity:new re.Validity({notBefore:s,notAfter:a}),extensions:new re.Extensions(((n=e.extensions)===null||n===void 0?void 0:n.map(b=>ne.AsnConvert.parse(b.rawData,re.Extension)))||[]),subjectPublicKeyInfo:ne.AsnConvert.parse(i,re.SubjectPublicKeyInfo)})});if(e.subject){let b=e.subject instanceof vn?e.subject:new vn(e.subject);c.tbsCertificate.subject=ne.AsnConvert.parse(b.toArrayBuffer(),re.Name)}if(e.issuer){let b=e.issuer instanceof vn?e.issuer:new vn(e.issuer);c.tbsCertificate.issuer=ne.AsnConvert.parse(b.toArrayBuffer(),re.Name)}let u={hash:"SHA-256"},d="signingKey"in e?{...u,...e.signingAlgorithm,...e.signingKey.algorithm}:{...u,...e.signingAlgorithm},l=yr.container.resolve(ls);c.tbsCertificate.signature=c.signatureAlgorithm=l.toAsnAlgorithm(d);let f=ne.AsnConvert.serialize(c.tbsCertificate),p="signingKey"in e?await r.subtle.sign(d,e.signingKey,f):e.signature,g=yr.container.resolveAll(xc).reverse(),v=null;for(let b of g)if(v=b.toAsnSignature(d,p),v)break;if(!v)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return c.signatureValue=v,new ud(ne.AsnConvert.serialize(c))}},uv,dv,Um,$m,Fm;_e.X509CrlReason=void 0;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(_e.X509CrlReason||(_e.X509CrlReason={}));var zm=class extends sa{get serialNumber(){return ie.__classPrivateFieldGet(this,uv,"f")||ie.__classPrivateFieldSet(this,uv,Se.Convert.ToHex(this.asn.userCertificate),"f"),ie.__classPrivateFieldGet(this,uv,"f")}get revocationDate(){return ie.__classPrivateFieldGet(this,dv,"f")||ie.__classPrivateFieldSet(this,dv,this.asn.revocationDate.getTime(),"f"),ie.__classPrivateFieldGet(this,dv,"f")}get reason(){return ie.__classPrivateFieldGet(this,Um,"f")===void 0&&this.extensions,ie.__classPrivateFieldGet(this,Um,"f")}get invalidity(){return ie.__classPrivateFieldGet(this,$m,"f")===void 0&&this.extensions,ie.__classPrivateFieldGet(this,$m,"f")}get extensions(){return ie.__classPrivateFieldGet(this,Fm,"f")||(ie.__classPrivateFieldSet(this,Fm,[],"f"),this.asn.crlEntryExtensions&&ie.__classPrivateFieldSet(this,Fm,this.asn.crlEntryExtensions.map(e=>{let r=Rn.create(ne.AsnConvert.serialize(e));switch(r.type){case Je.id_ce_cRLReasons:ie.__classPrivateFieldGet(this,Um,"f")===void 0&&ie.__classPrivateFieldSet(this,Um,ne.AsnConvert.parse(r.value,Je.CRLReason).reason,"f");break;case Je.id_ce_invalidityDate:ie.__classPrivateFieldGet(this,$m,"f")===void 0&&ie.__classPrivateFieldSet(this,$m,ne.AsnConvert.parse(r.value,Je.InvalidityDate).value,"f");break}return r}),"f")),ie.__classPrivateFieldGet(this,Fm,"f")}constructor(...e){let r;if(Se.BufferSourceConverter.isBufferSource(e[0])?r=Se.BufferSourceConverter.toArrayBuffer(e[0]):typeof e[0]=="string"?r=ne.AsnConvert.serialize(new Je.RevokedCertificate({userCertificate:uB(e[0]),revocationDate:new Je.Time(e[1]),crlEntryExtensions:e[2]})):e[0]instanceof Je.RevokedCertificate&&(r=e[0]),!r)throw new TypeError("Cannot create X509CrlEntry instance. Wrong constructor arguments.");super(r,Je.RevokedCertificate),uv.set(this,void 0),dv.set(this,void 0),Um.set(this,void 0),$m.set(this,void 0),Fm.set(this,void 0)}onInit(e){}};uv=new WeakMap,dv=new WeakMap,Um=new WeakMap,$m=new WeakMap,Fm=new WeakMap;var lv,fv,pv,mv,hv,gv,jm,UE=class extends Li{get version(){return this.asn.tbsCertList.version}get signatureAlgorithm(){if(!ie.__classPrivateFieldGet(this,fv,"f")){let e=yr.container.resolve(ls);ie.__classPrivateFieldSet(this,fv,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return ie.__classPrivateFieldGet(this,fv,"f")}get signature(){return this.asn.signature}get issuer(){return this.issuerName.toString()}get issuerName(){return ie.__classPrivateFieldGet(this,pv,"f")||ie.__classPrivateFieldSet(this,pv,new vn(this.asn.tbsCertList.issuer),"f"),ie.__classPrivateFieldGet(this,pv,"f")}get thisUpdate(){if(!ie.__classPrivateFieldGet(this,mv,"f")){let e=this.asn.tbsCertList.thisUpdate.getTime();if(!e)throw new Error("Cannot get 'thisUpdate' value");ie.__classPrivateFieldSet(this,mv,e,"f")}return ie.__classPrivateFieldGet(this,mv,"f")}get nextUpdate(){var e;return ie.__classPrivateFieldGet(this,hv,"f")===void 0&&ie.__classPrivateFieldSet(this,hv,((e=this.asn.tbsCertList.nextUpdate)===null||e===void 0?void 0:e.getTime())||void 0,"f"),ie.__classPrivateFieldGet(this,hv,"f")}get entries(){var e;return ie.__classPrivateFieldGet(this,gv,"f")||ie.__classPrivateFieldSet(this,gv,((e=this.asn.tbsCertList.revokedCertificates)===null||e===void 0?void 0:e.map(r=>new zm(r)))||[],"f"),ie.__classPrivateFieldGet(this,gv,"f")}get extensions(){return ie.__classPrivateFieldGet(this,jm,"f")||(ie.__classPrivateFieldSet(this,jm,[],"f"),this.asn.tbsCertList.crlExtensions&&ie.__classPrivateFieldSet(this,jm,this.asn.tbsCertList.crlExtensions.map(e=>Rn.create(ne.AsnConvert.serialize(e))),"f")),ie.__classPrivateFieldGet(this,jm,"f")}get tbs(){return ie.__classPrivateFieldGet(this,lv,"f")||ie.__classPrivateFieldSet(this,lv,this.asn.tbsCertListRaw||ne.AsnConvert.serialize(this.asn.tbsCertList),"f"),ie.__classPrivateFieldGet(this,lv,"f")}get tbsCertListSignatureAlgorithm(){return this.asn.tbsCertList.signature}get certListSignatureAlgorithm(){return this.asn.signatureAlgorithm}constructor(e){super(e,Li.isAsnEncoded(e)?Je.CertificateList:void 0),this.tag=kn.CrlTag,lv.set(this,void 0),fv.set(this,void 0),pv.set(this,void 0),mv.set(this,void 0),hv.set(this,void 0),gv.set(this,void 0),jm.set(this,void 0)}onInit(e){}getExtension(e){for(let r of this.extensions)if(typeof e=="string"){if(r.type===e)return r}else if(r instanceof e)return r;return null}getExtensions(e){return this.extensions.filter(r=>typeof e=="string"?r.type===e:r instanceof e)}async verify(e,r=kr.get()){if(!this.certListSignatureAlgorithm.isEqual(this.tbsCertListSignatureAlgorithm))throw new Error("algorithm identifier in the sequence tbsCertList and CertificateList mismatch");let n,i,o=e.publicKey;try{o instanceof ud?(n={...o.publicKey.algorithm,...o.signatureAlgorithm},i=await o.publicKey.export(n,["verify"])):o instanceof ds?(n={...o.algorithm,...this.signatureAlgorithm},i=await o.export(n,["verify"])):(n={...o.algorithm,...this.signatureAlgorithm},i=o)}catch{return!1}let s=yr.container.resolveAll(xc).reverse(),a=null;for(let c of s)if(a=c.toWebSignature(n,this.signature),a)break;if(!a)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return await r.subtle.verify(this.signatureAlgorithm,i,a,this.tbs)}async getThumbprint(...e){let r,n="SHA-1";return e[0]&&(e[0].subtle?r=e[0]:(n=e[0]||n,r=e[1])),r??(r=kr.get()),await r.subtle.digest(n,this.rawData)}findRevoked(e){let r=typeof e=="string"?e:e.serialNumber,n=uB(r);for(let i of this.asn.tbsCertList.revokedCertificates||[])if(Se.BufferSourceConverter.isEqual(i.userCertificate,n))return new zm(ne.AsnConvert.serialize(i));return null}};lv=new WeakMap,fv=new WeakMap,pv=new WeakMap,mv=new WeakMap,hv=new WeakMap,gv=new WeakMap,jm=new WeakMap;var aB=class{static async create(e,r=kr.get()){var n;let i=e.issuer instanceof vn?e.issuer:new vn(e.issuer),o=new re.CertificateList({tbsCertList:new re.TBSCertList({version:re.Version.v2,issuer:ne.AsnConvert.parse(i.toArrayBuffer(),re.Name),thisUpdate:new Je.Time(e.thisUpdate||new Date)})});if(e.nextUpdate&&(o.tbsCertList.nextUpdate=new Je.Time(e.nextUpdate)),e.extensions&&e.extensions.length&&(o.tbsCertList.crlExtensions=new re.Extensions(e.extensions.map(f=>ne.AsnConvert.parse(f.rawData,re.Extension))||[])),e.entries&&e.entries.length){o.tbsCertList.revokedCertificates=[];for(let f of e.entries){let p=Li.toArrayBuffer(f.serialNumber);if(o.tbsCertList.revokedCertificates.findIndex(b=>Se.isEqual(b.userCertificate,p))>-1)throw new Error(`Certificate serial number ${f.serialNumber} already exists in tbsCertList`);let v=new Je.RevokedCertificate({userCertificate:p,revocationDate:new Je.Time(f.revocationDate||new Date)});if("extensions"in f&&(!((n=f.extensions)===null||n===void 0)&&n.length)?v.crlEntryExtensions=f.extensions.map(b=>ne.AsnConvert.parse(b.rawData,re.Extension)):v.crlEntryExtensions=[],!(f instanceof zm)&&(f.reason&&v.crlEntryExtensions.push(new re.Extension({extnID:re.id_ce_cRLReasons,critical:!1,extnValue:new ne.OctetString(ne.AsnConvert.serialize(new re.CRLReason(f.reason)))})),f.invalidity&&v.crlEntryExtensions.push(new re.Extension({extnID:re.id_ce_invalidityDate,critical:!1,extnValue:new ne.OctetString(ne.AsnConvert.serialize(new re.InvalidityDate(f.invalidity)))})),f.issuer)){let b=e.issuer instanceof vn?e.issuer:new vn(e.issuer);v.crlEntryExtensions.push(new re.Extension({extnID:re.id_ce_certificateIssuer,critical:!1,extnValue:new ne.OctetString(ne.AsnConvert.serialize(ne.AsnConvert.parse(b.toArrayBuffer(),re.Name)))}))}o.tbsCertList.revokedCertificates.push(v)}}let s={...e.signingAlgorithm,...e.signingKey.algorithm},a=yr.container.resolve(ls);o.tbsCertList.signature=o.signatureAlgorithm=a.toAsnAlgorithm(s);let c=ne.AsnConvert.serialize(o.tbsCertList),u=await r.subtle.sign(s,e.signingKey,c),d=yr.container.resolveAll(xc).reverse(),l=null;for(let f of d)if(l=f.toAsnSignature(s,u),l)break;if(!l)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return o.signature=l,new UE(ne.AsnConvert.serialize(o))}};Rn.register(re.id_ce_basicConstraints,bv);Rn.register(re.id_ce_extKeyUsage,wv);Rn.register(re.id_ce_keyUsage,Iv);Rn.register(re.id_ce_subjectKeyIdentifier,Ev);Rn.register(re.id_ce_authorityKeyIdentifier,Sv);Rn.register(re.id_ce_subjectAltName,kv);Rn.register(re.id_ce_cRLDistributionPoints,Av);Rn.register(re.id_pe_authorityInfoAccess,Cv);Rn.register(re.id_ce_issuerAltName,Pv);af.register(qm.id_pkcs9_at_challengePassword,_v);af.register(qm.id_pkcs9_at_extensionRequest,Gm);yr.container.registerSingleton(xc,LE);yr.container.registerSingleton(xc,ca);ca.namedCurveSize.set("P-256",32);ca.namedCurveSize.set("K-256",32);ca.namedCurveSize.set("P-384",48);ca.namedCurveSize.set("P-521",66);_e.AlgorithmProvider=OE;_e.AsnData=sa;_e.AsnDefaultSignatureFormatter=LE;_e.AsnEcSignatureFormatter=ca;_e.Attribute=sf;_e.AttributeFactory=af;_e.AuthorityInfoAccessExtension=Cv;_e.AuthorityKeyIdentifierExtension=Sv;_e.BasicConstraintsExtension=bv;_e.CRLDistributionPointsExtension=Av;_e.CertificatePolicyExtension=Rv;_e.ChallengePasswordAttribute=_v;_e.CryptoProvider=Wm;_e.DN=EE;_e.DNS=IE;_e.DefaultAlgorithmSerializer=ME;_e.EMAIL=kE;_e.ExtendedKeyUsageExtension=wv;_e.Extension=Oi;_e.ExtensionFactory=Rn;_e.ExtensionsAttribute=Gm;_e.GUID=CE;_e.GeneralName=us;_e.GeneralNames=aa;_e.IP=RE;_e.IssuerAlternativeNameExtension=Pv;_e.KeyUsagesExtension=Iv;_e.Name=vn;_e.NameIdentifier=vv;_e.OidSerializer=Mo;_e.PemConverter=kn;_e.PemData=Li;_e.Pkcs10CertificateRequest=Tv;_e.Pkcs10CertificateRequestGenerator=iB;_e.PublicKey=ds;_e.REGISTERED_ID=Wy;_e.SubjectAlternativeNameExtension=kv;_e.SubjectKeyIdentifierExtension=Ev;_e.TextConverter=fs;_e.TextObject=Ut;_e.UPN=PE;_e.URL=AE;_e.X509Certificate=ud;_e.X509CertificateGenerator=sB;_e.X509Certificates=HE;_e.X509ChainBuilder=oB;_e.X509Crl=UE;_e.X509CrlEntry=zm;_e.X509CrlGenerator=aB;_e.cryptoProvider=kr;_e.diAlgorithm=Km;_e.diAlgorithmProvider=ls;_e.diAsnSignatureFormatter=xc;_e.idEd25519=DE;_e.idEd448=nB;_e.idX25519=TE;_e.idX448=rB});var zq=ce((VGe,Gq)=>{"use strict";function Rbe(t){return/^[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc0-9\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19d9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]*$/.test(t)}Gq.exports=Rbe});var Bv=ce((GGe,rW)=>{var Kq=Nt("node:util"),Qq=zq(),Jq=/[\{\[]/,Xq=/[\}\]]/,Yq=["do","if","in","for","let","new","try","var","case","else","enum","eval","null","this","true","void","with","await","break","catch","class","const","false","super","throw","while","yield","delete","export","import","public","return","static","switch","typeof","default","extends","finally","package","private","continue","debugger","function","arguments","interface","protected","implements","instanceof","NaN","undefined"],Zq={};for($E=0;$E<Yq.length;$E++)Zq[Yq[$E]]=!0;var $E,Abe=function(t){return Qq(t)&&!Zq.hasOwnProperty(t)},eW={s:function(t){return""+t},d:function(t){return""+Number(t)},o:function(t){return JSON.stringify(t)}},tW=function(){var t=[],e=0,r={},n=function(s){for(var a="";a.length<e*2;)a+=" ";t.push(a+s)},i=function(s){if(Xq.test(s.trim()[0])&&Jq.test(s[s.length-1])){e--,n(s),e++;return}if(Jq.test(s[s.length-1])){n(s),e++;return}if(Xq.test(s.trim()[0])){e--,n(s);return}n(s)},o=function(s){if(!s)return o;if(arguments.length===1&&s.indexOf(`
30
+ `)>-1)for(var a=s.trim().split(`
31
+ `),c=0;c<a.length;c++)i(a[c].trim());else i(Kq.format.apply(Kq,arguments));return o};return o.scope={},o.formats=eW,o.sym=function(s){return(!s||!Abe(s))&&(s="tmp"),r[s]||(r[s]=0),s+(r[s]++||"")},o.property=function(s,a){return arguments.length===1&&(a=s,s=""),a=a+"",Qq(a)?s?s+"."+a:a:s?s+"["+JSON.stringify(a)+"]":JSON.stringify(a)},o.toString=function(){return t.join(`
32
+ `)},o.toFunction=function(s){s||(s={});var a="return ("+o.toString()+")";Object.keys(o.scope).forEach(function(d){s[d]||(s[d]=o.scope[d])});var c=Object.keys(s).map(function(d){return d}),u=c.map(function(d){return s[d]});return Function.apply(null,c.concat(a)).apply(null,u)},arguments.length&&o.apply(null,arguments),o};tW.formats=eW;rW.exports=tW});var iW=ce((zGe,nW)=>{"use strict";var jE=class{constructor(){this.next=null,this.buffer=null}};nW.exports=class FE{constructor(){this.head=null,this.tail=null,this.length=0,this.count=0}push(e){let r=new jE;r.buffer=e,this.length>0?this.tail.next=r:this.head=r,this.tail=r,this.length+=e.length,this.count+=1}unshift(e){let r=new jE;r.buffer=e,r.next=this.head,this.isEmpty()&&(this.tail=r),this.head=r,this.length+=e.length,this.count+=1}shift(){if(this.isEmpty())return null;let e=this.head.buffer;return this.head===this.tail?(this.head=null,this.tail=null):this.head=this.head.next,this.length-=e.length,this.length=Math.max(this.length,0),this.count-=1,e}get first(){return this.isEmpty()?null:this.head.buffer}get last(){return this.isEmpty()?null:this.tail.buffer}isEmpty(){return this.length===0}clear(){this.head=null,this.tail=null,this.length=0,this.count=0}slice(e,r){if(e<0||e>=this.length)return new FE;if(r<0||r>this.length||r<e)return new FE;let n=new FE,i=this.head,o=e,s=r;for(;i;){if(i.buffer.length>o){o===0&&i.buffer.length<=s?n.push(i.buffer):i.buffer.length>=s?n.push(i.buffer.slice(o,s)):n.push(i.buffer.slice(o));break}o-=i.buffer.length,s-=i.buffer.length,i=i.next}if(i.buffer.length<s)for(;i;){if(i.buffer.length===s){n.push(i.buffer);break}else if(i.buffer.length>s){n.push(i.buffer.slice(0,s));break}else o<0&&i.buffer.length<s&&n.push(i.buffer);o-=i.buffer.length,s-=i.buffer.length,i=i.next}return n}}});var cW=ce((KGe,aW)=>{"use strict";var qE=Bv(),Cbe=iW(),cf=class t{constructor(){this.queue=new Cbe,this.offset=0}get length(){return this.queue.length-this.offset}append(e){if(Buffer.isBuffer(e)){if(this.offset>0){let r=this.queue.shift();this.queue.unshift(r.slice(this.offset)),this.offset=0}this.queue.push(e)}else if(Array.isArray(e))for(let r=0;r<e.length;r+=1)this.append(e[r]);else if(e instanceof t){if(this.offset>0){let n=this.queue.shift();this.queue.unshift(n.slice(this.offset)),this.offset=0}if(e.offset>0){let n=e.queue.shift();e.queue.unshift(n.slice(e.offset)),e.offset=0}let r=e.queue.head;for(;r;)this.queue.push(r.buffer),r=r.next}}get(e){let r=e;for(;r>=this.length;)r-=this.length;for(;r<0;)r+=this.length;let n=this.queue.head,{offset:i}=this;for(;n;){if(n.buffer.length-i>r)return n.buffer[r+i];r-=n.buffer.length-i,i=0,n=n.next}}slice(e,r){for(typeof e!="number"&&(e=0),typeof r!="number"&&(r=this.length);e<0;)e+=this.length;for(;r<0;)r+=this.length;if(r=Math.min(r,this.length),e>=this.length||r===0)return Buffer.alloc(0);let n=e;e=Math.min(n,r),r=Math.max(n,r);let i=this.queue.slice(e+this.offset,r+this.offset);if(i.count===1)return i.first;let o=i.head,s=Buffer.allocUnsafe(i.length),a=0;for(let c=0;c<i.count;c+=1)s.set(o.buffer,a),a+=o.buffer.length,o=o.next;return s}toString(e,r,n){return this.slice(r,n).toString(e)}consume(e){let r=e;for(;this.length>0;){let n=this.queue.first.length-this.offset;if(r>=n)this.queue.shift(),r-=n,this.offset=0;else{this.offset+=r;break}}}indexOf(e,r=0){if(!Number.isInteger(e))throw new TypeError("Invalid argument 1");if(e<0||e>255)throw new Error("Invalid argument 1");for(Number.isInteger(r)||(r=0);r>=this.length;)r-=this.length;for(;r<0;)r+=this.length;let n=this.queue.head,i=0,o=()=>{i+=n.buffer.length,n=n.next};for(;n;){let s=0;if(n===this.queue.head&&(s+=this.offset),r>=n.buffer.length-s){r-=n.buffer.length-s,o();continue}r<n.buffer.length&&(s+=r);let a=n.buffer.indexOf(e,s);if(a>-1)return a+i-this.offset;o(),s>this.offset&&(r=0)}return-1}},oW={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1};Object.keys(oW).forEach(t=>{let e=qE();e(`
33
+ function bufferlist_${t}(offset = 0) {
34
+ const start = offset + this.offset;
35
+ const head = this.queue.first;
36
+ const size = ${e.formats.d(oW[t])};
37
+ const isFirtsChunkEnough = head.length - start >= size;
38
+
39
+ return isFirtsChunkEnough
40
+ ? head.${t}(start)
41
+ : this.slice(offset, offset + size).${t}(0)
42
+ }
43
+ `),cf.prototype[t]=e.toFunction()});var Pbe=["readIntBE","readIntLE","readUIntBE","readUIntLE"];Pbe.forEach(t=>{let e=qE();e(`
44
+ function bufferlist_${t}(size, offset = 0) {
45
+ const start = offset + this.offset;
46
+ const head = this.queue.first;
47
+ const isFirtsChunkEnough = head.length - start >= size;
48
+
49
+ return isFirtsChunkEnough
50
+ ? head.${t}(start, size)
51
+ : this.slice(offset, offset + size).${t}(0, size)
52
+ }
53
+ `),cf.prototype[t]=e.toFunction()});var sW={writeDoubleBE:8,writeDoubleLE:8,writeFloatBE:4,writeFloatLE:4,writeInt32BE:4,writeInt32LE:4,writeUInt32BE:4,writeUInt32LE:4,writeInt16BE:2,writeInt16LE:2,writeUInt16BE:2,writeUInt16LE:2,writeInt8:1,writeUInt8:1};Object.keys(sW).forEach(t=>{let e=qE();e(`
54
+ function bufferlist_${t}(value) {
55
+ const size = ${e.formats.d(sW[t])};
56
+ const buf = Buffer.allocUnsafe(size);
57
+ buf.${t}(value, 0);
58
+ this.append(buf);
59
+ }
60
+ `),cf.prototype[t]=e.toFunction()});var _be=["writeIntBE","writeIntLE","writeUIntBE","writeUIntLE"];_be.forEach(t=>{let e=qE();e(`
61
+ function bufferlist_${t}(value, size) {
62
+ const buf = Buffer.allocUnsafe(size);
63
+ buf.${t}(value, 0, size);
64
+ this.append(buf);
65
+ }
66
+ `),cf.prototype[t]=e.toFunction()});aW.exports=cf});var Jm=ce((XGe,uW)=>{"use strict";uW.exports=class extends Error{constructor(e,r){let n=`requested ${e} bytes but only ${r} available`;super(n),this.name="NotEnoughDataError"}}});var Nv=ce((YGe,fW)=>{"use strict";var{Transform:Tbe}=Nt("node:stream"),WE=Bv(),Dbe=cW(),Bbe=Jm(),dW=Symbol("buffer"),uf=class extends Tbe{constructor(e={}){super(e),this[dW]=new Dbe}get buffer(){return this[dW]}get length(){return this.buffer.length}append(e){this.buffer.append(e)}get(e){return this.buffer.get(e)}slice(e,r){return this.buffer.slice(e,r)}consume(e){this.buffer.consume(e)}toString(e,r,n){return this.buffer.toString(e,r,n)}indexOf(e,r=0){return this.buffer.indexOf(e,r)}readBuffer(e){dB(e,this.length);let r=this.slice(0,e);return this.consume(e),r}writeBuffer(e){this.append(e)}},lW={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1},Nbe=["readIntBE","readIntLE","readUIntBE","readUIntLE"];Object.keys(lW).forEach(t=>{let e=WE();e(`
67
+ function binary_${t}() {
68
+ const bytes = ${e.formats.d(lW[t])};
69
+ assertSize(bytes, this.length);
70
+
71
+ const res = this.buffer.${t}(0);
72
+ this.consume(bytes);
73
+
74
+ return res;
75
+ }
76
+ `),uf.prototype[t]=e.toFunction({assertSize:dB})});Nbe.forEach(t=>{let e=WE();e(`
77
+ function binary_${t}(size) {
78
+ assertSize(size, this.length);
79
+
80
+ const res = this.buffer.${t}(size, 0);
81
+ this.consume(size);
82
+ return res;
83
+ }
84
+ `),uf.prototype[t]=e.toFunction({assertSize:dB})});var Obe=["writeDoubleBE","writeDoubleLE","writeFloatBE","writeFloatLE","writeInt32BE","writeInt32LE","writeUInt32BE","writeUInt32LE","writeInt16BE","writeInt16LE","writeUInt16BE","writeUInt16LE","writeInt8","writeUInt8"];Obe.forEach(t=>{let e=WE();e(`
85
+ function binary_${t}(value) {
86
+ this.buffer.${t}(value);
87
+ }
88
+ `),uf.prototype[t]=e.toFunction()});var Mbe=["writeIntBE","writeIntLE","writeUIntBE","writeUIntLE"];Mbe.forEach(t=>{let e=WE();e(`
89
+ function binary_${t}(value, size) {
90
+ this.buffer.${t}(value, size);
8
91
  }
9
- if (parsed.command && parsed.command !== "start" && parsed.command !== "studio") {
10
- throw new Error(`Unknown command: ${parsed.command}`);
92
+ `),uf.prototype[t]=e.toFunction()});function dB(t,e){if(t>e)throw new Bbe(t,e)}fW.exports=uf});var mW=ce((QGe,pW)=>{"use strict";pW.exports=function(e){return e!=null&&typeof e=="object"&&Array.isArray(e)===!1}});var yW=ce((ZGe,gW)=>{"use strict";var Lbe=mW();function hW(t){return Lbe(t)===!0&&Object.prototype.toString.call(t)==="[object Object]"}gW.exports=function(e){var r,n;return!(hW(e)===!1||(r=e.constructor,typeof r!="function")||(n=r.prototype,hW(n)===!1)||n.hasOwnProperty("isPrototypeOf")===!1)}});var ua=ce((eze,vW)=>{"use strict";var Hbe=yW();vW.exports={isType:Ube,isUserType:Hbe,isFunction:Ov,isDecodeType:$be,isEncodeType:Fbe};function Ube(t){return lB(t)&&Ov(t.encode)&&Ov(t.decode)}function Ov(t){return typeof t=="function"}function lB(t){return typeof t=="object"&&t!==null}function $be(t){return lB(t)&&Ov(t.decode)}function Fbe(t){return lB(t)&&Ov(t.encode)}});var dd=ce((tze,xW)=>{"use strict";var jbe=Symbol("skip"),qbe=Symbol("bytes");xW.exports={skip:jbe,bytes:qbe}});var ld=ce((rze,bW)=>{"use strict";var SW=dd();bW.exports=class VE{constructor(){this[SW.bytes]=0,this.node=void 0,this.current=void 0}get bytes(){return this[SW.bytes]}static clone(e){let r=new VE;return e instanceof VE&&(r.node=e.node,r.current=e.current),r}static clean(e){e instanceof VE&&(e.node=void 0,e.current=void 0)}}});var Xm=ce((nze,RW)=>{"use strict";var{isType:Wbe,isUserType:Vbe,isDecodeType:Gbe}=ua(),zbe=Nv(),fB=dd(),wW=ld();RW.exports={decode:IW,decodeCommon:EW};function IW(t,e){let r=t;Buffer.isBuffer(t)&&(r=new zbe,r.append(t));let n=new wW,i=EW(r,e,n);return IW.bytes=n.bytes,wW.clean(n),i}function EW(t,e,r){if(Wbe(e)){let n=e.decode.call(r,t);return r[fB.bytes]+=e.decode.bytes,n}return kW(t,e,r)}function kW(t,e,r){Kbe(e);let n=Object.create(null);r.node===void 0&&(r.node=n),r.current=n;let i=Object.keys(e);for(let o=0;o<i.length;o+=1){let s=i[o],a=e[s];if(!Gbe(a)){n[s]=kW(t,a,r),r.current=n;continue}let c=a.decode.call(r,t);r[fB.bytes]+=a.decode.bytes,a[fB.skip]!==!0&&(n[s]=c)}return n}function Kbe(t){if(!Vbe(t))throw new TypeError("Argument #2 should be a plain object.")}});var Mv=ce((ize,DW)=>{"use strict";var{isUserType:Jbe,isEncodeType:Xbe,isType:Ybe}=ua(),CW=dd(),AW=ld(),pB=Nv();DW.exports={encode:PW,encodeCommon:_W};function PW(t,e,r){let n=new AW;if(e instanceof pB){let i=r;r=e,e=i}return r instanceof pB||(r=new pB),_W(t,r,e,n),PW.bytes=n.bytes,AW.clean(n),r}function _W(t,e,r,n){Ybe(r)?(r.encode.call(n,t,e),n[CW.bytes]+=r.encode.bytes):TW(t,e,r,n)}function TW(t,e,r,n){Qbe(r),n.node===void 0&&(n.node=t),n.current=t;let i=Object.keys(r);for(let o=0;o<i.length;o+=1){let s=i[o],a=r[s],c=t[s];if(!Xbe(a)){TW(c,e,a,n),n.current=t;continue}a.encode.call(n,c,e),n[CW.bytes]+=a.encode.bytes}}function Qbe(t){if(!Jbe(t))throw new TypeError("Argument `schema` should be a plain object.")}});var Lv=ce((oze,HW)=>{"use strict";var{isUserType:Zbe,isType:NW}=ua(),BW=ld(),OW=dd();HW.exports={encodingLength:ewe,encodingLengthCommon:MW};function ewe(t,e){let r=new BW;return MW(t,e,r),BW.clean(r),r.bytes}function MW(t,e,r){NW(e)?r[OW.bytes]+=e.encodingLength.call(r,t):LW(t,e,r)}function LW(t,e,r){if(!Zbe(e))throw new TypeError("Argument `schema` should be a plain object.");r.node===void 0&&(r.node=t),r.current=t;let n=Object.keys(e);for(let i=0;i<n.length;i+=1){let o=n[i],s=e[o],a=t[o];if(!NW(s)){LW(a,s,r),r.current=t;continue}r[OW.bytes]+=s.encodingLength.call(r,a)}}});var GW=ce((sze,VW)=>{"use strict";var{decodeCommon:WW}=Xm(),{encodeCommon:twe}=Mv(),{encodingLengthCommon:UW}=Lv(),{isType:$W,isUserType:rwe,isFunction:nwe}=ua(),fd=ld();VW.exports=iwe;function iwe(t,e,r="count"){if(!$W(t)&&!rwe(t))throw new TypeError("Argument #1 should be a valid type.");let n=r==="bytes",i=typeof e=="number",o=$W(e),s=nwe(e);if(!i&&!o&&!s)throw new TypeError("Unknown type of argument #1.");return{encode:a,decode:c,encodingLength:u};function a(d,l){FW(d);let f=fd.clone(this);a.bytes=0;let p=0;if(o?p=d.length:i?p=e:s&&(p=e(f),jW(p)),n||qW(p,d.length),n){let g=fd.clone(f);for(let v of d)UW(v,t,g);o&&(p=g.bytes),qW(g.bytes,p),fd.clean(g)}o&&(e.encode.call(f,p,l),a.bytes+=e.encode.bytes),d.forEach(g=>{twe(g,l,t,f)}),a.bytes+=f.bytes,fd.clean(f)}function c(d){let l=0;c.bytes=0;let f=fd.clone(this);i?l=e:o?(l=e.decode.call(f,d),c.bytes+=e.decode.bytes):s&&(l=e(f)),jW(l);let p;return n?p=owe(t,l,d,f):p=swe(t,l,d,f),c.bytes+=f.bytes,fd.clean(f),p}function u(d){FW(d);let l=fd.clone(this),f=0;if(i&&n)return e;o&&!n&&(f=e.encodingLength(d.length));for(let p of d)UW(p,t,l);return fd.clean(l),f+=l.bytes,o&&n&&(f+=e.encodingLength(f)),f}}function FW(t){if(!Array.isArray(t))throw new TypeError("Argument #1 should be an Array.")}function jW(t){if(typeof t!="number")throw new TypeError("Length of an array should be a number.")}function qW(t,e){if(t!==e)throw new Error(`Argument #1 required length ${t} instead of ${e}`)}function owe(t,e,r,n){let i=[],o=n.bytes,s=0;for(;s<e;)i.push(WW(r,t,n)),s=n.bytes-o;if(s>e)throw new Error("Incorrect length of an array.");return i}function swe(t,e,r,n){let i=new Array(e);for(let o=0;o<e;o+=1)i[o]=WW(r,t,n);return i}});var XW=ce((aze,JW)=>{"use strict";var{isType:awe,isFunction:cwe}=ua(),uwe=Jm(),dwe=Nv();JW.exports=lwe;function lwe(t){let e=typeof t=="number",r=awe(t),n=cwe(t),i=t===null;if(!e&&!r&&!n&&!i)throw new TypeError("Unknown type of argument #1.");return{encode:o,decode:s,encodingLength:a};function o(c,u){zW(c),o.bytes=0;let d=this;if(e&&KW(t,c.length),r&&(t.encode.call(d,c.length,u),o.bytes+=t.encode.bytes),n){let l=t(d);mB(l),KW(l,c.length)}u.writeBuffer(Buffer.isBuffer(c)?c:c.buffer),o.bytes+=c.length,i&&(u.writeUInt8(0),o.bytes+=1)}function s(c){let u=0;s.bytes=0;let d=this;if(e)u=t;else if(r)u=t.decode.call(d,c),s.bytes+=t.decode.bytes,mB(u);else if(n)u=t(d),mB(u);else if(i&&(u=c.indexOf(0),u===-1))throw new uwe(c.length+1,c.length);let l=c.readBuffer(u);return s.bytes+=u,i&&(s.bytes+=1,c.consume(1)),l}function a(c){zW(c);let u=0;return e?t:(i?u=1:r&&(u=t.encodingLength(c.length)),u+c.length)}}function zW(t){if(!Buffer.isBuffer(t)&&!(t instanceof dwe))throw new TypeError("Argument 1 should be a Buffer or a BinaryStream.")}function KW(t,e){if(t!==e)throw new Error(`Buffer required length ${t} instead of ${e}`)}function mB(t){if(typeof t!="number")throw new TypeError("Length of a buffer should be a number.")}});var QW=ce((cze,YW)=>{"use strict";var{isType:fwe}=ua();YW.exports=pwe;function pwe(t){if(!fwe(t))throw new TypeError("Argument #1 should be valid type.");function e(n){let i=this,o=t.decode.call(i,n);return e.bytes=t.decode.bytes,!!o}function r(n,i){let o=this;t.encode.call(o,n?1:0,i),r.bytes=t.encode.bytes}return{encode:r,decode:e,encodingLength:t.encodingLength}}});var eV=ce((uze,ZW)=>{"use strict";var{decodeCommon:mwe}=Xm(),{encodeCommon:hwe}=Mv(),{encodingLengthCommon:gwe}=Lv(),{isType:ywe,isFunction:GE}=ua(),vwe=dd(),pd=ld();ZW.exports=xwe;function xwe(t,e=1){if(!ywe(t))throw new TypeError("Invalid data type.");if(!Number.isInteger(e)&&!GE(e))throw new TypeError("Argument #2 should be a valid integer or function.");return{[vwe.skip]:!0,encodingLength:r,decode:n,encode:i};function r(o){let s=pd.clone(this),a=GE(e)?e(s):e;return gwe(o,t,s),pd.clean(s),s.bytes*a}function n(o){let s=pd.clone(this);n.bytes=0;let a=GE(e)?e(s):e;if(a===0){pd.clean(s);return}for(let c=a;c>0;c-=1)mwe(o,t,s);n.bytes=s.bytes,pd.clean(s)}function i(o,s){i.bytes=0;let a=pd.clone(this),c=GE(e)?e(a):e;if(c===0){pd.clean(a);return}for(let u=c;u>0;u-=1)hwe(0,s,t,a);i.bytes=a.bytes,pd.clean(a)}}});var nV=ce((dze,rV)=>{"use strict";var{isType:Swe}=ua(),bwe=Jm();rV.exports=wwe;function wwe(t,e="ascii"){if(!Buffer.isEncoding(e))throw new Error("Argument #2 should be an encoding name.");if(typeof t=="number")return{encode:kwe(t,e),decode:Rwe(t,e),encodingLength:()=>t};if(Swe(t))return{encode:Awe(t,e),decode:Cwe(t,e),encodingLength:Pwe(t,e)};if(t===null)return{encode:Iwe(e),decode:Ewe(e),encodingLength(r){return Buffer.byteLength(r,e)+1}};if(typeof t=="function")return{encode:_we(t,e),decode:Twe(t,e),encodingLength(r){return Buffer.byteLength(r,e)}};throw new TypeError("Unknown type of argument #1.")}function Iwe(t){return function e(r,n){let i=Buffer.from(r.toString(),t);n.writeBuffer(i),n.writeInt8(0),e.bytes=i.length+1}}function Ewe(t){return function e(r){let n=r.indexOf(0);if(n===-1)throw new bwe(r.length+1,r.length);let i=n+1,o=r.readBuffer(i);return e.bytes=i,o.toString(t,0,n)}}function kwe(t,e){return function r(n,i){if(n=n.toString(),Buffer.byteLength(n,e)!==t)throw new Error(`Size of string should be ${t} in bytes.`);let o=Buffer.from(n,e);i.writeBuffer(o),r.bytes=o.length}}function Rwe(t,e){return function r(n){let i=n.readBuffer(t);return r.bytes=t,i.toString(e)}}function Awe(t,e){return function r(n,i){n=n.toString();let o=this;t.encode.call(o,Buffer.byteLength(n,e),i),r.bytes=t.encode.bytes;let s=Buffer.from(n,e);i.writeBuffer(s),r.bytes+=s.length}}function Cwe(t,e){return function r(n){let i=t.decode.call(this,n);if(typeof i!="number")throw new TypeError("Size of a string should be a number.");let o=n.readBuffer(i);return r.bytes=t.decode.bytes+o.length,o.toString(e)}}function Pwe(t,e){return function(n){let i=Buffer.byteLength(n,e);return t.encodingLength(i)+i}}function _we(t,e){return function r(n,i){r.bytes=0;let s=t(this),a=Buffer.from(n.toString(),e);tV(s),Dwe(s,a.length),i.writeBuffer(a),r.bytes+=a.length}}function Twe(t,e){return function r(n){let i=t(this);tV(i);let o=n.readBuffer(i);return r.bytes=i,o.toString(e)}}function tV(t){if(typeof t!="number")throw new TypeError("Length of a buffer should be a number.")}function Dwe(t,e){if(t!==e)throw new Error(`Buffer required length ${t} instead of ${e}`)}});var oV=ce((lze,iV)=>{"use strict";var zE=Bv();iV.exports={doublebe:Ui(8,"writeDoubleBE","readDoubleBE"),doublele:Ui(8,"writeDoubleLE","readDoubleLE"),floatbe:Ui(4,"writeFloatBE","readFloatBE"),floatle:Ui(4,"writeFloatLE","readFloatLE"),int8:Ui(1,"writeInt8","readInt8"),uint8:Ui(1,"writeUInt8","readUInt8"),int16be:Ui(2,"writeInt16BE","readInt16BE"),uint16be:Ui(2,"writeUInt16BE","readUInt16BE"),int16le:Ui(2,"writeInt16LE","readInt16LE"),uint16le:Ui(2,"writeUInt16LE","readUInt16LE"),int32be:Ui(4,"writeInt32BE","readInt32BE"),uint32be:Ui(4,"writeUInt32BE","readUInt32BE"),int32le:Ui(4,"writeInt32LE","readInt32LE"),uint32le:Ui(4,"writeUInt32LE","readUInt32LE"),int24be:Lo(3,"writeIntBE","readIntBE"),uint24be:Lo(3,"writeUIntBE","readUIntBE"),int24le:Lo(3,"writeIntLE","readIntLE"),uint24le:Lo(3,"writeUIntLE","readUIntLE"),int40be:Lo(5,"writeIntBE","readIntBE"),uint40be:Lo(5,"writeUIntBE","readUIntBE"),int40le:Lo(5,"writeIntLE","readIntLE"),uint40le:Lo(5,"writeUIntLE","readUIntLE"),int48be:Lo(6,"writeIntBE","readIntBE"),uint48be:Lo(6,"writeUIntBE","readUIntBE"),int48le:Lo(6,"writeIntLE","readIntLE"),uint48le:Lo(6,"writeUIntLE","readUIntLE")};function Ui(t,e,r){let n=zE(),i=zE();return n(`
93
+ function decode_${r}(rstream) {
94
+ decode_${r}.bytes = ${n.formats.d(t)};
95
+ return rstream.${r}()
11
96
  }
12
- await startStudioBridge({
13
- cwd: getFlag(parsed, "cwd") ?? process.cwd(),
14
- webUrl: getFlag(parsed, "web-url"),
15
- noOpen: hasFlag(parsed, "no-open"),
16
- dryRun: hasFlag(parsed, "dry-run"),
17
- json: hasFlag(parsed, "json")
18
- });
19
- return 0;
20
- }
21
- function parseArgs(argv) {
22
- const flags = new Map();
23
- let command;
24
- for (let index = 0; index < argv.length; index += 1) {
25
- const token = argv[index];
26
- if (!token.startsWith("--")) {
27
- command ??= token;
28
- continue;
29
- }
30
- const rawName = token.slice(2);
31
- const equalsIndex = rawName.indexOf("=");
32
- if (equalsIndex >= 0) {
33
- flags.set(rawName.slice(0, equalsIndex), rawName.slice(equalsIndex + 1));
34
- continue;
35
- }
36
- const next = argv[index + 1];
37
- if (next && !next.startsWith("--")) {
38
- flags.set(rawName, next);
39
- index += 1;
40
- continue;
41
- }
42
- flags.set(rawName, true);
97
+ `),i(`
98
+ function encode_${e}(value, wstream) {
99
+ wstream.${e}(value);
100
+ encode_${e}.bytes = ${n.formats.d(t)};
43
101
  }
44
- return { command, flags };
45
- }
46
- function getFlag(parsed, name) {
47
- const value = parsed.flags.get(name);
48
- return typeof value === "string" ? value : undefined;
49
- }
50
- function hasFlag(parsed, name) {
51
- return parsed.flags.get(name) === true;
52
- }
53
- function printHelp() {
54
- console.log(`Usage: hunsu-bridge [start|studio] [options]
55
-
56
- Options:
57
- --cwd <path> Repository or workspace path to open. Defaults to the current directory.
58
- --web-url <url> Studio URL to pair with. Defaults to HUNSU_WEB_URL or https://hunsu.app/studio.
59
- --no-open Print the paired Studio URL without opening a browser.
60
- --dry-run Print start information without starting the Bridge server.
61
- --json Print start information as JSON.
62
- --help Show this help.
63
- `);
64
- }
65
- main().then(code => {
66
- process.exitCode = code;
67
- }).catch(error => {
68
- console.error(error instanceof Error ? error.message : String(error));
69
- process.exitCode = 1;
70
- });
102
+ `),{encodingLength:()=>t,encode:i.toFunction(),decode:n.toFunction()}}function Lo(t,e,r){let n=zE(),i=zE();return n(`
103
+ function decode_${r}(rstream) {
104
+ decode_${r}.bytes = ${n.formats.d(t)};
105
+ return rstream.${r}(${n.formats.d(t)})
106
+ }
107
+ `),i(`
108
+ function encode_${e}(value, wstream) {
109
+ wstream.${e}(value, ${n.formats.d(t)});
110
+ encode_${e}.bytes = ${n.formats.d(t)};
111
+ }
112
+ `),{encodingLength:()=>t,encode:i.toFunction(),decode:n.toFunction()}}});var aV=ce((fze,sV)=>{"use strict";var{isType:Bwe,isFunction:hB,isUserType:Nwe}=ua(),gB=dd(),{decodeCommon:Owe}=Xm(),{encodeCommon:Mwe}=Mv(),{encodingLengthCommon:Lwe}=Lv(),md=ld();sV.exports=Hwe;function Hwe(t,e){if(!Bwe(e)&&!Nwe(e))throw new TypeError("Argument #2 should be a valid type.");let r={encode:n,decode:i,encodingLength:o,[gB.skip]:!1};return r;function n(s,a){let c=md.clone(this);n.bytes=0;let u=hB(t)?!!t(c):!!t;if(r[gB.skip]=!u,!u){md.clean(c);return}Mwe(s,a,e,c),n.bytes=c.bytes,md.clean(c)}function i(s){let a=md.clone(this);i.bytes=0;let c=hB(t)?!!t(a):!!t;if(r[gB.skip]=!c,!c){md.clean(a);return}let u=Owe(s,e,a);return i.bytes=a.bytes,md.clean(a),u}function o(s){let a=md.clone(this);return(hB(t)?t(a):t)&&Lwe(s,e,a),md.clean(a),a.bytes}}});var dV=ce((pze,uV)=>{"use strict";var KE=dd(),{decodeCommon:Uwe}=Xm(),cV=ld();uV.exports=$we;function $we(...t){if(t.length===0)throw new TypeError("You should set at least one condition type.");let e={decode:r,encode:()=>{},[KE.skip]:!0};return e;function r(n){r.bytes=0;let i=cV.clone(this);for(let o of t){let s=Uwe(n,o,i);if(o[KE.skip]!==!0)return r.bytes=i.bytes,cV.clean(i),e[KE.skip]=!1,s}e[KE.skip]=!0}}});var mV=ce((mze,pV)=>{"use strict";var fV=Bv(),Fwe=Jm(),Hv=class{constructor(e){this.stream=e,this.index=0}append(e){this.stream.append(e)}commit(){this.stream.consume(this.index)}get(e=0){return this.stream.get(this.index+e)}get length(){return this.stream.length}slice(e,r){return this.stream.slice(e,r)}toString(e,r,n){return this.stream.toString(e,r,n)}readBuffer(e){yB(this.index+e,this.length);let r=this.stream.slice(this.index,this.index+e);return this.index+=e,r}indexOf(e,r=0){return this.stream.indexOf(e,this.index+r)-this.index}},lV={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1};Object.keys(lV).forEach(t=>{let e=fV(),r=lV[t];e(`
113
+ function transaction_${t}() {
114
+ assertSize(this.index + ${e.formats.d(r)}, this.length);
115
+ const value = this.stream.buffer.${t}(this.index);
116
+ this.index += ${e.formats.d(r)};
117
+ return value;
118
+ }
119
+ `),Hv.prototype[t]=e.toFunction({assertSize:yB})});["readIntBE","readIntLE","readUIntBE","readUIntLE"].forEach(t=>{let e=fV();e(`
120
+ function transaction_${t}(bytes) {
121
+ assertSize(this.index + bytes, this.length);
122
+ const value = this.stream.buffer.${t}(bytes, this.index);
123
+ this.index += bytes;
124
+ return value;
125
+ }
126
+ `),Hv.prototype[t]=e.toFunction({assertSize:yB})});pV.exports=Hv;function yB(t,e){if(t>e)throw new Fwe(t,e)}});var Pr=ce((hze,wV)=>{"use strict";var vB=Nv(),jwe=GW(),qwe=XW(),Wwe=QW(),Vwe=eV(),Gwe=nV(),hV=oV(),zwe=aV(),Kwe=dV(),{encode:vV}=Mv(),{decode:xV}=Xm(),{encodingLength:Jwe}=Lv(),Xwe=mV(),SV=Jm(),bV={array:jwe,bool:Wwe,buffer:qwe,reserved:Vwe,string:Gwe,when:zwe,select:Kwe};for(let t of Object.keys(hV))bV[t]=hV[t];var JE=Symbol("schema");function gV(t){let e=new vB({readableObjectMode:!1,writableObjectMode:!0,transform:Ywe});return e[JE]=t,e}function yV(t){let e=null,r=Buffer.isBuffer(t);r||(e=t);let n=new vB({transform:Qwe,readableObjectMode:!0,writableObjectMode:!1});return n[JE]=e,r&&n.append(t),n}function Ywe(t,e,r){try{vV(t,this[JE],this);let n=this.slice();this.consume(n.length),r(null,n)}catch(n){r(n)}}function Qwe(t,e,r){this.append(t);try{for(;this.length>0;){let n=new Xwe(this),i=xV(n,this[JE]);n.commit(),this.push(i)}r()}catch(n){n instanceof SV?r():r(n)}}wV.exports={createEncodeStream:gV,createDecodeStream:yV,encode:vV,decode:xV,encodingLength:Jwe,createEncode:gV,createDecode:yV,types:bV,BinaryStream:vB,NotEnoughDataError:SV}});import*as Sc from"node:crypto";var df,IV=N(()=>{df=Sc&&typeof Sc=="object"&&"webcrypto"in Sc?Sc.webcrypto:Sc&&typeof Sc=="object"&&"randomBytes"in Sc?Sc:void 0});function lf(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Uv(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ps(t,...e){if(!lf(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function XE(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Uv(t.outputLen),Uv(t.blockLen)}function Qm(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function kV(t,e){ps(t);let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function wc(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function YE(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function ms(t,e){return t<<32-e|t>>>e}function Ic(t){if(ps(t),RV)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Zwe[t[r]];return e}function EV(t){if(t>=bc._0&&t<=bc._9)return t-bc._0;if(t>=bc.A&&t<=bc.F)return t-(bc.A-10);if(t>=bc.a&&t<=bc.f)return t-(bc.a-10)}function ff(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(RV)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=EV(t.charCodeAt(o)),a=EV(t.charCodeAt(o+1));if(s===void 0||a===void 0){let c=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[i]=s*16+a}return n}function AV(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function $v(t){return typeof t=="string"&&(t=AV(t)),ps(t),t}function hs(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];ps(i),e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}function QE(t){let e=n=>t().update($v(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function ZE(t=32){if(df&&typeof df.getRandomValues=="function")return df.getRandomValues(new Uint8Array(t));if(df&&typeof df.randomBytes=="function")return Uint8Array.from(df.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}var RV,Zwe,bc,Ym,pf=N(()=>{IV();RV=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Zwe=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));bc={_0:48,_9:57,A:65,F:70,a:97,f:102};Ym=class{}});function Fv(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function hd(t,e,r=""){let n=lf(t),i=t?.length,o=e!==void 0;if(!n||o&&i!==e){let s=r&&`"${r}" `,a=o?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return t}function jv(t){let e=t.toString(16);return e.length&1?"0"+e:e}function CV(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?bB:BigInt("0x"+t)}function Zm(t){return CV(Ic(t))}function wB(t){return ps(t),CV(Ic(Uint8Array.from(t).reverse()))}function ek(t,e){return ff(t.toString(16).padStart(e*2,"0"))}function IB(t,e){return ek(t,e).reverse()}function ti(t,e,r){let n;if(typeof e=="string")try{n=ff(e)}catch(o){throw new Error(t+" must be hex string or Uint8Array, cause: "+o)}else if(lf(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");let i=n.length;if(typeof r=="number"&&i!==r)throw new Error(t+" of length "+r+" expected, got "+i);return n}function PV(t,e,r){return xB(t)&&xB(e)&&xB(r)&&e<=t&&t<r}function _V(t,e,r,n){if(!PV(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function tk(t){let e;for(e=0;t>bB;t>>=SB,e+=1);return e}function TV(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=p=>new Uint8Array(p),i=p=>Uint8Array.of(p),o=n(t),s=n(t),a=0,c=()=>{o.fill(1),s.fill(0),a=0},u=(...p)=>r(s,o,...p),d=(p=n(0))=>{s=u(i(0),p),o=u(),p.length!==0&&(s=u(i(1),p),o=u())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0,g=[];for(;p<e;){o=u();let v=o.slice();g.push(v),p+=o.length}return hs(...g)};return(p,g)=>{c(),d(p);let v;for(;!(v=g(l()));)d();return c(),v}}function qv(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(i,o,s){let a=t[i];if(s&&a===void 0)return;let c=typeof a;if(c!==o||a===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${c}`)}Object.entries(e).forEach(([i,o])=>n(i,o,!1)),Object.entries(r).forEach(([i,o])=>n(i,o,!0))}function EB(t){let e=new WeakMap;return(r,...n)=>{let i=e.get(r);if(i!==void 0)return i;let o=t(r,...n);return e.set(r,o),o}}var bB,SB,xB,gd,rk=N(()=>{pf();pf();bB=BigInt(0),SB=BigInt(1);xB=t=>typeof t=="bigint"&&bB<=t;gd=t=>(SB<<BigInt(t))-SB});function gs(t,e){let r=t%e;return r>=$i?r:e+r}function DV(t,e){if(t===$i)throw new Error("invert: expected non-zero number");if(e<=$i)throw new Error("invert: expected positive modulus, got "+e);let r=gs(t,e),n=e,i=$i,o=ri,s=ri,a=$i;for(;r!==$i;){let u=n/r,d=n%r,l=i-s*u,f=o-a*u;n=r,r=d,i=s,o=a,s=l,a=f}if(n!==ri)throw new Error("invert: does not exist");return gs(i,e)}function kB(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function UV(t,e){let r=(t.ORDER+ri)/OV,n=t.pow(e,r);return kB(t,n,e),n}function rIe(t,e){let r=(t.ORDER-MV)/LV,n=t.mul(e,mf),i=t.pow(n,r),o=t.mul(e,i),s=t.mul(t.mul(o,mf),i),a=t.mul(o,t.sub(s,t.ONE));return kB(t,a,e),a}function nIe(t){let e=da(t),r=$V(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+eIe)/HV;return(a,c)=>{let u=a.pow(c,s),d=a.mul(u,n),l=a.mul(u,i),f=a.mul(u,o),p=a.eql(a.sqr(d),c),g=a.eql(a.sqr(l),c);u=a.cmov(u,d,p),d=a.cmov(f,l,g);let v=a.eql(a.sqr(d),c),b=a.cmov(u,d,v);return kB(a,b,c),b}}function $V(t){if(t<NV)throw new Error("sqrt is not defined for small field");let e=t-ri,r=0;for(;e%mf===$i;)e/=mf,r++;let n=mf,i=da(t);for(;BV(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return UV;let o=i.pow(n,e),s=(e+ri)/mf;return function(c,u){if(c.is0(u))return u;if(BV(c,u)!==1)throw new Error("Cannot find square root");let d=r,l=c.mul(c.ONE,o),f=c.pow(u,e),p=c.pow(u,s);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let g=1,v=c.sqr(f);for(;!c.eql(v,c.ONE);)if(g++,v=c.sqr(v),g===d)throw new Error("Cannot find square root");let b=ri<<BigInt(d-g-1),C=c.pow(l,b);d=g,l=c.sqr(C),f=c.mul(f,l),p=c.mul(p,C)}return p}}function iIe(t){return t%OV===NV?UV:t%LV===MV?rIe:t%HV===tIe?nIe(t):$V(t)}function RB(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=oIe.reduce((n,i)=>(n[i]="function",n),e);return qv(t,r),t}function sIe(t,e,r){if(r<$i)throw new Error("invalid exponent, negatives unsupported");if(r===$i)return t.ONE;if(r===ri)return e;let n=t.ONE,i=e;for(;r>$i;)r&ri&&(n=t.mul(n,i)),i=t.sqr(i),r>>=ri;return n}function nk(t,e,r=!1){let n=new Array(e.length).fill(r?t.ZERO:void 0),i=e.reduce((s,a,c)=>t.is0(a)?s:(n[c]=s,t.mul(s,a)),t.ONE),o=t.inv(i);return e.reduceRight((s,a,c)=>t.is0(a)?s:(n[c]=t.mul(s,n[c]),t.mul(s,a)),o),n}function BV(t,e){let r=(t.ORDER-ri)/mf,n=t.pow(e,r),i=t.eql(n,t.ONE),o=t.eql(n,t.ZERO),s=t.eql(n,t.neg(t.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function ik(t,e){e!==void 0&&Uv(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function da(t,e,r=!1,n={}){if(t<=$i)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,o,s=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let f=e;f.BITS&&(i=f.BITS),f.sqrt&&(o=f.sqrt),typeof f.isLE=="boolean"&&(r=f.isLE),typeof f.modFromBytes=="boolean"&&(s=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(i=e),n.sqrt&&(o=n.sqrt);let{nBitLength:c,nByteLength:u}=ik(t,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,l=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:u,MASK:gd(c),ZERO:$i,ONE:ri,allowedLengths:a,create:f=>gs(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return $i<=f&&f<t},is0:f=>f===$i,isValidNot0:f=>!l.is0(f)&&l.isValid(f),isOdd:f=>(f&ri)===ri,neg:f=>gs(-f,t),eql:(f,p)=>f===p,sqr:f=>gs(f*f,t),add:(f,p)=>gs(f+p,t),sub:(f,p)=>gs(f-p,t),mul:(f,p)=>gs(f*p,t),pow:(f,p)=>sIe(l,f,p),div:(f,p)=>gs(f*DV(p,t),t),sqrN:f=>f*f,addN:(f,p)=>f+p,subN:(f,p)=>f-p,mulN:(f,p)=>f*p,inv:f=>DV(f,t),sqrt:o||(f=>(d||(d=iIe(t)),d(l,f))),toBytes:f=>r?IB(f,u):ek(f,u),fromBytes:(f,p=!0)=>{if(a){if(!a.includes(f.length)||f.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);let v=new Uint8Array(u);v.set(f,r?0:v.length-f.length),f=v}if(f.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+f.length);let g=r?wB(f):Zm(f);if(s&&(g=gs(g,t)),!p&&!l.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:f=>nk(l,f),cmov:(f,p,g)=>g?p:f});return Object.freeze(l)}function FV(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function AB(t){let e=FV(t);return e+Math.ceil(e/2)}function jV(t,e,r=!1){let n=t.length,i=FV(e),o=AB(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?wB(t):Zm(t),a=gs(s,e-ri)+ri;return r?IB(a,i):ek(a,i)}var $i,ri,mf,NV,OV,MV,eIe,LV,tIe,HV,oIe,ok=N(()=>{rk();$i=BigInt(0),ri=BigInt(1),mf=BigInt(2),NV=BigInt(3),OV=BigInt(4),MV=BigInt(5),eIe=BigInt(7),LV=BigInt(8),tIe=BigInt(9),HV=BigInt(16);oIe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function aIe(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),a=Number(r&o),c=n?4:0,u=n?0:4;t.setUint32(e+c,s,n),t.setUint32(e+u,a,n)}function qV(t,e,r){return t&e^~t&r}function WV(t,e,r){return t&e^t&r^e&r}var Wv,Ec,Mn,Ln,VV=N(()=>{pf();Wv=class extends Ym{constructor(e,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=YE(this.buffer)}update(e){Qm(this),e=$v(e),ps(e);let{view:r,buffer:n,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=YE(e);for(;i<=o-s;s+=i)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Qm(this),kV(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,wc(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let l=s;l<i;l++)r[l]=0;aIe(n,i-8,BigInt(this.length*8),o),this.process(n,0);let a=YE(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,d[l],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=a,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ec=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Mn=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Ln=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});function cIe(t,e=!1){return e?{h:Number(t&sk),l:Number(t>>GV&sk)}:{h:Number(t>>GV&sk)|0,l:Number(t&sk)|0}}function zV(t,e=!1){let r=t.length,n=new Uint32Array(r),i=new Uint32Array(r);for(let o=0;o<r;o++){let{h:s,l:a}=cIe(t[o],e);[n[o],i[o]]=[s,a]}return[n,i]}function la(t,e,r,n){let i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}var sk,GV,CB,PB,hf,gf,Vv,Gv,KV,JV,XV,YV,QV,ZV,eG=N(()=>{sk=BigInt(4294967295),GV=BigInt(32);CB=(t,e,r)=>t>>>r,PB=(t,e,r)=>t<<32-r|e>>>r,hf=(t,e,r)=>t>>>r|e<<32-r,gf=(t,e,r)=>t<<32-r|e>>>r,Vv=(t,e,r)=>t<<64-r|e>>>r-32,Gv=(t,e,r)=>t>>>r-32|e<<64-r;KV=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),JV=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,XV=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),YV=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,QV=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),ZV=(t,e,r,n,i,o)=>e+r+n+i+o+(t/2**32|0)|0});var dIe,yd,_B,tG,lIe,fIe,vd,xd,ak,TB,rG,nG,iG,oG=N(()=>{VV();eG();pf();dIe=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),yd=new Uint32Array(64),_B=class extends Wv{constructor(e=32){super(64,e,8,!1),this.A=Ec[0]|0,this.B=Ec[1]|0,this.C=Ec[2]|0,this.D=Ec[3]|0,this.E=Ec[4]|0,this.F=Ec[5]|0,this.G=Ec[6]|0,this.H=Ec[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:a,H:c}=this;return[e,r,n,i,o,s,a,c]}set(e,r,n,i,o,s,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,r){for(let l=0;l<16;l++,r+=4)yd[l]=e.getUint32(r,!1);for(let l=16;l<64;l++){let f=yd[l-15],p=yd[l-2],g=ms(f,7)^ms(f,18)^f>>>3,v=ms(p,17)^ms(p,19)^p>>>10;yd[l]=v+yd[l-7]+g+yd[l-16]|0}let{A:n,B:i,C:o,D:s,E:a,F:c,G:u,H:d}=this;for(let l=0;l<64;l++){let f=ms(a,6)^ms(a,11)^ms(a,25),p=d+f+qV(a,c,u)+dIe[l]+yd[l]|0,v=(ms(n,2)^ms(n,13)^ms(n,22))+WV(n,i,o)|0;d=u,u=c,c=a,a=s+p|0,s=o,o=i,i=n,n=p+v|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,a,c,u,d)}roundClean(){wc(yd)}destroy(){this.set(0,0,0,0,0,0,0,0),wc(this.buffer)}},tG=zV(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),lIe=tG[0],fIe=tG[1],vd=new Uint32Array(80),xd=new Uint32Array(80),ak=class extends Wv{constructor(e=64){super(128,e,16,!1),this.Ah=Ln[0]|0,this.Al=Ln[1]|0,this.Bh=Ln[2]|0,this.Bl=Ln[3]|0,this.Ch=Ln[4]|0,this.Cl=Ln[5]|0,this.Dh=Ln[6]|0,this.Dl=Ln[7]|0,this.Eh=Ln[8]|0,this.El=Ln[9]|0,this.Fh=Ln[10]|0,this.Fl=Ln[11]|0,this.Gh=Ln[12]|0,this.Gl=Ln[13]|0,this.Hh=Ln[14]|0,this.Hl=Ln[15]|0}get(){let{Ah:e,Al:r,Bh:n,Bl:i,Ch:o,Cl:s,Dh:a,Dl:c,Eh:u,El:d,Fh:l,Fl:f,Gh:p,Gl:g,Hh:v,Hl:b}=this;return[e,r,n,i,o,s,a,c,u,d,l,f,p,g,v,b]}set(e,r,n,i,o,s,a,c,u,d,l,f,p,g,v,b){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=o|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=d|0,this.Fh=l|0,this.Fl=f|0,this.Gh=p|0,this.Gl=g|0,this.Hh=v|0,this.Hl=b|0}process(e,r){for(let _=0;_<16;_++,r+=4)vd[_]=e.getUint32(r),xd[_]=e.getUint32(r+=4);for(let _=16;_<80;_++){let F=vd[_-15]|0,he=xd[_-15]|0,z=hf(F,he,1)^hf(F,he,8)^CB(F,he,7),Ce=gf(F,he,1)^gf(F,he,8)^PB(F,he,7),de=vd[_-2]|0,R=xd[_-2]|0,V=hf(de,R,19)^Vv(de,R,61)^CB(de,R,6),le=gf(de,R,19)^Gv(de,R,61)^PB(de,R,6),se=XV(Ce,le,xd[_-7],xd[_-16]),H=YV(se,z,V,vd[_-7],vd[_-16]);vd[_]=H|0,xd[_]=se|0}let{Ah:n,Al:i,Bh:o,Bl:s,Ch:a,Cl:c,Dh:u,Dl:d,Eh:l,El:f,Fh:p,Fl:g,Gh:v,Gl:b,Hh:C,Hl:D}=this;for(let _=0;_<80;_++){let F=hf(l,f,14)^hf(l,f,18)^Vv(l,f,41),he=gf(l,f,14)^gf(l,f,18)^Gv(l,f,41),z=l&p^~l&v,Ce=f&g^~f&b,de=QV(D,he,Ce,fIe[_],xd[_]),R=ZV(de,C,F,z,lIe[_],vd[_]),V=de|0,le=hf(n,i,28)^Vv(n,i,34)^Vv(n,i,39),se=gf(n,i,28)^Gv(n,i,34)^Gv(n,i,39),H=n&o^n&a^o&a,G=i&s^i&c^s&c;C=v|0,D=b|0,v=p|0,b=g|0,p=l|0,g=f|0,{h:l,l:f}=la(u|0,d|0,R|0,V|0),u=a|0,d=c|0,a=o|0,c=s|0,o=n|0,s=i|0;let j=KV(V,se,G);n=JV(j,R,le,H),i=j|0}({h:n,l:i}=la(this.Ah|0,this.Al|0,n|0,i|0)),{h:o,l:s}=la(this.Bh|0,this.Bl|0,o|0,s|0),{h:a,l:c}=la(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:d}=la(this.Dh|0,this.Dl|0,u|0,d|0),{h:l,l:f}=la(this.Eh|0,this.El|0,l|0,f|0),{h:p,l:g}=la(this.Fh|0,this.Fl|0,p|0,g|0),{h:v,l:b}=la(this.Gh|0,this.Gl|0,v|0,b|0),{h:C,l:D}=la(this.Hh|0,this.Hl|0,C|0,D|0),this.set(n,i,o,s,a,c,u,d,l,f,p,g,v,b,C,D)}roundClean(){wc(vd,xd)}destroy(){wc(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},TB=class extends ak{constructor(){super(48),this.Ah=Mn[0]|0,this.Al=Mn[1]|0,this.Bh=Mn[2]|0,this.Bl=Mn[3]|0,this.Ch=Mn[4]|0,this.Cl=Mn[5]|0,this.Dh=Mn[6]|0,this.Dl=Mn[7]|0,this.Eh=Mn[8]|0,this.El=Mn[9]|0,this.Fh=Mn[10]|0,this.Fl=Mn[11]|0,this.Gh=Mn[12]|0,this.Gl=Mn[13]|0,this.Hh=Mn[14]|0,this.Hl=Mn[15]|0}},rG=QE(()=>new _B),nG=QE(()=>new ak),iG=QE(()=>new TB)});var ck,DB,sG=N(()=>{pf();ck=class extends Ym{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,XE(e);let n=$v(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(n.length>i?e.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),wc(o)}update(e){return Qm(this),this.iHash.update(e),this}digestInto(e){Qm(this),ps(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},DB=(t,e,r)=>new ck(t,e).update(r).digest();DB.create=(t,e)=>new ck(t,e)});function zv(t,e){let r=e.negate();return t?r:e}function dk(t,e){let r=nk(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function dG(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function BB(t,e){dG(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=gd(t),s=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function aG(t,e,r){let{windowSize:n,mask:i,maxNumber:o,shiftBy:s}=r,a=Number(t&i),c=t>>s;a>n&&(a-=o,c+=yf);let u=e*n,d=u+Math.abs(a)-1,l=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:d,isZero:l,isNeg:f,isNegF:p,offsetF:u}}function pIe(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function mIe(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}function OB(t){return lG.get(t)||1}function cG(t){if(t!==eh)throw new Error("invalid wNAF")}function fG(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>eh||n>eh;)r&yf&&(o=o.add(i)),n&yf&&(s=s.add(i)),i=i.double(),r>>=yf,n>>=yf;return{p1:o,p2:s}}function pG(t,e,r,n){pIe(r,t),mIe(n,e);let i=r.length,o=n.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");let s=t.ZERO,a=tk(BigInt(i)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=gd(c),d=new Array(Number(u)+1).fill(s),l=Math.floor((e.BITS-1)/c)*c,f=s;for(let p=l;p>=0;p-=c){d.fill(s);for(let v=0;v<o;v++){let b=n[v],C=Number(b>>BigInt(p)&u);d[C]=d[C].add(r[v])}let g=s;for(let v=d.length-1,b=s;v>0;v--)b=b.add(d[v]),g=g.add(b);if(f=f.add(g),p!==0)for(let v=0;v<c;v++)f=f.double()}return f}function uG(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return RB(e),e}else return da(t,{isLE:r})}function mG(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let u=e[c];if(!(typeof u=="bigint"&&u>eh))throw new Error(`CURVE.${c} must be positive bigint`)}let i=uG(e.p,r.Fp,n),o=uG(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!i.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:o}}var eh,yf,NB,lG,uk,hG=N(()=>{rk();ok();eh=BigInt(0),yf=BigInt(1);NB=new WeakMap,lG=new WeakMap;uk=class{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let i=e;for(;r>eh;)r&yf&&(n=n.add(i)),i=i.double(),r>>=yf;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=BB(r,this.bits),o=[],s=e,a=s;for(let c=0;c<n;c++){a=s,o.push(a);for(let u=1;u<i;u++)a=a.add(s),o.push(a);s=a.double()}return o}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let i=this.ZERO,o=this.BASE,s=BB(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:d,isNeg:l,isNegF:f,offsetF:p}=aG(n,a,s);n=c,d?o=o.add(zv(f,r[p])):i=i.add(zv(l,r[u]))}return cG(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=BB(e,this.bits);for(let s=0;s<o.windows&&n!==eh;s++){let{nextN:a,offset:c,isZero:u,isNeg:d}=aG(n,s,o);if(n=a,!u){let l=r[c];i=i.add(d?l.negate():l)}}return cG(n),i}getPrecomputes(e,r,n){let i=NB.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),NB.set(r,i))),i}cached(e,r,n){let i=OB(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=OB(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){dG(r,this.bits),lG.set(e,r),NB.delete(e)}hasCache(e){return OB(e)!==1}}});function hIe(t,e,r){let[[n,i],[o,s]]=e,a=gG(s*t,r),c=gG(-i*t,r),u=t-a*n-c*o,d=-a*i-c*s,l=u<Rc,f=d<Rc;l&&(u=-u),f&&(d=-d);let p=gd(Math.ceil(tk(r)/2))+rh;if(u<Rc||u>=p||d<Rc||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:l,k1:u,k2neg:f,k2:d}}function LB(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function MB(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Fv(r.lowS,"lowS"),Fv(r.prehash,"prehash"),r.format!==void 0&&LB(r.format),r}function th(t,e){let{BYTES:r}=t,n;if(typeof e=="bigint")n=e;else{let i=ti("private key",e);try{n=t.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function yIe(t,e={}){let r=mG("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:a}=o;qv(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=xG(n,i);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(se,H,G){let{x:j,y:me}=H.toAffine(),Pe=n.toBytes(j);if(Fv(G,"isCompressed"),G){d();let Te=!n.isOdd(me);return hs(vG(Te),Pe)}else return hs(Uint8Array.of(4),Pe,n.toBytes(me))}function f(se){hd(se,void 0,"Point");let{publicKey:H,publicKeyUncompressed:G}=u,j=se.length,me=se[0],Pe=se.subarray(1);if(j===H&&(me===2||me===3)){let Te=n.fromBytes(Pe);if(!n.isValid(Te))throw new Error("bad point: is not on curve, wrong x");let P=v(Te),B;try{B=n.sqrt(P)}catch($){let ye=$ instanceof Error?": "+$.message:"";throw new Error("bad point: is not on curve, sqrt error"+ye)}d();let K=n.isOdd(B);return(me&1)===1!==K&&(B=n.neg(B)),{x:Te,y:B}}else if(j===G&&me===4){let Te=n.BYTES,P=n.fromBytes(Pe.subarray(0,Te)),B=n.fromBytes(Pe.subarray(Te,Te*2));if(!b(P,B))throw new Error("bad point: is not on curve");return{x:P,y:B}}else throw new Error(`bad point: got length ${j}, expected compressed=${H} or uncompressed=${G}`)}let p=e.toBytes||l,g=e.fromBytes||f;function v(se){let H=n.sqr(se),G=n.mul(H,se);return n.add(n.add(G,n.mul(se,o.a)),o.b)}function b(se,H){let G=n.sqr(H),j=v(se);return n.eql(G,j)}if(!b(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let C=n.mul(n.pow(o.a,lk),gIe),D=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(C,D)))throw new Error("bad curve params: a or b");function _(se,H,G=!1){if(!n.isValid(H)||G&&n.is0(H))throw new Error(`bad point coordinate ${se}`);return H}function F(se){if(!(se instanceof R))throw new Error("ProjectivePoint expected")}function he(se){if(!c||!c.basises)throw new Error("no endo");return hIe(se,c.basises,i.ORDER)}let z=EB((se,H)=>{let{X:G,Y:j,Z:me}=se;if(n.eql(me,n.ONE))return{x:G,y:j};let Pe=se.is0();H==null&&(H=Pe?n.ONE:n.inv(me));let Te=n.mul(G,H),P=n.mul(j,H),B=n.mul(me,H);if(Pe)return{x:n.ZERO,y:n.ZERO};if(!n.eql(B,n.ONE))throw new Error("invZ was invalid");return{x:Te,y:P}}),Ce=EB(se=>{if(se.is0()){if(e.allowInfinityPoint&&!n.is0(se.Y))return;throw new Error("bad point: ZERO")}let{x:H,y:G}=se.toAffine();if(!n.isValid(H)||!n.isValid(G))throw new Error("bad point: x or y not field elements");if(!b(H,G))throw new Error("bad point: equation left != right");if(!se.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function de(se,H,G,j,me){return G=new R(n.mul(G.X,se),G.Y,G.Z),H=zv(j,H),G=zv(me,G),H.add(G)}class R{constructor(H,G,j){this.X=_("x",H),this.Y=_("y",G,!0),this.Z=_("z",j),Object.freeze(this)}static CURVE(){return o}static fromAffine(H){let{x:G,y:j}=H||{};if(!H||!n.isValid(G)||!n.isValid(j))throw new Error("invalid affine point");if(H instanceof R)throw new Error("projective point not allowed");return n.is0(G)&&n.is0(j)?R.ZERO:new R(G,j,n.ONE)}static fromBytes(H){let G=R.fromAffine(g(hd(H,void 0,"point")));return G.assertValidity(),G}static fromHex(H){return R.fromBytes(ti("pointHex",H))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(H=8,G=!0){return le.createCache(this,H),G||this.multiply(lk),this}assertValidity(){Ce(this)}hasEvenY(){let{y:H}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(H)}equals(H){F(H);let{X:G,Y:j,Z:me}=this,{X:Pe,Y:Te,Z:P}=H,B=n.eql(n.mul(G,P),n.mul(Pe,me)),K=n.eql(n.mul(j,P),n.mul(Te,me));return B&&K}negate(){return new R(this.X,n.neg(this.Y),this.Z)}double(){let{a:H,b:G}=o,j=n.mul(G,lk),{X:me,Y:Pe,Z:Te}=this,P=n.ZERO,B=n.ZERO,K=n.ZERO,T=n.mul(me,me),$=n.mul(Pe,Pe),ye=n.mul(Te,Te),be=n.mul(me,Pe);return be=n.add(be,be),K=n.mul(me,Te),K=n.add(K,K),P=n.mul(H,K),B=n.mul(j,ye),B=n.add(P,B),P=n.sub($,B),B=n.add($,B),B=n.mul(P,B),P=n.mul(be,P),K=n.mul(j,K),ye=n.mul(H,ye),be=n.sub(T,ye),be=n.mul(H,be),be=n.add(be,K),K=n.add(T,T),T=n.add(K,T),T=n.add(T,ye),T=n.mul(T,be),B=n.add(B,T),ye=n.mul(Pe,Te),ye=n.add(ye,ye),T=n.mul(ye,be),P=n.sub(P,T),K=n.mul(ye,$),K=n.add(K,K),K=n.add(K,K),new R(P,B,K)}add(H){F(H);let{X:G,Y:j,Z:me}=this,{X:Pe,Y:Te,Z:P}=H,B=n.ZERO,K=n.ZERO,T=n.ZERO,$=o.a,ye=n.mul(o.b,lk),be=n.mul(G,Pe),ct=n.mul(j,Te),It=n.mul(me,P),Zt=n.add(G,j),Dt=n.add(Pe,Te);Zt=n.mul(Zt,Dt),Dt=n.add(be,ct),Zt=n.sub(Zt,Dt),Dt=n.add(G,me);let _t=n.add(Pe,P);return Dt=n.mul(Dt,_t),_t=n.add(be,It),Dt=n.sub(Dt,_t),_t=n.add(j,me),B=n.add(Te,P),_t=n.mul(_t,B),B=n.add(ct,It),_t=n.sub(_t,B),T=n.mul($,Dt),B=n.mul(ye,It),T=n.add(B,T),B=n.sub(ct,T),T=n.add(ct,T),K=n.mul(B,T),ct=n.add(be,be),ct=n.add(ct,be),It=n.mul($,It),Dt=n.mul(ye,Dt),ct=n.add(ct,It),It=n.sub(be,It),It=n.mul($,It),Dt=n.add(Dt,It),be=n.mul(ct,Dt),K=n.add(K,be),be=n.mul(_t,Dt),B=n.mul(Zt,B),B=n.sub(B,be),be=n.mul(Zt,ct),T=n.mul(_t,T),T=n.add(T,be),new R(B,K,T)}subtract(H){return this.add(H.negate())}is0(){return this.equals(R.ZERO)}multiply(H){let{endo:G}=e;if(!i.isValidNot0(H))throw new Error("invalid scalar: out of range");let j,me,Pe=Te=>le.cached(this,Te,P=>dk(R,P));if(G){let{k1neg:Te,k1:P,k2neg:B,k2:K}=he(H),{p:T,f:$}=Pe(P),{p:ye,f:be}=Pe(K);me=$.add(be),j=de(G.beta,T,ye,Te,B)}else{let{p:Te,f:P}=Pe(H);j=Te,me=P}return dk(R,[j,me])[0]}multiplyUnsafe(H){let{endo:G}=e,j=this;if(!i.isValid(H))throw new Error("invalid scalar: out of range");if(H===Rc||j.is0())return R.ZERO;if(H===rh)return j;if(le.hasCache(this))return this.multiply(H);if(G){let{k1neg:me,k1:Pe,k2neg:Te,k2:P}=he(H),{p1:B,p2:K}=fG(R,j,Pe,P);return de(G.beta,B,K,me,Te)}else return le.unsafe(j,H)}multiplyAndAddUnsafe(H,G,j){let me=this.multiplyUnsafe(G).add(H.multiplyUnsafe(j));return me.is0()?void 0:me}toAffine(H){return z(this,H)}isTorsionFree(){let{isTorsionFree:H}=e;return s===rh?!0:H?H(R,this):le.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:H}=e;return s===rh?this:H?H(R,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(H=!0){return Fv(H,"isCompressed"),this.assertValidity(),p(R,this,H)}toHex(H=!0){return Ic(this.toBytes(H))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(H=!0){return this.toBytes(H)}_setWindowSize(H){this.precompute(H)}static normalizeZ(H){return dk(R,H)}static msm(H,G){return pG(R,i,H,G)}static fromPrivateKey(H){return R.BASE.multiply(th(i,H))}}R.BASE=new R(o.Gx,o.Gy,n.ONE),R.ZERO=new R(n.ZERO,n.ONE,n.ZERO),R.Fp=n,R.Fn=i;let V=i.BITS,le=new uk(R,e.endo?Math.ceil(V/2):V);return R.BASE.precompute(8),R}function vG(t){return Uint8Array.of(t?2:3)}function xG(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function vIe(t,e={}){let{Fn:r}=t,n=e.randomBytes||ZE,i=Object.assign(xG(t.Fp,r),{seed:AB(r.ORDER)});function o(p){try{return!!th(r,p)}catch{return!1}}function s(p,g){let{publicKey:v,publicKeyUncompressed:b}=i;try{let C=p.length;return g===!0&&C!==v||g===!1&&C!==b?!1:!!t.fromBytes(p)}catch{return!1}}function a(p=n(i.seed)){return jV(hd(p,i.seed,"seed"),r.ORDER)}function c(p,g=!0){return t.BASE.multiply(th(r,p)).toBytes(g)}function u(p){let g=a(p);return{secretKey:g,publicKey:c(g)}}function d(p){if(typeof p=="bigint")return!1;if(p instanceof t)return!0;let{secretKey:g,publicKey:v,publicKeyUncompressed:b}=i;if(r.allowedLengths||g===v)return;let C=ti("key",p).length;return C===v||C===b}function l(p,g,v=!0){if(d(p)===!0)throw new Error("first arg must be private key");if(d(g)===!1)throw new Error("second arg must be public key");let b=th(r,p);return t.fromHex(g).multiply(b).toBytes(v)}return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:u,Point:t,utils:{isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:p=>th(r,p),precompute(p=8,g=t.BASE){return g.precompute(p,!1)}},lengths:i})}function xIe(t,e,r={}){XE(e),qv(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||ZE,i=r.hmac||((G,...j)=>DB(e,G,hs(...j))),{Fp:o,Fn:s}=t,{ORDER:a,BITS:c}=s,{keygen:u,getPublicKey:d,getSharedSecret:l,utils:f,lengths:p}=vIe(t,r),g={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},v="compact";function b(G){let j=a>>rh;return G>j}function C(G,j){if(!s.isValidNot0(j))throw new Error(`invalid signature ${G}: out of range 1..Point.Fn.ORDER`);return j}function D(G,j){LB(j);let me=p.signature,Pe=j==="compact"?me:j==="recovered"?me+1:void 0;return hd(G,Pe,`${j} signature`)}class _{constructor(j,me,Pe){this.r=C("r",j),this.s=C("s",me),Pe!=null&&(this.recovery=Pe),Object.freeze(this)}static fromBytes(j,me=v){D(j,me);let Pe;if(me==="der"){let{r:K,s:T}=kc.toSig(hd(j));return new _(K,T)}me==="recovered"&&(Pe=j[0],me="compact",j=j.subarray(1));let Te=s.BYTES,P=j.subarray(0,Te),B=j.subarray(Te,Te*2);return new _(s.fromBytes(P),s.fromBytes(B),Pe)}static fromHex(j,me){return this.fromBytes(ff(j),me)}addRecoveryBit(j){return new _(this.r,this.s,j)}recoverPublicKey(j){let me=o.ORDER,{r:Pe,s:Te,recovery:P}=this;if(P==null||![0,1,2,3].includes(P))throw new Error("recovery id invalid");if(a*yG<me&&P>1)throw new Error("recovery id is ambiguous for h>1 curve");let K=P===2||P===3?Pe+a:Pe;if(!o.isValid(K))throw new Error("recovery id 2 or 3 invalid");let T=o.toBytes(K),$=t.fromBytes(hs(vG((P&1)===0),T)),ye=s.inv(K),be=he(ti("msgHash",j)),ct=s.create(-be*ye),It=s.create(Te*ye),Zt=t.BASE.multiplyUnsafe(ct).add($.multiplyUnsafe(It));if(Zt.is0())throw new Error("point at infinify");return Zt.assertValidity(),Zt}hasHighS(){return b(this.s)}toBytes(j=v){if(LB(j),j==="der")return ff(kc.hexFromSig(this));let me=s.toBytes(this.r),Pe=s.toBytes(this.s);if(j==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return hs(Uint8Array.of(this.recovery),me,Pe)}return hs(me,Pe)}toHex(j){return Ic(this.toBytes(j))}assertValidity(){}static fromCompact(j){return _.fromBytes(ti("sig",j),"compact")}static fromDER(j){return _.fromBytes(ti("sig",j),"der")}normalizeS(){return this.hasHighS()?new _(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Ic(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ic(this.toBytes("compact"))}}let F=r.bits2int||function(j){if(j.length>8192)throw new Error("input is too large");let me=Zm(j),Pe=j.length*8-c;return Pe>0?me>>BigInt(Pe):me},he=r.bits2int_modN||function(j){return s.create(F(j))},z=gd(c);function Ce(G){return _V("num < 2^"+c,G,Rc,z),s.toBytes(G)}function de(G,j){return hd(G,void 0,"message"),j?hd(e(G),void 0,"prehashed message"):G}function R(G,j,me){if(["recovered","canonical"].some(ct=>ct in me))throw new Error("sign() legacy options not supported");let{lowS:Pe,prehash:Te,extraEntropy:P}=MB(me,g);G=de(G,Te);let B=he(G),K=th(s,j),T=[Ce(K),Ce(B)];if(P!=null&&P!==!1){let ct=P===!0?n(p.secretKey):P;T.push(ti("extraEntropy",ct))}let $=hs(...T),ye=B;function be(ct){let It=F(ct);if(!s.isValidNot0(It))return;let Zt=s.inv(It),Dt=t.BASE.multiply(It).toAffine(),_t=s.create(Dt.x);if(_t===Rc)return;let lo=s.create(Zt*s.create(ye+_t*K));if(lo===Rc)return;let fo=(Dt.x===_t?0:2)|Number(Dt.y&rh),jd=lo;return Pe&&b(lo)&&(jd=s.neg(lo),fo^=1),new _(_t,jd,fo)}return{seed:$,k2sig:be}}function V(G,j,me={}){G=ti("message",G);let{seed:Pe,k2sig:Te}=R(G,j,me);return TV(e.outputLen,s.BYTES,i)(Pe,Te)}function le(G){let j,me=typeof G=="string"||lf(G),Pe=!me&&G!==null&&typeof G=="object"&&typeof G.r=="bigint"&&typeof G.s=="bigint";if(!me&&!Pe)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(Pe)j=new _(G.r,G.s);else if(me){try{j=_.fromBytes(ti("sig",G),"der")}catch(Te){if(!(Te instanceof kc.Err))throw Te}if(!j)try{j=_.fromBytes(ti("sig",G),"compact")}catch{return!1}}return j||!1}function se(G,j,me,Pe={}){let{lowS:Te,prehash:P,format:B}=MB(Pe,g);if(me=ti("publicKey",me),j=de(ti("message",j),P),"strict"in Pe)throw new Error("options.strict was renamed to lowS");let K=B===void 0?le(G):_.fromBytes(ti("sig",G),B);if(K===!1)return!1;try{let T=t.fromBytes(me);if(Te&&K.hasHighS())return!1;let{r:$,s:ye}=K,be=he(j),ct=s.inv(ye),It=s.create(be*ct),Zt=s.create($*ct),Dt=t.BASE.multiplyUnsafe(It).add(T.multiplyUnsafe(Zt));return Dt.is0()?!1:s.create(Dt.x)===$}catch{return!1}}function H(G,j,me={}){let{prehash:Pe}=MB(me,g);return j=de(j,Pe),_.fromBytes(G,"recovered").recoverPublicKey(j).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:l,utils:f,lengths:p,Point:t,sign:V,verify:se,recoverPublicKey:H,Signature:_,hash:e})}function SIe(t){let e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp,n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0,i=da(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),o={Fp:r,Fn:i,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:o}}function bIe(t){let{CURVE:e,curveOpts:r}=SIe(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}function wIe(t,e){let r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,ik(r.Fn.ORDER,r.Fn.BITS))})}function SG(t){let{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:i}=bIe(t),o=yIe(e,r),s=xIe(o,n,i);return wIe(t,s)}var gG,HB,kc,Rc,rh,yG,lk,gIe,bG=N(()=>{sG();pf();rk();hG();ok();gG=(t,e)=>(t+(t>=0?e:-e)/yG)/e;HB=class extends Error{constructor(e=""){super(e)}},kc={Err:HB,_tlv:{encode:(t,e)=>{let{Err:r}=kc;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,i=jv(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?jv(i.length/2|128):"";return jv(t)+o+i+e},decode(t,e){let{Err:r}=kc,n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let i=e[n++],o=!!(i&128),s=0;if(!o)s=i;else{let c=i&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(n+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(t){let{Err:e}=kc;if(t<Rc)throw new e("integer: negative integers are not allowed");let r=jv(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=kc;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Zm(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=kc,i=ti("signature",t),{v:o,l:s}=n.decode(48,i);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:u,l:d}=n.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){let{_tlv:e,_int:r}=kc,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}},Rc=BigInt(0),rh=BigInt(1),yG=BigInt(2),lk=BigInt(3),gIe=BigInt(4)});function fk(t,e){let r=n=>SG({...t,hash:n});return{...r(e),create:r}}var wG=N(()=>{bG();});var IG,EG,kG,IIe,EIe,kIe,RG,Kze,Jze,AG=N(()=>{oG();wG();ok();IG={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},EG={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},kG={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},IIe=da(IG.p),EIe=da(EG.p),kIe=da(kG.p),RG=fk({...IG,Fp:IIe,lowS:!1},rG),Kze=fk({...EG,Fp:EIe,lowS:!1},iG),Jze=fk({...kG,Fp:kIe,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},nG)});var pk,CG=N(()=>{AG();pk=RG});var _G=ce(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});Sd.LEB128=Sd.SignedLEB128=Sd.UnsignedLEB128=void 0;var nh;(function(t){t[t.LOWER_7=127]="LOWER_7",t[t.UPPER_1=128]="UPPER_1"})(nh||(nh={}));var PG=t=>Number.isSafeInteger(t),vf=class{static decode(e,r=0){let n=this.$scanForNullBytes(e,r),i=0,o=0;for(let s=0;s<=n-r;s++){let a=e[r+s]&nh.LOWER_7;i|=a<<o,o+=7}return i}static encode(e){if(this.check(e),e<0)throw new Error(`An unsigned number must NOT be negative, ${e} is!`);let r=[],n=e;do{let i=n&nh.LOWER_7;n>>=7,n&&(i=i|nh.UPPER_1),r.push(i)}while(n);return Uint8Array.from(r)}static check(e){if(!PG(e))throw new Error(`${e} is not a safe integer!`)}static $scanForNullBytes(e,r=0){let n=r,i=0;do{if(n>=e.byteLength)throw new Error("This is not a LEB128-encoded Uint8Array, no ending found!");i=e.slice(n,n+1)[0],n++}while(i&nh.UPPER_1);return n-1}static getLength(e,r=0){return this.$scanForNullBytes(e,r)-r}};Sd.UnsignedLEB128=vf;var Kv=class{static $ceil7mul(e){let r=e;for(;r%7;)r++;return r}static check(e){if(!PG(e))throw new Error(`${e} is not a safe integer!`)}static encode(e){if(this.check(e),e>=0)throw new Error(`A signed number must be negative, ${e} isn't!`);let r=Math.ceil(Math.log2(-e));return vf.encode((1<<this.$ceil7mul(r))+e)}static decode(e,r=0){let n=vf.decode(e,r);return-((1<<Math.ceil(Math.log2(n)))-n)}};Sd.SignedLEB128=Kv;var Jv=class{};Sd.LEB128=Jv;Jv.encode=t=>(t>=0?vf:Kv).encode(t);Jv.decode=(t,e=0,r=!1)=>(r?Kv:vf).decode(t,e)});var DG=ce((UB,TG)=>{(function(t){"use strict";function e(P){return parseInt(P)===P}function r(P){if(!e(P.length))return!1;for(var B=0;B<P.length;B++)if(!e(P[B])||P[B]<0||P[B]>255)return!1;return!0}function n(P,B){if(P.buffer&&P.name==="Uint8Array")return B&&(P.slice?P=P.slice():P=Array.prototype.slice.call(P)),P;if(Array.isArray(P)){if(!r(P))throw new Error("Array contains invalid value: "+P);return new Uint8Array(P)}if(e(P.length)&&r(P))return new Uint8Array(P);throw new Error("unsupported array-like object")}function i(P){return new Uint8Array(P)}function o(P,B,K,T,$){(T!=null||$!=null)&&(P.slice?P=P.slice(T,$):P=Array.prototype.slice.call(P,T,$)),B.set(P,K)}var s=(function(){function P(K){var T=[],$=0;for(K=encodeURI(K);$<K.length;){var ye=K.charCodeAt($++);ye===37?(T.push(parseInt(K.substr($,2),16)),$+=2):T.push(ye)}return n(T)}function B(K){for(var T=[],$=0;$<K.length;){var ye=K[$];ye<128?(T.push(String.fromCharCode(ye)),$++):ye>191&&ye<224?(T.push(String.fromCharCode((ye&31)<<6|K[$+1]&63)),$+=2):(T.push(String.fromCharCode((ye&15)<<12|(K[$+1]&63)<<6|K[$+2]&63)),$+=3)}return T.join("")}return{toBytes:P,fromBytes:B}})(),a=(function(){function P(T){for(var $=[],ye=0;ye<T.length;ye+=2)$.push(parseInt(T.substr(ye,2),16));return $}var B="0123456789abcdef";function K(T){for(var $=[],ye=0;ye<T.length;ye++){var be=T[ye];$.push(B[(be&240)>>4]+B[be&15])}return $.join("")}return{toBytes:P,fromBytes:K}})(),c={16:10,24:12,32:14},u=[1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145],d=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],l=[82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125],f=[3328402341,4168907908,4000806809,4135287693,4294111757,3597364157,3731845041,2445657428,1613770832,33620227,3462883241,1445669757,3892248089,3050821474,1303096294,3967186586,2412431941,528646813,2311702848,4202528135,4026202645,2992200171,2387036105,4226871307,1101901292,3017069671,1604494077,1169141738,597466303,1403299063,3832705686,2613100635,1974974402,3791519004,1033081774,1277568618,1815492186,2118074177,4126668546,2211236943,1748251740,1369810420,3521504564,4193382664,3799085459,2883115123,1647391059,706024767,134480908,2512897874,1176707941,2646852446,806885416,932615841,168101135,798661301,235341577,605164086,461406363,3756188221,3454790438,1311188841,2142417613,3933566367,302582043,495158174,1479289972,874125870,907746093,3698224818,3025820398,1537253627,2756858614,1983593293,3084310113,2108928974,1378429307,3722699582,1580150641,327451799,2790478837,3117535592,0,3253595436,1075847264,3825007647,2041688520,3059440621,3563743934,2378943302,1740553945,1916352843,2487896798,2555137236,2958579944,2244988746,3151024235,3320835882,1336584933,3992714006,2252555205,2588757463,1714631509,293963156,2319795663,3925473552,67240454,4269768577,2689618160,2017213508,631218106,1269344483,2723238387,1571005438,2151694528,93294474,1066570413,563977660,1882732616,4059428100,1673313503,2008463041,2950355573,1109467491,537923632,3858759450,4260623118,3218264685,2177748300,403442708,638784309,3287084079,3193921505,899127202,2286175436,773265209,2479146071,1437050866,4236148354,2050833735,3362022572,3126681063,840505643,3866325909,3227541664,427917720,2655997905,2749160575,1143087718,1412049534,999329963,193497219,2353415882,3354324521,1807268051,672404540,2816401017,3160301282,369822493,2916866934,3688947771,1681011286,1949973070,336202270,2454276571,201721354,1210328172,3093060836,2680341085,3184776046,1135389935,3294782118,965841320,831886756,3554993207,4068047243,3588745010,2345191491,1849112409,3664604599,26054028,2983581028,2622377682,1235855840,3630984372,2891339514,4092916743,3488279077,3395642799,4101667470,1202630377,268961816,1874508501,4034427016,1243948399,1546530418,941366308,1470539505,1941222599,2546386513,3421038627,2715671932,3899946140,1042226977,2521517021,1639824860,227249030,260737669,3765465232,2084453954,1907733956,3429263018,2420656344,100860677,4160157185,470683154,3261161891,1781871967,2924959737,1773779408,394692241,2579611992,974986535,664706745,3655459128,3958962195,731420851,571543859,3530123707,2849626480,126783113,865375399,765172662,1008606754,361203602,3387549984,2278477385,2857719295,1344809080,2782912378,59542671,1503764984,160008576,437062935,1707065306,3622233649,2218934982,3496503480,2185314755,697932208,1512910199,504303377,2075177163,2824099068,1841019862,739644986],p=[2781242211,2230877308,2582542199,2381740923,234877682,3184946027,2984144751,1418839493,1348481072,50462977,2848876391,2102799147,434634494,1656084439,3863849899,2599188086,1167051466,2636087938,1082771913,2281340285,368048890,3954334041,3381544775,201060592,3963727277,1739838676,4250903202,3930435503,3206782108,4149453988,2531553906,1536934080,3262494647,484572669,2923271059,1783375398,1517041206,1098792767,49674231,1334037708,1550332980,4098991525,886171109,150598129,2481090929,1940642008,1398944049,1059722517,201851908,1385547719,1699095331,1587397571,674240536,2704774806,252314885,3039795866,151914247,908333586,2602270848,1038082786,651029483,1766729511,3447698098,2682942837,454166793,2652734339,1951935532,775166490,758520603,3000790638,4004797018,4217086112,4137964114,1299594043,1639438038,3464344499,2068982057,1054729187,1901997871,2534638724,4121318227,1757008337,0,750906861,1614815264,535035132,3363418545,3988151131,3201591914,1183697867,3647454910,1265776953,3734260298,3566750796,3903871064,1250283471,1807470800,717615087,3847203498,384695291,3313910595,3617213773,1432761139,2484176261,3481945413,283769337,100925954,2180939647,4037038160,1148730428,3123027871,3813386408,4087501137,4267549603,3229630528,2315620239,2906624658,3156319645,1215313976,82966005,3747855548,3245848246,1974459098,1665278241,807407632,451280895,251524083,1841287890,1283575245,337120268,891687699,801369324,3787349855,2721421207,3431482436,959321879,1469301956,4065699751,2197585534,1199193405,2898814052,3887750493,724703513,2514908019,2696962144,2551808385,3516813135,2141445340,1715741218,2119445034,2872807568,2198571144,3398190662,700968686,3547052216,1009259540,2041044702,3803995742,487983883,1991105499,1004265696,1449407026,1316239930,504629770,3683797321,168560134,1816667172,3837287516,1570751170,1857934291,4014189740,2797888098,2822345105,2754712981,936633572,2347923833,852879335,1133234376,1500395319,3084545389,2348912013,1689376213,3533459022,3762923945,3034082412,4205598294,133428468,634383082,2949277029,2398386810,3913789102,403703816,3580869306,2297460856,1867130149,1918643758,607656988,4049053350,3346248884,1368901318,600565992,2090982877,2632479860,557719327,3717614411,3697393085,2249034635,2232388234,2430627952,1115438654,3295786421,2865522278,3633334344,84280067,33027830,303828494,2747425121,1600795957,4188952407,3496589753,2434238086,1486471617,658119965,3106381470,953803233,334231800,3005978776,857870609,3151128937,1890179545,2298973838,2805175444,3056442267,574365214,2450884487,550103529,1233637070,4289353045,2018519080,2057691103,2399374476,4166623649,2148108681,387583245,3664101311,836232934,3330556482,3100665960,3280093505,2955516313,2002398509,287182607,3413881008,4238890068,3597515707,975967766],g=[1671808611,2089089148,2006576759,2072901243,4061003762,1807603307,1873927791,3310653893,810573872,16974337,1739181671,729634347,4263110654,3613570519,2883997099,1989864566,3393556426,2191335298,3376449993,2106063485,4195741690,1508618841,1204391495,4027317232,2917941677,3563566036,2734514082,2951366063,2629772188,2767672228,1922491506,3227229120,3082974647,4246528509,2477669779,644500518,911895606,1061256767,4144166391,3427763148,878471220,2784252325,3845444069,4043897329,1905517169,3631459288,827548209,356461077,67897348,3344078279,593839651,3277757891,405286936,2527147926,84871685,2595565466,118033927,305538066,2157648768,3795705826,3945188843,661212711,2999812018,1973414517,152769033,2208177539,745822252,439235610,455947803,1857215598,1525593178,2700827552,1391895634,994932283,3596728278,3016654259,695947817,3812548067,795958831,2224493444,1408607827,3513301457,0,3979133421,543178784,4229948412,2982705585,1542305371,1790891114,3410398667,3201918910,961245753,1256100938,1289001036,1491644504,3477767631,3496721360,4012557807,2867154858,4212583931,1137018435,1305975373,861234739,2241073541,1171229253,4178635257,33948674,2139225727,1357946960,1011120188,2679776671,2833468328,1374921297,2751356323,1086357568,2408187279,2460827538,2646352285,944271416,4110742005,3168756668,3066132406,3665145818,560153121,271589392,4279952895,4077846003,3530407890,3444343245,202643468,322250259,3962553324,1608629855,2543990167,1154254916,389623319,3294073796,2817676711,2122513534,1028094525,1689045092,1575467613,422261273,1939203699,1621147744,2174228865,1339137615,3699352540,577127458,712922154,2427141008,2290289544,1187679302,3995715566,3100863416,339486740,3732514782,1591917662,186455563,3681988059,3762019296,844522546,978220090,169743370,1239126601,101321734,611076132,1558493276,3260915650,3547250131,2901361580,1655096418,2443721105,2510565781,3828863972,2039214713,3878868455,3359869896,928607799,1840765549,2374762893,3580146133,1322425422,2850048425,1823791212,1459268694,4094161908,3928346602,1706019429,2056189050,2934523822,135794696,3134549946,2022240376,628050469,779246638,472135708,2800834470,3032970164,3327236038,3894660072,3715932637,1956440180,522272287,1272813131,3185336765,2340818315,2323976074,1888542832,1044544574,3049550261,1722469478,1222152264,50660867,4127324150,236067854,1638122081,895445557,1475980887,3117443513,2257655686,3243809217,489110045,2662934430,3778599393,4162055160,2561878936,288563729,1773916777,3648039385,2391345038,2493985684,2612407707,505560094,2274497927,3911240169,3460925390,1442818645,678973480,3749357023,2358182796,2717407649,2306869641,219617805,3218761151,3862026214,1120306242,1756942440,1103331905,2578459033,762796589,252780047,2966125488,1425844308,3151392187,372911126],v=[1667474886,2088535288,2004326894,2071694838,4075949567,1802223062,1869591006,3318043793,808472672,16843522,1734846926,724270422,4278065639,3621216949,2880169549,1987484396,3402253711,2189597983,3385409673,2105378810,4210693615,1499065266,1195886990,4042263547,2913856577,3570689971,2728590687,2947541573,2627518243,2762274643,1920112356,3233831835,3082273397,4261223649,2475929149,640051788,909531756,1061110142,4160160501,3435941763,875846760,2779116625,3857003729,4059105529,1903268834,3638064043,825316194,353713962,67374088,3351728789,589522246,3284360861,404236336,2526454071,84217610,2593830191,117901582,303183396,2155911963,3806477791,3958056653,656894286,2998062463,1970642922,151591698,2206440989,741110872,437923380,454765878,1852748508,1515908788,2694904667,1381168804,993742198,3604373943,3014905469,690584402,3823320797,791638366,2223281939,1398011302,3520161977,0,3991743681,538992704,4244381667,2981218425,1532751286,1785380564,3419096717,3200178535,960056178,1246420628,1280103576,1482221744,3486468741,3503319995,4025428677,2863326543,4227536621,1128514950,1296947098,859002214,2240123921,1162203018,4193849577,33687044,2139062782,1347481760,1010582648,2678045221,2829640523,1364325282,2745433693,1077985408,2408548869,2459086143,2644360225,943212656,4126475505,3166494563,3065430391,3671750063,555836226,269496352,4294908645,4092792573,3537006015,3452783745,202118168,320025894,3974901699,1600119230,2543297077,1145359496,387397934,3301201811,2812801621,2122220284,1027426170,1684319432,1566435258,421079858,1936954854,1616945344,2172753945,1330631070,3705438115,572679748,707427924,2425400123,2290647819,1179044492,4008585671,3099120491,336870440,3739122087,1583276732,185277718,3688593069,3772791771,842159716,976899700,168435220,1229577106,101059084,606366792,1549591736,3267517855,3553849021,2897014595,1650632388,2442242105,2509612081,3840161747,2038008818,3890688725,3368567691,926374254,1835907034,2374863873,3587531953,1313788572,2846482505,1819063512,1448540844,4109633523,3941213647,1701162954,2054852340,2930698567,134748176,3132806511,2021165296,623210314,774795868,471606328,2795958615,3031746419,3334885783,3907527627,3722280097,1953799400,522133822,1263263126,3183336545,2341176845,2324333839,1886425312,1044267644,3048588401,1718004428,1212733584,50529542,4143317495,235803164,1633788866,892690282,1465383342,3115962473,2256965911,3250673817,488449850,2661202215,3789633753,4177007595,2560144171,286339874,1768537042,3654906025,2391705863,2492770099,2610673197,505291324,2273808917,3924369609,3469625735,1431699370,673740880,3755965093,2358021891,2711746649,2307489801,218961690,3217021541,3873845719,1111672452,1751693520,1094828930,2576986153,757954394,252645662,2964376443,1414855848,3149649517,370555436],b=[1374988112,2118214995,437757123,975658646,1001089995,530400753,2902087851,1273168787,540080725,2910219766,2295101073,4110568485,1340463100,3307916247,641025152,3043140495,3736164937,632953703,1172967064,1576976609,3274667266,2169303058,2370213795,1809054150,59727847,361929877,3211623147,2505202138,3569255213,1484005843,1239443753,2395588676,1975683434,4102977912,2572697195,666464733,3202437046,4035489047,3374361702,2110667444,1675577880,3843699074,2538681184,1649639237,2976151520,3144396420,4269907996,4178062228,1883793496,2403728665,2497604743,1383856311,2876494627,1917518562,3810496343,1716890410,3001755655,800440835,2261089178,3543599269,807962610,599762354,33778362,3977675356,2328828971,2809771154,4077384432,1315562145,1708848333,101039829,3509871135,3299278474,875451293,2733856160,92987698,2767645557,193195065,1080094634,1584504582,3178106961,1042385657,2531067453,3711829422,1306967366,2438237621,1908694277,67556463,1615861247,429456164,3602770327,2302690252,1742315127,2968011453,126454664,3877198648,2043211483,2709260871,2084704233,4169408201,0,159417987,841739592,504459436,1817866830,4245618683,260388950,1034867998,908933415,168810852,1750902305,2606453969,607530554,202008497,2472011535,3035535058,463180190,2160117071,1641816226,1517767529,470948374,3801332234,3231722213,1008918595,303765277,235474187,4069246893,766945465,337553864,1475418501,2943682380,4003061179,2743034109,4144047775,1551037884,1147550661,1543208500,2336434550,3408119516,3069049960,3102011747,3610369226,1113818384,328671808,2227573024,2236228733,3535486456,2935566865,3341394285,496906059,3702665459,226906860,2009195472,733156972,2842737049,294930682,1206477858,2835123396,2700099354,1451044056,573804783,2269728455,3644379585,2362090238,2564033334,2801107407,2776292904,3669462566,1068351396,742039012,1350078989,1784663195,1417561698,4136440770,2430122216,775550814,2193862645,2673705150,1775276924,1876241833,3475313331,3366754619,270040487,3902563182,3678124923,3441850377,1851332852,3969562369,2203032232,3868552805,2868897406,566021896,4011190502,3135740889,1248802510,3936291284,699432150,832877231,708780849,3332740144,899835584,1951317047,4236429990,3767586992,866637845,4043610186,1106041591,2144161806,395441711,1984812685,1139781709,3433712980,3835036895,2664543715,1282050075,3240894392,1181045119,2640243204,25965917,4203181171,4211818798,3009879386,2463879762,3910161971,1842759443,2597806476,933301370,1509430414,3943906441,3467192302,3076639029,3776767469,2051518780,2631065433,1441952575,404016761,1942435775,1408749034,1610459739,3745345300,2017778566,3400528769,3110650942,941896748,3265478751,371049330,3168937228,675039627,4279080257,967311729,135050206,3635733660,1683407248,2076935265,3576870512,1215061108,3501741890],C=[1347548327,1400783205,3273267108,2520393566,3409685355,4045380933,2880240216,2471224067,1428173050,4138563181,2441661558,636813900,4233094615,3620022987,2149987652,2411029155,1239331162,1730525723,2554718734,3781033664,46346101,310463728,2743944855,3328955385,3875770207,2501218972,3955191162,3667219033,768917123,3545789473,692707433,1150208456,1786102409,2029293177,1805211710,3710368113,3065962831,401639597,1724457132,3028143674,409198410,2196052529,1620529459,1164071807,3769721975,2226875310,486441376,2499348523,1483753576,428819965,2274680428,3075636216,598438867,3799141122,1474502543,711349675,129166120,53458370,2592523643,2782082824,4063242375,2988687269,3120694122,1559041666,730517276,2460449204,4042459122,2706270690,3446004468,3573941694,533804130,2328143614,2637442643,2695033685,839224033,1973745387,957055980,2856345839,106852767,1371368976,4181598602,1033297158,2933734917,1179510461,3046200461,91341917,1862534868,4284502037,605657339,2547432937,3431546947,2003294622,3182487618,2282195339,954669403,3682191598,1201765386,3917234703,3388507166,0,2198438022,1211247597,2887651696,1315723890,4227665663,1443857720,507358933,657861945,1678381017,560487590,3516619604,975451694,2970356327,261314535,3535072918,2652609425,1333838021,2724322336,1767536459,370938394,182621114,3854606378,1128014560,487725847,185469197,2918353863,3106780840,3356761769,2237133081,1286567175,3152976349,4255350624,2683765030,3160175349,3309594171,878443390,1988838185,3704300486,1756818940,1673061617,3403100636,272786309,1075025698,545572369,2105887268,4174560061,296679730,1841768865,1260232239,4091327024,3960309330,3497509347,1814803222,2578018489,4195456072,575138148,3299409036,446754879,3629546796,4011996048,3347532110,3252238545,4270639778,915985419,3483825537,681933534,651868046,2755636671,3828103837,223377554,2607439820,1649704518,3270937875,3901806776,1580087799,4118987695,3198115200,2087309459,2842678573,3016697106,1003007129,2802849917,1860738147,2077965243,164439672,4100872472,32283319,2827177882,1709610350,2125135846,136428751,3874428392,3652904859,3460984630,3572145929,3593056380,2939266226,824852259,818324884,3224740454,930369212,2801566410,2967507152,355706840,1257309336,4148292826,243256656,790073846,2373340630,1296297904,1422699085,3756299780,3818836405,457992840,3099667487,2135319889,77422314,1560382517,1945798516,788204353,1521706781,1385356242,870912086,325965383,2358957921,2050466060,2388260884,2313884476,4006521127,901210569,3990953189,1014646705,1503449823,1062597235,2031621326,3212035895,3931371469,1533017514,350174575,2256028891,2177544179,1052338372,741876788,1606591296,1914052035,213705253,2334669897,1107234197,1899603969,3725069491,2631447780,2422494913,1635502980,1893020342,1950903388,1120974935],D=[2807058932,1699970625,2764249623,1586903591,1808481195,1173430173,1487645946,59984867,4199882800,1844882806,1989249228,1277555970,3623636965,3419915562,1149249077,2744104290,1514790577,459744698,244860394,3235995134,1963115311,4027744588,2544078150,4190530515,1608975247,2627016082,2062270317,1507497298,2200818878,567498868,1764313568,3359936201,2305455554,2037970062,1047239e3,1910319033,1337376481,2904027272,2892417312,984907214,1243112415,830661914,861968209,2135253587,2011214180,2927934315,2686254721,731183368,1750626376,4246310725,1820824798,4172763771,3542330227,48394827,2404901663,2871682645,671593195,3254988725,2073724613,145085239,2280796200,2779915199,1790575107,2187128086,472615631,3029510009,4075877127,3802222185,4107101658,3201631749,1646252340,4270507174,1402811438,1436590835,3778151818,3950355702,3963161475,4020912224,2667994737,273792366,2331590177,104699613,95345982,3175501286,2377486676,1560637892,3564045318,369057872,4213447064,3919042237,1137477952,2658625497,1119727848,2340947849,1530455833,4007360968,172466556,266959938,516552836,0,2256734592,3980931627,1890328081,1917742170,4294704398,945164165,3575528878,958871085,3647212047,2787207260,1423022939,775562294,1739656202,3876557655,2530391278,2443058075,3310321856,547512796,1265195639,437656594,3121275539,719700128,3762502690,387781147,218828297,3350065803,2830708150,2848461854,428169201,122466165,3720081049,1627235199,648017665,4122762354,1002783846,2117360635,695634755,3336358691,4234721005,4049844452,3704280881,2232435299,574624663,287343814,612205898,1039717051,840019705,2708326185,793451934,821288114,1391201670,3822090177,376187827,3113855344,1224348052,1679968233,2361698556,1058709744,752375421,2431590963,1321699145,3519142200,2734591178,188127444,2177869557,3727205754,2384911031,3215212461,2648976442,2450346104,3432737375,1180849278,331544205,3102249176,4150144569,2952102595,2159976285,2474404304,766078933,313773861,2570832044,2108100632,1668212892,3145456443,2013908262,418672217,3070356634,2594734927,1852171925,3867060991,3473416636,3907448597,2614737639,919489135,164948639,2094410160,2997825956,590424639,2486224549,1723872674,3157750862,3399941250,3501252752,3625268135,2555048196,3673637356,1343127501,4130281361,3599595085,2957853679,1297403050,81781910,3051593425,2283490410,532201772,1367295589,3926170974,895287692,1953757831,1093597963,492483431,3528626907,1446242576,1192455638,1636604631,209336225,344873464,1015671571,669961897,3375740769,3857572124,2973530695,3747192018,1933530610,3464042516,935293895,3454686199,2858115069,1863638845,3683022916,4085369519,3292445032,875313188,1080017571,3279033885,621591778,1233856572,2504130317,24197544,3017672716,3835484340,3247465558,2220981195,3060847922,1551124588,1463996600],_=[4104605777,1097159550,396673818,660510266,2875968315,2638606623,4200115116,3808662347,821712160,1986918061,3430322568,38544885,3856137295,718002117,893681702,1654886325,2975484382,3122358053,3926825029,4274053469,796197571,1290801793,1184342925,3556361835,2405426947,2459735317,1836772287,1381620373,3196267988,1948373848,3764988233,3385345166,3263785589,2390325492,1480485785,3111247143,3780097726,2293045232,548169417,3459953789,3746175075,439452389,1362321559,1400849762,1685577905,1806599355,2174754046,137073913,1214797936,1174215055,3731654548,2079897426,1943217067,1258480242,529487843,1437280870,3945269170,3049390895,3313212038,923313619,679998e3,3215307299,57326082,377642221,3474729866,2041877159,133361907,1776460110,3673476453,96392454,878845905,2801699524,777231668,4082475170,2330014213,4142626212,2213296395,1626319424,1906247262,1846563261,562755902,3708173718,1040559837,3871163981,1418573201,3294430577,114585348,1343618912,2566595609,3186202582,1078185097,3651041127,3896688048,2307622919,425408743,3371096953,2081048481,1108339068,2216610296,0,2156299017,736970802,292596766,1517440620,251657213,2235061775,2933202493,758720310,265905162,1554391400,1532285339,908999204,174567692,1474760595,4002861748,2610011675,3234156416,3693126241,2001430874,303699484,2478443234,2687165888,585122620,454499602,151849742,2345119218,3064510765,514443284,4044981591,1963412655,2581445614,2137062819,19308535,1928707164,1715193156,4219352155,1126790795,600235211,3992742070,3841024952,836553431,1669664834,2535604243,3323011204,1243905413,3141400786,4180808110,698445255,2653899549,2989552604,2253581325,3252932727,3004591147,1891211689,2487810577,3915653703,4237083816,4030667424,2100090966,865136418,1229899655,953270745,3399679628,3557504664,4118925222,2061379749,3079546586,2915017791,983426092,2022837584,1607244650,2118541908,2366882550,3635996816,972512814,3283088770,1568718495,3499326569,3576539503,621982671,2895723464,410887952,2623762152,1002142683,645401037,1494807662,2595684844,1335535747,2507040230,4293295786,3167684641,367585007,3885750714,1865862730,2668221674,2960971305,2763173681,1059270954,2777952454,2724642869,1320957812,2194319100,2429595872,2815956275,77089521,3973773121,3444575871,2448830231,1305906550,4021308739,2857194700,2516901860,3518358430,1787304780,740276417,1699839814,1592394909,2352307457,2272556026,188821243,1729977011,3687994002,274084841,3594982253,3613494426,2701949495,4162096729,322734571,2837966542,1640576439,484830689,1202797690,3537852828,4067639125,349075736,3342319475,4157467219,4255800159,1030690015,1155237496,2951971274,1757691577,607398968,2738905026,499347990,3794078908,1011452712,227885567,2818666809,213114376,3034881240,1455525988,3414450555,850817237,1817998408,3092726480],F=[0,235474187,470948374,303765277,941896748,908933415,607530554,708780849,1883793496,2118214995,1817866830,1649639237,1215061108,1181045119,1417561698,1517767529,3767586992,4003061179,4236429990,4069246893,3635733660,3602770327,3299278474,3400528769,2430122216,2664543715,2362090238,2193862645,2835123396,2801107407,3035535058,3135740889,3678124923,3576870512,3341394285,3374361702,3810496343,3977675356,4279080257,4043610186,2876494627,2776292904,3076639029,3110650942,2472011535,2640243204,2403728665,2169303058,1001089995,899835584,666464733,699432150,59727847,226906860,530400753,294930682,1273168787,1172967064,1475418501,1509430414,1942435775,2110667444,1876241833,1641816226,2910219766,2743034109,2976151520,3211623147,2505202138,2606453969,2302690252,2269728455,3711829422,3543599269,3240894392,3475313331,3843699074,3943906441,4178062228,4144047775,1306967366,1139781709,1374988112,1610459739,1975683434,2076935265,1775276924,1742315127,1034867998,866637845,566021896,800440835,92987698,193195065,429456164,395441711,1984812685,2017778566,1784663195,1683407248,1315562145,1080094634,1383856311,1551037884,101039829,135050206,437757123,337553864,1042385657,807962610,573804783,742039012,2531067453,2564033334,2328828971,2227573024,2935566865,2700099354,3001755655,3168937228,3868552805,3902563182,4203181171,4102977912,3736164937,3501741890,3265478751,3433712980,1106041591,1340463100,1576976609,1408749034,2043211483,2009195472,1708848333,1809054150,832877231,1068351396,766945465,599762354,159417987,126454664,361929877,463180190,2709260871,2943682380,3178106961,3009879386,2572697195,2538681184,2236228733,2336434550,3509871135,3745345300,3441850377,3274667266,3910161971,3877198648,4110568485,4211818798,2597806476,2497604743,2261089178,2295101073,2733856160,2902087851,3202437046,2968011453,3936291284,3835036895,4136440770,4169408201,3535486456,3702665459,3467192302,3231722213,2051518780,1951317047,1716890410,1750902305,1113818384,1282050075,1584504582,1350078989,168810852,67556463,371049330,404016761,841739592,1008918595,775550814,540080725,3969562369,3801332234,4035489047,4269907996,3569255213,3669462566,3366754619,3332740144,2631065433,2463879762,2160117071,2395588676,2767645557,2868897406,3102011747,3069049960,202008497,33778362,270040487,504459436,875451293,975658646,675039627,641025152,2084704233,1917518562,1615861247,1851332852,1147550661,1248802510,1484005843,1451044056,933301370,967311729,733156972,632953703,260388950,25965917,328671808,496906059,1206477858,1239443753,1543208500,1441952575,2144161806,1908694277,1675577880,1842759443,3610369226,3644379585,3408119516,3307916247,4011190502,3776767469,4077384432,4245618683,2809771154,2842737049,3144396420,3043140495,2673705150,2438237621,2203032232,2370213795],he=[0,185469197,370938394,487725847,741876788,657861945,975451694,824852259,1483753576,1400783205,1315723890,1164071807,1950903388,2135319889,1649704518,1767536459,2967507152,3152976349,2801566410,2918353863,2631447780,2547432937,2328143614,2177544179,3901806776,3818836405,4270639778,4118987695,3299409036,3483825537,3535072918,3652904859,2077965243,1893020342,1841768865,1724457132,1474502543,1559041666,1107234197,1257309336,598438867,681933534,901210569,1052338372,261314535,77422314,428819965,310463728,3409685355,3224740454,3710368113,3593056380,3875770207,3960309330,4045380933,4195456072,2471224067,2554718734,2237133081,2388260884,3212035895,3028143674,2842678573,2724322336,4138563181,4255350624,3769721975,3955191162,3667219033,3516619604,3431546947,3347532110,2933734917,2782082824,3099667487,3016697106,2196052529,2313884476,2499348523,2683765030,1179510461,1296297904,1347548327,1533017514,1786102409,1635502980,2087309459,2003294622,507358933,355706840,136428751,53458370,839224033,957055980,605657339,790073846,2373340630,2256028891,2607439820,2422494913,2706270690,2856345839,3075636216,3160175349,3573941694,3725069491,3273267108,3356761769,4181598602,4063242375,4011996048,3828103837,1033297158,915985419,730517276,545572369,296679730,446754879,129166120,213705253,1709610350,1860738147,1945798516,2029293177,1239331162,1120974935,1606591296,1422699085,4148292826,4233094615,3781033664,3931371469,3682191598,3497509347,3446004468,3328955385,2939266226,2755636671,3106780840,2988687269,2198438022,2282195339,2501218972,2652609425,1201765386,1286567175,1371368976,1521706781,1805211710,1620529459,2105887268,1988838185,533804130,350174575,164439672,46346101,870912086,954669403,636813900,788204353,2358957921,2274680428,2592523643,2441661558,2695033685,2880240216,3065962831,3182487618,3572145929,3756299780,3270937875,3388507166,4174560061,4091327024,4006521127,3854606378,1014646705,930369212,711349675,560487590,272786309,457992840,106852767,223377554,1678381017,1862534868,1914052035,2031621326,1211247597,1128014560,1580087799,1428173050,32283319,182621114,401639597,486441376,768917123,651868046,1003007129,818324884,1503449823,1385356242,1333838021,1150208456,1973745387,2125135846,1673061617,1756818940,2970356327,3120694122,2802849917,2887651696,2637442643,2520393566,2334669897,2149987652,3917234703,3799141122,4284502037,4100872472,3309594171,3460984630,3545789473,3629546796,2050466060,1899603969,1814803222,1730525723,1443857720,1560382517,1075025698,1260232239,575138148,692707433,878443390,1062597235,243256656,91341917,409198410,325965383,3403100636,3252238545,3704300486,3620022987,3874428392,3990953189,4042459122,4227665663,2460449204,2578018489,2226875310,2411029155,3198115200,3046200461,2827177882,2743944855],z=[0,218828297,437656594,387781147,875313188,958871085,775562294,590424639,1750626376,1699970625,1917742170,2135253587,1551124588,1367295589,1180849278,1265195639,3501252752,3720081049,3399941250,3350065803,3835484340,3919042237,4270507174,4085369519,3102249176,3051593425,2734591178,2952102595,2361698556,2177869557,2530391278,2614737639,3145456443,3060847922,2708326185,2892417312,2404901663,2187128086,2504130317,2555048196,3542330227,3727205754,3375740769,3292445032,3876557655,3926170974,4246310725,4027744588,1808481195,1723872674,1910319033,2094410160,1608975247,1391201670,1173430173,1224348052,59984867,244860394,428169201,344873464,935293895,984907214,766078933,547512796,1844882806,1627235199,2011214180,2062270317,1507497298,1423022939,1137477952,1321699145,95345982,145085239,532201772,313773861,830661914,1015671571,731183368,648017665,3175501286,2957853679,2807058932,2858115069,2305455554,2220981195,2474404304,2658625497,3575528878,3625268135,3473416636,3254988725,3778151818,3963161475,4213447064,4130281361,3599595085,3683022916,3432737375,3247465558,3802222185,4020912224,4172763771,4122762354,3201631749,3017672716,2764249623,2848461854,2331590177,2280796200,2431590963,2648976442,104699613,188127444,472615631,287343814,840019705,1058709744,671593195,621591778,1852171925,1668212892,1953757831,2037970062,1514790577,1463996600,1080017571,1297403050,3673637356,3623636965,3235995134,3454686199,4007360968,3822090177,4107101658,4190530515,2997825956,3215212461,2830708150,2779915199,2256734592,2340947849,2627016082,2443058075,172466556,122466165,273792366,492483431,1047239e3,861968209,612205898,695634755,1646252340,1863638845,2013908262,1963115311,1446242576,1530455833,1277555970,1093597963,1636604631,1820824798,2073724613,1989249228,1436590835,1487645946,1337376481,1119727848,164948639,81781910,331544205,516552836,1039717051,821288114,669961897,719700128,2973530695,3157750862,2871682645,2787207260,2232435299,2283490410,2667994737,2450346104,3647212047,3564045318,3279033885,3464042516,3980931627,3762502690,4150144569,4199882800,3070356634,3121275539,2904027272,2686254721,2200818878,2384911031,2570832044,2486224549,3747192018,3528626907,3310321856,3359936201,3950355702,3867060991,4049844452,4234721005,1739656202,1790575107,2108100632,1890328081,1402811438,1586903591,1233856572,1149249077,266959938,48394827,369057872,418672217,1002783846,919489135,567498868,752375421,209336225,24197544,376187827,459744698,945164165,895287692,574624663,793451934,1679968233,1764313568,2117360635,1933530610,1343127501,1560637892,1243112415,1192455638,3704280881,3519142200,3336358691,3419915562,3907448597,3857572124,4075877127,4294704398,3029510009,3113855344,2927934315,2744104290,2159976285,2377486676,2594734927,2544078150],Ce=[0,151849742,303699484,454499602,607398968,758720310,908999204,1059270954,1214797936,1097159550,1517440620,1400849762,1817998408,1699839814,2118541908,2001430874,2429595872,2581445614,2194319100,2345119218,3034881240,3186202582,2801699524,2951971274,3635996816,3518358430,3399679628,3283088770,4237083816,4118925222,4002861748,3885750714,1002142683,850817237,698445255,548169417,529487843,377642221,227885567,77089521,1943217067,2061379749,1640576439,1757691577,1474760595,1592394909,1174215055,1290801793,2875968315,2724642869,3111247143,2960971305,2405426947,2253581325,2638606623,2487810577,3808662347,3926825029,4044981591,4162096729,3342319475,3459953789,3576539503,3693126241,1986918061,2137062819,1685577905,1836772287,1381620373,1532285339,1078185097,1229899655,1040559837,923313619,740276417,621982671,439452389,322734571,137073913,19308535,3871163981,4021308739,4104605777,4255800159,3263785589,3414450555,3499326569,3651041127,2933202493,2815956275,3167684641,3049390895,2330014213,2213296395,2566595609,2448830231,1305906550,1155237496,1607244650,1455525988,1776460110,1626319424,2079897426,1928707164,96392454,213114376,396673818,514443284,562755902,679998e3,865136418,983426092,3708173718,3557504664,3474729866,3323011204,4180808110,4030667424,3945269170,3794078908,2507040230,2623762152,2272556026,2390325492,2975484382,3092726480,2738905026,2857194700,3973773121,3856137295,4274053469,4157467219,3371096953,3252932727,3673476453,3556361835,2763173681,2915017791,3064510765,3215307299,2156299017,2307622919,2459735317,2610011675,2081048481,1963412655,1846563261,1729977011,1480485785,1362321559,1243905413,1126790795,878845905,1030690015,645401037,796197571,274084841,425408743,38544885,188821243,3613494426,3731654548,3313212038,3430322568,4082475170,4200115116,3780097726,3896688048,2668221674,2516901860,2366882550,2216610296,3141400786,2989552604,2837966542,2687165888,1202797690,1320957812,1437280870,1554391400,1669664834,1787304780,1906247262,2022837584,265905162,114585348,499347990,349075736,736970802,585122620,972512814,821712160,2595684844,2478443234,2293045232,2174754046,3196267988,3079546586,2895723464,2777952454,3537852828,3687994002,3234156416,3385345166,4142626212,4293295786,3841024952,3992742070,174567692,57326082,410887952,292596766,777231668,660510266,1011452712,893681702,1108339068,1258480242,1343618912,1494807662,1715193156,1865862730,1948373848,2100090966,2701949495,2818666809,3004591147,3122358053,2235061775,2352307457,2535604243,2653899549,3915653703,3764988233,4219352155,4067639125,3444575871,3294430577,3746175075,3594982253,836553431,953270745,600235211,718002117,367585007,484830689,133361907,251657213,2041877159,1891211689,1806599355,1654886325,1568718495,1418573201,1335535747,1184342925];function de(P){for(var B=[],K=0;K<P.length;K+=4)B.push(P[K]<<24|P[K+1]<<16|P[K+2]<<8|P[K+3]);return B}var R=function(P){if(!(this instanceof R))throw Error("AES must be instanitated with `new`");Object.defineProperty(this,"key",{value:n(P,!0)}),this._prepare()};R.prototype._prepare=function(){var P=c[this.key.length];if(P==null)throw new Error("invalid key size (must be 16, 24 or 32 bytes)");this._Ke=[],this._Kd=[];for(var B=0;B<=P;B++)this._Ke.push([0,0,0,0]),this._Kd.push([0,0,0,0]);for(var K=(P+1)*4,T=this.key.length/4,$=de(this.key),ye,B=0;B<T;B++)ye=B>>2,this._Ke[ye][B%4]=$[B],this._Kd[P-ye][B%4]=$[B];for(var be=0,ct=T,It;ct<K;){if(It=$[T-1],$[0]^=d[It>>16&255]<<24^d[It>>8&255]<<16^d[It&255]<<8^d[It>>24&255]^u[be]<<24,be+=1,T!=8)for(var B=1;B<T;B++)$[B]^=$[B-1];else{for(var B=1;B<T/2;B++)$[B]^=$[B-1];It=$[T/2-1],$[T/2]^=d[It&255]^d[It>>8&255]<<8^d[It>>16&255]<<16^d[It>>24&255]<<24;for(var B=T/2+1;B<T;B++)$[B]^=$[B-1]}for(var B=0,Zt,Dt;B<T&&ct<K;)Zt=ct>>2,Dt=ct%4,this._Ke[Zt][Dt]=$[B],this._Kd[P-Zt][Dt]=$[B++],ct++}for(var Zt=1;Zt<P;Zt++)for(var Dt=0;Dt<4;Dt++)It=this._Kd[Zt][Dt],this._Kd[Zt][Dt]=F[It>>24&255]^he[It>>16&255]^z[It>>8&255]^Ce[It&255]},R.prototype.encrypt=function(P){if(P.length!=16)throw new Error("invalid plaintext size (must be 16 bytes)");for(var B=this._Ke.length-1,K=[0,0,0,0],T=de(P),$=0;$<4;$++)T[$]^=this._Ke[0][$];for(var ye=1;ye<B;ye++){for(var $=0;$<4;$++)K[$]=f[T[$]>>24&255]^p[T[($+1)%4]>>16&255]^g[T[($+2)%4]>>8&255]^v[T[($+3)%4]&255]^this._Ke[ye][$];T=K.slice()}for(var be=i(16),ct,$=0;$<4;$++)ct=this._Ke[B][$],be[4*$]=(d[T[$]>>24&255]^ct>>24)&255,be[4*$+1]=(d[T[($+1)%4]>>16&255]^ct>>16)&255,be[4*$+2]=(d[T[($+2)%4]>>8&255]^ct>>8)&255,be[4*$+3]=(d[T[($+3)%4]&255]^ct)&255;return be},R.prototype.decrypt=function(P){if(P.length!=16)throw new Error("invalid ciphertext size (must be 16 bytes)");for(var B=this._Kd.length-1,K=[0,0,0,0],T=de(P),$=0;$<4;$++)T[$]^=this._Kd[0][$];for(var ye=1;ye<B;ye++){for(var $=0;$<4;$++)K[$]=b[T[$]>>24&255]^C[T[($+3)%4]>>16&255]^D[T[($+2)%4]>>8&255]^_[T[($+1)%4]&255]^this._Kd[ye][$];T=K.slice()}for(var be=i(16),ct,$=0;$<4;$++)ct=this._Kd[B][$],be[4*$]=(l[T[$]>>24&255]^ct>>24)&255,be[4*$+1]=(l[T[($+3)%4]>>16&255]^ct>>16)&255,be[4*$+2]=(l[T[($+2)%4]>>8&255]^ct>>8)&255,be[4*$+3]=(l[T[($+1)%4]&255]^ct)&255;return be};var V=function(P){if(!(this instanceof V))throw Error("AES must be instanitated with `new`");this.description="Electronic Code Block",this.name="ecb",this._aes=new R(P)};V.prototype.encrypt=function(P){if(P=n(P),P.length%16!==0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var B=i(P.length),K=i(16),T=0;T<P.length;T+=16)o(P,K,0,T,T+16),K=this._aes.encrypt(K),o(K,B,T);return B},V.prototype.decrypt=function(P){if(P=n(P),P.length%16!==0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var B=i(P.length),K=i(16),T=0;T<P.length;T+=16)o(P,K,0,T,T+16),K=this._aes.decrypt(K),o(K,B,T);return B};var le=function(P,B){if(!(this instanceof le))throw Error("AES must be instanitated with `new`");if(this.description="Cipher Block Chaining",this.name="cbc",!B)B=i(16);else if(B.length!=16)throw new Error("invalid initialation vector size (must be 16 bytes)");this._lastCipherblock=n(B,!0),this._aes=new R(P)};le.prototype.encrypt=function(P){if(P=n(P),P.length%16!==0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var B=i(P.length),K=i(16),T=0;T<P.length;T+=16){o(P,K,0,T,T+16);for(var $=0;$<16;$++)K[$]^=this._lastCipherblock[$];this._lastCipherblock=this._aes.encrypt(K),o(this._lastCipherblock,B,T)}return B},le.prototype.decrypt=function(P){if(P=n(P),P.length%16!==0)throw new Error("invalid ciphertext size (must be multiple of 16 bytes)");for(var B=i(P.length),K=i(16),T=0;T<P.length;T+=16){o(P,K,0,T,T+16),K=this._aes.decrypt(K);for(var $=0;$<16;$++)B[T+$]=K[$]^this._lastCipherblock[$];o(P,this._lastCipherblock,0,T,T+16)}return B};var se=function(P,B,K){if(!(this instanceof se))throw Error("AES must be instanitated with `new`");if(this.description="Cipher Feedback",this.name="cfb",!B)B=i(16);else if(B.length!=16)throw new Error("invalid initialation vector size (must be 16 size)");K||(K=1),this.segmentSize=K,this._shiftRegister=n(B,!0),this._aes=new R(P)};se.prototype.encrypt=function(P){if(P.length%this.segmentSize!=0)throw new Error("invalid plaintext size (must be segmentSize bytes)");for(var B=n(P,!0),K,T=0;T<B.length;T+=this.segmentSize){K=this._aes.encrypt(this._shiftRegister);for(var $=0;$<this.segmentSize;$++)B[T+$]^=K[$];o(this._shiftRegister,this._shiftRegister,0,this.segmentSize),o(B,this._shiftRegister,16-this.segmentSize,T,T+this.segmentSize)}return B},se.prototype.decrypt=function(P){if(P.length%this.segmentSize!=0)throw new Error("invalid ciphertext size (must be segmentSize bytes)");for(var B=n(P,!0),K,T=0;T<B.length;T+=this.segmentSize){K=this._aes.encrypt(this._shiftRegister);for(var $=0;$<this.segmentSize;$++)B[T+$]^=K[$];o(this._shiftRegister,this._shiftRegister,0,this.segmentSize),o(P,this._shiftRegister,16-this.segmentSize,T,T+this.segmentSize)}return B};var H=function(P,B){if(!(this instanceof H))throw Error("AES must be instanitated with `new`");if(this.description="Output Feedback",this.name="ofb",!B)B=i(16);else if(B.length!=16)throw new Error("invalid initialation vector size (must be 16 bytes)");this._lastPrecipher=n(B,!0),this._lastPrecipherIndex=16,this._aes=new R(P)};H.prototype.encrypt=function(P){for(var B=n(P,!0),K=0;K<B.length;K++)this._lastPrecipherIndex===16&&(this._lastPrecipher=this._aes.encrypt(this._lastPrecipher),this._lastPrecipherIndex=0),B[K]^=this._lastPrecipher[this._lastPrecipherIndex++];return B},H.prototype.decrypt=H.prototype.encrypt;var G=function(P){if(!(this instanceof G))throw Error("Counter must be instanitated with `new`");P!==0&&!P&&(P=1),typeof P=="number"?(this._counter=i(16),this.setValue(P)):this.setBytes(P)};G.prototype.setValue=function(P){if(typeof P!="number"||parseInt(P)!=P)throw new Error("invalid counter value (must be an integer)");if(P>Number.MAX_SAFE_INTEGER)throw new Error("integer value out of safe range");for(var B=15;B>=0;--B)this._counter[B]=P%256,P=parseInt(P/256)},G.prototype.setBytes=function(P){if(P=n(P,!0),P.length!=16)throw new Error("invalid counter bytes size (must be 16 bytes)");this._counter=P},G.prototype.increment=function(){for(var P=15;P>=0;P--)if(this._counter[P]===255)this._counter[P]=0;else{this._counter[P]++;break}};var j=function(P,B){if(!(this instanceof j))throw Error("AES must be instanitated with `new`");this.description="Counter",this.name="ctr",B instanceof G||(B=new G(B)),this._counter=B,this._remainingCounter=null,this._remainingCounterIndex=16,this._aes=new R(P)};j.prototype.encrypt=function(P){for(var B=n(P,!0),K=0;K<B.length;K++)this._remainingCounterIndex===16&&(this._remainingCounter=this._aes.encrypt(this._counter._counter),this._remainingCounterIndex=0,this._counter.increment()),B[K]^=this._remainingCounter[this._remainingCounterIndex++];return B},j.prototype.decrypt=j.prototype.encrypt;function me(P){P=n(P,!0);var B=16-P.length%16,K=i(P.length+B);o(P,K);for(var T=P.length;T<K.length;T++)K[T]=B;return K}function Pe(P){if(P=n(P,!0),P.length<16)throw new Error("PKCS#7 invalid length");var B=P[P.length-1];if(B>16)throw new Error("PKCS#7 padding byte out of range");for(var K=P.length-B,T=0;T<B;T++)if(P[K+T]!==B)throw new Error("PKCS#7 invalid padding byte");var $=i(K);return o(P,$,0,0,K),$}var Te={AES:R,Counter:G,ModeOfOperation:{ecb:V,cbc:le,cfb:se,ofb:H,ctr:j},utils:{hex:a,utf8:s},padding:{pkcs7:{pad:me,strip:Pe}},_arrayTest:{coerceArray:n,createArray:i,copyArray:o}};typeof UB<"u"?TG.exports=Te:typeof define=="function"&&define.amd?define([],function(){return Te}):(t.aesjs&&(Te._aesjs=t.aesjs),t.aesjs=Te)})(UB)});function OG(t,e,r){var n=e?0:4,i=e?4:0,o=e?0:3,s=e?1:2,a=e?2:1,c=e?3:0,u=e?_Ie:DIe,d=e?TIe:BIe,l=g.prototype,f="is"+t,p="_"+f;return l.buffer=void 0,l.offset=0,l[p]=!0,l.toNumber=D,l.toString=_,l.toJSON=D,l.toArray=CIe,sh&&(l.toBuffer=PIe),oh&&(l.toArrayBuffer=MG),g[f]=v,g;function g(z,Ce,de,R){return this instanceof g?b(this,z,Ce,de,R):new g(z,Ce,de,R)}function v(z){return!!(z&&z[p])}function b(z,Ce,de,R,V){if(oh&&mk&&(Ce instanceof mk&&(Ce=new oh(Ce)),R instanceof mk&&(R=new oh(R))),!Ce&&!de&&!R&&!ah){z.buffer=LG(BG,0);return}if(!NG(Ce,de)){var le=ah||Array;V=de,R=Ce,de=0,Ce=ah===sh?sh.alloc(8):new le(8)}z.buffer=Ce,z.offset=de|=0,hk!==typeof R&&(typeof R=="string"?C(Ce,de,R,V||10):NG(R,V)?$B(Ce,de,R,V):typeof V=="number"?(F(Ce,de+n,R),F(Ce,de+i,V)):R>0?u(Ce,de,R):R<0?d(Ce,de,R):$B(Ce,de,BG,0))}function C(z,Ce,de,R){var V=0,le=de.length,se=0,H=0;de[0]==="-"&&V++;for(var G=V;V<le;){var j=parseInt(de[V++],R);if(!(j>=0))break;H=H*R+j,se=se*R+Math.floor(H/ih),H%=ih}G&&(se=~se,H?H=ih-H:se++),F(z,Ce+n,se),F(z,Ce+i,H)}function D(){var z=this.buffer,Ce=this.offset,de=he(z,Ce+n),R=he(z,Ce+i);return r||(de|=0),de?de*ih+R:R}function _(z){var Ce=this.buffer,de=this.offset,R=he(Ce,de+n),V=he(Ce,de+i),le="",se=!r&&R&2147483648;for(se&&(R=~R,V=ih-V),z=z||10;;){var H=R%z*ih+V;if(R=Math.floor(R/z),V=Math.floor(H/z),le=(H%z).toString(z)+le,!R&&!V)break}return se&&(le="-"+le),le}function F(z,Ce,de){z[Ce+c]=de&255,de=de>>8,z[Ce+a]=de&255,de=de>>8,z[Ce+s]=de&255,de=de>>8,z[Ce+o]=de&255}function he(z,Ce){return z[Ce+o]*AIe+(z[Ce+s]<<16)+(z[Ce+a]<<8)+z[Ce+c]}}function CIe(t){var e=this.buffer,r=this.offset;return ah=null,t!==!1&&RIe(e)?e.length===8?e:e.slice(r,r+8):LG(e,r)}function PIe(t){var e=this.buffer,r=this.offset;return ah=sh,t!==!1&&sh.isBuffer(e)?e.length===8?e:e.slice(r,r+8):sh.from(MG.call(this,t))}function MG(t){var e=this.buffer,r=this.offset,n=e.buffer;if(ah=oh,t!==!1&&!e.offset&&n instanceof mk)return n.byteLength===8?n:n.slice(r,r+8);var i=new oh(8);return $B(i,0,e,r),i.buffer}function NG(t,e){var r=t&&t.length;return e|=0,r&&e+8<=r&&typeof t[e]!="string"}function $B(t,e,r,n){e|=0,n|=0;for(var i=0;i<8;i++)t[e++]=r[n++]&255}function LG(t,e){return Array.prototype.slice.call(t,e,e+8)}function _Ie(t,e,r){for(var n=e+8;n>e;)t[--n]=r&255,r/=256}function TIe(t,e,r){var n=e+8;for(r++;n>e;)t[--n]=-r&255^255,r/=256}function DIe(t,e,r){for(var n=e+8;e<n;)t[e++]=r&255,r/=256}function BIe(t,e,r){var n=e+8;for(r++;e<n;)t[e++]=-r&255^255,r/=256}function NIe(t){return!!t&&Object.prototype.toString.call(t)=="[object Array]"}var hk,sh,oh,mk,BG,RIe,ih,AIe,ah,gk,FB,yk=N(()=>{hk="undefined",sh=hk!==typeof Buffer&&Buffer,oh=hk!==typeof Uint8Array&&Uint8Array,mk=hk!==typeof ArrayBuffer&&ArrayBuffer,BG=[0,0,0,0,0,0,0,0],RIe=Array.isArray||NIe,ih=4294967296,AIe=16777216,gk=OG("Uint64BE",!0,!0),FB=OG("Int64BE",!0,!1)});var UG=ce((HG,vk)=>{(function(t){"use strict";let e="(0?\\d+|0x[a-f0-9]+)",r={fourOctet:new RegExp(`^${e}\\.${e}\\.${e}\\.${e}$`,"i"),threeOctet:new RegExp(`^${e}\\.${e}\\.${e}$`,"i"),twoOctet:new RegExp(`^${e}\\.${e}$`,"i"),longValue:new RegExp(`^${e}$`,"i")},n=new RegExp("^0[0-7]+$","i"),i=new RegExp("^0x[a-f0-9]+$","i"),o="%[0-9a-z]{1,}",s="(?:[0-9a-f]+::?)+",a={zoneIndex:new RegExp(o,"i"),native:new RegExp(`^(::)?(${s})?([0-9a-f]+)?(::)?(${o})?$`,"i"),deprecatedTransitional:new RegExp(`^(?:::)(${e}\\.${e}\\.${e}\\.${e}(${o})?)$`,"i"),transitional:new RegExp(`^((?:${s})|(?:::)(?:${s})?)${e}\\.${e}\\.${e}\\.${e}(${o})?$`,"i")};function c(p,g){if(p.indexOf("::")!==p.lastIndexOf("::"))return null;let v=0,b=-1,C=(p.match(a.zoneIndex)||[])[0],D,_;for(C&&(C=C.substring(1),p=p.replace(/%.+$/,""));(b=p.indexOf(":",b+1))>=0;)v++;if(p.substr(0,2)==="::"&&v--,p.substr(-2,2)==="::"&&v--,v>g)return null;for(_=g-v,D=":";_--;)D+="0:";return p=p.replace("::",D),p[0]===":"&&(p=p.slice(1)),p[p.length-1]===":"&&(p=p.slice(0,-1)),g=(function(){let F=p.split(":"),he=[];for(let z=0;z<F.length;z++)he.push(parseInt(F[z],16));return he})(),{parts:g,zoneId:C}}function u(p,g,v,b){if(p.length!==g.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");let C=0,D;for(;b>0;){if(D=v-b,D<0&&(D=0),p[C]>>D!==g[C]>>D)return!1;b-=v,C+=1}return!0}function d(p){if(i.test(p))return parseInt(p,16);if(p[0]==="0"&&!isNaN(parseInt(p[1],10))){if(n.test(p))return parseInt(p,8);throw new Error(`ipaddr: cannot parse ${p} as octal`)}return parseInt(p,10)}function l(p,g){for(;p.length<g;)p=`0${p}`;return p}let f={};f.IPv4=(function(){function p(g){if(g.length!==4)throw new Error("ipaddr: ipv4 octet count should be 4");let v,b;for(v=0;v<g.length;v++)if(b=g[v],!(0<=b&&b<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=g}return p.prototype.SpecialRanges={unspecified:[[new p([0,0,0,0]),8]],broadcast:[[new p([255,255,255,255]),32]],multicast:[[new p([224,0,0,0]),4]],linkLocal:[[new p([169,254,0,0]),16]],loopback:[[new p([127,0,0,0]),8]],carrierGradeNat:[[new p([100,64,0,0]),10]],private:[[new p([10,0,0,0]),8],[new p([172,16,0,0]),12],[new p([192,168,0,0]),16]],reserved:[[new p([192,0,0,0]),24],[new p([192,0,2,0]),24],[new p([192,88,99,0]),24],[new p([198,18,0,0]),15],[new p([198,51,100,0]),24],[new p([203,0,113,0]),24],[new p([240,0,0,0]),4]],as112:[[new p([192,175,48,0]),24],[new p([192,31,196,0]),24]],amt:[[new p([192,52,193,0]),24]]},p.prototype.kind=function(){return"ipv4"},p.prototype.match=function(g,v){let b;if(v===void 0&&(b=g,g=b[0],v=b[1]),g.kind()!=="ipv4")throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return u(this.octets,g.octets,8,v)},p.prototype.prefixLengthFromSubnetMask=function(){let g=0,v=!1,b={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},C,D,_;for(C=3;C>=0;C-=1)if(D=this.octets[C],D in b){if(_=b[D],v&&_!==0)return null;_!==8&&(v=!0),g+=_}else return null;return 32-g},p.prototype.range=function(){return f.subnetMatch(this,this.SpecialRanges)},p.prototype.toByteArray=function(){return this.octets.slice(0)},p.prototype.toIPv4MappedAddress=function(){return f.IPv6.parse(`::ffff:${this.toString()}`)},p.prototype.toNormalizedString=function(){return this.toString()},p.prototype.toString=function(){return this.octets.join(".")},p})(),f.IPv4.broadcastAddressFromCIDR=function(p){try{let g=this.parseCIDR(p),v=g[0].toByteArray(),b=this.subnetMaskFromPrefixLength(g[1]).toByteArray(),C=[],D=0;for(;D<4;)C.push(parseInt(v[D],10)|parseInt(b[D],10)^255),D++;return new this(C)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},f.IPv4.isIPv4=function(p){return this.parser(p)!==null},f.IPv4.isValid=function(p){try{return new this(this.parser(p)),!0}catch{return!1}},f.IPv4.isValidCIDR=function(p){try{return this.parseCIDR(p),!0}catch{return!1}},f.IPv4.isValidFourPartDecimal=function(p){return!!(f.IPv4.isValid(p)&&p.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},f.IPv4.isValidCIDRFourPartDecimal=function(p){let g=p.match(/^(.+)\/(\d+)$/);return!f.IPv4.isValidCIDR(p)||!g?!1:f.IPv4.isValidFourPartDecimal(g[1])},f.IPv4.networkAddressFromCIDR=function(p){let g,v,b,C,D;try{for(g=this.parseCIDR(p),b=g[0].toByteArray(),D=this.subnetMaskFromPrefixLength(g[1]).toByteArray(),C=[],v=0;v<4;)C.push(parseInt(b[v],10)&parseInt(D[v],10)),v++;return new this(C)}catch{throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},f.IPv4.parse=function(p){let g=this.parser(p);if(g===null)throw new Error("ipaddr: string is not formatted like an IPv4 Address");return new this(g)},f.IPv4.parseCIDR=function(p){let g;if(g=p.match(/^(.+)\/(\d+)$/)){let v=parseInt(g[2]);if(v>=0&&v<=32){let b=[this.parse(g[1]),v];return Object.defineProperty(b,"toString",{value:function(){return this.join("/")}}),b}}throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},f.IPv4.parser=function(p){let g,v,b;if(g=p.match(r.fourOctet))return(function(){let C=g.slice(1,6),D=[];for(let _=0;_<C.length;_++)v=C[_],D.push(d(v));return D})();if(g=p.match(r.longValue)){if(b=d(g[1]),b>4294967295||b<0)throw new Error("ipaddr: address outside defined range");return(function(){let C=[],D;for(D=0;D<=24;D+=8)C.push(b>>D&255);return C})().reverse()}else return(g=p.match(r.twoOctet))?(function(){let C=g.slice(1,4),D=[];if(b=d(C[1]),b>16777215||b<0)throw new Error("ipaddr: address outside defined range");return D.push(d(C[0])),D.push(b>>16&255),D.push(b>>8&255),D.push(b&255),D})():(g=p.match(r.threeOctet))?(function(){let C=g.slice(1,5),D=[];if(b=d(C[2]),b>65535||b<0)throw new Error("ipaddr: address outside defined range");return D.push(d(C[0])),D.push(d(C[1])),D.push(b>>8&255),D.push(b&255),D})():null},f.IPv4.subnetMaskFromPrefixLength=function(p){if(p=parseInt(p),p<0||p>32)throw new Error("ipaddr: invalid IPv4 prefix length");let g=[0,0,0,0],v=0,b=Math.floor(p/8);for(;v<b;)g[v]=255,v++;return b<4&&(g[b]=Math.pow(2,p%8)-1<<8-p%8),new this(g)},f.IPv6=(function(){function p(g,v){let b,C;if(g.length===16)for(this.parts=[],b=0;b<=14;b+=2)this.parts.push(g[b]<<8|g[b+1]);else if(g.length===8)this.parts=g;else throw new Error("ipaddr: ipv6 part count should be 8 or 16");for(b=0;b<this.parts.length;b++)if(C=this.parts[b],!(0<=C&&C<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");v&&(this.zoneId=v)}return p.prototype.SpecialRanges={unspecified:[new p([0,0,0,0,0,0,0,0]),128],linkLocal:[new p([65152,0,0,0,0,0,0,0]),10],multicast:[new p([65280,0,0,0,0,0,0,0]),8],loopback:[new p([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new p([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new p([0,0,0,0,0,65535,0,0]),96],deprecatedSiteLocal:[new p([65216,0,0,0,0,0,0,0]),10],discard:[new p([256,0,0,0,0,0,0,0]),64],rfc6145:[new p([0,0,0,0,65535,0,0,0]),96],rfc6052:[[new p([100,65435,0,0,0,0,0,0]),96],[new p([100,65435,1,0,0,0,0,0]),48]],"6to4":[new p([8194,0,0,0,0,0,0,0]),16],teredo:[new p([8193,0,0,0,0,0,0,0]),32],benchmarking:[new p([8193,2,0,0,0,0,0,0]),48],amt:[new p([8193,3,0,0,0,0,0,0]),32],as112v6:[[new p([8193,4,274,0,0,0,0,0]),48],[new p([9760,79,32768,0,0,0,0,0]),48]],deprecatedOrchid:[new p([8193,16,0,0,0,0,0,0]),28],orchid2:[new p([8193,32,0,0,0,0,0,0]),28],droneRemoteIdProtocolEntityTags:[new p([8193,48,0,0,0,0,0,0]),28],segmentRouting:[new p([24320,0,0,0,0,0,0,0]),16],reserved:[[new p([8193,0,0,0,0,0,0,0]),23],[new p([8193,3512,0,0,0,0,0,0]),32],[new p([16383,0,0,0,0,0,0,0]),20]]},p.prototype.isIPv4MappedAddress=function(){return this.range()==="ipv4Mapped"},p.prototype.kind=function(){return"ipv6"},p.prototype.match=function(g,v){let b;if(v===void 0&&(b=g,g=b[0],v=b[1]),g.kind()!=="ipv6")throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return u(this.parts,g.parts,16,v)},p.prototype.prefixLengthFromSubnetMask=function(){let g=0,v=!1,b={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},C,D;for(let _=7;_>=0;_-=1)if(C=this.parts[_],C in b){if(D=b[C],v&&D!==0)return null;D!==16&&(v=!0),g+=D}else return null;return 128-g},p.prototype.range=function(){return f.subnetMatch(this,this.SpecialRanges)},p.prototype.toByteArray=function(){let g,v=[],b=this.parts;for(let C=0;C<b.length;C++)g=b[C],v.push(g>>8),v.push(g&255);return v},p.prototype.toFixedLengthString=function(){let g=(function(){let b=[];for(let C=0;C<this.parts.length;C++)b.push(l(this.parts[C].toString(16),4));return b}).call(this).join(":"),v="";return this.zoneId&&(v=`%${this.zoneId}`),g+v},p.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");let g=this.parts.slice(-2),v=g[0],b=g[1];return new f.IPv4([v>>8,v&255,b>>8,b&255])},p.prototype.toNormalizedString=function(){let g=(function(){let b=[];for(let C=0;C<this.parts.length;C++)b.push(this.parts[C].toString(16));return b}).call(this).join(":"),v="";return this.zoneId&&(v=`%${this.zoneId}`),g+v},p.prototype.toRFC5952String=function(){let g=/((^|:)(0(:|$)){2,})/g,v=this.toNormalizedString(),b=0,C=-1,D;for(;D=g.exec(v);)D[0].length>C&&(b=D.index,C=D[0].length);return C<0?v:`${v.substring(0,b)}::${v.substring(b+C)}`},p.prototype.toString=function(){return this.toRFC5952String()},p})(),f.IPv6.broadcastAddressFromCIDR=function(p){try{let g=this.parseCIDR(p),v=g[0].toByteArray(),b=this.subnetMaskFromPrefixLength(g[1]).toByteArray(),C=[],D=0;for(;D<16;)C.push(parseInt(v[D],10)|parseInt(b[D],10)^255),D++;return new this(C)}catch(g){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${g})`)}},f.IPv6.isIPv6=function(p){return this.parser(p)!==null},f.IPv6.isValid=function(p){if(typeof p=="string"&&p.indexOf(":")===-1)return!1;try{let g=this.parser(p);return new this(g.parts,g.zoneId),!0}catch{return!1}},f.IPv6.isValidCIDR=function(p){if(typeof p=="string"&&p.indexOf(":")===-1)return!1;try{return this.parseCIDR(p),!0}catch{return!1}},f.IPv6.networkAddressFromCIDR=function(p){let g,v,b,C,D;try{for(g=this.parseCIDR(p),b=g[0].toByteArray(),D=this.subnetMaskFromPrefixLength(g[1]).toByteArray(),C=[],v=0;v<16;)C.push(parseInt(b[v],10)&parseInt(D[v],10)),v++;return new this(C)}catch(_){throw new Error(`ipaddr: the address does not have IPv6 CIDR format (${_})`)}},f.IPv6.parse=function(p){let g=this.parser(p);if(g.parts===null)throw new Error("ipaddr: string is not formatted like an IPv6 Address");return new this(g.parts,g.zoneId)},f.IPv6.parseCIDR=function(p){let g,v,b;if((v=p.match(/^(.+)\/(\d+)$/))&&(g=parseInt(v[2]),g>=0&&g<=128))return b=[this.parse(v[1]),g],Object.defineProperty(b,"toString",{value:function(){return this.join("/")}}),b;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},f.IPv6.parser=function(p){let g,v,b,C,D,_;if(b=p.match(a.deprecatedTransitional))return this.parser(`::ffff:${b[1]}`);if(a.native.test(p))return c(p,8);if((b=p.match(a.transitional))&&(_=b[6]||"",g=b[1],b[1].endsWith("::")||(g=g.slice(0,-1)),g=c(g+_,6),g.parts)){for(D=[parseInt(b[2]),parseInt(b[3]),parseInt(b[4]),parseInt(b[5])],v=0;v<D.length;v++)if(C=D[v],!(0<=C&&C<=255))return null;return g.parts.push(D[0]<<8|D[1]),g.parts.push(D[2]<<8|D[3]),{parts:g.parts,zoneId:g.zoneId}}return null},f.IPv6.subnetMaskFromPrefixLength=function(p){if(p=parseInt(p),p<0||p>128)throw new Error("ipaddr: invalid IPv6 prefix length");let g=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],v=0,b=Math.floor(p/8);for(;v<b;)g[v]=255,v++;return b<16&&(g[b]=Math.pow(2,p%8)-1<<8-p%8),new this(g)},f.fromByteArray=function(p){let g=p.length;if(g===4)return new f.IPv4(p);if(g===16)return new f.IPv6(p);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},f.isValid=function(p){return f.IPv6.isValid(p)||f.IPv4.isValid(p)},f.isValidCIDR=function(p){return f.IPv6.isValidCIDR(p)||f.IPv4.isValidCIDR(p)},f.parse=function(p){if(f.IPv6.isValid(p))return f.IPv6.parse(p);if(f.IPv4.isValid(p))return f.IPv4.parse(p);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},f.parseCIDR=function(p){try{return f.IPv6.parseCIDR(p)}catch{try{return f.IPv4.parseCIDR(p)}catch{throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},f.process=function(p){let g=this.parse(p);return g.kind()==="ipv6"&&g.isIPv4MappedAddress()?g.toIPv4Address():g},f.subnetMatch=function(p,g,v){let b,C,D,_;v==null&&(v="unicast");for(C in g)if(Object.prototype.hasOwnProperty.call(g,C)){for(D=g[C],D[0]&&!(D[0]instanceof Array)&&(D=[D]),b=0;b<D.length;b++)if(_=D[b],p.kind()===_[0].kind()&&p.match.apply(p,_))return C}return v},typeof vk<"u"&&vk.exports?vk.exports=f:t.ipaddr=f})(HG)});var qB=ce((tKe,FG)=>{"use strict";var xk=UG();function $G(t){if(typeof t!="string"||t.length===0||t.length>128)throw new TypeError("IP address must be a bounded string.");if(t.includes(".")){let e=t.slice(t.lastIndexOf(":")+1);if(!xk.IPv4.isValidFourPartDecimal(e))throw new TypeError("IPv4 text must use strict four-part decimal notation.")}return xk.parse(t)}function OIe(t){try{let e=$G(t);return e.kind()==="ipv6"&&e.isIPv4MappedAddress()?e.toIPv4Address().range()==="loopback":e.range()==="loopback"}catch{return!1}}function MIe(t){return typeof t=="string"&&xk.IPv4.isValidFourPartDecimal(t)}function LIe(t,e,r=0){let n=Uint8Array.from($G(t).toByteArray());if(e===void 0)return Buffer.from(n);if(!(e instanceof Uint8Array)||!Number.isSafeInteger(r)||r<0||r+n.byteLength>e.byteLength)throw new RangeError("IP buffer target is too small or has an invalid offset.");return e.set(n,r),e}function HIe(t,e=0,r){if(!(t instanceof Uint8Array)||!Number.isSafeInteger(e)||e<0)throw new TypeError("IP bytes and offset are invalid.");let n=t.byteLength-e,i=r===void 0?n:r;if(!Number.isSafeInteger(i)||i!==4&&i!==16||i>n)throw new RangeError("IP byte length must be exactly 4 or 16.");return xk.fromByteArray([...t.subarray(e,e+i)]).toString()}FG.exports=Object.freeze({isLoopback:OIe,isV4Format:MIe,toBuffer:LIe,toString:HIe})});var qG=ce((rKe,jG)=>{"use strict";jG.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,i,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!t(e[i],r[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;i--!==0;){var s=o[i];if(!t(e[s],r[s]))return!1}return!0}return e!==e&&r!==r}});var WG=ce(WB=>{"use strict";WB.toString=function(t){switch(t){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+t};WB.toType=function(t){switch(t.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return t.toUpperCase().startsWith("UNKNOWN_")?parseInt(t.slice(8)):0}});var VG=ce(VB=>{"use strict";VB.toString=function(t){switch(t){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+t};VB.toRcode=function(t){switch(t.toUpperCase()){case"NOERROR":return 0;case"FORMERR":return 1;case"SERVFAIL":return 2;case"NXDOMAIN":return 3;case"NOTIMP":return 4;case"REFUSED":return 5;case"YXDOMAIN":return 6;case"YXRRSET":return 7;case"NXRRSET":return 8;case"NOTAUTH":return 9;case"NOTZONE":return 10;case"RCODE_11":return 11;case"RCODE_12":return 12;case"RCODE_13":return 13;case"RCODE_14":return 14;case"RCODE_15":return 15}return 0}});var GG=ce(GB=>{"use strict";GB.toString=function(t){switch(t){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+t};GB.toOpcode=function(t){switch(t.toUpperCase()){case"QUERY":return 0;case"IQUERY":return 1;case"STATUS":return 2;case"OPCODE_3":return 3;case"NOTIFY":return 4;case"UPDATE":return 5;case"OPCODE_6":return 6;case"OPCODE_7":return 7;case"OPCODE_8":return 8;case"OPCODE_9":return 9;case"OPCODE_10":return 10;case"OPCODE_11":return 11;case"OPCODE_12":return 12;case"OPCODE_13":return 13;case"OPCODE_14":return 14;case"OPCODE_15":return 15}return 0}});var zG=ce(zB=>{"use strict";zB.toString=function(t){switch(t){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+t};zB.toClass=function(t){switch(t.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}});var KG=ce(KB=>{"use strict";KB.toString=function(t){switch(t){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return t<0?null:`OPTION_${t}`};KB.toCode=function(t){if(typeof t=="number")return t;if(!t)return-1;switch(t.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=t.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}});var JG={};wi(JG,{decode:()=>WIe,encode:()=>qIe,familyOf:()=>jIe,name:()=>FIe,sizeOf:()=>JB,v4:()=>Ac,v6:()=>xf});function JB(t){if(Ac.isFormat(t))return Ac.size;if(xf.isFormat(t))return xf.size;throw Error(`Invalid ip address: ${t}`)}function jIe(t){return JB(t)===Ac.size?1:2}function qIe(t,e,r){r=~~r;let n=JB(t);return typeof e=="function"&&(e=e(r+n)),n===Ac.size?Ac.encode(t,e,r):xf.encode(t,e,r)}function WIe(t,e,r){if(e=~~e,r=r||t.length-e,r===Ac.size)return Ac.decode(t,e,r);if(r===xf.size)return xf.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${Ac.size} for v4 or ${xf.size} for v6.`)}var UIe,$Ie,Ac,xf,FIe,XG=N(()=>{UIe=/^(\d{1,3}\.){3,3}\d{1,3}$/,$Ie=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i,Ac={name:"v4",size:4,isFormat:t=>UIe.test(t),encode(t,e,r){r=~~r,e=e||new Uint8Array(r+4);let n=t.length,i=0;for(let o=0;o<n;){let s=t.charCodeAt(o++);s===46?(e[r++]=i,i=0):i=i*10+(s-48)}return e[r]=i,e},decode(t,e){return e=~~e,`${t[e++]}.${t[e++]}.${t[e++]}.${t[e]}`}},xf={name:"v6",size:16,isFormat:t=>t.length>0&&$Ie.test(t),encode(t,e,r){r=~~r;let n=r+16,i=-1,o=0,s=0,a=!0,c=!1;e=e||new Uint8Array(r+16);for(let u=0;u<t.length;u++){let d=t.charCodeAt(u);d===58?(a?i!==-1?(r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2):r<n&&(i=r):(c===!0?(r<n&&(e[r]=s),r++):(r<n&&(e[r]=o>>8),r<n-1&&(e[r+1]=o&255),r+=2),o=0,s=0),a=!0,c=!1):d===46?(r<n&&(e[r]=s),r++,s=0,o=0,a=!1,c=!0):(a=!1,d>=97?d-=87:d>=65?d-=55:(d-=48,s=s*10+d),o=(o<<4)+d)}if(a===!1)c===!0?(r<n&&(e[r]=s),r++):(r<n&&(e[r]=o>>8),r<n-1&&(e[r+1]=o&255),r+=2);else if(i===0)r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2;else if(i!==-1){r+=2;for(let u=Math.min(r-1,n-1);u>=i+2;u--)e[u]=e[u-2];e[i]=0,e[i+1]=0,i=r}if(i!==r&&i!==-1)for(r>n-2&&(r=n-2);n>i;)e[--n]=r<n&&r>i?e[--r]:0;else for(;r<n;)e[r++]=0;return e},decode(t,e){e=~~e;let r="";for(let n=0;n<16;n+=2)n!==0&&(r+=":"),r+=(t[e+n]<<8|t[e+n+1]).toString(16);return r.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}},FIe="ip"});var ZG=ce(it=>{"use strict";var ot=Nt("node:buffer").Buffer,Lc=WG(),VIe=VG(),GIe=GG(),bk=zG(),XB=KG(),Sf=(XG(),Vi(JG)),zIe=0,YG=32768,YB=32768,KIe=~YB,QG=32768,JIe=~QG,Le=it.name={};Le.encode=function(t,e,r,{mail:n=!1}={}){e||(e=ot.alloc(Le.encodingLength(t))),r||(r=0);let i=r,o=t.replace(/^\.|\.$/gm,"");if(o.length){let s=[];if(n){let a="";o.split(".").forEach(c=>{c.endsWith("\\")?a+=(a.length?".":"")+c.slice(0,-1):s.length===0&&a.length?s.push(a+"."+c):s.push(c)})}else s=o.split(".");for(let a=0;a<s.length;a++){let c=e.write(s[a],r+1);e[r]=c,r+=c+1}}return e[r++]=0,Le.encode.bytes=r-i,e};Le.encode.bytes=0;Le.decode=function(t,e,{mail:r=!1}={}){e||(e=0);let n=[],i=e,o=0,s=0,a=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let c=t[e++];if(s+=a?0:1,c===0)break;if((c&192)===0){if(e+c>t.length)throw new Error("Cannot decode name (buffer overflow)");if(o+=c+1,o>254)throw new Error("Cannot decode name (name too long)");let u=t.toString("utf-8",e,e+c);r&&(u=u.replace(/\./g,"\\.")),n.push(u),e+=c,s+=a?0:c}else if((c&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let u=t.readUInt16BE(e-1)-49152;if(u>=i)throw new Error("Cannot decode name (bad pointer)");e=u,i=u,s+=a?0:1,a=!0}else throw new Error("Cannot decode name (bad label)")}return Le.decode.bytes=s,n.length===0?".":n.join(".")};Le.decode.bytes=0;Le.encodingLength=function(t){return t==="."||t===".."?1:ot.byteLength(t.replace(/^\.|\.$/gm,""))+2};var Lt={};Lt.encode=function(t,e,r){e||(e=ot.alloc(Lt.encodingLength(t))),r||(r=0);let n=e.write(t,r+1);return e[r]=n,Lt.encode.bytes=n+1,e};Lt.encode.bytes=0;Lt.decode=function(t,e){e||(e=0);let r=t[e],n=t.toString("utf-8",e+1,e+1+r);return Lt.decode.bytes=r+1,n};Lt.decode.bytes=0;Lt.encodingLength=function(t){return ot.byteLength(t)+1};var xs={};xs.encode=function(t,e,r){e||(e=xs.encodingLength(t)),r||(r=0);let n=(t.flags||0)&32767,i=t.type==="response"?YG:zIe;return e.writeUInt16BE(t.id||0,r),e.writeUInt16BE(n|i,r+2),e.writeUInt16BE(t.questions.length,r+4),e.writeUInt16BE(t.answers.length,r+6),e.writeUInt16BE(t.authorities.length,r+8),e.writeUInt16BE(t.additionals.length,r+10),e};xs.encode.bytes=12;xs.decode=function(t,e){if(e||(e=0),t.length<12)throw new Error("Header must be 12 bytes");let r=t.readUInt16BE(e+2);return{id:t.readUInt16BE(e),type:r&YG?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:GIe.toString(r>>11&15),flag_aa:(r>>10&1)===1,flag_tc:(r>>9&1)===1,flag_rd:(r>>8&1)===1,flag_ra:(r>>7&1)===1,flag_z:(r>>6&1)===1,flag_ad:(r>>5&1)===1,flag_cd:(r>>4&1)===1,rcode:VIe.toString(r&15),questions:new Array(t.readUInt16BE(e+4)),answers:new Array(t.readUInt16BE(e+6)),authorities:new Array(t.readUInt16BE(e+8)),additionals:new Array(t.readUInt16BE(e+10))}};xs.decode.bytes=12;xs.encodingLength=function(){return 12};var Cc=it.unknown={};Cc.encode=function(t,e,r){return e||(e=ot.alloc(Cc.encodingLength(t))),r||(r=0),e.writeUInt16BE(t.length,r),t.copy(e,r+2),Cc.encode.bytes=t.length+2,e};Cc.encode.bytes=0;Cc.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),n=t.slice(e+2,e+2+r);return Cc.decode.bytes=r+2,n};Cc.decode.bytes=0;Cc.encodingLength=function(t){return t.length+2};var Pc=it.ns={};Pc.encode=function(t,e,r){return e||(e=ot.alloc(Pc.encodingLength(t))),r||(r=0),Le.encode(t,e,r+2),e.writeUInt16BE(Le.encode.bytes,r),Pc.encode.bytes=Le.encode.bytes+2,e};Pc.encode.bytes=0;Pc.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),n=Le.decode(t,e+2);return Pc.decode.bytes=r+2,n};Pc.decode.bytes=0;Pc.encodingLength=function(t){return Le.encodingLength(t)+2};var _c=it.soa={};_c.encode=function(t,e,r){e||(e=ot.alloc(_c.encodingLength(t))),r||(r=0);let n=r;return r+=2,Le.encode(t.mname,e,r),r+=Le.encode.bytes,Le.encode(t.rname,e,r,{mail:!0}),r+=Le.encode.bytes,e.writeUInt32BE(t.serial||0,r),r+=4,e.writeUInt32BE(t.refresh||0,r),r+=4,e.writeUInt32BE(t.retry||0,r),r+=4,e.writeUInt32BE(t.expire||0,r),r+=4,e.writeUInt32BE(t.minimum||0,r),r+=4,e.writeUInt16BE(r-n-2,n),_c.encode.bytes=r-n,e};_c.encode.bytes=0;_c.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=Le.decode(t,e),e+=Le.decode.bytes,n.rname=Le.decode(t,e,{mail:!0}),e+=Le.decode.bytes,n.serial=t.readUInt32BE(e),e+=4,n.refresh=t.readUInt32BE(e),e+=4,n.retry=t.readUInt32BE(e),e+=4,n.expire=t.readUInt32BE(e),e+=4,n.minimum=t.readUInt32BE(e),e+=4,_c.decode.bytes=e-r,n};_c.decode.bytes=0;_c.encodingLength=function(t){return 22+Le.encodingLength(t.mname)+Le.encodingLength(t.rname)};var Tc=it.txt={};Tc.encode=function(t,e,r){Array.isArray(t)||(t=[t]);for(let i=0;i<t.length;i++)if(typeof t[i]=="string"&&(t[i]=ot.from(t[i])),!ot.isBuffer(t[i]))throw new Error("Must be a Buffer");e||(e=ot.alloc(Tc.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(i){e[r++]=i.length,i.copy(e,r,0,i.length),r+=i.length}),e.writeUInt16BE(r-n-2,n),Tc.encode.bytes=r-n,e};Tc.encode.bytes=0;Tc.decode=function(t,e){e||(e=0);let r=e,n=t.readUInt16BE(e);e+=2;let i=[];for(;n>0;){let o=t[e++];if(--n,n<o)throw new Error("Buffer overflow");i.push(t.slice(e,e+o)),e+=o,n-=o}return Tc.decode.bytes=e-r,i};Tc.decode.bytes=0;Tc.encodingLength=function(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=ot.byteLength(r)+1:e+=r.length+1}),e};var Dc=it.null={};Dc.encode=function(t,e,r){e||(e=ot.alloc(Dc.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=ot.from(t)),t||(t=ot.alloc(0));let n=r;r+=2;let i=t.length;return t.copy(e,r,0,i),r+=i,e.writeUInt16BE(r-n-2,n),Dc.encode.bytes=r-n,e};Dc.encode.bytes=0;Dc.decode=function(t,e){e||(e=0);let r=e,n=t.readUInt16BE(e);e+=2;let i=t.slice(e,e+n);return e+=n,Dc.decode.bytes=e-r,i};Dc.decode.bytes=0;Dc.encodingLength=function(t){return t?(ot.isBuffer(t)?t.length:ot.byteLength(t))+2:2};var Bc=it.hinfo={};Bc.encode=function(t,e,r){e||(e=ot.alloc(Bc.encodingLength(t))),r||(r=0);let n=r;return r+=2,Lt.encode(t.cpu,e,r),r+=Lt.encode.bytes,Lt.encode(t.os,e,r),r+=Lt.encode.bytes,e.writeUInt16BE(r-n-2,n),Bc.encode.bytes=r-n,e};Bc.encode.bytes=0;Bc.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=Lt.decode(t,e),e+=Lt.decode.bytes,n.os=Lt.decode(t,e),e+=Lt.decode.bytes,Bc.decode.bytes=e-r,n};Bc.decode.bytes=0;Bc.encodingLength=function(t){return Lt.encodingLength(t.cpu)+Lt.encodingLength(t.os)+2};var ys=it.ptr={},XIe=it.cname=ys,YIe=it.dname=ys;ys.encode=function(t,e,r){return e||(e=ot.alloc(ys.encodingLength(t))),r||(r=0),Le.encode(t,e,r+2),e.writeUInt16BE(Le.encode.bytes,r),ys.encode.bytes=Le.encode.bytes+2,e};ys.encode.bytes=0;ys.decode=function(t,e){e||(e=0);let r=Le.decode(t,e+2);return ys.decode.bytes=Le.decode.bytes+2,r};ys.decode.bytes=0;ys.encodingLength=function(t){return Le.encodingLength(t)+2};var Nc=it.srv={};Nc.encode=function(t,e,r){e||(e=ot.alloc(Nc.encodingLength(t))),r||(r=0),e.writeUInt16BE(t.priority||0,r+2),e.writeUInt16BE(t.weight||0,r+4),e.writeUInt16BE(t.port||0,r+6),Le.encode(t.target,e,r+8);let n=Le.encode.bytes+6;return e.writeUInt16BE(n,r),Nc.encode.bytes=n+2,e};Nc.encode.bytes=0;Nc.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e),n={};return n.priority=t.readUInt16BE(e+2),n.weight=t.readUInt16BE(e+4),n.port=t.readUInt16BE(e+6),n.target=Le.decode(t,e+8),Nc.decode.bytes=r+2,n};Nc.decode.bytes=0;Nc.encodingLength=function(t){return 8+Le.encodingLength(t.target)};var so=it.caa={};so.ISSUER_CRITICAL=128;so.encode=function(t,e,r){let n=so.encodingLength(t);return e||(e=ot.alloc(so.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=so.ISSUER_CRITICAL),e.writeUInt16BE(n-2,r),r+=2,e.writeUInt8(t.flags||0,r),r+=1,Lt.encode(t.tag,e,r),r+=Lt.encode.bytes,e.write(t.value,r),r+=ot.byteLength(t.value),so.encode.bytes=n,e};so.encode.bytes=0;so.decode=function(t,e){e||(e=0);let r=t.readUInt16BE(e);e+=2;let n=e,i={};return i.flags=t.readUInt8(e),e+=1,i.tag=Lt.decode(t,e),e+=Lt.decode.bytes,i.value=t.toString("utf-8",e,n+r),i.issuerCritical=!!(i.flags&so.ISSUER_CRITICAL),so.decode.bytes=r+2,i};so.decode.bytes=0;so.encodingLength=function(t){return Lt.encodingLength(t.tag)+Lt.encodingLength(t.value)+2};var bd=it.mx={};bd.encode=function(t,e,r){e||(e=ot.alloc(bd.encodingLength(t))),r||(r=0);let n=r;return r+=2,e.writeUInt16BE(t.preference||0,r),r+=2,Le.encode(t.exchange,e,r),r+=Le.encode.bytes,e.writeUInt16BE(r-n-2,n),bd.encode.bytes=r-n,e};bd.encode.bytes=0;bd.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=t.readUInt16BE(e),e+=2,n.exchange=Le.decode(t,e),e+=Le.decode.bytes,bd.decode.bytes=e-r,n};bd.encodingLength=function(t){return 4+Le.encodingLength(t.exchange)};var Oc=it.a={};Oc.encode=function(t,e,r){return e||(e=ot.alloc(Oc.encodingLength(t))),r||(r=0),e.writeUInt16BE(4,r),r+=2,Sf.v4.encode(t,e,r),Oc.encode.bytes=6,e};Oc.encode.bytes=0;Oc.decode=function(t,e){e||(e=0),e+=2;let r=Sf.v4.decode(t,e);return Oc.decode.bytes=6,r};Oc.decode.bytes=0;Oc.encodingLength=function(){return 6};var Mc=it.aaaa={};Mc.encode=function(t,e,r){return e||(e=ot.alloc(Mc.encodingLength(t))),r||(r=0),e.writeUInt16BE(16,r),r+=2,Sf.v6.encode(t,e,r),Mc.encode.bytes=18,e};Mc.encode.bytes=0;Mc.decode=function(t,e){e||(e=0),e+=2;let r=Sf.v6.decode(t,e);return Mc.decode.bytes=18,r};Mc.decode.bytes=0;Mc.encodingLength=function(){return 18};var Fi=it.option={};Fi.encode=function(t,e,r){e||(e=ot.alloc(Fi.encodingLength(t))),r||(r=0);let n=r,i=XB.toCode(t.code);if(e.writeUInt16BE(i,r),r+=2,t.data)e.writeUInt16BE(t.data.length,r),r+=2,t.data.copy(e,r),r+=t.data.length;else switch(i){case 8:let o=t.sourcePrefixLength||0,s=t.family||Sf.familyOf(t.ip),a=Sf.encode(t.ip,ot.alloc),c=Math.ceil(o/8);e.writeUInt16BE(c+4,r),r+=2,e.writeUInt16BE(s,r),r+=2,e.writeUInt8(o,r++),e.writeUInt8(t.scopePrefixLength||0,r++),a.copy(e,r,0,c),r+=c;break;case 11:t.timeout?(e.writeUInt16BE(2,r),r+=2,e.writeUInt16BE(t.timeout,r),r+=2):(e.writeUInt16BE(0,r),r+=2);break;case 12:let u=t.length||0;e.writeUInt16BE(u,r),r+=2,e.fill(0,r,r+u),r+=u;break;case 14:let d=t.tags.length*2;e.writeUInt16BE(d,r),r+=2;for(let l of t.tags)e.writeUInt16BE(l,r),r+=2;break;default:throw new Error(`Unknown roption code: ${t.code}`)}return Fi.encode.bytes=r-n,e};Fi.encode.bytes=0;Fi.decode=function(t,e){e||(e=0);let r={};r.code=t.readUInt16BE(e),r.type=XB.toString(r.code),e+=2;let n=t.readUInt16BE(e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=t.readUInt16BE(e),e+=2,r.sourcePrefixLength=t.readUInt8(e++),r.scopePrefixLength=t.readUInt8(e++);let i=ot.alloc(r.family===1?4:16);t.copy(i,0,e,e+n-4),r.ip=Sf.decode(i);break;case 11:n>0&&(r.timeout=t.readUInt16BE(e),e+=2);break;case 14:r.tags=[];for(let o=0;o<n;o+=2)r.tags.push(t.readUInt16BE(e)),e+=2}return Fi.decode.bytes=n+4,r};Fi.decode.bytes=0;Fi.encodingLength=function(t){if(t.data)return t.data.length+4;switch(XB.toCode(t.code)){case 8:let r=t.sourcePrefixLength||0;return Math.ceil(r/8)+8;case 11:return typeof t.timeout=="number"?6:4;case 12:return t.length+4;case 14:return 4+t.tags.length*2}throw new Error(`Unknown roption code: ${t.code}`)};var co=it.opt={};co.encode=function(t,e,r){e||(e=ot.alloc(co.encodingLength(t))),r||(r=0);let n=r,i=ch(t,Fi);return e.writeUInt16BE(i,r),r=Xv(t,Fi,e,r+2),co.encode.bytes=r-n,e};co.encode.bytes=0;co.decode=function(t,e){e||(e=0);let r=e,n=[],i=t.readUInt16BE(e);e+=2;let o=0;for(;i>0;)n[o++]=Fi.decode(t,e),e+=Fi.decode.bytes,i-=Fi.decode.bytes;return co.decode.bytes=e-r,n};co.decode.bytes=0;co.encodingLength=function(t){return 2+ch(t||[],Fi)};var gi=it.dnskey={};gi.PROTOCOL_DNSSEC=3;gi.ZONE_KEY=128;gi.SECURE_ENTRYPOINT=32768;gi.encode=function(t,e,r){e||(e=ot.alloc(gi.encodingLength(t))),r||(r=0);let n=r,i=t.key;if(!ot.isBuffer(i))throw new Error("Key must be a Buffer");return r+=2,e.writeUInt16BE(t.flags,r),r+=2,e.writeUInt8(gi.PROTOCOL_DNSSEC,r),r+=1,e.writeUInt8(t.algorithm,r),r+=1,i.copy(e,r,0,i.length),r+=i.length,gi.encode.bytes=r-n,e.writeUInt16BE(gi.encode.bytes-2,n),e};gi.encode.bytes=0;gi.decode=function(t,e){e||(e=0);let r=e;var n={},i=t.readUInt16BE(e);if(e+=2,n.flags=t.readUInt16BE(e),e+=2,t.readUInt8(e)!==gi.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=t.readUInt8(e),e+=1,n.key=t.slice(e,r+i+2),e+=n.key.length,gi.decode.bytes=e-r,n};gi.decode.bytes=0;gi.encodingLength=function(t){return 6+ot.byteLength(t.key)};var fa=it.rrsig={};fa.encode=function(t,e,r){e||(e=ot.alloc(fa.encodingLength(t))),r||(r=0);let n=r,i=t.signature;if(!ot.isBuffer(i))throw new Error("Signature must be a Buffer");return r+=2,e.writeUInt16BE(Lc.toType(t.typeCovered),r),r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.labels,r),r+=1,e.writeUInt32BE(t.originalTTL,r),r+=4,e.writeUInt32BE(t.expiration,r),r+=4,e.writeUInt32BE(t.inception,r),r+=4,e.writeUInt16BE(t.keyTag,r),r+=2,Le.encode(t.signersName,e,r),r+=Le.encode.bytes,i.copy(e,r,0,i.length),r+=i.length,fa.encode.bytes=r-n,e.writeUInt16BE(fa.encode.bytes-2,n),e};fa.encode.bytes=0;fa.decode=function(t,e){e||(e=0);let r=e;var n={},i=t.readUInt16BE(e);return e+=2,n.typeCovered=Lc.toString(t.readUInt16BE(e)),e+=2,n.algorithm=t.readUInt8(e),e+=1,n.labels=t.readUInt8(e),e+=1,n.originalTTL=t.readUInt32BE(e),e+=4,n.expiration=t.readUInt32BE(e),e+=4,n.inception=t.readUInt32BE(e),e+=4,n.keyTag=t.readUInt16BE(e),e+=2,n.signersName=Le.decode(t,e),e+=Le.decode.bytes,n.signature=t.slice(e,r+i+2),e+=n.signature.length,fa.decode.bytes=e-r,n};fa.decode.bytes=0;fa.encodingLength=function(t){return 20+Le.encodingLength(t.signersName)+ot.byteLength(t.signature)};var pa=it.rp={};pa.encode=function(t,e,r){e||(e=ot.alloc(pa.encodingLength(t))),r||(r=0);let n=r;return r+=2,Le.encode(t.mbox||".",e,r,{mail:!0}),r+=Le.encode.bytes,Le.encode(t.txt||".",e,r),r+=Le.encode.bytes,pa.encode.bytes=r-n,e.writeUInt16BE(pa.encode.bytes-2,n),e};pa.encode.bytes=0;pa.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=Le.decode(t,e,{mail:!0})||".",e+=Le.decode.bytes,n.txt=Le.decode(t,e)||".",e+=Le.decode.bytes,pa.decode.bytes=e-r,n};pa.decode.bytes=0;pa.encodingLength=function(t){return 2+Le.encodingLength(t.mbox||".")+Le.encodingLength(t.txt||".")};var An={};An.encode=function(t,e,r){e||(e=ot.alloc(An.encodingLength(t))),r||(r=0);let n=r;for(var i=[],o=0;o<t.length;o++){var s=Lc.toType(t[o]);i[s>>8]===void 0&&(i[s>>8]=[]),i[s>>8][s>>3&31]|=1<<7-(s&7)}for(o=0;o<i.length;o++)if(i[o]!==void 0){var a=ot.from(i[o]);e.writeUInt8(o,r),r+=1,e.writeUInt8(a.length,r),r+=1,a.copy(e,r),r+=a.length}return An.encode.bytes=r-n,e};An.encode.bytes=0;An.decode=function(t,e,r){e||(e=0);let n=e;for(var i=[];e-n<r;){var o=t.readUInt8(e);e+=1;var s=t.readUInt8(e);e+=1;for(var a=0;a<s;a++)for(var c=t.readUInt8(e+a),u=0;u<8;u++)if(c&1<<7-u){var d=Lc.toString(o<<8|a<<3|u);i.push(d)}e+=s}return An.decode.bytes=e-n,i};An.decode.bytes=0;An.encodingLength=function(t){for(var e=[],r=0;r<t.length;r++){var n=Lc.toType(t[r]);e[n>>8]=Math.max(e[n>>8]||0,n&255)}var i=0;for(r=0;r<e.length;r++)e[r]!==void 0&&(i+=2+Math.ceil((e[r]+1)/8));return i};var ma=it.nsec={};ma.encode=function(t,e,r){e||(e=ot.alloc(ma.encodingLength(t))),r||(r=0);let n=r;return r+=2,Le.encode(t.nextDomain,e,r),r+=Le.encode.bytes,An.encode(t.rrtypes,e,r),r+=An.encode.bytes,ma.encode.bytes=r-n,e.writeUInt16BE(ma.encode.bytes-2,n),e};ma.encode.bytes=0;ma.decode=function(t,e){e||(e=0);let r=e;var n={},i=t.readUInt16BE(e);return e+=2,n.nextDomain=Le.decode(t,e),e+=Le.decode.bytes,n.rrtypes=An.decode(t,e,i-(e-r)),e+=An.decode.bytes,ma.decode.bytes=e-r,n};ma.decode.bytes=0;ma.encodingLength=function(t){return 2+Le.encodingLength(t.nextDomain)+An.encodingLength(t.rrtypes)};var ha=it.nsec3={};ha.encode=function(t,e,r){e||(e=ot.alloc(ha.encodingLength(t))),r||(r=0);let n=r,i=t.salt;if(!ot.isBuffer(i))throw new Error("salt must be a Buffer");let o=t.nextDomain;if(!ot.isBuffer(o))throw new Error("nextDomain must be a Buffer");return r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.flags,r),r+=1,e.writeUInt16BE(t.iterations,r),r+=2,e.writeUInt8(i.length,r),r+=1,i.copy(e,r,0,i.length),r+=i.length,e.writeUInt8(o.length,r),r+=1,o.copy(e,r,0,o.length),r+=o.length,An.encode(t.rrtypes,e,r),r+=An.encode.bytes,ha.encode.bytes=r-n,e.writeUInt16BE(ha.encode.bytes-2,n),e};ha.encode.bytes=0;ha.decode=function(t,e){e||(e=0);let r=e;var n={},i=t.readUInt16BE(e);e+=2,n.algorithm=t.readUInt8(e),e+=1,n.flags=t.readUInt8(e),e+=1,n.iterations=t.readUInt16BE(e),e+=2;let o=t.readUInt8(e);e+=1,n.salt=t.slice(e,e+o),e+=o;let s=t.readUInt8(e);return e+=1,n.nextDomain=t.slice(e,e+s),e+=s,n.rrtypes=An.decode(t,e,i-(e-r)),e+=An.decode.bytes,ha.decode.bytes=e-r,n};ha.decode.bytes=0;ha.encodingLength=function(t){return 8+t.salt.length+t.nextDomain.length+An.encodingLength(t.rrtypes)};var ga=it.ds={};ga.encode=function(t,e,r){e||(e=ot.alloc(ga.encodingLength(t))),r||(r=0);let n=r,i=t.digest;if(!ot.isBuffer(i))throw new Error("Digest must be a Buffer");return r+=2,e.writeUInt16BE(t.keyTag,r),r+=2,e.writeUInt8(t.algorithm,r),r+=1,e.writeUInt8(t.digestType,r),r+=1,i.copy(e,r,0,i.length),r+=i.length,ga.encode.bytes=r-n,e.writeUInt16BE(ga.encode.bytes-2,n),e};ga.encode.bytes=0;ga.decode=function(t,e){e||(e=0);let r=e;var n={},i=t.readUInt16BE(e);return e+=2,n.keyTag=t.readUInt16BE(e),e+=2,n.algorithm=t.readUInt8(e),e+=1,n.digestType=t.readUInt8(e),e+=1,n.digest=t.slice(e,r+i+2),e+=n.digest.length,ga.decode.bytes=e-r,n};ga.decode.bytes=0;ga.encodingLength=function(t){return 6+ot.byteLength(t.digest)};var ao=it.sshfp={};ao.getFingerprintLengthForHashType=function(e){switch(e){case 1:return 20;case 2:return 32}};ao.encode=function(e,r,n){r||(r=ot.alloc(ao.encodingLength(e))),n||(n=0);let i=n;n+=2,r[n]=e.algorithm,n+=1,r[n]=e.hash,n+=1;let o=ot.from(e.fingerprint.toUpperCase(),"hex");if(o.length!==ao.getFingerprintLengthForHashType(e.hash))throw new Error("Invalid fingerprint length");return o.copy(r,n),n+=o.byteLength,ao.encode.bytes=n-i,r.writeUInt16BE(ao.encode.bytes-2,i),r};ao.encode.bytes=0;ao.decode=function(e,r){r||(r=0);let n=r,i={};r+=2,i.algorithm=e[r],r+=1,i.hash=e[r],r+=1;let o=ao.getFingerprintLengthForHashType(i.hash);return i.fingerprint=e.slice(r,r+o).toString("hex").toUpperCase(),r+=o,ao.decode.bytes=r-n,i};ao.decode.bytes=0;ao.encodingLength=function(t){return 4+ot.from(t.fingerprint,"hex").byteLength};var ya=it.naptr={};ya.encode=function(t,e,r){e||(e=ot.alloc(ya.encodingLength(t))),r||(r=0);let n=r;return r+=2,e.writeUInt16BE(t.order||0,r),r+=2,e.writeUInt16BE(t.preference||0,r),r+=2,Lt.encode(t.flags,e,r),r+=Lt.encode.bytes,Lt.encode(t.services,e,r),r+=Lt.encode.bytes,Lt.encode(t.regexp,e,r),r+=Lt.encode.bytes,Le.encode(t.replacement,e,r),r+=Le.encode.bytes,ya.encode.bytes=r-n,e.writeUInt16BE(ya.encode.bytes-2,n),e};ya.encode.bytes=0;ya.decode=function(t,e){e||(e=0);let r=e,n={};return e+=2,n.order=t.readUInt16BE(e),e+=2,n.preference=t.readUInt16BE(e),e+=2,n.flags=Lt.decode(t,e),e+=Lt.decode.bytes,n.services=Lt.decode(t,e),e+=Lt.decode.bytes,n.regexp=Lt.decode(t,e),e+=Lt.decode.bytes,n.replacement=Le.decode(t,e),e+=Le.decode.bytes,ya.decode.bytes=e-r,n};ya.decode.bytes=0;ya.encodingLength=function(t){return Lt.encodingLength(t.flags)+Lt.encodingLength(t.services)+Lt.encodingLength(t.regexp)+Le.encodingLength(t.replacement)+6};var va=it.tlsa={};va.encode=function(t,e,r){e||(e=ot.alloc(va.encodingLength(t))),r||(r=0);let n=r,i=t.certificate;if(!ot.isBuffer(i))throw new Error("Certificate must be a Buffer");return r+=2,e.writeUInt8(t.usage,r),r+=1,e.writeUInt8(t.selector,r),r+=1,e.writeUInt8(t.matchingType,r),r+=1,i.copy(e,r,0,i.length),r+=i.length,va.encode.bytes=r-n,e.writeUInt16BE(va.encode.bytes-2,n),e};va.encode.bytes=0;va.decode=function(t,e){e||(e=0);let r=e,n={},i=t.readUInt16BE(e);return e+=2,n.usage=t.readUInt8(e),e+=1,n.selector=t.readUInt8(e),e+=1,n.matchingType=t.readUInt8(e),e+=1,n.certificate=t.slice(e,r+i+2),e+=n.certificate.length,va.decode.bytes=e-r,n};va.decode.bytes=0;va.encodingLength=function(t){return 5+ot.byteLength(t.certificate)};var QB=it.record=function(t){switch(t.toUpperCase()){case"A":return Oc;case"PTR":return ys;case"CNAME":return XIe;case"DNAME":return YIe;case"TXT":return Tc;case"NULL":return Dc;case"AAAA":return Mc;case"SRV":return Nc;case"HINFO":return Bc;case"CAA":return so;case"NS":return Pc;case"SOA":return _c;case"MX":return bd;case"OPT":return co;case"DNSKEY":return gi;case"RRSIG":return fa;case"RP":return pa;case"NSEC":return ma;case"NSEC3":return ha;case"SSHFP":return ao;case"DS":return ga;case"NAPTR":return ya;case"TLSA":return va}return Cc},Hn=it.answer={};Hn.encode=function(t,e,r){e||(e=ot.alloc(Hn.encodingLength(t))),r||(r=0);let n=r;if(Le.encode(t.name,e,r),r+=Le.encode.bytes,e.writeUInt16BE(Lc.toType(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");e.writeUInt16BE(t.udpPayloadSize||4096,r+2),e.writeUInt8(t.extendedRcode||0,r+4),e.writeUInt8(t.ednsVersion||0,r+5),e.writeUInt16BE(t.flags||0,r+6),r+=8,co.encode(t.options||[],e,r),r+=co.encode.bytes}else{let i=bk.toClass(t.class===void 0?"IN":t.class);t.flush&&(i|=YB),e.writeUInt16BE(i,r+2),e.writeUInt32BE(t.ttl||0,r+4),r+=8;let o=QB(t.type);o.encode(t.data,e,r),r+=o.encode.bytes}return Hn.encode.bytes=r-n,e};Hn.encode.bytes=0;Hn.decode=function(t,e){e||(e=0);let r={},n=e;if(r.name=Le.decode(t,e),e+=Le.decode.bytes,r.type=Lc.toString(t.readUInt16BE(e)),r.type==="OPT")r.udpPayloadSize=t.readUInt16BE(e+2),r.extendedRcode=t.readUInt8(e+4),r.ednsVersion=t.readUInt8(e+5),r.flags=t.readUInt16BE(e+6),r.flag_do=(r.flags>>15&1)===1,r.options=co.decode(t,e+8),e+=8+co.decode.bytes;else{let i=t.readUInt16BE(e+2);r.ttl=t.readUInt32BE(e+4),r.class=bk.toString(i&KIe),r.flush=!!(i&YB);let o=QB(r.type);r.data=o.decode(t,e+8),e+=8+o.decode.bytes}return Hn.decode.bytes=e-n,r};Hn.decode.bytes=0;Hn.encodingLength=function(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return Le.encodingLength(t.name)+8+QB(t.type).encodingLength(e)};var vs=it.question={};vs.encode=function(t,e,r){e||(e=ot.alloc(vs.encodingLength(t))),r||(r=0);let n=r;return Le.encode(t.name,e,r),r+=Le.encode.bytes,e.writeUInt16BE(Lc.toType(t.type),r),r+=2,e.writeUInt16BE(bk.toClass(t.class===void 0?"IN":t.class),r),r+=2,vs.encode.bytes=r-n,t};vs.encode.bytes=0;vs.decode=function(t,e){e||(e=0);let r=e,n={};return n.name=Le.decode(t,e),e+=Le.decode.bytes,n.type=Lc.toString(t.readUInt16BE(e)),e+=2,n.class=bk.toString(t.readUInt16BE(e)),e+=2,n.class&QG&&(n.class&=JIe),vs.decode.bytes=e-r,n};vs.decode.bytes=0;vs.encodingLength=function(t){return Le.encodingLength(t.name)+4};it.AUTHORITATIVE_ANSWER=1024;it.TRUNCATED_RESPONSE=512;it.RECURSION_DESIRED=256;it.RECURSION_AVAILABLE=128;it.AUTHENTIC_DATA=32;it.CHECKING_DISABLED=16;it.DNSSEC_OK=32768;it.encode=function(t,e,r){let n=!e;n&&(e=ot.alloc(it.encodingLength(t))),r||(r=0);let i=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),xs.encode(t,e,r),r+=xs.encode.bytes,r=Xv(t.questions,vs,e,r),r=Xv(t.answers,Hn,e,r),r=Xv(t.authorities,Hn,e,r),r=Xv(t.additionals,Hn,e,r),it.encode.bytes=r-i,n&&it.encode.bytes!==e.length?e.slice(0,it.encode.bytes):e};it.encode.bytes=0;it.decode=function(t,e){e||(e=0);let r=e,n=xs.decode(t,e);return e+=xs.decode.bytes,e=Sk(n.questions,vs,t,e),e=Sk(n.answers,Hn,t,e),e=Sk(n.authorities,Hn,t,e),e=Sk(n.additionals,Hn,t,e),it.decode.bytes=e-r,n};it.decode.bytes=0;it.encodingLength=function(t){return xs.encodingLength(t)+ch(t.questions||[],vs)+ch(t.answers||[],Hn)+ch(t.authorities||[],Hn)+ch(t.additionals||[],Hn)};it.streamEncode=function(t){let e=it.encode(t),r=ot.alloc(2);r.writeUInt16BE(e.byteLength);let n=ot.concat([r,e]);return it.streamEncode.bytes=n.byteLength,n};it.streamEncode.bytes=0;it.streamDecode=function(t){let e=t.readUInt16BE(0);if(t.byteLength<e+2)return null;let r=it.decode(t.slice(2));return it.streamDecode.bytes=it.decode.bytes,r};it.streamDecode.bytes=0;function ch(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function Xv(t,e,r,n){for(let i=0;i<t.length;i++)e.encode(t[i],r,n),n+=e.encode.bytes;return n}function Sk(t,e,r,n){for(let i=0;i<t.length;i++)t[i]=e.decode(r,n),n+=e.decode.bytes;return n}});var rz=ce((uKe,tz)=>{"use strict";var ez=nEe;process.nextTick(rEe,42);tz.exports=QIe;function QIe(t){var e=n;return r;function r(i){e(i||eEe)}function n(i){var o=[i];e=s,t(a);function s(c){o.push(c)}function a(c){var u=arguments;for(e=ZIe(c)?n:d;o.length;)d(o.shift());function d(l){ez(tEe,l,u)}}}}function ZIe(t){return Object.prototype.toString.call(t)==="[object Error]"}function eEe(){}function tEe(t,e){t.apply(null,e)}function rEe(t){t===42&&(ez=process.nextTick)}function nEe(t,e,r){process.nextTick(function(){t(e,r)})}});var oz=ce((dKe,iz)=>{var ZB=ZG(),iEe=Nt("node:dgram"),oEe=rz(),sEe=Nt("node:events"),tN=Nt("node:os"),eN=function(){};iz.exports=function(t){t||(t={});var e=new sEe.EventEmitter,r=typeof t.port=="number"?t.port:5353,n=t.type||"udp4",i=t.ip||t.host||(n==="udp4"?"224.0.0.251":null),o={address:i,port:r},s={},a=!1,c=null;if(n==="udp6"&&(!i||!t.interface))throw new Error("For IPv6 multicast you must specify `ip` and `interface`");var u=t.socket||iEe.createSocket({type:n,reuseAddr:t.reuseAddr!==!1,toString:function(){return n}});u.on("error",function(l){l.code==="EACCES"||l.code==="EADDRINUSE"?e.emit("error",l):e.emit("warning",l)}),u.on("message",function(l,f){try{l=ZB.decode(l)}catch(p){e.emit("warning",p);return}e.emit("packet",l,f),l.type==="query"&&e.emit("query",l,f),l.type==="response"&&e.emit("response",l,f)}),u.on("listening",function(){r||(r=o.port=u.address().port),t.multicast!==!1&&(e.update(),c=setInterval(e.update,5e3),u.setMulticastTTL(t.ttl||255),u.setMulticastLoopback(t.loopback!==!1))});var d=oEe(function(l){if(!r||t.bind===!1)return l(null);u.once("error",l),u.bind(r,t.bind||t.interface,function(){u.removeListener("error",l),l(null)})});return d(function(l){if(l)return e.emit("error",l);e.emit("ready")}),e.send=function(l,f,p){if(typeof f=="function")return e.send(l,null,f);p||(p=eN),f?!f.host&&!f.address&&(f.address=o.address):f=o,d(g);function g(v){if(a)return p();if(v)return p(v);var b=ZB.encode(l);u.send(b,0,b.length,f.port,f.address||f.host,p)}},e.response=e.respond=function(l,f,p){Array.isArray(l)&&(l={answers:l}),l.type="response",l.flags=(l.flags||0)|ZB.AUTHORITATIVE_ANSWER,e.send(l,f,p)},e.query=function(l,f,p,g){if(typeof f=="function")return e.query(l,null,null,f);if(typeof f=="object"&&f&&f.port)return e.query(l,null,f,p);if(typeof p=="function")return e.query(l,f,null,p);g||(g=eN),typeof l=="string"&&(l=[{name:l,type:f||"ANY"}]),Array.isArray(l)&&(l={type:"query",questions:l}),l.type="query",e.send(l,p,g)},e.destroy=function(l){if(l||(l=eN),a)return process.nextTick(l);a=!0,clearInterval(c);for(var f in s)try{u.dropMembership(i,f)}catch{}s={},u.close(l)},e.update=function(){for(var l=t.interface?[].concat(t.interface):cEe(),f=!1,p=0;p<l.length;p++){var g=l[p];if(!s[g])try{u.addMembership(i,g),s[g]=!0,f=!0}catch(v){e.emit("warning",v)}}if(f){if(u.setMulticastInterface)try{u.setMulticastInterface(t.interface||aEe())}catch(v){e.emit("warning",v)}e.emit("networkInterface")}},e};function aEe(){for(var t=tN.networkInterfaces(),e=Object.keys(t),r=0;r<e.length;r++)for(var n=t[e[r]],i=0;i<n.length;i++){var o=n[i];if(nz(o.family)&&!o.internal)return tN.platform()==="darwin"&&e[r]==="en0"?o.address:"0.0.0.0"}return"127.0.0.1"}function cEe(){for(var t=tN.networkInterfaces(),e=Object.keys(t),r=[],n=0;n<e.length;n++)for(var i=t[e[n]],o=0;o<i.length;o++){var s=i[o];if(nz(s.family)){r.push(s.address);break}}return r}function nz(t){return t===4||t==="IPv4"}});var YY={};wi(YY,{AV1Obu:()=>mJ,AV1RtpPayload:()=>RN,AttributeKeys:()=>Wke,BitStream:()=>Cd,BitWriter:()=>wx,BitWriter2:()=>nR,BufferChain:()=>fEe,CONSENT_FAILURES:()=>XN,CONSENT_INTERVAL:()=>LX,COOKIE:()=>fR,Candidate:()=>Td,CandidatePair:()=>KN,CandidatePairState:()=>HX,CipherContext:()=>Rx,CipherSuite:()=>Wk,CipherSuiteList:()=>HK,Connection:()=>GX,ConnectionStates:()=>q1e,CurveType:()=>k6,DEFAULT_MAX_MESSAGE_SIZE:()=>yh,DePacketizerBase:()=>mke,Directions:()=>Bk,DtlsClient:()=>jN,DtlsServer:()=>mX,DtlsSocket:()=>O6,DtlsStates:()=>e1e,Event:()=>qe,EventDisposer:()=>BK,ExtensionProfiles:()=>Rd,FINGERPRINT_LENGTH:()=>hX,FINGERPRINT_XOR:()=>gX,GenericNack:()=>Dx,GroupDescription:()=>bh,H264RtpPayload:()=>vJ,HEADER_LENGTH:()=>$c,HashAlgorithm:()=>kx,ICE_COMPLETED:()=>JN,ICE_FAILED:()=>gx,INTEGRITY_LENGTH:()=>M6,IPV4_PROTOCOL:()=>L6,IPV6_PROTOCOL:()=>H6,IceCandidate:()=>aO,IceGathererStates:()=>a1e,IceTransportStates:()=>s1e,Inactive:()=>iY,Int:()=>Px,MediaDescription:()=>tR,MediaStream:()=>sY,MediaStreamTrack:()=>Lx,MediaStreamTrackFactory:()=>qRe,Message:()=>Ho,NalUnitType:()=>kd,NamedCurveAlgorithm:()=>Wc,NamedCurveAlgorithmList:()=>E6,OpusRtpPayload:()=>SJ,PacketChunk:()=>DJ,PacketResult:()=>NJ,PacketStatus:()=>BJ,PictureLossIndication:()=>_x,Profiles:()=>cke,PromiseQueue:()=>SEe,ProtectionProfileAeadAes128Gcm:()=>Nf,ProtectionProfileAes128CmHmacSha1_80:()=>Ph,RETRY_MAX:()=>yX,RETRY_RTO:()=>vX,RTCCertificate:()=>sO,RTCDataChannel:()=>V6,RTCDataChannelParameters:()=>G6,RTCDtlsFingerprint:()=>Qk,RTCDtlsParameters:()=>Zk,RTCDtlsTransport:()=>t6,RTCIceCandidate:()=>yY,RTCIceGatherer:()=>hY,RTCIceParameters:()=>cO,RTCIceTransport:()=>mY,RTCP_HEADER_SIZE:()=>zk,RTCPeerConnection:()=>U1e,RTCRtcpFeedback:()=>JX,RTCRtcpParameters:()=>yRe,RTCRtpCodecParameters:()=>Dd,RTCRtpCodingParameters:()=>YX,RTCRtpHeaderExtensionParameters:()=>ka,RTCRtpReceiver:()=>pO,RTCRtpRtxParameters:()=>XX,RTCRtpSender:()=>zY,RTCRtpSimulcastParameters:()=>z6,RTCRtpTransceiver:()=>nY,RTCSctpCapabilities:()=>dO,RTCSctpTransport:()=>jY,RTCSessionDescription:()=>VY,RTCStatsReport:()=>rY,RTP_EXTENSION_URI:()=>Rr,ReceiverEstimatedMaxBitrate:()=>Tx,RecvDelta:()=>xx,Recvonly:()=>Z6,Red:()=>D6,RedEncoder:()=>eX,RedHandler:()=>tX,RedHeader:()=>HN,RtcpHeader:()=>zc,RtcpPacketConverter:()=>UJ,RtcpPayloadSpecificFeedback:()=>Ih,RtcpReceiverInfo:()=>lR,RtcpRrPacket:()=>Eh,RtcpSenderInfo:()=>T6,RtcpSourceDescriptionPacket:()=>Nx,RtcpSrPacket:()=>_f,RtcpTransportLayerFeedback:()=>Pf,RtpBuilder:()=>Bke,RtpHeader:()=>Vc,RtpPacket:()=>Gc,RtpRouter:()=>GY,RunLengthChunk:()=>Sh,SDPManager:()=>KY,Sendonly:()=>Q6,Sendrecv:()=>eO,SessionDescription:()=>bx,SignalingStates:()=>j1e,SignatureAlgorithm:()=>Ea,SignatureScheme:()=>vN,SourceDescriptionChunk:()=>P6,SourceDescriptionItem:()=>_6,SrtcpSession:()=>lX,SrtpAuthenticationError:()=>Tf,SrtpContext:()=>Ax,SrtpSession:()=>fX,SsrcDescription:()=>rR,StatusVectorChunk:()=>_J,StunOverTurnProtocol:()=>PX,StunProtocol:()=>Kk,TcpTransport:()=>MK,TransceiverManager:()=>XY,TransportWideCC:()=>Bx,TurnProtocol:()=>TX,UdpTransport:()=>qk,Vp8RtpPayload:()=>wJ,Vp9RtpPayload:()=>EJ,WeriftError:()=>wEe,addSDPHeader:()=>y6,andDirection:()=>nO,buffer2ArrayBuffer:()=>mEe,bufferArrayXor:()=>dEe,bufferReader:()=>vi,bufferWriter:()=>_r,bufferWriterLE:()=>bK,bufferXor:()=>uEe,candidateFoundation:()=>Jk,candidateFromIce:()=>Rh,candidateFromSdp:()=>fO,candidatePairPriority:()=>Xk,candidatePriority:()=>Sx,candidateToIce:()=>gY,candidateToSdp:()=>lO,certificateTypes:()=>UK,classes:()=>U6,codecParametersFromString:()=>$x,codecParametersToString:()=>_1e,compactNtp:()=>oO,crc32:()=>AK,crc32c:()=>w6,createBufferWriter:()=>vx,createSelfSignedCertificate:()=>jRe,createStunOverTurnClient:()=>GN,createTurnClient:()=>BX,dePacketizeRtpPackets:()=>hke,debug:()=>xt,deepMerge:()=>fY,defaultOptions:()=>UX,defaultPeerConfig:()=>$1e,depacketizerCodecs:()=>gke,deserializeAbsSendTime:()=>JJ,deserializeAudioLevelIndication:()=>XJ,deserializeString:()=>zJ,deserializeUint16BE:()=>KJ,deserializeVideoOrientation:()=>YJ,dumpBuffer:()=>pEe,enumerate:()=>yke,findCodecByMimeType:()=>x6,findPort:()=>TK,fingerprint:()=>tO,generateStatsId:()=>hr,getBit:()=>Ne,getDataChannelMessageSize:()=>zX,getGlobalIp:()=>lRe,getHostAddresses:()=>VX,getStatsTimestamp:()=>Bd,growBufferSize:()=>AN,int:()=>vh,interfaceAddress:()=>oR,isDtls:()=>aY,isLinkLocalAddress:()=>WX,isMedia:()=>RJ,isRtcp:()=>$J,keyLength:()=>dJ,leb128decode:()=>gJ,makeIntegrityKey:()=>NX,methods:()=>$6,microTime:()=>uY,milliTime:()=>iO,nodeIpAddress:()=>ZN,normalizeFamilyNodeV18:()=>Ex,normalizeFingerprintAlgorithm:()=>rO,normalizeFingerprintValue:()=>Yk,ntpTime:()=>dY,ntpTime2Sec:()=>HJ,paddingBits:()=>lEe,paddingByte:()=>Ix,paddingLength:()=>WN,parseGroup:()=>Fk,parseIceServers:()=>lY,parseMessage:()=>pR,random16:()=>b6,random32:()=>jk,randomPort:()=>I6,randomPorts:()=>bEe,reverseDirection:()=>cY,reverseSimulcastDirection:()=>$Re,rtpHeaderExtensionsParser:()=>FJ,saltLength:()=>lJ,serializeAbsSendTime:()=>GJ,serializeAudioLevelIndication:()=>Ike,serializeRepairedRtpStreamId:()=>WJ,serializeSdesMid:()=>jJ,serializeSdesRTPStreamID:()=>qJ,serializeTransportWideCC:()=>VJ,serverReflexiveCandidate:()=>FX,signatures:()=>R6,sortCandidatePairs:()=>$X,supportedAudioCodecs:()=>xRe,supportedCodecs:()=>Y6,supportedVideoCodecs:()=>vRe,timer:()=>vke,timestampSeconds:()=>Hx,uint16Add:()=>$n,uint16Gt:()=>iR,uint16Gte:()=>xEe,uint24:()=>PK,uint32Add:()=>If,uint32Gt:()=>ba,uint32Gte:()=>gh,uint8Add:()=>CK,unwrapRtx:()=>nX,url2Address:()=>fRe,useAV1X:()=>eY,useAbsSendTime:()=>ERe,useAudioLevelIndication:()=>RRe,useDependencyDescriptor:()=>kRe,useFIR:()=>gRe,useH264:()=>QX,useNACK:()=>Kx,useOPUS:()=>J6,usePCMU:()=>X6,usePLI:()=>Th,useREMB:()=>Jx,useRepairedRtpStreamId:()=>wRe,useSdesMid:()=>SRe,useSdesRTPStreamId:()=>bRe,useTWCC:()=>KX,useTransportWideCC:()=>IRe,useVP8:()=>K6,useVP9:()=>ZX,useVideoOrientation:()=>ARe,validateAddress:()=>QN,validateRemoteCandidate:()=>YN,wrapRtx:()=>iX});import{randomBytes as SK}from"node:crypto";import{createSocket as _K}from"node:dgram";import{createSocket as IEe}from"node:dgram";import*as NK from"node:net";import{connect as EEe}from"node:net";import{createSign as kEe,randomBytes as REe,webcrypto as AEe}from"node:crypto";import{createHash as CEe,createHmac as PEe}from"node:crypto";import{randomBytes as VEe}from"node:crypto";import{setTimeout as GEe}from"node:timers/promises";import{createCipheriv as nke,createDecipheriv as ike}from"node:crypto";import{createHmac as nN}from"node:crypto";import{createCipheriv as Sz,createDecipheriv as bz,createHmac as wz,timingSafeEqual as Rke}from"node:crypto";import{createCipheriv as Rz,createDecipheriv as Az}from"node:crypto";import{setTimeout as Oke}from"node:timers/promises";import{randomBytes as $ke}from"node:crypto";import{createHmac as xX}from"node:crypto";import{randomBytes as SX}from"node:crypto";import{createHash as eRe}from"node:crypto";import{setTimeout as tRe}from"node:timers/promises";import{createHash as oRe}from"node:crypto";import{isIPv4 as qz}from"node:net";import{randomBytes as sRe}from"node:crypto";import{isIPv4 as Wz}from"node:net";import*as zN from"node:timers/promises";import{randomUUID as cRe}from"node:crypto";import*as jX from"node:os";import{EventEmitter as mRe}from"node:events";import{randomUUID as CRe}from"node:crypto";import{setTimeout as fN}from"node:timers/promises";import{createHash as PRe}from"node:crypto";import{createSocket as _Re}from"node:dgram";import{performance as zz}from"node:perf_hooks";import{randomUUID as TRe}from"node:crypto";import{randomUUID as oY}from"node:crypto";import{setTimeout as GRe}from"node:timers/promises";import{randomBytes as XRe}from"node:crypto";import{isIPv4 as YRe}from"node:net";import{randomUUID as QRe}from"node:crypto";import{setTimeout as ZRe}from"node:timers/promises";import{randomUUID as o1e}from"node:crypto";import{randomUUID as c1e}from"node:crypto";import{createHmac as iK,randomBytes as u1e}from"node:crypto";import{randomBytes as hK}from"node:crypto";import{randomUUID as gK}from"node:crypto";import{setTimeout as yK}from"node:timers/promises";import{randomUUID as N1e}from"node:crypto";function b6(){return S6.jspack.Unpack("!H",SK(2))[0]}function jk(){return S6.jspack.Unpack("!L",SK(4))[0]}function uEe(t,e){if(t.length!==e.length)throw new TypeError("[webrtc-stun] You can not XOR buffers which length are different");let r=t.length,n=Buffer.allocUnsafe(r);for(let i=0;i<r;i++)n[i]=t[i]^e[i];return n}function dEe(t){let e=[...t].sort((n,i)=>n.length-i.length).reverse()[0].length,r=Buffer.allocUnsafe(e);for(let n=0;n<e;n++)r[n]=0,t.forEach(i=>{r[n]^=i[n]??0});return r}function Ne(t,e,r=1){let n=t.toString(2).split("");n=[...Array(8-n.length).fill("0"),...n];let i=n.slice(e,e+r).join("");return Number.parseInt(i,2)}function Ix(t){let e=t.toString(2).split("");return[...[...Array(8-e.length)].map(()=>"0"),...e].join("")}function lEe(t,e){let r=t.toString(2);return[...[...Array(e-r.length)].map(()=>"0"),...r].join("")}function _r(t,e){return vx(t)(e)}function vx(t,e){let r=t.reduce((i,o)=>i+o,0),n=e?Buffer.alloc(r):void 0;return i=>{let o=n||Buffer.alloc(r),s=0;return i.forEach((a,c)=>{let u=t[c];u===8?o.writeBigUInt64BE(a,s):o.writeUIntBE(a,s,u),s+=u}),o}}function bK(t,e){let r=t.reduce((o,s)=>o+s,0),n=Buffer.alloc(r),i=0;return e.forEach((o,s)=>{let a=t[s];a===8?n.writeBigUInt64LE(o,i):n.writeUIntLE(o,i,a),i+=a}),n}function vi(t,e){let r=0;return e.map(n=>{let i;return n===8?i=t.readBigUInt64BE(r):i=t.readUIntBE(r,n),r+=n,i})}function mEe(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function wK(t){return typeof t!="string"}function IK(t){let e=new Array(256),r=0;for(let n=0;n<256;++n)r=n,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,r=r&1?t^r>>>1:r>>>1,e[n]=r;return new Int32Array(e)}function EK(t){let e=new Int32Array(4096),r=0,n=0,i=0;for(i=0;i<256;++i)e[i]=t[i];for(i=0;i<256;++i)for(n=t[i],r=256+i;r<4096;r+=256)n=e[r]=n>>>8^t[n&255];let o=[];for(i=1;i<16;++i)o[i-1]=e.subarray(i*256,i*256+256);return o}function kK(t,e,r){let n=e^-1,i=0,o=t.length,s=0,a=0;for(;i<o;)s=t.charCodeAt(i++),s<128?n=n>>>8^r[(n^s)&255]:s<2048?(n=n>>>8^r[(n^(192|s>>6&31))&255],n=n>>>8^r[(n^(128|s&63))&255]):s>=55296&&s<57344?(s=(s&1023)+64,a=t.charCodeAt(i++)&1023,n=n>>>8^r[(n^(240|s>>8&7))&255],n=n>>>8^r[(n^(128|s>>2&63))&255],n=n>>>8^r[(n^(128|a>>6&15|(s&3)<<4))&255],n=n>>>8^r[(n^(128|a&63))&255]):(n=n>>>8^r[(n^(224|s>>12&15))&255],n=n>>>8^r[(n^(128|s>>6&63))&255],n=n>>>8^r[(n^(128|s&63))&255]);return~n>>>0}function RK(t,e,r,n){let[i,o,s,a,c,u,d,l,f,p,g,v,b,C,D]=n,_=e^-1,F=0,he=t.length-15;for(;F<he;)_=D[t[F++]^_&255]^C[t[F++]^_>>>8&255]^b[t[F++]^_>>>16&255]^v[t[F++]^_>>>24]^g[t[F++]]^p[t[F++]]^f[t[F++]]^l[t[F++]]^d[t[F++]]^u[t[F++]]^c[t[F++]]^a[t[F++]]^s[t[F++]]^o[t[F++]]^i[t[F++]]^r[t[F++]];for(he+=15;F<he;)_=_>>>8^r[(_^t[F++])&255];return~_>>>0}function AK(t,e=0){return wK(t)?RK(t,e,gN,yEe):kK(t,e,gN)}function w6(t,e=0){return wK(t)?RK(t,e,yN,vEe):kK(t,e,yN)}function CK(t,e){return t+e&255}function $n(t,e){return t+e&65535}function If(t,e){return Number(BigInt(t)+BigInt(e)&0xffffffffn)}function PK(t){return t&16777215}function iR(t,e){return t<e&&e-t>32768||t>e&&t-e<32768}function xEe(t,e){return t===e||iR(t,e)}function ba(t,e){return t<e&&e-t>2147483648||t>e&&t-e<2147483648}function gh(t,e){return t===e||ba(t,e)}async function I6(t="udp4",e){let r=_K(t);setImmediate(()=>r.bind({port:0,address:oR(t,e)})),await new Promise(i=>{r.once("error",i),r.once("listening",i)});let n=r.address()?.port;return await new Promise(i=>r.close(()=>i())),n}async function bEe(t,e="udp4",r){return Promise.all([...Array(t)].map(()=>I6(e,r)))}async function TK(t,e,r="udp4",n){let i;for(let o=t;o<=e;o++){let s=_K(r);if(setImmediate(()=>s.bind({port:o,address:oR(r,n)})),await new Promise(c=>{s.once("error",u=>c(u)),s.once("listening",()=>c())})){await new Promise(c=>s.close(()=>c()));continue}if(i=s.address()?.port,await new Promise(c=>s.close(()=>c())),t<=i&&i<=e)break}if(!i)throw new Error("port not found");return i}function Ex(t){return t==="IPv4"?4:t==="IPv6"?6:t}function jK(t,e,r){switch(r){case Wc.secp256r1_23:return TEe({publicKey:t,privateKey:e});case Wc.x25519_29:return Buffer.from(FK.default.scalarMult(e,t));default:throw new Error}}function az(t,e,r){let n=PEe(t,e);return n.update(r),n.digest()}function Fx(t,e,r,n="sha256"){let i=r,o=[],s=e;do{s=az(n,t,s);let a=az(n,t,Buffer.concat([s,e]));o.push(a),r-=a.length}while(r>0);return Buffer.concat(o,i)}function qK(t,e,r){let n=Buffer.concat([Buffer.from("master secret"),e,r]);return Fx(t,n,48)}function WK(t,e){let r=VK("sha256",e);return Fx(t,Buffer.concat([Buffer.from("extended master secret"),r]),48)}function DEe(t,e,r,n,i,o){let s=o?n:i,a=o?i:n,c=Buffer.concat([Buffer.from(t),s,a]);return Fx(r,c,e)}function VK(t,e){return CEe(t).update(e).digest()}function GK(t,e,r,n=12){let i=VK("sha256",e);return Fx(t,Buffer.concat([Buffer.from(r),i]),n)}function BEe(t,e){return GK(t,e,"client finished")}function NEe(t,e){return GK(t,e,"server finished")}function OEe(t,e,r,n,i,o,s="sha256"){let a=n*2+i*2,c=t,u=Buffer.concat([r,e]),d=Fx(c,Buffer.concat([Buffer.from("key expansion"),u]),a,s),l=(0,$K.createDecode)(d),f=l.readBuffer(n),p=l.readBuffer(n),g=l.readBuffer(i),v=l.readBuffer(i),b=Buffer.alloc(o,0),C=Buffer.alloc(o,0);return g.copy(b,0),v.copy(C,0),{clientWriteKey:f,serverWriteKey:p,clientNonce:b,serverNonce:C}}function QEe(){let t=new Gx;return t.id=Vx.RSA,t.name="RSA",t.keyType=Wx.RSA,t}function ZEe(){let t=new Gx;return t.id=Vx.ECDHE_RSA,t.name="ECDHE_RSA",t.signType=aR.ECDHE,t.keyType=Wx.RSA,t}function eke(){let t=new Gx;return t.id=Vx.ECDHE_ECDSA,t.name="ECDHE_ECDSA",t.signType=aR.ECDHE,t.keyType=Wx.ECDSA,t}function tke(){let t=new Gx;return t.id=Vx.PSK,t.name="PSK",t.signType=aR.NULL,t.keyType=Wx.PSK,t}function rke(){let t=new Gx;return t.id=Vx.ECDHE_PSK,t.name="ECDHE_PSK",t.signType=aR.ECDHE,t.keyType=Wx.PSK,t}function ZK(t){switch(t){case an.TLS_RSA_WITH_AES_128_GCM_SHA256:return xa(an.TLS_RSA_WITH_AES_128_GCM_SHA256,"TLS_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",cz,Yv);case an.TLS_RSA_WITH_AES_256_GCM_SHA384:return xa(an.TLS_RSA_WITH_AES_256_GCM_SHA384,"TLS_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",cz,Qv,"sha384");case an.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:return xa(an.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",uz,Yv);case an.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:return xa(an.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",uz,Qv,"sha384");case an.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:return xa(an.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256","aes-128-gcm",dz,Yv);case an.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:return xa(an.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","aes-256-gcm",dz,Qv,"sha384");case an.TLS_PSK_WITH_AES_128_GCM_SHA256:return xa(an.TLS_PSK_WITH_AES_128_GCM_SHA256,"TLS_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",lz,Yv,"sha256");case an.TLS_PSK_WITH_AES_256_GCM_SHA384:return xa(an.TLS_PSK_WITH_AES_256_GCM_SHA384,"TLS_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",lz,Qv,"sha384");case an.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:return xa(an.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,"TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256","aes-128-gcm",fz,Yv,"sha256");case an.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:return xa(an.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,"TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384","aes-256-gcm",fz,Qv,"sha384");default:break}return null}function xa(t,e,r,n,i,o="sha256"){let s=new ske;return s.id=t,s.name=e,s.blockAlgorithm=r,s.kx=n,s.hashAlgorithm=o,s.keyLength=i.K_LEN,s.nonceLength=i.N_MAX,s.nonceImplicitLength=4,s.nonceExplicitLength=8,s.ivLength=s.nonceImplicitLength,s.authTagLength=16,s}function tJ(t){switch(t){case Wc.secp256r1_23:{let{privateKey:e,publicKey:r}=_Ee();return{curve:t,privateKey:e,publicKey:r}}case Wc.x25519_29:{let e=eJ.default.box.keyPair();return{curve:t,privateKey:Buffer.from(e.secretKey.buffer),publicKey:Buffer.from(e.publicKey.buffer)}}default:throw new Error}}function ake(t,e){return Buffer.from((0,cJ.encode)(t,e).slice())}function gJ(t){let e=0,r=0;for(let n=0;n<8;n++){let i=t.readUInt8(n);if(e|=(i&127)<<n*7,r++,!(i&128))break}return[e,r]}function hke(t,e,r){let n=i=>{let o=[];for(let c of e){let u=i.deSerialize(c.payload,r);u.fragment?(r??=Buffer.alloc(0),r=u.fragment):u.payload&&(r=void 0),o.push(u)}let s=!!o.find(c=>c.isKeyframe),a=Buffer.concat(o.map(c=>c.payload).filter(c=>c));return{isKeyframe:s,data:a,sequence:e.at(-1)?.header.sequenceNumber??0,timestamp:e.at(-1)?.header.timestamp??0,frameFragmentBuffer:r}};switch(t.toUpperCase()){case"AV1":{let i=e.map(a=>RN.deSerialize(a.payload)),o=!!i.find(a=>a.isKeyframe),s=RN.getFrame(i);return{isKeyframe:o,data:s,sequence:e.at(-1)?.header.sequenceNumber??0,timestamp:e.at(-1)?.header.timestamp??0}}case"MPEG4/ISO/AVC":return n(vJ);case"VP8":return n(wJ);case"VP9":return n(EJ);case"OPUS":return n(SJ);default:throw new Error}}function yke(t){return t.map((e,r)=>[r,e])}function AN(t,e){let r=Buffer.alloc(e);return t.copy(r),r}function Px(t){return Number.parseInt(t.toString(),10)}function RJ(t){let e=t[0];return e>127&&e<192}function mz(t){return t%4==0?0:4-t%4}function $J(t){return t.length>=2&&t[1]>=192&&t[1]<=208}function FJ(t,e){return t.map(r=>{let n=e[r.id];if(!n)return{uri:"unknown",value:r.payload};switch(n){case Rr.sdesMid:case Rr.sdesRTPStreamID:case Rr.repairedRtpStreamId:return{uri:n,value:zJ(r.payload)};case Rr.transportWideCC:return{uri:n,value:KJ(r.payload)};case Rr.absSendTime:return{uri:n,value:JJ(r.payload)};case Rr.audioLevelIndication:return{uri:n,value:XJ(r.payload)};case Rr.videoOrientation:return{uri:n,value:YJ(r.payload)};default:return{uri:n,value:r.payload}}}).reduce((r,n)=>(n&&(r[n.uri]=n.value),r),{})}function jJ(t){return Buffer.from(t)}function qJ(t){return Buffer.from(t)}function WJ(t){return Buffer.from(t)}function VJ(t){return _r([2],[t])}function GJ(t){let e=Buffer.alloc(3),r=t>>14n&0x00ffffffn;return e.writeUIntBE(Number(r),0,3),e}function Ike(t){let e=new Cd(Buffer.alloc(1));return e.writeBits(1,1),e.writeBits(7,t),e.uint8Array}function zJ(t){return t.toString()}function KJ(t){return t.readUInt16BE()}function JJ(t){return vi(t,[3])[0]}function XJ(t){let e=new Cd(t);return{v:e.readBits(1)===1,level:e.readBits(7)}}function YJ(t){let e=new Cd(t);return e.readBits(4),{c:e.readBits(1),f:e.readBits(1),r1:e.readBits(1),r0:e.readBits(1)}}function nX(t,e,r){return new Gc(new Vc({payloadType:e,marker:t.header.marker,sequenceNumber:B6.jspack.Unpack("!H",t.payload.subarray(0,2))[0],timestamp:t.header.timestamp,ssrc:r}),t.payload.subarray(2))}function iX(t,e,r,n){return new Gc(new Vc({payloadType:e,marker:t.header.marker,sequenceNumber:r,timestamp:t.header.timestamp,ssrc:n,csrc:t.header.csrc,extensions:t.header.extensions}),Buffer.concat([Buffer.from(B6.jspack.Pack("!H",[t.header.sequenceNumber])),t.payload]))}function N6(t,e,r="Failed to authenticate SRTP packet"){let n=t.length-e;Ox(t.length>=Iz+e,r);let i=aX(()=>Vc.deSerialize(t.subarray(0,n)),r);return i.paddingSize=0,Ox(i.payloadOffset>=Iz&&i.payloadOffset<=n,r),i}function sX(t,e,r,n="Failed to authenticate SRTCP packet"){return Ox(t.length>=Ake+e+r,n),aX(()=>zc.deSerialize(t.subarray(0,zk)),n)}function Ox(t,e){if(!t)throw new Tf(e)}function aX(t,e){try{return t()}catch{throw new Tf(e)}}function cX(t,e,r="Failed to authenticate SRTP packet"){if(!t.padding)return t.paddingSize=0,t;Ox(e.length>t.payloadOffset,r);let n=e[e.length-1];return Ox(n>0&&n<=e.length-t.payloadOffset,r),t.paddingSize=n,t}function kz(t,e,r){if(t.length!==e.length||!Rke(t,e))throw new Tf(r)}function Pz(t,e){try{t.final()}catch{throw new Tf(`Failed to authenticate ${e} packet`)}}function ex(t){return SX(t).toString("hex").substring(0,t)}function bX(){return SX(12)}function ph(t){let[e]=t,r=Mx.default.isV4Format(e)?L6:H6,n=Buffer.alloc(4);return n.writeUInt8(0,0),n.writeUInt8(r,1),n.writeUInt16BE(t[1],2),Buffer.concat([n,Mx.default.toBuffer(e)])}function Vke(t){if(t.length<4)throw new Error("STUN error code is less than 4 bytes");let e=t.readUInt8(2),r=t.readUInt8(3),n=t.slice(4).toString("utf8");return[e*100+r,n]}function mh(t){if(t.length<4)throw new Error("STUN address length is less than 4 bytes");let e=t.readUInt8(1),r=t.readUInt16BE(2),n=t.slice(4);switch(e){case L6:if(n.length!=4)throw new Error("STUN address has invalid length for IPv4");return[Mx.default.toString(n),r];case H6:if(n.length!=16)throw new Error("STUN address has invalid length for IPv6");return[Mx.default.toString(n),r];default:throw new Error("STUN address has unknown protocol")}}function wX(t,e){let r=[...F6,...e],n=t.slice(0,2);for(let i=2;i<t.length;i++){let o=t[i]^r[i-2],s=Buffer.alloc(1);s.writeUIntBE(o,0,1),n=Buffer.concat([n,s])}return n}function Pk(t,e){return mh(wX(t,e))}function Gke(t){let e=Buffer.alloc(4);e.writeUInt16BE(0,0),e.writeUInt8(Math.floor(t[0]/100),2),e.writeUInt8(t[0]%100,3);let r=Buffer.from(t[1],"utf8");return Buffer.concat([e,r])}function _k(t,e){return wX(ph(t),e)}function pR(t,e){if(t.length<$c)return;let r=t.readUint16BE(2);if(t.length!==$c+r)return;let n=t.readUint16BE(0),i=Buffer.from(t.slice($c-12,$c)),o=new EX;for(let a=$c;a<=t.length-4;){let c=t.readUInt16BE(a),u=t.readUInt16BE(a+2),d=t.slice(a+4,a+4+u),l=4*Math.floor((u+3)/4)-u;if(Object.keys($z).includes(c.toString())){let[,p,,g]=$z[c];if(g.name===Pk.name?o.setAttribute(p,g(d,i)):o.setAttribute(p,g(d)),p==="FINGERPRINT"){let v=kX(t.slice(0,a));if(o.getAttributeValue("FINGERPRINT")!==v)return}else if(p==="MESSAGE-INTEGRITY"&&e){let v=Qke(t.slice(0,a),e),b=o.getAttributeValue("MESSAGE-INTEGRITY");if(!v.equals(b))return}}a+=4+u+l}let s=o.getAttributes();return o.clear(),new Ho(n&16111,n&272,i,s)}function kX(t){let e=j6(t,t.length-$c+hX);return(AK(e)^gX)>>>0}function Qke(t,e){let r=j6(t,t.length-$c+M6);return Buffer.from(xX("sha1",e).update(r).digest("hex"),"hex")}function WN(t){let e=t%4;return e===0?0:4-e}async function BX({address:t,username:e,password:r},{lifetime:n,portRange:i,interfaceAddresses:o,transport:s}={}){n??=nRe,s??="udp";let a=s==="udp"?await qk.init("udp4",{portRange:i,interfaceAddresses:o}):await MK.init(t),c=new TX(t,e,r,n,a);return await c.connectionMade(),c}async function GN({address:t,username:e,password:r},{lifetime:n,portRange:i,interfaceAddresses:o,transport:s}={}){let a=await BX({address:t,username:e,password:r},{lifetime:n,portRange:i,interfaceAddresses:o,transport:s});return new PX(a)}function NX(t,e,r){return eRe("md5").update(Buffer.from([t,e,r].join(":"))).digest()}function jz(t){return(t[0]&192)==64}function Jk(t,e,r){let n=`${t}|${e}|${r}`;return oRe("md5").update(n,"ascii").digest("hex").slice(7)}function Sx(t,e=65535){let n=0;return t==="host"?n=126:t==="prflx"?n=110:t==="srflx"?n=100:n=0,(1<<24)*n+256*e+255}function YN(t){if(!["host","relay","srflx"].includes(t.type))throw new Error(`Unexpected candidate type "${t.type}"`);return t}function $X(t,e){return t.sort((r,n)=>Xk(r.localCandidate,r.remoteCandidate,e)-Xk(n.localCandidate,n.remoteCandidate,e)).reverse()}function Xk(t,e,r){let n=r&&t.priority||e.priority,i=r&&e.priority||t.priority;return 1*Math.min(n,i)+2*Math.max(n,i)+(n>i?1:0)}async function FX(t,e){let r=new Ho(1,0);try{let[n]=await t.request(r,e),i=t.localCandidate;if(!i)throw new Error("not exist");return new Td(Jk("srflx","udp",i.host),i.component,i.transport,Sx("srflx"),n.getAttributeValue("XOR-MAPPED-ADDRESS")[0],n.getAttributeValue("XOR-MAPPED-ADDRESS")[1],"srflx",i.host,i.port)}catch(n){uRe("error serverReflexiveCandidate",n)}}function QN(t){return t&&Number.isNaN(t[1])?[t[0],443]:t}async function lRe(t,e){let r=new Kk;await r.connectionMade(!0,void 0,e);let n=new Ho(1,0),[i]=await r.request(n,t??["stun.l.google.com",19302]);return await r.close(),i.getAttributeValue("XOR-MAPPED-ADDRESS")[0]}function WX(t){return Ex(t.family)===4&&t.address?.startsWith("169.254.")||Ex(t.family)===6&&t.address?.startsWith("fe80::")}function ZN(t,{useLinkLocalAddress:e}={}){let r=["ipsec","tun","utun","tap"],n=["vmnet","veth"],i=jX.networkInterfaces();dRe(i);let o=Object.keys(i).map(s=>{for(let c of[...r,...n])if(s.startsWith(c))return{nic:s,addresses:[]};let a=i[s].filter(c=>Ex(c.family)===t&&!qX.default.isLoopback(c.address)&&(e?!0:!WX(c)));return{nic:s,addresses:a.map(c=>c.address)}}).filter(s=>!!s);return o.sort((s,a)=>s.nic.localeCompare(a.nic)),Object.values(o).flatMap(s=>s.addresses)}function VX(t,e,r={}){let n=[];return t&&n.push(...ZN(4,r)),e&&n.push(...ZN(6,r)),n}function Gz(t){return t.map((e,r)=>[r,e])}function Uc(t,e){let r=t.split(e);return[r[0],r.slice(1).join(e)]}function zX(t){return Buffer.isBuffer(t)?t.length:Buffer.byteLength(t)}function SRe(){return new ka({uri:Rr.sdesMid})}function bRe(){return new ka({uri:Rr.sdesRTPStreamID})}function wRe(){return new ka({uri:Rr.repairedRtpStreamId})}function IRe(){return new ka({uri:Rr.transportWideCC})}function ERe(){return new ka({uri:Rr.absSendTime})}function kRe(){return new ka({uri:Rr.dependencyDescriptor})}function RRe(){return new ka({uri:Rr.audioLevelIndication})}function ARe(){return new ka({uri:Rr.videoOrientation})}function hr(t,...e){let r=e.filter(n=>n!==void 0);return`${t}_${r.join("_")}`}function Bd(){return performance.now()}function tO(t,e){let r=o=>o.toUpperCase(),n=o=>o.match(/(.{2})/g).join(":"),i=PRe(e).update(t).digest("hex");return n(r(i))}function rO(t){return URe[t.trim().toLowerCase()]}function Yk(t){return t.replace(/[^0-9a-f]/gi,"").toLowerCase()}function aY(t){let e=t[0];return e>19&&e<64}function $Re(t){return t==="recv"?"send":"recv"}function cY(t){return t==="sendonly"?"recvonly":t==="recvonly"?"sendonly":t}function lY(t){let e=a=>{if(!a)return;let[c,u]=a.split(":");return[c,Number.parseInt(u)]},r=e(t.find(({urls:a})=>a.includes("stun:"))?.urls.slice(5)),n=e(t.find(({urls:a})=>a.includes("turn:"))?.urls.slice(5)),{credential:i,username:o}=t.find(({urls:a})=>a.includes("turn:"))||{},s={stunServer:r,turnServer:n,turnUsername:o,turnPassword:i};return HRe("iceOptions",s),s}function Rh(t){let e=new aO(t.component,t.foundation,t.host,t.port,t.priority,t.transport,t.type,t.generation,t.ufrag);return e.relatedAddress=t.relatedAddress,e.relatedPort=t.relatedPort,e.tcpType=t.tcptype,e}function gY(t){return new Td(t.foundation,t.component,t.protocol,t.priority,t.ip,t.port,t.type,t.relatedAddress,t.relatedPort,t.tcpType,t.generation,t.ufrag)}function Yx(t){let e=t%4;return e?4-e:0}function HY(t){let e=Buffer.from(""),r=Buffer.from("");return t.forEach(([n,i])=>{let o=i.length+4,s=Buffer.alloc(4);s.writeUInt16BE(n,0),s.writeUInt16BE(o,2),e=Buffer.concat([e,r,s,i]),r=Buffer.concat([...Array(Yx(o))].map(()=>Buffer.from("\0")))}),e}function UY(t){let e=[],r=0;for(;r<=t.length-4;){let n=t.readUInt16BE(r),i=t.readUInt16BE(r+2);e.push([n,t.slice(r+4,r+i)]),r+=i+Yx(i)}return e}function p1e(t){if(t.length<12)throw new Error("SCTP packet length is less than 12 bytes");let e=t.readUInt16BE(0),r=t.readUInt16BE(2),n=t.readUInt32BE(4),i=t.readUInt32LE(8),o=w6(Buffer.concat([t.slice(0,8),Buffer.from("\0\0\0\0"),t.slice(12)]));if(i!==o)throw new Error("SCTP packet has invalid checksum");let s=[],a=12;for(;a+4<=t.length;){let c=t.readUInt8(a),u=t.readUInt8(a+1),d=t.readUInt16BE(a+2),l=t.slice(a+4,a+d),f=f1e[c.toString()];if(f)s.push(new f(u,l));else throw new Error("unknown");a+=d+Yx(d)}return[e,r,n,s]}function m1e(t,e,r,n){let i=Buffer.alloc(8);i.writeUInt16BE(t,0),i.writeUInt16BE(e,2),i.writeUInt32BE(r,4);let o=n.bytes,s=w6(Buffer.concat([i,Buffer.from("\0\0\0\0"),o])),a=Buffer.alloc(4);return a.writeUInt32LE(s,0),Buffer.concat([i,a,o])}function h1e(t){return t.map((e,r)=>[r,e])}function g1e(t){return t.reduce((e,r)=>(e[r]=new qe,e),{})}function bf(t){return(t-1)%eR}function hh(t){return(t+1)%eR}function pN(t){let e=t.match(/^IN (IP4|IP6) ([^ ]+)$/);if(!e)throw new Error("exception");return e[2]}function g6(t){return`IN IP${YRe(t)?4:6} ${t}`}function lO(t){let e=`${t.foundation} ${t.component} ${t.protocol} ${t.priority} ${t.ip} ${t.port} typ ${t.type}`;return t.relatedAddress!=null&&(e+=` raddr ${t.relatedAddress}`),t.relatedPort!=null&&(e+=` rport ${t.relatedPort}`),t.tcpType!=null&&(e+=` tcptype ${t.tcpType}`),t.generation!=null&&(e+=` generation ${t.generation}`),t.ufrag!=null&&(e+=` ufrag ${t.ufrag}`),e}function P1e(t){let e=[],r=[],n=t.split(`\r
127
+ `);return n.length===1&&(n=t.split(`
128
+ `)),n.forEach(i=>{i.startsWith("m=")?r.push([i]):r.length>0?r[r.length-1].push(i):e.push(i)}),[e,r]}function mN(t){if(t.includes(":")){let e=Uc(t.slice(2),":");return[e[0],e[1]]}else return[t.slice(2),void 0]}function Fk(t,e,r=n=>n.toString()){let n=e.split(" ");n.length>0&&t.push(new bh(n[0],n.slice(1).map(r)))}function fO(t){let e=Td.fromSdp(t);return Rh(e)}function y6(t,e){let n=new gk(XRe(64)).toString().slice(0,8),i=0;e.origin=`- ${n} ${i} IN IP4 0.0.0.0`,e.msidSemantic.push(new bh("WMS",["*"])),e.type=t}function $x(t){let e={};return t.split(";").forEach(r=>{if(r.includes("=")){let[n,i]=Uc(r,"=");MRe.includes(n)?e[n]=Number(i):e[n]=i}else if(r.includes(":")){let[n,i]=r.split(":");e[n]=Number.isNaN(Number(i))?i:Number(i)}else e[r]=void 0}),e}function _1e(t,e="="){let r=Object.entries(t).map(([n,i])=>i?`${n}${e}${i}`:n);if(r.length>0)return r.join(";")}function JY(){return{codecs:{audio:[J6(),X6()],video:[K6()]},headerExtensions:{audio:[],video:[]},iceTransportPolicy:"all",iceServers:[{urls:"stun:stun.l.google.com:19302"}],icePortRange:void 0,iceInterfaceAddresses:void 0,iceAdditionalHostAddresses:void 0,iceUseIpv4:!0,iceUseIpv6:!0,iceFilterStunResponse:void 0,iceFilterCandidatePair:void 0,icePasswordPrefix:void 0,iceUseLinkLocalAddress:void 0,dtls:{},bundlePolicy:"max-compat",debug:{},midSuffix:!1,forceTurnTCP:!1,maxMessageSize:yh}}var S6,DK,sR,Ah,xh,$K,FK,Un,Es,KK,Ef,Fc,eJ,Rf,Pd,Af,Ch,_d,Cf,ks,Rs,dR,Is,cJ,fJ,B6,Ak,Df,wf,Ia,wa,Bf,Mx,VN,Tk,MX,qX,Ux,Nk,Ok,jc,v6,wx,nR,fEe,pEe,Cd,hEe,gEe,gN,yEe,yN,vEe,vh,SEe,oR,wEe,xt,qe,BK,sz,qk,MK,Ea,kx,Wk,HK,Wc,E6,k6,vN,UK,R6,_Ee,TEe,qc,MEe,xN,Rx,Ax,A6,zK,Uo,Vk,LEe,JK,HEe,Cx,UEe,$Ee,SN,FEe,jEe,qEe,WEe,C6,kf,XK,zEe,YK,QK,jx,wN,KEe,rN,qx,JEe,XEe,YEe,aR,Wx,Vx,Gx,oke,ske,an,Yv,Qv,cz,uz,dz,lz,fz,cR,uR,wh,Gk,rJ,nJ,iJ,EN,oJ,sJ,aJ,uJ,Ph,Nf,cke,dJ,lJ,uke,RN,mJ,yJ,dke,vJ,kd,lke,fke,pke,SJ,wJ,EJ,mke,gke,vke,zk,zc,pz,_x,Tx,xke,Ih,Eh,lR,CJ,Dx,Ske,Bx,Sh,_J,xx,DJ,BJ,NJ,bke,Pf,Nx,P6,_6,_f,T6,HJ,wke,UJ,Rr,Eke,D6,HN,eX,kke,tX,Rd,hz,gz,yz,vz,xz,Vc,Gc,oX,Tf,Iz,Ake,Cke,Ez,Pke,iN,Cz,uX,Zv,_z,_ke,Tke,dX,lX,Dke,fX,Bke,yi,Nke,_h,pX,Mke,Tz,Lke,$N,FN,Dz,Bz,oN,Hke,Uke,Nz,Oz,O6,sN,jN,Sa,Fke,Mz,jke,kh,qke,zx,uh,mX,fR,hX,gX,$c,M6,L6,H6,yX,vX,Wke,U6,$6,Lz,qN,F6,tx,rx,zke,Kke,Hz,Uz,aN,cN,uN,dN,Jke,Xke,IX,EX,$z,Yke,Ho,j6,RX,AX,Zke,lN,q6,Fz,Kk,ji,rRe,nRe,iRe,PX,TX,Td,aRe,uRe,KN,JN,gx,LX,XN,HX,UX,dRe,fRe,ur,GX,pRe,Vz,W6,hRe,V6,G6,gRe,Kx,Th,Jx,KX,Dd,ka,yRe,JX,XX,YX,z6,QX,K6,ZX,eY,J6,X6,Y6,vRe,xRe,Kz,Jz,DRe,wk,Xz,Yz,BRe,NRe,ORe,Qz,e6,Zz,MRe,tY,eK,Dk,LRe,rY,nY,iY,Q6,Z6,eO,Bk,Lx,sY,HRe,URe,nO,iO,FRe,uY,Hx,dY,oO,jRe,qRe,fY,WRe,tK,VRe,zRe,KRe,JRe,Ss,t6,e1e,sO,Qk,Zk,t1e,r1e,n1e,i1e,rK,nK,mY,s1e,a1e,hY,yY,aO,cO,Ra,uO,Mk,r6,d1e,Lk,Hk,n6,i6,Xx,o6,Uk,a6,CY,c6,u6,DY,NY,MY,l1e,f1e,d6,$Y,Ik,$k,oK,nr,y1e,v1e,sK,bs,yx,FY,m6,aK,x1e,cK,uK,dK,S1e,b1e,eR,w1e,I1e,lK,fK,pK,mK,E1e,k1e,R1e,A1e,dh,yh,jY,dO,C1e,bx,tR,bh,VY,rR,Ek,pO,nx,GY,T1e,lh,D1e,B1e,hN,vK,xK,zY,O1e,M1e,KY,ix,L1e,H1e,ws,U1e,x6,$1e,F1e,XY,j1e,q1e,QY=N(()=>{S6=tt(Ou(),1),DK=tt(u9(),1),sR=tt(l_(),1),Ah=tt(Vq(),1),xh=tt(Pr(),1),$K=tt(Pr(),1),FK=tt(Lw(),1);CG();Un=tt(Pr(),1),Es=tt(Pr(),1),KK=tt(Pr(),1),Ef=tt(Pr(),1),Fc=tt(Pr(),1),eJ=tt(Lw(),1),Rf=tt(Pr(),1),Pd=tt(Pr(),1),Af=tt(Pr(),1),Ch=tt(Pr(),1),_d=tt(Pr(),1),Cf=tt(Pr(),1),ks=tt(Pr(),1),Rs=tt(Pr(),1),dR=tt(Pr(),1),Is=tt(Pr(),1),cJ=tt(Pr(),1),fJ=tt(_G(),1),B6=tt(Ou(),1),Ak=tt(DG(),1),Df=tt(Pr(),1),wf=tt(Pr(),1),Ia=tt(Pr(),1),wa=tt(Pr(),1),Bf=tt(Pr(),1);yk();Mx=tt(qB(),1),VN=tt(Ou(),1);yk();Tk=tt(qG(),1),MX=tt(oz(),1),qX=tt(qB(),1);yk();Ux=tt(l_(),1),Nk=tt(Ou(),1),Ok=tt(Ou(),1),jc=tt(Ou(),1),v6=tt(Ou(),1);wx=class{constructor(t){this.bitLength=t}value=0;set(t,e,r){return r&=(1<<t)-1,this.value|=r<<this.bitLength-t-e,this}get buffer(){let t=Math.ceil(this.bitLength/8),e=Buffer.alloc(t);return e.writeUIntBE(this.value,0,t),e}},nR=class{constructor(t){if(this.bitLength=t,t>32)throw new Error}_value=0n;offset=0n;set(t,e=1){let r=BigInt(t),n=BigInt(e);return r&=(1n<<n)-1n,this._value|=r<<BigInt(this.bitLength)-n-this.offset,this.offset+=n,this}get value(){return Number(this._value)}get buffer(){let t=Math.ceil(this.bitLength/8),e=Buffer.alloc(t);return e.writeUIntBE(this.value,0,t),e}};fEe=class{buffer;constructor(t){this.buffer=Buffer.alloc(t)}writeInt16BE(t,e){return this.buffer.writeInt16BE(t,e),this}writeUInt8(t,e){return this.buffer.writeUInt8(t,e),this}},pEe=t=>"0x"+t.toString("hex").replace(/(.)(.)/g,"$1$2 ").split(" ").filter(e=>e!=null&&e.length>0).join(",0x");Cd=class{constructor(t){this.uint8Array=t}position=0;bitsPending=0;writeBits(t,e){if(t==0)return this;e&=4294967295>>>32-t;let r;return this.bitsPending>0?this.bitsPending>t?(this.uint8Array[this.position-1]|=e<<this.bitsPending-t,r=t,this.bitsPending-=t):this.bitsPending==t?(this.uint8Array[this.position-1]|=e,r=t,this.bitsPending=0):(this.uint8Array[this.position-1]|=e>>t-this.bitsPending,r=this.bitsPending,this.bitsPending=0):(r=Math.min(8,t),this.bitsPending=8-r,this.uint8Array[this.position++]=e>>t-r<<this.bitsPending),t-=r,t>0&&this.writeBits(t,e),this}readBits(t){return this._readBits(t)}_readBits(t,e){if(typeof e>"u"&&(e=0),t==0)return e;let r,n;if(this.bitsPending>0){let i=this.uint8Array[this.position-1]&255>>8-this.bitsPending;n=Math.min(this.bitsPending,t),this.bitsPending-=n,r=i>>this.bitsPending}else n=Math.min(8,t),this.bitsPending=8-n,r=this.uint8Array[this.position++]>>this.bitsPending;return t-=n,e=e<<n|r,t>0?this._readBits(t,e):e}seekTo(t){this.position=t/8|0,this.bitsPending=t%8,this.bitsPending>0&&(this.bitsPending=8-this.bitsPending,this.position++)}},hEe=3988292384,gEe=2197175160;gN=IK(hEe),yEe=EK(gN),yN=IK(gEe),vEe=EK(yN);vh=t=>Number.parseInt(t,10),SEe=class{queue=[];running=!1;push=t=>new Promise((e,r)=>{this.queue.push({promise:t,done:e,failed:r}),this.running||this.run()});async run(){let t=this.queue.shift();if(t){this.running=!0;try{let e=await t.promise();t.done(e)}catch(e){t.failed(e)}this.run()}else this.running=!1}cancel(){this.queue=[]}},oR=(t,e)=>e?e[t]:void 0;wEe=class extends Error{message;payload;path;constructor(t){super(t.message)}toJSON(){return{message:this.message,payload:JSON.parse(JSON.stringify(this.payload)),path:this.path}}},xt=DK.default.debug,qe=class{event={stack:[],promiseStack:[],eventId:0};ended=!1;onended;onerror=t=>{};execute=(...t)=>{if(!this.ended){for(let e of this.event.stack)e.execute(...t);(async()=>{for(let e of this.event.promiseStack)await e.execute(...t)})().catch(e=>{this.onerror(e)})}};complete=()=>{if(!this.ended){for(let t of this.event.stack)t.complete&&t.complete();this.allUnsubscribe(),this.ended=!0,this.onended&&(this.onended(),this.onended=void 0)}};error=t=>{if(!this.ended){for(let e of this.event.stack)e.error&&e.error(t);this.allUnsubscribe()}};allUnsubscribe=()=>{if(this.ended)throw new Error("event completed");this.event={stack:[],promiseStack:[],eventId:0}};subscribe=(t,e,r)=>{let n=this.event.eventId;this.event.stack.push({execute:t,id:n,complete:e,error:r}),this.event.eventId++;let i=()=>{this.event.stack=this.event.stack.filter(s=>s.id!==n&&s)};return{unSubscribe:i,disposer:s=>{s.push(i)}}};pipe(t){this.subscribe((...e)=>{t.execute(...e)})}queuingSubscribe=(t,e,r)=>{if(this.ended)throw new Error("event completed");let n=this.event.eventId;this.event.promiseStack.push({execute:t,id:n,complete:e,error:r}),this.event.eventId++;let i=()=>{this.event.stack=this.event.stack.filter(s=>s.id!==n&&s)};return{unSubscribe:i,disposer:s=>{s.push(i)}}};once=(t,e,r)=>{let n=this.subscribe((...i)=>{n.unSubscribe(),t(...i)},e,r)};watch=(t,e)=>new Promise((r,n)=>{let i=e&&setTimeout(()=>{n("Event watch timeout")},e),{unSubscribe:o}=this.subscribe((...s)=>{t(...s)&&(i&&clearTimeout(i),o(),r(s))})});asPromise=t=>new Promise((e,r)=>{let n=t&&setTimeout(()=>{r("Event asPromise timeout")},t);this.once((...i)=>{n&&clearTimeout(n),e(i)},()=>{n&&clearTimeout(n),e([])},i=>{n&&clearTimeout(n),r(i)})});get returnTrigger(){let{execute:t,error:e,complete:r}=this;return{execute:t,error:e,complete:r}}get returnListener(){let{subscribe:t,once:e,asPromise:r}=this;return{subscribe:t,once:e,asPromise:r}}get length(){return this.event.stack.length}},BK=class{_disposer=[];push(t){this._disposer.push(t)}dispose(){this._disposer.forEach(t=>t()),this._disposer=[]}},sz=xt("werift-ice:packages/ice/src/transport.ts"),qk=class OK{constructor(e,r={}){this.socketType=e,this.options=r,this.socket=IEe(e),this.socket.on("message",(n,i)=>{Ex(i.family)===6&&([i.address]=i.address.split("%")),this.rinfo=i;try{this.onData(n,[i.address,i.port])}catch(o){sz("onData error",o)}})}type="udp";socket;rinfo;onData=()=>{};closed=!1;static async init(e,r={}){let n=new OK(e,r);return await n.init(),n}async init(){let e=oR(this.socketType,this.options.interfaceAddresses);if(this.options.port)this.socket.bind({port:this.options.port,address:e});else if(this.options.portRange){let r=await TK(this.options.portRange[0],this.options.portRange[1],this.socketType,this.options.interfaceAddresses);this.socket.bind({port:r,address:e})}else this.socket.bind({address:e});await new Promise(r=>this.socket.once("listening",r))}send=async(e,r)=>{if(r&&!NK.isIP(r[0]))return new Promise((n,i)=>{this.socket.send(e,r[1],r[0],o=>{o?(sz("send error",r,e),i(o)):n()})});r=r??[this.rinfo?.address,this.rinfo?.port],this.socket.send(e,r[1],r[0])};get address(){return this.socket.address()}get host(){return this.socket.address().address}get port(){return this.socket.address().port}close=()=>new Promise(e=>{this.closed=!0,this.socket.once("close",e);try{this.socket.close()}catch{e()}})},MK=class LK{constructor(e){this.addr=e,this.connect()}type="tcp";connecting;client;onData=()=>{};closed=!1;connect(){this.closed||(this.client&&this.client.destroy(),this.connecting=new Promise((e,r)=>{try{this.client=EEe({port:this.addr[1],host:this.addr[0]},e)}catch(n){r(n)}}),this.client.on("data",e=>{let r=[this.client.remoteAddress,this.client.remotePort];this.onData(e,r)}),this.client.on("end",()=>{this.connect()}),this.client.on("error",e=>{console.log("error",e)}))}async init(){await this.connecting}static async init(e){let r=new LK(e);return await r.init(),r}get address(){return{}}send=async(e,r)=>{await this.connecting,this.client.write(e,n=>{n&&console.log("err",n)})};close=async()=>{this.closed=!0,this.client.destroy()}},Ea={rsa_1:1,ecdsa_3:3},kx={sha256_4:4},Wk={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195:49195,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199:49199},HK=Object.values(Wk),Wc={x25519_29:29,secp256r1_23:23},E6=Object.values(Wc),k6={named_curve_3:3},vN={rsa_pkcs1_sha256:1025,ecdsa_secp256r1_sha256:1027},UK=[1,64],R6=[{hash:kx.sha256_4,signature:Ea.rsa_1},{hash:kx.sha256_4,signature:Ea.ecdsa_3}],_Ee=()=>{let t=pk.utils.randomPrivateKey(),e=pk.getPublicKey(t,!1),r=Buffer.from(t),n=Buffer.from(e);return{privateKey:r,publicKey:n}},TEe=({publicKey:t,privateKey:e})=>{let r=pk.getSharedSecret(e,t);return Buffer.from(r).subarray(1)};qc={CLIENT:1,SERVER:2},MEe=class{id=0;name;hashAlgorithm;verifyDataLength=12;blockAlgorithm;kx;init(...t){throw new Error("not implemented")}encrypt(...t){throw new Error("not implemented")}decrypt(...t){throw new Error("not implemented")}toString(){return this.name}},xN=AEe;Ah.cryptoProvider.set(xN);Rx=class{constructor(t,e,r,n){this.sessionType=t,this.certPem=e,this.keyPem=r,e&&r&&n&&this.parseX509(e,r,n)}localRandom;remoteRandom;cipherSuite;remoteCertificate;remoteKeyPair;localKeyPair;masterSecret;cipher;namedCurve;signatureHashAlgorithm;localCert;localPrivateKey;static createSelfSignedCertificateWithKey=async(t,e)=>{let r=(()=>{switch(t.signature){case Ea.rsa_1:return"RSASSA-PKCS1-v1_5";case Ea.ecdsa_3:return"ECDSA"}})(),n=(()=>{if(t.hash===kx.sha256_4)return"SHA-256"})(),i=(()=>{switch(e){case Wc.secp256r1_23:return"P-256";case Wc.x25519_29:return r==="ECDSA"?"P-256":"X25519";default:{if(r==="ECDSA")return"P-256";if(r==="RSASSA-PKCS1-v1_5")return"X25519"}}})(),o=(()=>{switch(r){case"ECDSA":return{name:r,hash:n,namedCurve:i};case"RSASSA-PKCS1-v1_5":return{name:r,hash:n,publicExponent:new Uint8Array([1,0,1]),modulusLength:2048}}})(),s=await xN.subtle.generateKey(o,!0,["sign","verify"]),c=(await Ah.X509CertificateGenerator.createSelfSigned({serialNumber:REe(8).toString("hex"),name:"C=AU, ST=Some-State, O=Internet Widgits Pty Ltd",notBefore:new Date,notAfter:new Date(Date.now()+10*365*24*60*60*1e3),signingAlgorithm:o,keys:s})).toString("pem"),u=Ah.PemConverter.encode(await xN.subtle.exportKey("pkcs8",s.privateKey),"private key");return{certPem:c,keyPem:u,signatureHash:t}};encryptPacket(t){let e=t.recordLayerHeader,r=e.protocolVersion.major<<8|e.protocolVersion.minor,n=this.cipher.encrypt(this.sessionType,t.fragment,{type:e.contentType,version:r,epoch:e.epoch,sequenceNumber:e.sequenceNumber});return t.fragment=n,t.recordLayerHeader.contentLen=n.length,t}decryptPacket(t){let e=t.recordLayerHeader,r=e.protocolVersion.major<<8|e.protocolVersion.minor;return this.cipher.decrypt(this.sessionType,t.fragment,{type:e.contentType,version:r,epoch:e.epoch,sequenceNumber:e.sequenceNumber})}verifyData(t){return this.sessionType===qc.CLIENT?BEe(this.masterSecret,t):NEe(this.masterSecret,t)}signatureData(t,e){let r=kEe(e).update(t),n=this.localPrivateKey.toPEM().toString();return r.sign(n)}generateKeySignature(t){let e=this.sessionType===qc.CLIENT?this.localRandom:this.remoteRandom,r=this.sessionType===qc.SERVER?this.localRandom:this.remoteRandom,n=this.valueKeySignature(e.serialize(),r.serialize(),this.localKeyPair.publicKey,this.namedCurve);return this.localPrivateKey.sign(n,t)}parseX509(t,e,r){let n=sR.Certificate.fromPEM(Buffer.from(t)),i=sR.PrivateKey.fromPEM(Buffer.from(e));this.localCert=n.raw,this.localPrivateKey=i,this.signatureHashAlgorithm=r}valueKeySignature(t,e,r,n){let i=Buffer.from((0,xh.encode)({type:k6.named_curve_3,curve:n,len:r.length},{type:xh.types.uint8,curve:xh.types.uint16be,len:xh.types.uint8}).slice());return Buffer.concat([t,e,i,r])}},Ax=class{srtpProfile;static findMatchingSRTPProfile(t,e){for(let r of e)if(t.includes(r))return r}},A6=t=>"0x"+t.toString("hex").replace(/(.)(.)/g,"$1$2 ").split(" ").filter(e=>e!=null&&e.length>0).join(",0x"),zK=t=>Object.entries({...t}).reduce((e,[r,n])=>((typeof n=="number"||typeof n=="string")&&(e[r]=n),Buffer.isBuffer(n)&&(e[r]=A6(n)),e),{}),Uo=class wd{constructor(e,r,n,i,o,s){this.msg_type=e,this.length=r,this.message_seq=n,this.fragment_offset=i,this.fragment_length=o,this.fragment=s}static spec={msg_type:Es.types.uint8,length:Es.types.uint24be,message_seq:Es.types.uint16be,fragment_offset:Es.types.uint24be,fragment_length:Es.types.uint24be,fragment:Es.types.buffer(e=>e.current.fragment_length)};get summary(){return zK(this)}static createEmpty(){return new wd(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new wd(...Object.values((0,Es.decode)(e,wd.spec)))}serialize(){let e=(0,Es.encode)(this,wd.spec).slice();return Buffer.from(e)}chunk(e){let r=0,n=this.fragment.length;if(n===0)return[new wd(this.msg_type,n,this.message_seq,r,0,this.fragment)];let i=[];for(e||(e=1240);r<n;){let o=Math.min(e,n-r),s=Buffer.from(this.fragment.slice(r,r+o));if(s.length<=0)throw new Error("Zero or less bytes processed while fragmenting handshake message.");i.push(new wd(this.msg_type,n,this.message_seq,r,s.length,s)),r+=s.length}return i}static assemble(e){if(!e?.length)throw new Error("cannot reassemble handshake from empty array");e=e.sort((n,i)=>n.fragment_offset-i.fragment_offset);let r=Buffer.alloc(e[0].length);for(let n of e)n.fragment.copy(r,n.fragment_offset);return new wd(e[0].msg_type,e[0].length,e[0].message_seq,0,r.length,r)}static findAllFragments(e,r){let n=e.find(i=>i.msg_type===r);return n?e?.length?e.filter(i=>i.msg_type===n.msg_type&&i.message_seq===n.message_seq&&i.length===n.length):[]:[]}},{uint16be:Vk,uint24be:LEe,buffer:JK,array:HEe,uint8:Cx,string:UEe}=KK.types,$Ee={type:Vk,data:JK(Vk)},SN=HEe($Ee,Vk,"bytes"),FEe=JK(LEe),jEe=Cx,qEe=UEe(Vk),WEe={hash:Cx,signature:Cx},C6={major:Cx,minor:Cx},kf=class ox{constructor(e=Math.floor(Date.now()/1e3),r=VEe(28)){this.gmt_unix_time=e,this.random_bytes=r}static spec={gmt_unix_time:Ef.types.uint32be,random_bytes:Ef.types.buffer(28)};static deSerialize(e){return new ox(...Object.values((0,Ef.decode)(e,ox.spec)))}static from(e){return new ox(...Object.values(e))}serialize(){let e=(0,Ef.encode)(this,ox.spec).slice();return Buffer.from(e)}},XK=class sx{constructor(e,r,n,i,o,s,a){this.clientVersion=e,this.random=r,this.sessionId=n,this.cookie=i,this.cipherSuites=o,this.compressionMethods=s,this.extensions=a}msgType=1;messageSeq=0;static spec={clientVersion:{major:Un.types.uint8,minor:Un.types.uint8},random:kf.spec,sessionId:Un.types.buffer(Un.types.uint8),cookie:Un.types.buffer(Un.types.uint8),cipherSuites:Un.types.array(Un.types.uint16be,Un.types.uint16be,"bytes"),compressionMethods:Un.types.array(Un.types.uint8,Un.types.uint8,"bytes"),extensions:SN};static createEmpty(){return new sx(void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new sx(...Object.values((0,Un.decode)(e,sx.spec)))}serialize(){let e=(0,Un.encode)(this,sx.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Uo(this.msgType,e.length,this.messageSeq,0,e.length,e)}},zEe=class ax{constructor(e,r,n,i,o){this.epoch=e,this.sequenceNumber=r,this.contentType=n,this.protocolVersion=i,this.contentLen=o}static spec={epoch:Fc.types.uint16be,sequenceNumber:Fc.types.uint48be,contentType:Fc.types.uint8,protocolVersion:C6,contentLen:Fc.types.uint16be};static createEmpty(){return new ax(void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){return new ax(...Object.values((0,Fc.decode)(e,ax.spec)))}serialize(){let e=(0,Fc.encode)(this,ax.spec).slice();return Buffer.from(e)}},YK=class bN{constructor(e,r){this.recordLayerHeader=e,this.fragment=r}get summary(){return{header:this.recordLayerHeader,fragment:A6(this.fragment)}}static createEmpty(){return new bN(void 0,void 0)}static deSerialize(e){if(e.length<13)throw new Error("Invalid DTLS record: buffer is too short");let r=e.readUInt8(0),n=e.readUInt8(1),i=e.readUInt8(2),o=e.readUInt16BE(3),s=e.slice(5,11).readUIntBE(0,6),a=e.readUInt16BE(11);if(e.length<13+a)throw new Error("Invalid DTLS record: fragment length exceeds buffer");let c=e.slice(13,13+a);return new bN({contentType:r,protocolVersion:{major:n,minor:i},epoch:o,sequenceNumber:s,contentLen:a},c)}serialize(){let e=this.fragment.length,r=13+e,n=Buffer.alloc(r);return n.writeUInt8(this.recordLayerHeader.contentType,0),n.writeUInt8(this.recordLayerHeader.protocolVersion.major,1),n.writeUInt8(this.recordLayerHeader.protocolVersion.minor,2),n.writeUInt16BE(this.recordLayerHeader.epoch,3),n.writeUIntBE(this.recordLayerHeader.sequenceNumber,5,6),n.writeUInt16BE(e,11),this.fragment.copy(n,13),n}computeMACHeader(){return new zEe(this.recordLayerHeader.epoch,this.recordLayerHeader.sequenceNumber,this.recordLayerHeader.contentType,this.recordLayerHeader.protocolVersion,this.recordLayerHeader.contentLen).serialize()}},QK=t=>e=>(t.lastFlight=e,e.flatMap(r=>(r.messageSeq=t.sequenceNumber++,r.toFragment().chunk()))),jx=t=>(e,r)=>e.map(n=>new YK({contentType:n.type,protocolVersion:t.version,epoch:t.epoch,sequenceNumber:r,contentLen:n.fragment.length},n.fragment)),wN=(t=>(t[t.CloseNotify=0]="CloseNotify",t[t.UnexpectedMessage=10]="UnexpectedMessage",t[t.BadRecordMac=20]="BadRecordMac",t[t.DecryptionFailed=21]="DecryptionFailed",t[t.RecordOverflow=22]="RecordOverflow",t[t.DecompressionFailure=30]="DecompressionFailure",t[t.HandshakeFailure=40]="HandshakeFailure",t[t.NoCertificate=41]="NoCertificate",t[t.BadCertificate=42]="BadCertificate",t[t.UnsupportedCertificate=43]="UnsupportedCertificate",t[t.CertificateRevoked=44]="CertificateRevoked",t[t.CertificateExpired=45]="CertificateExpired",t[t.CertificateUnknown=46]="CertificateUnknown",t[t.IllegalParameter=47]="IllegalParameter",t[t.UnknownCa=48]="UnknownCa",t[t.AccessDenied=49]="AccessDenied",t[t.DecodeError=50]="DecodeError",t[t.DecryptError=51]="DecryptError",t[t.ExportRestriction=60]="ExportRestriction",t[t.ProtocolVersion=70]="ProtocolVersion",t[t.InsufficientSecurity=71]="InsufficientSecurity",t[t.InternalError=80]="InternalError",t[t.UserCanceled=90]="UserCanceled",t[t.NoRenegotiation=100]="NoRenegotiation",t[t.UnsupportedExtension=110]="UnsupportedExtension",t))(wN||{}),KEe=xt("werift-dtls : packages/dtls/src/flight/flight.ts : warn"),rN=xt("werift-dtls : packages/dtls/src/flight/flight.ts : err"),qx=class IN{constructor(e,r,n,i){this.transport=e,this.dtls=r,this.flight=n,this.nextFlight=i}state="PREPARING";static RetransmitCount=10;createPacket(e){let r=QK(this.dtls)(e);return this.dtls.bufferHandshakeCache(r,!0,this.flight),jx(this.dtls)(r.map(i=>({type:22,fragment:i.serialize()})),++this.dtls.recordSequenceNumber)}async transmit(e){let r=0;for(;r<=IN.RetransmitCount;r++){if(this.setState("SENDING"),this.send(e).catch(n=>{rN("fail to send",rN)}),this.setState("WAITING"),this.nextFlight===void 0){this.setState("FINISHED");break}if(await GEe(1e3*((r+1)/2)),this.dtls.flight>=this.nextFlight){this.setState("FINISHED");break}else KEe(this.dtls.sessionId,"retransmit",r,this.dtls.flight)}if(r>IN.RetransmitCount)throw rN(this.dtls.sessionId,"retransmit failed",r),new Error(`over retransmitCount : ${this.flight} ${this.nextFlight}`)}send=e=>Promise.all(e.map(r=>this.transport.send(r)));setState(e){this.state=e}},JEe=class extends qx{constructor(t,e,r){super(t,e,1,3),this.cipher=r}async exec(t){if(this.dtls.flight===1)throw new Error;this.dtls.flight=1;let e=new XK({major:254,minor:253},new kf,Buffer.from([]),Buffer.from([]),HK,[0],t);this.dtls.version=e.clientVersion,this.cipher.localRandom=kf.from(e.random);let r=this.createPacket([e]),n=Buffer.concat(r.map(i=>i.serialize()));await this.transmit([n])}},XEe=xt("werift-dtls : packages/dtls/src/flight/client/flight3.ts : log"),YEe=class extends qx{constructor(t,e){super(t,e,3,5)}async exec(t){if(this.dtls.flight===3)throw new Error;this.dtls.flight=3,this.dtls.handshakeCache=[];let[e]=this.dtls.lastFlight;XEe("dtls version",e.clientVersion),e.cookie=t.cookie,this.dtls.cookie=t.cookie;let r=this.createPacket([e]),n=Buffer.concat(r.map(i=>i.serialize()));await this.transmit([n])}},aR={NULL:0,ECDHE:1},Wx={NULL:0,RSA:1,ECDSA:2,PSK:3},Vx={NULL:0,RSA:1,ECDHE_RSA:2,ECDHE_ECDSA:3,PSK:4,ECDHE_PSK:5},Gx=class{id=0;name;signType;keyType;toString(){return this.name}};oke=xt("werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err"),ske=class extends MEe{keyLength=0;nonceLength=0;ivLength=0;authTagLength=0;nonceImplicitLength=0;nonceExplicitLength=0;clientWriteKey;serverWriteKey;clientNonce;serverNonce;constructor(){super()}get summary(){return zK(this)}init(t,e,r){let n=OEe(t,r,e,this.keyLength,this.ivLength,this.nonceLength,this.hashAlgorithm);this.clientWriteKey=n.clientWriteKey,this.serverWriteKey=n.serverWriteKey,this.clientNonce=n.clientNonce,this.serverNonce=n.serverNonce}encrypt(t,e,r){let n=t===qc.CLIENT,i=n?this.clientNonce:this.serverNonce,o=n?this.clientWriteKey:this.serverWriteKey;if(!i||!o)throw new Error;i.writeUInt16BE(r.epoch,this.nonceImplicitLength),i.writeUIntBE(r.sequenceNumber,this.nonceImplicitLength+2,6);let s=i.slice(this.nonceImplicitLength),a=this.encodeAdditionalBuffer(r,e.length),c=nke(this.blockAlgorithm,o,i,{authTagLength:this.authTagLength});c.setAAD(a,{plaintextLength:e.length});let u=c.update(e),d=c.final(),l=c.getAuthTag();return Buffer.concat([s,u,d,l])}encodeAdditionalBuffer(t,e){let r=Buffer.alloc(13);return r.writeUInt16BE(t.epoch,0),r.writeUintBE(t.sequenceNumber,2,6),r.writeUInt8(t.type,8),r.writeUInt16BE(t.version,9),r.writeUInt16BE(e,11),r}decrypt(t,e,r){let n=t===qc.CLIENT,i=n?this.serverNonce:this.clientNonce,o=n?this.serverWriteKey:this.clientWriteKey;if(!i||!o)throw new Error;e.subarray(0,this.nonceExplicitLength).copy(i,this.nonceImplicitLength);let a=e.subarray(this.nonceExplicitLength,e.length-this.authTagLength),c=e.subarray(e.length-this.authTagLength),u=this.encodeAdditionalBuffer(r,a.length),d=ike(this.blockAlgorithm,o,i,{authTagLength:this.authTagLength});d.setAuthTag(c),d.setAAD(u,{plaintextLength:a.length});let l=d.update(a);try{let f=d.final();return f.length>0?Buffer.concat([l,f]):l}catch(f){throw oke("decrypt failed",f,t,A6(e),r,this.summary),f}}},an={TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:49195,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:49196,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:49199,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:49200,TLS_RSA_WITH_AES_128_GCM_SHA256:156,TLS_RSA_WITH_AES_256_GCM_SHA384:157,TLS_PSK_WITH_AES_128_GCM_SHA256:168,TLS_PSK_WITH_AES_256_GCM_SHA384:169,TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:53249,TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:53250,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:52396,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:52393,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:52392,TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:52395},Yv={K_LEN:16,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},Qv={K_LEN:32,N_MIN:12,N_MAX:12,P_MAX:2**36-31,A_MAX:2**53-1,C_MAX:2**36-15},cz=QEe(),uz=ZEe(),dz=eke(),lz=tke(),fz=rke();cR=class{static type=23},uR=class fh{static type=65281;static spec={type:Rf.types.uint16be,data:Rf.types.uint8};type=fh.type;data=0;constructor(e={}){Object.assign(this,e)}static createEmpty(){return new fh}static deSerialize(e){return new fh((0,Rf.decode)(e,fh.spec))}serialize(){let e=(0,Rf.encode)(this,fh.spec).slice();return Buffer.from(e)}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},wh=class Id{static type=14;static spec={type:Pd.types.uint16be,data:Pd.types.buffer(Pd.types.uint16be)};type=Id.type;data=Buffer.from([]);profiles=[];mki=Buffer.from([0]);constructor(e={}){Object.assign(this,e)}static create(e,r){return new Id({profiles:e,mki:r})}static deSerialize(e){let r=new Id((0,Pd.decode)(e,Id.spec)),n=r.data.readUInt16BE(),i=new Array(n/2);for(let o=0;o<i.length;o++)i[o]=r.data.readUInt16BE(o*2+2);return r.profiles=i,r.mki=r.data.slice(n+2),r}serialize(){let e=Buffer.alloc(2);e.writeUInt16BE(this.profiles.length*2);let r=Buffer.concat([e,...this.profiles.map(i=>{let o=Buffer.alloc(2);return o.writeUInt16BE(i),o}),this.mki]);this.data=r;let n=(0,Pd.encode)(this,Id.spec).slice();return Buffer.from(n)}static fromData(e){let r=Buffer.alloc(4);return r.writeUInt16BE(Id.type),r.writeUInt16BE(e.length,2),Id.deSerialize(Buffer.concat([r,e]))}get extension(){return{type:this.type,data:this.serialize().slice(4)}}},Gk=class cx{constructor(e){this.certificateList=e}msgType=11;messageSeq;static spec={certificateList:Af.types.array(FEe,Af.types.uint24be,"bytes")};static createEmpty(){return new cx(void 0)}static deSerialize(e){return new cx(...Object.values((0,Af.decode)(e,cx.spec)))}serialize(){let e=(0,Af.encode)(this,cx.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Uo(this.msgType,e.length,this.messageSeq,0,e.length,e)}},rJ=class ux{constructor(e=1){this.type=e}static spec={type:Ch.types.uint8};static createEmpty(){return new ux}static deSerialize(e){return new ux(...Object.values((0,Ch.decode)(e,ux.spec)))}serialize(){let e=(0,Ch.encode)(this,ux.spec).slice();return Buffer.from(e)}},nJ=class dx{constructor(e,r){this.algorithm=e,this.signature=r}msgType=15;messageSeq;static spec={algorithm:_d.types.uint16be,signature:_d.types.buffer(_d.types.uint16be)};static createEmpty(){return new dx(void 0,void 0)}static deSerialize(e){let r=(0,_d.decode)(e,dx.spec);return new dx(...Object.values(r))}serialize(){let e=(0,_d.encode)(this,dx.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Uo(this.msgType,e.length,this.messageSeq,0,e.length,e)}},iJ=class lx{constructor(e){this.publicKey=e}msgType=16;messageSeq;static spec={publicKey:Cf.types.buffer(Cf.types.uint8)};static createEmpty(){return new lx(void 0)}static deSerialize(e){let r=(0,Cf.decode)(e,lx.spec);return new lx(...Object.values(r))}serialize(){let e=(0,Cf.encode)(this,lx.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Uo(this.msgType,e.length,this.messageSeq,0,e.length,e)}},EN=class kN{constructor(e){this.verifyData=e}msgType=20;messageSeq;static createEmpty(){return new kN(void 0)}static deSerialize(e){return new kN(e)}serialize(){return this.verifyData}toFragment(){let e=this.serialize();return new Uo(this.msgType,e.length,this.messageSeq,0,e.length,e)}},oJ=class fx{constructor(e,r,n){this.certificateTypes=e,this.signatures=r,this.authorities=n}msgType=13;messageSeq;static spec={certificateTypes:ks.types.array(jEe,ks.types.uint8,"bytes"),signatures:ks.types.array(WEe,ks.types.uint16be,"bytes"),authorities:ks.types.array(qEe,ks.types.uint16be,"bytes")};static createEmpty(){return new fx(void 0,void 0,void 0)}static deSerialize(e){return new fx(...Object.values((0,ks.decode)(e,fx.spec)))}serialize(){let e=(0,ks.encode)(this,fx.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Uo(this.msgType,e.length,this.messageSeq,0,e.length,e)}},sJ=class Ed{constructor(e,r,n,i,o,s){this.serverVersion=e,this.random=r,this.sessionId=n,this.cipherSuite=i,this.compressionMethod=o,this.extensions=s}msgType=2;messageSeq;static spec={serverVersion:C6,random:kf.spec,sessionId:Rs.types.buffer(Rs.types.uint8),cipherSuite:Rs.types.uint16be,compressionMethod:Rs.types.uint8};static createEmpty(){return new Ed(void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){let r=(0,Rs.decode)(e,Ed.spec),n=new Ed(...Object.values(r));return n.serialize().length<e.length?new Ed(...Object.values((0,Rs.decode)(e,{...Ed.spec,extensions:SN}))):n}serialize(){let e=this.extensions===void 0?(0,Rs.encode)(this,Ed.spec).slice():(0,Rs.encode)(this,{...Ed.spec,extensions:SN}).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Uo(this.msgType,e.length,this.messageSeq,0,e.length,e)}},aJ=class px{msgType=14;messageSeq;static spec={};static createEmpty(){return new px}static deSerialize(e){return new px(...Object.values((0,dR.decode)(e,px.spec)))}serialize(){let e=(0,dR.encode)(this,px.spec).slice();return Buffer.from(e)}toFragment(){let e=this.serialize();return new Uo(this.msgType,e.length,this.messageSeq,0,e.length,e)}};uJ=class mx{constructor(e,r,n,i,o,s,a,c){this.ellipticCurveType=e,this.namedCurve=r,this.publicKeyLength=n,this.publicKey=i,this.hashAlgorithm=o,this.signatureAlgorithm=s,this.signatureLength=a,this.signature=c}msgType=12;messageSeq;static spec={ellipticCurveType:Is.types.uint8,namedCurve:Is.types.uint16be,publicKeyLength:Is.types.uint8,publicKey:Is.types.buffer(e=>e.current.publicKeyLength),hashAlgorithm:Is.types.uint8,signatureAlgorithm:Is.types.uint8,signatureLength:Is.types.uint16be,signature:Is.types.buffer(e=>e.current.signatureLength)};static createEmpty(){return new mx(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}static deSerialize(e){let r=(0,Is.decode)(e,mx.spec);return new mx(...Object.values(r))}serialize(){return ake(this,mx.spec)}toFragment(){let e=this.serialize();return new Uo(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Ph=1,Nf=7,cke=[Ph,Nf],dJ=t=>{switch(t){case Ph:case Nf:return 16}},lJ=t=>{switch(t){case Ph:return 14;case Nf:return 12}},uke=xt("werift-rtp : packages/rtp/src/codec/av1.ts"),RN=class pJ{zBit_RtpStartsWithFragment;yBit_RtpEndsWithFragment;w_RtpNumObus;nBit_RtpStartsNewCodedVideoSequence;obu_or_fragment=[];static deSerialize=e=>{let r=new pJ,n=0;if(r.zBit_RtpStartsWithFragment=Ne(e[n],0),r.yBit_RtpEndsWithFragment=Ne(e[n],1),r.w_RtpNumObus=Ne(e[n],2,2),r.nBit_RtpStartsNewCodedVideoSequence=Ne(e[n],4),n++,r.nBit_RtpStartsNewCodedVideoSequence&&r.zBit_RtpStartsWithFragment)throw new Error;[...Array(r.w_RtpNumObus-1).keys()].forEach(o=>{let[s,a]=gJ(e.subarray(n)),c=n+a,u=c+s,d=!1;r.zBit_RtpStartsWithFragment&&o===0&&(d=!0),r.obu_or_fragment.push({data:e.subarray(c,u),isFragment:d}),n+=a+s});let i=!1;return(r.yBit_RtpEndsWithFragment||r.w_RtpNumObus===1&&r.zBit_RtpStartsWithFragment)&&(i=!0),r.obu_or_fragment.push({data:e.subarray(n),isFragment:i}),r};static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nBit_RtpStartsNewCodedVideoSequence===1}static getFrame(e){let r=[],n=e.flatMap(a=>a.obu_or_fragment).reduce((a,c,u)=>(a[u]=c,a),{}),i=Object.keys(n).length;for(let a of Object.keys(n).map(Number)){let c=n[a];if(!c)continue;let{data:u,isFragment:d}=c;if(d){let l=[];for(let f=a;f<i;f++){let p=n[f];if(p.isFragment)l.push(p.data),delete n[f];else break}l.length<=1&&(uke("fragment lost, maybe packet lost"),l=[]),r.push(Buffer.concat(l))}else r.push(u)}let o=r.map(a=>mJ.deSerialize(a)),s=o.pop();return Buffer.concat([...o.map(a=>(a.obu_has_size_field=1,a.serialize())),s.serialize()])}},mJ=class hJ{obu_forbidden_bit;obu_type;obu_extension_flag;obu_has_size_field;obu_reserved_1bit;payload;static deSerialize(e){let r=new hJ,n=0;return r.obu_forbidden_bit=Ne(e[n],0),r.obu_type=yJ[Ne(e[n],1,4)],r.obu_extension_flag=Ne(e[n],5),r.obu_has_size_field=Ne(e[n],6),r.obu_reserved_1bit=Ne(e[n],7),n++,r.payload=e.subarray(n),r}serialize(){let e=new nR(8).set(this.obu_forbidden_bit).set(dke[this.obu_type],4).set(this.obu_extension_flag).set(this.obu_has_size_field).set(this.obu_reserved_1bit).buffer,r=Buffer.alloc(0);return this.obu_has_size_field&&(r=fJ.LEB128.encode(this.payload.length)),Buffer.concat([e,r,this.payload])}};yJ={0:"Reserved",1:"OBU_SEQUENCE_HEADER",2:"OBU_TEMPORAL_DELIMITER",3:"OBU_FRAME_HEADER",4:"OBU_TILE_GROUP",5:"OBU_METADATA",6:"OBU_FRAME",7:"OBU_REDUNDANT_FRAME_HEADER",8:"OBU_TILE_LIST",15:"OBU_PADDING"},dke=Object.entries(yJ).reduce((t,[e,r])=>(t[r]=Number(e),t),{}),vJ=class xJ{f;nri;nalUnitType;s;e;r;nalUnitPayloadType;payload;fragment;static deSerialize(e,r){let n=new xJ,i=0,o=e[i];if(n.f=Ne(o,0),n.nri=Ne(o,1,2),n.nalUnitType=Ne(o,3,5),i++,n.s=Ne(e[i],0),n.e=Ne(e[i],1),n.r=Ne(e[i],2),n.nalUnitPayloadType=Ne(e[i],3,5),i++,0<n.nalUnitType&&n.nalUnitType<kd.stap_a)n.payload=this.packaging(e);else if(n.nalUnitType===kd.stap_a){let s=fke,a=Buffer.alloc(0);for(;s<e.length;){let c=e.readUInt16BE(s);s+=pke,a=Buffer.concat([a,this.packaging(e.subarray(s,s+c))]),s+=c}n.payload=a}else if(n.nalUnitType===kd.fu_a){r||(r=Buffer.alloc(0));let s=e.subarray(i);if(n.fragment=Buffer.concat([r,s]),n.e){let a=new Cd(Buffer.alloc(1)).writeBits(1,0).writeBits(2,n.nri).writeBits(5,n.nalUnitPayloadType),c=Buffer.concat([a.uint8Array,n.fragment]);n.fragment=void 0,n.payload=this.packaging(c)}}return n}static packaging(e){return Buffer.concat([lke,e])}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.nalUnitType===kd.idrSlice||this.nalUnitPayloadType===kd.idrSlice}get isPartitionHead(){return this.nalUnitType===kd.fu_a||this.nalUnitType===kd.fu_b?this.s!==0:!0}},kd={idrSlice:5,stap_a:24,stap_b:25,mtap16:26,mtap24:27,fu_a:28,fu_b:29},lke=Buffer.from([0,0,0,1]),fke=1,pke=2,SJ=class bJ{payload;static deSerialize(e){let r=new bJ;return r.payload=e,r}static isDetectedFinalPacketInSequence(e){return!0}get isKeyframe(){return!0}static createCodecPrivate(e=48e3){return Buffer.concat([Buffer.from("OpusHead"),_r([1,1],[1,2]),bK([2,4,2,1],[312,e,0,0])])}},wJ=class IJ{xBit;nBit;sBit;pid;iBit;lBit;tBit;kBit;mBit;pictureId;payload;size0=0;hBit;ver;pBit;size1=0;size2=0;static deSerialize(e){let r=new IJ,n=0;if(r.xBit=Ne(e[n],0),r.nBit=Ne(e[n],2),r.sBit=Ne(e[n],3),r.pid=Ne(e[n],5,3),n++,r.xBit&&(r.iBit=Ne(e[n],0),r.lBit=Ne(e[n],1),r.tBit=Ne(e[n],2),r.kBit=Ne(e[n],3),n++),r.iBit)if(r.mBit=Ne(e[n],0),r.mBit){let i=Ix(Ne(e[n],1,7)),o=Ix(e[n+1]);r.pictureId=Number.parseInt(i+o,2),n+=2}else r.pictureId=Ne(e[n],1,7),n++;return r.lBit&&n++,(r.lBit||r.kBit)&&(r.tBit,r.kBit,n++),r.payload=e.subarray(n),r.payloadHeaderExist&&(r.size0=Ne(e[n],0,3),r.hBit=Ne(e[n],3),r.ver=Ne(e[n],4,3),r.pBit=Ne(e[n],7),n++,r.size1=e[n],n++,r.size2=e[n]),r}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return this.pBit===0}get isPartitionHead(){return this.sBit===1}get payloadHeaderExist(){return this.sBit===1&&this.pid===0}get size(){return this.payloadHeaderExist?this.size0+8*this.size1+2048*this.size2:0}},EJ=class kJ{iBit;pBit;lBit;fBit;bBit;eBit;vBit;zBit;m;pictureId;tid;u;sid;d;tl0PicIdx;pDiff=[];n_s;y;g;width=[];height=[];n_g=0;pgT=[];pgU=[];pgP_Diff=[];payload;static deSerialize(e){let{p:r,offset:n}=this.parseRtpPayload(e);return r.payload=e.subarray(n),r}static parseRtpPayload(e){let r=new kJ,n=0;if(r.iBit=Ne(e[n],0),r.pBit=Ne(e[n],1),r.lBit=Ne(e[n],2),r.fBit=Ne(e[n],3),r.bBit=Ne(e[n],4),r.eBit=Ne(e[n],5),r.vBit=Ne(e[n],6),r.zBit=Ne(e[n],7),n++,r.iBit)if(r.m=Ne(e[n],0),r.m){let i=Ix(Ne(e[n],1,7)),o=Ix(e[n+1]);r.pictureId=Number.parseInt(i+o,2),n+=2}else r.pictureId=Ne(e[n],1,7),n++;if(r.lBit&&(r.tid=Ne(e[n],0,3),r.u=Ne(e[n],3),r.sid=Ne(e[n],4,3),r.d=Ne(e[n],7),n++,r.fBit===0&&(r.tl0PicIdx=e[n],n++)),r.fBit&&r.pBit)for(;;){r.pDiff=[...r.pDiff,Ne(e[n],0,7)];let i=Ne(e[n],7);if(n++,i===0)break}return r.vBit&&(r.n_s=Ne(e[n],0,3),r.y=Ne(e[n],3),r.g=Ne(e[n],4),n++,r.y&&[...Array(r.n_s+1)].forEach(()=>{r.width.push(e.readUInt16BE(n)),n+=2,r.height.push(e.readUInt16BE(n)),n+=2}),r.g&&(r.n_g=e[n],n++),r.n_g>0&&[...Array(r.n_g).keys()].forEach(i=>{r.pgT.push(Ne(e[n],0,3)),r.pgU.push(Ne(e[n],3));let o=Ne(e[n],4,2);n++,r.pgP_Diff[i]=[],o>0&&[...Array(o)].forEach(()=>{r.pgP_Diff[i].push(e[n]),n++})})),{offset:n,p:r}}static isDetectedFinalPacketInSequence(e){return e.marker}get isKeyframe(){return!!(!this.pBit&&this.bBit&&(!this.sid||!this.lBit))}get isPartitionHead(){return this.bBit&&(!this.lBit||!this.d)}},mke=class{payload;fragment;static deSerialize(t,e){return{}}static isDetectedFinalPacketInSequence(t){return!0}get isKeyframe(){return!0}};gke=["MPEG4/ISO/AVC","VP8","VP9","OPUS","AV1"];vke={setTimeout:(...t)=>{let e=setTimeout(...t);return()=>clearTimeout(e)},setInterval:(...t)=>{let e=setInterval(()=>{t[0]()},...t.slice(1));return()=>clearInterval(e)}};zk=4,zc=class CN{version=2;padding=!1;count=0;type=0;length=0;constructor(e={}){Object.assign(this,e)}static serialize(e,r,n,i){let s=new CN({type:e,count:r,version:2,length:i}).serialize();return Buffer.concat([s,n])}serialize(){let e=new wx(8);return e.set(2,0,this.version),this.padding&&e.set(1,2,1),e.set(5,3,this.count),_r([1,1,2],[e.value,this.type,this.length])}static deSerialize(e){let[r,n,i]=vi(e,[1,1,2]),o=Ne(r,0,2),s=Ne(r,2,1)>0,a=Ne(r,3,5);return new CN({version:o,padding:s,count:a,type:n,length:i})}},pz=class PN{static count=4;count=PN.count;senderSsrc;mediaSsrc;fir=[];constructor(e={}){Object.assign(this,e)}get length(){return Math.floor(this.serialize().length/4-1)}static deSerialize(e){let[r,n]=vi(e,[4,4]),i=[];for(let o=8;o<e.length;o+=8)i.push({ssrc:e.readUInt32BE(o),sequenceNumber:e[o+4]});return new PN({senderSsrc:r,mediaSsrc:n,fir:i})}serialize(){let e=_r([4,4],[this.senderSsrc,this.mediaSsrc]),r=Buffer.alloc(this.fir.length*8);return this.fir.forEach(({ssrc:n,sequenceNumber:i},o)=>{r.writeUInt32BE(n,o*8),r[o*8+4]=i}),Buffer.concat([e,r])}},_x=class _N{static count=1;count=_N.count;length=2;senderSsrc;mediaSsrc;constructor(e={}){Object.assign(this,e)}static deSerialize(e){let[r,n]=vi(e,[4,4]);return new _N({senderSsrc:r,mediaSsrc:n})}serialize(){return _r([4,4],[this.senderSsrc,this.mediaSsrc])}},Tx=class TN{static count=15;length;count=TN.count;senderSsrc;mediaSsrc;uniqueID="REMB";ssrcNum=0;brExp;brMantissa;bitrate;ssrcFeedbacks=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let[r,n,i,o,s]=vi(e,[4,4,4,1,1]),a=Ne(s,0,6),c=(Ne(s,6,2)<<16)+(e[14]<<8)+e[15],u=a>46?18446744073709551615n:BigInt(c)<<BigInt(a),d=[];for(let l=16;l<e.length;l+=4){let f=e.slice(l).readUIntBE(0,4);d.push(f)}return new TN({senderSsrc:r,mediaSsrc:n,uniqueID:_r([4],[i]).toString(),ssrcNum:o,brExp:a,brMantissa:c,ssrcFeedbacks:d,bitrate:u})}serialize(){let e=Buffer.concat([_r([4,4],[this.senderSsrc,this.mediaSsrc]),Buffer.from(this.uniqueID),_r([1],[this.ssrcNum])]),r=new wx(24);r.set(6,0,this.brExp).set(18,6,this.brMantissa);let n=Buffer.concat(this.ssrcFeedbacks.map(o=>_r([4],[o]))),i=Buffer.concat([e,_r([3],[r.value]),n]);return this.length=i.length/4,i}},xke=xt("werift-rtp: /rtcp/psfb/index"),Ih=class DN{static type=206;type=DN.type;feedback;constructor(e={}){Object.assign(this,e)}serialize(){let e=this.feedback.serialize();return zc.serialize(this.type,this.feedback.count,e,this.feedback.length)}static deSerialize(e,r){let n;switch(r.count){case pz.count:n=pz.deSerialize(e);break;case _x.count:n=_x.deSerialize(e);break;case Tx.count:n=Tx.deSerialize(e);break;default:xke("unknown psfb packet",r.count);break}return new DN({feedback:n})}},Eh=class kk{ssrc=0;reports=[];static type=201;type=kk.type;constructor(e={}){Object.assign(this,e)}serialize(){let e=_r([4],[this.ssrc]);return e=Buffer.concat([e,...this.reports.map(r=>r.serialize())]),zc.serialize(kk.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,r){let[n]=vi(e,[4]),i=4,o=[];for(let s=0;s<r;s++)o.push(lR.deSerialize(e.slice(i,i+24))),i+=24;return new kk({ssrc:n,reports:o})}},lR=class AJ{ssrc;fractionLost;packetsLost;highestSequence;jitter;lsr;dlsr;constructor(e={}){Object.assign(this,e)}toJSON(){return{ssrc:this.ssrc,fractionLost:this.fractionLost,packetsLost:this.packetsLost,highestSequence:this.highestSequence,jitter:this.jitter,lsr:this.lsr,dlsr:this.dlsr}}serialize(){return _r([4,1,3,4,4,4,4],[this.ssrc,this.fractionLost,this.packetsLost,this.highestSequence,this.jitter,this.lsr,this.dlsr])}static deSerialize(e){let[r,n,i,o,s,a,c]=vi(e,[4,1,3,4,4,4,4]);return new AJ({ssrc:r,fractionLost:n,packetsLost:i,highestSequence:o,jitter:s,lsr:a,dlsr:c})}},CJ=205,Dx=class BN{static count=1;count=BN.count;header;senderSsrc;mediaSourceSsrc;lost=[];toJSON(){return{lost:this.lost,senderSsrc:this.senderSsrc,mediaSourceSsrc:this.mediaSourceSsrc}}constructor(e={}){Object.assign(this,e),this.header||(this.header=new zc({type:CJ,count:this.count,version:2}))}static deSerialize(e,r){let[n,i]=vi(e,[4,4]),o=[];for(let s=8;s<e.length;s+=4){let[a,c]=vi(e.subarray(s),[2,2]);o.push(a);for(let u=0;u<16;u++)c>>u&1&&o.push(a+u+1)}return new BN({header:r,senderSsrc:n,mediaSourceSsrc:i,lost:o})}serialize(){let e=_r([4,4],[this.senderSsrc,this.mediaSourceSsrc]),r=[];if(this.lost.length>0){let i=this.lost[0],o=0;this.lost.slice(1).forEach(s=>{let a=s-i-1;a>=0&&a<16?o|=1<<a:(r.push(_r([2,2],[i,o])),i=s,o=0)}),r.push(_r([2,2],[i,o]))}let n=Buffer.concat([e,Buffer.concat(r)]);return this.header.length=n.length/4,Buffer.concat([this.header.serialize(),n])}},Ske=xt("werift/rtp/rtcp/rtpfb/twcc"),Bx=class NN{static count=15;count=NN.count;length=2;senderSsrc;mediaSourceSsrc;baseSequenceNumber;packetStatusCount;referenceTime;fbPktCount;packetChunks=[];recvDeltas=[];header;constructor(e={}){Object.assign(this,e),this.header||(this.header=new zc({type:205,count:this.count,version:2}))}static deSerialize(e,r){let[n,i,o,s,a,c]=vi(e,[4,4,2,2,3,1]),u=[],d=[],l=16;for(let p=0;p<s;){let g=Ne(e.slice(l,l+1)[0],0,1),v;switch(g){case 0:{let b=Sh.deSerialize(e.slice(l,l+2));v=b;let C=Math.min(s-p,b.runLength);if(b.packetStatus===1||b.packetStatus===2)for(let D=0;D<C;D++)d.push(new xx({type:b.packetStatus}));p+=C}break;case 1:{let b=_J.deSerialize(e.slice(l,l+2));v=b,b.symbolSize===0&&b.symbolList.forEach(C=>{C===1&&d.push(new xx({type:1}))}),b.symbolSize===1&&b.symbolList.forEach(C=>{(C===1||C===2)&&d.push(new xx({type:C}))}),p+=b.symbolList.length}break}if(!v)throw new Error;l+=2,u.push(v)}let f=l;return d.forEach(p=>{p.type===1&&(p.deSerialize(e.slice(f,f+1)),f++),p.type===2&&(p.deSerialize(e.slice(f,f+2)),f+=2)}),new NN({senderSsrc:n,mediaSourceSsrc:i,baseSequenceNumber:o,packetStatusCount:s,referenceTime:a,fbPktCount:c,recvDeltas:d,packetChunks:u,header:r})}serialize(){let e=_r([4,4,2,2,3,1],[this.senderSsrc,this.mediaSourceSsrc,this.baseSequenceNumber,this.packetStatusCount,this.referenceTime,this.fbPktCount]),r=Buffer.concat(this.packetChunks.map(o=>o.serialize())),n=Buffer.concat(this.recvDeltas.map(o=>{try{return o.serialize()}catch(s){Ske(s?.message);return}}).filter(o=>o)),i=Buffer.concat([e,r,n]);if(this.header.padding&&i.length%4!==0){let o=4-i.length%4,s=Buffer.alloc(o);return s[s.length-1]=s.length,this.header.length=Math.floor((i.length+s.length)/4),Buffer.concat([this.header.serialize(),i,s])}return this.header.length=Math.floor(i.length/4),Buffer.concat([this.header.serialize(),i])}get packetResults(){let e=this.baseSequenceNumber-1,r=this.packetChunks.filter(s=>s instanceof Sh).flatMap(s=>s.results(e)),n=0,o=BigInt(this.referenceTime)*64n;for(let s of r){let a=this.recvDeltas[n];!s.received||!a||(o+=BigInt(a.delta)/1000n,s.delta=a.delta,s.receivedAtMs=Number(o),n++)}return r}},Sh=class PJ{type;packetStatus;runLength;constructor(e={}){Object.assign(this,e),this.type=0}static deSerialize(e){let r=Ne(e[0],1,2),n=(Ne(e[0],3,5)<<8)+e[1];return new PJ({type:0,packetStatus:r,runLength:n})}serialize(){return new nR(16).set(0).set(this.packetStatus,2).set(this.runLength,13).buffer}results(e){let r=this.packetStatus===1||this.packetStatus===2,n=[];for(let i=0;i<=this.runLength;++i)n.push(new NJ({sequenceNumber:++e,received:r}));return n}},_J=class TJ{type;symbolSize;symbolList=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let n=Ne(e[0],1,1),i=[];function o(s,a){for(let c=0;c<s;c++)a(c)}switch(n){case 0:o(6,s=>i.push(Ne(e[0],2+s,1))),o(8,s=>i.push(Ne(e[1],s,1)));break;case 1:o(3,s=>i.push(Ne(e[0],2+s*2,2))),o(4,s=>i.push(Ne(e[1],s*2,2)));break;default:n=(Ne(e[0],2,6)<<8)+e[1]}return new TJ({type:1,symbolSize:n,symbolList:i})}serialize(){let e=Buffer.alloc(2),r=new nR(16).set(1).set(this.symbolSize),n=this.symbolSize===0?1:2;return this.symbolList.forEach(i=>{r.set(i,n)}),e.writeUInt16BE(r.value),e}},xx=class ON{type;delta;constructor(e={}){Object.assign(this,e)}static deSerialize(e){let r,n;if(e.length===1?(r=1,n=250*e[0]):e.length===2&&(r=2,n=250*e.readInt16BE()),r===void 0||n===void 0)throw new Error;return new ON({type:r,delta:n})}deSerialize(e){let r=ON.deSerialize(e);this.delta=r.delta}parsed=!1;parseDelta(){this.delta=Math.floor(this.delta/250),this.delta<0||this.delta>255?(this.delta>32767&&(this.delta=32767),this.delta<-32768&&(this.delta=-32768),this.type||(this.type=2)):this.type||(this.type=1),this.parsed=!0}serialize(){if(this.parsed||this.parseDelta(),this.type===1){let e=Buffer.alloc(1);return e.writeUInt8(this.delta),e}else if(this.type===2){let e=Buffer.alloc(2);return e.writeInt16BE(this.delta),e}throw new Error("errDeltaExceedLimit "+this.delta+" "+this.type)}},DJ=(t=>(t[t.TypeTCCRunLengthChunk=0]="TypeTCCRunLengthChunk",t[t.TypeTCCStatusVectorChunk=1]="TypeTCCStatusVectorChunk",t[t.packetStatusChunkLength=2]="packetStatusChunkLength",t))(DJ||{}),BJ=(t=>(t[t.TypeTCCPacketNotReceived=0]="TypeTCCPacketNotReceived",t[t.TypeTCCPacketReceivedSmallDelta=1]="TypeTCCPacketReceivedSmallDelta",t[t.TypeTCCPacketReceivedLargeDelta=2]="TypeTCCPacketReceivedLargeDelta",t[t.TypeTCCPacketReceivedWithoutDelta=3]="TypeTCCPacketReceivedWithoutDelta",t))(BJ||{}),NJ=class{sequenceNumber=0;delta=0;received=!1;receivedAtMs=0;constructor(t){Object.assign(this,t)}},bke=xt("werift-rtp:packages/rtp/rtcp/rtpfb/index"),Pf=class MN{static type=CJ;type=MN.type;feedback;header;constructor(e={}){Object.assign(this,e)}serialize(){return this.feedback.serialize()}static deSerialize(e,r){let n;switch(r.count){case Dx.count:n=Dx.deSerialize(e,r);break;case Bx.count:n=Bx.deSerialize(e,r);break;default:bke("unknown rtpfb packet",r.count);break}return new MN({feedback:n,header:r})}},Nx=class LN{static type=202;type=LN.type;chunks=[];constructor(e){Object.assign(this,e)}get length(){let e=0;return this.chunks.forEach(r=>e+=r.length),e}serialize(){let e=Buffer.concat(this.chunks.map(r=>r.serialize()));for(;e.length%4;)e=Buffer.concat([e,Buffer.from([0])]);return zc.serialize(this.type,this.chunks.length,e,e.length/4)}static deSerialize(e,r){let n=[];for(let i=0;i<e.length;){let o=P6.deSerialize(e.slice(i));n.push(o),i+=o.length}return new LN({chunks:n})}},P6=class OJ{source;items=[];constructor(e={}){Object.assign(this,e)}get length(){let e=4;return this.items.forEach(r=>e+=r.length),e+=1,e+=mz(e),e}serialize(){let e=Buffer.concat([_r([4],[this.source]),Buffer.concat(this.items.map(n=>n.serialize()))]);return Buffer.concat([e,Buffer.alloc(mz(e.length))])}static deSerialize(e){let r=e.readUInt32BE(),n=[];for(let i=4;i<e.length&&e[i]!==0;){let s=_6.deSerialize(e.slice(i));n.push(s),i+=s.length}return new OJ({source:r,items:n})}},_6=class MJ{type;text;constructor(e){Object.assign(this,e)}get length(){return 2+Buffer.from(this.text).length}serialize(){let e=Buffer.from(this.text);return Buffer.concat([_r([1,1],[this.type,e.length]),e])}static deSerialize(e){let r=e[0],n=e[1],i=e.slice(2,2+n).toString();return new MJ({type:r,text:i})}};_f=class Rk{ssrc=0;senderInfo;reports=[];static type=200;type=Rk.type;constructor(e){Object.assign(this,e)}toJSON(){return{ssrc:this.ssrc,senderInfo:this.senderInfo.toJSON(),reports:this.reports.map(e=>e.toJSON())}}serialize(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.ssrc),e=Buffer.concat([e,this.senderInfo.serialize()]),e=Buffer.concat([e,...this.reports.map(r=>r.serialize())]),zc.serialize(Rk.type,this.reports.length,e,Math.floor(e.length/4))}static deSerialize(e,r){let n=e.readUInt32BE(),i=T6.deSerialize(e.subarray(4,24)),o=24,s=[];for(let c=0;c<r;c++)s.push(lR.deSerialize(e.subarray(o,o+24))),o+=24;return new Rk({ssrc:n,senderInfo:i,reports:s})}},T6=class LJ{ntpTimestamp;rtpTimestamp;packetCount;octetCount;constructor(e={}){Object.assign(this,e)}toJSON(){return{ntpTimestamp:HJ(this.ntpTimestamp),rtpTimestamp:this.rtpTimestamp}}serialize(){return _r([8,4,4,4],[this.ntpTimestamp,this.rtpTimestamp,this.packetCount,this.octetCount])}static deSerialize(e){let[r,n,i,o]=vi(e,[8,4,4,4]);return new LJ({ntpTimestamp:r,rtpTimestamp:n,packetCount:i,octetCount:o})}},HJ=t=>{let[e,r]=vi(_r([8],[t]),[4,4]);return+`${e}.${r}`},wke=xt("werift-rtp:packages/rtp/src/rtcp/rtcp.ts"),UJ=class{static deSerialize(t){let e=0,r=[];for(;e<t.length;){let n=zc.deSerialize(t.subarray(e,e+zk));e+=zk;let i=t.subarray(e);e+=n.length*4,n.padding&&(i=i.subarray(0,i.length-i.subarray(-1)[0]));try{switch(n.type){case _f.type:r.push(_f.deSerialize(i,n.count));break;case Eh.type:r.push(Eh.deSerialize(i,n.count));break;case Nx.type:r.push(Nx.deSerialize(i,n));break;case Pf.type:r.push(Pf.deSerialize(i,n));break;case Ih.type:r.push(Ih.deSerialize(i,n));break;default:break}}catch(o){wke("deSerialize RTCP",o)}}return r}};Rr={sdesMid:"urn:ietf:params:rtp-hdrext:sdes:mid",sdesRTPStreamID:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",repairedRtpStreamId:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",transportWideCC:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",absSendTime:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",dependencyDescriptor:"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension",audioLevelIndication:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",videoOrientation:"urn:3gpp:video-orientation"};Eke=xt("packages/rtp/src/rtp/red/packet.ts"),D6=class QJ{header;blocks=[];static deSerialize(e){let r=e instanceof ArrayBuffer?Buffer.from(e):e,n=new QJ,i=0;return[n.header,i]=HN.deSerialize(r),n.header.fields.forEach(({blockLength:o,timestampOffset:s,blockPT:a})=>{if(o&&s){let c=r.subarray(i,i+o);n.blocks.push({block:c,blockPT:a,timestampOffset:s}),i+=o}else{let c=r.subarray(i);n.blocks.push({block:c,blockPT:a})}}),n}serialize(){this.header=new HN;for(let{timestampOffset:r,blockPT:n,block:i}of this.blocks)r?this.header.fields.push({fBit:1,blockPT:n,blockLength:i.length,timestampOffset:r}):this.header.fields.push({fBit:0,blockPT:n});let e=this.header.serialize();for(let{block:r}of this.blocks)e=Buffer.concat([e,r]);return e}},HN=class ZJ{fields=[];static deSerialize(e){let r=0,n=new ZJ;for(;;){let i={};n.fields.push(i);let o=new Cd(e.subarray(r));if(i.fBit=o.readBits(1),i.blockPT=o.readBits(7),r++,i.fBit===0)break;i.timestampOffset=o.readBits(14),i.blockLength=o.readBits(10),r+=3}return[n,r]}serialize(){let e=Buffer.alloc(0);for(let r of this.fields)try{if(r.timestampOffset&&r.blockLength){let n=new Cd(Buffer.alloc(4)).writeBits(1,r.fBit).writeBits(7,r.blockPT).writeBits(14,r.timestampOffset).writeBits(10,r.blockLength);e=Buffer.concat([e,n.uint8Array])}else{let n=new Cd(Buffer.alloc(1)).writeBits(1,0).writeBits(7,r.blockPT);e=Buffer.concat([e,n.uint8Array])}}catch(n){Eke(n?.message)}return e}},eX=class{constructor(t=1){this.distance=t}cache=[];cacheSize=10;push(t){this.cache.push(t),this.cache.length>this.cacheSize&&this.cache.shift()}build(){let t=new D6,e=this.cache.slice(-(this.distance+1)),r=e.pop();return r&&(e.forEach(n=>{let i=If(r.timestamp,-n.timestamp);i>kke||t.blocks.push({block:n.block,blockPT:n.blockPT,timestampOffset:i})}),t.blocks.push({block:r.block,blockPT:r.blockPT})),t}},kke=16383,tX=class{size=150;sequenceNumbers=[];push(t,e){let r=[];return t.blocks.forEach(({blockPT:i,timestampOffset:o,block:s},a)=>{let c=$n(e.header.sequenceNumber,-(t.blocks.length-(a+1)));o?r.push(new Gc(new Vc({timestamp:If(e.header.timestamp,-o),payloadType:i,ssrc:e.header.ssrc,sequenceNumber:c,marker:!0}),s)):r.push(new Gc(new Vc({timestamp:e.header.timestamp,payloadType:i,ssrc:e.header.ssrc,sequenceNumber:c,marker:!0}),s))}),r.filter(i=>this.sequenceNumbers.includes(i.header.sequenceNumber)?!1:(this.sequenceNumbers.length>this.size&&this.sequenceNumbers.shift(),this.sequenceNumbers.push(i.header.sequenceNumber),!0))}},Rd={OneByte:48862,TwoByte:4096},hz=2,gz=4,yz=8,vz=12,xz=4,Vc=class rX{version=2;padding=!1;paddingSize=0;extension=!1;marker=!1;payloadOffset=0;payloadType=0;sequenceNumber=0;timestamp=0;ssrc=0;csrcLength=0;csrc=[];extensionProfile=Rd.OneByte;extensionLength;extensions=[];constructor(e={}){Object.assign(this,e)}static deSerialize(e){let r=new rX,n=0,i=e[n++];r.version=Ne(i,0,2),r.padding=Ne(i,2)>0,r.extension=Ne(i,3)>0,r.csrcLength=Ne(i,4,4),r.csrc=[...Array(r.csrcLength)].map(()=>{let s=e.readUInt32BE(n);return n+=4,s}),n+=vz-1;let o=e[1];r.marker=Ne(o,0)>0,r.payloadType=Ne(o,1,7),r.sequenceNumber=e.readUInt16BE(hz),r.timestamp=e.readUInt32BE(gz),r.ssrc=e.readUInt32BE(yz);for(let s=0;s<r.csrc.length;s++){let a=vz+s*xz;r.csrc[s]=e.subarray(a).readUInt32BE()}if(r.extension){r.extensionProfile=e.subarray(n).readUInt16BE(),n+=2;let s=e.subarray(n).readUInt16BE()*4;switch(r.extensionLength=s,n+=2,r.extensionProfile){case Rd.OneByte:{let a=n+s;for(;n<a;){if(e[n]===0){n++;continue}let c=e[n]>>4,u=(e[n]&(e[n]^240))+1;if(n++,c===15)break;let d={id:c,payload:e.subarray(n,n+u)};r.extensions=[...r.extensions,d],n+=u}}break;case Rd.TwoByte:{let a=n+s;for(;n<a;){if(e[n]===0){n++;continue}let c=e[n];n++;let u=e[n];n++;let d={id:c,payload:e.subarray(n,n+u)};r.extensions=[...r.extensions,d],n+=u}}break;default:{let a={id:0,payload:e.subarray(n,n+s)};r.extensions=[...r.extensions,a],n+=r.extensions[0].payload.length}break}}return r.payloadOffset=n,r.padding&&(r.paddingSize=e[e.length-1]),r}get serializeSize(){let{csrc:e,extensionProfile:r,extensions:n}=this,i=12+e.length*xz;if(n.length>0||this.extension===!0){let o=4;switch(r){case Rd.OneByte:for(let s of n)o+=1+s.payload.length;break;case Rd.TwoByte:for(let s of n)o+=2+s.payload.length;break;default:o+=n[0].payload.length}i+=Math.floor((o+3)/4)*4}return i}serialize(e){let r=Buffer.alloc(e),n=0,i=new wx(8);i.set(2,0,this.version),this.padding&&i.set(1,2,1),this.extensions.length>0&&(this.extension=!0),this.extension&&i.set(1,3,1),i.set(4,4,this.csrc.length),r.writeUInt8(i.value,n++);let o=new wx(8);this.marker&&o.set(1,0,1),o.set(7,1,this.payloadType),r.writeUInt8(o.value,n++),r.writeUInt16BE(this.sequenceNumber,hz),n+=2,r.writeUInt32BE(this.timestamp,gz),n+=4,r.writeUInt32BE(this.ssrc,yz),n+=4;for(let s of this.csrc)r.writeUInt32BE(s,n),n+=4;if(this.extension){let s=n;r.writeUInt16BE(this.extensionProfile,n),n+=4;let a=n;switch(this.extensionProfile){case Rd.OneByte:for(let d of this.extensions)r.writeUInt8(d.id<<4|d.payload.length-1,n++),d.payload.copy(r,n),n+=d.payload.length;break;case Rd.TwoByte:for(let d of this.extensions)r.writeUInt8(d.id,n++),r.writeUInt8(d.payload.length,n++),d.payload.copy(r,n),n+=d.payload.length;break;default:{let d=this.extensions[0].payload.length;if(d%4!=0)throw new Error;this.extensions[0].payload.copy(r,n),n+=d}}let c=n-a,u=Math.trunc((c+3)/4)*4;r.writeUInt16BE(Math.trunc(u/4),s+2);for(let d=0;d<u-c;d++)r.writeUInt8(0,n),n++}return this.payloadOffset=n,r}},Gc=class UN{constructor(e,r){this.header=e,this.payload=r}get serializeSize(){return this.header.serializeSize+this.payload.length}clone(){return new UN(new Vc({...this.header}),this.payload)}serialize(){let e=this.header.serialize(this.header.serializeSize+this.payload.length),{payloadOffset:r}=this.header;if(this.payload.copy(e,r),this.header.padding){let n=Buffer.alloc(this.header.paddingSize);n.writeUInt8(this.header.paddingSize,this.header.paddingSize-1),e=Buffer.concat([e,n])}return e}static deSerialize(e){let r=Vc.deSerialize(e);return new UN(r,e.subarray(r.payloadOffset,e.length-r.paddingSize))}clear(){this.payload=null}};oX=class{constructor(t,e,r,n){this.srtpSessionKey=t,this.srtpSessionSalt=e,this.srtcpSessionKey=r,this.srtcpSessionSalt=n}encryptRtp(t,e,r){return Buffer.from([])}decryptRtp(t,e,r){return[]}encryptRTCP(t,e){return Buffer.from([])}decryptRTCP(t){return[]}},Tf=class extends Error{constructor(t){super(t),this.name="SrtpAuthenticationError"}},Iz=12,Ake=8;Cke=class extends oX{constructor(t,e,r,n,i,o){super(t,e,r,n),this.srtpSessionAuthTag=i,this.srtcpSessionAuthTag=o}authTagLength=10;encryptRtp(t,e,r){let n=t.serialize(t.serializeSize),i=this.generateCounter(t.sequenceNumber,r,t.ssrc,this.srtpSessionSalt),s=Sz("aes-128-ctr",this.srtpSessionKey,i).update(e),a=this.generateSrtpAuthTag(r,n,s);return Buffer.concat([n,s,a])}decryptRtp(t,e,r=N6(t,this.authTagLength)){let n=t.length-this.authTagLength,i=t.subarray(0,n),o=t.subarray(n),s=this.generateSrtpAuthTag(e,i.subarray(0,r.payloadOffset),i.subarray(r.payloadOffset));kz(o,s,"Failed to authenticate SRTP packet");let a=this.generateCounter(r.sequenceNumber,e,r.ssrc,this.srtpSessionSalt),c=bz("aes-128-ctr",this.srtpSessionKey,a),u=i.subarray(r.payloadOffset),d=c.update(u),l=Buffer.concat([i.subarray(0,r.payloadOffset),d]);return[l,cX(r,l,"Failed to authenticate SRTP packet")]}encryptRTCP(t,e){let r=Buffer.from(t),n=r.readUInt32BE(4),i=this.generateCounter(e&65535,e>>16,n,this.srtcpSessionSalt);Sz("aes-128-ctr",this.srtcpSessionKey,i).update(r.slice(8)).copy(r,8),r=Buffer.concat([r,Buffer.alloc(4)]),r.writeUInt32BE(e,r.length-4),r[r.length-4]|=128;let a=this.generateSrtcpAuthTag(r);return r=Buffer.concat([r,a]),r}decryptRTCP(t){let e=sX(t,this.authTagLength,Ez),r=t.length-(this.authTagLength+Ez),n=t.subarray(0,t.length-this.authTagLength),i=t.subarray(t.length-this.authTagLength),o=this.generateSrtcpAuthTag(n);kz(i,o,"Failed to authenticate SRTCP packet");let s=Buffer.from(t).slice(0,r);if(t[r]>>>7===0)return[s,e];let c=t.readUInt32BE(r);c&=~(1<<31);let u=t.readUInt32BE(4),d=this.generateCounter(c&65535,c>>16,u,this.srtcpSessionSalt);return bz("aes-128-ctr",this.srtcpSessionKey,d).update(s.subarray(8)).copy(s,8),[s,e]}generateSrtcpAuthTag(t){return wz("sha1",this.srtcpSessionAuthTag).update(t).digest().slice(0,10)}generateCounter(t,e,r,n){let i=Buffer.alloc(16);i.writeUInt32BE(r,4),i.writeUInt32BE(e,8),i.writeUInt32BE(Number(BigInt(t)<<16n),12);for(let o=0;o<n.length;o++)i[o]^=n[o];return i}generateSrtpAuthTag(t,...e){let r=wz("sha1",this.srtpSessionAuthTag),n=Buffer.alloc(4);n.writeUInt32BE(t);for(let i of e)r.update(i);return r.update(n).digest().subarray(0,10)}},Ez=4;Pke=class extends oX{aeadAuthTagLen=16;rtpIvWriter=vx([2,4,4,2],!0);rtcpIvWriter=vx([2,4,2,4],!0);aadWriter=vx([4],!0);constructor(t,e,r,n){super(t,e,r,n)}encryptRtp(t,e,r){let n=t.serialize(t.serializeSize),i=this.rtpInitializationVector(t,r),o=Rz("aes-128-gcm",this.srtpSessionKey,i);o.setAAD(n);let s=o.update(e);o.final();let a=o.getAuthTag();return Buffer.concat([n,s,a])}decryptRtp(t,e,r=N6(t,this.aeadAuthTagLen)){let n=t.subarray(0,r.payloadOffset),i=t.length-this.aeadAuthTagLen,o=t.subarray(i),s=Buffer.from([]);s=AN(s,t.length-this.aeadAuthTagLen),n.copy(s);let a=this.rtpInitializationVector(r,e),c=t.slice(r.payloadOffset,i),u=Az("aes-128-gcm",this.srtpSessionKey,a);u.setAAD(n),u.setAuthTag(o);let d=u.update(c);return Pz(u,"SRTP"),d.copy(s,r.payloadOffset),[s,cX(r,s,"Failed to authenticate SRTP packet")]}encryptRTCP(t,e){let r=t.readUInt32BE(4),n=t.length+this.aeadAuthTagLen,i=Buffer.from([]);i=AN(i,n+iN),t.slice(0,8).copy(i);let o=this.rtcpInitializationVector(r,e),s=this.rtcpAdditionalAuthenticatedData(t,e),a=Rz("aes-128-gcm",this.srtcpSessionKey,o);a.setAAD(s);let c=a.update(t.slice(8));return a.final(),c.copy(i,8),a.getAuthTag().copy(i,8+c.length),s.slice(8,12).copy(i,n),i}decryptRTCP(t){let e=sX(t,this.aeadAuthTagLen,iN),r=t.length-iN,n=r-this.aeadAuthTagLen,i=t.readUInt32BE(4),o=t.readUInt32BE(r),s=o>>>31===1,a=o&~(Cz<<24),c=this.rtcpInitializationVector(i,a),u=s?Buffer.concat([t.subarray(0,8),t.subarray(r)]):Buffer.concat([t.subarray(0,n),t.subarray(r)]),d=s?t.slice(8,n):Buffer.alloc(0),l=s?Buffer.alloc(n):Buffer.from(t.subarray(0,n));s&&t.slice(0,8).copy(l);let f=Az("aes-128-gcm",this.srtcpSessionKey,c);f.setAAD(u),f.setAuthTag(t.subarray(n,r));let p=f.update(d);return Pz(f,"SRTCP"),s&&p.copy(l,8),[l,e]}rtpInitializationVector(t,e){let r=this.rtpIvWriter([0,t.ssrc,e,t.sequenceNumber]);for(let n=0;n<r.length;n++)r[n]^=this.srtpSessionSalt[n];return r}rtcpInitializationVector(t,e){let r=this.rtcpIvWriter([0,t,0,e]);for(let n=0;n<r.length;n++)r[n]^=this.srtcpSessionSalt[n];return r}rtcpAdditionalAuthenticatedData(t,e){let r=Buffer.concat([t.subarray(0,8),this.aadWriter([e])]);return r[8]|=Cz,r}},iN=4,Cz=128;uX=class{constructor(t,e,r){this.masterKey=t,this.masterSalt=e,this.profile=r;{let n=14-e.length;n>0&&(this.masterSalt=Buffer.concat([e,Buffer.alloc(n)]))}switch(this.srtpSessionKey=this.generateSessionKey(0),this.srtpSessionSalt=this.generateSessionSalt(2),this.srtpSessionAuthTag=this.generateSessionAuthTag(1),this.srtpSessionAuth=nN("sha1",this.srtpSessionAuthTag),this.srtcpSessionKey=this.generateSessionKey(3),this.srtcpSessionSalt=this.generateSessionSalt(5),this.srtcpSessionAuthTag=this.generateSessionAuthTag(4),this.srtcpSessionAuth=nN("sha1",this.srtcpSessionAuthTag),r){case Ph:this.cipher=new Cke(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt,this.srtpSessionAuthTag,this.srtcpSessionAuthTag);break;case Nf:this.cipher=new Pke(this.srtpSessionKey,this.srtpSessionSalt,this.srtcpSessionKey,this.srtcpSessionSalt);break}}srtpSSRCStates={};srtpSessionKey;srtpSessionSalt;srtpSessionAuthTag;srtpSessionAuth;srtcpSSRCStates={};srtcpSessionKey;srtcpSessionSalt;srtcpSessionAuthTag;srtcpSessionAuth;cipher;generateSessionKey(t){let e=Buffer.from(this.masterSalt),r=Buffer.from([t,0,0,0,0,0,0]);for(let i=r.length-1,o=e.length-1;i>=0;i--,o--)e[o]=e[o]^r[i];e=Buffer.concat([e,Buffer.from([0,0])]);let n=new Ak.default.AES(this.masterKey);return Buffer.from(n.encrypt(e))}generateSessionSalt(t){let e=Buffer.from(this.masterSalt),r=Buffer.from([t,0,0,0,0,0,0]);for(let i=r.length-1,o=e.length-1;i>=0;i--,o--)e[o]=e[o]^r[i];e=Buffer.concat([e,Buffer.from([0,0])]);let n=new Ak.default.AES(this.masterKey);return e=Buffer.from(n.encrypt(e)),e.subarray(0,14)}generateSessionAuthTag(t){let e=Buffer.from(this.masterSalt),r=Buffer.from([t,0,0,0,0,0,0]);for(let s=r.length-1,a=e.length-1;s>=0;s--,a--)e[a]=e[a]^r[s];let n=Buffer.concat([e,Buffer.from([0,0])]),i=Buffer.concat([e,Buffer.from([0,1])]),o=new Ak.default.AES(this.masterKey);return n=Buffer.from(o.encrypt(n)),i=Buffer.from(o.encrypt(i)),Buffer.concat([n,i.subarray(0,4)])}getSrtpSsrcState(t){let e=this.srtpSSRCStates[t];return e||(e={ssrc:t,rolloverCounter:0,lastSequenceNumber:0},this.srtpSSRCStates[t]=e,e)}getSrtcpSsrcState(t){let e=this.srtcpSSRCStates[t];return e||(e={srtcpIndex:0,ssrc:t},this.srtcpSSRCStates[t]=e,e)}updateRolloverCount(t,e){e.rolloverHasProcessed?t===0?e.lastSequenceNumber>Zv&&e.rolloverCounter++:e.lastSequenceNumber<Zv&&t>_z-Zv?e.rolloverCounter>0&&e.rolloverCounter--:t<Zv&&e.lastSequenceNumber>_z-Zv&&e.rolloverCounter++:e.rolloverHasProcessed=!0,e.lastSequenceNumber=t}generateSrtpAuthTag(t,e){this.srtpSessionAuth=nN("sha1",this.srtpSessionAuthTag);let r=Buffer.alloc(4);return r.writeUInt32BE(e),this.srtpSessionAuth.update(t).update(r).digest().slice(0,10)}index(t){let e=this.srtcpSSRCStates[t];return e?e.srtcpIndex:0}setIndex(t,e){let r=this.getSrtcpSsrcState(t);r.srtcpIndex=e%2147483647}},Zv=100,_z=65535,_ke=class extends uX{constructor(t,e,r){super(t,e,r)}encryptRTCP(t){let e=t.readUInt32BE(4),r=this.getSrtcpSsrcState(e);return r.srtcpIndex++,r.srtcpIndex>>Tke&&(r.srtcpIndex=0),this.cipher.encryptRTCP(t,r.srtcpIndex)}decryptRTCP(t){return this.cipher.decryptRTCP(t)}},Tke=2147483647,dX=class{constructor(t){this.ContextCls=t}localContext;remoteContext;onData;start(t,e,r,n,i){this.localContext=new this.ContextCls(t,e,i),this.remoteContext=new this.ContextCls(r,n,i)}},lX=class extends dX{constructor(t){super(_ke),this.config=t,this.start(t.keys.localMasterKey,t.keys.localMasterSalt,t.keys.remoteMasterKey,t.keys.remoteMasterSalt,t.profile)}decrypt=t=>{let[e]=this.remoteContext.decryptRTCP(t);return e};encrypt(t){return this.localContext.encryptRTCP(t)}},Dke=class extends uX{constructor(t,e,r){super(t,e,r)}encryptRtp(t,e){let r=this.getSrtpSsrcState(e.ssrc);return this.updateRolloverCount(e.sequenceNumber,r),this.cipher.encryptRtp(e,t,r.rolloverCounter)}decryptRtp(t){let e=N6(t,this.rtpAuthTagLength),r=this.srtpSSRCStates[e.ssrc],n=r?{...r}:{ssrc:e.ssrc,rolloverCounter:0,lastSequenceNumber:0};this.updateRolloverCount(e.sequenceNumber,n);let i=this.cipher.decryptRtp(t,n.rolloverCounter,e);return r?Object.assign(r,n):this.srtpSSRCStates[e.ssrc]=n,i}get rtpAuthTagLength(){return this.profile===Nf?16:10}},fX=class extends dX{constructor(t){super(Dke),this.config=t,this.start(t.keys.localMasterKey,t.keys.localMasterSalt,t.keys.remoteMasterKey,t.keys.remoteMasterSalt,t.profile)}decrypt=t=>{let[e]=this.remoteContext.decryptRtp(t);return e};encrypt(t,e){return this.localContext.encryptRtp(t,e)}},Bke=class{constructor(t){this.props=t}sequenceNumber=b6();timestamp=jk();create(t){this.sequenceNumber=$n(this.sequenceNumber,1);let e=this.props.between*this.props.clockRate/1e3;this.timestamp=If(this.timestamp,e);let r=new Vc({sequenceNumber:this.sequenceNumber,timestamp:Number(this.timestamp),payloadType:96,extension:!0,marker:!1,padding:!1});return new Gc(r,t)}},yi=xt("werift-dtls : packages/dtls/src/flight/client/flight5.ts : log"),Nke=class extends qx{constructor(t,e,r,n){super(t,e,5,7),this.cipher=r,this.srtp=n}handleHandshake(t){this.dtls.bufferHandshakeCache([t],!1,4);let e=(()=>{switch(t.msg_type){case 2:return sJ.deSerialize(t.fragment);case 11:return Gk.deSerialize(t.fragment);case 12:return uJ.deSerialize(t.fragment);case 13:return oJ.deSerialize(t.fragment);case 14:return aJ.deSerialize(t.fragment)}})();e&&_h[e.msgType]({dtls:this.dtls,cipher:this.cipher,srtp:this.srtp})(e)}async exec(){if(this.dtls.flight===5){yi(this.dtls.sessionId,"flight5 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=5;let t=this.dtls.requestedCertificateTypes.length>0;yi(this.dtls.sessionId,"send flight5",t);let e=[t&&this.sendCertificate(),this.sendClientKeyExchange(),t&&this.sendCertificateVerify(),this.sendChangeCipherSpec(),this.sendFinished()].filter(r=>r);this.dtls.lastMessage=e,await this.transmit(e)}sendCertificate(){let t=new Gk([Buffer.from(this.cipher.localCert)]),e=this.createPacket([t]);return Buffer.concat(e.map(n=>n.serialize()))}sendClientKeyExchange(){if(!this.cipher.localKeyPair)throw new Error;let t=new iJ(this.cipher.localKeyPair.publicKey),e=this.createPacket([t]),r=Buffer.concat(e.map(a=>a.serialize())),n=this.cipher.localKeyPair,i=this.cipher.remoteKeyPair;if(!i.publicKey)throw new Error("not exist");let o=jK(i.publicKey,n.privateKey,n.curve);yi(this.dtls.sessionId,"extendedMasterSecret",this.dtls.options.extendedMasterSecret,this.dtls.remoteExtendedMasterSecret);let s=Buffer.concat(this.dtls.sortedHandshakeCache.map(a=>a.serialize()));return this.cipher.masterSecret=this.dtls.options.extendedMasterSecret&&this.dtls.remoteExtendedMasterSecret?WK(o,s):qK(o,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize()),this.cipher.cipher=ZK(this.cipher.cipherSuite),this.cipher.cipher.init(this.cipher.masterSecret,this.cipher.remoteRandom.serialize(),this.cipher.localRandom.serialize()),yi(this.dtls.sessionId,"cipher",this.cipher.cipher.summary),r}sendCertificateVerify(){let t=Buffer.concat(this.dtls.sortedHandshakeCache.map(s=>s.serialize())),e=this.cipher.signatureData(t,"sha256"),r=(()=>{switch(this.cipher.signatureHashAlgorithm?.signature){case Ea.ecdsa_3:return vN.ecdsa_secp256r1_sha256;case Ea.rsa_1:return vN.rsa_pkcs1_sha256}})();if(!r)throw new Error;yi(this.dtls.sessionId,"signatureScheme",this.cipher.signatureHashAlgorithm?.signature,r);let n=new nJ(r,e),i=this.createPacket([n]);return Buffer.concat(i.map(s=>s.serialize()))}sendChangeCipherSpec(){let t=rJ.createEmpty().serialize(),e=jx(this.dtls)([{type:20,fragment:t}],++this.dtls.recordSequenceNumber);return Buffer.concat(e.map(n=>n.serialize()))}sendFinished(){let t=Buffer.concat(this.dtls.sortedHandshakeCache.map(o=>o.serialize())),e=this.cipher.verifyData(t),r=new EN(e);this.dtls.epoch=1;let[n]=this.createPacket([r]);this.dtls.recordSequenceNumber=0;let i=this.cipher.encryptPacket(n).serialize();return yi(this.dtls.sessionId,"finished",this.cipher.cipher.summary),i}},_h={};_h[2]=({cipher:t,srtp:e,dtls:r})=>n=>{yi(r.sessionId,"serverHello",n.cipherSuite),t.remoteRandom=kf.from(n.random),t.cipherSuite=n.cipherSuite,yi(r.sessionId,"selected cipherSuite",t.cipherSuite),n.extensions&&n.extensions.forEach(i=>{switch(i.type){case wh.type:{let o=wh.fromData(i.data),s=Ax.findMatchingSRTPProfile(o.profiles,r.options.srtpProfiles||[]);if(yi(r.sessionId,"selected srtp profile",s),s==null)return;e.srtpProfile=s}break;case cR.type:r.remoteExtendedMasterSecret=!0;break;case uR.type:yi(r.sessionId,"RenegotiationIndication");break}})};_h[11]=({cipher:t,dtls:e})=>r=>{yi(e.sessionId,"handshake certificate",r),t.remoteCertificate=r.certificateList[0]};_h[12]=({cipher:t,dtls:e})=>r=>{if(!t.localRandom||!t.remoteRandom)throw new Error;yi(e.sessionId,"ServerKeyExchange",r),yi(e.sessionId,"selected curve",r.namedCurve),t.remoteKeyPair={curve:r.namedCurve,publicKey:r.publicKey},t.localKeyPair=tJ(r.namedCurve)};_h[13]=({dtls:t})=>e=>{yi(t.sessionId,"certificate_request",e),t.requestedCertificateTypes=e.certificateTypes,t.requestedSignatureAlgorithms=e.signatures};_h[14]=({dtls:t})=>e=>{yi(t.sessionId,"server_hello_done",e)};pX=class hx{constructor(e,r){this.serverVersion=e,this.cookie=r}msgType=3;messageSeq;static spec={serverVersion:C6,cookie:Df.types.buffer(Df.types.uint8)};static createEmpty(){return new hx(void 0,void 0)}static deSerialize(e){return new hx(...Object.values((0,Df.decode)(e,hx.spec)))}serialize(){let e=(0,Df.encode)(this,hx.spec).slice();return Buffer.from(e)}get version(){return{major:255-this.serverVersion.major,minor:255-this.serverVersion.minor}}toFragment(){let e=this.serialize();return new Uo(this.msgType,e.length,this.messageSeq,0,e.length,e)}},Mke=xt("werift-dtls : packages/dtls/src/context/dtls.ts : log"),Tz=class{constructor(t,e){this.options=t,this.sessionType=e}version={major:254,minor:253};lastFlight=[];lastMessage=[];recordSequenceNumber=0;sequenceNumber=0;epoch=0;flight=0;handshakeCache={};cookie;requestedCertificateTypes=[];requestedSignatureAlgorithms=[];remoteExtendedMasterSecret=!1;get sessionId(){return this.cookie?this.cookie.toString("hex").slice(0,10):""}get sortedHandshakeCache(){return Object.entries(this.handshakeCache).sort(([t],[e])=>Number(t)-Number(e)).flatMap(([,{data:t}])=>t.sort((e,r)=>e.message_seq-r.message_seq))}checkHandshakesExist=t=>!t.find(e=>this.sortedHandshakeCache.find(r=>r.msg_type===e)==null);bufferHandshakeCache(t,e,r){this.handshakeCache[r]||(this.handshakeCache[r]={data:[],isLocal:e,flight:r});let n=t.filter(i=>{let o=this.handshakeCache[r].data.find(s=>s.msg_type===i.msg_type);return o?(Mke(this.sessionId,"exist",o.summary,e,r),!1):!0});this.handshakeCache[r].data=[...this.handshakeCache[r].data,...n]}},Lke=class{constructor(t){this.socket=t}send=t=>this.socket.send(t)},$N=class Hc{static type=10;static spec={type:Ia.types.uint16be,data:Ia.types.array(Ia.types.uint16be,Ia.types.uint16be,"bytes")};type=Hc.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new Hc}static fromData(e){return new Hc({type:Hc.type,data:(0,Ia.decode)(e,Hc.spec.data)})}static deSerialize(e){return new Hc((0,Ia.decode)(e,Hc.spec))}serialize(){return Buffer.from((0,Ia.encode)(this,Hc.spec).slice())}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},FN=class Ad{static type=13;static spec={type:wa.types.uint16be,data:wa.types.array({hash:wa.types.uint8,signature:wa.types.uint8},wa.types.uint16be,"bytes")};type=Ad.type;data=[];constructor(e={}){Object.assign(this,e)}static createEmpty(){return new Ad}static deSerialize(e){return new Ad((0,wa.decode)(e,Ad.spec))}serialize(){let e=(0,wa.encode)(this,Ad.spec).slice();return Buffer.from(e)}static fromData(e){let r=Buffer.alloc(2);return r.writeUInt16BE(Ad.type),Ad.deSerialize(Buffer.concat([r,e]))}get extension(){return{type:this.type,data:this.serialize().slice(2)}}},Dz=class Ck{constructor(e,r){this.level=e,this.description=r}static spec={level:Bf.types.uint8,description:Bf.types.uint8};static deSerialize(e){return new Ck(...Object.values((0,Bf.decode)(e,Ck.spec)))}serialize(){let e=(0,Bf.encode)(this,Ck.spec).slice();return Buffer.from(e)}},Bz=xt("werift-dtls : packages/dtls/record/receive.ts : log"),oN=xt("werift-dtls : packages/dtls/record/receive.ts : err"),Hke=t=>{let e=0,r=[];for(;t.length>e;){let n=t.readUInt16BE(e+11);if(t.length<e+(12+n))break;let i=YK.deSerialize(t.subarray(e));r.push(i),e+=13+n}return r},Uke=(t,e)=>r=>{switch(r.recordLayerHeader.contentType){case 20:return Bz(t.sessionId,"change cipher spec"),[{type:20,data:void 0}];case 22:{let i=r.fragment;try{r.recordLayerHeader.epoch>0&&(Bz(t.sessionId,"decrypt handshake"),i=e.decryptPacket(r))}catch(o){throw oN(t.sessionId,"decrypt failed",o),o}try{let o=0,s=[];for(;i.length>o;){let a=Uo.deSerialize(i.subarray(o));s.push({type:22,data:a}),o+=a.fragment_length+12}return s}catch(o){throw oN(t.sessionId,"decSerialize failed",o,i),o}}case 23:return[{type:23,data:e.decryptPacket(r)}];case 21:{let i=Dz.deSerialize(r.fragment);if(wN[i.description]==null){let o=e.decryptPacket(r);i=Dz.deSerialize(o)}if(oN(t.sessionId,"ContentType.alert",i,wN[i.description],"flight",t.flight,"lastFlight",t.lastFlight),i.level>1)throw new Error("alert fatal error");return[{type:21,data:void 0}]}default:return[{type:21,data:void 0}]}},Nz=xt("werift-dtls : packages/dtls/src/socket.ts : log"),Oz=xt("werift-dtls : packages/dtls/src/socket.ts : err"),O6=class{constructor(t,e){this.options=t,this.sessionType=e,this.dtls=new Tz(this.options,this.sessionType),this.cipher=new Rx(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.transport=new Lke(this.options.transport),this.setupExtensions(),this.transport.socket.onData=this.udpOnMessage}onConnect=new qe;onData=new qe;onError=new qe;onClose=new qe;transport;cipher;dtls;srtp=new Ax;connected=!1;extensions=[];onHandleHandshakes;bufferFragmentedHandshakes=[];renegotiation(){Nz("renegotiation",this.sessionType),this.connected=!1,this.cipher=new Rx(this.sessionType,this.options.cert,this.options.key,this.options.signatureHash),this.dtls=new Tz(this.options,this.sessionType),this.srtp=new Ax,this.extensions=[],this.bufferFragmentedHandshakes=[]}udpOnMessage=t=>{let e=Hke(t);for(let r of e)try{let n=Uke(this.dtls,this.cipher)(r);for(let i of n)switch(i.type){case 22:{let o=i.data,s=this.handleFragmentHandshake([o]),a=Object.values(s.reduce((c,u)=>(c[u.msg_type]||(c[u.msg_type]=[]),c[u.msg_type].push(u),c),{})).map(c=>Uo.assemble(c)).sort((c,u)=>c.msg_type-u.msg_type);this.onHandleHandshakes(a).catch(c=>{Oz(this.dtls.sessionId,"onHandleHandshakes error",c),this.onError.execute(c)})}break;case 23:this.onData.execute(i.data);break;case 21:this.onClose.execute();break}}catch(n){Oz(this.dtls.sessionId,"catch udpOnMessage error",n)}};setupExtensions(){if(Nz(this.dtls.sessionId,"support srtpProfiles",this.options.srtpProfiles),this.options.srtpProfiles&&this.options.srtpProfiles.length>0){let t=wh.create(this.options.srtpProfiles,Buffer.from([0]));this.extensions.push(t.extension)}{let t=$N.createEmpty();t.data=E6,this.extensions.push(t.extension)}{let t=FN.createEmpty();t.data=R6,this.extensions.push(t.extension)}this.options.extendedMasterSecret&&this.extensions.push({type:cR.type,data:Buffer.alloc(0)});{let t=uR.createEmpty();this.extensions.push(t.extension)}}waitForReady=t=>new Promise(async(e,r)=>{for(let n=0;n<10;n++)if(t()){e();break}else await Oke(100*n);r("waitForReady timeout")});handleFragmentHandshake(t){let e=t.filter(r=>r.fragment_length!==r.length?(this.bufferFragmentedHandshakes.push(r),!1):!0);if(this.bufferFragmentedHandshakes.length>1){let[r]=this.bufferFragmentedHandshakes.slice(-1);r.fragment_offset+r.fragment_length===r.length&&(e=[...this.bufferFragmentedHandshakes,...e],this.bufferFragmentedHandshakes=[])}return e}send=async t=>{let e=jx(this.dtls)([{type:23,fragment:t}],++this.dtls.recordSequenceNumber)[0];await this.transport.send(this.cipher.encryptPacket(e).serialize())};close(){this.transport.socket.close()}extractSessionKeys(t,e){let r=this.exportKeyingMaterial("EXTRACTOR-dtls_srtp",t*2+e*2),{clientKey:n,serverKey:i,clientSalt:o,serverSalt:s}=(0,wf.decode)(r,{clientKey:wf.types.buffer(t),serverKey:wf.types.buffer(t),clientSalt:wf.types.buffer(e),serverSalt:wf.types.buffer(e)});return this.sessionType===qc.CLIENT?{localKey:n,localSalt:o,remoteKey:i,remoteSalt:s}:{localKey:i,localSalt:s,remoteKey:n,remoteSalt:o}}exportKeyingMaterial(t,e){return DEe(t,e,this.cipher.masterSecret,this.cipher.localRandom.serialize(),this.cipher.remoteRandom.serialize(),this.sessionType===qc.CLIENT)}get remoteCertificate(){return this.cipher.remoteCertificate}},sN=xt("werift-dtls : packages/dtls/src/client.ts : log"),jN=class extends O6{constructor(t){super(t,qc.CLIENT),this.onHandleHandshakes=this.handleHandshakes,sN(this.dtls.sessionId,"start client")}async connect(){await new JEe(this.transport,this.dtls,this.cipher).exec(this.extensions)}flight5;handleHandshakes=async t=>{sN(this.dtls.sessionId,"handleHandshakes",t.map(e=>e.msg_type));for(let e of t)switch(e.msg_type){case 3:{let r=pX.deSerialize(e.fragment);await new YEe(this.transport,this.dtls).exec(r)}break;case 2:{if(this.connected)return;this.flight5=new Nke(this.transport,this.dtls,this.cipher,this.srtp),this.flight5.handleHandshake(e)}break;case 11:case 12:case 13:await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(e);break;case 14:{await this.waitForReady(()=>!!this.flight5),this.flight5?.handleHandshake(e);let r=[11,12,this.options.certificateRequest&&13].filter(n=>typeof n=="number");await this.waitForReady(()=>this.dtls.checkHandshakesExist(r)),await this.flight5?.exec()}break;case 20:this.dtls.flight=7,this.connected=!0,this.onConnect.execute(),sN(this.dtls.sessionId,"dtls connected");break}}},Sa=xt("werift-dtls : packages/dtls/flight/server/flight2.ts : log"),Fke=(t,e,r,n)=>i=>{Sa("dtls version",i.clientVersion),e.flight=2,e.recordSequenceNumber=0,e.sequenceNumber=0,i.extensions.forEach(l=>{switch(l.type){case $N.type:{let f=$N.fromData(l.data).data;Sa(e.sessionId,"curves",f);let p=f.filter(g=>E6.includes(g))[0];r.namedCurve=p,Sa(e.sessionId,"curve selected",r.namedCurve)}break;case FN.type:{if(!r.signatureHashAlgorithm)throw new Error("need to set certificate");let f=FN.fromData(l.data).data;Sa(e.sessionId,"hash,signature",f);let p=f.find(v=>v.signature===r.signatureHashAlgorithm?.signature)?.signature,g=f.find(v=>v.hash===r.signatureHashAlgorithm?.hash)?.hash;if(p==null||g==null)throw new Error("invalid signatureHash")}break;case wh.type:{if(!e.options?.srtpProfiles||e.options.srtpProfiles.length===0)return;let f=wh.fromData(l.data);Sa(e.sessionId,"srtp profiles",f.profiles);let p=Ax.findMatchingSRTPProfile(f.profiles,e.options?.srtpProfiles);if(!p)throw new Error;n.srtpProfile=p,Sa(e.sessionId,"srtp profile selected",n.srtpProfile)}break;case cR.type:e.remoteExtendedMasterSecret=!0;break;case uR.type:Sa(e.sessionId,"RenegotiationIndication",l.data);break;case 43:{let p=[...l.data.subarray(1)].map(g=>g.toString(10));Sa("dtls supported version",p)}break}}),r.localRandom=new kf,r.remoteRandom=kf.from(i.random);let o=i.cipherSuites;Sa(e.sessionId,"cipher suites",o);let s=(()=>{switch(r.signatureHashAlgorithm?.signature){case Ea.ecdsa_3:return Wk.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;case Ea.rsa_1:return Wk.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199}})();if(s===void 0||!o.includes(s))throw new Error("dtls cipher suite negotiation failed");r.cipherSuite=s,Sa(e.sessionId,"selected cipherSuite",r.cipherSuite),r.localKeyPair=tJ(r.namedCurve),e.cookie||=$ke(20);let a=new pX({major:254,minor:253},e.cookie),c=QK(e)([a]),d=jx(e)(c.map(l=>({type:22,fragment:l.serialize()})),++e.recordSequenceNumber).map(l=>l.serialize());for(let l of d)t.send(l)},Mz=xt("werift-dtls : packages/dtls/flight/server/flight4.ts : log"),jke=class extends qx{constructor(t,e,r,n){super(t,e,4,6),this.cipher=r,this.srtp=n}async exec(t,e=!1){if(this.dtls.flight===4){Mz(this.dtls.sessionId,"flight4 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=4,this.dtls.sequenceNumber=1,this.dtls.bufferHandshakeCache([t],!1,4);let r=[this.sendServerHello(),this.sendCertificate(),this.sendServerKeyExchange(),e&&this.sendCertificateRequest(),this.sendServerHelloDone()].filter(n=>n);this.dtls.lastMessage=r,await this.transmit(r)}sendServerHello(){let t=[];this.srtp.srtpProfile&&t.push(wh.create([this.srtp.srtpProfile],Buffer.from([0])).extension),this.dtls.options.extendedMasterSecret&&t.push({type:cR.type,data:Buffer.alloc(0)});let e=uR.createEmpty();t.push(e.extension);let r=new sJ(this.dtls.version,this.cipher.localRandom,Buffer.from([0]),this.cipher.cipherSuite,0,t),n=this.createPacket([r]);return Buffer.concat(n.map(i=>i.serialize()))}sendCertificate(){let t=new Gk([Buffer.from(this.cipher.localCert)]),e=this.createPacket([t]);return Buffer.concat(e.map(r=>r.serialize()))}sendServerKeyExchange(){let t=this.cipher.generateKeySignature("sha256");if(!this.cipher.signatureHashAlgorithm)throw new Error("not exist");let e=new uJ(k6.named_curve_3,this.cipher.namedCurve,this.cipher.localKeyPair.publicKey.length,this.cipher.localKeyPair.publicKey,this.cipher.signatureHashAlgorithm.hash,this.cipher.signatureHashAlgorithm.signature,t.length,t),r=this.createPacket([e]);return Buffer.concat(r.map(n=>n.serialize()))}sendCertificateRequest(){let t=new oJ(UK,R6,[]);Mz(this.dtls.sessionId,"sendCertificateRequest",t);let e=this.createPacket([t]);return Buffer.concat(e.map(r=>r.serialize()))}sendServerHelloDone(){let t=new aJ,e=this.createPacket([t]);return Buffer.concat(e.map(r=>r.serialize()))}},kh=xt("werift-dtls : packages/dtls/flight/server/flight6.ts"),qke=class extends qx{constructor(t,e,r){super(t,e,6),this.cipher=r}handleHandshake(t){this.dtls.bufferHandshakeCache([t],!1,5);let e=(()=>{switch(t.msg_type){case 11:return Gk.deSerialize(t.fragment);case 15:return nJ.deSerialize(t.fragment);case 16:return iJ.deSerialize(t.fragment);case 20:return EN.deSerialize(t.fragment)}})();if(e){let r=zx[e.msgType];if(!r)return;r({dtls:this.dtls,cipher:this.cipher})(e)}}async exec(){if(this.dtls.flight===6){kh(this.dtls.sessionId,"flight6 twice"),this.send(this.dtls.lastMessage);return}this.dtls.flight=6;let t=[this.sendChangeCipherSpec(),this.sendFinished()];this.dtls.lastMessage=t,await this.transmit(t)}sendChangeCipherSpec(){let t=rJ.createEmpty().serialize(),e=jx(this.dtls)([{type:20,fragment:t}],++this.dtls.recordSequenceNumber);return Buffer.concat(e.map(n=>n.serialize()))}sendFinished(){let t=Buffer.concat(this.dtls.sortedHandshakeCache.map(o=>o.serialize())),e=this.cipher.verifyData(t),r=new EN(e);this.dtls.epoch=1;let[n]=this.createPacket([r]);return this.dtls.recordSequenceNumber=0,this.cipher.encryptPacket(n).serialize()}},zx={};zx[16]=({cipher:t,dtls:e})=>r=>{if(t.remoteKeyPair={curve:t.namedCurve,publicKey:r.publicKey},!t.remoteKeyPair.publicKey||!t.localKeyPair||!t.remoteRandom||!t.localRandom)throw new Error("not exist");let n=jK(t.remoteKeyPair.publicKey,t.localKeyPair.privateKey,t.localKeyPair.curve);kh(e.sessionId,"extendedMasterSecret",e.options.extendedMasterSecret,e.remoteExtendedMasterSecret);let i=Buffer.concat(e.sortedHandshakeCache.map(o=>o.serialize()));t.masterSecret=e.options.extendedMasterSecret&&e.remoteExtendedMasterSecret?WK(n,i):qK(n,t.remoteRandom.serialize(),t.localRandom.serialize()),t.cipher=ZK(t.cipherSuite),t.cipher.init(t.masterSecret,t.localRandom.serialize(),t.remoteRandom.serialize()),kh(e.sessionId,"setup cipher",t.cipher.summary)};zx[11]=({cipher:t,dtls:e})=>r=>{kh(e.sessionId,"handshake certificate",r),t.remoteCertificate=r.certificateList[0]};zx[15]=({cipher:t,dtls:e})=>r=>{if(!t.remoteCertificate)throw new Error("client certificate missing before certificate verify");kh(e.sessionId,"certificate_verify",r.algorithm)};zx[20]=({dtls:t})=>e=>{kh(t.sessionId,"finished",e)};uh=xt("werift-dtls : packages/dtls/src/server.ts : log"),mX=class extends O6{constructor(t){super(t,qc.SERVER),this.onHandleHandshakes=this.handleHandshakes,uh(this.dtls.sessionId,"start server")}flight6;handleHandshakes=async t=>{uh(this.dtls.sessionId,"handleHandshakes",t.map(e=>e.msg_type));for(let e of t)switch(e.msg_type){case 1:{this.connected&&this.renegotiation();let r=XK.deSerialize(e.fragment);r.cookie.length===0?(uh(this.dtls.sessionId,"send flight2"),Fke(this.transport,this.dtls,this.cipher,this.srtp)(r)):this.dtls.cookie&&r.cookie.equals(this.dtls.cookie)?(uh(this.dtls.sessionId,"send flight4"),await new jke(this.transport,this.dtls,this.cipher,this.srtp).exec(e,this.options.certificateRequest)):uh("wrong state",{dtlsCookie:this.dtls.cookie?.toString("hex").slice(10),helloCookie:r.cookie.toString("hex").slice(10)})}break;case 11:case 15:case 16:{if(this.connected)return;this.flight6=new qke(this.transport,this.dtls,this.cipher),this.flight6.handleHandshake(e)}break;case 20:{await this.waitForReady(()=>!!this.flight6),this.flight6?.handleHandshake(e);let r=[16,this.options.certificateRequest&&11,this.options.certificateRequest&&15].filter(n=>typeof n=="number");await this.waitForReady(()=>this.dtls.checkHandshakesExist(r)),await this.flight6?.exec(),this.connected=!0,this.onConnect.execute(),uh(this.dtls.sessionId,"dtls connected")}break}}},fR=554869826,hX=8,gX=1398035790,$c=20,M6=24,L6=1,H6=2,yX=6,vX=50,Wke=["FINGERPRINT","MESSAGE-INTEGRITY","CHANGE-REQUEST","PRIORITY","USERNAME","ICE-CONTROLLING","SOURCE-ADDRESS","USE-CANDIDATE","ICE-CONTROLLED","ERROR-CODE","XOR-MAPPED-ADDRESS","CHANGED-ADDRESS","LIFETIME","REQUESTED-TRANSPORT","NONCE","REALM","XOR-RELAYED-ADDRESS","CHANNEL-NUMBER","XOR-PEER-ADDRESS","DATA","SOFTWARE","MAPPED-ADDRESS","RESPONSE-ORIGIN","OTHER-ADDRESS"],U6=(t=>(t[t.REQUEST=0]="REQUEST",t[t.INDICATION=16]="INDICATION",t[t.RESPONSE=256]="RESPONSE",t[t.ERROR=272]="ERROR",t))(U6||{}),$6=(t=>(t[t.BINDING=1]="BINDING",t[t.SHARED_SECRET=2]="SHARED_SECRET",t[t.ALLOCATE=3]="ALLOCATE",t[t.REFRESH=4]="REFRESH",t[t.SEND=6]="SEND",t[t.DATA=7]="DATA",t[t.CREATE_PERMISSION=8]="CREATE_PERMISSION",t[t.CHANNEL_BIND=9]="CHANNEL_BIND",t))($6||{});Lz=class{queue=[];wait=new qe;put(t){this.queue.push(t),this.queue.length===1&&this.wait.execute(t)}get(){let t=this.queue.shift();return t||new Promise(e=>{this.wait.subscribe(r=>{this.queue.shift(),e(r)})})}},qN=t=>{let e,r,n=new Promise((o,s)=>{e=o,r=s});n.then(()=>{i.execute(void 0),i.complete()}).catch(o=>{i.execute(o??new Error),i.complete()});let i=new qe;return t(e,r,i).catch(()=>{}),{awaitable:n,resolve:e,reject:r}};F6=Buffer.alloc(6);F6.writeUInt16BE(fR>>16,0);F6.writeUInt32BE(fR,2);tx=t=>{let e=Buffer.alloc(4);return e.writeUInt32BE(t,0),e},rx=t=>t.readUInt32BE(0),zke=t=>{let e=Buffer.alloc(4);return e.writeUInt16BE(t,0),e},Kke=t=>t.readUInt16BE(0),Hz=t=>new FB(t.toString()).toBuffer(),Uz=t=>{let e=new FB(t);return BigInt(e.toString())},aN=t=>Buffer.from(t,"utf8"),cN=t=>t.toString("utf8"),uN=t=>t,dN=t=>t,Jke=t=>Buffer.from([]),Xke=t=>null,IX=[[1,"MAPPED-ADDRESS",ph,mh],[3,"CHANGE-REQUEST",tx,rx],[4,"SOURCE-ADDRESS",ph,mh],[5,"CHANGED-ADDRESS",ph,mh],[6,"USERNAME",aN,cN],[8,"MESSAGE-INTEGRITY",uN,dN],[9,"ERROR-CODE",Gke,Vke],[12,"CHANNEL-NUMBER",zke,Kke],[13,"LIFETIME",tx,rx],[18,"XOR-PEER-ADDRESS",_k,Pk],[19,"DATA",uN,dN],[20,"REALM",aN,cN],[21,"NONCE",uN,dN],[22,"XOR-RELAYED-ADDRESS",_k,Pk],[25,"REQUESTED-TRANSPORT",tx,rx],[32,"XOR-MAPPED-ADDRESS",_k,Pk],[36,"PRIORITY",tx,rx],[37,"USE-CANDIDATE",Jke,Xke],[32802,"SOFTWARE",aN,cN],[32808,"FINGERPRINT",tx,rx],[32809,"ICE-CONTROLLED",Hz,Uz],[32810,"ICE-CONTROLLING",Hz,Uz],[32811,"RESPONSE-ORIGIN",ph,mh],[32812,"OTHER-ADDRESS",ph,mh]],EX=class{constructor(t=[]){this.attributes=t}getAttributes(){return this.attributes}setAttribute(t,e){let r=this.attributes.find(n=>n[0]===t);return r?r[1]=e:this.attributes.push([t,e]),this}getAttributeValue(t){let e=this.attributes.find(r=>r[0]===t);if(e)return e[1]}get attributesKeys(){return this.attributes.map(t=>t[0])}clear(){this.attributes=[]}},$z=IX.reduce((t,e)=>(t[e[0]]=e,t),{}),Yke=IX.reduce((t,e)=>(t[e[1]]=e,t),{});Ho=class extends EX{constructor(t,e,r=bX(),n=[]){super(n),this.messageMethod=t,this.messageClass=e,this.transactionId=r}toJSON(){return this.json}get json(){return{messageMethod:$6[this.messageMethod],messageClass:U6[this.messageClass],attributes:this.attributes}}get transactionIdHex(){return this.transactionId.toString("hex")}get bytes(){let t=Buffer.from([]);for(let r of this.attributesKeys){let n=this.getAttributeValue(r),[i,,o]=Yke[r],s=o.name===_k.name?o(n,this.transactionId):o(n),a=s.length,c=4*Math.floor((a+3)/4)-a,u=Buffer.alloc(4);u.writeUInt16BE(i,0),u.writeUInt16BE(a,2),t=Buffer.concat([t,u,s,Buffer.alloc(c,0)])}let e=Buffer.alloc(8);return e.writeUInt16BE(this.messageMethod|this.messageClass,0),e.writeUInt16BE(t.length,2),e.writeUInt32BE(fR,4),Buffer.concat([e,this.transactionId,t])}addMessageIntegrity(t){return this.setAttribute("MESSAGE-INTEGRITY",this.messageIntegrity(t)),this}messageIntegrity(t){let e=j6(this.bytes,this.bytes.length-$c+M6);return Buffer.from(xX("sha1",t).update(e).digest("hex"),"hex")}addFingerprint(){this.setAttribute("FINGERPRINT",kX(this.bytes))}},j6=(t,e)=>{let r=Buffer.alloc(t.length);return t.copy(r,0,0,2),r.writeUInt16BE(e,2),t.copy(r,4,4),r};RX=class extends Error{response;addr},AX=class extends RX{constructor(t,e){super(),this.response=t,this.addr=e}get str(){let t="STUN transaction failed",e=this.response.getAttributeValue("ERROR-CODE");if(e){let[r,n]=e;t+=` (${r} - ${n})`}return t}},Zke=class extends RX{get str(){return"STUN transaction timed out"}},lN=xt("werift-ice:packages/ice/src/stun/transaction.ts"),q6=class{constructor(t,e,r,n){this.request=t,this.addr=e,this.protocol=r,this.retransmissions=n,this.triesMax=1+(this.retransmissions?this.retransmissions:yX)}timeoutDelay=vX;ended=!1;tries=0;triesMax;onResponse=new qe;responseReceived=(t,e)=>{this.onResponse.length>0&&(t.messageClass===256?(this.onResponse.execute(t,e),this.onResponse.complete()):this.onResponse.error(new AX(t,e)))};run=async()=>{try{return this.retry().catch(e=>{lN("retry failed",e)}),await this.onResponse.asPromise()}catch(t){throw t}finally{this.cancel()}};retry=async()=>{for(;this.tries<this.triesMax&&!this.ended&&(this.protocol.sendStun(this.request,this.addr).catch(t=>{lN("send stun failed",t)}),await new Promise(t=>setTimeout(t,this.timeoutDelay)),!this.ended);)this.timeoutDelay*=2,this.tries++;this.tries>=this.triesMax&&(lN(`retry failed times:${this.tries} maxLimit:${this.triesMax}`),this.onResponse.error(new Zke))};cancel(){this.ended=!0}},Fz=xt("werift-ice : packages/ice/src/stun/protocol.ts"),Kk=class CX{static type="stun";type=CX.type;transport;transactions={};get transactionsKeys(){return Object.keys(this.transactions)}localCandidate;sentMessage;localIp;onRequestReceived=new qe;onDataReceived=new qe;constructor(){}connectionMade=async(e,r,n)=>{e?this.transport=await qk.init("udp4",{portRange:r,interfaceAddresses:n}):this.transport=await qk.init("udp6",{portRange:r,interfaceAddresses:n}),this.transport.onData=(i,o)=>{this.datagramReceived(i,o)}};datagramReceived(e,r){try{let n=pR(e);if(!n){this.localCandidate&&this.onDataReceived.execute(e);return}(n.messageClass===256||n.messageClass===272)&&this.transactionsKeys.includes(n.transactionIdHex)?this.transactions[n.transactionIdHex].responseReceived(n,r):n.messageClass===0&&this.onRequestReceived.execute(n,r,e)}catch(n){Fz("datagramReceived error",n)}}getExtraInfo(){let{address:e,port:r}=this.transport.address;return[e,r]}async sendStun(e,r){if(this.transport.closed)return;let n=e.bytes;await this.transport.send(n,r).catch(()=>{Fz("sendStun failed",r,e)})}async sendData(e,r){this.transport.closed||await this.transport.send(e,r)}async request(e,r,n,i){if(this.transactionsKeys.includes(e.transactionIdHex))throw new Error("already request ed");n&&(e.addMessageIntegrity(n),e.addFingerprint());let o=new q6(e,r,this,i);this.transactions[e.transactionIdHex]=o;try{return await o.run()}catch(s){throw s}finally{delete this.transactions[e.transactionIdHex]}}async close(){Object.values(this.transactions).forEach(e=>{e.cancel()}),await this.transport.close(),this.onRequestReceived.complete(),this.onDataReceived.complete()}},ji=xt("werift-ice:packages/ice/src/turn/protocol.ts"),rRe=500,nRe=600,iRe=285212672,PX=class _X{constructor(e){this.turn=e,e.onData.subscribe((r,n)=>{this.handleStunMessage(r,n)}).disposer(this.disposer)}static type="turn";type=_X.type;localCandidate;disposer=new BK;onRequestReceived=new qe;onDataReceived=new qe;handleStunMessage=(e,r)=>{try{let n=pR(e);if(!n){this.onDataReceived.execute(e);return}if(n.messageClass===256||n.messageClass===272){let i=this.turn.transactions[n.transactionIdHex];i&&i.responseReceived(n,r)}else n.messageClass===0&&this.onRequestReceived.execute(n,r,e)}catch(n){ji("datagramReceived error",n)}};async request(e,r,n){if(this.turn.transactions[e.transactionIdHex])throw new Error("exist");n&&(e.addMessageIntegrity(n),e.addFingerprint());let i=new q6(e,r,this);this.turn.transactions[e.transactionIdHex]=i;try{return await i.run()}catch(o){throw o}finally{delete this.turn.transactions[e.transactionIdHex]}}async connectionMade(){}async sendData(e,r){await this.turn.sendData(e,r)}async sendStun(e,r){await this.turn.sendData(e.bytes,r)}async close(){return this.disposer.dispose(),this.turn.close()}},TX=class DX{constructor(e,r,n,i,o,s={}){this.server=e,this.username=r,this.password=n,this.lifetime=i,this.transport=o,this.options=s,this.channelRefreshTime=this.options.channelRefreshTime??rRe}static type="turn";type=DX.type;onData=new qe;onRequestReceived=new qe;onDataReceived=new qe;integrityKey;nonce;realm;relayedAddress;mappedAddress;localCandidate;transactions={};refreshHandle;channelNumber=16384;channelByAddr={};addrByChannel={};channelRefreshTime;channelBinding;channelRefreshAt=0;tcpBuffer=Buffer.alloc(0);permissionByAddr={};creatingPermission=Promise.resolve();async connectionMade(){this.transport.onData=(i,o)=>{this.dataReceived(i,o)};let e=new Ho(3,0);e.setAttribute("LIFETIME",this.lifetime).setAttribute("REQUESTED-TRANSPORT",iRe);let[r]=await this.requestWithRetry(e,this.server).catch(i=>{throw ji("connect error",i),i});this.relayedAddress=r.getAttributeValue("XOR-RELAYED-ADDRESS"),this.mappedAddress=r.getAttributeValue("XOR-MAPPED-ADDRESS");let n=r.getAttributeValue("LIFETIME");ji("connect",this.relayedAddress,this.mappedAddress,{exp:n}),this.refresh(n)}handleChannelData(e){let[r,n]=VN.jspack.Unpack("!HH",e.slice(0,4)),i=this.addrByChannel[r];if(i){let o=e.subarray(4,4+n);this.onData.execute(o,i)}}handleSTUNMessage(e,r){try{let n=pR(e);if(!n)throw new Error("not stun message");if(n.messageClass===256||n.messageClass===272){let i=this.transactions[n.transactionIdHex];i&&i.responseReceived(n,r)}else n.messageClass===0&&this.onData.execute(e,r);if(n.getAttributeValue("DATA")){let i=n.getAttributeValue("DATA");this.onData.execute(i,r)}}catch{ji("parse error",e.toString())}}dataReceived(e,r){let n=(i,o)=>{i.length>=4&&jz(i)?this.handleChannelData(i):this.handleSTUNMessage(i,o)};if(this.transport.type==="tcp")for(this.tcpBuffer=Buffer.concat([this.tcpBuffer,e]);this.tcpBuffer.length>=4;){let[,i]=vi(this.tcpBuffer.subarray(0,4),[2,2]);i+=WN(i);let o=jz(this.tcpBuffer)?4+i:20+i;if(this.tcpBuffer.length<o)break;n(this.tcpBuffer.subarray(0,o),r),this.tcpBuffer=this.tcpBuffer.subarray(o)}else n(e,r)}async send(e,r){if(!this.transport.closed)if(this.transport.type==="tcp"){let n=WN(e.length);await this.transport.send(n>0?Buffer.concat([e,Buffer.alloc(n)]):e,r)}else await this.transport.send(e,r)}async createPermission(e){let r=new Ho(8,0);r.setAttribute("XOR-PEER-ADDRESS",e).setAttribute("USERNAME",this.username).setAttribute("REALM",this.realm).setAttribute("NONCE",this.nonce),await this.request(r,this.server).catch(n=>{throw n})}refresh=e=>{this.refreshHandle=qN(async(r,n,i)=>{let o=!0;for(i.once(()=>{o=!1});o;){let s=.8333333333333334*e*1e3;ji("refresh delay",s,{exp:e}),await tRe(s);let a=new Ho(4,0);a.setAttribute("LIFETIME",e);try{let[c]=await this.requestWithRetry(a,this.server);e=c.getAttributeValue("LIFETIME"),ji("refresh",{exp:e})}catch(c){ji("refresh error",c)}}})};async request(e,r){if(this.transactions[e.transactionIdHex])throw new Error("exist");this.integrityKey&&e.setAttribute("USERNAME",this.username).setAttribute("REALM",this.realm).setAttribute("NONCE",this.nonce).addMessageIntegrity(this.integrityKey).addFingerprint();let n=new q6(e,r,this);this.transactions[e.transactionIdHex]=n;try{return await n.run()}catch(i){throw i}finally{delete this.transactions[e.transactionIdHex]}}async requestWithRetry(e,r){let n,i;try{[n,i]=await this.request(e,r)}catch(o){if(!(o instanceof AX))throw ji("requestWithRetry error",o),o;this.server=o.addr;let[s]=o.response.getAttributeValue("ERROR-CODE"),a=o.response.getAttributeValue("NONCE"),c=o.response.getAttributeValue("REALM");if((s===401&&c||s===438&&this.realm)&&a)ji("retry with nonce",s),this.nonce=a,s===401&&(this.realm=c),this.integrityKey=NX(this.username,this.realm,this.password),e.transactionId=bX(),[n,i]=await this.request(e,this.server);else throw o}return[n,i]}async sendData(e,r){let n=await this.getChannel(r).catch(o=>new Error("channelBind error"));if(n instanceof Error){await this.getPermission(r);let o=new Ho(6,16).setAttribute("DATA",e).setAttribute("XOR-PEER-ADDRESS",r);await this.sendStun(o,this.server);return}let i=VN.jspack.Pack("!HH",[n.number,e.length]);await this.send(Buffer.concat([Buffer.from(i),e]),this.server)}async getPermission(e){await this.creatingPermission,this.permissionByAddr[e.join(":")]||(this.creatingPermission=this.createPermission(e),this.permissionByAddr[e.join(":")]=!0,await this.creatingPermission.catch(n=>{throw ji("createPermission error",n),n}))}async getChannel(e){this.channelBinding&&await this.channelBinding;let r=this.channelByAddr[e.join(":")];return r?this.channelRefreshAt<vh(Date.now()/1e3)&&(this.channelBinding=this.channelBind(r.number,e),this.channelRefreshAt=vh(Date.now()/1e3)+this.channelRefreshTime,await this.channelBinding.catch(n=>{throw ji("channelBind error",n),n}),this.channelBinding=void 0,ji("channelBind refresh",r)):(this.channelByAddr[e.join(":")]={number:this.channelNumber++,address:e},r=this.channelByAddr[e.join(":")],this.addrByChannel[r.number]=e,this.channelBinding=this.channelBind(r.number,e),await this.channelBinding.catch(n=>{throw ji("channelBind error",n),n}),this.channelRefreshAt=vh(Date.now()/1e3)+this.channelRefreshTime,this.channelBinding=void 0,ji("channelBind",r)),r}async channelBind(e,r){let n=new Ho(9,0);n.setAttribute("CHANNEL-NUMBER",e).setAttribute("XOR-PEER-ADDRESS",r);let[i]=await this.requestWithRetry(n,this.server);if(i.messageMethod!==9)throw new Error("should be CHANNEL_BIND")}async sendStun(e,r){await this.send(e.bytes,r)}async close(){this.refreshHandle?.resolve?.(),await this.transport.close()}};Td=class OX{constructor(e,r,n,i,o,s,a,c,u,d,l,f){this.foundation=e,this.component=r,this.transport=n,this.priority=i,this.host=o,this.port=s,this.type=a,this.relatedAddress=c,this.relatedPort=u,this.tcptype=d,this.generation=l,this.ufrag=f}static fromSdp(e){let r=e.split(" ");if(r.length<8)throw new Error("SDP does not have enough properties");let n={foundation:r[0],component:Number(r[1]),transport:r[2],priority:Number(r[3]),host:r[4],port:Number(r[5]),type:r[7]};for(let l=8,f=r.length-1;l<f;l+=2)r[l]==="raddr"?n.related_address=r[l+1]:r[l]==="rport"?n.related_port=Number(r[l+1]):r[l]==="tcptype"?n.tcptype=r[l+1]:r[l]==="generation"?n.generation=Number(r[l+1]):r[l]==="ufrag"&&(n.ufrag=r[l+1]);let{foundation:i,component:o,transport:s,priority:a,host:c,port:u,type:d}=n;return new OX(i,o,s,a,c,u,d,n.related_address,n.related_port,n.tcptype,n.generation,n.ufrag)}canPairWith(e){let r=qz(this.host),n=qz(e.host);return this.component===e.component&&this.transport.toLowerCase()===e.transport.toLowerCase()&&r===n}toSdp(){let e=`${this.foundation} ${this.component} ${this.transport} ${this.priority} ${this.host} ${this.port} typ ${this.type}`;return this.relatedAddress&&(e+=` raddr ${this.relatedAddress}`),this.relatedPort!=null&&(e+=` rport ${this.relatedPort}`),this.tcptype&&(e+=` tcptype ${this.tcptype}`),this.generation!=null&&(e+=` generation ${this.generation}`),this.ufrag!=null&&(e+=` ufrag ${this.ufrag}`),e}};aRe=class{cache=new Map;mdnsInstance=(0,MX.default)();constructor(){this.mdnsInstance.setMaxListeners(50)}lookup(t){return new Promise((e,r)=>{let n=()=>{this.mdnsInstance.removeListener("response",o),clearTimeout(i)},i=setTimeout(()=>{n(),r(new Error("No mDNS response"))},1e4),o=s=>{let a=s.answers?.[0];a?.type==="A"&&a.name===t&&(n(),e(a.data))};this.mdnsInstance.on("response",o),this.mdnsInstance.query(t,"A")})}close(){this.mdnsInstance.destroy()}},uRe=xt("werift-ice : packages/ice/src/ice.ts : log"),KN=class{constructor(t,e,r){this.protocol=t,this.remoteCandidate=e,this.iceControlling=r}id=cRe().toString();handle;nominated=!1;remoteNominated=!1;_state=0;get state(){return this._state}packetsSent=0;packetsReceived=0;bytesSent=0;bytesReceived=0;rtt;totalRoundTripTime=0;roundTripTimeMeasurements=0;toJSON(){return this.json}get json(){return{protocol:this.protocol.type,localCandidate:this.localCandidate.toSdp(),remoteCandidate:this.remoteCandidate.toSdp()}}updateState(t){this._state=t}get localCandidate(){if(!this.protocol.localCandidate)throw new Error("localCandidate not exist");return this.protocol.localCandidate}get remoteAddr(){return[this.remoteCandidate.host,this.remoteCandidate.port]}get component(){return this.localCandidate.component}get priority(){return Xk(this.localCandidate,this.remoteCandidate,this.iceControlling)}get foundation(){return this.localCandidate.foundation}},JN=1,gx=2,LX=5,XN=6,HX=(t=>(t[t.FROZEN=0]="FROZEN",t[t.WAITING=1]="WAITING",t[t.IN_PROGRESS=2]="IN_PROGRESS",t[t.SUCCEEDED=3]="SUCCEEDED",t[t.FAILED=4]="FAILED",t))(HX||{}),UX={useIpv4:!0,useIpv6:!0};dRe=xt("werift-ice : packages/ice/src/utils.ts");fRe=t=>{if(!t)return;let[e,r]=t.split(":");return[e,Number.parseInt(r)]},ur=xt("werift-ice : packages/ice/src/ice.ts : log"),GX=class{constructor(t,e){this._iceControlling=t,this.options={...UX,...e};let{stunServer:r,turnServer:n}=this.options;this.stunServer=QN(r)??["stun.l.google.com",19302],this.turnServer=QN(n),this.restart(),ur("new Connection",this.options)}localUsername=ex(4);localPassword=ex(22);remoteIsLite=!1;remotePassword="";remoteUsername="";checkList=[];localCandidates=[];stunServer;turnServer;options;remoteCandidatesEnd=!1;localCandidatesEnd=!1;generation=-1;userHistory={};tieBreaker=BigInt(new gk(sRe(64)).toString());state="new";lookup;_remoteCandidates=[];nominated;nominating=!1;checkListDone=!1;checkListState=new Lz;earlyChecks=[];earlyChecksDone=!1;localCandidatesStart=!1;protocols=[];queryConsentHandle;onData=new qe;stateChanged=new qe;onIceCandidate=new qe;get iceControlling(){return this._iceControlling}set iceControlling(t){if(!(this.generation>0||this.nominated)){this._iceControlling=t;for(let e of this.checkList)e.iceControlling=t}}async restart(){this.generation++,this.localUsername=ex(4),this.localPassword=ex(22),this.options.localPasswordPrefix&&(this.localPassword=this.options.localPasswordPrefix+this.localPassword.slice(this.options.localPasswordPrefix.length)),this.userHistory[this.localUsername]=this.localPassword,this.remoteUsername="",this.remotePassword="",this.localCandidates=[],this._remoteCandidates=[],this.remoteCandidatesEnd=!1,this.localCandidatesEnd=!1,this.state="new",this.lookup?.close?.(),this.lookup=void 0,this.nominated=void 0,this.nominating=!1,this.checkList=[],this.checkListDone=!1,this.checkListState=new Lz,this.earlyChecks=[],this.earlyChecksDone=!1,this.localCandidatesStart=!1;for(let t of this.protocols)t.localCandidate&&(t.localCandidate.generation=this.generation,t.localCandidate.ufrag=this.localUsername);this.queryConsentHandle?.resolve?.(),this.queryConsentHandle=void 0}resetNominatedPair(){ur("resetNominatedPair"),this.nominated=void 0,this.nominating=!1}setRemoteParams({iceLite:t,usernameFragment:e,password:r}){ur("setRemoteParams",{iceLite:t,usernameFragment:e,password:r}),this.remoteIsLite=t,this.remoteUsername=e,this.remotePassword=r}async gatherCandidates(){if(!this.localCandidatesStart){this.localCandidatesStart=!0;let t=VX(this.options.useIpv4,this.options.useIpv6,{useLinkLocalAddress:this.options.useLinkLocalAddress}),{interfaceAddresses:e}=this.options;if(e){let n=t.filter(i=>Object.values(e).includes(i));n.length&&(t=n)}this.options.additionalHostAddresses&&(t=Array.from(new Set([...this.options.additionalHostAddresses,...t])));let r=this.getCandidatePromises(t,5);await Promise.allSettled(r),this.localCandidatesEnd=!0}this.setState("completed")}appendLocalCandidate(t){this.localCandidates.push(t),this.onIceCandidate.execute(t)}ensureProtocol(t){t.onRequestReceived.subscribe((e,r,n)=>{if(e.messageMethod!==1){this.respondError(e,r,t,[400,"Bad Request"]);return}let i=e.getAttributeValue("USERNAME"),{remoteUsername:o}=Vz(i),s=this.userHistory[o]??this.localPassword,{iceControlling:a}=this;if(a&&e.attributesKeys.includes("ICE-CONTROLLING"))if(this.tieBreaker>=e.getAttributeValue("ICE-CONTROLLING")){this.respondError(e,r,t,[487,"Role Conflict"]);return}else this.switchRole(!1);else if(!a&&e.attributesKeys.includes("ICE-CONTROLLED"))if(this.tieBreaker<e.getAttributeValue("ICE-CONTROLLED"))this.respondError(e,r,t,[487,"Role Conflict"]);else{this.switchRole(!0);return}if(this.options.filterStunResponse&&!this.options.filterStunResponse(e,r,t))return;let c=new Ho(1,256,e.transactionId);c.setAttribute("XOR-MAPPED-ADDRESS",r).addMessageIntegrity(Buffer.from(s,"utf8")).addFingerprint(),t.sendStun(c,r).catch(u=>{ur("sendStun error",u)}),this.checkList.length===0&&!this.earlyChecksDone?this.earlyChecks.push([e,r,t]):this.checkIncoming(e,r,t)}),t.onDataReceived.subscribe(e=>{try{let r=this.nominated;r&&r.protocol===t&&(r.packetsReceived++,r.bytesReceived+=e.length),this.onData.execute(e)}catch(r){ur("dataReceived",r)}})}getCandidatePromises(t,e=5){let r=[];t=t.filter(c=>!this.protocols.find(u=>u.localIp===c));let n=t.map(async c=>{let u=new Kk;this.ensureProtocol(u);try{await u.connectionMade(Wz(c),this.options.portRange,this.options.interfaceAddresses),u.localIp=c,this.protocols.push(u),ur("protocol",u.localIp);let d=[c,u.getExtraInfo()[1]];return u.localCandidate=new Td(Jk("host","udp",d[0]),1,"udp",Sx("host"),d[0],d[1],"host",void 0,void 0,void 0,this.generation,this.localUsername),this.pairLocalProtocol(u),this.appendLocalCandidate(u.localCandidate),u}catch(d){ur("error protocol STUN",d)}});r.push(...n.map(c=>c.then(u=>u?.localCandidate)));let{stunServer:i,turnServer:o}=this;if(i){let c=n.map(async u=>{let d=await u;return d?new Promise(async(f,p)=>{let g=setTimeout(p,e*1e3);if(d.localCandidate?.host&&Wz(d.localCandidate?.host)){let v=await FX(d,i).catch(b=>{ur("error",b)});v&&this.appendLocalCandidate(v),clearTimeout(g),f(v)}else clearTimeout(g),f()}).catch(f=>{ur("query STUN server",f)}):void 0});r.push(...c)}let{turnUsername:s,turnPassword:a}=this.options;if(o&&s&&a){let c=(async()=>{let u=await GN({address:o,username:s,password:a},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:this.options.turnTransport==="tcp"?"tcp":"udp"}).catch(async f=>{if(this.options.turnTransport!=="tcp")return await GN({address:o,username:s,password:a},{portRange:this.options.portRange,interfaceAddresses:this.options.interfaceAddresses,transport:"tcp"});throw f});this.ensureProtocol(u),this.protocols.push(u);let d=u.turn.relayedAddress,l=u.turn.mappedAddress;return ur("turn candidateAddress",d),u.localCandidate=new Td(Jk("relay","udp",d[0]),1,"udp",Sx("relay"),d[0],d[1],"relay",l[0],l[1],void 0,this.generation,this.localUsername),this.appendLocalCandidate(u.localCandidate),u.localCandidate})().catch(u=>{ur("query TURN server",u)});this.options.forceTurn&&(r=[]),r.push(c)}return r}async connect(){if(ur("start connect ice"),!this.localCandidatesEnd&&!this.localCandidatesStart)throw new Error("Local candidates gathering was not performed");if(!this.remoteUsername||!this.remotePassword)throw new Error("Remote username or password is missing");for(let e of this.remoteCandidates)this.pairRemoteCandidate(e);this.sortCheckList(),this.unfreezeInitial(),ur("earlyChecks",this.localPassword,this.earlyChecks.length);for(let e of this.earlyChecks)this.checkIncoming(...e);for(this.earlyChecks=[],this.earlyChecksDone=!0;!(this.state==="closed"||!this.schedulingChecks());)await zN.setTimeout(20);let t=gx;for(;this.checkList.length>0&&t===gx;)t=await this.checkListState.get(),ur("checkListState",t);for(let e of this.checkList)e.handle?.resolve?.();if(t!==JN)throw new Error("ICE negotiation failed");this.queryConsent(),this.setState("connected")}unfreezeInitial(){let[t]=this.checkList;if(!t)return;t.state===0&&t.updateState(1);let e=new Set(t.localCandidate.foundation);for(let r of this.checkList)r.component===t.component&&!e.has(r.localCandidate.foundation)&&r.state===0&&(r.updateState(1),e.add(r.localCandidate.foundation))}schedulingChecks(){{let t=this.checkList.filter(e=>!(this.options.forceTurn&&e.protocol.type===Kk.type)).find(e=>e.state===1);if(t)return t.handle=this.checkStart(t),!0}{let t=this.checkList.find(e=>e.state===0);if(t)return t.handle=this.checkStart(t),!0}return this.remoteCandidatesEnd?!1:!this.checkListDone}queryConsent=()=>{this.queryConsentHandle&&this.queryConsentHandle.resolve(),this.queryConsentHandle=qN(async(t,e,r)=>{let n=0,i=!1,o=new AbortController;r.once(()=>{i=!0,n+=XN,o.abort(),this.queryConsentHandle=void 0});let{localUsername:s,remoteUsername:a,iceControlling:c}=this;try{for(;this.state!=="closed"&&!i;){await zN.setTimeout(LX*(.8+.4*Math.random())*1e3,void 0,{signal:o.signal});let u=this.nominated;if(!u||i)break;let d=this.buildRequest({nominate:!1,localUsername:s,remoteUsername:a,iceControlling:c});try{await u.protocol.request(d,u.remoteAddr,Buffer.from(this.remotePassword,"utf8"),0),n=0,this.state==="disconnected"&&this.setState("connected")}catch{if(u.id===this.nominated?.id){ur("no stun response"),n++,this.setState("disconnected");break}}if(n>=XN){ur("Consent to send expired"),this.queryConsentHandle=void 0,this.setState("closed");break}}}catch{}})};async close(){this.setState("closed"),this.queryConsentHandle?.resolve?.(),this.checkList&&!this.checkListDone&&this.checkListState.put(new Promise(t=>{t(gx)})),this.nominated=void 0;for(let t of this.protocols)t.close&&await t.close();this.protocols=[],this.localCandidates=[],this.lookup?.close?.(),this.lookup=void 0}setState(t){this.state=t,this.stateChanged.execute(t)}async addRemoteCandidate(t){if(!t){this.remoteCandidatesEnd=!0;return}if(t.host.includes(".local"))try{this.lookup||(this.lookup=new aRe);let e=await this.lookup.lookup(t.host);t.host=e}catch{return}try{YN(t)}catch{return}ur("addRemoteCandidate",t),this._remoteCandidates.push(t),this.pairRemoteCandidate(t),this.sortCheckList()}send=async t=>{let e=this.nominated;if(e)await e.protocol.sendData(t,e.remoteAddr),e.packetsSent++,e.bytesSent+=t.length;else return};getDefaultCandidate(){let t=this.localCandidates.sort((r,n)=>r.priority-n.priority),[e]=t;return e}set remoteCandidates(t){if(this.remoteCandidatesEnd)throw new Error("Cannot set remote candidates after end-of-candidates.");this._remoteCandidates=[];for(let e of t){try{YN(e)}catch{continue}this._remoteCandidates.push(e)}this.remoteCandidatesEnd=!0}get remoteCandidates(){return this._remoteCandidates}get candidatePairs(){return this.checkList}sortCheckList(){$X(this.checkList,this.iceControlling)}findPair(t,e){return this.checkList.find(n=>(0,Tk.default)(n.protocol,t)&&(0,Tk.default)(n.remoteCandidate,e))}switchRole(t){ur("switch role",t),this.iceControlling=t,this.sortCheckList()}checkComplete(t){if(t.handle=void 0,t.state===3){if(t.nominated&&(t.remoteCandidate.generation==null||t.remoteCandidate.generation===this.generation)&&this.nominated==null){ur("nominated",t.toJSON()),this.nominated=t,this.nominating=!1;for(let e of this.checkList)e.component===t.component&&[1,0].includes(e.state)&&e.updateState(4)}if(this.nominated){this.checkListDone||(ur("ICE completed"),this.checkListState.put(new Promise(e=>e(JN))),this.checkListDone=!0);return}ur("not completed",t.toJSON());for(let e of this.checkList)e.localCandidate.foundation===t.localCandidate.foundation&&e.state===0&&e.updateState(1)}{let e=[3,4];if(this.checkList.find(({state:r})=>!e.includes(r)))return}!this.iceControlling&&this.checkList.find(({state:r})=>r===3)||this.checkListDone||(ur("ICE failed"),this.checkListState.put(new Promise(e=>{e(gx)})))}checkStart=t=>qN(async e=>{ur("check start",t.toJSON()),t.updateState(2);let r={},{remotePassword:n,remoteUsername:i,generation:o}=this,s=t.localCandidate.ufrag??this.localUsername,a=this.iceControlling&&!this.remoteIsLite,c=this.buildRequest({nominate:a,localUsername:s,remoteUsername:i,iceControlling:this.iceControlling}),u=performance.now();try{let[d,l]=await t.protocol.request(c,t.remoteAddr,Buffer.from(n,"utf8"),4),p=(performance.now()-u)/1e3;t.rtt=p,t.totalRoundTripTime+=p,t.roundTripTimeMeasurements++,ur("response received",c.toJSON(),d.toJSON(),l,{localUsername:s,remoteUsername:i,remotePassword:n,generation:o,rtt:p}),r.response=d,r.addr=l}catch(d){let l=d;if(ur("failure case",c.toJSON(),l.response?JSON.stringify(l.response.toJSON(),null,2):d,{localUsername:s,remoteUsername:i,remotePassword:n,generation:o},t.remoteAddr),l.response?.getAttributeValue("ERROR-CODE")[0]===487){c.attributesKeys.includes("ICE-CONTROLLED")?this.switchRole(!0):c.attributesKeys.includes("ICE-CONTROLLING")&&this.switchRole(!1),await this.checkStart(t).awaitable,e();return}if(l.response?.getAttributeValue("ERROR-CODE")[0]===401){ur("retry 401",t.toJSON()),await this.checkStart(t).awaitable,e();return}else{ur("checkStart CandidatePairState.FAILED",t.toJSON()),t.updateState(4),this.checkComplete(t),e();return}}if(!(0,Tk.default)(r.addr,t.remoteAddr)){t.updateState(4),this.checkComplete(t),e();return}if(a||t.remoteNominated)t.nominated=!0;else if(this.iceControlling&&!this.nominating){this.nominating=!0;let d=this.buildRequest({nominate:!0,localUsername:s,remoteUsername:i,iceControlling:this.iceControlling});try{await t.protocol.request(d,t.remoteAddr,Buffer.from(this.remotePassword,"utf8"))}catch{t.updateState(4),this.checkComplete(t);return}t.nominated=!0}t.updateState(3),this.checkComplete(t),e()});addPair(t){this.checkList.push(t),this.sortCheckList()}checkIncoming(t,e,r){let n=t.getAttributeValue("USERNAME"),{remoteUsername:i}=Vz(n),o,[s,a]=e;for(let u of this.remoteCandidates)if(u.host===s&&u.port===a){o=u;break}o||(o=new Td(ex(10),1,"udp",t.getAttributeValue("PRIORITY"),s,a,"prflx",void 0,void 0,void 0,void 0,void 0),this._remoteCandidates.push(o));let c=this.findPair(r,o);c||(c=new KN(r,o,this.iceControlling),c.updateState(1),this.addPair(c)),c.localCandidate.ufrag=i,ur("Triggered Checks",t.toJSON(),c.toJSON(),{localUsername:this.localUsername,remoteUsername:this.remoteUsername,localPassword:this.localPassword,remotePassword:this.remotePassword,generation:this.generation}),[1,4].includes(c.state)&&(c.handle=this.checkStart(c)),t.attributesKeys.includes("USE-CANDIDATE")&&!this.iceControlling&&(c.remoteNominated=!0,c.state===3&&(c.nominated=!0,this.checkComplete(c)))}tryPair(t,e){if(t.localCandidate?.canPairWith(e)&&!this.findPair(t,e)){let r=new KN(t,e,this.iceControlling);if(this.options.filterCandidatePair&&!this.options.filterCandidatePair(r))return;r.updateState(1),this.addPair(r)}}pairLocalProtocol(t){for(let e of this.remoteCandidates)this.tryPair(t,e)}pairRemoteCandidate=t=>{for(let e of this.protocols)this.tryPair(e,t)};buildRequest({nominate:t,remoteUsername:e,localUsername:r,iceControlling:n}){let i=pRe({remoteUsername:e,localUsername:r}),o=new Ho(1,0);return o.setAttribute("USERNAME",i).setAttribute("PRIORITY",Sx("prflx")),n?(o.setAttribute("ICE-CONTROLLING",this.tieBreaker),t&&o.setAttribute("USE-CANDIDATE",null)):o.setAttribute("ICE-CONTROLLED",this.tieBreaker),o}respondError(t,e,r,n){let i=new Ho(t.messageMethod,272,t.transactionId);i.setAttribute("ERROR-CODE",n).addMessageIntegrity(Buffer.from(this.localPassword,"utf8")).addFingerprint(),r.sendStun(i,e).catch(o=>{ur("sendStun error",o)})}},pRe=({remoteUsername:t,localUsername:e})=>`${t}:${e}`,Vz=t=>{let[e,r]=t.split(":");return{remoteUsername:e,localUsername:r}};W6=class extends mRe{addEventListener=(t,e)=>{this.addListener(t,e)};removeEventListener=(t,e)=>{this.removeListener(t,e)}},hRe=xt("werift:packages/webrtc/src/dataChannel.ts");V6=class extends W6{constructor(t,e,r=!0){if(super(),this.sctp=t,this.parameters=e,this.sendOpen=r,this.id=this.parameters.id,e.negotiated){if(this.id==null||this.id<0||this.id>65534)throw new Error("ID must be in range 0-65534 if data channel is negotiated out-of-band");this.sctp.dataChannelAddNegotiated(this)}else r&&(this.sendOpen=!1,this.sctp.dataChannelOpen(this))}stateChange=new qe;stateChanged=new qe;onMessage=new qe;error=new qe;bufferedAmountLow=new qe;onopen;onclose;onclosing;onmessage;onerror;isCreatedByRemote=!1;id;readyState="connecting";bufferedAmount=0;_bufferedAmountLowThreshold=0;messagesSent=0;bytesSent=0;messagesReceived=0;bytesReceived=0;get ordered(){return this.parameters.ordered}get maxRetransmits(){return this.parameters.maxRetransmits}get maxPacketLifeTime(){return this.parameters.maxPacketLifeTime}get label(){return this.parameters.label}get protocol(){return this.parameters.protocol}get negotiated(){return this.parameters.negotiated}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(t){if(t<0||t>4294967295)throw new Error("bufferedAmountLowThreshold must be in range 0 - 4294967295");this._bufferedAmountLowThreshold=t}setId(t){this.id=t}setReadyState(t){if(t!==this.readyState){switch(this.readyState=t,this.stateChange.execute(t),this.stateChanged.execute(t),t){case"open":this.onopen&&this.onopen(),this.emit("open");break;case"closed":this.onclose&&this.onclose(),this.emit("close");break;case"closing":this.onclosing&&this.onclosing();break}hRe("change state",t)}}addBufferedAmount(t){let e=this.bufferedAmount>this.bufferedAmountLowThreshold&&this.bufferedAmount+t<=this.bufferedAmountLowThreshold;this.bufferedAmount+=t,e&&(this.bufferedAmountLow.execute(),this.emit("bufferedamountlow"))}send(t){let e=this.sctp.datachannelSend(this,t);this.messagesSent++,this.bytesSent+=e}close(){this.sctp.dataChannelClose(this)}},G6=class{label="";maxPacketLifeTime;maxRetransmits;ordered=!0;protocol="";negotiated=!1;id;constructor(t={}){Object.assign(this,t)}},gRe=()=>({type:"ccm",parameter:"fir"}),Kx=()=>({type:"nack"}),Th=()=>({type:"nack",parameter:"pli"}),Jx=()=>({type:"goog-remb"}),KX=()=>({type:"transport-cc"}),Dd=class{payloadType;mimeType;clockRate;channels;rtcpFeedback=[];parameters;direction="all";constructor(t){Object.assign(this,t)}get name(){return this.mimeType.split("/")[1]}get contentType(){return this.mimeType.split("/")[0]}get str(){let t=`${this.name}/${this.clockRate}`;return this.channels===2&&(t+="/2"),t}},ka=class{id;uri;constructor(t){Object.assign(this,t)}},yRe=class{cname;mux=!1;ssrc;constructor(t={}){Object.assign(this,t)}},JX=class{type;parameter;constructor(t={}){Object.assign(this,t)}},XX=class{ssrc;constructor(t={}){Object.assign(this,t)}},YX=class{ssrc;payloadType;rtx;constructor(t){Object.assign(this,t)}},z6=class{rid;direction;constructor(t){Object.assign(this,t)}},QX=(t={})=>new Dd({mimeType:"video/h264",clockRate:9e4,rtcpFeedback:[Kx(),Th(),Jx()],parameters:"profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1",...t}),K6=(t={})=>new Dd({mimeType:"video/VP8",clockRate:9e4,rtcpFeedback:[Kx(),Th(),Jx()],...t}),ZX=(t={})=>new Dd({mimeType:"video/VP9",clockRate:9e4,rtcpFeedback:[Kx(),Th(),Jx()],...t}),eY=(t={})=>new Dd({mimeType:"video/AV1X",clockRate:9e4,rtcpFeedback:[Kx(),Th(),Jx()],...t}),J6=(t={})=>new Dd({mimeType:"audio/OPUS",clockRate:48e3,channels:2,...t}),X6=(t={})=>new Dd({mimeType:"audio/PCMU",clockRate:8e3,channels:1,payloadType:0,...t}),Y6=[eY(),ZX(),K6(),QX(),J6(),X6()].map(t=>t.mimeType),vRe=Y6.filter(t=>t.toLowerCase().startsWith("video/")),xRe=Y6.filter(t=>t.toLowerCase().startsWith("audio/"));Kz=2,Jz=3,DRe=0,wk=50,Xz=51,Yz=53,BRe=56,NRe=57,ORe="0.0.0.0",Qz=9,e6={auto:"actpass",client:"active",server:"passive"},Zz=Object.keys(e6).reduce((t,e)=>{let r=e6[e];return t[r]=e,t},{}),MRe=["apt","max-fr","max-fs","maxplaybackrate","minptime","stereo","useinbandfec"],tY=["cname","msid","mslabel","label"],eK={SRTP_AES128_CM_HMAC_SHA1_80:Ph,SRTP_AEAD_AES_128_GCM:Nf},Dk=["sendonly","sendrecv"],LRe=["sendrecv","recvonly"],rY=class extends Map{constructor(t){if(super(),t)for(let e of t)this.set(e.id,e)}};nY=class{constructor(t,e,r,n,i){this.kind=t,this.receiver=r,this.sender=n,this._direction=i,e&&this.setDtlsTransport(e)}id=TRe().toString();onTrack=new qe;mid;mLineIndex;usedForSender=!1;_currentDirection;offerDirection;_codecs=[];set codecs(t){this._codecs=t}get codecs(){return this._codecs}headerExtensions=[];options={};stopping=!1;stopped=!1;get dtlsTransport(){return this.receiver.dtlsTransport}get direction(){return this._direction}setDirection(t){this._direction=t,Dk.includes(this._currentDirection??"")&&(this.usedForSender=!0)}get currentDirection(){return this._currentDirection}setCurrentDirection(t){this._currentDirection=t}setDtlsTransport(t){this.receiver.setDtlsTransport(t),this.sender.setDtlsTransport(t)}get msid(){return`${this.sender.streamId} ${this.sender.trackId}`}addTrack(t){this.receiver.addTrack(t)&&this.onTrack.execute(t,this)}stop(){this.stopping||(this.stopping=!0)}getPayloadType(t){return this.codecs.find(e=>e.mimeType.toLowerCase().includes(t.toLowerCase()))?.payloadType}getCodecStats(){let t=Bd(),e=[];if(!this.dtlsTransport)return e;let r=hr("transport",this.dtlsTransport.id);for(let n of this.codecs){let i={type:"codec",id:hr("codec",n.payloadType,r),timestamp:t,payloadType:n.payloadType,transportId:r,mimeType:n.mimeType,clockRate:n.clockRate,channels:n.channels,sdpFmtpLine:n.parameters};e.push(i)}return e}},iY="inactive",Q6="sendonly",Z6="recvonly",eO="sendrecv",Bk=[iY,Q6,Z6,eO],Lx=class extends W6{uuid=oY().toString();streamId;remote=!1;label;kind;id;ssrc;rid;header;codec;enabled=!0;onReceiveRtp=new qe;onReceiveRtcp=new qe;onSourceChanged=new qe;stopped=!1;muted=!0;constructor(t){super(),Object.assign(this,t),this.onReceiveRtp.subscribe(e=>{this.muted=!1,this.header=e.header}),this.label=`${this.remote?"remote":"local"} ${this.kind}`}stop=()=>{this.stopped=!0,this.muted=!0,this.onReceiveRtp.complete(),this.emit("ended")};writeRtp=t=>{if(this.remote)throw new Error("this is remoteTrack");if(this.stopped)return;let e=Buffer.isBuffer(t)?Gc.deSerialize(t):t;e.header.payloadType=this.codec?.payloadType??e.header.payloadType,this.onReceiveRtp.execute(e)}},sY=class{id;tracks=[];constructor(t){Array.isArray(t)?this.tracks=t:Object.assign(this,t),this.id??=oY().toString()}addTrack(t){t.streamId=this.id,this.tracks.push(t)}getTracks(){return this.tracks}getAudioTracks(){return this.tracks.filter(t=>t.kind==="audio")}getVideoTracks(){return this.tracks.filter(t=>t.kind==="video")}},HRe=xt("werift:packages/webrtc/src/utils.ts");URe={sha1:"sha1","sha-1":"sha1",sha224:"sha224","sha-224":"sha224",sha256:"sha256","sha-256":"sha256",sha384:"sha384","sha-384":"sha384",sha512:"sha512","sha-512":"sha512"};nO=(t,e)=>Bk[Bk.indexOf(t)&Bk.indexOf(e)];iO=Date.now,FRe=BigInt(Date.now())*1000n-process.hrtime.bigint()/1000n,uY=()=>FRe+process.hrtime.bigint()/1000n,Hx=()=>Date.now()/1e3,dY=()=>{let e=(zz.timeOrigin+zz.now()-Date.UTC(1900,0,1))/1e3,[r,n]=e.toString().split(".").map(Number);return _r([4,4],[r,n]).readBigUInt64BE()},oO=t=>{let e=_r([8],[t]),[,r,n]=vi(e,[2,2,2,2]);return _r([2,2],[r,n]).readUInt32BE()};jRe=Rx.createSelfSignedCertificateWithKey,qRe=class{static async rtpSource({port:t,kind:e,cb:r}){t??=await I6();let n=new Lx({kind:e}),i=_Re("udp4");i.bind(t);let o=a=>{r&&(a=r(a)),n.writeRtp(a)};return i.addListener("message",o),[n,t,()=>{i.removeListener("message",o);try{i.close()}catch{}}]}},fY=(t,e)=>{if(!t||typeof t!="object")return e!==null&&typeof e=="object"?e:t;if(!e||typeof e!="object")return e??t;for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];n!=null&&(t[r]=n)}return t},WRe=xt("werift:packages/webrtc/src/media/receiver/nack.ts"),tK=150,VRe=class{constructor(t){this.receiver=t}newEstSeqNum=0;_lost={};nackLoop;onPacketLost=new qe;mediaSourceSsrc;retryCount=10;closed=!1;get lostSeqNumbers(){return Object.keys(this._lost).map(Number).sort()}getLost(t){return this._lost[t]}setLost(t,e){this._lost[t]=e,!(this.nackLoop||this.closed)&&(this.nackLoop=setInterval(async()=>{try{await this.sendNack(),Object.keys(this._lost).length||(clearInterval(this.nackLoop),this.nackLoop=void 0)}catch(r){WRe("failed to send nack",r)}},5))}removeLost(t){delete this._lost[t]}addPacket(t){let{sequenceNumber:e,ssrc:r}=t.header;if(this.mediaSourceSsrc=r,this.newEstSeqNum===0){this.newEstSeqNum=e;return}if(this.getLost(e)){this.removeLost(e);return}if(e===$n(this.newEstSeqNum,1))this.newEstSeqNum=e;else if(e>$n(this.newEstSeqNum,1)){for(let n=$n(this.newEstSeqNum,1);n<e;n=$n(n,1))this.setLost(n,1);this.newEstSeqNum=e,this.pruneLost()}}pruneLost(){this.lostSeqNumbers.length>tK&&(this._lost=Object.entries(this._lost).slice(-tK).reduce((t,[e,r])=>(t[e]=r,t),{}))}close(){this.closed=!0,clearInterval(this.nackLoop),this._lost={}}updateRetryCount(){this.lostSeqNumbers.forEach(t=>{if(this._lost[t]++>this.retryCount)return this.removeLost(t),t})}sendNack=()=>new Promise((t,e)=>{if(this.lostSeqNumbers.length>0&&this.mediaSourceSsrc){let r=new Dx({senderSsrc:this.receiver.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,lost:this.lostSeqNumbers}),n=new Pf({feedback:r});this.receiver.dtlsTransport.sendRtcp([n]).then(t).catch(e),this.updateRetryCount(),this.onPacketLost.execute(r)}})},zRe=xt("werift:packages/webrtc/media/receiver/receiverTwcc"),KRe=class{constructor(t,e,r){this.dtlsTransport=t,this.rtcpSsrc=e,this.mediaSourceSsrc=r,this.runTWCC()}extensionInfo={};twccRunning=!1;fbPktCount=0;lastTimestamp;handleTWCC(t){this.extensionInfo[t]={tsn:t,timestamp:uY()},Object.keys(this.extensionInfo).length>10&&this.sendTWCC()}async runTWCC(){for(;this.twccRunning;)this.sendTWCC(),await GRe(100)}sendTWCC(){if(Object.keys(this.extensionInfo).length===0)return;let t=Object.values(this.extensionInfo).sort((d,l)=>d.tsn-l.tsn),e=t[0].tsn,r=t.slice(-1)[0].tsn,n=[],i=t[0].tsn,o=$n(r-e,1),s,a,c=[];for(let d=e;d<=r;d++){let l=this.extensionInfo[d]?.timestamp;if(l){this.lastTimestamp||(this.lastTimestamp=l),s||(s=this.lastTimestamp);let f=l-this.lastTimestamp;this.lastTimestamp=l;let p=new xx({delta:Number(f)});p.parseDelta(),c.push(p),a!=null&&a.status!==p.type&&(n.push(new Sh({packetStatus:a.status,runLength:d-a.minTSN})),a={minTSN:d,status:p.type}),d===r&&(a!=null?n.push(new Sh({packetStatus:a.status,runLength:d-a.minTSN+1})):n.push(new Sh({packetStatus:p.type,runLength:1}))),a==null&&(a={minTSN:d,status:p.type})}}if(!s)return;let u=new Pf({feedback:new Bx({senderSsrc:this.rtcpSsrc,mediaSourceSsrc:this.mediaSourceSsrc,baseSequenceNumber:i,packetStatusCount:o,referenceTime:PK(Math.floor(Number(s/1000n/64n))),fbPktCount:this.fbPktCount,recvDeltas:c,packetChunks:n})});this.dtlsTransport.sendRtcp([u]).catch(d=>{zRe(d)}),this.extensionInfo={},this.fbPktCount=CK(this.fbPktCount,1)}},JRe=class{base_seq;max_seq;cycles=0;packets_received=0;clockRate;jitter_q4=0;last_arrival;last_timestamp;expected_prior=0;received_prior=0;constructor(t){this.clockRate=t}add(t,e=Date.now()/1e3){let r=this.max_seq==null||iR(t.header.sequenceNumber,this.max_seq);if(this.packets_received++,this.base_seq==null&&(this.base_seq=t.header.sequenceNumber),r){let n=vh(e*this.clockRate);if(this.max_seq!=null&&t.header.sequenceNumber<this.max_seq&&(this.cycles+=65536),this.max_seq=t.header.sequenceNumber,t.header.timestamp!==this.last_timestamp&&this.packets_received>1){let i=Math.abs(n-(this.last_arrival??0)-(t.header.timestamp-(this.last_timestamp??0)));this.jitter_q4+=i-(this.jitter_q4+8>>4)}this.last_arrival=n,this.last_timestamp=t.header.timestamp}}get fraction_lost(){let t=this.packets_expected-this.expected_prior;this.expected_prior=this.packets_expected;let e=this.packets_received-this.received_prior;this.received_prior=this.packets_received;let r=t-e;return t==0||r<=0?0:Math.floor((r<<8)/t)}get jitter(){return this.jitter_q4>>4}get packets_expected(){return this.cycles+(this.max_seq??0)-(this.base_seq??0)+1}get packets_lost(){let t=this.packets_expected-this.packets_received;return t<0?0:t}},Ss=xt("werift:packages/webrtc/src/transport/dtls.ts"),t6=class pY{constructor(e,r,n,i=[]){this.config=e,this.iceTransport=r,this.localCertificate=n,this.srtpProfiles=i,this.localCertificate??=pY.localCertificate}id=QRe().toString();state="new";role="auto";srtpStarted=!1;transportSequenceNumber=0;bytesSent=0;bytesReceived=0;packetsSent=0;packetsReceived=0;dataReceiver=()=>{};dtls;srtp;srtcp;onStateChange=new qe;onRtcp=new qe;onRtp=new qe;static localCertificate;static localCertificatePromise;remoteParameters;get localParameters(){return new Zk(this.localCertificate?this.localCertificate.getFingerprints():[],this.role)}static async SetupCertificate(){return this.localCertificate?this.localCertificate:this.localCertificatePromise?this.localCertificatePromise:(this.localCertificatePromise=(async()=>{let{certPem:e,keyPem:r,signatureHash:n}=await Rx.createSelfSignedCertificateWithKey({signature:Ea.ecdsa_3,hash:kx.sha256_4},Wc.secp256r1_23);return this.localCertificate=new sO(r,e,n),this.localCertificate})(),this.localCertificatePromise)}setRemoteParams(e){let r=t1e([...this.remoteParameters?.fingerprints??[],...e.fingerprints]),n=e.role==="auto"&&this.remoteParameters?.role?this.remoteParameters.role:e.role;this.remoteParameters=new Zk(r,n)}async start(){if(this.state!=="new")throw new Error("state must be new");if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw new Error("remote fingerprint not exist");this.role==="auto"&&(this.iceTransport.role==="controlling"?this.role="server":this.role="client"),this.setState("connecting"),await new Promise(async(e,r)=>{this.role==="server"?this.dtls=new mX({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:rK(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0,certificateRequest:!0}):this.dtls=new jN({cert:this.localCertificate?.certPem,key:this.localCertificate?.privateKey,signatureHash:this.localCertificate?.signatureHash,transport:rK(this.iceTransport.connection),srtpProfiles:this.srtpProfiles,extendedMasterSecret:!0}),this.dtls.onData.subscribe(n=>{this.config.debug.inboundPacketLoss&&this.config.debug.inboundPacketLoss/100<Math.random()||this.dataReceiver(n)}),this.dtls.onClose.subscribe(()=>{this.state!=="failed"&&this.setState("closed")}),this.dtls.onConnect.once(e),this.dtls.onError.once(n=>{this.setState("failed"),Ss("dtls failed",n),r(n)}),this.dtls instanceof jN&&(await ZRe(100),this.dtls.connect().catch(n=>{this.setState("failed"),Ss("dtls connect failed",n),r(n)}))});try{this.verifyRemoteCertificateFingerprint()}catch(e){throw this.setState("failed"),this.dtls?.close(),e}this.srtpProfiles.length>0&&this.startSrtp(),this.setState("connected"),Ss("dtls connected")}verifyRemoteCertificateFingerprint(){if(!this.remoteParameters||this.remoteParameters.fingerprints.length===0)throw new Error("remote fingerprint not exist");let e=this.dtls?.remoteCertificate;if(!e)throw new Error("remote certificate not available");let r=this.remoteParameters.fingerprints.flatMap(({algorithm:a,value:c})=>{let u=rO(a);if(!u)return[];let d=Yk(c);if(!d)throw new Error("remote fingerprint value is empty");return[{normalizedAlgorithm:u,normalizedValue:d}]});if(r.length===0)throw new Error("no supported remote fingerprint algorithms");let n=n1e(r),i=r.filter(({normalizedAlgorithm:a})=>a===n),o=i.reduce((a,{normalizedAlgorithm:c})=>(a.has(c)||a.set(c,Yk(tO(e,c))),a),new Map);if(!i.some(({normalizedAlgorithm:a,normalizedValue:c})=>o.get(a)===c))throw new Error("remote certificate fingerprint mismatch")}updateSrtpSession(){if(!this.dtls)throw new Error;let e=this.dtls.srtp.srtpProfile;if(!e)throw new Error("need srtpProfile");Ss("selected SRTP Profile",e);let{localKey:r,localSalt:n,remoteKey:i,remoteSalt:o}=this.dtls.extractSessionKeys(dJ(e),lJ(e)),s={keys:{localMasterKey:r,localMasterSalt:n,remoteMasterKey:i,remoteMasterSalt:o},profile:e};this.srtp=new fX(s),this.srtcp=new lX(s)}startSrtp(){this.srtpStarted||(this.srtpStarted=!0,this.updateSrtpSession(),this.iceTransport.connection.onData.subscribe(e=>{if(!(this.config.debug.inboundPacketLoss&&this.config.debug.inboundPacketLoss/100<Math.random())&&RJ(e))if(this.bytesReceived+=e.length,this.packetsReceived++,$J(e)){let r;try{r=this.srtcp.decrypt(e)}catch(i){if(i instanceof Tf){Ss("dropping invalid SRTCP packet",i);return}throw i}let n;try{n=UJ.deSerialize(r)}catch(i){Ss("dropping malformed SRTCP packet",i);return}for(let i of n)try{this.onRtcp.execute(i)}catch(o){Ss("RTCP error",o)}}else{let r;try{r=this.srtp.decrypt(e)}catch(i){if(i instanceof Tf){Ss("dropping invalid SRTP packet",i);return}throw i}let n;try{n=Gc.deSerialize(r)}catch(i){Ss("dropping malformed SRTP packet",i);return}try{this.onRtp.execute(n)}catch(i){Ss("RTP error",i)}}}))}sendData=async e=>{if(!(this.config.debug.outboundPacketLoss&&this.config.debug.outboundPacketLoss/100<Math.random())){if(!this.dtls)throw new Error("dtls not established");await this.dtls.send(e)}};async sendRtp(e,r){try{let n=this.srtp.encrypt(e,r);return this.config.debug.outboundPacketLoss&&this.config.debug.outboundPacketLoss/100<Math.random()||(this.bytesSent+=n.length,this.packetsSent++,await this.iceTransport.connection.send(n).catch(()=>{})),n.length}catch(n){return Ss("failed to send",n),0}}async sendRtcp(e){let r=Buffer.concat(e.map(i=>i.serialize())),n=this.srtcp.encrypt(r);if(this.config.debug.outboundPacketLoss&&this.config.debug.outboundPacketLoss/100<Math.random())return n.length;this.bytesSent+=n.length,this.packetsSent++,await this.iceTransport.connection.send(n).catch(()=>{})}setState(e){e!=this.state&&(this.state=e,this.onStateChange.execute(e))}async stop(){this.setState("closed"),await this.iceTransport.stop()}async getStats(){let e=Bd(),r=[],i={type:"transport",id:hr("transport",this.id),timestamp:e,bytesSent:this.bytesSent,bytesReceived:this.bytesReceived,packetsSent:this.packetsSent,packetsReceived:this.packetsReceived,dtlsState:this.state,iceState:this.iceTransport.state,selectedCandidatePairId:this.iceTransport.connection.nominated?hr("candidate-pair",this.iceTransport.connection.nominated.localCandidate.foundation,this.iceTransport.connection.nominated.remoteCandidate.foundation):void 0,localCertificateId:this.localCertificate?hr("certificate","local"):void 0,remoteCertificateId:this.remoteParameters?hr("certificate","remote"):void 0,dtlsRole:this.role==="auto"?void 0:this.role};if(r.push(i),this.localCertificate){let s=this.localCertificate.getFingerprints();if(s.length>0){let a={type:"certificate",id:hr("certificate","local"),timestamp:e,fingerprint:s[0].value,fingerprintAlgorithm:s[0].algorithm,base64Certificate:Buffer.from(this.localCertificate.certPem).toString("base64")};r.push(a)}}if(this.remoteParameters&&this.remoteParameters.fingerprints.length>0){let s={type:"certificate",id:hr("certificate","remote"),timestamp:e,fingerprint:this.remoteParameters.fingerprints[0].value,fingerprintAlgorithm:this.remoteParameters.fingerprints[0].algorithm,base64Certificate:""};r.push(s)}let o=await this.iceTransport.getStats();return r.push(...o),r}},e1e=["new","connecting","connected","closed","failed"],sO=class{constructor(t,e,r){this.certPem=e,this.signatureHash=r;let n=Ux.Certificate.fromPEM(Buffer.from(e));this.publicKey=n.publicKey.toPEM(),this.privateKey=Ux.PrivateKey.fromPEM(Buffer.from(t)).toPEM()}publicKey;privateKey;getFingerprints(){return[new Qk("sha-256",tO(Ux.Certificate.fromPEM(Buffer.from(this.certPem)).raw,"sha256"))]}},Qk=class{constructor(t,e){this.algorithm=t,this.value=e}},Zk=class{constructor(t=[],e){this.fingerprints=t,this.role=e}},t1e=t=>{let e=new Set;return t.filter(({algorithm:r,value:n})=>{let i=`${rO(r)??r.trim().toLowerCase()}:${Yk(n)}`;return e.has(i)?!1:(e.add(i),!0)})},r1e=["sha512","sha384","sha256","sha224","sha1"],n1e=t=>r1e.find(e=>t.some(({normalizedAlgorithm:r})=>r===e))??t[0].normalizedAlgorithm,i1e=class{constructor(t){this.ice=t,t.onData.subscribe(e=>{aY(e)&&this.onData&&this.onData(e)})}closed=!1;onData=()=>{};get address(){return{}}type="ice";send=t=>this.ice.send(t);async close(){this.closed=!0,this.ice.close()}},rK=t=>new i1e(t),nK=xt("werift:packages/webrtc/src/transport/ice.ts"),mY=class{constructor(t){this.iceGather=t,this.connection=this.iceGather.connection,this.connection.stateChanged.subscribe(e=>{this.setState(e)}),this.iceGather.onIceCandidate=e=>{this.onIceCandidate.execute(e)}}id=o1e().toString();connection;state="new";waitStart;renominating=!1;onStateChange=new qe;onIceCandidate=new qe;onNegotiationNeeded=new qe;get role(){return this.connection.iceControlling?"controlling":"controlled"}get gatheringState(){return this.iceGather.gatheringState}get localCandidates(){return this.iceGather.localCandidates}get localParameters(){return this.iceGather.localParameters}setState(t){t!==this.state&&(this.state=t,this.onStateChange.execute(t))}gather(){return this.iceGather.gather()}addRemoteCandidate=t=>{if(!this.connection.remoteCandidatesEnd)return t?this.connection.addRemoteCandidate(gY(t)):this.connection.addRemoteCandidate(void 0)};setRemoteParams(t,e=!1){e&&(this.renominating=!0),this.connection.remoteUsername&&this.connection.remotePassword&&(this.connection.remoteUsername!==t.usernameFragment||this.connection.remotePassword!==t.password)&&(this.renominating?(nK("renomination",t),this.connection.resetNominatedPair(),this.renominating=!1):(nK("restart",t),this.restart())),this.connection.setRemoteParams(t)}restart(){this.connection.restart(),this.setState("new"),this.iceGather.gatheringState="new",this.waitStart=void 0,this.onNegotiationNeeded.execute()}async start(){if(this.state==="closed")throw new Error("RTCIceTransport is closed");if(!this.connection.remotePassword||!this.connection.remoteUsername)throw new Error("remoteParams missing");this.waitStart&&await this.waitStart.asPromise(),this.waitStart=new qe,this.setState("checking");try{await this.connection.connect()}catch(t){throw this.setState("failed"),t}this.waitStart.execute(),this.waitStart.complete(),this.waitStart=void 0}async stop(){this.state!=="closed"&&(this.setState("closed"),await this.connection.close()),this.onStateChange.complete(),this.onIceCandidate.complete(),this.onNegotiationNeeded.complete()}async getStats(){let t=Bd(),e=[];for(let n of this.localCandidates){let i={type:"local-candidate",id:hr("local-candidate",n.foundation),timestamp:t,transportId:hr("transport",this.id),address:n.ip,port:n.port,protocol:n.protocol,candidateType:n.type,priority:n.priority,foundation:n.foundation};e.push(i)}for(let n of this.connection.remoteCandidates){let i=Rh(n),o={type:"remote-candidate",id:hr("remote-candidate",i.foundation),timestamp:t,transportId:hr("transport",this.id),address:i.ip,port:i.port,protocol:i.protocol,candidateType:i.type,priority:i.priority,foundation:i.foundation};e.push(o)}let r=this.connection?.candidatePairs?[...this.connection.candidatePairs.filter(n=>n.nominated),...this.connection.candidatePairs.filter(n=>!n.nominated)]:[];for(let n of r){let i={type:"candidate-pair",id:hr("candidate-pair",n.foundation),timestamp:t,transportId:hr("transport",this.id),localCandidateId:hr("local-candidate",n.localCandidate.foundation),remoteCandidateId:hr("remote-candidate",n.remoteCandidate.foundation),state:n.state,nominated:n.nominated,packetsSent:n.packetsSent,packetsReceived:n.packetsReceived,bytesSent:n.bytesSent,bytesReceived:n.bytesReceived,currentRoundTripTime:n.rtt};e.push(i)}return e}},s1e=["new","checking","connected","completed","disconnected","failed","closed"],a1e=["new","gathering","complete"],hY=class{constructor(t={}){this.options=t,this.connection=new GX(!1,this.options),this.connection.onIceCandidate.subscribe(e=>{this.onIceCandidate(Rh(e))})}onIceCandidate=()=>{};gatheringState="new";connection;onGatheringStateChange=new qe;async gather(){this.gatheringState==="new"&&(this.setState("gathering"),await this.connection.gatherCandidates(),this.onIceCandidate(void 0),this.setState("complete"))}get localCandidates(){return this.connection.localCandidates.map(Rh)}get localParameters(){return new cO({usernameFragment:this.connection.localUsername,password:this.connection.localPassword})}setState(t){t!==this.gatheringState&&(this.gatheringState=t,this.onGatheringStateChange.execute(t))}};yY=class{candidate;sdpMid;sdpMLineIndex;usernameFragment;constructor(t){Object.assign(this,t)}static fromSdp(t){let e=Td.fromSdp(t);return Rh(e).toJSON()}static isThis(t){if(typeof t?.candidate=="string")return!0}toJSON(){return{candidate:this.candidate,sdpMid:this.sdpMid,sdpMLineIndex:this.sdpMLineIndex,usernameFragment:this.usernameFragment}}},aO=class{constructor(t,e,r,n,i,o,s,a,c){this.component=t,this.foundation=e,this.ip=r,this.port=n,this.priority=i,this.protocol=o,this.type=s,this.generation=a,this.ufrag=c}relatedAddress;relatedPort;sdpMid;sdpMLineIndex;tcpType;toJSON(){return new yY({candidate:lO(this),sdpMLineIndex:this.sdpMLineIndex,sdpMid:this.sdpMid,usernameFragment:this.ufrag})}static fromJSON(t){try{if(!t.candidate)throw new Error("candidate is required");let e=fO(t.candidate);return e.sdpMLineIndex=t.sdpMLineIndex??void 0,e.sdpMid=t.sdpMid??void 0,e}catch{}}},cO=class{iceLite=!1;usernameFragment;password;constructor(t={}){Object.assign(this,t)}},Ra=class vY{constructor(e=0,r=Buffer.from("")){this.flags=e,this._body=r}get body(){return this._body}set body(e){this._body=e}static type=-1;get type(){return vY.type}get bytes(){if(!this.body)throw new Error;let e=Buffer.alloc(4);return e.writeUInt8(this.type,0),e.writeUInt8(this.flags,1),e.writeUInt16BE(this.body.length+4,2),Buffer.concat([e,this.body,...[...Array(Yx(this.body.length))].map(()=>Buffer.from("\0"))])}},uO=class extends Ra{constructor(t=0,e){super(t,e),this.flags=t,e?(this.initiateTag=e.readUInt32BE(0),this.advertisedRwnd=e.readUInt32BE(4),this.outboundStreams=e.readUInt16BE(8),this.inboundStreams=e.readUInt16BE(10),this.initialTsn=e.readUInt32BE(12),this.params=UY(e.slice(16))):(this.initiateTag=0,this.advertisedRwnd=0,this.outboundStreams=0,this.inboundStreams=0,this.initialTsn=0,this.params=[])}initiateTag;advertisedRwnd;outboundStreams;inboundStreams;initialTsn;params;get body(){let t=Buffer.alloc(16);return t.writeUInt32BE(this.initiateTag,0),t.writeUInt32BE(this.advertisedRwnd,4),t.writeUInt16BE(this.outboundStreams,8),t.writeUInt16BE(this.inboundStreams,10),t.writeUInt32BE(this.initialTsn,12),Buffer.concat([t,HY(this.params)])}},Mk=class xY extends uO{static type=1;get type(){return xY.type}},r6=class SY extends uO{static type=2;get type(){return SY.type}},d1e=class bY extends uO{static type=130;get type(){return bY.type}},Lk=class wY extends Ra{constructor(e=0,r){if(super(e,r),this.flags=e,r){this.cumulativeTsn=r.readUInt32BE(0);let n=4;for(;n<r.length;)this.streams.push([r.readUInt16BE(n),r.readUInt16BE(n+2)]),n+=4}else this.cumulativeTsn=0}static type=192;streams=[];cumulativeTsn;get type(){return wY.type}set body(e){}get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),Buffer.concat([e,...this.streams.map(([r,n])=>{let i=Buffer.alloc(4);return i.writeUInt16BE(r,0),i.writeUInt16BE(n,2),i})])}},Hk=class IY extends Ra{constructor(e=0,r){super(e,r),this.flags=e,r&&(this.tsn=r.readUInt32BE(0),this.streamId=r.readUInt16BE(4),this.streamSeqNum=r.readUInt16BE(6),this.protocol=r.readUInt32BE(8),this.userData=r.slice(12))}static type=0;get type(){return IY.type}tsn=0;streamId=0;streamSeqNum=0;protocol=0;userData=Buffer.from("");abandoned=!1;acked=!1;misses=0;retransmit=!1;sentCount=0;bookSize=0;expiry;maxRetransmits;sentTime;get bytes(){let e=16+this.userData.length,r=Buffer.alloc(16);r.writeUInt8(this.type,0),r.writeUInt8(this.flags,1),r.writeUInt16BE(e,2),r.writeUInt32BE(this.tsn,4),r.writeUInt16BE(this.streamId,8),r.writeUInt16BE(this.streamSeqNum,10),r.writeUInt32BE(this.protocol,12);let n=Buffer.concat([r,this.userData]);return e%4&&(n=Buffer.concat([n,...[...Array(Yx(e))].map(()=>Buffer.from("\0"))])),n}},n6=class EY extends Ra{static type=10;get type(){return EY.type}},i6=class kY extends Ra{static type=11;get type(){return kY.type}},Xx=class extends Ra{constructor(t=0,e=void 0){super(t,e),this.flags=t,e&&(this.params=UY(e))}params=[];get body(){return HY(this.params)}},o6=class RY extends Xx{static type=6;get type(){return RY.type}},Uk=class s6 extends Xx{static type=9;static CODE={InvalidStreamIdentifier:1,MissingMandatoryParameter:2,StaleCookieError:3,OutofResource:4,UnresolvableAddress:5,UnrecognizedChunkType:6,InvalidMandatoryParameter:7,UnrecognizedParameters:8,NoUserData:9,CookieReceivedWhileShuttingDown:10,RestartofanAssociationwithNewAddresses:11,UserInitiatedAbort:12,ProtocolViolation:13};get type(){return s6.type}get descriptions(){return this.params.map(([e,r])=>({name:(Object.entries(s6.CODE).find(([,i])=>i===e)||[])[0],body:r}))}},a6=class AY extends Xx{static type=4;get type(){return AY.type}},CY=class PY extends Xx{static type=5;get type(){return PY.type}},c6=class _Y extends Xx{static type=130;get type(){return _Y.type}},u6=class TY extends Ra{constructor(e=0,r){if(super(e,r),this.flags=e,r){this.cumulativeTsn=r.readUInt32BE(0),this.advertisedRwnd=r.readUInt32BE(4);let n=r.readUInt16BE(8),i=r.readUInt16BE(10),o=12;[...Array(n)].forEach(()=>{this.gaps.push([r.readUInt16BE(o),r.readUInt16BE(o+2)]),o+=4}),[...Array(i)].forEach(()=>{this.duplicates.push(r.readUInt32BE(o)),o+=4})}}static type=3;get type(){return TY.type}gaps=[];duplicates=[];cumulativeTsn=0;advertisedRwnd=0;get bytes(){let e=16+4*(this.gaps.length+this.duplicates.length),r=Buffer.alloc(16);r.writeUInt8(this.type,0),r.writeUInt8(this.flags,1),r.writeUInt16BE(e,2),r.writeUInt32BE(this.cumulativeTsn,4),r.writeUInt32BE(this.advertisedRwnd,8),r.writeUInt16BE(this.gaps.length,12),r.writeUInt16BE(this.duplicates.length,14);let n=Buffer.concat([r,...this.gaps.map(i=>{let o=Buffer.alloc(4);return o.writeUInt16BE(i[0],0),o.writeUInt16BE(i[1],2),o})]);return n=Buffer.concat([n,...this.duplicates.map(i=>{let o=Buffer.alloc(4);return o.writeUInt32BE(i,0),o})]),n}},DY=class BY extends Ra{constructor(e=0,r){super(e,r),this.flags=e,r&&(this.cumulativeTsn=r.readUInt32BE(0))}static type=7;get type(){return BY.type}cumulativeTsn=0;get body(){let e=Buffer.alloc(4);return e.writeUInt32BE(this.cumulativeTsn,0),e}},NY=class OY extends Ra{static type=8;get type(){return OY.type}},MY=class LY extends Ra{static type=14;get type(){return LY.type}},l1e=[Hk,Mk,r6,u6,a6,CY,o6,DY,NY,Uk,n6,i6,MY,c6,Lk],f1e=l1e.reduce((t,e)=>(t[e.type]=e,t),{});d6=class l6{constructor(e,r,n,i){this.requestSequence=e,this.responseSequence=r,this.lastTsn=n,this.streams=i}static type=13;get type(){return l6.type}get bytes(){let e=Buffer.from(jc.jspack.Pack("!LLL",[this.requestSequence,this.responseSequence,this.lastTsn]));return Buffer.concat([e,...this.streams.map(r=>Buffer.from(jc.jspack.Pack("!H",[r])))])}static parse(e){let[r,n,i]=jc.jspack.Unpack("!LLL",e),o=[];for(let s=12;s<e.length;s+=2)o.push(jc.jspack.Unpack("!H",e.slice(s))[0]);return new l6(r,n,i,o)}},$Y=class f6{constructor(e,r){this.requestSequence=e,this.newStreams=r}static type=17;get type(){return f6.type}get bytes(){return Buffer.from(jc.jspack.Pack("!LHH",[this.requestSequence,this.newStreams,0]))}static parse(e){let[r,n]=jc.jspack.Unpack("!LHH",e);return new f6(r,n)}},Ik={ReconfigResultSuccessPerformed:1,BadSequenceNumber:5},$k=class p6{constructor(e,r){this.responseSequence=e,this.result=r}static type=16;get type(){return p6.type}get bytes(){return Buffer.from(jc.jspack.Pack("!LL",[this.responseSequence,this.result]))}static parse(e){let[r,n]=jc.jspack.Unpack("!LL",e);return new p6(r,n)}},oK={13:d6,16:$k,17:$Y},nr=xt("werift/sctp/sctp"),y1e=24,v1e=60,sK=65535,bs=1200,yx=1,FY=2,m6=4,aK=10,x1e=8,cK=1/8,uK=1/4,dK=3,S1e=1,b1e=60,eR=2**32,w1e=200,I1e=30,lK=135,fK=7,pK=32776,mK=49152,E1e=["new","closed","connected","connecting"],k1e=class h6{constructor(e,r=5e3){this.transport=e,this.port=r,this.localPort=this.port,this.transport.onData=n=>{this.handleData(n)}}flush=new qe;stateChanged=g1e(E1e);onReconfigStreams=new qe;onReceive=new qe;onSackReceived=async()=>{};associationState=1;started=!1;state="new";isServer=!0;isStopping=!1;isClosed=!1;hmacKey=u1e(16);localPartialReliability=!0;localPort;localVerificationTag=jk();remoteExtensions=[];remotePartialReliability=!0;remotePort;remoteVerificationTag=0;advertisedRwnd=1024*1024;peerAdvertisedRwnd=this.advertisedRwnd;get peerRwnd(){return Math.max(0,this.peerAdvertisedRwnd-this.flightSize)}inboundStreams={};_inboundStreamsCount=0;_inboundStreamsMax=sK;lastReceivedTsn;sackDuplicates=[];sackMisOrdered=new Set;sackNeeded=!1;sackPacketCount=0;sackHasNewDataInPacket=!1;sackImmediate=!1;sackTimeout;cwnd=3*bs;fastRecoveryExit;fastRecoveryTransmit=!1;forwardTsnChunk;flightSize=0;outboundQueue=[];outboundStreamSeq={};_outboundStreamsCount=sK;localTsn=Number(jk());lastSackedTsn=bf(this.localTsn);advancedPeerAckTsn=bf(this.localTsn);partialBytesAcked=0;sentQueue=[];transmitting=!1;transmitRequested=!1;reconfigRequestSeq=this.localTsn;reconfigResponseSeq=0;reconfigRequest;reconfigQueue=[];srtt;rttvar;rto=dK;timer1Handle;timer1Chunk;timer1Failures=0;timer2Handle;timer2Chunk;timer2Failures=0;timer3Handle;timerReconfigHandle;timerReconfigFailures=0;timerHeartbeatHandle;heartbeatInterval=I1e;ssthresh;get isStopped(){return this.isStopping||this.isClosed}get maxChannels(){if(this._inboundStreamsCount>0)return Math.min(this._inboundStreamsCount,this._outboundStreamsCount)}static client(e,r=5e3){let n=new h6(e,r);return n.isServer=!1,n}static server(e,r=5e3){let n=new h6(e,r);return n.isServer=!0,n}async handleData(e){if(this.isStopped)return;let r,[,,n,i]=p1e(e);if(i.filter(s=>s.type===Mk.type).length>0){if(i.length!=1)throw new Error;r=0}else r=this.localVerificationTag;if(n===r){this.sackHasNewDataInPacket=!1;for(let s of i)await this.receiveChunk(s);this.sackNeeded&&(this.sackHasNewDataInPacket&&this.sackPacketCount++,this.sackPacketCount>=2&&(this.sackImmediate=!0),await this.scheduleSack())}}async scheduleSack(){if(!this.isStopped&&this.sackNeeded){if(this.sackImmediate){this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),await this.sendSack();return}this.sackTimeout||(this.sackTimeout=setTimeout(()=>{this.sackTimeout=void 0,this.sendSack().catch(e=>{nr("send delayed sack failed",e.message)})},w1e))}}async sendSack(){if(this.isStopped||!this.sackNeeded)return;let e=[],r;[...this.sackMisOrdered].sort().forEach(i=>{let o=(i-this.lastReceivedTsn)%eR;i===r?e[e.length-1][1]=o:e.push([o,o]),r=hh(i)});let n=new u6(0,void 0);n.cumulativeTsn=this.lastReceivedTsn,n.advertisedRwnd=Math.max(0,this.advertisedRwnd),n.duplicates=[...this.sackDuplicates],n.gaps=e,await this.sendChunk(n).catch(i=>{nr("send sack failed",i.message)}),this.sackDuplicates=[],this.sackNeeded=!1,this.sackPacketCount=0,this.sackImmediate=!1}async receiveChunk(e){switch(e.type){case Hk.type:this.receiveDataChunk(e);break;case Mk.type:{if(!this.isServer)return;let r=e;nr("receive init",r),this.lastReceivedTsn=bf(r.initialTsn),this.reconfigResponseSeq=bf(r.initialTsn),this.remoteVerificationTag=r.initiateTag,this.ssthresh=r.advertisedRwnd,this.peerAdvertisedRwnd=r.advertisedRwnd,this.getExtensions(r.params),this._inboundStreamsCount=Math.min(r.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,r.inboundStreams);let n=new r6;n.initiateTag=this.localVerificationTag,n.advertisedRwnd=this.advertisedRwnd,n.outboundStreams=this._outboundStreamsCount,n.inboundStreams=this._inboundStreamsCount,n.initialTsn=this.localTsn,this.setExtensions(n.params);let i=Date.now()/1e3,o=Buffer.from(Ok.jspack.Pack("!L",[i]));o=Buffer.concat([o,iK("sha1",this.hmacKey).update(o).digest()]),n.params.push([fK,o]),nr("send initAck",n),await this.sendChunk(n).catch(s=>{nr("send initAck failed",s.message)})}break;case r6.type:{if(this.associationState!=2)return;let r=e;this.timer1Cancel(),this.lastReceivedTsn=bf(r.initialTsn),this.reconfigResponseSeq=bf(r.initialTsn),this.remoteVerificationTag=r.initiateTag,this.ssthresh=r.advertisedRwnd,this.peerAdvertisedRwnd=r.advertisedRwnd,this.getExtensions(r.params),this._inboundStreamsCount=Math.min(r.outboundStreams,this._inboundStreamsMax),this._outboundStreamsCount=Math.min(this._outboundStreamsCount,r.inboundStreams);let n=new n6;for(let[i,o]of r.params)if(i===fK){n.body=o;break}await this.sendChunk(n).catch(i=>{nr("send echo failed",i.message)}),this.timer1Start(n),this.setState(3)}break;case u6.type:await this.receiveSackChunk(e);break;case a6.type:{let r=new CY;r.params=e.params,await this.sendChunk(r).catch(n=>{nr("send heartbeat ack failed",n.message)})}break;case o6.type:this.setState(1);break;case DY.type:{this.timer2Cancel(),this.setState(7);let r=new NY;await this.sendChunk(r).catch(n=>{nr("send shutdown ack failed",n.message)}),this.t2Start(r),this.setState(6)}break;case Uk.type:nr("ErrorChunk",e.descriptions);break;case n6.type:{if(!this.isServer)return;let n=e.body,i=iK("sha1",this.hmacKey).update(n.slice(0,4)).digest();if(n?.length!=y1e||!n.slice(4).equals(i)){nr("x State cookie is invalid");return}let o=Date.now()/1e3,s=Ok.jspack.Unpack("!L",n)[0];if(s<o-v1e||s>o){let c=new Uk(0,void 0);c.params.push([Uk.CODE.StaleCookieError,Buffer.concat([...Array(8)].map(()=>Buffer.from("\0")))]),await this.sendChunk(c).catch(u=>{nr("send errorChunk failed",u.message)});return}let a=new i6;await this.sendChunk(a).catch(c=>{nr("send cookieAck failed",c.message)}),this.setState(4)}break;case i6.type:{if(this.associationState!=3)return;this.timer1Cancel(),this.setState(4)}break;case MY.type:{if(this.associationState!=8)return;this.timer2Cancel(),this.setState(1)}break;case c6.type:{if(this.associationState!=4)return;let r=e;for(let[n,i]of r.params){let o=oK[n];o&&await this.receiveReconfigParam(o.parse(i))}}break;case Lk.type:this.receiveForwardTsnChunk(e);break}}getExtensions(e){for(let[r,n]of e)r===mK?this.remotePartialReliability=!0:r===pK&&(this.remoteExtensions=[...n])}async receiveReconfigParam(e){switch(nr("receiveReconfigParam",oK[e.type]),e.type){case d6.type:{let r=e,n=new $k(r.requestSequence,Ik.ReconfigResultSuccessPerformed);this.reconfigResponseSeq=r.requestSequence,await this.sendReconfigParam(n),await Promise.all(r.streams.map(async i=>{delete this.inboundStreams[i],this.outboundStreamSeq[i]&&(this.reconfigQueue.includes(i)||this.reconfigQueue.push(i))})),await this.transmitReconfigRequest(),this.onReconfigStreams.execute(r.streams)}break;case $k.type:{let r=e;if(r.result!==Ik.ReconfigResultSuccessPerformed)nr("OutgoingSSNResetRequestParam failed",Object.keys(Ik).find(n=>Ik[n]===r.result));else if(r.responseSequence===this.reconfigRequest?.requestSequence){let n=this.reconfigRequest.streams.map(i=>(delete this.outboundStreamSeq[i],i));this.onReconfigStreams.execute(n),this.reconfigRequest=void 0,this.timerReconfigCancel(),this.rto=dK,this.timerReconfigFailures=0,this.reconfigQueue.length>0&&await this.transmitReconfigRequest()}}break;case $Y.type:{let r=e;this._inboundStreamsCount+=r.newStreams;let n=new $k(r.requestSequence,1);this.reconfigResponseSeq=r.requestSequence,await this.sendReconfigParam(n)}break}}receiveDataChunk(e){if(this.sackNeeded=!0,this.markReceived(e.tsn)){this.sackImmediate=!0;return}this.sackHasNewDataInPacket=!0,this.sackImmediate=!0,(e.flags&yx)===0&&(this.sackImmediate=!0),this.sackMisOrdered.size>0&&(this.sackImmediate=!0);let r=this.getInboundStream(e.streamId);r.addChunk(e),this.advertisedRwnd-=e.userData.length;for(let n of r.popMessages())this.advertisedRwnd+=n[2].length,this.receive(...n)}async receiveSackChunk(e){if(ba(this.lastSackedTsn,e.cumulativeTsn))return;let r=Date.now()/1e3;this.lastSackedTsn=e.cumulativeTsn;let n=this.flightSize>=this.cwnd,i=0,o=0;for(;this.sentQueue.length>0&&gh(this.lastSackedTsn,this.sentQueue[0].tsn);){let a=this.sentQueue.shift();i++,a?.acked||(o+=a.bookSize,this.flightSizeDecrease(a)),i===1&&a.sentCount===1&&this.updateRto(r-a.sentTime)}this.sentQueue.length||(this.sentQueue=[]);let s=!1;if(e.gaps.length>0){let a=new Set,c;e.gaps.forEach(d=>{for(let l=d[0];l<d[1]+1;l++)c=(e.cumulativeTsn+l)%eR,a.add(c)});let u=e.cumulativeTsn;for(let d of this.sentQueue){if(ba(d.tsn,c))break;a.has(d.tsn)&&!d.acked&&(o+=d.bookSize,d.acked=!0,this.flightSizeDecrease(d),u=d.tsn)}for(let d of this.sentQueue){if(ba(d.tsn,u))break;a.has(d.tsn)||(d.misses++,d.misses===3&&(d.misses=0,this.maybeAbandon(d)||(d.retransmit=!0),d.acked=!1,this.flightSizeDecrease(d),s=!0))}}this.fastRecoveryExit===void 0?(i&&n&&(this.cwnd<=this.ssthresh?this.cwnd+=Math.min(o,bs):(this.partialBytesAcked+=o,this.partialBytesAcked>=this.cwnd&&(this.partialBytesAcked-=this.cwnd,this.cwnd+=bs))),s&&(this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*bs),this.cwnd=this.ssthresh,this.partialBytesAcked=0,this.fastRecoveryExit=this.sentQueue[this.sentQueue.length-1].tsn,this.fastRecoveryTransmit=!0)):gh(e.cumulativeTsn,this.fastRecoveryExit)&&(this.fastRecoveryExit=void 0),this.sentQueue.length===0?this.timer3Cancel():i>0&&this.timer3Restart(),this.peerAdvertisedRwnd=e.advertisedRwnd,this.updateAdvancedPeerAckPoint(),await this.onSackReceived(),await this.transmit()}receiveForwardTsnChunk(e){if(this.sackNeeded=!0,this.sackImmediate=!0,gh(this.lastReceivedTsn,e.cumulativeTsn))return;let r=n=>ba(n,this.lastReceivedTsn);this.lastReceivedTsn=e.cumulativeTsn,this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(r));for(let n of[...this.sackMisOrdered].sort())if(n===hh(this.lastReceivedTsn))this.lastReceivedTsn=n;else break;this.sackDuplicates=this.sackDuplicates.filter(r),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(r));for(let[n,i]of e.streams){let o=this.getInboundStream(n);o.streamSequenceNumber=$n(i,1);for(let s of o.popMessages())this.advertisedRwnd+=s[2].length,this.receive(...s)}Object.values(this.inboundStreams).forEach(n=>{this.advertisedRwnd+=n.pruneChunks(this.lastReceivedTsn)})}updateRto(e){this.srtt?(this.rttvar=(1-uK)*this.rttvar+uK*Math.abs(this.srtt-e),this.srtt=(1-cK)*this.srtt+cK*e):(this.rttvar=e/2,this.srtt=e),this.rto=Math.max(S1e,Math.min(this.srtt+4*this.rttvar,b1e))}receive(e,r,n){this.onReceive.execute(e,r,n)}getInboundStream(e){return this.inboundStreams[e]||(this.inboundStreams[e]=new R1e),this.inboundStreams[e]}markReceived(e){if(gh(this.lastReceivedTsn,e)||this.sackMisOrdered.has(e))return this.sackDuplicates.push(e),!0;this.sackMisOrdered.add(e);for(let n of[...this.sackMisOrdered].sort())if(n===hh(this.lastReceivedTsn))this.lastReceivedTsn=n;else break;let r=n=>ba(n,this.lastReceivedTsn);return this.sackDuplicates=this.sackDuplicates.filter(r),this.sackMisOrdered=new Set([...this.sackMisOrdered].filter(r)),!1}send=async(e,r,n,{expiry:i,maxRetransmits:o,ordered:s}={expiry:void 0,maxRetransmits:void 0,ordered:!0})=>{let a=s&&this.outboundStreamSeq[e]||0,c=Math.ceil(n.length/bs),u=0,d=[];for(let l=0;l<c;l++){let f=new Hk(0,void 0);f.flags=0,s||(f.flags=m6),l===0&&(f.flags|=FY),l===c-1&&(f.flags|=yx),f.tsn=this.localTsn,f.streamId=e,f.streamSeqNum=a,f.protocol=r,f.userData=n.slice(u,u+bs),f.bookSize=f.userData.length,f.expiry=i,f.maxRetransmits=o,u+=bs,this.localTsn=hh(this.localTsn),d.push(f)}for(d.forEach(l=>{this.outboundQueue.push(l)}),s&&(this.outboundStreamSeq[e]=$n(a,1)),await this.transmit();this.outboundQueue.length;)await this.flush.asPromise()};async transmit(){if(!this.isStopped){if(this.transmitting){this.transmitRequested=!0;return}this.transmitting=!0;try{do this.transmitRequested=!1,await this.transmitOnce();while(this.transmitRequested)}finally{this.transmitting=!1}}}async transmitOnce(){if(this.isStopped)return;this.forwardTsnChunk&&(await this.sendChunk(this.forwardTsnChunk).catch(i=>{nr("send forwardTsn failed",i.message)}),this.forwardTsnChunk=void 0,this.timer3Handle||this.timer3Start());let e=this.fastRecoveryExit!=null?2*bs:4*bs,r=Math.min(this.flightSize+e,this.cwnd),n=!0;for(let i of this.sentQueue){if(i.retransmit){if(this.fastRecoveryTransmit)this.fastRecoveryTransmit=!1;else if(this.flightSize>=r)break;this.flightSizeIncrease(i),i.misses=0,i.retransmit=!1,i.sentCount++,await this.sendChunk(i).catch(o=>{nr("send data failed",o.message)}),n&&this.timer3Restart()}n=!1}for(;this.outboundQueue.length>0&&this.flightSize<r&&this.peerRwnd>0;){let i=this.outboundQueue.shift();if(!i)break;if(i.bookSize>this.peerRwnd&&this.flightSize>0){this.outboundQueue.unshift(i);break}this.sentQueue.push(i),this.flightSizeIncrease(i),i.sentCount++,i.sentTime=Date.now()/1e3,await this.sendChunk(i).catch(o=>{nr("send data outboundQueue failed",o.message)}),this.timer3Handle||this.timer3Start()}this.outboundQueue.length||(this.outboundQueue=[]),this.flush.execute()}async transmitReconfigRequest(){if(this.reconfigQueue.length>0&&this.associationState===4&&!this.reconfigRequest){let e=[...new Set(this.reconfigQueue)],r=e.slice(0,lK);this.reconfigQueue=e.slice(lK);let n=new d6(this.reconfigRequestSeq,this.reconfigResponseSeq,bf(this.localTsn),r);this.reconfigRequestSeq=hh(this.reconfigRequestSeq),this.reconfigRequest=n,await this.sendReconfigParam(n),this.timerReconfigHandleStart()}}async sendReconfigParam(e){nr("sendReconfigParam",e);let r=new c6;r.params.push([e.type,e.bytes]),await this.sendChunk(r).catch(n=>{nr("send reconfig failed",n.message)})}async sendResetRequest(e){nr("sendResetRequest",e);let r=new Hk(0,void 0);r.streamId=e,this.outboundQueue.push(r),this.timer3Handle||await this.transmit()}flightSizeIncrease(e){this.flightSize+=e.bookSize}flightSizeDecrease(e){this.flightSize=Math.max(0,this.flightSize-e.bookSize)}timer1Start(e){if(this.timer1Handle)throw new Error;this.timer1Chunk=e,this.timer1Failures=0,this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}timer1Expired=()=>{if(!this.isStopped)if(this.timer1Failures++,this.timer1Handle=void 0,this.timer1Failures>x1e)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer1Chunk).catch(e=>{nr("send timer1 chunk failed",e.message)})}),this.isStopped)return;this.timer1Handle=setTimeout(this.timer1Expired,this.rto*1e3)}};timer1Cancel(){this.timer1Handle&&(clearTimeout(this.timer1Handle),this.timer1Handle=void 0,this.timer1Chunk=void 0)}t2Start(e){if(this.timer2Handle)throw new Error;this.timer2Chunk=e,this.timer2Failures=0,this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}timer2Expired=()=>{if(!this.isStopped)if(this.timer2Failures++,this.timer2Handle=void 0,this.timer2Failures>aK)this.setState(1);else{if(setImmediate(()=>{this.isStopped||this.sendChunk(this.timer2Chunk).catch(e=>{nr("send timer2Chunk failed",e.message)})}),this.isStopped)return;this.timer2Handle=setTimeout(this.timer2Expired,this.rto*1e3)}};timer2Cancel(){this.timer2Handle&&(clearTimeout(this.timer2Handle),this.timer2Handle=void 0,this.timer2Chunk=void 0)}timer3Start(){if(!this.isStopped){if(this.timer3Handle)throw new Error;this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3)}}timer3Restart(){this.isStopped||(this.timer3Cancel(),this.timer3Handle=setTimeout(this.timer3Expired,this.rto*1e3))}timer3Expired=()=>{this.isStopped||(this.timer3Handle=void 0,this.sentQueue.forEach(e=>{this.maybeAbandon(e)||(e.retransmit=!0)}),this.updateAdvancedPeerAckPoint(),this.fastRecoveryExit=void 0,this.flightSize=0,this.partialBytesAcked=0,this.ssthresh=Math.max(Math.floor(this.cwnd/2),4*bs),this.cwnd=bs,this.transmit())};timer3Cancel(){this.timer3Handle&&(clearTimeout(this.timer3Handle),this.timer3Handle=void 0)}timerReconfigHandleStart(){this.isStopped||this.timerReconfigHandle||(nr("timerReconfigHandleStart",{rto:this.rto}),this.timerReconfigFailures=0,this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3))}timerReconfigHandleExpired=async()=>{if(!this.isStopped){if(this.timerReconfigFailures++,this.rto=Math.ceil(this.rto*1.5),this.timerReconfigFailures>aK)nr("timerReconfigFailures",this.timerReconfigFailures),this.setState(1),this.timerReconfigHandle=void 0;else if(this.reconfigRequest){if(nr("timerReconfigHandleExpired",this.timerReconfigFailures,this.rto),await this.sendReconfigParam(this.reconfigRequest),this.isStopped)return;this.timerReconfigHandle=setTimeout(this.timerReconfigHandleExpired,this.rto*1e3)}}};timerReconfigCancel(){this.timerReconfigHandle&&(nr("timerReconfigCancel"),clearTimeout(this.timerReconfigHandle),this.timerReconfigHandle=void 0,this.timerReconfigFailures=0)}heartbeatStart(){this.timerHeartbeatHandle||this.associationState!==4||(this.timerHeartbeatHandle=setTimeout(this.timerHeartbeatExpired,(this.rto+this.heartbeatInterval)*1e3))}heartbeatRestart(){this.heartbeatCancel(),this.heartbeatStart()}heartbeatCancel(){this.timerHeartbeatHandle&&(clearTimeout(this.timerHeartbeatHandle),this.timerHeartbeatHandle=void 0)}timerHeartbeatExpired=async()=>{if(this.timerHeartbeatHandle=void 0,this.associationState===4){if(this.flightSize===0&&this.outboundQueue.length===0){let e=new a6;e.params.push([1,Buffer.from(Ok.jspack.Pack("!L",[Math.floor(Date.now()/1e3)]))]),await this.sendChunk(e).catch(r=>{nr("send heartbeat failed",r.message)})}this.heartbeatStart()}};setHeartbeatInterval(e){if(e<=0)throw new Error("heartbeat interval must be > 0");this.heartbeatInterval=e,this.heartbeatRestart()}updateAdvancedPeerAckPoint(){ba(this.lastSackedTsn,this.advancedPeerAckTsn)&&(this.advancedPeerAckTsn=this.lastSackedTsn);let e=0,r={};for(;this.sentQueue.length>0&&this.sentQueue[0].abandoned;){let n=this.sentQueue.shift();this.advancedPeerAckTsn=n.tsn,e++,n.flags&m6||(r[n.streamId]=n.streamSeqNum)}this.sentQueue.length||(this.sentQueue=[]),e&&(this.forwardTsnChunk=new Lk(0,void 0),this.forwardTsnChunk.cumulativeTsn=this.advancedPeerAckTsn,this.forwardTsnChunk.streams=Object.entries(r).map(([n,i])=>[Number(n),i]))}maybeAbandon(e){if(e.abandoned)return!0;if(!(!!e.maxRetransmits&&e.maxRetransmits<e.sentCount||!!e.expiry&&e.expiry<Date.now()/1e3))return!1;let n=this.sentQueue.findIndex(i=>i.type===e.type);for(let i=n;i>=0;i--){let o=this.sentQueue[i];if(o.abandoned=!0,o.retransmit=!1,o.flags&yx)break}for(let i=n;i<this.sentQueue.length;i++){let o=this.sentQueue[i];if(o.abandoned=!0,o.retransmit=!1,o.flags&yx)break}return!0}static getCapabilities(){return new A1e(65536)}setRemotePort(e){this.remotePort=e}async start(e){this.started||(this.started=!0,this.setConnectionState("connecting"),e&&this.setRemotePort(e),this.isServer||await this.init())}async init(){let e=new Mk;e.initiateTag=this.localVerificationTag,e.advertisedRwnd=this.advertisedRwnd,e.outboundStreams=this._outboundStreamsCount,e.inboundStreams=this._inboundStreamsMax,e.initialTsn=this.localTsn,this.setExtensions(e.params),nr("send init",e);try{await this.sendChunk(e),this.timer1Start(e),this.setState(2)}catch(r){nr("send init failed",r.message)}}setExtensions(e){let r=[];this.localPartialReliability&&(e.push([mK,Buffer.from("")]),r.push(Lk.type)),r.push(d1e.type),e.push([pK,Buffer.from(r)])}async sendChunk(e){if(this.state==="closed")return;if(this.remotePort===void 0)throw new Error("invalid remote port");let r=m1e(this.localPort,this.remotePort,this.remoteVerificationTag,e);await this.transport.send(r)}setState(e){e!=this.associationState&&(this.associationState=e),e===4?(this.isStopping=!1,this.isClosed=!1,this.setConnectionState("connected"),this.heartbeatStart()):e===1&&(this.isClosed=!0,this.timer1Cancel(),this.timer2Cancel(),this.timer3Cancel(),this.timerReconfigCancel(),this.heartbeatCancel(),this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),this.setConnectionState("closed"),this.removeAllListeners())}setConnectionState(e){this.state=e,nr("setConnectionState",e),this.stateChanged[e].execute()}async stop(){if(this.isStopped){this.setState(1);return}this.isStopping=!0,this.transport.onData=void 0,this.sackTimeout&&(clearTimeout(this.sackTimeout),this.sackTimeout=void 0),this.associationState!==1&&await this.abort(),this.setState(1),clearTimeout(this.timer1Handle),clearTimeout(this.timer2Handle),clearTimeout(this.timer3Handle),clearTimeout(this.timerReconfigHandle),clearTimeout(this.timerHeartbeatHandle),clearTimeout(this.sackTimeout)}async abort(){let e=new o6;await this.sendChunk(e).catch(r=>{nr("send abort failed",r.message)})}removeAllListeners(){Object.values(this.stateChanged).forEach(e=>e.allUnsubscribe())}},R1e=class{reassembly=[];streamSequenceNumber=0;constructor(){}addChunk(t){if(this.reassembly.length===0||ba(t.tsn,this.reassembly[this.reassembly.length-1].tsn)){this.reassembly.push(t);return}for(let[e,r]of h1e(this.reassembly)){if(r.tsn===t.tsn)throw new Error("duplicate chunk in reassembly");if(ba(r.tsn,t.tsn)){this.reassembly.splice(e,0,t);break}}}*popMessages(){let t=0,e,r,n;for(;t<this.reassembly.length;){let i=this.reassembly[t];if(e===void 0){if(n=!(i.flags&m6),!(i.flags&FY)){if(n)break;t++;continue}if(n&&iR(i.streamSeqNum,this.streamSequenceNumber))break;r=i.tsn,e=t}else if(i.tsn!==r){if(n)break;e=void 0,t++;continue}if(i.flags&yx){let o=this.reassembly.slice(e,t+1).map(a=>a.userData).reduce((a,c)=>(a.push(c),a.push(Buffer.from("")),a),[]);o.pop();let s=Buffer.concat(o);this.reassembly=[...this.reassembly.slice(0,e),...this.reassembly.slice(t+1)],n&&i.streamSeqNum===this.streamSequenceNumber&&(this.streamSequenceNumber=$n(this.streamSequenceNumber,1)),t=e,yield[i.streamId,i.protocol,s]}else t++;r=hh(r)}}pruneChunks(t){let e=-1,r=0;for(let[n,i]of this.reassembly.entries())if(gh(t,i.tsn))e=n,r+=i.userData.length;else break;return this.reassembly=this.reassembly.slice(e+1),r}},A1e=class{constructor(t){this.maxMessageSize=t}};dh=xt("werift:packages/webrtc/src/transport/sctp.ts"),yh=65536,jY=class qY{constructor(e=5e3,r=yh){this.port=e,this.maxMessageSize=r}dtlsTransport;sctp;onDataChannel=new qe;id=c1e().toString();mid;mLineIndex;bundled=!1;dataChannels={};remoteMaxMessageSize=yh;dataChannelQueue=[];dataChannelId;eventDisposer=[];setDtlsTransport(e){this.dtlsTransport&&this.dtlsTransport.id===e.id||(this.eventDisposer.forEach(r=>r()),this.dtlsTransport=e,this.sctp=new k1e(new C1e(this.dtlsTransport),this.port),this.eventDisposer=[...[this.sctp.onReceive.subscribe(this.datachannelReceive),this.sctp.onReconfigStreams.subscribe(r=>{r.forEach(n=>{let i=this.dataChannels[n];i&&(i.setReadyState("closing"),i.setReadyState("closed"),delete this.dataChannels[n])})}),this.sctp.stateChanged.connected.subscribe(()=>{Object.values(this.dataChannels).forEach(r=>{r.negotiated&&r.readyState!=="open"&&r.setReadyState("open")}),this.dataChannelFlush()}),this.sctp.stateChanged.closed.subscribe(()=>{Object.values(this.dataChannels).forEach(r=>{r.setReadyState("closed")}),this.dataChannels={}}),this.dtlsTransport.onStateChange.subscribe(r=>{r==="closed"&&this.sctp.setState(1)})].map(r=>r.unSubscribe),()=>this.sctp.onSackReceived=async()=>{}],this.sctp.onSackReceived=async()=>{await this.dataChannelFlush()})}get isServer(){return this.dtlsTransport.iceTransport.role!=="controlling"}channelByLabel(e){return Object.values(this.dataChannels).find(r=>r.label===e)}datachannelReceive=async(e,r,n)=>{if(r===wk&&n.length>0)switch(dh("DCEP",e,r,n),n[0]){case Jz:{if(n.length<12){dh("DATA_CHANNEL_OPEN data.length not enough");return}if(Object.keys(this.dataChannels).includes(e.toString()))dh("datachannel already opened","retransmit ack");else{let[,o,,s,a,c]=Nk.jspack.Unpack("!BBHLHH",n),u=12,d=n.slice(u,u+a).toString("utf8");u+=a;let l=n.slice(u,u+c).toString("utf8");dh("DATA_CHANNEL_OPEN",{channelType:o,reliability:s,streamId:e,label:d,protocol:l});let f=(o&3)===1?s:void 0,p=(o&3)===2?s:void 0,g=new G6({label:d,ordered:(o&128)===0,maxPacketLifeTime:p,maxRetransmits:f,protocol:l,id:e}),v=new V6(this,g,!1);v.isCreatedByRemote=!0,this.dataChannels[e]=v,this.onDataChannel.execute(v),v.setReadyState("open")}let i=this.dataChannels[e];this.dataChannelQueue.push([i,wk,Buffer.from(Nk.jspack.Pack("!B",[Kz]))]),await this.dataChannelFlush()}break;case Kz:{dh("DATA_CHANNEL_ACK",e,r);let i=this.dataChannels[e];if(!i)throw new Error("channel not found");i.setReadyState("open")}break}else{let i=this.dataChannels[e];if(i){let o=(()=>{switch(r){case Xz:return n.toString("utf8");case BRe:return"";case Yz:return n;case NRe:return Buffer.from([]);default:throw new Error}})();i.messagesReceived++,i.bytesReceived+=n.length,i.onMessage.execute(o),i.emit("message",{data:o}),i.onmessage&&i.onmessage({data:o})}}};dataChannelAddNegotiated(e){if(e.id==null)throw new Error;if(this.dataChannels[e.id])throw new Error;this.dataChannels[e.id]=e,this.sctp.associationState===4&&e.setReadyState("open")}dataChannelOpen(e){if(e.id){if(this.dataChannels[e.id])throw new Error(`Data channel with ID ${e.id} already registered`);this.dataChannels[e.id]=e}let r=DRe,n=0,i=0;e.ordered||(r=128),e.maxRetransmits?(r=1,i=e.maxRetransmits):e.maxPacketLifeTime&&(r=2,i=e.maxPacketLifeTime);let o=Nk.jspack.Pack("!BBHLHH",[Jz,r,n,i,e.label.length,e.protocol.length]),s=Buffer.concat([Buffer.from(o),Buffer.from(e.label,"utf8"),Buffer.from(e.protocol,"utf8")]);this.dataChannelQueue.push([e,wk,s]),this.dataChannelFlush()}async dataChannelFlush(){if(this.sctp.associationState==4){for(;this.dataChannelQueue.length>0;){let[e,r,n]=this.dataChannelQueue.shift(),i=e.id;if(i===void 0){for(i=this.dataChannelId;Object.keys(this.dataChannels).includes(i.toString());)i+=2;this.dataChannels[i]=e,e.setId(i)}if(r===wk)await this.sctp.send(i,r,n,{ordered:!0});else{let o=e.maxPacketLifeTime?Date.now()+e.maxPacketLifeTime/1e3:void 0;await this.sctp.send(i,r,n,{expiry:o,maxRetransmits:e.maxRetransmits,ordered:e.ordered}),e.addBufferedAmount(-n.length)}}this.dataChannelQueue=[]}}assertSendableMessageSize(e){if(this.remoteMaxMessageSize!==0&&e>this.remoteMaxMessageSize)throw new Error(`max-message-size exceeded: ${e} > ${this.remoteMaxMessageSize}`)}datachannelSend=(e,r)=>{let n=Buffer.isBuffer(r)?r:Buffer.from(r),i=zX(r);return this.assertSendableMessageSize(i),e.addBufferedAmount(i),this.dataChannelQueue.push(typeof r=="string"?[e,Xz,n]:[e,Yz,n]),this.sctp.associationState!==4&&dh("sctp not established",this.sctp.associationState),this.dataChannelFlush(),i};getCapabilities(){return qY.getCapabilities(this.maxMessageSize)}static getCapabilities(e=yh){return new dO(e)}setRemoteMaxMessageSize(e){this.remoteMaxMessageSize=e??yh}setRemotePort(e){this.sctp.setRemotePort(e)}async start(e){this.isServer?this.dataChannelId=0:this.dataChannelId=1,this.sctp.isServer=this.isServer,await this.sctp.start(e)}async stop(){this.dtlsTransport.dataReceiver=()=>{},await this.sctp.stop()}dataChannelClose(e){["closing","closed"].includes(e.readyState)||(e.setReadyState("closing"),this.sctp.associationState===4?(this.sctp.reconfigQueue.includes(e.id)||this.sctp.reconfigQueue.push(e.id),this.sctp.reconfigQueue.length===1&&this.sctp.transmitReconfigRequest()):(this.dataChannelQueue=this.dataChannelQueue.filter(r=>r[0].id!==e.id),this.sctp.reconfigQueue=this.sctp.reconfigQueue.filter(r=>r!==e.id),e.id&&delete this.dataChannels[e.id],e.setReadyState("closed")))}},dO=class{constructor(t){this.maxMessageSize=t}},C1e=class{constructor(t){this.dtls=t}set onData(t){this.dtls.dataReceiver=t}send=t=>this.dtls.sendData(t);close(){}},bx=class WY{version=0;origin;name="-";time="0 0";host;group=[];extMapAllowMixed=!0;msidSemantic=[];media=[];type;dtlsRole;iceOptions;iceLite;icePassword;iceUsernameFragment;dtlsFingerprints=[];static parse(e){let[r,n]=P1e(e),i=new WY;r.forEach(s=>{if(s.startsWith("v="))i.version=Number.parseInt(s.slice(2),10);else if(s.startsWith("o="))i.origin=s.slice(2);else if(s.startsWith("s="))i.name=s.slice(2);else if(s.startsWith("c="))i.host=pN(s.slice(2));else if(s.startsWith("t="))i.time=s.slice(2);else if(s.startsWith("a=")){let[a,c]=mN(s);switch(a){case"fingerprint":{let[u,d]=c?.split(" ")||[];i.dtlsFingerprints.push(new Qk(u,d))}break;case"ice-lite":i.iceLite=!0;break;case"ice-options":i.iceOptions=c;break;case"ice-pwd":i.icePassword=c;break;case"ice-ufrag":i.iceUsernameFragment=c;break;case"group":Fk(i.group,c);break;case"msid-semantic":Fk(i.msidSemantic,c);break;case"setup":i.dtlsRole=Zz[c];break;case"extmap-allow-mixed":i.extMapAllowMixed=!0;break}}});let o=i.group.find(s=>s.semantic==="BUNDLE");return n.forEach(s=>{let c=s[0].match(/^m=([^ ]+) ([0-9]+) ([A-Z/]+) (.+)/);if(!c)throw new Error("m line not found");let u=c[1],d=c[4].split(" "),l=["audio","video"].includes(u)?d.map(g=>Number(g)):void 0,f=new tR(u,Number.parseInt(c[2]),c[3],l||d);if(f.dtlsParams=new Zk([...i.dtlsFingerprints],i.dtlsRole),f.iceParams=new cO({iceLite:i.iceLite,usernameFragment:i.iceUsernameFragment,password:i.icePassword}),f.iceOptions=i.iceOptions,i.media.push(f),s.slice(1).forEach(g=>{if(g.startsWith("c="))f.host=pN(g.slice(2));else if(g.startsWith("a=")){let[v,b]=mN(g);switch(v){case"candidate":if(!b)throw new Error;f.iceCandidates.push(fO(b));break;case"end-of-candidates":f.iceCandidatesComplete=!0;break;case"extmap":{let[C,D]=b.split(" ");C.includes("/")&&([C]=C.split("/")),f.rtp.headerExtensions.push(new ka({id:Number.parseInt(C),uri:D}))}break;case"fingerprint":{if(!b)throw new Error;let[C,D]=b.split(" ");f.dtlsParams?.fingerprints.push(new Qk(C,D))}break;case"ice-options":f.iceOptions=b;break;case"ice-pwd":f.iceParams.password=b;break;case"ice-ufrag":f.iceParams.usernameFragment=b;break;case"ice-lite":f.iceParams.iceLite=!0;break;case"max-message-size":f.sctpCapabilities=new dO(Number.parseInt(b,10));break;case"mid":f.rtp.muxId=b;break;case"msid":f.msid=b;break;case"rtcp":{let[C,D]=Uc(b," ");f.rtcpPort=Number.parseInt(C),f.rtcpHost=pN(D)}break;case"rtcp-mux":f.rtcpMux=!0;break;case"setup":f.dtlsParams.role=Zz[b];break;case"recvonly":case"sendonly":case"sendrecv":case"inactive":f.direction=v;break;case"rtpmap":{let[C,D]=Uc(b," "),[_,F,he]=D.split("/"),z;f.kind==="audio"&&(z=he?Number.parseInt(he):1);let Ce=new Dd({mimeType:f.kind+"/"+_,channels:z,clockRate:Number.parseInt(F),payloadType:Number.parseInt(C)});f.rtp.codecs.push(Ce)}break;case"sctpmap":{if(!b)throw new Error;let[C,D]=Uc(b," ");f.sctpMap[Number.parseInt(C)]=D,f.sctpPort=Number.parseInt(C)}break;case"sctp-port":if(!b)throw new Error;f.sctpPort=Number.parseInt(b);break;case"ssrc":{let[C,D]=Uc(b," "),_=Number.parseInt(C),[F,he]=Uc(D,":"),z=f.ssrc.find(Ce=>Ce.ssrc===_);z||(z=new rR({ssrc:_}),f.ssrc.push(z)),tY.includes(F)&&(z[F]=he)}break;case"ssrc-group":Fk(f.ssrcGroup,b);break;case"rid":{let[C,D]=Uc(b," ");f.simulcastParameters.push(new z6({rid:C,direction:D}))}break}}}),(!f.iceParams.usernameFragment||!f.iceParams.password)&&f.rtp.muxId&&o&&o.items.includes(f.rtp.muxId))for(let g=0;g<o.items.length;g++){if(!o.items.includes(g.toString()))continue;let v=i.media[g];if(v.iceParams?.usernameFragment&&v.iceParams.password){f.iceParams={...v.iceParams};break}}f.dtlsParams.role||(f.dtlsParams=void 0);let p=g=>f.rtp.codecs.find(v=>v.payloadType===g);s.slice(1).forEach(g=>{if(g.startsWith("a=")){let[v,b]=mN(g);if(v==="fmtp"){let[C,D]=Uc(b," "),_=p(Number(C));_.parameters=D}else if(v==="rtcp-fb"){let[C,D,_]=b.split(" ");f.rtp.codecs.forEach(F=>{["*",F.payloadType.toString()].includes(C)&&F.rtcpFeedback.push(new JX({type:D,parameter:_}))})}}})}),i}webrtcTrackId(e){if(e.msid?.includes(" ")){let r=e.msid.split(" ");for(let n of this.msidSemantic)if(n.semantic==="WMS"&&(n.items.includes(r[0])||n.items.includes("*")))return r[1]}}get string(){let e=[`v=${this.version}`,`o=${this.origin}`,`s=${this.name}`];this.host&&e.push(`c=${g6(this.host)}`),e.push(`t=${this.time}`),this.group.forEach(i=>e.push(`a=group:${i.str}`)),this.extMapAllowMixed&&e.push("a=extmap-allow-mixed"),this.msidSemantic.forEach(i=>e.push(`a=msid-semantic:${i.str}`));let r=this.media.map(i=>i.toString()).join("");return e.join(`\r
129
+ `)+`\r
130
+ `+r}toJSON(){return new VY(this.string,this.type)}toSdp(){return{type:this.type,sdp:this.string}}},tR=class{constructor(t,e,r,n){this.kind=t,this.port=e,this.profile=r,this.fmt=n}host;direction;msid;rtcpPort;rtcpHost;rtcpMux=!1;ssrc=[];ssrcGroup=[];rtp={codecs:[],headerExtensions:[]};sctpCapabilities;sctpMap={};sctpPort;dtlsParams;iceParams;iceCandidates=[];iceCandidatesComplete=!1;iceOptions;simulcastParameters=[];toString(){let t=[];if(t.push(`m=${this.kind} ${this.port} ${this.profile} ${this.fmt.map(e=>e.toString()).join(" ")}`),this.host&&t.push(`c=${g6(this.host)}`),this.iceCandidates.forEach(e=>{t.push(`a=candidate:${lO(e)}`)}),this.iceCandidatesComplete&&t.push("a=end-of-candidates"),this.iceParams?.usernameFragment&&t.push(`a=ice-ufrag:${this.iceParams.usernameFragment}`),this.iceParams?.password&&t.push(`a=ice-pwd:${this.iceParams.password}`),this.iceParams?.iceLite&&t.push("a=ice-lite"),this.iceOptions&&t.push(`a=ice-options:${this.iceOptions}`),this.dtlsParams&&(this.dtlsParams.fingerprints.forEach(e=>{t.push(`a=fingerprint:${e.algorithm} ${e.value}`)}),t.push(`a=setup:${e6[this.dtlsParams.role]}`)),this.direction&&t.push(`a=${this.direction}`),this.rtp.muxId&&t.push(`a=mid:${this.rtp.muxId}`),this.msid&&t.push(`a=msid:${this.msid}`),this.rtcpPort&&this.rtcpHost&&(t.push(`a=rtcp:${this.rtcpPort} ${g6(this.rtcpHost)}`),this.rtcpMux&&t.push("a=rtcp-mux")),this.ssrcGroup.forEach(e=>{t.push(`a=ssrc-group:${e.str}`)}),this.ssrc.forEach(e=>{tY.forEach(r=>{let n=e[r];n!==void 0&&t.push(`a=ssrc:${e.ssrc} ${r}:${n}`)})}),this.rtp.codecs.forEach(e=>{t.push(`a=rtpmap:${e.payloadType} ${e.str}`),e.rtcpFeedback.forEach(r=>{let n=r.type;r.parameter&&(n+=` ${r.parameter}`),t.push(`a=rtcp-fb:${e.payloadType} ${n}`)}),e.parameters&&t.push(`a=fmtp:${e.payloadType} ${e.parameters}`)}),Object.keys(this.sctpMap).forEach(e=>{let r=this.sctpMap[Number(e)];t.push(`a=sctpmap:${e} ${r}`)}),this.sctpPort&&t.push(`a=sctp-port:${this.sctpPort}`),this.sctpCapabilities&&t.push(`a=max-message-size:${this.sctpCapabilities.maxMessageSize}`),this.rtp.headerExtensions.forEach(e=>t.push(`a=extmap:${e.id} ${e.uri}`)),this.simulcastParameters.length){this.simulcastParameters.forEach(i=>{t.push(`a=rid:${i.rid} ${i.direction}`)});let e="a=simulcast:",r=this.simulcastParameters.filter(i=>i.direction==="recv");r.length&&(e+=`recv ${r.map(i=>i.rid).join(";")} `);let n=this.simulcastParameters.filter(i=>i.direction==="send");n.length&&(e+=`send ${n.map(i=>i.rid).join(";")}`),t.push(e)}return t.join(`\r
131
+ `)+`\r
132
+ `}},bh=class{constructor(t,e){this.semantic=t,this.items=e}get str(){return`${this.semantic} ${this.items.join(" ")}`}};VY=class{constructor(t,e){this.sdp=t,this.type=e}static isThis(t){if(typeof t?.sdp=="string")return!0}toSdp(){return{sdp:this.sdp,type:this.type}}};rR=class{ssrc;cname;msid;msLabel;label;constructor(t){Object.assign(this,t)}},Ek=xt("werift:packages/webrtc/src/media/rtpReceiver.ts"),pO=class{constructor(t,e,r){this.config=t,this.kind=e,this.rtcpSsrc=r}codecs={};get codecArray(){return Object.values(this.codecs).sort((t,e)=>t.payloadType-e.payloadType)}ssrcByRtx={};nack=new VRe(this);audioRedHandler=new tX;type="receiver";uuid=CRe().toString();tracks=[];trackBySSRC={};trackByRID={};lastSRtimestamp={};receiveLastSRTimestamp={};onPacketLost=this.nack.onPacketLost;onRtcp=new qe;dtlsTransport;sdesMid;latestRid;latestRepairedRid;receiverTWCC;stopped=!1;remoteStreamId;remoteTrackId;rtcpRunning=!1;rtcpCancel=new AbortController;remoteStreams={};setDtlsTransport(t){this.dtlsTransport=t}get track(){return this.tracks[0]??new Lx({kind:this.kind})}get nackEnabled(){return this.codecArray[0]?.rtcpFeedback.find(t=>t.type==="nack")}get twccEnabled(){return this.codecArray[0]?.rtcpFeedback.find(t=>t.type===KX().type)}get pliEnabled(){return this.codecArray[0]?.rtcpFeedback.find(t=>t.type===Th().type)}prepareReceive(t){t.codecs.forEach(e=>{this.codecs[e.payloadType]=e}),t.encodings.forEach(e=>{e.rtx&&(this.ssrcByRtx[e.rtx.ssrc]=e.ssrc)})}setupTWCC(t){this.twccEnabled&&!this.receiverTWCC&&(this.receiverTWCC=new KRe(this.dtlsTransport,this.rtcpSsrc,t))}addTrack(t){return this.tracks.find(r=>{if(r.rid)return r.rid===t.rid;if(r.ssrc)return r.ssrc===t.ssrc})?!1:(this.tracks.push(t),t.ssrc&&(this.trackBySSRC[t.ssrc]=t),t.rid&&(this.trackByRID[t.rid]=t),!0)}stop(){this.stopped=!0,this.rtcpRunning=!1,this.rtcpCancel.abort(),this.receiverTWCC&&(this.receiverTWCC.twccRunning=!1),this.nack.close()}async runRtcp(){if(!(this.rtcpRunning||this.stopped)){this.rtcpRunning=!0;try{for(;this.rtcpRunning;){await fN(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let t=Object.entries(this.remoteStreams).map(([r,n])=>{let i=0,o=0;if(this.lastSRtimestamp[r]){i=this.lastSRtimestamp[r];let s=Hx()-this.receiveLastSRTimestamp[r];s>0&&s<65536&&(o=vh(s*65536))}return new lR({ssrc:Number(r),fractionLost:n.fraction_lost,packetsLost:n.packets_lost,highestSequence:n.max_seq,jitter:n.jitter,lsr:i,dlsr:o})}),e=new Eh({ssrc:this.rtcpSsrc,reports:t});try{this.config.debug.receiverReportDelay&&await fN(this.config.debug.receiverReportDelay),await this.dtlsTransport.sendRtcp([e])}catch(r){Ek("sendRtcp failed",r),await fN(500+Math.random()*1e3)}}}catch{}}}async getStats(){let t=Bd(),e=[];if(!this.dtlsTransport)return e;let r=hr("transport",this.dtlsTransport.id);for(let n of this.tracks){if(!n.ssrc)continue;let i=this.remoteStreams[n.ssrc];if(!i)continue;let o={type:"inbound-rtp",id:hr("inbound-rtp",n.ssrc),timestamp:t,ssrc:n.ssrc,kind:this.kind,transportId:r,codecId:this.codecs[0]?hr("codec",this.codecs[0].payloadType,r):void 0,mid:this.sdesMid,trackIdentifier:n.id,packetsReceived:i.packets_received,packetsLost:i.packets_lost,jitter:i.jitter};if(e.push(o),this.lastSRtimestamp[n.ssrc]){let s={type:"remote-outbound-rtp",id:hr("remote-outbound-rtp",n.ssrc),timestamp:t,ssrc:n.ssrc,kind:this.kind,transportId:r,codecId:o.codecId,localId:o.id,remoteTimestamp:this.receiveLastSRTimestamp[n.ssrc]*1e3};e.push(s)}}return e}async sendRtcpPLI(t){if(!this.pliEnabled){Ek("pli not supported",{mediaSsrc:t});return}if(this.stopped)return;Ek("sendRtcpPLI",{mediaSsrc:t});let e=new Ih({feedback:new _x({senderSsrc:this.rtcpSsrc,mediaSsrc:t})});try{await this.dtlsTransport.sendRtcp([e])}catch(r){Ek(r)}}handleRtcpPacket(t){switch(t.type){case _f.type:{let e=t;this.lastSRtimestamp[e.ssrc]=oO(e.senderInfo.ntpTimestamp),this.receiveLastSRTimestamp[e.ssrc]=Hx();let r=this.trackBySSRC[t.ssrc];r&&r.onReceiveRtcp.execute(t)}break}this.onRtcp.execute(t)}handleRtpBySsrc=(t,e)=>{let r=this.trackBySSRC[t.header.ssrc];this.handleRTP(t,e,r)};handleRtpByRid=(t,e,r)=>{let n=this.trackByRID[e];this.trackBySSRC[t.header.ssrc]||(this.trackBySSRC[t.header.ssrc]=n),this.handleRTP(t,r,n)};handleRTP(t,e,r){if(this.stopped)return;let n=this.codecs[t.header.payloadType];if(!n)return;if(this.remoteStreams[t.header.ssrc]=this.remoteStreams[t.header.ssrc]??new JRe(n.clockRate),this.remoteStreams[t.header.ssrc].add(t),this.receiverTWCC){let o=e[Rr.transportWideCC];if(!o==null)throw new Error("undefined");this.receiverTWCC.handleTWCC(o)}else this.twccEnabled&&this.setupTWCC(t.header.ssrc);if(n.name.toLowerCase()==="rtx"){let o=this.ssrcByRtx[t.header.ssrc],s=$x(n.parameters??""),a=this.codecs[s.apt];if(t.payload.length<2)return;t=nX(t,a.payloadType,o),r=this.trackBySSRC[o]}let i;if(!(n.name.toLowerCase()==="red"&&(i=D6.deSerialize(t.payload),!Object.keys(this.codecs).includes(i.header.fields[0].blockPT.toString())))){if(r?.kind==="video"&&this.nackEnabled&&this.nack.addPacket(t),r)if(i){if(r.kind==="audio"){let o=this.audioRedHandler.push(i,t);for(let s of o)r.onReceiveRtp.execute(s.clone(),e)}}else r.onReceiveRtp.execute(t.clone(),e);this.runRtcp()}}},nx=xt("werift:packages/webrtc/src/media/router.ts"),GY=class{ssrcTable={};ridTable={};extIdUriMap={};constructor(){}registerRtpSender(t){this.ssrcTable[t.ssrc]=t}registerRtpReceiver(t,e){nx("registerRtpReceiver",e),this.ssrcTable[e]=t}registerRtpReceiverBySsrc(t,e){nx("registerRtpReceiverBySsrc",e),e.encodings.filter(r=>r.ssrc!=null).forEach((r,n)=>{this.registerRtpReceiver(t.receiver,r.ssrc),t.addTrack(new Lx({ssrc:r.ssrc,kind:t.kind,id:t.sender.trackId,remote:!0,codec:e.codecs[n]})),r.rtx&&this.registerRtpReceiver(t.receiver,r.rtx.ssrc)}),e.headerExtensions.forEach(r=>{this.extIdUriMap[r.id]=r.uri})}registerRtpReceiverByRid(t,e,r){let[n]=r.codecs;nx("registerRtpReceiverByRid",e),t.addTrack(new Lx({rid:e.rid,kind:t.kind,id:t.sender.trackId,remote:!0,codec:n})),this.ridTable[e.rid]=t.receiver}routeRtp=t=>{let e=FJ(t.header.extensions,this.extIdUriMap),r=this.ssrcTable[t.header.ssrc],n=e[Rr.sdesRTPStreamID];if(typeof n=="string"?(r=this.ridTable[n],r.latestRid=n,r.handleRtpByRid(t,n,e)):r?r.handleRtpBySsrc(t,e):(r=Object.values(this.ridTable).filter(s=>s instanceof pO).find(s=>s.trackBySSRC[t.header.ssrc]),r&&(nx("simulcast register receiver by ssrc",t.header.ssrc),this.registerRtpReceiver(r,t.header.ssrc),r.handleRtpBySsrc(t,e))),!r){nx("ssrcReceiver not found");return}let i=e[Rr.sdesMid];typeof i=="string"&&(r.sdesMid=i);let o=e[Rr.repairedRtpStreamId];typeof o=="string"&&(r.latestRepairedRid=o)};routeRtcp=t=>{let e=[];switch(t.type){case _f.type:t=t,e.push(this.ssrcTable[t.ssrc]);break;case Eh.type:t=t,t.reports.forEach(r=>{e.push(this.ssrcTable[r.ssrc])});break;case Nx.type:{let r=t}break;case Pf.type:{let r=t;r.feedback&&e.push(this.ssrcTable[r.feedback.mediaSourceSsrc])}break;case Ih.type:{let r=t;switch(r.feedback.count){case Tx.count:{let n=r.feedback;e.push(this.ssrcTable[n.ssrcFeedbacks[0]])}break;default:e.push(this.ssrcTable[r.feedback.senderSsrc]||this.ssrcTable[r.feedback.mediaSsrc])}}break}e.filter(r=>r).forEach(r=>r.handleRtcpPacket(t))}},T1e=class{numPackets=0;totalSize=0;firstPacketSentAtMs=0;lastPacketSentAtMs=0;firstPacketReceivedAtMs=0;lastPacketReceivedAtMs=0;addPacket(t,e,r){this.numPackets===0?(this.firstPacketSentAtMs=e,this.firstPacketReceivedAtMs=r,this.lastPacketSentAtMs=e,this.lastPacketReceivedAtMs=r):(e<this.firstPacketSentAtMs&&(this.firstPacketSentAtMs=e),r<this.firstPacketReceivedAtMs&&(this.firstPacketReceivedAtMs=r),e>this.lastPacketSentAtMs&&(this.lastPacketSentAtMs=e),r>this.lastPacketReceivedAtMs&&(this.lastPacketReceivedAtMs=r)),this.numPackets++,this.totalSize+=t}reset(){this.numPackets=0,this.totalSize=0,this.firstPacketSentAtMs=0,this.lastPacketSentAtMs=0,this.firstPacketReceivedAtMs=0,this.lastPacketReceivedAtMs=0}get receiveBitrate(){let t=this.lastPacketReceivedAtMs-this.firstPacketReceivedAtMs,e=this.totalSize/t*8*1e3;return Px(e)}get sendBitrate(){let t=this.lastPacketSentAtMs-this.firstPacketSentAtMs,e=this.totalSize/t*8*1e3;return Px(e)}},lh=20,D1e=10,B1e=class{congestion=!1;onAvailableBitrate=new qe;onCongestion=new qe;onCongestionScore=new qe;congestionCounter=0;cumulativeResult=new T1e;sentInfos={};_congestionScore=1;get congestionScore(){return this._congestionScore}set congestionScore(t){this._congestionScore=t,this.onCongestionScore.execute(t)}_availableBitrate=0;get availableBitrate(){return this._availableBitrate}set availableBitrate(t){this._availableBitrate=t,this.onAvailableBitrate.execute(t)}constructor(){}receiveTWCC(t){let r=iO()-this.cumulativeResult.firstPacketSentAtMs;r>1e3&&(this.cumulativeResult.reset(),this.congestionCounter<lh?this.congestionCounter++:this.congestionScore<D1e&&this.congestionScore++,this.congestionCounter>=lh&&!this.congestion&&(this.congestion=!0,this.onCongestion.execute(this.congestion)));for(let n of t.packetResults){if(!n.received)continue;let i=n.sequenceNumber,o=this.sentInfos[i];o&&n.receivedAtMs&&this.cumulativeResult.addPacket(o.size,o.sendingAtMs,n.receivedAtMs)}if(r>=100&&this.cumulativeResult.numPackets>=20){if(this.availableBitrate=Math.min(this.cumulativeResult.sendBitrate,this.cumulativeResult.receiveBitrate),this.cumulativeResult.reset(),this.congestionCounter>-lh){let n=Px(lh/2)+1,i=Px(lh/4)+1,o=n-(n-i)/10*this.congestionScore;this.congestionCounter=this.congestionCounter-o}this.congestionCounter<=-lh&&(this.congestionScore>1&&(this.congestionScore--,this.onCongestion.execute(!1)),this.congestionCounter=0),this.congestionCounter<=0&&this.congestion&&(this.congestion=!1,this.onCongestion.execute(this.congestion))}}rtpPacketSent(t){Object.keys(t).map(e=>Number(e)).sort().filter(e=>e<t.wideSeq).forEach(e=>{delete this.sentInfos[e]}),this.sentInfos[t.wideSeq]=t}},hN=xt("werift:packages/webrtc/src/media/rtpSender.ts"),vK=128,xK=.85,zY=class{constructor(t){this.trackOrKind=t,this.kind=typeof this.trackOrKind=="string"?this.trackOrKind:this.trackOrKind.kind,typeof t!="string"&&(t.streamId&&(this.streamId=t.streamId),this.registerTrack(t))}type="sender";kind;ssrc=v6.jspack.Unpack("!L",hK(4))[0];rtxSsrc=v6.jspack.Unpack("!L",hK(4))[0];streamId=gK().toString();trackId=gK().toString();onReady=new qe;onRtcp=new qe;onPictureLossIndication=new qe;onGenericNack=new qe;senderBWE=new B1e;cname;mid;rtpStreamId;repairedRtpStreamId;rtxPayloadType;rtxSequenceNumber=b6();redRedundantPayloadType;_redDistance=2;redEncoder=new eX(this._redDistance);headerExtensions=[];disposeTrack;lastSRtimestamp;lastSentSRTimestamp;ntpTimestamp=0n;rtpTimestamp=0;octetCount=0;packetCount=0;rtt;receiverEstimatedMaxBitrate=0n;sequenceNumber;timestamp;timestampOffset=0;seqOffset=0;rtpCache=[];codec;dtlsTransport;dtlsDisposer=[];track;stopped=!1;rtcpRunning=!1;rtcpCancel=new AbortController;setDtlsTransport(t){this.dtlsTransport&&this.dtlsDisposer.forEach(e=>e()),this.dtlsTransport=t,this.dtlsDisposer=[this.dtlsTransport.onStateChange.subscribe(e=>{e==="connected"&&this.onReady.execute()}).unSubscribe]}get redDistance(){return this._redDistance}set redDistance(t){this._redDistance=t,this.redEncoder.distance=t}prepareSend(t){this.cname=t.rtcp?.cname,this.mid=t.muxId,this.headerExtensions=t.headerExtensions,this.rtpStreamId=t.rtpStreamId,this.repairedRtpStreamId=t.repairedRtpStreamId,this.codec=t.codecs[0],this.track&&(this.track.codec=this.codec),t.codecs.forEach(e=>{let r=$x(e.parameters??"");e.name.toLowerCase()==="rtx"&&r.apt===this.codec?.payloadType&&(this.rtxPayloadType=e.payloadType),e.name.toLowerCase()==="red"&&(this.redRedundantPayloadType=Number((e.parameters??"").split("/")[0]))})}registerTrack(t){if(t.stopped)throw new Error("track is ended");this.disposeTrack&&this.disposeTrack(),t.id=this.trackId;let{unSubscribe:e}=t.onReceiveRtp.subscribe(async r=>{await this.sendRtp(r)});this.track=t,this.disposeTrack=e,this.codec&&(t.codec=this.codec),t.onSourceChanged.subscribe(r=>{this.replaceRTP(r)})}async replaceTrack(t){if(t!==null){if(t.stopped)throw new Error("track is ended");if(this.sequenceNumber!=null){let e=t.header||(await t.onReceiveRtp.asPromise())[0].header;this.replaceRTP(e)}this.registerTrack(t),hN("replaceTrack","ssrc",t.ssrc,"rid",t.rid)}}stop(){this.stopped=!0,this.rtcpRunning=!1,this.rtcpCancel.abort(),this.disposeTrack&&this.disposeTrack(),this.track=void 0}async runRtcp(){if(!(this.rtcpRunning||this.stopped)){this.rtcpRunning=!0;try{for(;this.rtcpRunning;){await yK(500+Math.random()*1e3,void 0,{signal:this.rtcpCancel.signal});let t=[new _f({ssrc:this.ssrc,senderInfo:new T6({ntpTimestamp:this.ntpTimestamp,rtpTimestamp:this.rtpTimestamp,packetCount:this.packetCount,octetCount:this.octetCount})})];this.lastSRtimestamp=oO(this.ntpTimestamp),this.lastSentSRTimestamp=Hx(),this.cname&&t.push(new Nx({chunks:[new P6({source:this.ssrc,items:[new _6({type:1,text:this.cname})]})]}));try{await this.dtlsTransport.sendRtcp(t)}catch(e){hN("sendRtcp failed",e),await yK(500+Math.random()*1e3)}}}catch{}}}replaceRTP({sequenceNumber:t,timestamp:e},r=!1){this.sequenceNumber!=null&&(this.seqOffset=$n(this.sequenceNumber,-t),r&&(this.seqOffset=$n(this.seqOffset,2))),this.timestamp!=null&&(this.timestampOffset=If(this.timestamp,-e),r&&(this.timestampOffset=$n(this.timestampOffset,1))),this.rtpCache=[],hN("replaceRTP",this.sequenceNumber,t,this.seqOffset)}async sendRtp(t){if(this.dtlsTransport.state!=="connected"||!this.codec)return;t=Buffer.isBuffer(t)?Gc.deSerialize(t):t;let{header:e,payload:r}=t;e.ssrc=this.ssrc,e.payloadType=this.codec.payloadType,e.timestamp=If(e.timestamp,this.timestampOffset),e.sequenceNumber=$n(e.sequenceNumber,this.seqOffset),this.timestamp=e.timestamp,this.sequenceNumber=e.sequenceNumber;let n=dY(),i=[...e.extensions];e.extensions=this.headerExtensions.map(u=>{let d=(()=>{switch(u.uri){case Rr.sdesMid:return this.mid?jJ(this.mid):void 0;case Rr.sdesRTPStreamID:return this.rtpStreamId?qJ(this.rtpStreamId):void 0;case Rr.repairedRtpStreamId:return this.repairedRtpStreamId?WJ(this.repairedRtpStreamId):void 0;case Rr.transportWideCC:return this.dtlsTransport.transportSequenceNumber=$n(this.dtlsTransport.transportSequenceNumber,1),VJ(this.dtlsTransport.transportSequenceNumber);case Rr.absSendTime:return GJ(n)}})();if(d)return{id:u.id,payload:d}}).filter(u=>u);for(let u of i){let d=e.extensions.find(l=>l.id===u.id);d?d.payload=u.payload:e.extensions.push(u)}e.extensions=e.extensions.sort((u,d)=>u.id-d.id),this.ntpTimestamp=n,this.rtpTimestamp=e.timestamp,this.octetCount+=r.length,this.packetCount=If(this.packetCount,1),this.rtpCache[e.sequenceNumber%vK]=t;let o=r;this.redRedundantPayloadType&&(this.redEncoder.push({block:o,timestamp:e.timestamp,blockPT:this.redRedundantPayloadType}),o=this.redEncoder.build().serialize());let s=await this.dtlsTransport.sendRtp(o,e);this.runRtcp();let a=iO(),c={wideSeq:this.dtlsTransport.transportSequenceNumber,size:s,sendingAtMs:a,sentAtMs:a};this.senderBWE.rtpPacketSent(c)}handleRtcpPacket(t){switch(t.type){case _f.type:case Eh.type:t.reports.filter(r=>r.ssrc===this.ssrc).forEach(r=>{if(this.lastSRtimestamp===r.lsr&&r.dlsr&&this.lastSentSRTimestamp){let n=Hx()-this.lastSentSRTimestamp-r.dlsr/65536;this.rtt===void 0?this.rtt=n:this.rtt=xK*this.rtt+(1-xK)*n}});break;case Pf.type:{let e=t;switch(e.feedback.count){case Bx.count:{let r=e.feedback;this.senderBWE.receiveTWCC(r)}break;case Dx.count:{let r=e.feedback;r.lost.forEach(async n=>{let i=this.rtpCache[n%vK];i&&i.header.sequenceNumber!==n&&(i=void 0),i&&(this.rtxPayloadType!=null&&(i=iX(i,this.rtxPayloadType,this.rtxSequenceNumber,this.rtxSsrc),this.rtxSequenceNumber=$n(this.rtxSequenceNumber,1)),await this.dtlsTransport.sendRtp(i.payload,i.header))}),this.onGenericNack.execute(r)}break}}break;case Ih.type:{let e=t;switch(e.feedback.count){case Tx.count:{let r=e.feedback;this.receiverEstimatedMaxBitrate=r.bitrate}break;case _x.count:this.onPictureLossIndication.execute();break}}break}this.onRtcp.execute(t)}getParameters(){return{encodings:[]}}setParameters(t){}async getStats(){let t=Bd(),e=[];if(!this.dtlsTransport)return e;let r=hr("transport",this.dtlsTransport.id),n={type:"outbound-rtp",id:hr("outbound-rtp",this.ssrc),timestamp:t,ssrc:this.ssrc,kind:this.kind,transportId:r,codecId:this.codec?hr("codec",this.codec.payloadType,r):void 0,mid:this.mid,packetsSent:this.packetCount,bytesSent:this.octetCount,rtxSsrc:this.rtxPayloadType?this.rtxSsrc:void 0};if(e.push(n),this.track){let i={type:"media-source",id:hr("media-source",this.trackId),timestamp:t,trackIdentifier:this.trackId,kind:this.kind};e.push(i)}if(this.rtt!==void 0){let i={type:"remote-inbound-rtp",id:hr("remote-inbound-rtp",this.ssrc),timestamp:t,ssrc:this.ssrc,kind:this.kind,transportId:r,codecId:n.codecId,localId:n.id,roundTripTime:this.rtt};e.push(i)}return e}},O1e=xt("werift:packages/webrtc/src/transport/sctpManager.ts"),M1e=class{sctpTransport;sctpRemotePort;dataChannelsOpened=0;dataChannelsClosed=0;dataChannels=[];onDataChannel=new qe;constructor(){}createSctpTransport(t){let e=new jY(5e3,t);return e.mid=void 0,e.onDataChannel.subscribe(r=>{this.dataChannelsOpened++,this.dataChannels.push(r),this.onDataChannel.execute(r)}),this.sctpTransport=e,e}createDataChannel(t,e={}){let n={...{protocol:"",ordered:!0,negotiated:!1},...e};if(n.maxPacketLifeTime&&n.maxRetransmits)throw new Error("can not select both");this.sctpTransport||(this.sctpTransport=this.createSctpTransport());let i=new G6({id:n.id,label:t,maxPacketLifeTime:n.maxPacketLifeTime,maxRetransmits:n.maxRetransmits,negotiated:n.negotiated,ordered:n.ordered,protocol:n.protocol}),o=new V6(this.sctpTransport,i);return this.dataChannelsOpened++,this.dataChannels.push(o),o.stateChange.subscribe(s=>{if(s==="closed"){this.dataChannelsClosed++;let a=this.dataChannels.indexOf(o);a!==-1&&this.dataChannels.splice(a,1)}}),o}async connectSctp(){!this.sctpTransport||!this.sctpRemotePort||(await this.sctpTransport.start(this.sctpRemotePort),await this.sctpTransport.sctp.stateChanged.connected.asPromise(),O1e("sctp connected"))}setRemoteSCTP(t,e){if(this.sctpTransport){if(this.sctpTransport.setRemoteMaxMessageSize(t.sctpCapabilities?.maxMessageSize),this.sctpRemotePort=t.sctpPort,!this.sctpRemotePort)throw new Error("sctpRemotePort not exist");this.sctpTransport.setRemotePort(this.sctpRemotePort),this.sctpTransport.mLineIndex=e,this.sctpTransport.mid||(this.sctpTransport.mid=t.rtp.muxId)}}async close(){this.sctpTransport&&await this.sctpTransport.stop(),this.onDataChannel.allUnsubscribe()}async getStats(){let t=Bd(),e=[];for(let r of this.dataChannels){let n={type:"data-channel",id:hr("data-channel",r.id),timestamp:t,label:r.label,protocol:r.protocol,dataChannelIdentifier:r.id,state:r.readyState,messagesSent:r.messagesSent||0,bytesSent:r.bytesSent||0,messagesReceived:r.messagesReceived||0,bytesReceived:r.bytesReceived||0};e.push(n)}return e}},KY=class{currentLocalDescription;currentRemoteDescription;pendingLocalDescription;pendingRemoteDescription;cname;midSuffix;bundlePolicy;seenMid=new Set;constructor({cname:t,midSuffix:e,bundlePolicy:r}){this.cname=t,this.midSuffix=e??!1,this.bundlePolicy=r}get localDescription(){if(this._localDescription)return this._localDescription.toJSON()}get remoteDescription(){if(this._remoteDescription)return this._remoteDescription.toJSON()}get _localDescription(){return this.pendingLocalDescription||this.currentLocalDescription}get _remoteDescription(){return this.pendingRemoteDescription||this.currentRemoteDescription}get inactiveRemoteMedia(){return this._remoteDescription?.media?.find?.(t=>t.direction==="inactive")}createMediaDescriptionForTransceiver(t,e){let r=new tR(t.kind,9,"UDP/TLS/RTP/SAVPF",t.codecs.map(n=>n.payloadType));return r.direction=e,r.msid=t.msid,r.rtp={codecs:t.codecs,headerExtensions:t.headerExtensions,muxId:t.mid},r.rtcpHost="0.0.0.0",r.rtcpPort=9,r.rtcpMux=!0,r.ssrc=[new rR({ssrc:t.sender.ssrc,cname:this.cname})],t.options.simulcast&&(r.simulcastParameters=t.options.simulcast.map(n=>new z6(n))),r.rtp.codecs.find(n=>n.name.toLowerCase()==="rtx")&&(r.ssrc.push(new rR({ssrc:t.sender.rtxSsrc,cname:this.cname})),r.ssrcGroup=[new bh("FID",[t.sender.ssrc.toString(),t.sender.rtxSsrc.toString()])]),this.addTransportDescription(r,t.dtlsTransport),r}createMediaDescriptionForSctp(t){let e=new tR("application",Qz,"UDP/DTLS/SCTP",["webrtc-datachannel"]);return e.sctpPort=t.port,e.rtp.muxId=t.mid,e.sctpCapabilities=t.getCapabilities(),this.addTransportDescription(e,t.dtlsTransport),e}addTransportDescription(t,e){let r=e.iceTransport;t.iceCandidates=r.localCandidates,t.iceCandidatesComplete=r.gatheringState==="complete",t.iceParams=r.localParameters,t.iceOptions="trickle",t.host=ORe,t.port=Qz,t.direction==="inactive"&&(t.port=0,t.msid=void 0),t.dtlsParams||(t.dtlsParams=e.localParameters,t.dtlsParams.fingerprints||(t.dtlsParams.fingerprints=e.localParameters.fingerprints))}allocateMid(t=""){let e="";for(let r=0;e=(r++).toString()+t,!!this.seenMid.has(e););return this.seenMid.add(e),e}parseSdp({sdp:t,isLocal:e,signalingState:r,type:n}){let i=bx.parse(t);return this.validateDescription({description:i,isLocal:e,signalingState:r}),i.type=n,i}validateDescription({description:t,isLocal:e,signalingState:r}){if(e){if(t.type==="offer"){if(!["stable","have-local-offer"].includes(r))throw new Error("Cannot handle offer in signaling state")}else if(t.type==="answer"&&!["have-remote-offer","have-local-pranswer"].includes(r))throw new Error("Cannot handle answer in signaling state")}else if(t.type==="offer"){if(!["stable","have-remote-offer"].includes(r))throw new Error("Cannot handle offer in signaling state")}else if(t.type==="answer"&&!["have-local-offer","have-remote-pranswer"].includes(r))throw new Error("Cannot handle answer in signaling state")}buildOfferSdp(t,e){let r=new bx;y6("offer",r),(this.currentLocalDescription?.media??[]).forEach((i,o)=>{let s=i.rtp.muxId;if(s)if(i.kind==="application"){if(!e)throw new Error("sctpTransport not found");e.mLineIndex=o,r.media.push(this.createMediaDescriptionForSctp(e))}else{let a=t.find(c=>c.mid===s);if(!a){if(i.direction==="inactive"){r.media.push(i);return}throw new Error("transceiver not found")}a.mLineIndex=o,r.media.push(this.createMediaDescriptionForTransceiver(a,a.direction))}});for(let i of t.filter(o=>!r.media.find(s=>s.rtp.muxId===o.mid))){i.mid==null&&(i.mid=this.allocateMid(this.midSuffix?"av":""));let o=this.createMediaDescriptionForTransceiver(i,i.direction);i.mLineIndex===void 0?(i.mLineIndex=r.media.length,r.media.push(o)):r.media[i.mLineIndex]=o}if(e&&!r.media.find(i=>i.kind==="application")&&(e.mLineIndex=r.media.length,e.mid==null&&(e.mid=this.allocateMid(this.midSuffix?"dc":"")),r.media.push(this.createMediaDescriptionForSctp(e))),this.bundlePolicy!=="disable"){let i=r.media.map(o=>o.rtp.muxId).filter(o=>o);if(i.length){let o=new bh("BUNDLE",i);r.group.push(o)}}return r}buildAnswerSdp({transceivers:t,sctpTransport:e,signalingState:r}){if(!["have-remote-offer","have-local-pranswer"].includes(r))throw new Error("createAnswer failed");if(!this._remoteDescription)throw new Error("wrong state");let n=new bx;y6("answer",n);for(let i of this._remoteDescription.media){let o,s;if(["audio","video"].includes(i.kind)){let a=t.find(c=>c.mid===i.rtp.muxId);if(!a)throw new Error(`Transceiver with mid=${i.rtp.muxId} not found`);s=this.createMediaDescriptionForTransceiver(a,nO(a.direction,a.offerDirection)),o=a.dtlsTransport}else if(i.kind==="application"){if(!e||!e.mid)throw new Error("sctpTransport not found");s=this.createMediaDescriptionForSctp(e),o=e.dtlsTransport}else throw new Error("invalid kind");s.dtlsParams&&(o.role==="auto"?s.dtlsParams.role="client":s.dtlsParams.role=o.role),i.simulcastParameters&&i.simulcastParameters.length>0&&(s.simulcastParameters=i.simulcastParameters.map(a=>({...a,direction:a.direction==="send"?"recv":"send"}))),n.media.push(s)}if(this.bundlePolicy!=="disable"){let i=new bh("BUNDLE",[]);for(let o of n.media)o.rtp.muxId&&i.items.push(o.rtp.muxId);n.group.push(i)}return n}setLocalDescription(t){this.currentLocalDescription=t,t.type==="answer"?this.pendingLocalDescription=void 0:this.pendingLocalDescription=t}setRemoteDescription(t,e){if(!t.sdp||!t.type||t.type==="rollback"||t.type==="pranswer")throw new Error("invalid sessionDescription");let r=this.parseSdp({sdp:t.sdp,isLocal:!1,signalingState:e,type:t.type});return r.type==="answer"?(this.currentRemoteDescription=r,this.pendingRemoteDescription=void 0):this.pendingRemoteDescription=r,r}registerMid(t){this.seenMid.add(t)}get remoteIsBundled(){let t=this._remoteDescription;return t?t.group.find(r=>r.semantic==="BUNDLE"&&this.bundlePolicy!=="disable"):void 0}setLocal(t,e,r){let n=new Map(e.map(s=>[s?.mLineIndex,s])),i=e.find(s=>s?.dtlsTransport)?.dtlsTransport??r?.dtlsTransport;t.media.filter(s=>["audio","video"].includes(s.kind)).forEach((s,a)=>{let u=(n.get(a)??e[a])?.dtlsTransport??i;if(!u)throw new Error(`dtls transport not found for media index ${a}`);this.addTransportDescription(s,u)});let o=t.media.find(s=>s.kind==="application");r&&o&&this.addTransportDescription(o,r.dtlsTransport),this.setLocalDescription(t)}},ix=xt("werift:packages/webrtc/src/transport/secureTransportManager.ts"),L1e=class{connectionState="new";iceConnectionState="new";iceGatheringState="new";certificate;iceGatheringStateChange=new qe;iceConnectionStateChange=new qe;onIceCandidate=new qe;connectionStateChange=new qe;config;transceiverManager;sctpManager;constructor({config:t,transceiverManager:e,sctpManager:r}){if(this.config=t,this.transceiverManager=e,this.sctpManager=r,this.config.dtls){let{keys:n}=this.config.dtls;n&&this.setupCertificate(n)}}get dtlsTransports(){return[...this.transceiverManager.getTransceivers().map(e=>e?.dtlsTransport),this.sctpManager.sctpTransport?.dtlsTransport].filter(e=>e!=null).reduce((e,r)=>(e.map(n=>n.id).includes(r.id)||e.push(r),e),[])}get iceTransports(){return this.dtlsTransports.map(t=>t.iceTransport)}setupCertificate(t){this.certificate=new sO(t.keyPem,t.certPem,t.signatureHash)}createTransport(){let t=this.iceTransports.find(i=>i.state!=="closed"),e=new hY({...lY(this.config.iceServers),forceTurn:this.config.iceTransportPolicy==="relay",portRange:this.config.icePortRange,interfaceAddresses:this.config.iceInterfaceAddresses,additionalHostAddresses:this.config.iceAdditionalHostAddresses,filterStunResponse:this.config.iceFilterStunResponse,filterCandidatePair:this.config.iceFilterCandidatePair,localPasswordPrefix:this.config.icePasswordPrefix,useIpv4:this.config.iceUseIpv4,useIpv6:this.config.iceUseIpv6,turnTransport:this.config.forceTurnTCP===!0?"tcp":"udp",useLinkLocalAddress:this.config.iceUseLinkLocalAddress});t&&(e.connection.localUsername=t.connection.localUsername,e.connection.localPassword=t.connection.localPassword),e.onGatheringStateChange.subscribe(()=>{this.updateIceGatheringState()}),this.updateIceGatheringState();let r=new mY(e);return r.onStateChange.subscribe(()=>{this.updateIceConnectionState()}),new t6(this.config,r,this.certificate,H1e)}handleNewIceCandidate({candidate:t,media:e,remoteIsBundled:r,transceiver:n,sctpTransport:i,bundlePolicy:o}){return o==="max-bundle"||r?(t.sdpMLineIndex=0,e&&(t.sdpMid=e.rtp.muxId)):(n&&(t.sdpMLineIndex=n.mLineIndex,t.sdpMid=n.mid),i&&(t.sdpMLineIndex=i.mLineIndex,t.sdpMid=i.mid)),t.foundation&&!t.foundation.startsWith("candidate:")&&(t.foundation="candidate:"+t.foundation),this.onIceCandidate.execute(t),t}async addIceCandidate(t,e){let r=aO.fromJSON(e);if(!r)return;let n;typeof r.sdpMid=="number"&&(n=this.getTransportByMid(r.sdpMid)),!n&&typeof r.sdpMLineIndex=="number"&&(n=this.getTransportByMLineIndex(t,r.sdpMLineIndex)),n||(n=this.iceTransports[0]),n?await n.addRemoteCandidate(r):ix("iceTransport not found for candidate",r)}getTransportByMid(t){let e,r=this.transceiverManager.getTransceivers().find(n=>n.mid===t);return r?e=r.dtlsTransport.iceTransport:!e&&this.sctpManager.sctpTransport?.mid===t&&(e=this.sctpManager.sctpTransport.dtlsTransport.iceTransport),e}getTransportByMLineIndex(t,e){let r=t.media[e];return r?this.getTransportByMid(r.rtp.muxId):void 0}restartIce(){for(let t of this.iceTransports)t.restart()}setLocalRole({type:t,role:e}){for(let r of this.dtlsTransports){let n=r.iceTransport;t==="offer"?n.connection.iceControlling=!0:n.connection.iceControlling=!1,n.connection.remoteIsLite&&(n.connection.iceControlling=!0),t==="answer"&&e&&(r.role=e)}}updateIceGatheringState(){let t=this.iceTransports;function e(...n){return t.filter(i=>n.includes(i.gatheringState)).length===t.length}let r;t.length&&e("complete")?r="complete":!t.length||e("new","complete")?r="new":t.map(n=>n.gatheringState).includes("gathering")?r="gathering":r="new",this.iceGatheringState!==r&&(this.iceGatheringState=r,this.iceGatheringStateChange.execute(r))}updateIceConnectionState(){let t=this.iceTransports,e;function r(...i){return t.filter(o=>i.includes(o.state)).length===t.length}function n(...i){return t.some(o=>i.includes(o.state))}this.connectionState==="closed"?e="closed":n("failed")?e="failed":n("disconnected")?e="disconnected":r("new","closed")?e="new":n("new","checking")?e="checking":r("completed","closed")?e="completed":r("connected","completed","closed")?e="connected":e="new",this.iceConnectionState!==e&&(ix("iceConnectionStateChange",e),this.iceConnectionState=e,this.iceConnectionStateChange.execute(e))}async gatherCandidates(t){let e=this.iceTransports.find(r=>r.state==="connected"||r.state==="completed");t&&e?ix("skipping ICE gathering for bundled connection"):await Promise.allSettled(this.iceTransports.map(r=>r.gather())).catch(r=>{ix("gatherCandidates failed",r)})}setConnectionState(t){ix("connectionStateChange",t),this.connectionState=t,this.connectionStateChange.execute(t)}async getStats(){let t=[];for(let e of this.dtlsTransports){let r=await e.getStats();r&&t.push(...r)}return t}async ensureCerts(){this.certificate||(this.certificate=await t6.SetupCertificate());for(let t of this.dtlsTransports)t.localCertificate=this.certificate}async close(){this.setConnectionState("closed"),await Promise.allSettled([...this.dtlsTransports.map(t=>t.stop())]),this.iceGatheringStateChange.allUnsubscribe(),this.iceConnectionStateChange.allUnsubscribe(),this.onIceCandidate.allUnsubscribe(),this.connectionStateChange.allUnsubscribe()}},H1e=[eK.SRTP_AEAD_AES_128_GCM,eK.SRTP_AES128_CM_HMAC_SHA1_80],ws=xt("werift:packages/webrtc/src/peerConnection.ts"),U1e=class extends W6{cname=N1e().toString();config=JY();signalingState="stable";negotiationneeded=!1;needRestart=!1;router=new GY;sdpManager;transceiverManager;sctpManager;secureManager;isClosed=!1;shouldNegotiationneeded=!1;remoteBundleNegotiated=!1;iceGatheringStateChange=new qe;iceConnectionStateChange=new qe;signalingStateChange=new qe;connectionStateChange=new qe;onDataChannel=new qe;onRemoteTransceiverAdded=new qe;onTransceiverAdded=new qe;onIceCandidate=new qe;onNegotiationneeded=new qe;onTrack=new qe;ondatachannel;onicecandidate;onicecandidateerror;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;onconnectionstatechange;oniceconnectionstatechange;constructor(t={}){super(),this.setConfiguration(t),this.sdpManager=new KY({cname:this.cname,bundlePolicy:this.config.bundlePolicy}),this.transceiverManager=new XY(this.cname,this.config,this.router),this.transceiverManager.onTransceiverAdded.pipe(this.onTransceiverAdded),this.transceiverManager.onRemoteTransceiverAdded.pipe(this.onRemoteTransceiverAdded),this.transceiverManager.onTrack.subscribe(({track:e,stream:r,transceiver:n})=>{let i={track:e,streams:[r],transceiver:n,receiver:n.receiver};this.onTrack.execute(e),this.emit("track",i),this.ontrack&&this.ontrack(i)}),this.transceiverManager.onNegotiationNeeded.subscribe(()=>this.needNegotiation()),this.sctpManager=new M1e,this.sctpManager.onDataChannel.subscribe(e=>{this.onDataChannel.execute(e);let r={channel:e};this.ondatachannel?.(r),this.emit("datachannel",r)}),this.secureManager=new L1e({config:this.config,sctpManager:this.sctpManager,transceiverManager:this.transceiverManager}),this.secureManager.iceGatheringStateChange.pipe(this.iceGatheringStateChange),this.secureManager.iceConnectionStateChange.subscribe(e=>{e==="closed"&&this.close(),this.iceConnectionStateChange.execute(e)}),this.secureManager.connectionStateChange.subscribe(e=>{this.connectionStateChange.execute(e),this.onconnectionstatechange?.(),this.emit("connectionstatechange")}),this.secureManager.onIceCandidate.subscribe(e=>{let r=e?e.toJSON():void 0;this.onIceCandidate.execute(r),this.onicecandidate?.({candidate:r}),this.emit("icecandidate",{candidate:r})})}get connectionState(){return this.secureManager.connectionState}get iceConnectionState(){return this.secureManager.iceConnectionState}get iceGathererState(){return this.secureManager.iceGatheringState}get iceGatheringState(){return this.secureManager.iceGatheringState}get dtlsTransports(){return this.secureManager.dtlsTransports}get sctpTransport(){return this.sctpManager.sctpTransport}get sctpRemotePort(){return this.sctpManager.sctpRemotePort}get iceTransports(){return this.secureManager.iceTransports}get extIdUriMap(){return this.router.extIdUriMap}get iceGeneration(){return this.iceTransports[0].connection.generation}get localDescription(){return this.sdpManager.localDescription}get remoteDescription(){return this.sdpManager.remoteDescription}get remoteIsBundled(){return this.sdpManager.remoteIsBundled}get _localDescription(){return this.sdpManager._localDescription}get _remoteDescription(){return this.sdpManager._remoteDescription}getTransceivers(){return this.transceiverManager.getTransceivers()}getSenders(){return this.transceiverManager.getSenders()}getReceivers(){return this.transceiverManager.getReceivers()}setConfiguration(t){if(fY(this.config,t),this.config.icePortRange){let[e,r]=this.config.icePortRange;if(e===r)throw new Error("should not be same value");if(e>=r)throw new Error("The min must be less than max")}if(!Number.isInteger(this.config.maxMessageSize)||this.config.maxMessageSize<0)throw new Error("maxMessageSize must be a non-negative integer");this.sctpManager?.sctpTransport&&(this.sctpManager.sctpTransport.maxMessageSize=this.config.maxMessageSize);for(let[e,r]of Gz([...this.config.codecs.audio||[],...this.config.codecs.video||[]]))if(r.payloadType==null)switch(r.payloadType=96+e,r.name.toLowerCase()){case"rtx":r.parameters=`apt=${r.payloadType-1}`;break;case"red":if(r.contentType==="audio"){let n=r.payloadType+1;r.parameters=`${n}/${n}`,r.payloadType=63}break}[...this.config.headerExtensions.audio||[],...this.config.headerExtensions.video||[]].forEach((e,r)=>{e.id=1+r})}getConfiguration(){return this.config}async createOffer({iceRestart:t}={}){(t||this.needRestart)&&(this.needRestart=!1,this.secureManager.restartIce()),await this.secureManager.ensureCerts();for(let r of this.transceiverManager.getTransceivers())r.codecs.length===0&&this.transceiverManager.assignTransceiverCodecs(r),r.headerExtensions.length===0&&(r.headerExtensions=this.config.headerExtensions[r.kind]??[]);return this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport).toJSON()}createSctpTransport(){let t=this.sctpManager.createSctpTransport(this.config.maxMessageSize),e=this.findOrCreateTransport();return t.setDtlsTransport(e),t}createDataChannel(t,e={}){this.sctpTransport||(this.createSctpTransport(),this.needNegotiation());let r=this.sctpManager.createDataChannel(t,e);if(!r.sctp.dtlsTransport){let n=this.findOrCreateTransport();r.sctp.setDtlsTransport(n)}return r}removeTrack(t){if(this.isClosed)throw new Error("peer closed");this.transceiverManager.removeTrack(t),this.needNegotiation()}needNegotiation=async()=>{this.shouldNegotiationneeded=!0,!(this.negotiationneeded||this.signalingState!=="stable")&&(this.shouldNegotiationneeded=!1,setImmediate(()=>{this.negotiationneeded=!0,this.onNegotiationneeded.execute(),this.onnegotiationneeded&&this.onnegotiationneeded({})}))};findOrCreateTransport(){let t=this.dtlsTransports.find(i=>i.state!=="closed"),e=t?.iceTransport;if((this.sdpManager.bundlePolicy==="max-bundle"||this.sdpManager.bundlePolicy!=="disable"&&(this.remoteIsBundled||this.remoteBundleNegotiated))&&t)return t;let r=this.secureManager.createTransport();r.onRtp.subscribe(i=>{this.router.routeRtp(i)}),r.onRtcp.subscribe(i=>{this.router.routeRtcp(i)});let n=r.iceTransport;return n.onNegotiationNeeded.subscribe(()=>{this.needNegotiation()}),n.onIceCandidate.subscribe(i=>{if(!this.localDescription){ws("localDescription not found when ice candidate was gathered");return}if(!i){this.sdpManager.setLocal(this._localDescription,this.transceiverManager.getTransceivers(),this.sctpTransport),this.onIceCandidate.execute(void 0),this.onicecandidate&&this.onicecandidate({candidate:void 0}),this.emit("icecandidate",{candidate:void 0});return}if(!this._localDescription){ws("localDescription not found when ice candidate was gathered");return}this.secureManager.handleNewIceCandidate({candidate:i,bundlePolicy:this.sdpManager.bundlePolicy,remoteIsBundled:!!this.sdpManager.remoteIsBundled,media:this._localDescription.media[0],transceiver:this.transceiverManager.getTransceivers().find(o=>o?.dtlsTransport?.iceTransport.id===n.id),sctpTransport:this.sctpTransport?.dtlsTransport.iceTransport.id===n.id?this.sctpTransport:void 0})}),r}async setLocalDescription(t){t=t??(["stable","have-local-offer","have-remote-pranswer"].includes(this.signalingState)?await this.createOffer():await this.createAnswer());let r=this.sdpManager.parseSdp({sdp:t.sdp,isLocal:!0,signalingState:this.signalingState,type:t.type});r.type==="offer"?this.setSignalingState("have-local-offer"):r.type==="answer"&&this.setSignalingState("stable");for(let[i,o]of Gz(r.media)){let s=o.rtp.muxId;if(this.sdpManager.registerMid(s),["audio","video"].includes(o.kind)){let a=this.transceiverManager.getTransceiverByMLineIndex(i);a&&(a.mid=s)}o.kind==="application"&&this.sctpTransport&&(this.sctpTransport.mid=s)}let n=r.media.find(i=>i.dtlsParams)?.dtlsParams?.role;if(this.secureManager.setLocalRole({type:r.type,role:n}),["answer","pranswer"].includes(r.type))for(let i of this.transceiverManager.getTransceivers()){let o=nO(i.direction,i.offerDirection);i.setCurrentDirection(o)}return this.sdpManager.setLocal(r,this.transceiverManager.getTransceivers(),this.sctpTransport),await this.gatherCandidates().catch(i=>{ws("gatherCandidates failed",i)}),r.type==="answer"&&this.connect().catch(i=>{ws("connect failed",i),this.secureManager.setConnectionState("failed")}),this.sdpManager.setLocal(r,this.transceiverManager.getTransceivers(),this.sctpTransport),this.shouldNegotiationneeded&&this.needNegotiation(),r}async gatherCandidates(){await this.secureManager.gatherCandidates(!!this.sdpManager.remoteIsBundled)}async addIceCandidate(t){let e=this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(),this.sctpTransport);await this.secureManager.addIceCandidate(e,t)}async connect(){ws("start connect"),(await Promise.allSettled(this.dtlsTransports.map(async e=>{let{iceTransport:r}=e;if(r.state==="connected")return;let n=()=>e.state==="connected";n()||(this.secureManager.setConnectionState("connecting"),await r.start().catch(i=>{throw ws("iceTransport.start failed",i),i}),!n()&&(await e.start().catch(i=>{throw ws("dtlsTransport.start failed",i),i}),this.sctpTransport&&this.sctpTransport.dtlsTransport.id===e.id&&await this.sctpManager.connectSctp()))}))).find(e=>e.status==="rejected")?this.secureManager.setConnectionState("failed"):this.secureManager.setConnectionState("connected")}restartIce(){this.needRestart=!0,this.needNegotiation()}async setRemoteDescription(t){t instanceof bx&&(t=t.toSdp());let e=this.sdpManager.setRemoteDescription(t,this.signalingState);e.group.some(s=>s.semantic==="BUNDLE"&&s.items.length>0)&&(this.remoteBundleNegotiated=!0);let r,n=(s,a)=>s.kind===a.kind&&[void 0,a.rtp.muxId].includes(s.mid),i=e.media.map((s,a)=>{let c;if(["audio","video"].includes(s.kind)){let d=this.transceiverManager.getTransceivers().find(l=>n(l,s));if(!d)d=this.addTransceiver(s.kind,{direction:"recvonly"}),d.mid=s.rtp.muxId,this.onRemoteTransceiverAdded.execute(d);else if(d.direction==="inactive"&&d.stopping){d.stopped=!0,t.type==="answer"&&d.setCurrentDirection("inactive");return}this.sdpManager.remoteIsBundled&&(r?d.setDtlsTransport(r):r=d.dtlsTransport),c=d.dtlsTransport,this.transceiverManager.setRemoteRTP(d,s,e.type,a)}else if(s.kind==="application"){let d=this.sctpTransport;d||(d=this.createSctpTransport(),d.mid=s.rtp.muxId),this.sdpManager.remoteIsBundled&&(r?d.setDtlsTransport(r):r=d.dtlsTransport),c=d.dtlsTransport,this.sctpManager.setRemoteSCTP(s,a)}else throw new Error("invalid media kind");let u=c.iceTransport;if(s.iceParams){let d=!!this.sdpManager.inactiveRemoteMedia;u.setRemoteParams(s.iceParams,d),s.iceParams?.iceLite&&(u.connection.iceControlling=!0)}return s.dtlsParams&&c.setRemoteParams(s.dtlsParams),s.iceCandidates.forEach(u.addRemoteCandidate),s.iceCandidatesComplete&&u.addRemoteCandidate(void 0),e.type==="answer"&&s.dtlsParams?.role&&(c.role=s.dtlsParams.role==="client"?"server":"client"),u});i=i.filter(s=>!!s);let o=this.transceiverManager.getTransceivers().filter(s=>e.media.find(a=>n(s,a))==null);if(t.type==="answer")for(let s of o)s.stop(),s.stopped=!0;e.type==="offer"?this.setSignalingState("have-remote-offer"):e.type==="answer"&&this.setSignalingState("stable"),e.type==="answer"&&(ws("caller start connect"),this.connect().catch(s=>{ws("connect failed",s),this.secureManager.setConnectionState("failed")})),this.negotiationneeded=!1,this.shouldNegotiationneeded&&this.needNegotiation()}addTransceiver(t,e={}){let r=this.findOrCreateTransport(),n=this.transceiverManager.addTransceiver(t,r,e);return this.secureManager.updateIceConnectionState(),this.needNegotiation(),n}addTrack(t,e){if(this.isClosed)throw new Error("is closed");let r=this.transceiverManager.addTrack(t,e);if(!r.dtlsTransport){let n=this.findOrCreateTransport();r.setDtlsTransport(n)}return this.needNegotiation(),r.sender}async createAnswer(){return this.assertNotClosed(),await this.secureManager.ensureCerts(),this.sdpManager.buildAnswerSdp({transceivers:this.transceiverManager.getTransceivers(),sctpTransport:this.sctpTransport,signalingState:this.signalingState}).toJSON()}assertNotClosed(){if(this.isClosed)throw new Error("RTCPeerConnection is closed")}setSignalingState(t){ws("signalingStateChange",t),this.signalingState=t,this.signalingStateChange.execute(t),this.onsignalingstatechange&&this.onsignalingstatechange({})}createPeerConnectionStats(){let t=Bd();return{type:"peer-connection",id:hr("peer-connection"),timestamp:t,dataChannelsOpened:this.sctpManager.dataChannelsOpened,dataChannelsClosed:this.sctpManager.dataChannelsClosed}}async getStats(t){let e=[];e.push(this.createPeerConnectionStats());let r=await this.transceiverManager.getStats(t);e.push(...r);let n=await this.secureManager.getStats();if(e.push(...n),this.sctpTransport){let i=await this.sctpManager.getStats();i&&e.push(...i)}return new rY(e)}async close(){this.isClosed||(this.isClosed=!0,this.setSignalingState("closed"),this.transceiverManager.close(),await this.secureManager.close(),await this.sctpManager.close(),this.onDataChannel.allUnsubscribe(),this.iceGatheringStateChange.allUnsubscribe(),this.iceConnectionStateChange.allUnsubscribe(),this.signalingStateChange.allUnsubscribe(),this.onTransceiverAdded.allUnsubscribe(),this.onRemoteTransceiverAdded.allUnsubscribe(),this.onIceCandidate.allUnsubscribe(),ws("peerConnection closed"))}},x6=(t,e)=>t.find(r=>r.mimeType.toLowerCase()===e.mimeType.toLowerCase())?e:void 0;$1e=JY(),F1e=xt("werift:packages/webrtc/src/media/rtpTransceiverManager.ts"),XY=class{constructor(t,e,r){this.cname=t,this.config=e,this.router=r}transceivers=[];onTransceiverAdded=new qe;onRemoteTransceiverAdded=new qe;onTrack=new qe;onNegotiationNeeded=new qe;getTransceivers(){return this.transceivers}getSenders(){return this.getTransceivers().map(t=>t.sender)}getReceivers(){return this.getTransceivers().map(t=>t.receiver)}getTransceiverByMLineIndex(t){return this.transceivers.find(e=>e.mLineIndex===t)}pushTransceiver(t){this.transceivers.push(t)}replaceTransceiver(t,e){this.transceivers[e]=t}addTransceiver(t,e,r={}){let n=typeof t=="string"?t:t.kind,i=r.direction||"sendrecv",o=new zY(t),s=new pO(this.config,n,o.ssrc),a=new nY(n,e,s,o,i);a.options=r,this.router.registerRtpSender(a.sender);let c=this.transceivers.findIndex(d=>d.currentDirection==="inactive"&&!d.usedForSender),u=this.transceivers.find(d=>d.currentDirection==="inactive"&&!d.usedForSender);return c>-1&&u?(this.replaceTransceiver(a,c),a.mLineIndex=u.mLineIndex,a.mid=u.mid,u.setCurrentDirection(void 0)):this.pushTransceiver(a),this.onTransceiverAdded.execute(a),a}addTrack(t,e){if(this.getSenders().find(i=>i.track?.uuid===t.uuid))throw new Error("Track already added");let r=this.transceivers.find(i=>i.sender.track==null&&i.kind===t.kind&&Dk.includes(i.direction)===!0);if(r)return r.sender.registerTrack(t),r;let n=this.transceivers.find(i=>i.sender.track==null&&i.kind===t.kind&&Dk.includes(i.direction)===!1&&!i.usedForSender);if(n){switch(n.sender.registerTrack(t),n.direction){case"recvonly":n.setDirection("sendrecv");break;case"inactive":n.setDirection("sendonly");break}return n}else return this.addTransceiver(t,void 0,{direction:"sendrecv"})}removeTrack(t){if(!this.getSenders().find(({ssrc:r})=>t.ssrc===r))throw new Error("Sender does not exist");let e=this.transceivers.find(({sender:{ssrc:r}})=>t.ssrc===r);if(!e)throw new Error("No matching transceiver found");if(t.stop(),e.currentDirection==="recvonly"){this.onNegotiationNeeded.execute();return}e.stopping||e.stopped?e.setDirection("inactive"):e.direction==="sendrecv"?e.setDirection("recvonly"):(e.direction==="sendonly"||e.direction==="recvonly")&&e.setDirection("inactive")}assignTransceiverCodecs(t){let e=this.config.codecs[t.kind].filter(r=>{switch(r.direction){case"recvonly":return!!LRe.includes(t.direction);case"sendonly":return!!Dk.includes(t.direction);case"sendrecv":return!![eO,Z6,Q6].includes(t.direction);case"all":return!0;default:return!1}});t.codecs=e}getLocalRtpParams(t){if(t.mid==null)throw new Error("mid not assigned");return{codecs:t.codecs,muxId:t.mid,headerExtensions:t.headerExtensions,rtcp:{cname:this.cname,ssrc:t.sender.ssrc,mux:!0}}}getRemoteRtpParams(t,e){return{muxId:t.rtp.muxId,rtcp:t.rtp.rtcp,codecs:e.codecs,headerExtensions:e.headerExtensions,encodings:Object.values(e.codecs.reduce((n,i)=>{if(i.name.toLowerCase()==="rtx"){let o=$x(i.parameters??""),s=n[o.apt];return s&&t.ssrc.length===2&&(s.rtx=new XX({ssrc:t.ssrc[1].ssrc})),n}return n[i.payloadType]=new YX({ssrc:t.ssrc[0]?.ssrc,payloadType:i.payloadType}),n},{}))}}setRemoteRTP(t,e,r,n){if(t.mid||(t.mid=e.rtp.muxId),t.mLineIndex=n,t.codecs=e.rtp.codecs.filter(a=>{let c=this.config.codecs[e.kind]||[],u=x6(c,a);if(!u)return!1;if(u?.name.toLowerCase()==="rtx"){let l=$x(u.parameters??"").apt,f=e.rtp.codecs.find(p=>p.payloadType===l);return f?!!x6(c,f):!1}return!0}),F1e("negotiated codecs",t.codecs),t.codecs.length===0)throw new Error("negotiate codecs failed.");t.headerExtensions=e.rtp.headerExtensions.filter(a=>(this.config.headerExtensions[e.kind]||[]).find(c=>c.uri===a.uri));let i=e.direction??"inactive",o=cY(i);["answer","pranswer"].includes(r)?t.setCurrentDirection(o):t.offerDirection=o;let s=this.getLocalRtpParams(t);if(t.sender.prepareSend(s),["recvonly","sendrecv"].includes(t.direction)){let a=this.getRemoteRtpParams(e,t);for(let c of e.simulcastParameters)this.router.registerRtpReceiverByRid(t,c,a);t.receiver.prepareReceive(a),this.router.registerRtpReceiverBySsrc(t,a)}if(["sendonly","sendrecv"].includes(i)){if(e.msid){let[a,c]=e.msid.split(" ");t.receiver.remoteStreamId=a,t.receiver.remoteTrackId=c}this.onTrack.execute({track:t.receiver.track,transceiver:t,stream:new sY({id:t.receiver.remoteStreamId,tracks:[t.receiver.track]})})}e.ssrc[0]?.ssrc&&t.receiver.setupTWCC(e.ssrc[0].ssrc)}async getStats(t){let e=[];for(let r of this.transceivers){let n=!t||r.sender.track===t||r.receiver.track===t;if(r.sender){let i=await r.sender.getStats();if(i)for(let o of i)o.type==="outbound-rtp"||o.type==="media-source"?n&&e.push(o):e.push(o)}if(r.receiver){let i=await r.receiver.getStats();if(i)for(let o of i)o.type==="inbound-rtp"||o.type==="remote-outbound-rtp"?n&&e.push(o):e.push(o)}if(n){let i=r.getCodecStats();i&&e.push(...i)}}return e}close(){for(let t of this.transceivers)t.receiver.stop(),t.sender.stop();this.onTransceiverAdded.allUnsubscribe(),this.onRemoteTransceiverAdded.allUnsubscribe(),this.onTrack.allUnsubscribe(),this.onNegotiationNeeded.allUnsubscribe()}},j1e=["stable","have-local-offer","have-remote-offer","have-local-pranswer","have-remote-pranswer","closed"],q1e=["closed","failed","disconnected","new","connecting","connected"]});var Kc=ce((KXe,rQ)=>{"use strict";var eQ=["nodebuffer","arraybuffer","fragments"],tQ=typeof Blob<"u";tQ&&eQ.push("blob");rQ.exports={BINARY_TYPES:eQ,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:tQ,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Qx=ce((JXe,hR)=>{"use strict";var{EMPTY_BUFFER:Q1e}=Kc(),hO=Buffer[Symbol.species];function Z1e(t,e){if(t.length===0)return Q1e;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),n=0;for(let i=0;i<t.length;i++){let o=t[i];r.set(o,n),n+=o.length}return n<e?new hO(r.buffer,r.byteOffset,n):r}function nQ(t,e,r,n,i){for(let o=0;o<i;o++)r[n+o]=t[o]^e[o&3]}function iQ(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function eAe(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function gO(t){if(gO.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new hO(t):ArrayBuffer.isView(t)?e=new hO(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),gO.readOnly=!1),e}hR.exports={concat:Z1e,mask:nQ,toArrayBuffer:eAe,toBuffer:gO,unmask:iQ};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=Nt("bufferutil");hR.exports.mask=function(e,r,n,i,o){o<48?nQ(e,r,n,i,o):t.mask(e,r,n,i,o)},hR.exports.unmask=function(e,r){e.length<32?iQ(e,r):t.unmask(e,r)}}catch{}});var aQ=ce((XXe,sQ)=>{"use strict";var oQ=Symbol("kDone"),yO=Symbol("kRun"),vO=class{constructor(e){this[oQ]=()=>{this.pending--,this[yO]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[yO]()}[yO](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[oQ])}}};sQ.exports=vO});var Nh=ce((YXe,lQ)=>{"use strict";var Zx=Nt("node:zlib"),cQ=Qx(),tAe=aQ(),{kStatusCode:uQ}=Kc(),rAe=Buffer[Symbol.species],nAe=Buffer.from([0,0,255,255]),yR=Symbol("permessage-deflate"),Jc=Symbol("total-length"),Dh=Symbol("callback"),Nd=Symbol("buffers"),Bh=Symbol("error"),gR,xO=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!gR){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;gR=new tAe(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Dh];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,n=e.find(i=>!(r.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>i.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(n=>{let i=r[n];if(i.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(i=i[0],n==="client_max_window_bits"){if(i!==!0){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else if(n==="server_max_window_bits"){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=o}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=i})}),e}decompress(e,r,n){gR.add(i=>{this._decompress(e,r,(o,s)=>{i(),n(o,s)})})}compress(e,r,n){gR.add(i=>{this._compress(e,r,(o,s)=>{i(),n(o,s)})})}_decompress(e,r,n){let i=this._isServer?"client":"server";if(!this._inflate){let o=`${i}_max_window_bits`,s=typeof this.params[o]!="number"?Zx.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=Zx.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[yR]=this,this._inflate[Jc]=0,this._inflate[Nd]=[],this._inflate.on("error",oAe),this._inflate.on("data",dQ)}this._inflate[Dh]=n,this._inflate.write(e),r&&this._inflate.write(nAe),this._inflate.flush(()=>{let o=this._inflate[Bh];if(o){this._inflate.close(),this._inflate=null,n(o);return}let s=cQ.concat(this._inflate[Nd],this._inflate[Jc]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Jc]=0,this._inflate[Nd]=[],r&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),n(null,s)})}_compress(e,r,n){let i=this._isServer?"server":"client";if(!this._deflate){let o=`${i}_max_window_bits`,s=typeof this.params[o]!="number"?Zx.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=Zx.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[Jc]=0,this._deflate[Nd]=[],this._deflate.on("data",iAe)}this._deflate[Dh]=n,this._deflate.write(e),this._deflate.flush(Zx.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=cQ.concat(this._deflate[Nd],this._deflate[Jc]);r&&(o=new rAe(o.buffer,o.byteOffset,o.length-4)),this._deflate[Dh]=null,this._deflate[Jc]=0,this._deflate[Nd]=[],r&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),n(null,o)})}};lQ.exports=xO;function iAe(t){this[Nd].push(t),this[Jc]+=t.length}function dQ(t){if(this[Jc]+=t.length,this[yR]._maxPayload<1||this[Jc]<=this[yR]._maxPayload){this[Nd].push(t);return}this[Bh]=new RangeError("Max payload size exceeded"),this[Bh].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Bh][uQ]=1009,this.removeListener("data",dQ),this.reset()}function oAe(t){if(this[yR]._inflate=null,this[Bh]){this[Dh](this[Bh]);return}t[uQ]=1007,this[Dh](t)}});var Oh=ce((QXe,vR)=>{"use strict";var{isUtf8:fQ}=Nt("node:buffer"),{hasBlob:sAe}=Kc(),aAe=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function cAe(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function SO(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function uAe(t){return sAe&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}vR.exports={isBlob:uAe,isValidStatusCode:cAe,isValidUTF8:SO,tokenChars:aAe};if(fQ)vR.exports.isValidUTF8=function(t){return t.length<24?SO(t):fQ(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=Nt("utf-8-validate");vR.exports.isValidUTF8=function(e){return e.length<32?SO(e):t(e)}}catch{}});var kO=ce((ZXe,xQ)=>{"use strict";var{Writable:dAe}=Nt("node:stream"),pQ=Nh(),{BINARY_TYPES:lAe,EMPTY_BUFFER:mQ,kStatusCode:fAe,kWebSocket:pAe}=Kc(),{concat:bO,toArrayBuffer:mAe,unmask:hAe}=Qx(),{isValidStatusCode:gAe,isValidUTF8:hQ}=Oh(),xR=Buffer[Symbol.species],$o=0,gQ=1,yQ=2,vQ=3,wO=4,IO=5,SR=6,EO=class extends dAe{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||lAe[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[pAe]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=$o}_write(e,r,n){if(this._opcode===8&&this._state==$o)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new xR(n.buffer,n.byteOffset+e,n.length-e),new xR(n.buffer,n.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let n=this._buffers[0],i=r.length-e;e>=n.length?r.set(this._buffers.shift(),i):(r.set(new Uint8Array(n.buffer,n.byteOffset,e),i),this._buffers[0]=new xR(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case $o:this.getInfo(e);break;case gQ:this.getPayloadLength16(e);break;case yQ:this.getPayloadLength64(e);break;case vQ:this.getMask();break;case wO:this.getData(e);break;case IO:case SR:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let n=(r[0]&64)===64;if(n&&!this._extensions[pQ.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=gQ:this._payloadLength===127?this._state=yQ:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=vQ:this._state=wO}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=wO}getData(e){let r=mQ;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&hAe(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=IO,this.decompress(r,e);return}if(r.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(n);return}this._messageLength=this._totalPayloadLength,this._fragments.push(r)}this.dataMessage(e)}decompress(e,r){this._extensions[pQ.extensionName].decompress(e,this._fin,(i,o)=>{if(i)return r(i);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(s);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let s=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");r(s);return}this._fragments.push(o)}this.dataMessage(r),this._state===$o&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=$o;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=bO(n,r):this._binaryType==="arraybuffer"?i=mAe(bO(n,r)):this._binaryType==="blob"?i=new Blob(n):i=n,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=$o):(this._state=SR,setImmediate(()=>{this.emit("message",i,!0),this._state=$o,this.startLoop(e)}))}else{let i=bO(n,r);if(!this._skipUTF8Validation&&!hQ(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===IO||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=$o):(this._state=SR,setImmediate(()=>{this.emit("message",i,!1),this._state=$o,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,mQ),this.end();else{let n=e.readUInt16BE(0);if(!gAe(n)){let o=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(o);return}let i=new xR(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!hQ(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(o);return}this._loop=!1,this.emit("conclude",n,i),this.end()}this._state=$o;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=$o):(this._state=SR,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=$o,this.startLoop(r)}))}createError(e,r,n,i,o){this._loop=!1,this._errored=!0;let s=new e(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(s,this.createError),s.code=o,s[fAe]=i,s}};xQ.exports=EO});var CO=ce((tYe,wQ)=>{"use strict";var{Duplex:eYe}=Nt("node:stream"),{randomFillSync:yAe}=Nt("node:crypto"),{types:{isUint8Array:vAe}}=Nt("node:util"),SQ=Nh(),{EMPTY_BUFFER:xAe,kWebSocket:SAe,NOOP:bAe}=Kc(),{isBlob:Mh,isValidStatusCode:wAe}=Oh(),{mask:bQ,toBuffer:Of}=Qx(),Fo=Symbol("kByteLength"),IAe=Buffer.alloc(4),bR=8*1024,Mf,Lh=bR,As=0,EAe=1,kAe=2,RO=class t{constructor(e,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=As,this.onerror=bAe,this[SAe]=void 0}static frame(e,r){let n,i=!1,o=2,s=!1;r.mask&&(n=r.maskBuffer||IAe,r.generateMask?r.generateMask(n):(Lh===bR&&(Mf===void 0&&(Mf=Buffer.alloc(bR)),yAe(Mf,0,bR),Lh=0),n[0]=Mf[Lh++],n[1]=Mf[Lh++],n[2]=Mf[Lh++],n[3]=Mf[Lh++]),s=(n[0]|n[1]|n[2]|n[3])===0,o=6);let a;typeof e=="string"?(!r.mask||s)&&r[Fo]!==void 0?a=r[Fo]:(e=Buffer.from(e),a=e.length):(a=e.length,i=r.mask&&r.readOnly&&!s);let c=a;a>=65536?(o+=8,c=127):a>125&&(o+=2,c=126);let u=Buffer.allocUnsafe(i?a+o:o);return u[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(a,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(a,4,6)),r.mask?(u[1]|=128,u[o-4]=n[0],u[o-3]=n[1],u[o-2]=n[2],u[o-1]=n[3],s?[u,e]:i?(bQ(e,n,u,o,a),[u]):(bQ(e,n,e,0,a),[u,e])):[u,e]}close(e,r,n,i){let o;if(e===void 0)o=xAe;else{if(typeof e!="number"||!wAe(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+a),o.writeUInt16BE(e,0),typeof r=="string")o.write(r,2);else if(vAe(r))o.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[Fo]:o.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==As?this.enqueue([this.dispatch,o,!1,s,i]):this.sendFrame(t.frame(o,s),i)}ping(e,r,n){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):Mh(e)?(i=e.size,o=!1):(e=Of(e),i=e.length,o=Of.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[Fo]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};Mh(e)?this._state!==As?this.enqueue([this.getBlobData,e,!1,s,n]):this.getBlobData(e,!1,s,n):this._state!==As?this.enqueue([this.dispatch,e,!1,s,n]):this.sendFrame(t.frame(e,s),n)}pong(e,r,n){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):Mh(e)?(i=e.size,o=!1):(e=Of(e),i=e.length,o=Of.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[Fo]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};Mh(e)?this._state!==As?this.enqueue([this.getBlobData,e,!1,s,n]):this.getBlobData(e,!1,s,n):this._state!==As?this.enqueue([this.dispatch,e,!1,s,n]):this.sendFrame(t.frame(e,s),n)}send(e,r,n){let i=this._extensions[SQ.extensionName],o=r.binary?2:1,s=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Mh(e)?(a=e.size,c=!1):(e=Of(e),a=e.length,c=Of.readOnly),this._firstFragment?(this._firstFragment=!1,s&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=i._threshold),this._compress=s):(s=!1,o=0),r.fin&&(this._firstFragment=!0);let u={[Fo]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:s};Mh(e)?this._state!==As?this.enqueue([this.getBlobData,e,this._compress,u,n]):this.getBlobData(e,this._compress,u,n):this._state!==As?this.enqueue([this.dispatch,e,this._compress,u,n]):this.dispatch(e,this._compress,u,n)}getBlobData(e,r,n,i){this._bufferedBytes+=n[Fo],this._state=kAe,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(AO,this,a,i);return}this._bufferedBytes-=n[Fo];let s=Of(o);r?this.dispatch(s,r,n,i):(this._state=As,this.sendFrame(t.frame(s,n),i),this.dequeue())}).catch(o=>{process.nextTick(RAe,this,o,i)})}dispatch(e,r,n,i){if(!r){this.sendFrame(t.frame(e,n),i);return}let o=this._extensions[SQ.extensionName];this._bufferedBytes+=n[Fo],this._state=EAe,o.compress(e,n.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");AO(this,c,i);return}this._bufferedBytes-=n[Fo],this._state=As,n.readOnly=!1,this.sendFrame(t.frame(a,n),i),this.dequeue()})}dequeue(){for(;this._state===As&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Fo],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Fo],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};wQ.exports=RO;function AO(t,e,r){typeof r=="function"&&r(e);for(let n=0;n<t._queue.length;n++){let i=t._queue[n],o=i[i.length-1];typeof o=="function"&&o(e)}}function RAe(t,e,r){AO(t,e,r),t.onerror(e)}});var TQ=ce((rYe,_Q)=>{"use strict";var{kForOnEventAttribute:eS,kListener:PO}=Kc(),IQ=Symbol("kCode"),EQ=Symbol("kData"),kQ=Symbol("kError"),RQ=Symbol("kMessage"),AQ=Symbol("kReason"),Hh=Symbol("kTarget"),CQ=Symbol("kType"),PQ=Symbol("kWasClean"),Xc=class{constructor(e){this[Hh]=null,this[CQ]=e}get target(){return this[Hh]}get type(){return this[CQ]}};Object.defineProperty(Xc.prototype,"target",{enumerable:!0});Object.defineProperty(Xc.prototype,"type",{enumerable:!0});var Lf=class extends Xc{constructor(e,r={}){super(e),this[IQ]=r.code===void 0?0:r.code,this[AQ]=r.reason===void 0?"":r.reason,this[PQ]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[IQ]}get reason(){return this[AQ]}get wasClean(){return this[PQ]}};Object.defineProperty(Lf.prototype,"code",{enumerable:!0});Object.defineProperty(Lf.prototype,"reason",{enumerable:!0});Object.defineProperty(Lf.prototype,"wasClean",{enumerable:!0});var Uh=class extends Xc{constructor(e,r={}){super(e),this[kQ]=r.error===void 0?null:r.error,this[RQ]=r.message===void 0?"":r.message}get error(){return this[kQ]}get message(){return this[RQ]}};Object.defineProperty(Uh.prototype,"error",{enumerable:!0});Object.defineProperty(Uh.prototype,"message",{enumerable:!0});var tS=class extends Xc{constructor(e,r={}){super(e),this[EQ]=r.data===void 0?null:r.data}get data(){return this[EQ]}};Object.defineProperty(tS.prototype,"data",{enumerable:!0});var AAe={addEventListener(t,e,r={}){for(let i of this.listeners(t))if(!r[eS]&&i[PO]===e&&!i[eS])return;let n;if(t==="message")n=function(o,s){let a=new tS("message",{data:s?o:o.toString()});a[Hh]=this,wR(e,this,a)};else if(t==="close")n=function(o,s){let a=new Lf("close",{code:o,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Hh]=this,wR(e,this,a)};else if(t==="error")n=function(o){let s=new Uh("error",{error:o,message:o.message});s[Hh]=this,wR(e,this,s)};else if(t==="open")n=function(){let o=new Xc("open");o[Hh]=this,wR(e,this,o)};else return;n[eS]=!!r[eS],n[PO]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[PO]===e&&!r[eS]){this.removeListener(t,r);break}}};_Q.exports={CloseEvent:Lf,ErrorEvent:Uh,Event:Xc,EventTarget:AAe,MessageEvent:tS};function wR(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var IR=ce((nYe,DQ)=>{"use strict";var{tokenChars:rS}=Oh();function Aa(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function CAe(t){let e=Object.create(null),r=Object.create(null),n=!1,i=!1,o=!1,s,a,c=-1,u=-1,d=-1,l=0;for(;l<t.length;l++)if(u=t.charCodeAt(l),s===void 0)if(d===-1&&rS[u]===1)c===-1&&(c=l);else if(l!==0&&(u===32||u===9))d===-1&&c!==-1&&(d=l);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${l}`);d===-1&&(d=l);let p=t.slice(c,d);u===44?(Aa(e,p,r),r=Object.create(null)):s=p,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${l}`);else if(a===void 0)if(d===-1&&rS[u]===1)c===-1&&(c=l);else if(u===32||u===9)d===-1&&c!==-1&&(d=l);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${l}`);d===-1&&(d=l),Aa(r,t.slice(c,d),!0),u===44&&(Aa(e,s,r),r=Object.create(null),s=void 0),c=d=-1}else if(u===61&&c!==-1&&d===-1)a=t.slice(c,l),c=d=-1;else throw new SyntaxError(`Unexpected character at index ${l}`);else if(i){if(rS[u]!==1)throw new SyntaxError(`Unexpected character at index ${l}`);c===-1?c=l:n||(n=!0),i=!1}else if(o)if(rS[u]===1)c===-1&&(c=l);else if(u===34&&c!==-1)o=!1,d=l;else if(u===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${l}`);else if(u===34&&t.charCodeAt(l-1)===61)o=!0;else if(d===-1&&rS[u]===1)c===-1&&(c=l);else if(c!==-1&&(u===32||u===9))d===-1&&(d=l);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${l}`);d===-1&&(d=l);let p=t.slice(c,d);n&&(p=p.replace(/\\/g,""),n=!1),Aa(r,a,p),u===44&&(Aa(e,s,r),r=Object.create(null),s=void 0),a=void 0,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${l}`);if(c===-1||o||u===32||u===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=l);let f=t.slice(c,d);return s===void 0?Aa(e,f,r):(a===void 0?Aa(r,f,!0):n?Aa(r,a,f.replace(/\\/g,"")):Aa(r,a,f),Aa(e,s,r)),e}function PAe(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(n=>[e].concat(Object.keys(n).map(i=>{let o=n[i];return Array.isArray(o)||(o=[o]),o.map(s=>s===!0?i:`${i}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}DQ.exports={format:PAe,parse:CAe}});var AR=ce((sYe,WQ)=>{"use strict";var _Ae=Nt("node:events"),TAe=Nt("node:https"),DAe=Nt("node:http"),OQ=Nt("node:net"),BAe=Nt("node:tls"),{randomBytes:NAe,createHash:OAe}=Nt("node:crypto"),{Duplex:iYe,Readable:oYe}=Nt("node:stream"),{URL:_O}=Nt("node:url"),Od=Nh(),MAe=kO(),LAe=CO(),{isBlob:HAe}=Oh(),{BINARY_TYPES:BQ,CLOSE_TIMEOUT:UAe,EMPTY_BUFFER:ER,GUID:$Ae,kForOnEventAttribute:TO,kListener:FAe,kStatusCode:jAe,kWebSocket:Cn,NOOP:MQ}=Kc(),{EventTarget:{addEventListener:qAe,removeEventListener:WAe}}=TQ(),{format:VAe,parse:GAe}=IR(),{toBuffer:zAe}=Qx(),LQ=Symbol("kAborted"),DO=[8,13],Yc=["CONNECTING","OPEN","CLOSING","CLOSED"],KAe=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Tr=class t extends _Ae{constructor(e,r,n){super(),this._binaryType=BQ[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ER,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),HQ(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){BQ.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,n){let i=new MAe({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),o=new LAe(e,this._extensions,n.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[Cn]=this,o[Cn]=this,e[Cn]=this,i.on("conclude",YAe),i.on("drain",QAe),i.on("error",ZAe),i.on("message",eCe),i.on("ping",tCe),i.on("pong",rCe),o.onerror=nCe,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",FQ),e.on("data",RR),e.on("end",jQ),e.on("error",qQ),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Od.extensionName]&&this._extensions[Od.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){uo(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),$Q(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){BO(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||ER,r,n)}pong(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){BO(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||ER,r,n)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){BO(this,e,n);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Od.extensionName]||(i.compress=!1),this._sender.send(e||ER,i,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){uo(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Tr,"CONNECTING",{enumerable:!0,value:Yc.indexOf("CONNECTING")});Object.defineProperty(Tr.prototype,"CONNECTING",{enumerable:!0,value:Yc.indexOf("CONNECTING")});Object.defineProperty(Tr,"OPEN",{enumerable:!0,value:Yc.indexOf("OPEN")});Object.defineProperty(Tr.prototype,"OPEN",{enumerable:!0,value:Yc.indexOf("OPEN")});Object.defineProperty(Tr,"CLOSING",{enumerable:!0,value:Yc.indexOf("CLOSING")});Object.defineProperty(Tr.prototype,"CLOSING",{enumerable:!0,value:Yc.indexOf("CLOSING")});Object.defineProperty(Tr,"CLOSED",{enumerable:!0,value:Yc.indexOf("CLOSED")});Object.defineProperty(Tr.prototype,"CLOSED",{enumerable:!0,value:Yc.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Tr.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Tr.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[TO])return e[FAe];return null},set(e){for(let r of this.listeners(t))if(r[TO]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[TO]:!0})}})});Tr.prototype.addEventListener=qAe;Tr.prototype.removeEventListener=WAe;WQ.exports=Tr;function HQ(t,e,r,n){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:UAe,protocolVersion:DO[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!DO.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${DO.join(", ")})`);let o;if(e instanceof _O)o=e;else try{o=new _O(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let s=o.protocol==="wss:",a=o.protocol==="ws+unix:",c;if(o.protocol!=="ws:"&&!s&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"),c){let v=new SyntaxError(c);if(t._redirects===0)throw v;kR(t,v);return}let u=s?443:80,d=NAe(16).toString("base64"),l=s?TAe.request:DAe.request,f=new Set,p;if(i.createConnection=i.createConnection||(s?XAe:JAe),i.defaultPort=i.defaultPort||u,i.port=o.port||u,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(p=new Od({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=VAe({[Od.extensionName]:p.offer()})),r.length){for(let v of r){if(typeof v!="string"||!KAe.test(v)||f.has(v))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(v)}i.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),a){let v=i.path.split(":");i.socketPath=v[0],i.path=v[1]}let g;if(i.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?i.socketPath:o.host;let v=n&&n.headers;if(n={...n,headers:{}},v)for(let[b,C]of Object.entries(v))n.headers[b.toLowerCase()]=C}else if(t.listenerCount("redirect")===0){let v=a?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!v||t._originalSecure&&!s)&&(delete i.headers.authorization,delete i.headers.cookie,v||delete i.headers.host,i.auth=void 0)}i.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),g=t._req=l(i),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=l(i);i.timeout&&g.on("timeout",()=>{uo(t,g,"Opening handshake has timed out")}),g.on("error",v=>{g===null||g[LQ]||(g=t._req=null,kR(t,v))}),g.on("response",v=>{let b=v.headers.location,C=v.statusCode;if(b&&i.followRedirects&&C>=300&&C<400){if(++t._redirects>i.maxRedirects){uo(t,g,"Maximum redirects exceeded");return}g.abort();let D;try{D=new _O(b,e)}catch{let F=new SyntaxError(`Invalid URL: ${b}`);kR(t,F);return}HQ(t,D,r,n)}else t.emit("unexpected-response",g,v)||uo(t,g,`Unexpected server response: ${v.statusCode}`)}),g.on("upgrade",(v,b,C)=>{if(t.emit("upgrade",v),t.readyState!==Tr.CONNECTING)return;g=t._req=null;let D=v.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){uo(t,b,"Invalid Upgrade header");return}let _=OAe("sha1").update(d+$Ae).digest("base64");if(v.headers["sec-websocket-accept"]!==_){uo(t,b,"Invalid Sec-WebSocket-Accept header");return}let F=v.headers["sec-websocket-protocol"],he;if(F!==void 0?f.size?f.has(F)||(he="Server sent an invalid subprotocol"):he="Server sent a subprotocol but none was requested":f.size&&(he="Server sent no subprotocol"),he){uo(t,b,he);return}F&&(t._protocol=F);let z=v.headers["sec-websocket-extensions"];if(z!==void 0){if(!p){uo(t,b,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Ce;try{Ce=GAe(z)}catch{uo(t,b,"Invalid Sec-WebSocket-Extensions header");return}let de=Object.keys(Ce);if(de.length!==1||de[0]!==Od.extensionName){uo(t,b,"Server indicated an extension that was not requested");return}try{p.accept(Ce[Od.extensionName])}catch{uo(t,b,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Od.extensionName]=p}t.setSocket(b,C,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(g,t):g.end()}function kR(t,e){t._readyState=Tr.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function JAe(t){return t.path=t.socketPath,OQ.connect(t)}function XAe(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=OQ.isIP(t.host)?"":t.host),BAe.connect(t)}function uo(t,e,r){t._readyState=Tr.CLOSING;let n=new Error(r);Error.captureStackTrace(n,uo),e.setHeader?(e[LQ]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(kR,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function BO(t,e,r){if(e){let n=HAe(e)?e.size:zAe(e).length;t._socket?t._sender._bufferedBytes+=n:t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${Yc[t.readyState]})`);process.nextTick(r,n)}}function YAe(t,e){let r=this[Cn];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[Cn]!==void 0&&(r._socket.removeListener("data",RR),process.nextTick(UQ,r._socket),t===1005?r.close():r.close(t,e))}function QAe(){let t=this[Cn];t.isPaused||t._socket.resume()}function ZAe(t){let e=this[Cn];e._socket[Cn]!==void 0&&(e._socket.removeListener("data",RR),process.nextTick(UQ,e._socket),e.close(t[jAe])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function NQ(){this[Cn].emitClose()}function eCe(t,e){this[Cn].emit("message",t,e)}function tCe(t){let e=this[Cn];e._autoPong&&e.pong(t,!this._isServer,MQ),e.emit("ping",t)}function rCe(t){this[Cn].emit("pong",t)}function UQ(t){t.resume()}function nCe(t){let e=this[Cn];e.readyState!==Tr.CLOSED&&(e.readyState===Tr.OPEN&&(e._readyState=Tr.CLOSING,$Q(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function $Q(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function FQ(){let t=this[Cn];if(this.removeListener("close",FQ),this.removeListener("data",RR),this.removeListener("end",jQ),t._readyState=Tr.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Cn]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",NQ),t._receiver.on("finish",NQ))}function RR(t){this[Cn]._receiver.write(t)||this.pause()}function jQ(){let t=this[Cn];t._readyState=Tr.CLOSING,t._receiver.end(),this.end()}function qQ(){let t=this[Cn];this.removeListener("error",qQ),this.on("error",MQ),t&&(t._readyState=Tr.CLOSING,this.destroy())}});var KQ=ce((cYe,zQ)=>{"use strict";var aYe=AR(),{Duplex:iCe}=Nt("node:stream");function VQ(t){t.emit("close")}function oCe(){!this.destroyed&&this._writableState.finished&&this.destroy()}function GQ(t){this.removeListener("error",GQ),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function sCe(t,e){let r=!0,n=new iCe({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,s){let a=!s&&n._readableState.objectMode?o.toString():o;n.push(a)||t.pause()}),t.once("error",function(o){n.destroyed||(r=!1,n.destroy(o))}),t.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(i,o){if(t.readyState===t.CLOSED){o(i),process.nextTick(VQ,n);return}let s=!1;t.once("error",function(c){s=!0,o(c)}),t.once("close",function(){s||o(i),process.nextTick(VQ,n)}),r&&t.terminate()},n._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){n._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),n._readableState.endEmitted&&n.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},n._read=function(){t.isPaused&&t.resume()},n._write=function(i,o,s){if(t.readyState===t.CONNECTING){t.once("open",function(){n._write(i,o,s)});return}t.send(i,s)},n.on("end",oCe),n.on("error",GQ),n}zQ.exports=sCe});var NO=ce((uYe,JQ)=>{"use strict";var{tokenChars:aCe}=Oh();function cCe(t){let e=new Set,r=-1,n=-1,i=0;for(i;i<t.length;i++){let s=t.charCodeAt(i);if(n===-1&&aCe[s]===1)r===-1&&(r=i);else if(i!==0&&(s===32||s===9))n===-1&&r!==-1&&(n=i);else if(s===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${i}`);n===-1&&(n=i);let a=t.slice(r,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(r,i);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}JQ.exports={parse:cCe}});var rZ=ce((lYe,tZ)=>{"use strict";var uCe=Nt("node:events"),CR=Nt("node:http"),{Duplex:dYe}=Nt("node:stream"),{createHash:dCe}=Nt("node:crypto"),XQ=IR(),Hf=Nh(),lCe=NO(),fCe=AR(),{CLOSE_TIMEOUT:pCe,GUID:mCe,kWebSocket:hCe}=Kc(),gCe=/^[+/0-9A-Za-z]{22}==$/,YQ=0,QQ=1,eZ=2,OO=class extends uCe{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:pCe,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:fCe,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=CR.createServer((n,i)=>{let o=CR.STATUS_CODES[426];i.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),i.end(o)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=yCe(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,o,s)=>{this.handleUpgrade(i,o,s,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=YQ}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===eZ){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(nS,this);return}if(e&&this.once("close",e),this._state!==QQ)if(this._state=QQ,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(nS,this):process.nextTick(nS,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{nS(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,n,i){r.on("error",ZQ);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Uf(this,e,r,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){Uf(this,e,r,400,"Invalid Upgrade header");return}if(o===void 0||!gCe.test(o)){Uf(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Uf(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){iS(r,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=lCe.parse(c)}catch{Uf(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],l={};if(this.options.perMessageDeflate&&d!==void 0){let f=new Hf({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=XQ.parse(d);p[Hf.extensionName]&&(f.accept(p[Hf.extensionName]),l[Hf.extensionName]=f)}catch{Uf(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(p,g,v,b)=>{if(!p)return iS(r,g||401,v,b);this.completeUpgrade(l,o,u,e,r,n,i)});return}if(!this.options.verifyClient(f))return iS(r,401)}this.completeUpgrade(l,o,u,e,r,n,i)}completeUpgrade(e,r,n,i,o,s,a){if(!o.readable||!o.writable)return o.destroy();if(o[hCe])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>YQ)return iS(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${dCe("sha1").update(r+mCe).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let l=this.options.handleProtocols?this.options.handleProtocols(n,i):n.values().next().value;l&&(u.push(`Sec-WebSocket-Protocol: ${l}`),d._protocol=l)}if(e[Hf.extensionName]){let l=e[Hf.extensionName].params,f=XQ.format({[Hf.extensionName]:[l]});u.push(`Sec-WebSocket-Extensions: ${f}`),d._extensions=e}this.emit("headers",u,i),o.write(u.concat(`\r
133
+ `).join(`\r
134
+ `)),o.removeListener("error",ZQ),d.setSocket(o,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(nS,this)})),a(d,i)}};tZ.exports=OO;function yCe(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let n of Object.keys(e))t.removeListener(n,e[n])}}function nS(t){t._state=eZ,t.emit("close")}function ZQ(){this.destroy()}function iS(t,e,r,n){r=r||CR.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${CR.STATUS_CODES[e]}\r
135
+ `+Object.keys(n).map(i=>`${i}: ${n[i]}`).join(`\r
136
+ `)+`\r
137
+ \r
138
+ `+r)}function Uf(t,e,r,n,i,o){if(t.listenerCount("wsClientError")){let s=new Error(i);Error.captureStackTrace(s,Uf),t.emit("wsClientError",s,r,e)}else iS(r,n,i,o)}});var dZ={};wi(dZ,{PerMessageDeflate:()=>oZ.default,Receiver:()=>sZ.default,Sender:()=>aZ.default,WebSocket:()=>MO.default,WebSocketServer:()=>uZ.default,createWebSocketStream:()=>nZ.default,default:()=>vCe,extension:()=>iZ.default,subprotocol:()=>cZ.default});var nZ,iZ,oZ,sZ,aZ,cZ,MO,uZ,vCe,lZ=N(()=>{nZ=tt(KQ(),1),iZ=tt(IR(),1),oZ=tt(Nh(),1),sZ=tt(kO(),1),aZ=tt(CO(),1),cZ=tt(NO(),1),MO=tt(AR(),1),uZ=tt(rZ(),1),vCe=MO.default});var oi="[redacted]",k3=new Set(["hunsuBridgeToken","hunsuConnectAccessToken","hunsuConnectRefreshToken","hunsuConnectDeviceCode","token","access_token","refresh_token","authorization","controlToken","bridgeControlToken","code","state"].map(t=>t.toLowerCase())),R3=["hunsuBridgeToken","hunsuConnectAccessToken","hunsuConnectRefreshToken","hunsuConnectDeviceCode","access_token","refresh_token","authorization","controlToken","bridgeControlToken","token","code","state"].join("|"),Uee=[R3,"apiKey","accessToken","refreshToken","authToken","bridgeAuthToken","controlToken","bridgeControlToken","OPENAI_API_KEY","CODEX_ACCESS_TOKEN"].join("|"),$ee=/([?&])([^=&#\s"'<>\\]+)=([^&#\s"'<>\\]*)/giu,Fee=new RegExp(`((?:%3f|%26)(?:${R3})(?:%3d|=))((?:(?!%26|%23)[^\\s"'<>\\\\])+)`,"giu"),jee=/("(?:[^"\\]*(?:token|secret|api.?key|authorization|credential|auth\.json|password|cookie)[^"\\]*)"\s*:\s*)("(?:\\.|[^"\\])*"|[^,}\]\s]+)/giu,qee=new RegExp(`(^|[\\s,;])(${Uee})(\\s*=\\s*)(?:Bearer\\s+)?[^\\s,;&]+`,"gimu");function A3(t){return t.replace($ee,(e,r,n,i)=>{let o=Vee(n);return k3.has(o)?`${r}${n}=${D3(i)}`:e})}function Qh(t){let e=Wee(t);return e!==void 0?e:A3(t).replace(Fee,(r,n,i)=>`${n}${D3(i)}`).replace(/sk-[A-Za-z0-9_-]{10,}/gu,oi).replace(/\bhunsu_bridge_[A-Za-z0-9_-]+\b/giu,oi).replace(/\bhunsu_control_[A-Za-z0-9_-]+\b/giu,oi).replace(/(OPENAI_API_KEY|CODEX_ACCESS_TOKEN)(\s*=\s*)(?:"[^"]*"|'[^']*'|\S+)/giu,`$1$2${oi}`).replace(/~\/\.codex\/auth\.json/giu,oi).replace(jee,`$1"${oi}"`).replace(qee,(r,n,i,o)=>`${n}${i}${o}${oi}`).replace(/(Bearer\s+)(?!\[redacted\])[^\s,"'\\]+/giu,`$1${oi}`)}function Qr(t){return r1(t,new WeakSet)}function Ds(t){C3(t,new WeakSet)}function r1(t,e){if(typeof t=="string")return Qh(t);if(Array.isArray(t)){if(e.has(t))return"[circular]";e.add(t);let n=t.map((i,o)=>T3(t[o-1])?oi:r1(i,e));return e.delete(t),n}if(typeof t!="object"||t===null)return t;if(t instanceof Date)return t.toISOString();if(e.has(t))return"[circular]";e.add(t);let r={};for(let[n,i]of Object.entries(t))r[n]=_3(n,i)?oi:r1(i,e);return e.delete(t),r}function C3(t,e){if(typeof t=="string"){if(Qh(t)!==t)throw t1();return}if(!(typeof t!="object"||t===null||t instanceof Date)&&!e.has(t)){e.add(t);for(let[r,[n,i]]of Object.entries(t).entries()){if(Array.isArray(t)&&T3(t[r-1])&&i!==oi||_3(n,i)&&i!==oi)throw t1();C3(i,e)}e.delete(t)}}function Wee(t){let e=t.trim();if(!(!(e.startsWith("{")&&e.endsWith("}"))&&!(e.startsWith("[")&&e.endsWith("]"))))try{let r=JSON.parse(e);if(typeof r!="object"||r===null)return;let n=Qr(r);return JSON.stringify(r)===JSON.stringify(n)?void 0:JSON.stringify(n)}catch{return}}function Vee(t){let e=t.replace(/^amp;/iu,"");try{return decodeURIComponent(e.replace(/\+/gu," ")).toLowerCase()}catch{return e.toLowerCase()}}function P3(t){return/token|secret|api.?key|authorization|credential|auth\.json|password|cookie/iu.test(t)}function _3(t,e){return!(t==="credentialsPresent"&&typeof e=="boolean")&&P3(t)}function T3(t){if(typeof t!="string"||!/^--?[^=]+$/u.test(t))return!1;let e=t.replace(/^--?/u,"").replace(/[-_]/gu,"");return P3(e)||k3.has(e.toLowerCase())}function D3(t){return Gee(t)?t:oi}function Gee(t){if(t.toLowerCase()===oi)return!0;try{return decodeURIComponent(t).toLowerCase()===oi}catch{return!1}}function t1(){return new Error("Diagnostics contain sensitive data.")}var zee=Object.freeze({production:Object.freeze({webUrl:"https://hunsu.app/studio",connectApiUrl:"https://connect.hunsu.app",connectWsUrl:"wss://connect.hunsu.app/v1/connect/device",connectTicketIssuer:"https://connect.hunsu.app",connectTicketSigningKeyId:"connect-enaK6bbNEOky9hUYzzJuN3Qi",connectTicketSigningPublicJwk:Object.freeze({kty:"EC",crv:"P-256",x:"LmCMF_gjDJ9HQOmdmk_ylwWFA5r3cwvuMpJ_f6Ud3Cg",y:"wjC2rVxMFzICuC-QH3RKXb5ztR968bg2oVc5PJ1A1gM"})}),preview:Object.freeze({webUrl:"https://preview.hunsu.app/studio",connectApiUrl:"https://connect.preview.hunsu.app",connectWsUrl:"wss://connect.preview.hunsu.app/v1/connect/device",connectTicketIssuer:"https://connect.preview.hunsu.app",connectTicketSigningKeyId:"connect-LPehY8CSnG6Y0rkTzjQB4I77",connectTicketSigningPublicJwk:Object.freeze({kty:"EC",crv:"P-256",x:"69FCDW0whttjj1IhJjFMQOOl-icup4Dv4MlpgasZcWw",y:"9oGa20XKzFy9LCFn34v3H7ss42sD_9eKhjBbWwwBTa4"})})});function Pn(t){return t==="production"||t==="preview"}function B3(t){return zee[t]}function xS(t){return t==="preview"?"candidate-next":"next"}import{randomBytes as sPe}from"node:crypto";import{mkdir as aPe}from"node:fs/promises";import{isAbsolute as cPe,resolve as uPe}from"node:path";import{homedir as Kee}from"node:os";import{join as Jee,resolve as M3}from"node:path";var SS="127.0.0.1";var Xee="https://hunsu.app/studio",n1={bridgeApi:{name:"bridgeApi",defaultHost:SS,hostEnv:["HUNSU_BRIDGE_HOST","HOST"],defaultPort:19687,portEnv:["HUNSU_BRIDGE_PORT","PORT"],reserved:!1,allowPortZero:!0},studioWeb:{name:"studioWeb",defaultHost:SS,hostEnv:["HUNSU_WEB_HOST"],defaultPort:19688,portEnv:["HUNSU_WEB_PORT"],reserved:!1,allowPortZero:!1},agentPreview:{name:"agentPreview",defaultHost:SS,hostEnv:["HUNSU_AGENT_PREVIEW_HOST"],defaultPort:19673,portEnv:["HUNSU_AGENT_PREVIEW_PORT"],reserved:!0,allowPortZero:!1}};var Yee=["read-only","workspace-write","danger-full-access"],Qee=["never","on-request","on-failure","untrusted"],Zee=["user","auto_review"],ete=["deterministic"];function Sn(t){return{ok:!0,value:t}}function Ta(t){return{ok:!1,error:t}}function Da(t,e){return t.ok?Sn(e(t.value)):t}function jo(t,e){return t.ok?e(t.value):t}function Yf(t){if(t.ok)return t.value;throw new Error(t.error.message)}function tte(t,e={}){let r=i1(n1.bridgeApi,t,e.overrides?.bridgeApi);if(!r.ok)return r;let n=i1(n1.studioWeb,t,e.overrides?.studioWeb);if(!n.ok)return n;let i=i1(n1.agentPreview,t,e.overrides?.agentPreview);return i.ok?Sn({bridgeApi:r.value,studioWeb:n.value,agentPreview:i.value}):i}function rte(t,e){return jo(tte(t,e),r=>ite(r,e.activePortNames))}function L3(t){return Da(ote(t,"HUNSU_WEB_URL",Xee),e=>({webUrl:e}))}function Ar(){return process.env}function nte(t){return Da(rte(t,{activePortNames:["bridgeApi"]}),e=>({bridgeApi:e.bridgeApi}))}function wS(t,e={}){let r=U3(e.processEnv??t);return jo(nte(t),({bridgeApi:n})=>jo(fte(e.roadmapRegistryPath,t,"HUNSU_ROADMAP_REGISTRY_PATH",Jee(e.homeDir??Kee(),".config","hunsu","roadmaps.json"),e.cwd),i=>jo(s1(e.routeWorktreeRoot,t,"HUNSU_ROUTE_WORKTREE_ROOT",void 0,e.cwd),o=>jo(s1(e.actionWorktreeRoot,t,"HUNSU_ACTION_WORKTREE_ROOT",void 0,e.cwd),s=>jo(bS(t,"HUNSU_BRIDGE_TEST_RUNNER",ete),a=>jo(Zh(t,e.codexAppServer),c=>Da(ste(t,e.codexThreadOptions),u=>({bridgeApi:n,processEnv:r,roadmapRegistryPath:i,routeWorktreeRoot:o,actionWorktreeRoot:s,testRunner:a,codexAppServer:c,codexThreadOptions:u}))))))))}function ite(t,e){for(let r=0;r<e.length;r+=1){let n=t[e[r]];if(n.port!==0)for(let i=r+1;i<e.length;i+=1){let o=t[e[i]];if(!(o.port!==n.port||o.port===0)&&gte(n.host,o.host))return Ta({code:"port_conflict",message:`Hunsu port conflict: ${n.name} and ${o.name} both use ${n.host}:${n.port}.`,port:n.port})}}return Sn(t)}function IS(t){return`http://${t.host}:${t.port}`}function ote(t,e,r){let n=t[e];return lte(n===void 0||n.trim()===""?r:n,e)}function Zh(t,e={}){let r=e.command??a1(t,["HUNSU_CODEX_APP_SERVER_COMMAND"])?.value??"codex";return r.trim()===""?Ta({code:"missing_required_env",env:"HUNSU_CODEX_APP_SERVER_COMMAND",message:"Invalid HUNSU_CODEX_APP_SERVER_COMMAND: expected a non-empty command."}):Da(pte(t,e.args),n=>({command:r,args:n,environment:U3(e.environment??t)}))}function ste(t,e={}){return jo(bS(t,"HUNSU_CODEX_SANDBOX_MODE",Yee),r=>jo(bS(t,"HUNSU_CODEX_APPROVAL_POLICY",Qee),n=>jo(bS(t,"HUNSU_CODEX_APPROVALS_REVIEWER",Zee),i=>jo(ute(t,"HUNSU_CODEX_NETWORK_ACCESS"),o=>Da(hte(t,"HUNSU_CODEX_ADDITIONAL_DIRECTORIES"),s=>({...r===void 0?{}:{sandboxMode:r},...n===void 0?{}:{approvalPolicy:n},...i===void 0?{}:{approvalsReviewer:i},...o===void 0?{}:{networkAccessEnabled:o},...s.length===0?{}:{additionalDirectories:s},...e}))))))}function i1(t,e,r){let n=r?.host!==void 0?{value:r.host,source:"override",env:void 0}:a1(e,t.hostEnv)??{value:t.defaultHost,source:"default",env:void 0},i=r?.port!==void 0?Da(H3(r.port,t,void 0),o=>({value:o,source:"override",env:void 0})):ate(e,t);return Da(i,o=>({name:t.name,host:n.value,hostSource:n.source,hostEnv:n.env,port:o.value,portSource:o.source,portEnv:o.env,reserved:t.reserved}))}function ate(t,e){let r=a1(t,e.portEnv);return r?Da(H3(r.value,e,r.env),n=>({value:n,source:"env",env:r.env})):Sn({value:e.defaultPort,source:"default"})}function H3(t,e,r){let n=typeof t=="number"?t:Number(t),i=e.allowPortZero?0:1;return!Number.isInteger(n)||n<i||n>65535?Ta({code:"invalid_port",env:r,portName:e.name,message:r?`Invalid ${r}: ${t}. Expected an integer port from ${i} to 65535.`:`Invalid ${e.name} port: ${t}. Expected an integer port from ${i} to 65535.`}):Sn(n)}function cte(t,e){return/^(1|true|yes|on)$/i.test(e)?Sn(!0):/^(0|false|no|off)$/i.test(e)?Sn(!1):Ta({code:"invalid_boolean",env:t,message:`Invalid ${t}: ${e}. Expected true, false, 1, 0, yes, no, on, or off.`})}function ute(t,e){let r=t[e];return r===void 0||r.trim()===""?Sn(void 0):cte(e,r)}function dte(t,e,r){return r.includes(e)?Sn(e):Ta({code:"invalid_enum",env:t,value:e,allowed:r,message:`Invalid ${t}: ${e}. Expected one of: ${r.join(", ")}.`})}function bS(t,e,r){let n=t[e];return n===void 0||n.trim()===""?Sn(void 0):dte(e,n,r)}function lte(t,e){try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error("Unsupported protocol");return Sn(r.toString().replace(/\/$/,""))}catch{return Ta({code:"invalid_url",env:e,value:t,message:e?`Invalid ${e}: ${t}. Expected an http or https URL.`:`Invalid URL: ${t}. Expected an http or https URL.`})}}function s1(t,e,r,n,i){if(t!==void 0)return o1(t,void 0,i);let o=e[r];return o!==void 0&&o.trim()!==""?o1(o,r,i):n===void 0?Sn(void 0):o1(n,void 0,i)}function fte(t,e,r,n,i){return Da(s1(t,e,r,n,i),o=>o??M3(i??".",n))}function o1(t,e,r="."){return t.trim()===""||t.includes("\0")?Ta({code:"invalid_path",env:e,path:t,message:e?`Invalid ${e}: expected a non-empty filesystem path.`:"Invalid filesystem path: expected a non-empty path."}):Sn(M3(r,t))}function pte(t,e){if(e!==void 0)return Sn([...e]);let r=t.HUNSU_CODEX_APP_SERVER_ARGS;return r===void 0||r.trim()===""?Sn(["app-server","--stdio"]):r.trim().startsWith("[")?mte("HUNSU_CODEX_APP_SERVER_ARGS",r):Sn(r.split(/\s+/).filter(Boolean))}function mte(t,e){try{let r=JSON.parse(e);if(Array.isArray(r)&&r.every(n=>typeof n=="string"))return Sn(r)}catch{return Ta({code:"invalid_json",env:t,value:e,message:`Invalid ${t}: expected a JSON string array.`})}return Ta({code:"invalid_json",env:t,value:e,message:`Invalid ${t}: expected a JSON string array.`})}function hte(t,e){let r=t[e];return Sn(r===void 0||r.trim()===""?[]:r.split(",").map(n=>n.trim()).filter(Boolean))}function U3(t){let e={};for(let[r,n]of Object.entries(t))n!==void 0&&(e[r]=n);return e}function a1(t,e){for(let r of e){let n=t[r];if(n!==void 0&&n.trim()!=="")return{value:n,source:"env",env:r}}}function gte(t,e){let r=N3(t),n=N3(e);return r===n||O3(r)||O3(n)}function N3(t){let e=t.trim().toLowerCase();return e==="localhost"?SS:e}function O3(t){return t==="0.0.0.0"||t==="::"||t==="[::]"}function S(t){return{ok:!0,value:t}}function oe(t){return{ok:!1,error:t}}function Ee(t,e="text"){return typeof t!="string"||t.trim()===""?Zf(e,`${e} must be a non-empty string`):S(t)}function ES(t){return ho(t,"title")}function kS(t){return ho(t,"goal")}function $3(t,e="title"){return ho(t,e)}function F3(t,e="acceptanceCriterion"){return ho(t,e)}function j3(t,e="constraint"){return ho(t,e)}function q3(t,e="notes"){return ho(t,e)}function qo(t,e="summary"){return ho(t,e)}function W3(t,e="evidence"){return ho(t,e)}function Wo(t,e="failureReason"){return ho(t,e)}function V3(t,e="risk"){return ho(t,e)}function Gd(t,e="commit"){return ho(t,e)}function un(t,e="teamName"){return ho(t,e)}function Ba(t,e="number"){return!Number.isInteger(t)||Number(t)<1?Zf(e,`${e} must be a positive integer`):S(t)}function G3(t,e="number"){return!Number.isInteger(t)||Number(t)<0?Zf(e,`${e} must be a non-negative integer`):S(t)}function po(t,e="array"){return t.length===0?Zf(e,`${e} must include at least one item`):S(t)}function Qf(t,e="array"){return t.length!==1?Zf(e,`${e} must include exactly one item`):S(t)}function Gi(t,e){let r=Ee(t,e);return r.ok?/\s/.test(r.value)?Zf(e,`${e} must not contain whitespace`):S(r.value):r}function zi(t){return Gi(t,"requestId")}function mo(t){return Gi(t,"destinationId")}function _n(t){return Gi(t,"moveId")}function Vo(t){return Gi(t,"hunsuId")}function eg(t){return Gi(t,"hunsuDraftId")}function lr(t){return Gi(t,"lineId")}function Zr(t){return Gi(t,"nodeId")}function z3(t){return Gi(t,"artifactId")}function K3(t){return Gi(t,"artifactActionId")}function iu(t){return Gi(t,"skillDraftId")}function tg(t){return Gi(t,"agentConversationHash")}function J3(t){return Gi(t,"executeId")}function zd(t){return Gi(t,"worktreeHash")}function Zf(t,e){return oe({type:"PrimitiveValidationError",field:t,message:e})}function ho(t,e){let r=Ee(t,e);return r.ok?S(r.value):r}var fr=class extends Error{constructor(e){super(e),this.name="DomainInvariantError"}};function ke(t){return oe({type:"DomainWorkflowError",message:t})}function rg(t){return{type:"DomainWorkflowError",message:t instanceof Error?t.message:String(t)}}function er(t){if(t.ok)return t.value;throw new fr(t.error.message)}function yte(t){return{kind:"direct",provider:{providerId:"codex",model:c1(t.model??"codex-default"),reasoningEffort:t.reasoningEffort??"default",serviceTier:t.serviceTier??"default",experimental:!0}}}function u1(t){let e=t.model??vte(t.modelSelection),r=t.reasoningEffort??xte(t.modelSelection),n=t.serviceTier??Ste(t.modelSelection);return{...t,model:e,reasoningEffort:r,serviceTier:n,modelSelection:t.modelSelection??yte({model:e,reasoningEffort:r,serviceTier:n})}}function X3(t){return t.kind==="direct"?t.provider:void 0}function vte(t){return t?.kind==="direct"?c1(t.provider.model):c1("codex-default")}function xte(t){return t?.kind==="direct"?t.provider.reasoningEffort??"default":"default"}function Ste(t){return t?.kind==="direct"?t.provider.serviceTier??"default":"default"}function c1(t){return er(Ee(t,"modelSelection.provider.model"))}var RS=["default","minimal","low","medium","high","xhigh"],AS=["default","fast"],Y3=["TEAM","DIRECTOR","SYSTEM"],Q3=["input","output","context","artifact","final_evidence"],Z3=["warn","block"],e4=["majority","unanimous","weighted","coordinator_decides"],t4=["pending","claimed","in_progress","reached","blocked","superseded","canceled"],r4=["initial-execute-team","initial-request","hunsu"],n4=["active","paused","complete","failed","abandoned"],i4=["arrived","accident"],o4=["draft","ready","confirmed","discarded"],s4=["draft","accepted","discarded"],a4=["transcript","command-output","test-log","screenshot","diff-summary","note"],c4=["host","check"],u4=["move","commit","move-or-commit"];var CS="hunsu-template-v1";function ep(t){return{engine:CS,template:t}}function Kd(t,e){if(typeof t!="object"||t===null||Array.isArray(t))return ke(`${e} must be an object`);let r=t,n=new Set(["engine","template"]),i=Object.keys(r).filter(o=>!n.has(o));return i.length>0?ke(`${e} has unsupported field: ${i[0]}`):"engine"in r?"template"in r?r.engine!==CS?ke(`${e}.engine must be ${CS}`):typeof r.template!="string"?ke(`${e}.template must be a string`):S({engine:CS,template:r.template}):ke(`${e}.template is required`):ke(`${e}.engine is required`)}function d4(t,e){let r=Kd(t,e);if(!r.ok)throw new fr(r.error.message)}function ng(t,e){return d4(t,"promptTemplate"),t.template.replace(/\{\{\s*([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[0-9]+\])*)\s*\}\}/g,(r,n)=>{let i=bte(e,n);if(i==null)throw new fr(`Prompt template value is unavailable: ${n}`);return l4(i)})}function bte(t,e){let r=e.match(/[A-Za-z_$][\w$]*|\[[0-9]+\]/g);if(!r||r.join("").replace(/\]\[/g,"][")==="")return;let n=t;for(let i of r){if(i.startsWith("[")){let o=Number(i.slice(1,-1));if(!Array.isArray(n))return;n=n[o];continue}if(typeof n!="object"||n===null)return;n=n[i]}return n}function l4(t){return typeof t=="string"?t:typeof t=="number"||typeof t=="boolean"?String(t):Array.isArray(t)?t.map(l4).join(`
139
+ `):typeof t=="object"&&t!==null?JSON.stringify(t):""}var _S="Create a closure-free ExecutionPlan using the available Members.",f4=["Discuss HUNSU changes conversationally and edit only decoded request files under .hunsu-request when a file-backed draft change is needed.","Help the user refine divergent Hunsu changes while preserving the current Execute result as the source of truth."].join(" "),l1={kind:"read_only",network:"disabled"},f1={policy:"never"},wte=["read_only","worktree_write","unrestricted"],Ite=["disabled","enabled"],Ete=["never","on_request"],kte=["user","auto_review"],Rte="root-team";function ig(t){return Cte(t)}function Jd(t,e="Harness"){let r=$r(t,e);if(!r.ok)return r;if(typeof r.value.rootTeamId!="string"||r.value.rootTeamId.trim()==="")return Ve(`${e}.rootTeamId must be a non-empty string`);if(!Array.isArray(r.value.executors))return Ve(`${e}.executors must be an array`);if(!Array.isArray(r.value.resources))return Ve(`${e}.resources must be an array`);let n=new Set;for(let[u,d]of r.value.executors.entries()){let l=jte(d,`${e}.executors[${u}]`);if(!l.ok)return l;let f=String(d.id);if(n.has(f))return Ve(`${e}.executors must not include duplicate Executor ${f}`);n.add(f)}if(!r.value.executors.find(u=>{let d=u;return d.id===r.value.rootTeamId&&d.kind==="team"}))return Ve(`${e}.rootTeamId must reference a Team Executor`);let o=new Map,s=new Map;for(let u of r.value.executors){let d=u,l=String(d.id),f=d.kind==="team"?"team":"member";o.set(l,f),f==="team"&&s.set(l,(d.members??[]).map(p=>String(p.executorId)))}for(let[u,d]of r.value.executors.entries()){let l=d;if(l.kind!=="team")continue;let f=l.members;for(let[p,g]of f.entries()){let v=String(g.executorId),b=o.get(v);if(!b)return Ve(`${e}.executors[${u}].members[${p}].executorId references unknown Executor ${g.executorId}`);if(g.visibleProfile.kind!==b)return Ve(`${e}.executors[${u}].members[${p}].visibleProfile.kind must match Executor ${v} kind ${b}`)}}let a=Ate(s);if(a)return Ve(`${e}.executors must not contain cyclic Team Memberships: ${a.join(" -> ")}`);for(let[u,d]of r.value.resources.entries()){let l=Jte(d,`${e}.resources[${u}]`);if(!l.ok)return l}let c=S1(r.value.guardrails,`${e}.guardrails`);return c.ok?Array.isArray(r.value.artifactActions)?S(go(r.value)):Ve(`${e}.artifactActions must be an array`):c}function Ate(t){let e=new Set,r=new Set,n=[],i=o=>{if(e.has(o)){let s=n.indexOf(o);return[...n.slice(s),o]}if(!r.has(o)){e.add(o),n.push(o);for(let s of t.get(o)??[]){if(!t.has(s))continue;let a=i(s);if(a)return a}n.pop(),e.delete(o),r.add(o)}};for(let o of t.keys()){let s=i(o);if(s)return s}}function p1(t,e="Member"){let r=$r(t,e);if(!r.ok)return r;let n=x4(r.value,e);return n.ok?S(OS(r.value)):n}function og(t,e="Manager"){let r=$r(t,e);if(!r.ok)return r;let n=Fte(r.value,e);return n.ok?S(Zte(r.value)):n}function Cte(t){let e=$r(t,"Harness");if(!e.ok)return e;let r=Hte(e.value);switch(r.kind){case"team_execution_plan":return PS({...r,kind:"team_execution_plan"},"team_execution_plan","maxAttemptCount");case"role_squad":return PS(r,"role_squad","maxRoundCount");case"council_vote":return Qte(Ei("council_vote.voteRule",r.voteRule,e4),()=>PS(r,"council_vote","maxRoundCount"));case"court_debate":return PS(r,"court_debate","maxRoundCount");default:return Ve(`Unsupported Harness kind: ${String(r.kind)}`)}}function m1(t){return t.kind==="team_execution_plan"}function TS(t){return m1(t)?S(t):oe({type:"DomainWorkflowError",message:`Harness ${t.kind} is not executable yet`})}function Vn(t="",e=[]){return{kind:"team_execution_plan",maxAttemptCount:er(Ba(5,"team_execution_plan.maxAttemptCount")),team:{promptTemplate:ep(t||_S)},members:[Ii("azir","Plan briefly, then implement the focused goal in this repository.",e),Ii("galio","Verify the completed work against the focused goal with concrete evidence.",[])]}}function Ii(t,e="",r=[],n=l1,i=f1,o=[]){return{id:er(Ee(t,"executorId")),promptTemplate:ep(e),skills:MS(r),plugins:HS(o),model:er(Ee("codex-default","member.model")),reasoningEffort:"default",serviceTier:"default",execution:sg(n),approval:ag(i)}}function tp(t="manager.hunsu.default",e=f4,r=[],n=[],i){return{id:er(Ee(t,"manager.id")),promptTemplate:ep(e),skills:MS(r),plugins:HS(n),...i?{modelSelection:JSON.parse(JSON.stringify(i))}:{}}}function ki(t){let e=JSON.parse(JSON.stringify(t));return{...e,guardrails:e.guardrails?.map(r=>({...r})),members:e.members.map(OS)}}function p4(t){let e=JSON.parse(JSON.stringify(t));return{...e,team:{promptTemplate:{...e.team.promptTemplate}},guardrails:e.guardrails?.map(r=>({...r}))}}function m4(t){let e=ki(t),{members:r,...n}=e;return p4(n)}function Bs(t,e=Rte){let r=Pte(e,"rootTeamId"),n=m4(t),i=t.members.map(OS),o=i.map(s=>({executorId:s.id,visibleProfile:Dte(s)}));return{rootTeamId:r,executors:[{kind:"team",id:r,planner:{promptTemplate:{...n.team.promptTemplate},maxAttemptCount:"maxAttemptCount"in n?n.maxAttemptCount:void 0,guardrails:n.guardrails?.map(s=>({...s}))},members:o},...i.map(Tte)],resources:Ote(i),guardrails:n.guardrails?.map(s=>({...s}))??[],artifactActions:[]}}function Xd(t,e=t.rootTeamId){let r=h4(t,e);if(!r)throw new fr(`Harness does not define Team ${e}`);let n=r.members.map(o=>Bte(t,o));return{kind:"team_execution_plan",maxAttemptCount:r.planner.maxAttemptCount??er(Ba(5,"team.maxAttemptCount")),guardrails:r.planner.guardrails?.map(o=>({...o})),team:{promptTemplate:{...r.planner.promptTemplate}},members:n}}function ou(t){return Xd(t,t.rootTeamId)}function go(t){return{rootTeamId:t.rootTeamId,executors:t.executors.map(g1),resources:t.resources.map(Lte),guardrails:t.guardrails.map(e=>({...e})),artifactActions:JSON.parse(JSON.stringify(t.artifactActions))}}function DS(t,e){let r=t.executors.find(n=>n.id===e);return r?g1(r):void 0}function h4(t,e){let r=t.executors.find(n=>n.id===e&&n.kind==="team");return r?g1(r):void 0}function h1(t,e){let r=t.executors.find(n=>n.id===e&&n.kind==="member");return r?y4(r):void 0}function BS(t){let e=u1(t.runtimePolicy);return{id:t.id,promptTemplate:{...t.promptTemplate},skills:t.resources.filter(r=>r.kind==="skill").map(r=>LS(r.skill)),plugins:t.resources.filter(r=>r.kind==="plugin").map(r=>({...r.plugin})),...t.runtimePolicy.modelSelection?{modelSelection:e.modelSelection}:{},model:e.model,reasoningEffort:e.reasoningEffort,serviceTier:e.serviceTier,execution:sg(e.execution),approval:ag(e.approval)}}function rp(t,e){return t.members.find(r=>r.id===e)?OS(t.members.find(r=>r.id===e)):void 0}function Pte(t,e){return er(Ee(t,e))}function _te(t){return{...t.modelSelection?{modelSelection:t.modelSelection}:{},model:t.model,reasoningEffort:t.reasoningEffort,serviceTier:t.serviceTier,execution:sg(t.execution),approval:ag(t.approval)}}function g4(t){return[...t.skills.map(e=>({kind:"skill",skill:LS(e)})),...(t.plugins??[]).map(e=>({kind:"plugin",plugin:{...e}}))]}function Tte(t){return{kind:"member",id:t.id,promptTemplate:{...t.promptTemplate},resources:g4(t),runtimePolicy:_te(t)}}function Dte(t){return{kind:"member",label:t.id,summary:er(Ee(t.promptTemplate.template||`Member ${t.id}`,"visibleProfile.summary")),capabilities:t.skills.map(e=>e.name)}}function Bte(t,e){let r=t.executors.find(n=>n.id===e.executorId);if(!r)throw new fr(`Team Membership references unknown Executor ${e.executorId}`);return r.kind==="member"?BS(r):Ii(r.id,Nte(e.visibleProfile),[],l1,f1,[])}function Nte(t){let e=t.capabilities?.length?`
140
+ Capabilities:
141
+ ${t.capabilities.map(r=>`- ${r}`).join(`
142
+ `)}`:"";return[t.kind==="team"?"Composite Team Executor.":"Member Executor.",t.label?`Label: ${t.label}`:void 0,t.summary?`Summary: ${t.summary}`:void 0,e||void 0].filter(Boolean).join(`
143
+ `)}function Ote(t){let e=[],r=new Set;for(let n of t)for(let i of g4(n)){let o=Mte(n.id,i);r.has(o)||(r.add(o),e.push({id:o,binding:i}))}return e}function Mte(t,e){return e.kind==="skill"?`resource.${t}.skill.${e.skill.name}`:e.kind==="plugin"?`resource.${t}.plugin.${e.plugin.id}`:`resource.${t}.package.${e.lock.kind}.${e.lock.key}.${e.lock.version}`}function g1(t){return t.kind==="member"?{...y4(t),packageLock:t.packageLock?{...t.packageLock}:void 0}:{...t,planner:{promptTemplate:{...t.planner.promptTemplate},maxAttemptCount:t.planner.maxAttemptCount,guardrails:t.planner.guardrails?.map(e=>({...e}))},members:t.members.map(e=>({executorId:e.executorId,visibleProfile:{...e.visibleProfile,capabilities:e.visibleProfile.capabilities?[...e.visibleProfile.capabilities]:void 0}})),packageLock:t.packageLock?{...t.packageLock}:void 0}}function y4(t){let e=u1(t.runtimePolicy);return{kind:"member",id:t.id,promptTemplate:{...t.promptTemplate},resources:t.resources.map(v4),runtimePolicy:{...t.runtimePolicy.modelSelection?{modelSelection:e.modelSelection}:{},model:e.model,reasoningEffort:e.reasoningEffort,serviceTier:e.serviceTier,execution:sg(e.execution),approval:ag(e.approval)}}}function v4(t){return t.kind==="skill"?{kind:"skill",skill:LS(t.skill)}:t.kind==="plugin"?{kind:"plugin",plugin:{...t.plugin}}:{kind:"package",lock:{...t.lock}}}function Lte(t){return{id:t.id,binding:v4(t.binding),packageLock:t.packageLock?{...t.packageLock}:void 0}}function PS(t,e,r){for(let n of[I4(t[r],`${e}.${r}`),S1(t.guardrails,`${e}.guardrails`),Ute(t.team,`${e}.team`),$te(t.members,`${e}.members`,!0)])if(!n.ok)return n;return S(ki(t))}function Hte(t){return t.kind==="team_execution_plan"?{...t,kind:"team_execution_plan"}:t}function y1(t,e){let r=$r(t,e);if(!r.ok)return r;if(r.value.kind!=="local-snapshot"&&r.value.kind!=="local-root-installed"&&r.value.kind!=="registry-package"&&r.value.kind!=="skillMeta")return Ve(`${e}.kind must be local-snapshot, local-root-installed, registry-package, or skillMeta`);if(typeof r.value.name!="string"||r.value.name.trim()==="")return Ve(`${e}.name must be a non-empty string`);if(r.value.kind==="skillMeta"){let n=Xte(r.value,["agent","kind","name","source"],e);return n.ok?typeof r.value.source!="string"||r.value.source.trim()===""?Ve(`${e}.source must be a non-empty string`):r.value.agent!=="codex"?Ve(`${e}.agent must be codex`):S(void 0):n}if(r.value.kind==="local-root-installed")return r.value.sourcePath!==void 0&&(typeof r.value.sourcePath!="string"||r.value.sourcePath.trim()==="")?Ve(`${e}.sourcePath must be a non-empty string when provided`):S(void 0);if(r.value.kind==="local-snapshot"){for(let n of["sourcePath","contentHash","snapshotRef"])if(typeof r.value[n]!="string"||r.value[n].trim()==="")return Ve(`${e}.${n} must be a non-empty string`);if(r.value.snapshotFiles!==void 0){if(!Array.isArray(r.value.snapshotFiles))return Ve(`${e}.snapshotFiles must be an array`);for(let[n,i]of r.value.snapshotFiles.entries()){let o=$r(i,`${e}.snapshotFiles[${n}]`);if(!o.ok)return o;if(typeof o.value.path!="string"||o.value.path.trim()==="")return Ve(`${e}.snapshotFiles[${n}].path must be a non-empty string`);if(typeof o.value.text!="string")return Ve(`${e}.snapshotFiles[${n}].text must be a string`)}}return S(void 0)}if(r.value.registryKind!=="apm")return Ve(`${e}.registryKind must be apm`);for(let n of["registry","package","version","integrity","contentHash"])if(typeof r.value[n]!="string"||r.value[n].trim()==="")return Ve(`${e}.${n} must be a non-empty string`);return ere(String(r.value.version))?r.value.snapshotFiles!==void 0?Ve(`${e}.snapshotFiles is not supported for registry-package skills`):S(void 0):Ve(`${e}.version must be an exact semver version`)}function v1(t,e){let r=$r(t,e);return r.ok?r.value.kind!=="local-root-installed"?Ve(`${e}.kind must be local-root-installed`):typeof r.value.id!="string"||r.value.id.trim()===""?Ve(`${e}.id must be a non-empty string`):S(void 0):r}function Ute(t,e){let r=$r(t,e);if(!r.ok)return r;let n=Kd(r.value.promptTemplate,`${e}.promptTemplate`);return n.ok?S(void 0):n}function $te(t,e,r){if(!Array.isArray(t))return Ve(`${e} must be an array`);if(r&&t.length===0)return Ve(`${e} must include at least one Member`);let n=new Set;for(let[i,o]of t.entries()){let s=$r(o,`${e}[${i}]`);if(!s.ok)return s;let a=x4(s.value,`${e}[${i}]`);if(!a.ok)return a;let c=String(s.value.id);if(n.has(c))return Ve(`${e} must not include duplicate Member ${c}`);n.add(c)}return S(void 0)}function x4(t,e){if(typeof t.id!="string"||t.id.trim()==="")return Ve(`${e}.id must be a non-empty string`);let r=Kd(t.promptTemplate,`${e}.promptTemplate`);if(!r.ok)return r;if(typeof t.model!="string"||t.model.trim()==="")return Ve(`${e}.model must be a non-empty string`);for(let n of[x1(t.modelSelection,`${e}.modelSelection`,!0),Ei(`${e}.reasoningEffort`,t.reasoningEffort,RS),t.serviceTier===void 0?S(void 0):Ei(`${e}.serviceTier`,t.serviceTier,AS),b4(t.execution,`${e}.execution`),w4(t.approval,`${e}.approval`)])if(!n.ok)return n;if(!Array.isArray(t.skills))return Ve(`${e}.skills must be an array`);for(let[n,i]of t.skills.entries()){let o=y1(i,`${e}.skills[${n}]`);if(!o.ok)return o}if(t.plugins!==void 0){if(!Array.isArray(t.plugins))return Ve(`${e}.plugins must be an array`);for(let[n,i]of t.plugins.entries()){let o=v1(i,`${e}.plugins[${n}]`);if(!o.ok)return o}}return S(void 0)}function Fte(t,e){let r=Yte(t,["id","plugins","promptTemplate","skills"],["modelSelection"],e);if(!r.ok)return r;if(typeof t.id!="string"||t.id.trim()==="")return Ve(`${e}.id must be a non-empty string`);let n=Kd(t.promptTemplate,`${e}.promptTemplate`);if(!n.ok)return n;let i=x1(t.modelSelection,`${e}.modelSelection`,!0);if(!i.ok)return i;if(!Array.isArray(t.skills))return Ve(`${e}.skills must be an array`);for(let[o,s]of t.skills.entries()){let a=y1(s,`${e}.skills[${o}]`);if(!a.ok)return a}if(!Array.isArray(t.plugins))return Ve(`${e}.plugins must be an array`);for(let[o,s]of t.plugins.entries()){let a=v1(s,`${e}.plugins[${o}]`);if(!a.ok)return a}return S(void 0)}function jte(t,e){let r=$r(t,e);return r.ok?r.value.kind==="team"?qte(r.value,e):r.value.kind==="member"?zte(r.value,e):Ve(`${e}.kind must be team or member`):r}function qte(t,e){if(typeof t.id!="string"||t.id.trim()==="")return Ve(`${e}.id must be a non-empty string`);let r=Wte(t.planner,`${e}.planner`);if(!r.ok)return r;if(!Array.isArray(t.members))return Ve(`${e}.members must be an array`);let n=new Set;for(let[i,o]of t.members.entries()){let s=Vte(o,`${e}.members[${i}]`);if(!s.ok)return s;let a=String(o.executorId);if(n.has(a))return Ve(`${e}.members must not include duplicate Membership ${a}`);n.add(a)}return NS(t.packageLock,`${e}.packageLock`)}function Wte(t,e){let r=$r(t,e);if(!r.ok)return r;let n=Kd(r.value.promptTemplate,`${e}.promptTemplate`);if(!n.ok)return n;if(r.value.maxAttemptCount!==void 0){let i=I4(r.value.maxAttemptCount,`${e}.maxAttemptCount`);if(!i.ok)return i}return S1(r.value.guardrails,`${e}.guardrails`)}function Vte(t,e){let r=$r(t,e);return r.ok?typeof r.value.executorId!="string"||r.value.executorId.trim()===""?Ve(`${e}.executorId must be a non-empty string`):Gte(r.value.visibleProfile,`${e}.visibleProfile`):r}function Gte(t,e){let r=$r(t,e);if(!r.ok)return r;let n=Ei(`${e}.kind`,r.value.kind,["team","member"]);if(!n.ok)return n;for(let i of["label","summary"])if(r.value[i]!==void 0&&(typeof r.value[i]!="string"||String(r.value[i]).trim()===""))return Ve(`${e}.${i} must be a non-empty string when provided`);if(r.value.capabilities!==void 0){if(!Array.isArray(r.value.capabilities))return Ve(`${e}.capabilities must be an array`);for(let[i,o]of r.value.capabilities.entries())if(typeof o!="string"||o.trim()==="")return Ve(`${e}.capabilities[${i}] must be a non-empty string`)}return S(void 0)}function zte(t,e){if(typeof t.id!="string"||t.id.trim()==="")return Ve(`${e}.id must be a non-empty string`);let r=Kd(t.promptTemplate,`${e}.promptTemplate`);if(!r.ok)return r;if(!Array.isArray(t.resources))return Ve(`${e}.resources must be an array`);for(let[i,o]of t.resources.entries()){let s=S4(o,`${e}.resources[${i}]`);if(!s.ok)return s}let n=Kte(t.runtimePolicy,`${e}.runtimePolicy`);return n.ok?NS(t.packageLock,`${e}.packageLock`):n}function Kte(t,e){let r=$r(t,e);if(!r.ok)return r;let n=x1(r.value.modelSelection,`${e}.modelSelection`,!0);if(!n.ok)return n;let i=r.value.modelSelection!==void 0;if(r.value.model!==void 0&&(typeof r.value.model!="string"||r.value.model.trim()===""))return Ve(`${e}.model must be a non-empty string when provided`);if(r.value.model===void 0&&!i)return Ve(`${e}.modelSelection or ${e}.model must be provided`);for(let o of[r.value.reasoningEffort===void 0&&i?S(void 0):Ei(`${e}.reasoningEffort`,r.value.reasoningEffort,RS),r.value.serviceTier===void 0?S(void 0):Ei(`${e}.serviceTier`,r.value.serviceTier,AS),b4(r.value.execution,`${e}.execution`),w4(r.value.approval,`${e}.approval`)])if(!o.ok)return o;return S(void 0)}function x1(t,e,r=!1){if(t===void 0&&r)return S(void 0);let n=$r(t,e);if(!n.ok)return n;if(n.value.kind==="alias")return d1(n.value.aliasId,`${e}.aliasId`);if(n.value.kind!=="direct")return Ve(`${e}.kind must be direct or alias`);let i=$r(n.value.provider,`${e}.provider`);if(!i.ok)return i;for(let o of[d1(i.value.providerId,`${e}.provider.providerId`),d1(i.value.model,`${e}.provider.model`),i.value.reasoningEffort===void 0?S(void 0):Ei(`${e}.provider.reasoningEffort`,i.value.reasoningEffort,RS),i.value.serviceTier===void 0?S(void 0):Ei(`${e}.provider.serviceTier`,i.value.serviceTier,AS)])if(!o.ok)return o;if(i.value.experimental!==void 0&&typeof i.value.experimental!="boolean")return Ve(`${e}.provider.experimental must be a boolean when provided`);if(i.value.providerId==="codex"&&i.value.experimental!==!0){if(i.value.model==="gpt-5.5-thinking"&&i.value.reasoningEffort!=="high"&&i.value.reasoningEffort!=="xhigh")return Ve(`${e}.provider.reasoningEffort must be high or xhigh for gpt-5.5-thinking`);if(i.value.model==="gpt-5.5"&&(i.value.reasoningEffort==="minimal"||i.value.reasoningEffort==="xhigh"))return Ve(`${e}.provider.reasoningEffort is not supported for gpt-5.5`)}return S(void 0)}function d1(t,e){return typeof t=="string"&&t.trim()!==""?S(void 0):Ve(`${e} must be a non-empty string`)}function Jte(t,e){let r=$r(t,e);if(!r.ok)return r;if(typeof r.value.id!="string"||r.value.id.trim()==="")return Ve(`${e}.id must be a non-empty string`);let n=S4(r.value.binding,`${e}.binding`);return n.ok?NS(r.value.packageLock,`${e}.packageLock`):n}function S4(t,e){let r=$r(t,e);return r.ok?r.value.kind==="skill"?y1(r.value.skill,`${e}.skill`):r.value.kind==="plugin"?v1(r.value.plugin,`${e}.plugin`):r.value.kind==="package"?NS(r.value.lock,`${e}.lock`):Ve(`${e}.kind must be skill, plugin, or package`):r}function NS(t,e){if(t===void 0)return S(void 0);let r=$r(t,e);if(!r.ok)return r;for(let n of["origin","kind","key","version","integrity"])if(typeof r.value[n]!="string"||String(r.value[n]).trim()==="")return Ve(`${e}.${n} must be a non-empty string`);return S(void 0)}function b4(t,e){let r=$r(t,e);if(!r.ok)return r;let n=Ei(`${e}.kind`,r.value.kind,wte);if(!n.ok)return n;let i=Ei(`${e}.network`,r.value.network,Ite);return i.ok?S(void 0):i}function w4(t,e){let r=$r(t,e);if(!r.ok)return r;let n=Ei(`${e}.policy`,r.value.policy,Ete);if(!n.ok)return n;if(r.value.policy==="on_request"){let i=Ei(`${e}.reviewer`,r.value.reviewer,kte);return i.ok?S(void 0):i}return"reviewer"in r.value?Ve(`${e}.reviewer is only allowed when policy is on_request`):S(void 0)}function S1(t,e){if(t===void 0)return S(void 0);if(!Array.isArray(t))return Ve(`${e} must be an array`);for(let[r,n]of t.entries()){let i=$r(n,`${e}[${r}]`);if(!i.ok)return i;if(typeof i.value.name!="string"||i.value.name.trim()==="")return Ve(`${e}[${r}].name must be a non-empty string`);let o=Ei(`${e}[${r}].scope`,i.value.scope,Q3);if(!o.ok)return o;if(typeof i.value.rule!="string"||i.value.rule.trim()==="")return Ve(`${e}[${r}].rule must be a non-empty string`);let s=Ei(`${e}[${r}].severity`,i.value.severity,Z3);if(!s.ok)return s}return S(void 0)}function $r(t,e){return t&&typeof t=="object"&&!Array.isArray(t)?S(t):Ve(`${e} must be an object`)}function Xte(t,e,r){let n=e.filter(o=>!(o in t));if(n.length>0)return Ve(`${r} is missing required keys: ${n.join(", ")}`);let i=Object.keys(t).filter(o=>!e.includes(o));return i.length>0?Ve(`${r} has unsupported keys: ${i.join(", ")}`):S(void 0)}function Yte(t,e,r,n){let i=e.filter(a=>!(a in t));if(i.length>0)return Ve(`${n} is missing required keys: ${i.join(", ")}`);let o=[...e,...r],s=Object.keys(t).filter(a=>!o.includes(a));return s.length>0?Ve(`${n} has unsupported keys: ${s.join(", ")}`):S(void 0)}function I4(t,e){return Number.isInteger(t)&&Number(t)>=1?S(void 0):Ve(`${e} must be a positive integer`)}function Ei(t,e,r){return typeof e=="string"&&r.includes(e)?S(e):Ve(`${t} must be one of: ${r.join(", ")}`)}function Qte(t,e){return t.ok?e():t}function Ve(t){return oe({type:"DomainWorkflowError",message:t})}function OS(t){let e={...t,promptTemplate:{...t.promptTemplate},skills:MS(t.skills),plugins:HS(t.plugins??[]),execution:sg(t.execution),approval:ag(t.approval)};return t.modelSelection&&(e.modelSelection=JSON.parse(JSON.stringify(t.modelSelection))),e}function Zte(t){let e={...t,promptTemplate:{...t.promptTemplate},skills:MS(t.skills),plugins:HS(t.plugins)};return t.modelSelection&&(e.modelSelection=JSON.parse(JSON.stringify(t.modelSelection))),e}function sg(t){return{...t}}function ag(t){return{...t}}function MS(t=[]){return t.map(LS)}function LS(t){return t.kind==="local-snapshot"?{...t,snapshotFiles:t.snapshotFiles?.map(e=>({...e}))}:{...t}}function HS(t=[]){return t.map(e=>({...e}))}function ere(t){return/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(t)}function E4(t,e,r,n){let i=r==="initial-execute-team"||r==="initial-request"?"SYSTEM":"DIRECTOR";return{...e,requestId:t,status:"pending",source:r,createdBy:i,updatedBy:i,createdAt:n,updatedAt:n}}function cg(t,e){return FS(e.claimedBy)?t.status!=="pending"&&t.status!=="blocked"?Kr(`Destination ${t.id} cannot be claimed from status ${t.status}`):S({...$S(t,e),status:"claimed",claimedBy:e.claimedBy}):Kr("Claim Destination requires claimedBy")}function ug(t,e){return FS(e.claimedBy)?t.status==="blocked"?Kr(`Destination ${t.id} cannot start work from status blocked`):R1(t)?Kr(`Destination ${t.id} cannot start work from status ${t.status}`):S({...$S(t,e),status:"in_progress",claimedBy:e.claimedBy}):Kr("Start Destination work requires claimedBy")}function dg(t,e){return FS(e.blockedReason)?R1(t)?Kr(`Destination ${t.id} cannot be blocked from status ${t.status}`):S({...$S(t,e),status:"blocked",claimedBy:"claimedBy"in t?t.claimedBy:void 0,blockedReason:e.blockedReason}):Kr("Block Destination requires blockedReason")}function lg(t,e){return FS(e.reachedByMoveId)?R1(t)?Kr(`Destination ${t.id} cannot be reached from status ${t.status}`):S({...$S(t,e),status:"reached",claimedBy:"claimedBy"in t?t.claimedBy:void 0,reachedByMoveId:e.reachedByMoveId}):Kr("Reach Destination requires reachedByMoveId")}function fg(t){return t.status==="active"?S({...t,status:"paused"}):Kr(`Line ${t.id} cannot be paused from status ${t.status}`)}function pg(t){return t.status==="paused"?S({...t,status:"active"}):Kr(`Line ${t.id} cannot be resumed from status ${t.status}`)}function mg(t){return t.status==="active"||t.status==="paused"?S({...t,status:"complete"}):Kr(`Line ${t.id} cannot be completed from status ${t.status}`)}function hg(t){return t.status==="active"||t.status==="paused"?S({...t,status:"abandoned"}):Kr(`Line ${t.id} cannot be abandoned from status ${t.status}`)}function k4(t){return t.status==="active"?S({...t,status:"failed"}):Kr(`Line ${t.id} cannot fail from status ${t.status}`)}function R4(t){return t.status==="active"?S(t):Kr(`TEAM line ${t.id} cannot continue from status ${t.status}`)}function b1(t){let e=Qf(t.reachedDestinationIds,"reachedDestinationIds");if(!e.ok)return Kr("Arrived MOVE must reach exactly one Destination");let r=po(t.evidence,"evidence");return r.ok?S({...t,outcome:"arrived",reachedDestinationIds:e.value,evidence:r.value}):Kr("Arrived MOVE requires evidence")}function w1(t){let e=Wo(t.failureReason,"failureReason");if(!e.ok)return Kr("Accident MOVE requires failureReason");let r=po(t.evidence,"evidence");return r.ok?S({...t,outcome:"accident",reachedDestinationIds:[],failureReason:e.value,evidence:r.value}):Kr("Accident MOVE requires evidence")}function I1(t,e){return t.outcome==="accident"?{...t,...e,outcome:"accident",reachedDestinationIds:[],failureReason:t.failureReason}:{...t,...e,outcome:"arrived",reachedDestinationIds:t.reachedDestinationIds}}function US(t){return t.outcome==="accident"?w1(t):b1({...t,reachedDestinationIds:t.reachedDestinationIds})}function A4(t){return{...t,status:"draft"}}function E1(t,e){return t.status!=="draft"?Kr(`Skill Draft ${t.id} cannot be accepted from status ${t.status}`):S({...t,status:"accepted",acceptedSnapshot:e})}function k1(t){return t.status!=="draft"?Kr(`Skill Draft ${t.id} cannot be discarded from status ${t.status}`):S({...t,status:"discarded"})}function $S(t,e){let{claimedBy:r,reachedByMoveId:n,blockedReason:i,canceledReason:o,supersededByDestinationId:s,...a}=t;return{...a,updatedBy:e.updatedBy,updatedAt:e.updatedAt}}function R1(t){return t.status==="reached"||t.status==="canceled"||t.status==="superseded"}function FS(t){return typeof t=="string"&&t.trim()!==""}function Kr(t){return oe({type:"DomainModelError",message:t})}function Gt(t,e){return t&&typeof t=="object"&&!Array.isArray(t)?S(t):ke(`${e} must be an object`)}function si(t,e){return Array.isArray(t)?S(t):ke(`${e} must be an array`)}function dn(t,e,r){return typeof e=="string"&&r.includes(e)?S(e):ke(`${t} must be one of: ${r.join(", ")}`)}function A1(t,e){return dn(e,t,Y3)}function tre(t,e){return dn(e,t,r4)}function rre(t,e){return typeof t=="number"&&Number.isFinite(t)?S(t):ke(`${e} must be a finite number`)}function _4(t,e){return t===void 0?S(void 0):typeof t=="boolean"?S(t):ke(`${e} must be a boolean`)}function qS(t,e){return Number.isInteger(t)&&Number(t)>=0?S(Number(t)):ke(`${e} must be a non-negative integer`)}function Ns(t,e){return t===void 0?S(void 0):typeof t=="string"?S(t):ke(`${e} must be a string`)}function Fr(t,e){if(t===void 0)return S(void 0);let r=Ee(t,e);return r.ok?S(r.value):ke(r.error.message)}function C1(t,e){let r=Ee(t,e);return r.ok?S(r.value):ke(r.error.message)}function or(t,e="at"){return Ns(t,e)}function nre(t,e){if(t===void 0)return S(void 0);let r=si(t,e);if(!r.ok)return r;let n=[];for(let i=0;i<r.value.length;i+=1){let o=Q(Ee(r.value[i],`${e}[${i}]`));if(!o.ok)return o;n.push(o.value)}return S(n)}function ire(t,e){return t===void 0?S(void 0):rre(t,e)}function P1(t,e){let r=Gt(t,e);if(!r.ok)return r;let n=Q(zi(r.value.id));if(!n.ok)return n;let i=Q(ES(r.value.title));if(!i.ok)return i;let o=Q(kS(r.value.goal));if(!o.ok)return o;let s=A1(r.value.createdBy,`${e}.createdBy`);if(!s.ok)return s;let a=Ns(r.value.createdAt,`${e}.createdAt`);return a.ok?S({id:n.value,title:i.value,goal:o.value,createdBy:s.value,createdAt:a.value}):a}function WS(t,e){let r=Gt(t,e);if(!r.ok)return r;let n=Q(mo(r.value.id));if(!n.ok)return n;let i=Q($3(r.value.title,`${e}.title`));if(!i.ok)return i;let o=ore(r.value.acceptanceCriteria,`${e}.acceptanceCriteria`);if(!o.ok)return o;let s=sre(r.value.constraints,`${e}.constraints`);if(!s.ok)return s;let a=ire(r.value.priority,`${e}.priority`);if(!a.ok)return a;let c=r.value.notes===void 0?S(void 0):Q(q3(r.value.notes,`${e}.notes`));return c.ok?S({id:n.value,title:i.value,acceptanceCriteria:o.value,constraints:s.value,priority:a.value,notes:c.value}):c}function VS(t,e,r=!0){let n=si(t,e);if(!n.ok)return n;if(r){let s=Q(po(n.value,e));if(!s.ok)return s}let i=[];for(let s=0;s<n.value.length;s+=1){let a=WS(n.value[s],`${e}[${s}]`);if(!a.ok)return a;i.push(a.value)}let o=YS(i.map(s=>s.id),e,"DestinationId");return o.ok?S(i):o}function ore(t,e){if(t===void 0)return S(void 0);let r=si(t,e);if(!r.ok)return r;let n=[];for(let i=0;i<r.value.length;i+=1){let o=Q(F3(r.value[i],`${e}[${i}]`));if(!o.ok)return o;n.push(o.value)}return S(n)}function sre(t,e){if(t===void 0)return S(void 0);let r=si(t,e);if(!r.ok)return r;let n=[];for(let i=0;i<r.value.length;i+=1){let o=Q(j3(r.value[i],`${e}[${i}]`));if(!o.ok)return o;n.push(o.value)}return S(n)}function are(t,e){let r=Gt(t,e);if(!r.ok)return r;let n=WS(r.value,e);if(!n.ok)return n;let i=Q(zi(r.value.requestId));if(!i.ok)return i;let o=tre(r.value.source,`${e}.source`);if(!o.ok)return o;let s=A1(r.value.createdBy,`${e}.createdBy`);if(!s.ok)return s;let a=A1(r.value.updatedBy,`${e}.updatedBy`);if(!a.ok)return a;let c=dn(`${e}.status`,r.value.status,t4);if(!c.ok)return c;let u=Ns(r.value.createdAt,`${e}.createdAt`);if(!u.ok)return u;let d=Ns(r.value.updatedAt,`${e}.updatedAt`);if(!d.ok)return d;let l={...n.value,requestId:i.value,source:o.value,createdBy:s.value,updatedBy:a.value,createdAt:u.value,updatedAt:d.value};switch(c.value){case"pending":return Ere(r.value,e,["claimedBy","reachedByMoveId","blockedReason","canceledReason","supersededByDestinationId"],l);case"claimed":case"in_progress":{let f=Q(Ee(r.value.claimedBy,`${e}.claimedBy`));if(!f.ok)return f;let p=np(r.value,e,["reachedByMoveId","blockedReason","canceledReason","supersededByDestinationId"]);return p.ok?S({...l,status:c.value,claimedBy:f.value}):p}case"reached":{let f=Q(_n(r.value.reachedByMoveId));if(!f.ok)return f;let p=Fr(r.value.claimedBy,`${e}.claimedBy`);if(!p.ok)return p;let g=np(r.value,e,["blockedReason","canceledReason","supersededByDestinationId"]);return g.ok?S({...l,status:"reached",reachedByMoveId:f.value,claimedBy:p.value}):g}case"blocked":{let f=Q(Wo(r.value.blockedReason,`${e}.blockedReason`));if(!f.ok)return f;let p=Fr(r.value.claimedBy,`${e}.claimedBy`);if(!p.ok)return p;let g=np(r.value,e,["reachedByMoveId","canceledReason","supersededByDestinationId"]);return g.ok?S({...l,status:"blocked",blockedReason:f.value,claimedBy:p.value}):g}case"superseded":{let f=Q(mo(r.value.supersededByDestinationId));if(!f.ok)return f;let p=Fr(r.value.claimedBy,`${e}.claimedBy`);if(!p.ok)return p;let g=np(r.value,e,["reachedByMoveId","blockedReason","canceledReason"]);return g.ok?S({...l,status:"superseded",supersededByDestinationId:f.value,claimedBy:p.value}):g}case"canceled":{let f=Q(Wo(r.value.canceledReason,`${e}.canceledReason`));if(!f.ok)return f;let p=Fr(r.value.claimedBy,`${e}.claimedBy`);if(!p.ok)return p;let g=np(r.value,e,["reachedByMoveId","blockedReason","supersededByDestinationId"]);return g.ok?S({...l,status:"canceled",canceledReason:f.value,claimedBy:p.value}):g}}}function T4(t,e){let r=si(t,e);if(!r.ok)return r;let n=[];for(let i=0;i<r.value.length;i+=1){let o=are(r.value[i],`${e}[${i}]`);if(!o.ok)return o;n.push(o.value)}return S(n)}function jS(t,e,r){let n=si(t,e);if(!n.ok)return n;if(r){let s=Q(po(n.value,e));if(!s.ok)return s}let i=[];for(let s=0;s<n.value.length;s+=1){let a=Q(mo(n.value[s]));if(!a.ok)return a;i.push(a.value)}let o=YS(i,e,"DestinationId");return o.ok?S(i):o}function cre(t,e,r){let n=si(t,e);if(!n.ok)return n;if(r){let s=Q(po(n.value,e));if(!s.ok)return s}let i=[];for(let s=0;s<n.value.length;s+=1){let a=Q(_n(n.value[s]));if(!a.ok)return a;i.push(a.value)}let o=YS(i,e,"MoveId");return o.ok?S(i):o}function ure(t,e,r){let n=si(t,e);if(!n.ok)return n;if(r){let s=Q(po(n.value,e));if(!s.ok)return s}let i=[];for(let s=0;s<n.value.length;s+=1){let a=Q(Zr(n.value[s]));if(!a.ok)return a;i.push(a.value)}let o=YS(i,e,"NodeId");return o.ok?r?Q(po(i,e)):S(i):o}function GS(t,e,r){let n=si(t,e);if(!n.ok)return n;if(r){let o=Q(po(n.value,e));if(!o.ok)return o}let i=[];for(let o=0;o<n.value.length;o+=1){let s=Q(W3(n.value[o],`${e}[${o}]`));if(!s.ok)return s;i.push(s.value)}return S(i)}function zS(t,e){let r=si(t,e);if(!r.ok)return r;let n=[];for(let i=0;i<r.value.length;i+=1){let o=Q(V3(r.value[i],`${e}[${i}]`));if(!o.ok)return o;n.push(o.value)}return S(n)}function dre(t,e){return t===void 0?S(void 0):zS(t,e)}function D4(t,e){let r=Gt(t,e);if(!r.ok)return r;switch(r.value.type){case"destination":{let n=Q(mo(r.value.id));return n.ok?S({type:"destination",id:n.value}):n}case"move":{let n=Q(_n(r.value.id));return n.ok?S({type:"move",id:n.value}):n}case"line":{let n=Q(lr(r.value.id));return n.ok?S({type:"line",id:n.value}):n}case"node":{let n=Q(Zr(r.value.id));return n.ok?S({type:"node",id:n.value}):n}default:return ke(`${e}.type must be destination, move, line, or node`)}}function su(t,e){if(t===void 0)return S(void 0);let r=Gt(t,e);if(!r.ok)return r;let n=dn(`${e}.provider`,r.value.provider,["codex","local"]);if(!n.ok)return n;let i=Q(tg(r.value.conversationHash));if(!i.ok)return i;let o=Fr(r.value.threadId,`${e}.threadId`);if(!o.ok)return o;let s=Q(Ee(r.value.contextHash,`${e}.contextHash`));if(!s.ok)return s;let a=r.value.worktreeHash===void 0?S(void 0):Q(zd(r.value.worktreeHash));if(!a.ok)return a;let c=Q(Ee(r.value.startedAt,`${e}.startedAt`));if(!c.ok)return c;let u=Fr(r.value.endedAt,`${e}.endedAt`);if(!u.ok)return u;let d={conversationHash:i.value,contextHash:s.value,worktreeHash:a.value,startedAt:c.value};return n.value==="local"?o.value!==void 0?ke(`${e}.threadId is only valid for codex conversations`):u.value===void 0?S({provider:"local",...d}):S({provider:"local",...d,endedAt:u.value}):u.value===void 0?S({provider:"codex",...d,threadId:o.value}):S({provider:"codex",...d,threadId:o.value,endedAt:u.value})}function KS(t,e){if(t===void 0)return S(void 0);let r=Gt(t,e);if(!r.ok)return r;let n=Q(zd(r.value.worktreeHash));if(!n.ok)return n;let i=Q(Ee(r.value.path,`${e}.path`));if(!i.ok)return i;let o=Q(Ee(r.value.branch,`${e}.branch`));if(!o.ok)return o;let s=Q(Ee(r.value.baseRef,`${e}.baseRef`));if(!s.ok)return s;let a=Q(Ee(r.value.createdAt,`${e}.createdAt`));if(!a.ok)return a;let c=Fr(r.value.removedAt,`${e}.removedAt`);if(!c.ok)return c;let u={worktreeHash:n.value,path:i.value,branch:o.value,baseRef:s.value,createdAt:a.value};return c.value===void 0?S(u):S({...u,removedAt:c.value})}function _1(t,e){let r=Gt(t,e);if(!r.ok)return r;let n=dn(`${e}.kind`,r.value.kind,["local-snapshot","local-root-installed","registry-package","skillMeta"]);if(!n.ok)return n;let i=Q(Ee(r.value.name,`${e}.name`));if(!i.ok)return i;if(n.value==="skillMeta"){let l=Q(Ee(r.value.source,`${e}.source`));if(!l.ok)return l;let f=dn(`${e}.agent`,r.value.agent,["codex"]);return f.ok?S({kind:"skillMeta",name:i.value,source:l.value,agent:f.value}):f}if(n.value==="local-root-installed"){let l=Fr(r.value.sourcePath,`${e}.sourcePath`);return l.ok?S({kind:"local-root-installed",name:i.value,sourcePath:l.value}):l}if(n.value==="local-snapshot"){let l=Q(Ee(r.value.sourcePath,`${e}.sourcePath`));if(!l.ok)return l;let f=Q(Ee(r.value.contentHash,`${e}.contentHash`));if(!f.ok)return f;let p=Q(Ee(r.value.snapshotRef,`${e}.snapshotRef`));if(!p.ok)return p;let g=r.value.snapshotFiles===void 0?S(void 0):gre(r.value.snapshotFiles,`${e}.snapshotFiles`);return g.ok?S({kind:"local-snapshot",name:i.value,sourcePath:l.value,contentHash:f.value,snapshotRef:p.value,snapshotFiles:g.value}):g}let o=dn(`${e}.registryKind`,r.value.registryKind,["apm"]);if(!o.ok)return o;let s=Q(Ee(r.value.registry,`${e}.registry`));if(!s.ok)return s;let a=Q(Ee(r.value.package,`${e}.package`));if(!a.ok)return a;let c=Q(Ee(r.value.version,`${e}.version`));if(!c.ok)return c;if(!yre(String(c.value)))return ke(`${e}.version must be an exact semver version`);let u=Q(Ee(r.value.integrity,`${e}.integrity`));if(!u.ok)return u;let d=Q(Ee(r.value.contentHash,`${e}.contentHash`));return d.ok?r.value.snapshotFiles!==void 0?ke(`${e}.snapshotFiles is not supported for registry-package skills`):S({kind:"registry-package",registryKind:o.value,name:i.value,registry:s.value,package:a.value,version:c.value,integrity:u.value,contentHash:d.value}):d}function au(t,e,r){if(t===void 0)return S(void 0);let n=Gt(t,e);if(!n.ok)return n;let i=Q(Ee(n.value.origin,`${e}.origin`));if(!i.ok)return i;let o=dn(`${e}.kind`,n.value.kind,["team","member","manager","skill"]);if(!o.ok)return o;if(r&&!r.includes(o.value))return ke(`${e}.kind must be ${r.join(" or ")}`);let s=Q(Ee(n.value.key,`${e}.key`));if(!s.ok)return s;let a=Q(Ee(n.value.version,`${e}.version`));if(!a.ok)return a;let c=Q(Ee(n.value.integrity,`${e}.integrity`));return c.ok?S({origin:i.value,kind:o.value,key:s.value,version:a.value,integrity:c.value}):c}function B4(t,e){if(t===void 0)return S([]);let r=si(t,e);if(!r.ok)return r;let n=[];for(let i=0;i<r.value.length;i+=1){let o=Gt(r.value[i],`${e}[${i}]`);if(!o.ok)return o;let s=Q(Ee(o.value.executorId,`${e}[${i}].executorId`));if(!s.ok)return s;let a=au(o.value.lock,`${e}[${i}].lock`,["member"]);if(!a.ok)return a;if(!a.value)return ke(`${e}[${i}].lock is required`);n.push({executorId:s.value,lock:a.value})}return S(n)}function N4(t,e){if(t===void 0)return S([]);let r=si(t,e);if(!r.ok)return r;let n=[];for(let i=0;i<r.value.length;i+=1){let o=Gt(r.value[i],`${e}[${i}]`);if(!o.ok)return o;let s=Q(Ee(o.value.name,`${e}[${i}].name`));if(!s.ok)return s;let a=au(o.value.lock,`${e}[${i}].lock`,["skill"]);if(!a.ok)return a;if(!a.value)return ke(`${e}[${i}].lock is required`);n.push({name:s.value,lock:a.value})}return S(n)}function JS(t,e){let r=Gt(t,e);if(!r.ok)return r;let n=Q(Ee(r.value.name,`${e}.name`));if(!n.ok)return n;let i=Q(Ee(r.value.url,`${e}.url`));if(!i.ok)return i;let o=dn(`${e}.transport`,r.value.transport,["http","ssh"]);if(!o.ok)return o;let s=Fr(r.value.identity,`${e}.identity`);return s.ok?S({name:n.value,url:i.value,transport:o.value,identity:s.value}):s}function gg(t,e){let r=Gt(t,e);if(!r.ok)return r;let n=Q(z3(r.value.id));if(!n.ok)return n;let i=vre(r.value.owner,`${e}.owner`);if(!i.ok)return i;let o=dn(`${e}.kind`,r.value.kind,a4);if(!o.ok)return o;let s=Fr(r.value.path,`${e}.path`);if(!s.ok)return s;let a=Fr(r.value.text,`${e}.text`);return a.ok?s.value===void 0&&a.value===void 0?ke(`${e} must include path, text, or both`):s.value!==void 0&&a.value!==void 0?S({id:n.value,owner:i.value,kind:o.value,path:s.value,text:a.value}):s.value!==void 0?S({id:n.value,owner:i.value,kind:o.value,path:s.value}):S({id:n.value,owner:i.value,kind:o.value,text:a.value}):a}function O4(t,e){let r=Gt(t,e);if(!r.ok)return r;let n=Q(K3(r.value.id));if(!n.ok)return n;let i=Q(Ee(r.value.title,`${e}.title`));if(!i.ok)return i;let o=dn(`${e}.kind`,r.value.kind,c4);if(!o.ok)return o;let s=dn(`${e}.sourceScope`,r.value.sourceScope,u4);if(!s.ok)return s;let a=xre(r.value.env,`${e}.env`);if(!a.ok)return a;let c=Sre(r.value.runner,`${e}.runner`);if(!c.ok)return c;let u=bre(r.value.aliases,`${e}.aliases`);if(!u.ok)return u;let d=lre(a.value,u.value,`${e}.env`);if(!d.ok)return d;let l=wre(r.value.evidence,`${e}.evidence`);if(!l.ok)return l;let f=qS(r.value.displayOrder,`${e}.displayOrder`);return f.ok?o.value==="check"&&c.value.type!=="command"?ke(`${e}.runner.type must be command for check actions`):S({id:n.value,title:i.value,kind:o.value,sourceScope:s.value,env:a.value,runner:c.value,aliases:u.value,evidence:l.value,displayOrder:f.value}):f}function lre(t,e,r){let n=new Set(Object.keys(e??{}));for(let[i,o]of Object.entries(t??{})){if("alias"in o&&!n.has(String(o.alias)))return ke(`${r}.${i}.alias references unknown alias: ${o.alias}`);if("fromAliasUrl"in o&&!n.has(String(o.fromAliasUrl)))return ke(`${r}.${i}.fromAliasUrl references unknown alias: ${o.fromAliasUrl}`)}return S(void 0)}function T1(t,e){let r=Gt(t,e);if(!r.ok)return r;let n=Q(lr(r.value.id));if(!n.ok)return n;let i=Q(zi(r.value.requestId));if(!i.ok)return i;let o=r.value.teamName===void 0?S(void 0):Q(un(r.value.teamName,`${e}.teamName`));if(!o.ok)return o;let s=dn(`${e}.status`,r.value.status,n4);if(!s.ok)return s;let a=cre(r.value.moveIds,`${e}.moveIds`,!1);if(!a.ok)return a;let c=Q(Zr(r.value.rootNodeId));if(!c.ok)return c;let u=Q(Zr(r.value.currentNodeId));if(!u.ok)return u;let d=ure(r.value.nodeIds,`${e}.nodeIds`,!0);if(!d.ok)return d;let l=j4(r.value.parentLineId);if(!l.ok)return l;let f=yg(r.value.forkedFromMoveId);if(!f.ok)return f;if(f.value!==void 0&&l.value===void 0)return ke(`${e}.parentLineId is required when forkedFromMoveId is present`);let p={id:n.value,requestId:i.value,teamName:o.value,moveIds:a.value,rootNodeId:c.value,currentNodeId:u.value,nodeIds:d.value};if(l.value!==void 0){let v={...p,parentLineId:l.value,forkedFromMoveId:f.value};return P4(v,s.value)}return P4(p,s.value)}function M4(t,e){let r=Gt(t,e);if(!r.ok)return r;let n=Q(iu(r.value.id));if(!n.ok)return n;let i=Q(Ee(r.value.name,`${e}.name`));if(!i.ok)return i;let o=Fr(r.value.sourcePath,`${e}.sourcePath`);if(!o.ok)return o;let s=Q(Ee(r.value.draftPath,`${e}.draftPath`));if(!s.ok)return s;let a=hre(r.value.createdFromNodeId);if(!a.ok)return a;let c=Ns(r.value.createdAt,`${e}.createdAt`);if(!c.ok)return c;let u=dn(`${e}.status`,r.value.status,s4);if(!u.ok)return u;let d={id:n.value,name:i.value,sourcePath:o.value,draftPath:s.value,createdFromNodeId:a.value,createdAt:c.value};switch(u.value){case"accepted":{let l=_1(r.value.acceptedSnapshot,`${e}.acceptedSnapshot`);return l.ok?S({...d,status:"accepted",acceptedSnapshot:l.value}):l}case"draft":return r.value.acceptedSnapshot!==void 0?ke(`${e}.acceptedSnapshot is only valid for accepted Skill Drafts`):S({...d,status:"draft"});case"discarded":return r.value.acceptedSnapshot!==void 0?ke(`${e}.acceptedSnapshot is only valid for accepted Skill Drafts`):S({...d,status:"discarded"})}}function L4(t,e,r){let n=Gt(t,e);if(!n.ok)return n;let i=Q(eg(n.value.id));if(!i.ok)return i;let o=Q(lr(n.value.sourceLineId));if(!o.ok)return o;let s=Q(Zr(n.value.sourceNodeId));if(!s.ok)return s;let a=yg(n.value.sourceMoveId);if(!a.ok)return a;let c=D4(n.value.target,`${e}.target`);if(!c.ok)return c;let u=Q(un(n.value.newTeamName,`${e}.newTeamName`));if(!u.ok)return u;let d=Q(qo(n.value.summary,`${e}.summary`));if(!d.ok)return d;let l=D1(n.value.teamSnapshot,`${e}.teamSnapshot`,r);if(!l.ok)return l;let f=$4(n.value.changedFiles,`${e}.changedFiles`);if(!f.ok)return f;let p=Ns(n.value.createdAt,`${e}.createdAt`);if(!p.ok)return p;let g=Ns(n.value.updatedAt,`${e}.updatedAt`);if(!g.ok)return g;let v=dn(`${e}.status`,n.value.status,o4);if(!v.ok)return v;let b={id:i.value,sourceLineId:o.value,sourceNodeId:s.value,sourceMoveId:a.value,target:c.value,newTeamName:u.value,summary:d.value,teamSnapshot:l.value,changedFiles:f.value,createdAt:p.value,updatedAt:g.value};switch(v.value){case"ready":{let D=Q(Vo(n.value.hunsuId));if(!D.ok)return D;let _=Q(lr(n.value.newLineId));if(!_.ok)return _;if(n.value.conversationRef===void 0)return ke(`${e}.conversationRef is required for ready HUNSU Drafts`);let F=su(n.value.conversationRef,`${e}.conversationRef`);return F.ok?F.value?S({...b,status:"ready",hunsuId:D.value,newLineId:_.value,conversationRef:F.value}):ke(`${e}.conversationRef is required for ready HUNSU Drafts`):F}case"confirmed":{let D=Q(Vo(n.value.hunsuId));if(!D.ok)return D;let _=Q(lr(n.value.newLineId));if(!_.ok)return _;if(n.value.conversationRef===void 0)return ke(`${e}.conversationRef is required for confirmed HUNSU Drafts`);let F=su(n.value.conversationRef,`${e}.conversationRef`);return F.ok?F.value?S({...b,status:"confirmed",hunsuId:D.value,newLineId:_.value,conversationRef:F.value}):ke(`${e}.conversationRef is required for confirmed HUNSU Drafts`):F}case"draft":return n.value.hunsuId!==void 0||n.value.newLineId!==void 0||n.value.conversationRef!==void 0?ke(`${e} draft status cannot carry hunsuId, newLineId, or conversationRef`):S({...b,status:"draft"});case"discarded":if(n.value.hunsuId!==void 0||n.value.newLineId!==void 0)return ke(`${e} discarded status cannot carry hunsuId or newLineId`);if(n.value.conversationRef===void 0)return S({...b,status:"discarded"});let C=su(n.value.conversationRef,`${e}.conversationRef`);return C.ok?S({...b,status:"discarded",conversationRef:C.value}):C}}function H4(t,e,r){let n=Gt(t,e);if(!n.ok)return n;let i=Q(_n(n.value.id));if(!i.ok)return i;let o=Q(lr(n.value.lineId));if(!o.ok)return o;let s=Q(Zr(n.value.fromNodeId));if(!s.ok)return s;let a=Q(Zr(n.value.toNodeId));if(!a.ok)return a;let c=n.value.teamName===void 0?S(void 0):Q(un(n.value.teamName,`${e}.teamName`));if(!c.ok)return c;let u=n.value.ordinal===void 0?S(void 0):qS(n.value.ordinal,`${e}.ordinal`);if(!u.ok)return u;let d=n.value.snapshot===void 0?S(void 0):D1(n.value.snapshot,`${e}.snapshot`,r);if(!d.ok)return d;let l=mre(n.value.sourceHunsuId);if(!l.ok)return l;let f=XS(n.value.executeId);if(!f.ok)return f;let p=su(n.value.conversationRef,`${e}.conversationRef`);if(!p.ok)return p;let g=KS(n.value.worktree,`${e}.worktree`);if(!g.ok)return g;let v=Q(qo(n.value.summary,`${e}.summary`));if(!v.ok)return v;let b=Q(Gd(n.value.commit,`${e}.commit`));if(!b.ok)return b;let C=GS(n.value.evidence,`${e}.evidence`,!0);if(!C.ok)return C;let D=dre(n.value.risks,`${e}.risks`);if(!D.ok)return D;let _=dn(`${e}.recordedBy`,n.value.recordedBy,["SYSTEM"]);if(!_.ok)return _;let F=Ns(n.value.recordedAt,`${e}.recordedAt`);if(!F.ok)return F;let he=dn(`${e}.outcome`,n.value.outcome,i4);if(!he.ok)return he;let z={id:i.value,lineId:o.value,fromNodeId:s.value,toNodeId:a.value,teamName:c.value,ordinal:u.value,snapshot:d.value,sourceHunsuId:l.value,executeId:f.value,conversationRef:p.value,worktree:g.value,summary:v.value,commit:b.value,evidence:C.value,risks:D.value,recordedBy:_.value,recordedAt:F.value};if(he.value==="arrived"){let R=jS(n.value.reachedDestinationIds,`${e}.reachedDestinationIds`,!0);if(!R.ok)return R;let V=Q(Qf(R.value,`${e}.reachedDestinationIds`));return V.ok?n.value.failureReason!==void 0?ke(`${e}.failureReason is only valid for accident MOVEs`):S({...z,outcome:"arrived",reachedDestinationIds:V.value}):V}let Ce=jS(n.value.reachedDestinationIds,`${e}.reachedDestinationIds`,!1);if(!Ce.ok)return Ce;if(Ce.value.length!==0)return ke(`${e}.reachedDestinationIds must be empty for accident MOVEs`);let de=Q(Wo(n.value.failureReason,`${e}.failureReason`));return de.ok?S({...z,outcome:"accident",reachedDestinationIds:[],failureReason:de.value}):de}function U4(t,e,r){let n=Gt(t,e);if(!n.ok)return n;let i=Q(Vo(n.value.id));if(!i.ok)return i;let o=pre(n.value.hunsuDraftId);if(!o.ok)return o;let s=su(n.value.conversationRef,`${e}.conversationRef`);if(!s.ok)return s;let a=Q(lr(n.value.lineId));if(!a.ok)return a;let c=Q(Zr(n.value.fromNodeId));if(!c.ok)return c;let u=Q(Zr(n.value.toNodeId));if(!u.ok)return u;let d=D4(n.value.target,`${e}.target`);if(!d.ok)return d;let l=Q(qo(n.value.summary,`${e}.summary`));if(!l.ok)return l;let f=n.value.newLineId===void 0?S(void 0):Q(lr(n.value.newLineId));if(!f.ok)return f;let p=yg(n.value.sourceMoveId);if(!p.ok)return p;let g=n.value.newTeamName===void 0?S(void 0):Q(un(n.value.newTeamName,`${e}.newTeamName`));if(!g.ok)return g;let v=D1(n.value.teamSnapshot,`${e}.teamSnapshot`,r);if(!v.ok)return v;let b=$4(n.value.changedFiles,`${e}.changedFiles`);if(!b.ok)return b;let C=dn(`${e}.recordedBy`,n.value.recordedBy,["DIRECTOR"]);if(!C.ok)return C;let D=Ns(n.value.recordedAt,`${e}.recordedAt`);return D.ok?S({id:i.value,hunsuDraftId:o.value,conversationRef:s.value,lineId:a.value,fromNodeId:c.value,toNodeId:u.value,target:d.value,summary:l.value,newLineId:f.value,sourceMoveId:p.value,newTeamName:g.value,teamSnapshot:v.value,changedFiles:b.value,recordedBy:C.value,recordedAt:D.value}):D}function $4(t,e){let r=si(t,e);if(!r.ok)return r;if(r.value.length===0)return ke(`${e} must contain at least one changed file`);let n=[];for(let i=0;i<r.value.length;i+=1){let o=fre(r.value[i],`${e}[${i}]`);if(!o.ok)return o;n.push(o.value)}return S(n)}function fre(t,e){let r=Gt(t,e);if(!r.ok)return r;let n=Q(Ee(r.value.path,`${e}.path`));if(!n.ok)return n;let i=dn(`${e}.kind`,r.value.kind,["added","updated","removed"]);if(!i.ok)return i;let o=Q(qo(r.value.summary,`${e}.summary`));return o.ok?S({path:n.value,kind:i.value,summary:o.value}):o}function F4(t,e,r){let n=Gt(t,e);if(!n.ok)return n;let i=Q(Zr(n.value.id));if(!i.ok)return i;let o=Q(zi(n.value.requestId));if(!o.ok)return o;let s=j4(n.value.lineId);if(!s.ok)return s;let a=n.value.teamName===void 0?S(void 0):Q(un(n.value.teamName,`${e}.teamName`));if(!a.ok)return a;let c=qS(n.value.ordinal,`${e}.ordinal`);if(!c.ok)return c;let u=T4(n.value.destinations,`${e}.destinations`);if(!u.ok)return u;let d=r(n.value.harness);if(!d.ok)return d;let l=q4(n.value.harnessGraph,d.value,`${e}.harnessGraph`);if(!l.ok)return l;let f=au(n.value.harnessLock,`${e}.harnessLock`,["team"]);if(!f.ok)return f;let p=B4(n.value.executorPackageBindings,`${e}.executorPackageBindings`);if(!p.ok)return p;let g=N4(n.value.resourcePackageBindings,`${e}.resourcePackageBindings`);if(!g.ok)return g;let v=vg(n.value.artifactActions??[],`${e}.artifactActions`);if(!v.ok)return v;let b=Ire(n.value.source,`${e}.source`);if(!b.ok)return b;let C=Ns(n.value.createdAt,`${e}.createdAt`);return C.ok?S({id:i.value,requestId:o.value,lineId:s.value,teamName:a.value,ordinal:c.value,destinations:u.value,harness:d.value,harnessGraph:l.value,harnessLock:f.value,executorPackageBindings:p.value,resourcePackageBindings:g.value,artifactActions:v.value,source:b.value,createdAt:C.value}):C}function pre(t){return t===void 0?S(void 0):Q(eg(t))}function mre(t){return t===void 0?S(void 0):Q(Vo(t))}function yg(t){return t===void 0?S(void 0):Q(_n(t))}function j4(t){return t===void 0?S(void 0):Q(lr(t))}function hre(t){return t===void 0?S(void 0):Q(Zr(t))}function XS(t){return t===void 0?S(void 0):Q(J3(t))}function D1(t,e,r){let n=Gt(t,e);if(!n.ok)return n;let i=Q(un(n.value.teamName,`${e}.teamName`));if(!i.ok)return i;let o=qS(n.value.moveOrdinal,`${e}.moveOrdinal`);if(!o.ok)return o;let s=T4(n.value.destinations,`${e}.destinations`);if(!s.ok)return s;let a=r(n.value.harness);if(!a.ok)return a;let c=q4(n.value.harnessGraph,a.value,`${e}.harnessGraph`);if(!c.ok)return c;let u=au(n.value.harnessLock,`${e}.harnessLock`,["team"]);if(!u.ok)return u;let d=B4(n.value.executorPackageBindings,`${e}.executorPackageBindings`);if(!d.ok)return d;let l=N4(n.value.resourcePackageBindings,`${e}.resourcePackageBindings`);if(!l.ok)return l;let f=vg(n.value.artifactActions??[],`${e}.artifactActions`);return f.ok?S({teamName:i.value,moveOrdinal:o.value,destinations:s.value,harness:a.value,harnessGraph:c.value,harnessLock:u.value,executorPackageBindings:d.value,resourcePackageBindings:l.value,artifactActions:f.value}):f}function q4(t,e,r){return t===void 0?S(Bs(e)):Jd(t,r)}function vg(t,e){let r=si(t,e);if(!r.ok)return r;let n=[];for(let i=0;i<r.value.length;i+=1){let o=O4(r.value[i],`${e}[${i}]`);if(!o.ok)return o;if(n.some(s=>s.id===o.value.id))return ke(`${e} contains duplicate ArtifactActionId: ${o.value.id}`);n.push(o.value)}return S(n)}function gre(t,e){let r=si(t,e);if(!r.ok)return r;let n=[];for(let i=0;i<r.value.length;i+=1){let o=Gt(r.value[i],`${e}[${i}]`);if(!o.ok)return o;let s=Q(Ee(o.value.path,`${e}[${i}].path`));if(!s.ok)return s;let a=o.value.text;if(typeof a!="string")return ke(`${e}[${i}].text must be a string`);n.push({path:s.value,text:a})}return S(n)}function yre(t){return/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(t)}function vre(t,e){let r=Gt(t,e);if(!r.ok)return r;switch(r.value.type){case"move":{let n=Q(_n(r.value.id));return n.ok?S({type:"move",id:n.value}):n}case"hunsu":{let n=Q(Vo(r.value.id));return n.ok?S({type:"hunsu",id:n.value}):n}case"line":{let n=Q(lr(r.value.id));return n.ok?S({type:"line",id:n.value}):n}default:return ke(`${e}.type must be move, hunsu, or line`)}}function xre(t,e){if(t===void 0)return S(void 0);let r=Gt(t,e);if(!r.ok)return r;let n={};for(let[i,o]of Object.entries(r.value)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))return ke(`${e}.${i} must be a valid environment variable name`);let s=Gt(o,`${e}.${i}`);if(!s.ok)return s;if(["default","value","required","alias","fromAliasUrl"].filter(c=>c in s.value).length!==1)return ke(`${e}.${i} must declare exactly one of default, value, required, alias, or fromAliasUrl`);if("default"in s.value){let c=C4(s.value.default,`${e}.${i}.default`);if(!c.ok)return c;n[i]={default:c.value}}else if("value"in s.value){let c=C4(s.value.value,`${e}.${i}.value`);if(!c.ok)return c;n[i]={value:c.value}}else if("alias"in s.value){let c=Q(Ee(s.value.alias,`${e}.${i}.alias`));if(!c.ok)return c;n[i]={alias:c.value}}else if("fromAliasUrl"in s.value){let c=Q(Ee(s.value.fromAliasUrl,`${e}.${i}.fromAliasUrl`));if(!c.ok)return c;n[i]={fromAliasUrl:c.value}}else{if(s.value.required!==!0)return ke(`${e}.${i}.required must be true`);let c=_4(s.value.secret,`${e}.${i}.secret`);if(!c.ok)return c;n[i]={required:!0,secret:c.value}}}return S(n)}function Sre(t,e){let r=Gt(t,e);if(!r.ok)return r;switch(r.value.type){case"docker_compose":{let n=Q(Ee(r.value.file,`${e}.file`));if(!n.ok)return n;let i=Fr(r.value.projectName,`${e}.projectName`);return i.ok?S({type:"docker_compose",file:n.value,projectName:i.value}):i}case"command":{let n=Q(Ee(r.value.command,`${e}.command`));if(!n.ok)return n;let i=Fr(r.value.stopCommand,`${e}.stopCommand`);return i.ok?S({type:"command",command:n.value,stopCommand:i.value}):i}default:return ke(`${e}.type must be docker_compose or command`)}}function bre(t,e){if(t===void 0)return S(void 0);let r=Gt(t,e);if(!r.ok)return r;let n={};for(let[i,o]of Object.entries(r.value)){if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return ke(`${e}.${i} must start with a letter and contain only letters, numbers, "_" or "-"`);let s=Gt(o,`${e}.${i}`);if(!s.ok)return s;let a="target"in s.value,c="service"in s.value,u="containerPort"in s.value;if(a&&(c||u||"healthPath"in s.value))return ke(`${e}.${i} must not mix target with docker service fields`);if(a){let p=Q(Ee(s.value.target,`${e}.${i}.target`));if(!p.ok)return p;n[i]={target:p.value};continue}if(!c||!u)return ke(`${e}.${i} must declare either target or both service and containerPort`);let d=Q(Ee(s.value.service,`${e}.${i}.service`));if(!d.ok)return d;let l=Q(Ba(s.value.containerPort,`${e}.${i}.containerPort`));if(!l.ok)return l;let f=Fr(s.value.healthPath,`${e}.${i}.healthPath`);if(!f.ok)return f;n[i]={service:d.value,containerPort:l.value,healthPath:f.value}}return S(n)}function wre(t,e){if(t===void 0)return S(void 0);let r=Gt(t,e);if(!r.ok)return r;let n=nre(r.value.paths,`${e}.paths`);if(!n.ok)return n;let i=_4(r.value.attach,`${e}.attach`);return i.ok?S({attach:i.value,paths:n.value}):i}function C4(t,e){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"?S(t):ke(`${e} must be a string, number, or boolean`)}function YS(t,e,r){let n=new Set;for(let i of t){if(n.has(i))return ke(`${e} contains duplicate ${r}: ${i}`);n.add(i)}return S(void 0)}function Ire(t,e){let r=Gt(t,e);if(!r.ok)return r;switch(r.value.type){case"initial-execute-team":case"request":{let n=Q(zi(r.value.requestId));return n.ok?S({type:r.value.type,requestId:n.value}):n}case"move":{let n=Q(_n(r.value.moveId));if(!n.ok)return n;let i=Q(Zr(r.value.fromNodeId));return i.ok?S({type:"move",moveId:n.value,fromNodeId:i.value}):i}case"hunsu":{let n=Q(Vo(r.value.hunsuId));if(!n.ok)return n;let i=Q(Zr(r.value.fromNodeId));return i.ok?S({type:"hunsu",hunsuId:n.value,fromNodeId:i.value}):i}default:return ke(`${e}.type must be a supported node source type`)}}function P4(t,e){switch(e){case"active":return S({...t,status:"active"});case"paused":return S({...t,status:"paused"});case"complete":return S({...t,status:"complete"});case"failed":return S({...t,status:"failed"});case"abandoned":return S({...t,status:"abandoned"})}}function Ere(t,e,r,n){let i=np(t,e,r);return i.ok?S({...n,status:"pending"}):i}function np(t,e,r){let n=r.find(i=>t[i]!==void 0);return n?ke(`${e}.${n} is not valid for this lifecycle status`):S(void 0)}function Q(t){return t.ok?S(t.value):ke(t.error.message)}function W4(t,e){let r=Gt(t,"Command");if(!r.ok)return r;switch(r.value.type){case"RegisterHunsuOrigin":{let n=JS(r.value.origin,"origin");if(!n.ok)return n;let i=Fr(r.value.actor,"actor");if(!i.ok)return i;let o=or(r.value.at);return o.ok?S({type:"RegisterHunsuOrigin",origin:n.value,actor:i.value,at:o.value}):o}case"CreateInitialTeam":{let n=$t(zi(r.value.requestId));if(!n.ok)return n;let i=$t(lr(r.value.lineId));if(!i.ok)return i;let o=$t(ES(r.value.title));if(!o.ok)return o;let s=$t(kS(r.value.goal));if(!s.ok)return s;let a=VS(r.value.destinations,"destinations");if(!a.ok)return a;let c=r.value.harness===void 0?S(void 0):e(r.value.harness);if(!c.ok)return c;let u=au(r.value.harnessLock,"harnessLock",["team"]);if(!u.ok)return u;let d=r.value.teamName===void 0?S(void 0):$t(un(r.value.teamName));if(!d.ok)return d;let l=Fr(r.value.actor,"actor");if(!l.ok)return l;let f=or(r.value.at);return f.ok?S({type:"CreateInitialTeam",requestId:n.value,lineId:i.value,title:o.value,goal:s.value,destinations:a.value,harness:c.value,harnessLock:u.value,teamName:d.value,actor:l.value,at:f.value}):f}case"StartLine":{let n=$t(zi(r.value.requestId));if(!n.ok)return n;let i=$t(lr(r.value.lineId));if(!i.ok)return i;let o=r.value.teamName===void 0?S(void 0):$t(un(r.value.teamName));if(!o.ok)return o;let s=or(r.value.at);return s.ok?S({type:"StartLine",lineId:i.value,requestId:n.value,teamName:o.value,at:s.value}):s}case"PauseLine":case"ResumeLine":{let n=$t(lr(r.value.lineId));if(!n.ok)return n;let i=or(r.value.at);return i.ok?S({type:r.value.type,lineId:n.value,at:i.value}):i}case"AcceptLine":case"RejectLine":{let n=$t(lr(r.value.lineId));if(!n.ok)return n;let i=Fr(r.value.reason,"reason");if(!i.ok)return i;let o=or(r.value.at);return o.ok?S({type:r.value.type,lineId:n.value,reason:i.value,at:o.value}):o}case"ClaimDestination":case"StartDestinationWork":{let n=$t(mo(r.value.destinationId));if(!n.ok)return n;let i=$t(Ee(r.value.actor,"actor"));if(!i.ok)return i;let o=or(r.value.at);return o.ok?S({type:r.value.type,destinationId:n.value,actor:i.value,at:o.value}):o}case"ReportDestinationBlocked":{let n=$t(mo(r.value.destinationId));if(!n.ok)return n;let i=$t(Wo(r.value.reason,"reason"));if(!i.ok)return i;let o=$t(Ee(r.value.actor,"actor"));if(!o.ok)return o;let s=or(r.value.at);return s.ok?S({type:"ReportDestinationBlocked",destinationId:n.value,reason:i.value,actor:o.value,at:s.value}):s}case"RecordMove":{let n=$t(lr(r.value.lineId));if(!n.ok)return n;let i=$t(_n(r.value.moveId));if(!i.ok)return i;let o=$t(qo(r.value.summary));if(!o.ok)return o;let s=$t(Gd(r.value.commit,"commit"));if(!s.ok)return s;let a=jS(r.value.reachedDestinationIds,"reachedDestinationIds",!0);if(!a.ok)return a;let c=$t(Qf(a.value,"reachedDestinationIds"));if(!c.ok)return c;let u=GS(r.value.evidence,"evidence",!0);if(!u.ok)return u;let d=r.value.risks===void 0?S(void 0):zS(r.value.risks,"risks");if(!d.ok)return d;let l=XS(r.value.executeId);if(!l.ok)return l;let f=su(r.value.conversationRef,"conversationRef");if(!f.ok)return f;let p=KS(r.value.worktree,"worktree");if(!p.ok)return p;let g=$t(Ee(r.value.actor,"actor"));if(!g.ok)return g;let v=or(r.value.at);return v.ok?S({type:"RecordMove",lineId:n.value,moveId:i.value,summary:o.value,commit:s.value,reachedDestinationIds:c.value,evidence:u.value,risks:d.value,executeId:l.value,conversationRef:f.value,worktree:p.value,actor:g.value,at:v.value}):v}case"RecordAccident":{let n=$t(lr(r.value.lineId));if(!n.ok)return n;let i=$t(_n(r.value.moveId));if(!i.ok)return i;let o=$t(qo(r.value.summary));if(!o.ok)return o;let s=$t(Gd(r.value.commit,"commit"));if(!s.ok)return s;let a=GS(r.value.evidence,"evidence",!0);if(!a.ok)return a;let c=$t(Wo(r.value.failureReason));if(!c.ok)return c;let u=r.value.risks===void 0?S(void 0):zS(r.value.risks,"risks");if(!u.ok)return u;let d=XS(r.value.executeId);if(!d.ok)return d;let l=su(r.value.conversationRef,"conversationRef");if(!l.ok)return l;let f=KS(r.value.worktree,"worktree");if(!f.ok)return f;let p=$t(Ee(r.value.actor,"actor"));if(!p.ok)return p;let g=or(r.value.at);return g.ok?S({type:"RecordAccident",lineId:n.value,moveId:i.value,summary:o.value,commit:s.value,evidence:a.value,failureReason:c.value,risks:u.value,executeId:d.value,conversationRef:l.value,worktree:f.value,actor:p.value,at:g.value}):g}case"AttachMoveEvidence":{let n=$t(_n(r.value.moveId));if(!n.ok)return n;let i=gg(r.value.artifact,"artifact");if(!i.ok)return i;let o=$t(Ee(r.value.actor,"actor"));if(!o.ok)return o;let s=or(r.value.at);return s.ok?S({type:"AttachMoveEvidence",moveId:n.value,artifact:i.value,actor:o.value,at:s.value}):s}case"ConfirmHunsuDraft":{let n=L4(r.value.draft,"draft",e);if(!n.ok)return n;if(n.value.status!=="ready")return ke(`HUNSU Draft ${n.value.id} cannot be confirmed from status ${n.value.status}`);let i=$t(Ee(r.value.actor,"actor"));if(!i.ok)return i;let o=or(r.value.at);return o.ok?S({type:"ConfirmHunsuDraft",draft:n.value,actor:i.value,at:o.value}):o}case"CreateSkillDraft":{let n=$t(iu(r.value.draftId));if(!n.ok)return n;let i=$t(lr(r.value.lineId));if(!i.ok)return i;let o=$t(Ee(r.value.name,"name"));if(!o.ok)return o;let s=$t(Ee(r.value.draftPath,"draftPath"));if(!s.ok)return s;let a=Fr(r.value.sourcePath,"sourcePath");if(!a.ok)return a;let c=$t(Ee(r.value.actor,"actor"));if(!c.ok)return c;let u=or(r.value.at);return u.ok?S({type:"CreateSkillDraft",draftId:n.value,lineId:i.value,name:o.value,draftPath:s.value,sourcePath:a.value,actor:c.value,at:u.value}):u}case"DiscardSkillDraft":{let n=$t(iu(r.value.draftId));if(!n.ok)return n;let i=$t(Ee(r.value.actor,"actor"));if(!i.ok)return i;let o=or(r.value.at);return o.ok?S({type:"DiscardSkillDraft",draftId:n.value,actor:i.value,at:o.value}):o}case"RecordArtifact":{let n=gg(r.value.artifact,"artifact");if(!n.ok)return n;let i=or(r.value.at);return i.ok?S({type:"RecordArtifact",artifact:n.value,at:i.value}):i}default:return ke(`Unsupported command type: ${String(r.value.type)}`)}}function $t(t){return t.ok?S(t.value):ke(t.error.message)}function V4(t,e){let r=Gt(t,"DomainEvent");if(!r.ok)return r;switch(r.value.type){case"HunsuOriginRegistered":{let n=JS(r.value.origin,"event.origin");if(!n.ok)return n;let i=or(r.value.at,"event.at");return i.ok?S({type:"HunsuOriginRegistered",origin:n.value,at:i.value}):i}case"InitialTeamCreated":{let n=P1(r.value.request,"event.request");if(!n.ok)return n;let i=T1(r.value.line,"event.line");if(!i.ok)return i;let o=VS(r.value.destinations,"event.destinations");if(!o.ok)return o;let s=r.value.harness===void 0?S(void 0):e(r.value.harness);if(!s.ok)return s;let a=au(r.value.harnessLock,"event.harnessLock",["team"]);if(!a.ok)return a;let c=or(r.value.at,"event.at");return c.ok?S({type:"InitialTeamCreated",request:n.value,line:i.value,destinations:o.value,harness:s.value,harnessLock:a.value,at:c.value}):c}case"RequestCreated":{let n=P1(r.value.request,"event.request");return n.ok?S({type:"RequestCreated",request:n.value}):n}case"DestinationDeclared":{let n=Gn(zi(r.value.requestId));if(!n.ok)return n;let i=WS(r.value.destination,"event.destination");if(!i.ok)return i;let o=or(r.value.at,"event.at");return o.ok?S({type:"DestinationDeclared",requestId:n.value,destination:i.value,at:o.value}):o}case"HarnessSeeded":{let n=Gn(zi(r.value.requestId));if(!n.ok)return n;let i=e(r.value.harness);if(!i.ok)return i;let o=or(r.value.at,"event.at");return o.ok?S({type:"HarnessSeeded",requestId:n.value,harness:i.value,at:o.value}):o}case"LineStarted":{let n=T1(r.value.line,"event.line");return n.ok?S({type:"LineStarted",line:n.value}):n}case"SkillDraftCreated":{let n=M4(r.value.draft,"event.draft");return n.ok?S({type:"SkillDraftCreated",draft:n.value}):n}case"SkillDraftAccepted":{let n=Gn(iu(r.value.draftId));if(!n.ok)return n;let i=_1(r.value.skill,"event.skill");if(!i.ok)return i;let o=or(r.value.at,"event.at");return o.ok?S({type:"SkillDraftAccepted",draftId:n.value,skill:i.value,at:o.value}):o}case"SkillDraftDiscarded":{let n=Gn(iu(r.value.draftId));if(!n.ok)return n;let i=or(r.value.at,"event.at");return i.ok?S({type:"SkillDraftDiscarded",draftId:n.value,at:i.value}):i}case"NodeCreated":{let n=F4(r.value.node,"event.node",e);return n.ok?S({type:"NodeCreated",node:n.value}):n}case"LinePaused":case"LineResumed":{let n=Gn(lr(r.value.lineId));if(!n.ok)return n;let i=or(r.value.at,"event.at");return i.ok?S({type:r.value.type,lineId:n.value,at:i.value}):i}case"LineAccepted":case"LineRejected":{let n=Gn(lr(r.value.lineId));if(!n.ok)return n;let i=Fr(r.value.reason,"event.reason");if(!i.ok)return i;let o=or(r.value.at,"event.at");return o.ok?S({type:r.value.type,lineId:n.value,reason:i.value,at:o.value}):o}case"DestinationClaimed":case"DestinationWorkStarted":{let n=Gn(mo(r.value.destinationId));if(!n.ok)return n;let i=C1(r.value.actor,"event.actor");if(!i.ok)return i;let o=or(r.value.at,"event.at");return o.ok?S({type:r.value.type,destinationId:n.value,actor:i.value,at:o.value}):o}case"DestinationBlocked":{let n=Gn(mo(r.value.destinationId));if(!n.ok)return n;let i=Gn(Wo(r.value.reason,"event.reason"));if(!i.ok)return i;let o=C1(r.value.actor,"event.actor");if(!o.ok)return o;let s=or(r.value.at,"event.at");return s.ok?S({type:"DestinationBlocked",destinationId:n.value,reason:i.value,actor:o.value,at:s.value}):s}case"MoveRecorded":{let n=H4(r.value.move,"event.move",e);return n.ok?S({type:"MoveRecorded",move:n.value}):n}case"DestinationReached":{let n=Gn(mo(r.value.destinationId));if(!n.ok)return n;let i=Gn(_n(r.value.moveId));if(!i.ok)return i;let o=or(r.value.at,"event.at");return o.ok?S({type:"DestinationReached",destinationId:n.value,moveId:i.value,at:o.value}):o}case"HunsuRecorded":{let n=U4(r.value.hunsu,"event.hunsu",e);return n.ok?S({type:"HunsuRecorded",hunsu:n.value}):n}case"LineForkedByHunsu":{let n=Gn(Vo(r.value.hunsuId));if(!n.ok)return n;let i=Gn(lr(r.value.fromLineId));if(!i.ok)return i;let o=Gn(lr(r.value.newLineId));if(!o.ok)return o;let s=r.value.newTeamName??r.value.newTeamName,a=s===void 0?S(void 0):Gn(un(s,(s===r.value.newTeamName,"event.newTeamName")));if(!a.ok)return a;let c=yg(r.value.fromMoveId);if(!c.ok)return c;let u=Gn(zi(r.value.requestId));if(!u.ok)return u;let d=or(r.value.at,"event.at");return d.ok?S({type:"LineForkedByHunsu",hunsuId:n.value,fromLineId:i.value,newLineId:o.value,newTeamName:a.value,fromMoveId:c.value,requestId:u.value,at:d.value}):d}case"ArtifactRecorded":{let n=gg(r.value.artifact,"event.artifact");if(!n.ok)return n;let i=or(r.value.at,"event.at");return i.ok?S({type:"ArtifactRecorded",artifact:n.value,at:i.value}):i}default:return ke(`Unsupported Hunsu domain event type: ${String(r.value.type)}`)}}function Gn(t){return t.ok?S(t.value):ke(t.error.message)}var B1=["T1","Gen.G","Hanwha Life Esports","KT Rolster","Dplus KIA","DRX","Nongshim RedForce","BNK FearX","DN Freecs","OKSavingsBank BRION","Bilibili Gaming","JD Gaming","Top Esports","Anyone's Legend","Ninjas in Pyjamas","Weibo Gaming","Invictus Gaming","Team WE","LNG Esports","TT Gaming","LGD Gaming","EDward Gaming","Ultra Prime","Oh My God","Cloud9","Team Liquid","FlyQuest","Shopify Rebellion","100 Thieves","Dignitas","LYON","Sentinels","G2 Esports","Fnatic","Karmine Corp","Team Vitality","Team Heretics","GIANTX","Movistar KOI","SK Gaming","Natus Vincere","Rogue"];function Jr(t,e){return t.some(r=>r.id===e.id)?t.map(r=>r.id===e.id?e:r):[...t,e]}function N1(t){return Array.from(new Set(t))}function Os(t){return er(Zr(`${t}:root`))}function QS(t){let e=t.nodes.reduce((r,n)=>{let i=n.id.match(/^N(\d+)$/i);return i?Math.max(r,Number(i[1])):r},0);return er(Zr(`N${String(e+1).padStart(4,"0")}`))}function Ms(t){let e=new Set(t.lines.map(n=>n.teamName).filter(n=>!!n)),r=B1.find(n=>!e.has(n));return r?er(un(r)):er(un(`${B1[t.lines.length%B1.length]}-${t.lines.length+1}`))}function G4(t,e){if(!t.requests.some(r=>r.id===e))throw new fr(`Unknown request: ${e}`)}function zn(t,e){let r=t.lines.find(n=>n.id===e);if(!r)throw new fr(`Unknown line: ${e}`);return r}function O1(t){if(t.status!=="active")throw new fr(`TEAM line ${t.id} cannot continue from status ${t.status}`)}function Yd(t,e){let r=t.nodes.find(n=>n.id===e);if(!r)throw new fr(`Unknown node: ${e}`);return r}function ZS(t,e){return Yd(t,Os(e))}function eb(t,e){return Yd(t,e.currentNodeId)}function M1(t,e){let r=t.moves.find(n=>n.id===e);if(!r)throw new fr(`Unknown MOVE: ${e}`);return r}function z4(t,e){let r=t.skillDrafts.find(n=>n.id===e);if(!r)throw new fr(`Unknown Skill Draft: ${e}`);return r}function tb(t,e){let r=t.destinations.find(n=>n.id===e);if(!r)throw new fr(`Unknown Destination: ${e}`);return r}function kre(t,e){let r=t.destinations.find(n=>n.id===e);if(!r)throw new fr(`Unknown Destination in node ${t.id}: ${e}`);return r}function K4(t,e){let r=tb(t,e);if(r.status!=="pending"&&r.status!=="blocked")throw new fr(`Destination ${e} cannot be claimed from status ${r.status}`);return r}function J4(t,e){let r=tb(t,e);if(Y4(r))throw new fr(`Destination ${e} cannot be blocked from status ${r.status}`);return r}function X4(t,e){let r=kre(t,e);if(Y4(r))throw new fr(`Destination ${e} cannot be reached from status ${r.status}`);return r}function Y4(t){return t.status==="reached"||t.status==="canceled"||t.status==="superseded"}function xg(t,e){if(t.length===0)throw new fr(e)}function Q4(t,e){if(t.length!==1)throw new fr(e)}function Z4(t,e){if(t.trim()==="")throw new fr(e)}function cu(){return{origins:[],requests:[],destinations:[],nodes:[],edges:[],lines:[],moves:[],hunsus:[],skillDrafts:[],artifacts:[],artifactActions:[],futureConstraints:[]}}function t8(t){return Ki(t.reduce((e,r)=>U1(e,r),cu()))}function uu(t){let e=r8(t);if(!e.ok)return e;try{return S(t8(t))}catch(r){return oe(rg(r))}}function r8(t){let e={requestIds:new Set,destinationIds:new Set,lineIds:new Set,moveIds:new Set,hunsuIds:new Set,skillDraftIds:new Set,artifactIds:new Set},r=cu();for(let n=0;n<t.length;n+=1){let i=t[n],o=Are(i,n,e);if(!o.ok)return o;let s=Cre(i,n,r);if(!s.ok)return s;try{r=U1(r,i)}catch(c){return oe(rg(c))}let a=Ure(r,n);if(!a.ok)return a}return S(t)}function U1(t,e){switch(e.type){case"HunsuOriginRegistered":return{...t,origins:Rre(t.origins,e.origin)};case"InitialTeamCreated":return Fre(t,e);case"RequestCreated":return Ki({...t,requests:Jr(t.requests,e.request)});case"DestinationDeclared":return jre(t,e.requestId,e.destination,e.at);case"HarnessSeeded":return qre(t,e.requestId,e.harness,e.at);case"LineStarted":return Ki({...t,lines:Jr(t.lines,i8(t,e.line))});case"SkillDraftCreated":return{...t,skillDrafts:Jr(t.skillDrafts,e.draft)};case"SkillDraftAccepted":return{...t,skillDrafts:t.skillDrafts.map(r=>r.id===e.draftId?er(E1(r,{...e.skill})):r)};case"SkillDraftDiscarded":return{...t,skillDrafts:t.skillDrafts.map(r=>r.id===e.draftId?er(k1(r)):r)};case"NodeCreated":return Ki({...t,nodes:Jr(t.nodes,e.node)});case"LinePaused":return Sg(t,e.lineId,fg);case"LineResumed":return Sg(t,e.lineId,pg);case"LineAccepted":return Sg(t,e.lineId,mg);case"LineRejected":return Sg(t,e.lineId,hg);case"DestinationClaimed":return H1(t,e.destinationId,r=>cg(r,{claimedBy:e.actor,updatedBy:"TEAM",updatedAt:e.at}));case"DestinationWorkStarted":return H1(t,e.destinationId,r=>ug(r,{claimedBy:e.actor,updatedBy:"TEAM",updatedAt:e.at}));case"DestinationBlocked":return H1(t,e.destinationId,r=>dg(r,{blockedReason:e.reason,updatedBy:"TEAM",updatedAt:e.at}));case"MoveRecorded":return Wre(t,e.move);case"DestinationReached":return t;case"HunsuRecorded":return Vre(t,e.hunsu);case"LineForkedByHunsu":return Gre(t,e);case"ArtifactRecorded":return{...t,artifacts:Jr(t.artifacts,e.artifact)}}}function Rre(t,e){return t.some(r=>r.name===e.name)?t.map(r=>r.name===e.name?{...e}:{...r}):[...t.map(r=>({...r})),{...e}]}function Are(t,e,r){switch(t.type){case"InitialTeamCreated":{let n=Go(r.requestIds,"RequestId",t.request.id,e);if(!n.ok)return n;let i=Go(r.lineIds,"LineId",t.line.id,e);return i.ok?$re(r.destinationIds,t.destinations,e):i}case"RequestCreated":return Go(r.requestIds,"RequestId",t.request.id,e);case"DestinationDeclared":return Go(r.destinationIds,"DestinationId",t.destination.id,e);case"LineStarted":return Go(r.lineIds,"LineId",t.line.id,e);case"SkillDraftCreated":return Go(r.skillDraftIds,"SkillDraftId",t.draft.id,e);case"MoveRecorded":return Go(r.moveIds,"MoveId",t.move.id,e);case"HunsuRecorded":return Go(r.hunsuIds,"HunsuId",t.hunsu.id,e);case"LineForkedByHunsu":return Go(r.lineIds,"LineId",t.newLineId,e);case"ArtifactRecorded":return Go(r.artifactIds,"ArtifactId",t.artifact.id,e);case"HunsuOriginRegistered":case"HarnessSeeded":case"SkillDraftAccepted":case"SkillDraftDiscarded":case"NodeCreated":case"LinePaused":case"LineResumed":case"LineAccepted":case"LineRejected":case"DestinationClaimed":case"DestinationWorkStarted":case"DestinationBlocked":case"DestinationReached":return S(void 0)}}function Cre(t,e,r){switch(t.type){case"InitialTeamCreated":return Pre(t,e);case"DestinationDeclared":return r.requests.some(n=>n.id===t.requestId)?S(void 0):Ue(e,`Unknown request: ${t.requestId}`);case"HarnessSeeded":return r.nodes.some(n=>n.id===Os(t.requestId))?S(void 0):Ue(e,`Unknown root node for request: ${t.requestId}`);case"LineStarted":return _re(r,t.line,e);case"SkillDraftAccepted":return e8(r,t.draftId,e,n=>E1(n,t.skill));case"SkillDraftDiscarded":return e8(r,t.draftId,e,k1);case"NodeCreated":return Tre(r,t.node,e);case"LinePaused":return rb(r,t.lineId,e,fg);case"LineResumed":return rb(r,t.lineId,e,pg);case"LineAccepted":return rb(r,t.lineId,e,mg);case"LineRejected":return rb(r,t.lineId,e,hg);case"DestinationClaimed":return L1(r,t.destinationId,e,n=>cg(n,{claimedBy:t.actor,updatedBy:"TEAM",updatedAt:t.at}));case"DestinationWorkStarted":return L1(r,t.destinationId,e,n=>ug(n,{claimedBy:t.actor,updatedBy:"TEAM",updatedAt:t.at}));case"DestinationBlocked":return L1(r,t.destinationId,e,n=>dg(n,{blockedReason:t.reason,updatedBy:"TEAM",updatedAt:t.at}));case"MoveRecorded":return Dre(r,t.move,e);case"HunsuRecorded":return Bre(r,t.hunsu,e);case"LineForkedByHunsu":return Lre(r,t,e);case"ArtifactRecorded":return Hre(r,t.artifact,e);case"DestinationReached":return Ue(e,"DestinationReached is a legacy no-op event and cannot be projected");case"HunsuOriginRegistered":case"RequestCreated":case"SkillDraftCreated":return S(void 0)}}function Pre(t,e){return t.line.requestId!==t.request.id?Ue(e,`Initial line ${t.line.id} request ${t.line.requestId} does not match request ${t.request.id}`):t.line.status!=="active"?Ue(e,`Initial line ${t.line.id} cannot start from status ${t.line.status}`):t.line.rootNodeId!==t.line.currentNodeId?Ue(e,`Initial line ${t.line.id} currentNodeId must start at rootNodeId`):t.line.nodeIds.includes(t.line.rootNodeId)?t.line.moveIds.length!==0?Ue(e,`Initial line ${t.line.id} cannot start with MOVEs`):"parentLineId"in t.line||"forkedFromMoveId"in t.line?Ue(e,`Initial line ${t.line.id} cannot carry fork metadata`):S(void 0):Ue(e,`Initial line ${t.line.id} nodeIds must include rootNodeId ${t.line.rootNodeId}`)}function _re(t,e,r){if(!t.requests.some(i=>i.id===e.requestId))return Ue(r,`Unknown request: ${e.requestId}`);if(e.status!=="active")return Ue(r,`Line ${e.id} cannot start from status ${e.status}`);let n=t.nodes.find(i=>i.id===Os(e.requestId));return n?e.rootNodeId!==n.id||e.currentNodeId!==n.id||!e.nodeIds.includes(n.id)?Ue(r,`Line ${e.id} must start at request root node ${n.id}`):e.moveIds.length!==0?Ue(r,`Line ${e.id} cannot start with MOVEs`):"parentLineId"in e||"forkedFromMoveId"in e?Ue(r,`LineStarted ${e.id} cannot carry fork metadata`):S(void 0):Ue(r,`Unknown root node for request: ${e.requestId}`)}function e8(t,e,r,n){let i=t.skillDrafts.find(o=>o.id===e);return i?nb(r,n(i)):Ue(r,`Unknown Skill Draft: ${e}`)}function Tre(t,e,r){if(e.lineId){let i=t.lines.find(o=>o.id===e.lineId);if(!i)return Ue(r,`Unknown line: ${e.lineId}`);if(i.requestId!==e.requestId)return Ue(r,`Node ${e.id} request ${e.requestId} does not match line ${i.id} request ${i.requestId}`)}let n=e.source;switch(n.type){case"initial-execute-team":case"request":return t.requests.some(i=>i.id===n.requestId)?S(void 0):Ue(r,`Unknown request: ${n.requestId}`);case"move":{let i=t.moves.find(o=>o.id===n.moveId);return i?i.toNodeId===e.id&&i.fromNodeId===n.fromNodeId?S(void 0):Ue(r,`Node ${e.id} does not match MOVE ${i.id} topology`):Ue(r,`Unknown MOVE: ${n.moveId}`)}case"hunsu":{let i=t.hunsus.find(o=>o.id===n.hunsuId);return i?i.toNodeId===e.id&&i.fromNodeId===n.fromNodeId?S(void 0):Ue(r,`Node ${e.id} does not match HUNSU ${i.id} topology`):Ue(r,`Unknown HUNSU: ${n.hunsuId}`)}}}function rb(t,e,r,n){let i=t.lines.find(o=>o.id===e);return i?nb(r,n(i)):Ue(r,`Unknown line: ${e}`)}function L1(t,e,r,n){let i=new Set(t.lines.map(s=>s.currentNodeId)),o=t.nodes.filter(s=>i.has(s.id)).flatMap(s=>s.destinations.filter(a=>a.id===e));if(o.length===0)return Ue(r,`Unknown Destination in active route nodes: ${e}`);for(let s of o){let a=nb(r,n(s));if(!a.ok)return a}return S(void 0)}function Dre(t,e,r){let n=t.lines.find(s=>s.id===e.lineId);if(!n)return Ue(r,`Unknown line: ${e.lineId}`);if(n.status!=="active")return Ue(r,`TEAM line ${n.id} cannot continue from status ${n.status}`);let i=t.nodes.find(s=>s.id===e.fromNodeId);if(!i)return Ue(r,`Unknown node: ${e.fromNodeId}`);if(i.id!==n.currentNodeId||i.requestId!==n.requestId)return Ue(r,`MOVE ${e.id} source node ${i.id} does not match current node for line ${n.id}`);if(e.toNodeId===e.fromNodeId)return Ue(r,`MOVE ${e.id} cannot be a self-loop`);if(t.nodes.some(s=>s.id===e.toNodeId))return Ue(r,`MOVE ${e.id} target node already exists: ${e.toNodeId}`);let o=US(e);if(!o.ok)return Ue(r,o.error.message);for(let s of e.reachedDestinationIds){let a=Mre(i,s,r);if(!a.ok)return a;let c=nb(r,lg(a.value,{reachedByMoveId:e.id,updatedBy:"TEAM",updatedAt:e.recordedAt}));if(!c.ok)return c}return S(void 0)}function Bre(t,e,r){let n=t.lines.find(s=>s.id===e.lineId);if(!n)return Ue(r,`Unknown line: ${e.lineId}`);let i=t.nodes.find(s=>s.id===e.fromNodeId);if(!i)return Ue(r,`Unknown node: ${e.fromNodeId}`);if(i.requestId!==n.requestId||!n.nodeIds.includes(i.id))return Ue(r,`Node ${i.id} does not belong to line ${n.id}`);if(e.toNodeId===e.fromNodeId)return Ue(r,`HUNSU ${e.id} cannot be a self-loop`);if(t.nodes.some(s=>s.id===e.toNodeId))return Ue(r,`HUNSU ${e.id} target node already exists: ${e.toNodeId}`);let o=Nre(t,e,n,i,r);return o.ok?Ore(t,e,i,r):o}function Nre(t,e,r,n,i){switch(e.target.type){case"line":{let o=t.lines.find(s=>s.id===e.target.id);return o?o.id===e.lineId?S(void 0):Ue(i,`HUNSU target line ${o.id} does not match event line ${e.lineId}`):Ue(i,`Unknown line: ${e.target.id}`)}case"node":{let o=t.nodes.find(s=>s.id===e.target.id);return o?o.requestId===r.requestId&&r.nodeIds.includes(o.id)?S(void 0):Ue(i,`Node ${o.id} does not belong to line ${r.id}`):Ue(i,`Unknown node: ${e.target.id}`)}case"move":{let o=n8(t,r,e.target.id,i);return o.ok?S(void 0):o}case"destination":return n.destinations.some(o=>o.id===e.target.id)?S(void 0):Ue(i,`Unknown Destination in node ${n.id}: ${e.target.id}`)}return Ue(i,`Unsupported HUNSU target: ${JSON.stringify(e.target)}`)}function Ore(t,e,r,n){if(e.changedFiles.length===0)return Ue(n,`HUNSU ${e.id} must include changed runtime files`);let i=new Set;for(let c of e.changedFiles){let u=String(c.path);if(!u.startsWith(".hunsu-request/"))return Ue(n,`HUNSU changed file must be under .hunsu-request: ${u}`);if(i.has(u))return Ue(n,`Duplicate HUNSU changed file: ${u}`);i.add(u)}if(e.teamSnapshot.moveOrdinal!==r.ordinal)return Ue(n,`HUNSU ${e.id} Team snapshot ordinal ${e.teamSnapshot.moveOrdinal} does not match source node ordinal ${r.ordinal}`);let o=new Set(r.destinations.map(c=>String(c.id))),s=new Set(t.destinations.map(c=>String(c.id))),a=new Set;for(let c of e.teamSnapshot.destinations){let u=String(c.id);if(a.has(u))return Ue(n,`Duplicate DestinationId in HUNSU Team snapshot: ${u}`);if(a.add(u),c.requestId!==r.requestId)return Ue(n,`Destination ${c.id} request ${c.requestId} does not match source request ${r.requestId}`);if(!o.has(u)&&s.has(u))return Ue(n,`Duplicate DestinationId in HUNSU Team snapshot: ${u}`)}return S(void 0)}function Mre(t,e,r){let n=t.destinations.find(i=>i.id===e);return n?S(n):Ue(r,`Unknown Destination in node ${t.id}: ${e}`)}function n8(t,e,r,n){let i=t.moves.find(o=>o.id===r);return i?i.lineId===e.id||e.moveIds.includes(i.id)?S(i):Ue(n,`MOVE ${i.id} does not belong to line ${e.id}`):Ue(n,`Unknown MOVE: ${r}`)}function Lre(t,e,r){let n=t.lines.find(o=>o.id===e.fromLineId);if(!n)return Ue(r,`Unknown line: ${e.fromLineId}`);if(e.requestId!==n.requestId)return Ue(r,`LineForkedByHunsu request ${e.requestId} does not match parent line ${n.id}`);let i=t.hunsus.find(o=>o.id===e.hunsuId);if(!i)return Ue(r,`Unknown HUNSU: ${e.hunsuId}`);if(i.lineId!==e.fromLineId)return Ue(r,`HUNSU ${i.id} does not belong to parent line ${e.fromLineId}`);if(i.newLineId!==e.newLineId)return Ue(r,`Line fork ${e.newLineId} does not match HUNSU recorded new line ${i.newLineId}`);if(i.sourceMoveId!==e.fromMoveId)return Ue(r,`Line fork ${e.newLineId} fromMoveId does not match HUNSU source move`);if(i.newTeamName!==e.newTeamName)return Ue(r,`Line fork ${e.newLineId} Team name does not match HUNSU record`);if(e.fromMoveId){let o=n8(t,n,e.fromMoveId,r);if(!o.ok)return o;if(o.value.toNodeId!==i.fromNodeId)return Ue(r,`Line fork source MOVE ${o.value.id} does not end at HUNSU source node ${i.fromNodeId}`)}return t.nodes.some(o=>o.id===i.toNodeId)?S(void 0):Ue(r,`Unknown HUNSU target node: ${i.toNodeId}`)}function Hre(t,e,r){switch(e.owner.type){case"move":return t.moves.some(n=>n.id===e.owner.id)?S(void 0):Ue(r,`Unknown MOVE: ${e.owner.id}`);case"hunsu":return t.hunsus.some(n=>n.id===e.owner.id)?S(void 0):Ue(r,`Unknown HUNSU: ${e.owner.id}`);case"line":return t.lines.some(n=>n.id===e.owner.id)?S(void 0):Ue(r,`Unknown line: ${e.owner.id}`)}}function Ure(t,e){for(let r of t.edges){if(!t.nodes.find(o=>o.id===r.fromNodeId))return Ue(e,`Edge ${r.id} references missing fromNode ${r.fromNodeId}`);if(!t.nodes.find(o=>o.id===r.toNodeId))return Ue(e,`Edge ${r.id} references missing toNode ${r.toNodeId}`);switch(r.type){case"move":{let o=t.moves.find(s=>s.id===r.moveId);if(!o)return Ue(e,`MOVE edge ${r.id} references missing MOVE ${r.moveId}`);if(o.lineId!==r.lineId||o.fromNodeId!==r.fromNodeId||o.toNodeId!==r.toNodeId||o.id!==r.id)return Ue(e,`MOVE edge ${r.id} does not match MOVE ${o.id}`);break}case"hunsu":{let o=t.hunsus.find(s=>s.id===r.hunsuId);if(!o)return Ue(e,`HUNSU edge ${r.id} references missing HUNSU ${r.hunsuId}`);if(o.lineId!==r.lineId||o.fromNodeId!==r.fromNodeId||o.toNodeId!==r.toNodeId||o.id!==r.id)return Ue(e,`HUNSU edge ${r.id} does not match HUNSU ${o.id}`);break}}}return S(void 0)}function nb(t,e){return e.ok?S(void 0):Ue(t,e.error.message)}function Ue(t,e){return ke(`Invalid event stream at event ${t}: ${e}`)}function $re(t,e,r){for(let n of e){let i=Go(t,"DestinationId",n.id,r);if(!i.ok)return i}return S(void 0)}function Go(t,e,r,n){return t.has(r)?ke(`Duplicate ${e} in event stream at event ${n}: ${r}`):(t.add(r),S(void 0))}function Fre(t,e){let r=e.destinations.map(s=>a8(e.request.id,s,"initial-execute-team",e.at)),n=ki(e.harness??Vn()),i={id:e.line.rootNodeId,requestId:e.request.id,lineId:e.line.id,teamName:e.line.teamName,ordinal:0,destinations:r,harness:n,harnessGraph:Bs(n),harnessLock:e.harnessLock?{...e.harnessLock}:void 0,executorPackageBindings:[],resourcePackageBindings:[],artifactActions:[],source:{type:"initial-execute-team",requestId:e.request.id},createdAt:e.at??e.request.createdAt},o=i8({...t,requests:Jr(t.requests,e.request),nodes:Jr(t.nodes,i)},{...e.line,rootNodeId:i.id,currentNodeId:e.line.currentNodeId,nodeIds:e.line.nodeIds});return Ki({...t,requests:Jr(t.requests,e.request),nodes:Jr(t.nodes,i),lines:Jr(t.lines,o)})}function jre(t,e,r,n){let i=a8(e,r,"initial-request",n),o=t.nodes.find(a=>a.id===Os(e)),s=o?{...o,destinations:Jr(o.destinations,i)}:{id:Os(e),requestId:e,ordinal:0,destinations:[i],harness:Vn(),harnessGraph:Bs(Vn()),artifactActions:[],source:{type:"request",requestId:e},createdAt:n};return Ki({...t,nodes:Jr(t.nodes,s)})}function qre(t,e,r,n){let i=ZS(t,e);return Ki({...t,nodes:Jr(t.nodes,{...i,harness:ki(r),harnessGraph:Bs(r),createdAt:i.createdAt??n})})}function Wre(t,e){let r=zn(t,e.lineId),n=Yd(t,e.fromNodeId),i=e.toNodeId,o=er(US(I1(e,{fromNodeId:n.id,toNodeId:i,teamName:e.teamName??r.teamName??n.teamName??Ms(t),ordinal:e.ordinal??n.ordinal+1}))),s=t.nodes.find(l=>l.id===i)??zre(n,o,i),a=er(US(I1(o,{snapshot:o.snapshot??Xre(s)}))),c={id:a.id,type:"move",lineId:a.lineId,fromNodeId:n.id,toNodeId:i,moveId:a.id},u={...t,nodes:Jr(t.nodes,s),moves:Jr(t.moves,a),edges:Jr(t.edges,c)},d=c8(Qre(u,a),a.lineId,i);return Ki(a.outcome==="accident"?Sg(d,a.lineId,k4):d)}function Vre(t,e){zn(t,e.lineId);let r=Yd(t,e.fromNodeId),n=e.toNodeId,i={...e,fromNodeId:r.id,toNodeId:n},o=t.nodes.find(c=>c.id===n)??Kre(r,i,n),s={id:i.id,type:"hunsu",lineId:i.lineId,fromNodeId:r.id,toNodeId:n,hunsuId:i.id},a={...t,nodes:Jr(t.nodes,o),hunsus:Jr(t.hunsus,i),edges:Jr(t.edges,s)};return i.newLineId?Ki(a):Ki(c8(a,i.lineId,n))}function Gre(t,e){let r=zn(t,e.fromLineId),n=t.hunsus.find(c=>c.id===e.hunsuId),i=e.fromMoveId?t.moves.find(c=>c.id===e.fromMoveId):void 0,o=n?.toNodeId??i?.toNodeId??r.currentNodeId,s=e.fromMoveId?r.moveIds.indexOf(e.fromMoveId):-1,a=s>=0?r.moveIds.slice(0,s+1):[];return Ki({...t,lines:Jr(t.lines,{id:e.newLineId,requestId:e.requestId,teamName:e.newTeamName??Ms(t),status:"active",moveIds:a,rootNodeId:r.rootNodeId,currentNodeId:o,nodeIds:[o],parentLineId:e.fromLineId,forkedFromMoveId:e.fromMoveId})})}function i8(t,e){return{...e,teamName:e.teamName??Ms(t)}}function zre(t,e,r){let n=new Set(e.reachedDestinationIds);return{id:r,requestId:t.requestId,lineId:e.lineId,teamName:e.teamName??t.teamName,ordinal:e.ordinal??t.ordinal+1,destinations:t.destinations.map(i=>n.has(i.id)?er(lg(i,{reachedByMoveId:e.id,updatedBy:"TEAM",updatedAt:e.recordedAt})):{...i}),harness:ki(t.harness),harnessGraph:go(t.harnessGraph),harnessLock:t.harnessLock?{...t.harnessLock}:void 0,executorPackageBindings:t.executorPackageBindings?.map(i=>({executorId:i.executorId,lock:{...i.lock}})),resourcePackageBindings:t.resourcePackageBindings?.map(i=>({name:i.name,lock:{...i.lock}})),artifactActions:$1(t.artifactActions),source:{type:"move",moveId:e.id,fromNodeId:t.id},createdAt:e.recordedAt}}function Kre(t,e,r){let n=e.teamSnapshot;return{id:r,requestId:t.requestId,lineId:e.newLineId??e.lineId,teamName:n.teamName,ordinal:n.moveOrdinal,destinations:n.destinations.map(i=>({...i})),harness:ki(n.harness),harnessGraph:go(n.harnessGraph),harnessLock:n.harnessLock?{...n.harnessLock}:void 0,executorPackageBindings:n.executorPackageBindings?.map(i=>({executorId:i.executorId,lock:{...i.lock}})),resourcePackageBindings:n.resourcePackageBindings?.map(i=>({name:i.name,lock:{...i.lock}})),artifactActions:$1(n.artifactActions),source:{type:"hunsu",hunsuId:e.id,fromNodeId:t.id},createdAt:e.recordedAt}}function $1(t){return s8((t??[]).map(o8))}function o8(t){return{...t,env:t.env?Object.fromEntries(Object.entries(t.env).map(([e,r])=>[e,{...r}])):void 0,runner:{...t.runner},aliases:t.aliases?Object.fromEntries(Object.entries(t.aliases).map(([e,r])=>[e,{...r}])):void 0,evidence:t.evidence?{...t.evidence,paths:t.evidence.paths?.slice()}:void 0}}function s8(t){return t.slice().sort((e,r)=>e.displayOrder-r.displayOrder||String(e.id).localeCompare(String(r.id)))}function Jre(t){let e=new Set,r=[];for(let n of t)e.has(n.id)||(e.add(n.id),r.push(o8(n)));return r}function Xre(t){return{teamName:t.teamName??er(un("Team")),moveOrdinal:t.ordinal,destinations:t.destinations.map(e=>({...e})),harness:ki(t.harness),harnessGraph:go(t.harnessGraph),harnessLock:t.harnessLock?{...t.harnessLock}:void 0,executorPackageBindings:t.executorPackageBindings?.map(e=>({executorId:e.executorId,lock:{...e.lock}})),resourcePackageBindings:t.resourcePackageBindings?.map(e=>({name:e.name,lock:{...e.lock}})),artifactActions:$1(t.artifactActions)}}function a8(t,e,r,n){return E4(t,e,r,n)}function Yre(t,e,r){return t.map(n=>n.id===e?er(r(n)):{...n})}function H1(t,e,r){let n=new Set(t.lines.map(o=>o.currentNodeId)),i=t.nodes.map(o=>!n.has(o.id)||!o.destinations.some(s=>s.id===e)?o:{...o,destinations:Yre(o.destinations,e,r)});return Ki({...t,nodes:i})}function Sg(t,e,r){return zn(t,e),Ki({...t,lines:t.lines.map(n=>n.id===e?er(r(n)):n)})}function Qre(t,e){return zn(t,e.lineId),{...t,lines:t.lines.map(r=>r.id===e.lineId?{...r,moveIds:N1([...r.moveIds,e.id])}:r)}}function c8(t,e,r){return zn(t,e),{...t,lines:t.lines.map(n=>n.id===e?{...n,currentNodeId:r,nodeIds:er(po(N1([...n.nodeIds,r]),"nodeIds"))}:n)}}function Ki(t){let e=t.requests.flatMap(i=>{let o=Zre(t,i.id);return o?[o]:[]}),r=e.flatMap(i=>i.destinations),n=e.flatMap(i=>i.artifactActions);return{...t,destinations:r.map(i=>({...i})),artifactActions:s8(Jre(n))}}function Zre(t,e){let r=t.lines.filter(i=>i.requestId===e&&i.status!=="abandoned"),n=r.findLast(i=>i.status==="active")??r.at(-1);return n?t.nodes.find(i=>i.id===n.currentNodeId):t.nodes.find(i=>i.id===Os(e))}function ene(t,e=cu()){let r=rne(t);if(!r.ok)return r;let n=nne(r.value,e);if(!n.ok)return n;try{return S(tne(n.value,e))}catch(i){return oe(rg(i))}}function tne(t,e=cu()){switch(t.type){case"RegisterHunsuOrigin":return[{type:"HunsuOriginRegistered",origin:{...t.origin},at:t.at}];case"CreateInitialTeam":{xg(t.destinations,"CreateInitialTeam requires at least one Destination");let r=t.harness?ki(t.harness):Vn(),n=Os(t.requestId);return[{type:"InitialTeamCreated",request:{id:t.requestId,title:t.title,goal:t.goal,createdBy:"SYSTEM",createdAt:t.at},line:{id:t.lineId,requestId:t.requestId,teamName:t.teamName??Ms(e),status:"active",moveIds:[],rootNodeId:n,currentNodeId:n,nodeIds:[n]},destinations:t.destinations,harness:r,harnessLock:t.harnessLock,at:t.at}]}case"StartLine":{G4(e,t.requestId);let r=ZS(e,t.requestId),n=t.teamName??Ms(e);return[{type:"LineStarted",line:{id:t.lineId,requestId:t.requestId,teamName:n,status:"active",moveIds:[],rootNodeId:r.id,currentNodeId:r.id,nodeIds:[r.id]}}]}case"PauseLine":return zn(e,t.lineId),[{type:"LinePaused",lineId:t.lineId,at:t.at}];case"ResumeLine":return zn(e,t.lineId),[{type:"LineResumed",lineId:t.lineId,at:t.at}];case"AcceptLine":return zn(e,t.lineId),[{type:"LineAccepted",lineId:t.lineId,reason:t.reason,at:t.at}];case"RejectLine":return zn(e,t.lineId),[{type:"LineRejected",lineId:t.lineId,reason:t.reason,at:t.at}];case"ClaimDestination":return K4(e,t.destinationId),[{type:"DestinationClaimed",destinationId:t.destinationId,actor:t.actor,at:t.at}];case"StartDestinationWork":return tb(e,t.destinationId),[{type:"DestinationWorkStarted",destinationId:t.destinationId,actor:t.actor,at:t.at}];case"ReportDestinationBlocked":return J4(e,t.destinationId),[{type:"DestinationBlocked",destinationId:t.destinationId,reason:t.reason,actor:t.actor,at:t.at}];case"RecordMove":{let r=zn(e,t.lineId);O1(r);let n=eb(e,r);Q4(t.reachedDestinationIds,"MOVE must reach exactly one Destination");for(let s of t.reachedDestinationIds)X4(n,s);let i=QS(e);return[{type:"MoveRecorded",move:er(b1({id:t.moveId,lineId:t.lineId,fromNodeId:n.id,toNodeId:i,executeId:t.executeId,conversationRef:t.conversationRef,worktree:t.worktree,summary:t.summary,commit:t.commit,reachedDestinationIds:t.reachedDestinationIds,evidence:t.evidence,risks:t.risks,recordedBy:"SYSTEM",recordedAt:t.at}))}]}case"RecordAccident":{let r=zn(e,t.lineId);O1(r);let n=eb(e,r);xg(t.evidence,"A ACCIDENT must include evidence"),Z4(t.failureReason,"A ACCIDENT must include a failure reason");let i=QS(e);return[{type:"MoveRecorded",move:er(w1({id:t.moveId,lineId:t.lineId,fromNodeId:n.id,toNodeId:i,executeId:t.executeId,conversationRef:t.conversationRef,worktree:t.worktree,failureReason:t.failureReason,summary:t.summary,commit:t.commit,evidence:t.evidence,risks:t.risks,recordedBy:"SYSTEM",recordedAt:t.at}))}]}case"AttachMoveEvidence":return M1(e,t.moveId),[{type:"ArtifactRecorded",artifact:t.artifact,at:t.at}];case"ConfirmHunsuDraft":{let r=t.draft,n=zn(e,r.sourceLineId),i=Yd(e,r.sourceNodeId);if(i.requestId!==n.requestId)throw new fr(`Node ${i.id} does not belong to line ${n.id}`);return r.sourceMoveId&&M1(e,r.sourceMoveId),xg(r.changedFiles,"A confirmed HUNSU Draft must include at least one changed runtime file"),[one(r.hunsuId,r.sourceLineId,i.id,QS(e),r.target,r.summary,r.teamSnapshot,r.changedFiles,t.at,{hunsuDraftId:r.id,conversationRef:r.conversationRef,newLineId:r.newLineId,sourceMoveId:r.sourceMoveId,newTeamName:r.newTeamName}),{type:"LineForkedByHunsu",hunsuId:r.hunsuId,fromLineId:r.sourceLineId,newLineId:r.newLineId,newTeamName:r.newTeamName,fromMoveId:r.sourceMoveId,requestId:i.requestId,at:t.at}]}case"CreateSkillDraft":{let r=zn(e,t.lineId),n=eb(e,r);return[{type:"SkillDraftCreated",draft:A4({id:t.draftId,name:t.name,sourcePath:t.sourcePath,draftPath:t.draftPath,createdFromNodeId:n.id,createdAt:t.at})}]}case"DiscardSkillDraft":{let r=z4(e,t.draftId);if(r.status!=="draft")throw new fr(`Skill Draft ${t.draftId} cannot be discarded from status ${r.status}`);return[{type:"SkillDraftDiscarded",draftId:t.draftId,at:t.at}]}case"RecordArtifact":return[{type:"ArtifactRecorded",artifact:t.artifact,at:t.at}]}}function bg(t,e){let r=uu(t);if(!r.ok)return r;let n=r.value,i=ene(e,n);return i.ok?S([...t,...i.value]):i}function rne(t){return W4(t,ig)}function ib(t){return V4(t,ig)}function nne(t,e){let r=ine(t,e);if(!r.ok)return r;switch(t.type){case"RegisterHunsuOrigin":case"CreateInitialTeam":return S(t);case"RecordArtifact":return ai([Ane(e,t.artifact)],t);case"StartLine":return ai([pne(e,t.requestId),xne(e,t.requestId)],t);case"PauseLine":return ai([hne(e,t.lineId)],t);case"ResumeLine":return ai([gne(e,t.lineId)],t);case"AcceptLine":return ai([yne(e,t.lineId)],t);case"RejectLine":return ai([vne(e,t.lineId)],t);case"ClaimDestination":return ai([wne(e,t.destinationId)],t);case"StartDestinationWork":return ai([bne(e,t.destinationId)],t);case"ReportDestinationBlocked":return ai([Ine(e,t.destinationId)],t);case"RecordMove":return ai([u8(e,t.lineId),j1(e,t.lineId),...kne(e,t.lineId,t.moveId,t.reachedDestinationIds)],t);case"RecordAccident":return ai([u8(e,t.lineId),j1(e,t.lineId)],t);case"AttachMoveEvidence":return ai([d8(e,t.moveId),Cne(t.artifact,t.moveId)],t);case"ConfirmHunsuDraft":return ai([l8(e,t.draft.sourceNodeId,t.draft.sourceLineId),Pne(e,t.draft.sourceLineId,t.draft.target),...t.draft.sourceMoveId?[f8(e,t.draft.sourceMoveId,t.draft.sourceLineId)]:[]],t);case"CreateSkillDraft":return ai([j1(e,t.lineId)],t);case"DiscardSkillDraft":return ai([_ne(e,t.draftId,"discarded")],t)}}function ine(t,e){switch(t.type){case"CreateInitialTeam":{let r=sne(e,t.requestId);if(!r.ok)return r;let n=F1(e,t.lineId);return n.ok?lne(e,t.destinations.map(i=>i.id)):n}case"StartLine":return F1(e,t.lineId);case"RecordMove":case"RecordAccident":return ane(e,t.moveId);case"AttachMoveEvidence":case"RecordArtifact":return dne(e,t.artifact.id);case"CreateSkillDraft":return une(e,t.draftId);case"ConfirmHunsuDraft":{let r=cne(e,t.draft.hunsuId);return r.ok?F1(e,t.draft.newLineId):r}case"RegisterHunsuOrigin":case"PauseLine":case"ResumeLine":case"AcceptLine":case"RejectLine":case"ClaimDestination":case"StartDestinationWork":case"ReportDestinationBlocked":case"DiscardSkillDraft":return S(void 0)}}function ai(t,e){let r=t.find(n=>!n.ok);return r&&!r.ok?oe(r.error):S(e)}function one(t,e,r,n,i,o,s,a,c,u={}){return xg(a,"A HUNSU must include at least one changed runtime file"),{type:"HunsuRecorded",hunsu:{id:t,...u,lineId:e,fromNodeId:r,toNodeId:n,target:i,summary:o,teamSnapshot:s,changedFiles:a,recordedBy:"DIRECTOR",recordedAt:c}}}function Na(t,e){return e.ok?S(t):ke(e.error.message)}function sne(t,e){return t.requests.some(r=>r.id===e)?ke(`Duplicate RequestId: ${e}`):S(void 0)}function F1(t,e){return t.lines.some(r=>r.id===e)?ke(`Duplicate LineId: ${e}`):S(void 0)}function ane(t,e){return t.moves.some(r=>r.id===e)?ke(`Duplicate MoveId: ${e}`):S(void 0)}function cne(t,e){return t.hunsus.some(r=>r.id===e)?ke(`Duplicate HunsuId: ${e}`):S(void 0)}function une(t,e){return t.skillDrafts.some(r=>r.id===e)?ke(`Duplicate SkillDraftId: ${e}`):S(void 0)}function dne(t,e){return t.artifacts.some(r=>r.id===e)?ke(`Duplicate ArtifactId: ${e}`):S(void 0)}function lne(t,e){let r=new Set,n=fne(t);for(let i of e){if(r.has(i))return ke(`Duplicate DestinationId in command: ${i}`);if(n.has(i))return ke(`Duplicate DestinationId: ${i}`);r.add(i)}return S(void 0)}function fne(t){return new Set([...t.destinations.map(e=>e.id),...t.nodes.flatMap(e=>e.destinations.map(r=>r.id))])}function pne(t,e){return t.requests.some(r=>r.id===e)?S(void 0):ke(`Unknown request: ${e}`)}function mne(t,e){return zo(t,e)}function hne(t,e){let r=zo(t,e);return r.ok?Na(r.value,fg(r.value)):r}function gne(t,e){let r=zo(t,e);return r.ok?Na(r.value,pg(r.value)):r}function yne(t,e){let r=zo(t,e);return r.ok?Na(r.value,mg(r.value)):r}function vne(t,e){let r=zo(t,e);return r.ok?Na(r.value,hg(r.value)):r}function xne(t,e){return q1(t,Os(e))}function d8(t,e){return p8(t,e)}function Sne(t,e){return Tne(t,e)}function bne(t,e){let r=V1(t,e);return r.ok?Na(r.value,ug(r.value,{claimedBy:"validation",updatedBy:"TEAM"})):r}function j1(t,e){return W1(t,e)}function u8(t,e){let r=zo(t,e);return r.ok?Na(r.value,R4(r.value)):r}function wne(t,e){let r=V1(t,e);return r.ok?Na(r.value,cg(r.value,{claimedBy:"validation",updatedBy:"TEAM"})):r}function Ine(t,e){let r=V1(t,e);return r.ok?Na(r.value,dg(r.value,{blockedReason:"validation",updatedBy:"TEAM"})):r}function Ene(t,e,r){let n=W1(t,e);return n.ok?m8(n.value,r):n}function kne(t,e,r,n){let i=W1(t,e);return i.ok?n.length!==1?[ke("MOVE must reach exactly one Destination")]:n.map(o=>Rne(i.value,o,r)):[i]}function Rne(t,e,r){let n=m8(t,e);return n.ok?Na(n.value,lg(n.value,{reachedByMoveId:r,updatedBy:"TEAM"})):n}function Ane(t,e){switch(e.owner.type){case"move":return d8(t,e.owner.id);case"hunsu":return Sne(t,e.owner.id);case"line":return mne(t,e.owner.id)}}function Cne(t,e){return t.owner.type!=="move"||t.owner.id!==e?ke(`AttachMoveEvidence artifact owner must be move ${e}`):S(void 0)}function l8(t,e,r){let n=zo(t,r);if(!n.ok)return n;let i=q1(t,e);return i.ok?n.value.nodeIds.includes(i.value.id)?i:ke(`Node ${i.value.id} does not belong to line ${n.value.id}`):i}function f8(t,e,r){let n=zo(t,r);if(!n.ok)return n;let i=p8(t,e);return i.ok&&i.value.lineId!==n.value.id&&!n.value.moveIds.includes(i.value.id)?ke(`MOVE ${i.value.id} does not belong to line ${n.value.id}`):i}function Pne(t,e,r){switch(r.type){case"line":{let n=zo(t,e);if(!n.ok)return n;let i=zo(t,r.id);return i.ok?i.value.id===n.value.id?S(n.value):ke(`HUNSU target line ${i.value.id} does not match command line ${n.value.id}`):i}case"node":return l8(t,r.id,e);case"move":return f8(t,r.id,e);case"destination":return Ene(t,e,r.id)}}function _ne(t,e,r){let n=Dne(t,e);return n.ok?n.value.status!=="draft"?ke(`Skill Draft ${e} cannot be ${r} from status ${n.value.status}`):S(n.value):n}function zo(t,e){let r=t.lines.find(n=>n.id===e);return r?S(r):ke(`Unknown line: ${e}`)}function q1(t,e){let r=t.nodes.find(n=>n.id===e);return r?S(r):ke(`Unknown node: ${e}`)}function W1(t,e){let r=zo(t,e);return r.ok?q1(t,r.value.currentNodeId):r}function p8(t,e){let r=t.moves.find(n=>n.id===e);return r?S(r):ke(`Unknown MOVE: ${e}`)}function Tne(t,e){let r=t.hunsus.find(n=>n.id===e);return r?S(r):ke(`Unknown HUNSU: ${e}`)}function Dne(t,e){let r=t.skillDrafts.find(n=>n.id===e);return r?S(r):ke(`Unknown Skill Draft: ${e}`)}function V1(t,e){let r=t.destinations.find(n=>n.id===e);return r?S(r):ke(`Unknown Destination: ${e}`)}function m8(t,e){let r=t.destinations.find(n=>n.id===e);return r?S(r):ke(`Unknown Destination in node ${t.id}: ${e}`)}var h8="hunsu.connect.enrollment.v1";var ip="hunsu.connect.signal-frame.v1",g8="hunsu.connect.control-frame.v1";function y8(t,e="publicJwk"){return!x8(t)||!S8(t,["kty","crv","x","y"])?Oa(e,"P-256 public JWK must contain only kty, crv, x, and y."):t.kty!=="EC"||t.crv!=="P-256"?Oa(e,"Public JWK must use EC P-256."):!ob(t.x,32,32)||!ob(t.y,32,32)?Oa(e,"P-256 public JWK coordinates must be 32-byte base64url values."):{ok:!0,value:{kty:"EC",crv:"P-256",x:t.x,y:t.y}}}function v8(t){return!x8(t)||!S8(t,["schema","sessionId","sequence","iv","ciphertext"])?Oa("$signal","Connect signal frame has unknown or missing fields."):t.schema!==ip?Oa("schema","Connect signal frame schema is not supported."):typeof t.sessionId!="string"||!/^cs_[A-Za-z0-9_-]{20,125}$/u.test(t.sessionId)?Oa("sessionId","Connect session ID is invalid."):!Number.isSafeInteger(t.sequence)||Number(t.sequence)<1?Oa("sequence","Connect signal sequence must be a positive safe integer starting at 1."):ob(t.iv,12,12)?ob(t.ciphertext,16,65536)?{ok:!0,value:{schema:ip,sessionId:t.sessionId,sequence:Number(t.sequence),iv:t.iv,ciphertext:t.ciphertext}}:Oa("ciphertext","Connect signal ciphertext must contain 16-65536 bytes of base64url data."):Oa("iv","Connect signal IV must be exactly 12 bytes of base64url data.")}function Oa(t,e){return{ok:!1,error:{code:"INVALID_CONNECT_WIRE",field:t,message:e}}}function x8(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function S8(t,e){let r=Object.keys(t);return r.length===e.length&&r.every(n=>e.includes(n))}function ob(t,e,r){if(typeof t!="string"||!/^[A-Za-z0-9_-]+$/u.test(t)||t.length%4===1)return!1;let i=Math.floor(t.length*3/4);return i>=e&&i<=r}var La="hunsu-peer-v1",z1="hunsu.control.v1",K1="hunsu.stream.v1",b8="stun:stun.cloudflare.com:3478",w8=12*6e4,wg=64*1024,h2e=32*1024,I8=32,Bne=["health","bridge.status","connection.status","provider.inventory","modelAlias.validate","modelAlias.resolve","roadmap.registry.list","roadmap.registry.remove","roadmap.open","roadmap.port.inspect","roadmap.port.apply","roadmap.create","roadmap.board","roadmap.worktree","roadmap.skills","roadmap.commands","execute.start","execute.pause","execute.resume","execute.stop","execute.completeMove","execute.status","artifactAction.list","artifactAction.runs","artifactAction.start","artifactAction.stop","moveFile.tree","moveFile.blob","moveFile.diff","hunsuDraft.list","hunsuDraft.start","hunsuDraft.get","hunsuDraft.message","hunsuDraft.diffArtifact.create","hunsuDraft.diffArtifact.get","hunsuDraft.approve","hunsuDraft.discard","line.accept","line.reject","agentSession.list","agentSession.get","agentSession.events","live.events"];var Qd=256,Nne=1024,One=64*1024,Mne=2*1024,Lne=new Set(["projectPath","repositoryPath","repositoryRoot","worktreePath","runtimePath","cwd"]);function E8(t){let e=["remote.access"];return(t==="execute.start"||t==="execute.pause"||t==="execute.resume"||t==="execute.stop"||t==="execute.completeMove")&&e.push("execute.start"),(t==="artifactAction.start"||t==="artifactAction.stop")&&e.push("artifactAction.run"),(t==="artifactAction.list"||t==="artifactAction.runs"||t==="artifactAction.start"||t==="artifactAction.stop")&&e.push("env.read","hostAlias.expose"),e}function k8(t){let e=ab(t,"$signalPlaintext");if(!e.ok)return e;if(e.value.type==="peer.offer"||e.value.type==="peer.answer"){let r=Ma(e.value,["type","sdp"],"$signalPlaintext");if(!r.ok)return r;let n=Ri(e.value.sdp,"sdp",One,!1);return n.ok?S({type:e.value.type,sdp:n.value}):n}if(e.value.type==="peer.ice"){let r=Ma(e.value,["type","candidate","sdpMid","sdpMLineIndex","usernameFragment"],"$signalPlaintext");if(!r.ok)return r;let n=Ri(e.value.candidate,"candidate",Mne),i=G1(e.value.sdpMid,"sdpMid",64),o=G1(e.value.usernameFragment,"usernameFragment",256);return n.ok?i.ok?o.ok?e.value.sdpMLineIndex!==void 0&&(!Number.isInteger(e.value.sdpMLineIndex)||Number(e.value.sdpMLineIndex)<0||Number(e.value.sdpMLineIndex)>8)?Tn("sdpMLineIndex","ICE media line index is invalid."):S({type:"peer.ice",candidate:n.value,...i.value?{sdpMid:i.value}:{},...e.value.sdpMLineIndex===void 0?{}:{sdpMLineIndex:Number(e.value.sdpMLineIndex)},...o.value?{usernameFragment:o.value}:{}}):o:i:n}if(e.value.type==="peer.close"){let r=Ma(e.value,["type","reason"],"$signalPlaintext");return r.ok?e.value.reason==="complete"||e.value.reason==="canceled"||e.value.reason==="expired"||e.value.reason==="failed"?S({type:"peer.close",reason:e.value.reason}):Tn("reason","Peer close reason is invalid."):r}return Tn("type","Peer signaling message type is not supported.")}function R8(t){let e=ab(t,"$hello");if(!e.ok)return e;let r=Ma(e.value,["type","protocolVersion","sessionId","ticket","browserAgreementPublicJwk","browserNonce"],"$hello");if(!r.ok)return r;if(e.value.type!=="peer.client-hello"||e.value.protocolVersion!==La)return Tn("type","Peer client hello version is not supported.");let n=Ri(e.value.sessionId,"sessionId",Qd),i=Ri(e.value.ticket,"ticket",8192),o=Une(e.value.browserAgreementPublicJwk,"browserAgreementPublicJwk"),s=sb(e.value.browserNonce,"browserNonce",24,64);return n.ok?i.ok?o.ok?s.ok?S({type:"peer.client-hello",protocolVersion:La,sessionId:n.value,ticket:i.value,browserAgreementPublicJwk:o.value,browserNonce:s.value}):s:o:i:n}function A8(t){let e=C8(t,"$message",new WeakSet);if(!e.ok)return e;let r=ab(t,"$message");if(!r.ok)return r;let n=Ri(r.value.type,"type",64),i=Ri(r.value.sessionId,"sessionId",Qd);if(!n.ok)return n;if(!i.ok)return i;if(n.value==="session.confirm"){let o=Ma(r.value,["type","sessionId","transcriptHash"],"$message");if(!o.ok)return o;let s=sb(r.value.transcriptHash,"transcriptHash",32,32);return s.ok?S({type:"session.confirm",sessionId:i.value,transcriptHash:s.value}):s}if(n.value==="command.request"){let o=Ma(r.value,["type","sessionId","requestId","workspaceId","deadline","command","payload"],"$message");if(!o.ok)return o;let s=Ri(r.value.requestId,"requestId",Qd),a=Ri(r.value.workspaceId,"workspaceId",Qd),c=$ne(r.value.deadline,"deadline");return s.ok?a.ok?c.ok?Hne(r.value.command)?S({type:"command.request",sessionId:i.value,requestId:s.value,workspaceId:a.value,deadline:c.value,command:r.value.command,...r.value.payload===void 0?{}:{payload:r.value.payload}}):Tn("command","Remote command name is not supported."):c:a:s}if(n.value==="stream.cancel"){let o=Ma(r.value,["type","sessionId","requestId","streamId","workspaceId","reason"],"$message");if(!o.ok)return o;let s=Ri(r.value.requestId,"requestId",Qd),a=Ri(r.value.streamId,"streamId",Qd),c=Ri(r.value.workspaceId,"workspaceId",Qd),u=G1(r.value.reason,"reason",Nne);return s.ok?a.ok?c.ok?u.ok?S({type:"stream.cancel",sessionId:i.value,requestId:s.value,streamId:a.value,workspaceId:c.value,...u.value?{reason:u.value}:{}}):u:c:a:s}if(n.value==="session.close"){let o=Ma(r.value,["type","sessionId","reason"],"$message");return o.ok?r.value.reason==="lease_expired"||r.value.reason==="replaced"||r.value.reason==="canceled"||r.value.reason==="protocol_error"?S({type:"session.close",sessionId:i.value,reason:r.value.reason}):Tn("reason","Session close reason is invalid."):o}return Tn("type","Inbound remote control message is not supported.")}function Hne(t){return typeof t=="string"&&Bne.includes(t)}function Une(t,e){let r=ab(t,e);if(!r.ok)return r;let n=Ma(r.value,["kty","crv","x","y","key_ops","ext"],e);if(!n.ok)return n;if(r.value.kty!=="EC"||r.value.crv!=="P-256"||r.value.d!==void 0)return Tn(e,"Peer public key must be a public P-256 EC key.");let i=sb(r.value.x,`${e}.x`,32,32),o=sb(r.value.y,`${e}.y`,32,32);return i.ok?o.ok?S({kty:"EC",crv:"P-256",x:i.value,y:o.value,ext:!0}):o:i}function C8(t,e,r){if(typeof t!="object"||t===null)return S(!0);if(r.has(t))return Tn(e,"Remote peer message must not be cyclic.");r.add(t);for(let[n,i]of Object.entries(t)){if(Lne.has(n))return Tn(`${e}.${n}`,"Remote peer messages cannot contain canonical local paths.");let o=C8(i,`${e}.${n}`,r);if(!o.ok)return o}return r.delete(t),S(!0)}function ab(t,e){return typeof t=="object"&&t!==null&&!Array.isArray(t)?S(t):Tn(e,"Value must be an object.")}function Ri(t,e,r,n=!0){if(typeof t!="string")return Tn(e,"Value must be a string.");let i=n?t.trim():t;return i&&i.length<=r&&!/[\u0000\u000b\u000c\u007f]/u.test(i)?S(i):Tn(e,`Value must contain 1-${r} allowed characters.`)}function G1(t,e,r){return t===void 0?S(void 0):Ri(t,e,r)}function $ne(t,e){let r=Ri(t,e,64);return r.ok&&Number.isFinite(Date.parse(r.value))?r:Tn(e,"Value must be an ISO timestamp.")}function sb(t,e,r,n){let i=Math.ceil(n*4/3),o=Ri(t,e,i);if(!o.ok)return o;if(!/^[A-Za-z0-9_-]+$/u.test(o.value)||o.value.length%4===1)return Tn(e,"Value must be unpadded base64url.");let s=Math.floor(o.value.length*3/4);return s>=r&&s<=n?S(o.value):Tn(e,"Decoded value has an invalid size.")}function Ma(t,e,r){let n=new Set(e),i=Object.keys(t).find(o=>!n.has(o));return i?Tn(`${r}.${i}`,"Field is not allowed."):S(!0)}function Tn(t,e){return oe({code:"INVALID_REMOTE_PEER_WIRE",field:t,message:e})}import{execFile as Vce,spawn as Gce}from"node:child_process";import{existsSync as Qt,mkdirSync as bo,mkdtempSync as zce,readFileSync as Vs,readdirSync as c0,realpathSync as Kce,renameSync as Jce,rmSync as u0,statSync as Tu,writeFileSync as es}from"node:fs";import{createHash as ci,randomBytes as Xce,timingSafeEqual as Yce}from"node:crypto";import{homedir as qs,tmpdir as uw}from"node:os";import{basename as ts,dirname as Ci,isAbsolute as i0,join as at,normalize as aP,relative as cP,resolve as Yn}from"node:path";import{fileURLToPath as Qce}from"node:url";import{promisify as Zce}from"node:util";import{delimiter as Fne,dirname as jne,join as qne,resolve as Wne}from"node:path";import{fileURLToPath as Vne}from"node:url";import{spawn as Gne}from"node:child_process";import{createInterface as zne}from"node:readline";import{Buffer as Kne}from"node:buffer";var M8=_S,Jne={type:"object",properties:{executorId:{type:"string"},goal:{type:"string"}},required:["executorId","goal"],additionalProperties:!1},Xne={type:["object","null"],properties:{executorId:{type:"string"},prompt:{type:"string"}},required:["executorId","prompt"],additionalProperties:!1},Yne={type:["string","array"],items:{type:"string"}},Qne={type:"object",properties:{kind:{type:"string",enum:["goal"]},stage:{type:"string",enum:["needs_evaluation"]},id:{type:"string"},assignee:Jne,evaluator:Xne,remainingAttempts:{type:"integer",minimum:0},requires:Yne},required:["kind","stage","id","assignee","evaluator","remainingAttempts","requires"],additionalProperties:!1},P8={type:"object",properties:{kind:{type:"string",enum:["queue"]},id:{type:"string"},items:{type:"array",items:Qne}},required:["kind","id","items"],additionalProperties:!1},L8={type:"object",properties:{type:{type:"string",enum:["pass","fail"]},summary:{type:"string"},reason:{type:"string"},feedback:{type:"string"},nextGoal:{type:"string"},evidence:{type:"array",items:{type:"string"}}},required:["type","summary","reason","feedback","nextGoal","evidence"],additionalProperties:!1},Zne={sandboxMode:"workspace-write",approvalPolicy:"never",approvalsReviewer:"user",networkAccessEnabled:!1},J1=class{subscribers=new Map;push(e){let r=this.subscribers.get(e.runId);if(r)for(let n of r)n.closed||(n.queue.push(e),n.resolve?.(),n.resolve=void 0)}close(e){let r=this.subscribers.get(e);if(r)for(let n of r)n.closed=!0,n.resolve?.(),n.resolve=void 0}async*events(e){let r={queue:[],closed:!1},n=this.subscribers.get(e);n||(n=new Set,this.subscribers.set(e,n)),n.add(r);try{for(;;){let i=r.queue.shift();if(i){yield i;continue}if(r.closed)return;await new Promise(o=>{r.resolve=o})}}finally{n.delete(r),n.size===0&&this.subscribers.delete(e)}}},Ig=class extends Error{code;data;constructor(e,r,n){super(r),this.code=e,this.data=n}},X1=class{child;stdout;messageHandlers=new Set;errorHandlers=new Set;closeHandlers=new Set;constructor(e){this.child=Gne(e.command,e.args,{cwd:e.cwd,env:kie(e.environment)}),this.stdout=zne({input:this.child.stdout}),this.stdout.on("line",r=>this.handleLine(r)),this.child.stderr.on("data",()=>{}),this.child.once("error",r=>this.emitError(r)),this.child.once("close",()=>this.emitClose())}send(e){if(this.child.stdin.destroyed||!this.child.stdin.writable)throw new Error("Codex app-server stdin is closed");this.child.stdin.write(`${JSON.stringify(e)}
144
+ `)}close(){this.stdout.close(),this.child.killed||this.child.kill("SIGTERM")}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onError(e){return this.errorHandlers.add(e),()=>this.errorHandlers.delete(e)}onClose(e){return this.closeHandlers.add(e),()=>this.closeHandlers.delete(e)}handleLine(e){if(e.trim())try{let r=JSON.parse(e);for(let n of this.messageHandlers)n(r)}catch(r){this.emitError(new Error(`Invalid Codex app-server JSON-RPC message: ${r instanceof Error?r.message:String(r)}`))}}emitError(e){for(let r of this.errorHandlers)r(e)}emitClose(){for(let e of this.closeHandlers)e()}},Y1=class{requestTimeoutMs;transportFactory;clientInfo;serverRequestHandler;transport;startPromise;initialized;nextId=1;pending=new Map;notificationHandlers=new Set;constructor(e={}){let r=e.environment??{},n=e.command??"codex",i=e.args??["app-server","--stdio"];this.requestTimeoutMs=e.requestTimeoutMs??6e4,this.clientInfo=e.clientInfo??{name:"hunsu-studio",title:"Hunsu Studio",version:"0.1.0"},this.transportFactory=e.transportFactory??(()=>new X1({command:n,args:i,environment:r,cwd:e.cwd})),this.serverRequestHandler=e.handleServerRequest??H8}setServerRequestHandler(e){this.serverRequestHandler=e}async initialize(){return await this.ensureStarted(),this.initialized}async request(e,r,n={}){return await this.ensureStarted(),this.requestRaw(e,r,n.timeoutMs)}notify(e,r){this.transport?.send(r===void 0?{method:e}:{method:e,params:r})}onNotification(e){return this.notificationHandlers.add(e),()=>this.notificationHandlers.delete(e)}close(){this.disposeTransport(new Error("Codex app-server client closed"),!0)}async ensureStarted(){if(!(this.transport&&this.initialized)){if(this.startPromise)return this.startPromise;this.startPromise=this.start();try{await this.startPromise}finally{this.startPromise=void 0}}}async start(){let e=this.transportFactory();this.transport=e,e.onMessage(r=>this.handleMessage(r)),e.onError(r=>this.disposeTransport(r,!0)),e.onClose(()=>{this.disposeTransport(new Error("Codex app-server process exited"),!1)}),this.initialized=await this.requestRaw("initialize",{clientInfo:this.clientInfo,capabilities:null},this.requestTimeoutMs),this.notify("initialized")}requestRaw(e,r,n=this.requestTimeoutMs){let i=this.transport;if(!i)throw new Error("Codex app-server transport is not started");let o=`hunsu-${this.nextId++}`;return new Promise((s,a)=>{let c=setTimeout(()=>{this.pending.delete(o);let u=new Error(`Codex app-server request timed out: ${e}`);a(u),this.disposeTransport(u,!0)},n);this.pending.set(o,{method:e,resolve:s,reject:a,timer:c});try{i.send(r===void 0?{id:o,method:e}:{id:o,method:e,params:r})}catch(u){clearTimeout(c),this.pending.delete(o),a(u instanceof Error?u:new Error(String(u)))}})}handleMessage(e){if(e.id!==void 0&&(e.result!==void 0||e.error!==void 0)&&!e.method){this.handleResponse(e);return}if(e.id!==void 0&&typeof e.method=="string"){this.handleServerRequest(e);return}if(typeof e.method=="string")for(let r of this.notificationHandlers)r(e)}handleResponse(e){let r=this.pending.get(e.id);if(r){if(clearTimeout(r.timer),this.pending.delete(e.id),e.error){r.reject(new Error(`Codex app-server ${r.method} failed: ${e.error.message}`));return}r.resolve(e.result)}}async handleServerRequest(e){try{let r=await this.serverRequestHandler(e);this.transport?.send({id:e.id,result:r})}catch(r){let n=r instanceof Ig?r:new Ig(-32603,r instanceof Error?r.message:String(r));this.transport?.send({id:e.id,error:{code:n.code,message:n.message,data:n.data}})}}rejectPending(e){for(let[r,n]of this.pending)clearTimeout(n.timer),n.reject(e),this.pending.delete(r)}disposeTransport(e,r){let n=this.transport;this.transport=void 0,this.initialized=void 0,this.rejectPending(e),r&&n?.close()}},Q1=class{eventBus=new J1;client;threadOptions;activeByRunId=new Map;activeByThreadId=new Map;activeByTurnId=new Map;constructor(e={}){this.threadOptions={...Zne,...e.threadOptions},this.client=e.client??new Y1({...e.clientOptions,environment:e.clientOptions?.environment??e.environment??{}}),this.client.setServerRequestHandler(r=>this.handleServerRequest(r)),this.client.onNotification(r=>this.handleNotification(r))}async runTeamPlanning(e){let r=N8(e);return this.executeTurn(e,r,B8(e),void 0,!0,P8)}async runMemberPath(e){let r=V8(e,e.memberPath.executorId);return this.executeTurn(e,r,pie(e),void 0,!1,e.outputSchema)}async runMoveFinalizer(e){let r=Iie();return this.executeTurn(e,r,mie(e),void 0,!0)}async runHunsuDraftTurn(e){let r=O8(e.manager);return this.executeTurn(e,r,hie(e),e.providerThreadId,!1,void 0,{reusePreparedThread:!0})}async prepareHunsuDraftSession(e){let r=O8(e.manager),n=await this.prepareThread(e,r,e.providerThreadId,!1);return{runId:e.runId,provider:"codex",providerThreadId:n}}async resumeRun(e){let r=N8(e);return this.executeTurn(e,r,B8(e),e.providerThreadId,!0,P8)}async pauseRun(e){this.eventBus.push({type:"runner.status.changed",runId:e,phase:"waiting",headline:"Pause requested",detail:"Codex app-server will stop after the current turn boundary."})}async stopRun(e){let r=this.activeByRunId.get(e);if(this.eventBus.push({type:"runner.status.changed",runId:e,phase:"waiting",headline:"Stop requested"}),r?.threadId&&r.turnId){try{await this.client.request("turn/interrupt",{threadId:r.threadId,turnId:r.turnId},{timeoutMs:1e4})}catch(n){this.eventBus.push({type:"runner.error",runId:e,error:`Codex app-server interrupt failed: ${n instanceof Error?n.message:String(n)}`})}r.completed=!0,r.reject(new Error("Codex turn interrupted by Studio"));return}if(r){r.completed=!0,this.client.close(),r.reject(new Error("Codex turn interrupted by Studio before app-server returned a turn id"));return}this.eventBus.close(e)}async providerStatus(){try{let r={backend:"app-server",available:!0,initialized:await this.client.initialize()};try{r.account=await this.client.request("account/read",{refreshToken:!1})}catch(i){r.accountError=i instanceof Error?i.message:String(i)}try{r.rateLimits=await this.client.request("account/rateLimits/read")}catch(i){r.rateLimitsError=i instanceof Error?i.message:String(i)}let n=[r.accountError,r.rateLimitsError].filter(Boolean);return n.length>0&&(r.error=n.join("; ")),r}catch(e){return{backend:"app-server",available:!1,error:e instanceof Error?e.message:String(e)}}}events(e){return this.eventBus.events(e)}async executeTurn(e,r,n,i,o=!1,s,a={}){let c=a.reusePreparedThread===!0&&i!==void 0&&!s;try{let u=c?i:await this.prepareThread(e,r,i,o,s);c&&this.eventBus.push({type:"runner.status.changed",runId:e.runId,phase:"working",headline:"Prepared thread reused",detail:u,providerThreadId:u});try{return await this.startTurn(e,r,u,n,o,s)}catch(d){if(!c)throw d;let l=d instanceof Error?d.message:String(d);this.eventBus.push({type:"runner.status.changed",runId:e.runId,phase:"working",headline:"Prepared thread reuse failed",detail:l,providerThreadId:i});let f=await this.prepareThread(e,r,i,o,s);return await this.startTurn(e,r,f,n,o,s)}}catch(u){let d=u instanceof Error?u.message:String(u);throw this.eventBus.push({type:"runner.error",runId:e.runId,error:d}),u}finally{this.eventBus.close(e.runId)}}async startTurn(e,r,n,i,o,s){let a;try{return await new Promise((c,u)=>{a={runId:e.runId,threadId:n,rawEvents:[],activeCommandExecutionIds:new Set,backgroundTerminalCleanupRequested:!1,finalEmitted:!1,completed:!1,resolve:c,reject:u},this.trackActiveTurn(a),this.client.request("turn/start",this.turnStartParamsFor(e,r,n,i,o,s),{timeoutMs:6e4}).then(d=>{let l=Ua(d,"turn");if(!a||a.completed)return;let f=ft(l,"id");f&&this.setActiveTurnId(a,f),l&&ft(l,"status")!=="inProgress"&&this.completeActiveTurn(a,l)}).catch(d=>{a?.completed||u(d instanceof Error?d:new Error(String(d)))})})}finally{a&&this.untrackActiveTurn(a)}}async prepareThread(e,r,n,i,o){let s=n?await this.client.request("thread/resume",this.threadResumeParamsFor(e,r,n,i)):await this.client.request("thread/start",this.threadStartParamsFor(e,r,i)),a=cb(s,["thread","id"])??n;if(!a)throw new Error("Codex app-server did not return a thread id");return this.eventBus.push({type:"runner.status.changed",runId:e.runId,phase:"working",headline:"Thread ready",detail:a,providerThreadId:a}),o?(await this.client.request("thread/goal/clear",{threadId:a},{timeoutMs:6e4}),this.eventBus.push({type:"runner.status.changed",runId:e.runId,phase:"working",headline:"Provider goal cleared",providerThreadId:a})):(await this.client.request("thread/goal/set",this.threadGoalSetParamsFor(e,r,a),{timeoutMs:6e4}),this.eventBus.push({type:"runner.status.changed",runId:e.runId,phase:"working",headline:"Provider goal set",providerThreadId:a})),a}threadStartParamsFor(e,r,n){let i=this.effectiveThreadOptions(e,r,n);return{cwd:e.repositoryPath,approvalPolicy:i.approvalPolicy,approvalsReviewer:i.approvalsReviewer??"user",sandbox:i.sandboxMode,model:i.model??null,serviceTier:i.serviceTier==="fast"?"fast":null,ephemeral:!1,threadSource:"user"}}threadResumeParamsFor(e,r,n,i){let o=this.effectiveThreadOptions(e,r,i);return{threadId:n,cwd:e.repositoryPath,approvalPolicy:o.approvalPolicy,approvalsReviewer:o.approvalsReviewer??"user",sandbox:o.sandboxMode,model:o.model??null,serviceTier:o.serviceTier==="fast"?"fast":null}}threadGoalSetParamsFor(e,r,n){return{threadId:n,objective:gie(e,r)}}turnStartParamsFor(e,r,n,i,o,s){let a=this.effectiveThreadOptions(e,r,o);return{threadId:n,input:[{type:"text",text:i,text_elements:[]}],cwd:e.repositoryPath,approvalPolicy:a.approvalPolicy,approvalsReviewer:a.approvalsReviewer??"user",sandboxPolicy:eie(e.repositoryPath,a,o),model:a.model??null,serviceTier:a.serviceTier==="fast"?"fast":null,effort:a.modelReasoningEffort??null,outputSchema:s??null}}effectiveThreadOptions(e,r,n){let i=Eie(r),o={...this.threadOptions,...e.codexThreadOptions,...i,...G8(e.resolvedModelSelection)};return n&&(o.networkAccessEnabled=e.codexThreadOptions?.networkAccessEnabled??this.threadOptions.networkAccessEnabled??i.networkAccessEnabled,o.sandboxMode="read-only",o.approvalPolicy="never",o.approvalsReviewer="user"),o}handleNotification(e){let r=_8(e,this.activeByThreadId,this.activeByTurnId);if(!r)return;r.rawEvents.push(T8(e));let n=Ji(e.params)?e.params:{},i=ft(n,"turnId")??cb(n,["turn","id"]);this.eventBus.push({type:"runner.appServer.message",runId:r.runId,direction:"server-notification",providerThreadId:r.threadId,providerTurnId:i??r.turnId,method:e.method,message:e}),i&&i!==r.turnId&&this.setActiveTurnId(r,i),(e.method==="item/started"||e.method==="item/completed")&&this.trackCommandExecutionItem(r,e.method,Ua(n,"item"));let o=tie({runId:r.runId,providerThreadId:r.threadId,providerTurnId:i??r.turnId},e);for(let s of o)switch(s.kind){case"setTurnId":this.setActiveTurnId(r,s.turnId);break;case"usage":r.usage=s.usage;break;case"teamEvent":this.eventBus.push(s.event);break;case"finalResponse":r.finalResponse=s.finalResponse,this.requestBackgroundTerminalCleanupIfNeeded(r);break;case"completeTurn":this.completeActiveTurn(r,s.turn);break}}trackCommandExecutionItem(e,r,n){if(ft(n,"type")!=="commandExecution")return;let i=Eg(n);if(!i)return;let o=ft(n,"status");if(r==="item/completed"||o==="completed"||o==="failed"||o==="declined"){e.activeCommandExecutionIds.delete(i);return}e.activeCommandExecutionIds.add(i)}requestBackgroundTerminalCleanupIfNeeded(e){e.backgroundTerminalCleanupRequested||e.activeCommandExecutionIds.size===0||(e.backgroundTerminalCleanupRequested=!0,this.client.request("thread/backgroundTerminals/clean",{threadId:e.threadId},{timeoutMs:1e4}).catch(()=>{}))}completeActiveTurn(e,r){if(e.completed)return;e.completed=!0;let n=ft(r,"id")??e.turnId;n&&this.setActiveTurnId(e,n);let i=ft(r,"status");if(i==="failed"){let s=Ua(r,"error"),a=ft(s,"message")??"Codex app-server turn failed";this.eventBus.push({type:"runner.error",runId:e.runId,error:a}),e.reject(new Error(a));return}if(i==="interrupted"){e.reject(new Error("Codex app-server turn interrupted"));return}let o=e.finalResponse??die(r);o&&!e.finalEmitted&&(e.finalEmitted=!0,this.eventBus.push({type:"runner.final",runId:e.runId,finalResponse:o})),e.resolve({runId:e.runId,provider:"codex",providerThreadId:e.threadId,providerTurnId:e.turnId,finalResponse:o,rawResult:{rawEvents:e.rawEvents,finalResponse:o,usage:e.usage,turn:r}})}trackActiveTurn(e){this.activeByRunId.set(e.runId,e),this.activeByThreadId.set(e.threadId,e),e.turnId&&this.activeByTurnId.set(e.turnId,e)}setActiveTurnId(e,r){e.turnId&&e.turnId!==r&&this.activeByTurnId.delete(e.turnId),e.turnId=r,this.activeByTurnId.set(r,e)}untrackActiveTurn(e){this.activeByRunId.delete(e.runId),this.activeByThreadId.delete(e.threadId),e.turnId&&this.activeByTurnId.delete(e.turnId)}async handleServerRequest(e){let r=Ji(e.params)?e.params:{},n=_8(e,this.activeByThreadId,this.activeByTurnId);n?.rawEvents.push(T8(e));let i=n?.runId;i&&this.eventBus.push({type:"runner.appServer.message",runId:i,direction:"server-request",providerThreadId:n?.threadId,providerTurnId:n?.turnId,method:e.method,message:e});let o=iie(e.method,r);return i&&o&&this.eventBus.push({type:"runner.status.changed",runId:i,phase:"waiting",headline:"Approval requested",detail:o,providerThreadId:n?.threadId,providerTurnId:n?.turnId}),e.method==="item/permissions/requestApproval"&&(n?.threadId&&n.turnId&&this.client.request("turn/interrupt",{threadId:n.threadId,turnId:n.turnId},{timeoutMs:1e4}).catch(()=>{}),i&&this.eventBus.push({type:"runner.error",runId:i,error:"Codex app-server requested additional permissions; Hunsu declined and interrupted the turn."}),n&&!n.completed&&(n.completed=!0,n.reject(new Error("Codex app-server requested additional permissions; Hunsu declined and interrupted the turn.")))),H8(e)}};function Zd(t={}){return new Q1(t)}function H8(t){switch(t.method){case"item/commandExecution/requestApproval":return{decision:"decline"};case"item/fileChange/requestApproval":return{decision:"decline"};case"execCommandApproval":case"applyPatchApproval":return{decision:"denied"};case"item/permissions/requestApproval":return{permissions:{},scope:"turn",strictAutoReview:!0};default:throw new Ig(-32601,`Unsupported Codex app-server request: ${t.method??"unknown"}`)}}function eie(t,e,r){let n=e.networkAccessEnabled===!0;return r||e.sandboxMode==="read-only"?{type:"readOnly",networkAccess:n}:e.sandboxMode==="danger-full-access"?{type:"dangerFullAccess",networkAccess:n}:{type:"workspaceWrite",writableRoots:[t],networkAccess:n,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}function _8(t,e,r){let n=Ji(t.params)?t.params:{},i=ft(n,"turnId")??cb(n,["turn","id"]);if(i){let s=r.get(i);if(s)return s}let o=ft(n,"threadId")??cb(n,["thread","id"]);return o?e.get(o):void 0}function T8(t){return{source:"codex.app-server",message:t}}function tie(t,e){let r=Ji(e.params)?e.params:{};switch(e.method){case"turn/started":{let n=Ua(r,"turn"),i=ft(n,"id")??ft(r,"turnId")??t.providerTurnId??"turn";return[...i?[{kind:"setTurnId",turnId:i}]:[],{kind:"teamEvent",event:{type:"runner.turn.started",runId:t.runId,providerThreadId:t.providerThreadId,providerTurnId:i,turn:n,startedAtMs:$a(r,"startedAtMs")}},{kind:"teamEvent",event:{type:"runner.status.changed",runId:t.runId,phase:"working",headline:"Working",detail:i,providerThreadId:t.providerThreadId,providerTurnId:i}}]}case"turn/completed":{let n=Ua(r,"turn"),i=ft(n,"id")??ft(r,"turnId")??t.providerTurnId;return[{kind:"teamEvent",event:{type:"runner.turn.completed",runId:t.runId,providerThreadId:t.providerThreadId,providerTurnId:i,turn:n,completedAtMs:$a(r,"completedAtMs")}},{kind:"completeTurn",turn:n}]}case"thread/tokenUsage/updated":{let n=rie(r);return[{kind:"usage",usage:n},{kind:"teamEvent",event:{type:"runner.status.changed",runId:t.runId,phase:"working",headline:"Working",detail:nie(n),providerThreadId:t.providerThreadId,providerTurnId:t.providerTurnId}}]}case"item/started":case"item/completed":return oie(t,e.method,Ua(r,"item"));case"item/agentMessage/delta":case"item/agentMessage/textDelta":case"item/agentMessage/outputDelta":case"item/assistantMessage/delta":case"item/assistantMessage/textDelta":case"item/assistantMessage/outputDelta":{let n=D8(r);if(!n)return[];let i=Eg(r)??"agentMessage",o=ft(r,"turnId")??t.providerTurnId;return[{kind:"teamEvent",event:{type:"runner.item.delta",runId:t.runId,providerThreadId:t.providerThreadId,providerTurnId:o,itemId:i,deltaKind:"agentMessage",delta:n}}]}case"item/commandExecution/outputDelta":case"item/fileChange/outputDelta":case"item/plan/delta":case"item/reasoning/textDelta":case"item/reasoning/summaryTextDelta":{let n=D8(r);if(!n)return[];let i=sie(e.method),o=Eg(r)??i,s=ft(r,"turnId")??t.providerTurnId;return[{kind:"teamEvent",event:{type:"runner.item.delta",runId:t.runId,providerThreadId:t.providerThreadId,providerTurnId:s,itemId:o,deltaKind:i,delta:n,contentIndex:$a(r,"contentIndex")}}]}case"turn/plan/updated":{let n=ft(r,"explanation");return[{kind:"teamEvent",event:{type:"runner.status.changed",runId:t.runId,phase:"thinking",headline:"Planning",detail:n?op(n,500):"Codex plan updated.",providerThreadId:t.providerThreadId,providerTurnId:t.providerTurnId}}]}case"error":{let n=Ua(r,"error");return[{kind:"teamEvent",event:{type:"runner.error",runId:t.runId,error:ft(n,"message")??"Codex app-server error"}}]}default:return[]}}function rie(t){let e=Ua(t,"tokenUsage"),r=Ua(e,"last");if(r)return{input_tokens:$a(r,"inputTokens")??0,cached_input_tokens:$a(r,"cachedInputTokens")??0,output_tokens:$a(r,"outputTokens")??0,reasoning_output_tokens:$a(r,"reasoningOutputTokens")??0}}function nie(t){return t?`Codex turn usage. Input ${t.input_tokens}, output ${t.output_tokens}, reasoning ${t.reasoning_output_tokens}.`:"Codex app-server usage updated."}function iie(t,e){switch(t){case"item/commandExecution/requestApproval":return`Codex app-server requested command approval; Hunsu declined: ${ft(e,"command")??"unknown command"}`;case"item/fileChange/requestApproval":return`Codex app-server requested file-change approval; Hunsu declined${ft(e,"grantRoot")?` for ${ft(e,"grantRoot")}`:""}.`;case"item/permissions/requestApproval":return"Codex app-server requested additional permissions; Hunsu declined.";case"execCommandApproval":return`Codex app-server requested command approval; Hunsu declined: ${e.command?.join(" ")??"unknown command"}`;case"applyPatchApproval":return"Codex app-server requested patch approval; Hunsu declined.";default:return}}function oie(t,e,r){let n=e==="item/started"?"started":"completed",i=aie(r);if(!i)return[];let o=i.id??Eg(r)??i.type,s={kind:"teamEvent",event:n==="started"?{type:"runner.item.started",runId:t.runId,providerThreadId:t.providerThreadId,providerTurnId:t.providerTurnId,itemId:o,item:i}:{type:"runner.item.completed",runId:t.runId,providerThreadId:t.providerThreadId,providerTurnId:t.providerTurnId,itemId:o,item:i}};switch(i.type){case"agentMessage":{let a=i.text;return n!=="completed"||!a?[s]:[s,{kind:"finalResponse",finalResponse:a}]}case"reasoning":return[s];case"plan":return[s];case"commandExecution":return[s];case"fileChange":return[s];case"mcpToolCall":return[s];case"webSearch":return[s];default:return[s]}}function sie(t){switch(t){case"item/agentMessage/delta":case"item/agentMessage/textDelta":case"item/agentMessage/outputDelta":case"item/assistantMessage/delta":case"item/assistantMessage/textDelta":case"item/assistantMessage/outputDelta":return"agentMessage";case"item/plan/delta":return"plan";case"item/reasoning/textDelta":return"reasoningText";case"item/reasoning/summaryTextDelta":return"reasoningSummary";case"item/fileChange/outputDelta":return"fileChangeOutput";default:return"commandOutput"}}function aie(t){let e=ft(t,"type");if(!t||!e)return;let r={id:Eg(t),type:e,raw:t},n=ft(t,"text");if(n!==void 0)r.text=n;else{let b=cie(t);b!==void 0&&(r.text=b)}let i=Z1(t.summary);i.length>0&&(r.summary=i);let o=Z1(t.content);o.length>0&&(r.content=o);let s=ft(t,"command");s!==void 0&&(r.command=s);let a=ft(t,"cwd");a!==void 0&&(r.cwd=a);let c=ft(t,"status");c!==void 0&&(r.status=c);let u=uie(t);u.length>0&&(r.commandActions=u);let d=ft(t,"aggregatedOutput");d!==void 0&&(r.aggregatedOutput=d);let l=$a(t,"exitCode");l!==void 0&&(r.exitCode=l);let f=$a(t,"durationMs");f!==void 0&&(r.durationMs=f),"changes"in t&&(r.changes=t.changes);let p=ft(t,"server");p!==void 0&&(r.server=p);let g=ft(t,"tool");g!==void 0&&(r.tool=g);let v=ft(t,"query");return v!==void 0&&(r.query=v),r}function cie(t){let e=Z1(t.content);if(e.length!==0)return e.join(`
145
+
146
+ `)}function Z1(t){return Array.isArray(t)?t.flatMap(e=>{if(typeof e=="string")return e?[e]:[];if(!Ji(e))return[];let r=ft(e,"text")??ft(e,"content")??ft(e,"summary");return r?[r]:[]}):[]}function uie(t){let e=t.commandActions;return Array.isArray(e)?e.flatMap(r=>{if(!Ji(r))return[];let n=ft(r,"type");switch(n){case"read":return[{type:n,command:ft(r,"command"),name:ft(r,"name"),path:ft(r,"path")}];case"listFiles":return[{type:n,command:ft(r,"command"),path:ft(r,"path")}];case"search":return[{type:n,command:ft(r,"command"),query:ft(r,"query"),path:ft(r,"path")}];case"unknown":return[{type:n,command:ft(r,"command")}];default:return[]}}):[]}function die(t){let e=Array.isArray(t?.items)?t.items:[];for(let r of[...e].reverse())if(Ji(r)&&r.type==="agentMessage"&&typeof r.text=="string")return r.text}function Eg(t){if(Ji(t))return ft(t,"itemId")??ft(t,"id")}function Ua(t,e){if(!Ji(t))return;let r=t[e];return Ji(r)?r:void 0}function ft(t,e){if(!Ji(t))return;let r=t[e];return typeof r=="string"?r:void 0}function D8(t){let e=ft(t,"delta");if(e!==void 0)return e;let r=ft(t,"deltaBase64");if(r)try{return Kne.from(r,r.includes("-")||r.includes("_")?"base64url":"base64").toString("utf8")}catch{return}}function $a(t,e){if(!Ji(t))return;let r=t[e];return typeof r=="number"?r:void 0}function cb(t,e){let r=t;for(let n of e){if(!Ji(r))return;r=r[n]}return typeof r=="string"?r:void 0}function Ji(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function B8(t){let e=ub(t);return["<role>"," <purpose>"," Plan a closure-free executable ExecutionPlan."," </purpose>",""," <instructions>",Ha(U8(t,e),4)," </instructions>","</role>","","<goal>",Ha(q8(t),2),"</goal>","","<member_profiles>",vie(e.members),"</member_profiles>","","<rules>"," Return one structured ExecutionPlan object with root kind queue."," Put each executable step in the queue items array as kind goal with stage needs_evaluation."," Use each goal item to delegate to one assignee Executor and optionally one evaluator Executor."," A goal assignee must name executorId and a standalone goal."," A goal evaluator, when present, must name executorId and a prompt that can return pass or fail with type, summary, reason, feedback, nextGoal, and evidence.",` Set remainingAttempts to ${fie(t.maxAttemptCount)||lie(e)} for each goal unless a smaller bound is clearly enough.`," Set requires to PrevMove unless this goal intentionally depends on earlier Path ids.","</rules>"].join(`
147
+ `)}function lie(t){switch(t.kind){case"team_execution_plan":return t.maxAttemptCount;case"role_squad":case"council_vote":case"court_debate":return t.maxRoundCount}}function fie(t){return Number.isInteger(t)&&t&&t>0?t:void 0}function pie(t){let e=V8(t,t.memberPath.executorId);return["<member>",ng(e.promptTemplate,F8(t)).trim()||"No additional Member prompt.","</member>","","<goal>",t.memberPath.goal.trim(),"</goal>","","<constraints>","Do not read .hunsu files.","Do not create commits.","Use bounded commands for verification; do not run preview servers, dev servers, watchers, or other long-running processes in the foreground.","If you start a preview server, dev server, watcher, or any other long-running command, stop it before your final response.","Do not leave running command sessions, local listeners, or background processes open at the end of the turn.","</constraints>"].join(`
148
+ `)}function mie(t){let e=kg(t),r=t.pathOutputs.map(n=>[`- ${n.pathId} (${n.executorId})`,` goal: ${n.goal}`,n.commit?` commit: ${n.commit}`:void 0,n.finalResponse?` output: ${op(n.finalResponse,2e3)}`:void 0].filter(Boolean).join(`
149
+ `)).join(`
150
+ `);return["You are the MOVE finalizer for a completed Hunsu Execute.","Write the Git commit message for MOVE N+1 from the source MOVE to terminal Path diff.","Do not edit files. Do not create Git commits. Return only the commit message content.","",`MOVE id: ${t.moveId}`,`Source MOVE commit: ${t.sourceMoveCommit}`,`Terminal Path commit: ${t.terminalPathCommit}`,t.terminalMemberPathId?`Terminal Path id: ${t.terminalMemberPathId}`:void 0,"","Destination:",e?Sie(e):`- ${t.requestGoal}`,"","Completion summary:",t.completionSummary||"Not provided.","","Path commits:",Object.entries(t.pathCommits).map(([n,i])=>`- ${n}: ${i}`).join(`
151
+ `)||"- none","","Path outputs:",r||"- none","","Diff stat:",t.diffStat?.trim()||"Not provided.","","Diff name-status:",t.diffNameStatus?.trim()||"Not provided.","","Diff patch:",t.diffPatch?.trim()||"Not provided.","","Commit message requirements:","- First line: concise imperative subject for the MOVE result.","- Body: summarize the product changes and relevant Path outputs.","- Do not include Hunsu trailers; Studio appends system trailers."].filter(n=>n!==void 0).join(`
152
+ `)}function hie(t){let e=ng(t.manager.promptTemplate,j8(t)).trim();return["<role>","You are the Hunsu Draft agent for a local Hunsu Studio session.","Help the user refine a proposed HUNSU intervention conversationally.","You may edit decoded draft request files under .hunsu-request/ in the supplied Route worktree.","Do not edit .hunsu/ encoded runtime files, .hunsu-prev/, product files, or create commits.","Available request runtime files are .hunsu-request/destinations.json, .hunsu-request/harness.json, .hunsu-request/executors.json, .hunsu-request/resources.json, and .hunsu-request/artifact-actions.json.","Edit only the files required by the user's explicit request.","Use destinations.json for Destination/TODO changes and artifact-actions.json for Artifact Action changes.","For a simple TODO/Destination addition, edit only .hunsu-request/destinations.json.",".hunsu-request/executors.json is the source of truth for Member definitions.",".hunsu-request/resources.json is the source of truth for Skill, Plugin, and Resource bindings.",".hunsu-request/harness.json stores Harness policy only; it must not contain a members field.","Do not edit .hunsu-request/harness.json unless the user explicitly asks to change root Team or Harness policy.","Do not edit .hunsu-request/executors.json unless the user explicitly asks to change Member definitions or Member config.","Do not edit .hunsu-request/resources.json unless the user explicitly asks to change Resource bindings or requirements.","Do not create, copy, or update Resource bindings or assignment entries for newly added Destinations; Team-planner routing and binding are handled outside Destination edits.","After editing .hunsu-request files, run the supplied Draft check command. It creates a DiffArtifact in Hunsu Bridge.",'If the DiffArtifact passes, include this exact marker in your final reply: ::hunsu-diff{draftSessionId="<draftSessionId>" diffArtifactId="<diffArtifactId>" status="pass"}','If the DiffArtifact fails, include the same marker with status="failed" and explain the validation error briefly.',"Confirmation is handled by Hunsu Bridge from the DiffArtifact id.","</role>","","<manager>",`id: ${t.manager.id}`,"instructions:",Ha(e||"No Manager-specific instructions.",2),"</manager>","","<draft_check_command>",Ha(t.draftCheckCommand,2),"</draft_check_command>","","<source_snapshot>",Ha(bie(t.sourceSnapshot),2),"</source_snapshot>","","<request_goal>",Ha(t.requestGoal,2),"</request_goal>","","<conversation>",Ha(wie(t.messages),2),"</conversation>","","<latest_user_message>",Ha(t.userMessage,2),"</latest_user_message>","","<response_rules>","Answer naturally and briefly.","If you edited .hunsu-request files, summarize the changed files and the intended runtime change after running the Draft check command.","If the requested change cannot be represented in the provided .hunsu-request runtime files, say which runtime file or schema is missing.","If more detail is needed, ask a focused follow-up question.","Do not output JSON unless the user explicitly asks for an example.","</response_rules>"].join(`
153
+ `)}function gie(t,e){let r=ng(e.promptTemplate,j8(t));if(K8(t))return op(["Objective: discuss a HUNSU draft with the user.",`Source: ${t.sourceSnapshot.teamName??"Team"} ${t.sourceSnapshot.moveOrdinal!==void 0?`M${String(t.sourceSnapshot.moveOrdinal).padStart(4,"0")}`:t.sourceSnapshot.sourceNodeId}`,eA(t)?`User request: ${t.userMessage}`:"Status: preparing the Draft chat session before the first user message.",r.trim()?`Instructions:
154
+ ${r.trim()}`:void 0].filter(Boolean).join(`
155
+
156
+ `),4e3);if(z8(t)){let i=[`Objective: ${t.memberPath.goal}`,r.trim()?`Member:
157
+ ${r.trim()}`:void 0].filter(Boolean);return op(i.join(`
158
+
159
+ `),4e3)}let n=[`Objective:
160
+ ${q8(t)}`,`Instructions:
161
+ ${r.trim()||M8}`].filter(Boolean);return op(n.join(`
162
+
163
+ `),4e3)}function U8(t,e){let r=ng(e.team.promptTemplate,$8(t,e)).trim();return r||M8}function $8(t,e){let r=W8(t);return{requestGoal:t.requestGoal,currentDestination:r[0]??kg(t),currentDestinations:r,selectedDestinations:r,activeDestinations:t.activeDestinations,constraints:tA(t),members:e.members.map(n=>({id:n.id,promptTemplate:n.promptTemplate.template,model:n.model,reasoningEffort:n.reasoningEffort,serviceTier:n.serviceTier,skills:n.skills.map(i=>i.name),plugins:n.plugins.map(i=>i.id)}))}}function F8(t){let e=W8(t);return{requestGoal:t.requestGoal,pathGoal:t.memberPath.goal,memberPath:t.memberPath,dependencyOutputs:t.dependencyOutputs??[],worktreeStatus:t.worktreeStatus,worktreeDiff:t.worktreeDiff,attemptTranscript:t.attemptTranscript,evaluationFeedback:t.attemptTranscript,currentDestination:e[0]??kg(t),currentDestinations:e,selectedDestinations:e,activeDestinations:t.activeDestinations,constraints:tA(t),sourceMoveId:t.sourceMoveId,targetMoveOrdinal:t.targetMoveOrdinal}}function j8(t){return z8(t)?F8(t):K8(t)?{requestGoal:t.requestGoal,sourceSnapshot:t.sourceSnapshot,userMessage:eA(t)?t.userMessage:void 0,messages:eA(t)?t.messages:[]}:$8(t,ub(t))}function q8(t){let e=kg(t),r=tA(t).map(n=>`- ${n}`).join(`
164
+ `);return[e?yie(e):`- ${t.requestGoal}`,r?`Relevant constraints:
165
+ ${r}`:void 0].filter(n=>n!==void 0).join(`
166
+
167
+ `)}function kg(t){let e=t.selectedDestinationIds?.[0];return e?t.activeDestinations.find(r=>r.id===e):[...t.activeDestinations].sort((r,n)=>(n.priority??0)-(r.priority??0))[0]}function W8(t){let e=t.selectedDestinationIds??[];if(e.length===0){let n=kg(t);return n?[n]:[]}let r=new Set(e);return t.activeDestinations.filter(n=>r.has(n.id))}function tA(t){return t.futureConstraints&&t.futureConstraints.length>0?t.futureConstraints:t.board.futureConstraints.map(e=>e.constraint)}function yie(t){let e=[`- ${t.title}`];return t.acceptanceCriteria&&t.acceptanceCriteria.length>0&&e.push(` Acceptance: ${t.acceptanceCriteria.join("; ")}`),t.constraints&&t.constraints.length>0&&e.push(` Constraints: ${t.constraints.join("; ")}`),t.notes?.trim()&&e.push(` Notes: ${t.notes.trim()}`),e.join(`
168
+ `)}function vie(t){return t.map(e=>[` <member id="${xie(e.id)}">`," <profile>",Ha(e.promptTemplate.template.trim()||"No profile.",6)," </profile>"," </member>"].join(`
169
+ `)).join(`
170
+
171
+ `)||` <member id="default">
172
+ <profile>
173
+ No profile.
174
+ </profile>
175
+ </member>`}function Ha(t,e){let r=" ".repeat(e);return t.split(`
176
+ `).map(n=>n?`${r}${n}`:"").join(`
177
+ `)}function xie(t){return t.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Sie(t){let e=[`- ${t.title}`];return t.acceptanceCriteria&&t.acceptanceCriteria.length>0&&e.push(` Acceptance: ${t.acceptanceCriteria.join("; ")}`),t.constraints&&t.constraints.length>0&&e.push(` Constraints: ${t.constraints.join("; ")}`),t.notes?.trim()&&e.push(` Notes: ${t.notes.trim()}`),e.join(`
178
+ `)}function bie(t){return[`draftSessionId source line: ${t.sourceLineId}`,`source node: ${t.sourceNodeId}`,t.sourceMoveId?`source move: ${t.sourceMoveId}`:void 0,t.moveOrdinal!==void 0?`position: M${String(t.moveOrdinal).padStart(4,"0")}`:void 0,t.teamName?`team: ${t.teamName}`:void 0,t.summary?`summary: ${t.summary}`:void 0,"destinations:",t.destinationSummaries.length>0?t.destinationSummaries.map(e=>`- ${e.id} [${e.status}] ${e.title}`).join(`
179
+ `):"- none"].filter(e=>e!==void 0).join(`
180
+ `)}function wie(t){return t.length===0?"No prior draft conversation.":t.map(e=>`${e.role==="draft-agent"?"Draft Agent":e.role==="user"?"User":"System"}: ${op(e.text,1200)}`).join(`
181
+
182
+ `)}function N8(t){let e=ub(t);return Ii("team",U8(t,e),[])}function Iie(){return Ii("move-finalizer","Write a precise final MOVE commit message from the completed Execute diff and evidence.",[])}function O8(t=tp()){return{...Ii(String(t.id),t.promptTemplate.template,t.skills),promptTemplate:{...t.promptTemplate},plugins:t.plugins.map(r=>({...r})),...t.modelSelection?{modelSelection:JSON.parse(JSON.stringify(t.modelSelection))}:{},execution:{kind:"worktree_write",network:"enabled"},approval:{policy:"never"}}}function V8(t,e){if(t.harnessGraph){let i=h1(t.harnessGraph,e);if(!i)throw new Error(`Harness does not define required Member ${e}`);return BS(i)}let r=ub(t),n=rp(r,e);if(!n)throw new Error(`Harness ${r.kind} does not define required Member ${e}`);return n}function ub(t){return t.harnessGraph?Xd(t.harnessGraph,t.teamScopeId??t.harnessGraph.rootTeamId):t.harness??Vn()}function Eie(t){let e={approvalPolicy:t.approval.policy==="on_request"?"on-request":"never",approvalsReviewer:t.approval.policy==="on_request"?t.approval.reviewer:"user",networkAccessEnabled:t.execution.network==="enabled"};switch(t.execution.kind){case"read_only":e.sandboxMode="read-only";break;case"worktree_write":e.sandboxMode="workspace-write";break;case"unrestricted":e.sandboxMode="danger-full-access";break}let r=t.modelSelection?X3(t.modelSelection):void 0;return r?{...e,...G8(r)}:(t.modelSelection||(t.model&&t.model!=="codex-default"&&(e.model=t.model),t.reasoningEffort&&t.reasoningEffort!=="default"&&(e.modelReasoningEffort=t.reasoningEffort),e.serviceTier=t.serviceTier??"default"),e)}function G8(t){return!t||t.providerId!=="codex"?{}:{model:t.model==="codex-default"?void 0:t.model,modelReasoningEffort:t.reasoningEffort&&t.reasoningEffort!=="default"?t.reasoningEffort:void 0,serviceTier:t.serviceTier??"default"}}function z8(t){return"memberPath"in t}function eA(t){return"draftSessionId"in t&&"sourceSnapshot"in t&&"userMessage"in t}function K8(t){return"draftSessionId"in t&&"sourceSnapshot"in t}function kie(t){let e={};for(let[i,o]of Object.entries(t))o!==void 0&&(e[i]=o);let r=Wne(jne(Vne(import.meta.url)),"../../.."),n=qne(r,"node_modules",".bin");return e.PATH=[n,t.PATH].filter(Boolean).join(Fne),e}function op(t,e=4e3){return t.length<=e?t:`${t.slice(0,e-1)}...`}var du=class extends Error{constructor(e){super(e),this.name="HunsuError"}};var Dr=class extends du{command;stderr;constructor(e,r){super(`Git command failed: git ${e.join(" ")}${r?`
183
+ ${r}`:""}`),this.name="GitError",this.command=e,this.stderr=r}};function rA(t){let e=[];for(let[r,n]of Object.entries(t))n!==void 0&&e.push(`${r}: ${String(n)}`);return e.join(`
184
+ `)}function J8(t,e="commitSha"){return typeof t=="string"&&/^[0-9a-f]{40}$/i.test(t)?S(t):Y8(e,"must be a 40-character Git commit SHA")}function Aie(t,e="runtimeChecksum"){return typeof t=="string"&&/^[0-9a-f]{64}$/i.test(t)?S(t):Y8(e,"must be a SHA-256 hex checksum")}function Xr(t,e="commitSha"){return X8(J8(t,e))}function sp(t,e="runtimeChecksum"){return X8(Aie(t,e))}function X8(t){if(t.ok)return t.value;throw new du(`${t.error.field} ${t.error.message}`)}function Y8(t,e){return oe({type:"CorePrimitiveError",field:t,message:e})}import{createHash as Hie}from"node:crypto";import{gzipSync as Uie,gunzipSync as $ie}from"node:zlib";import{existsSync as Pg,mkdirSync as Fie,readFileSync as dA,rmSync as eM,writeFileSync as jie}from"node:fs";import{dirname as qie,join as fu}from"node:path";import{mkdirSync as Cie,mkdtempSync as Pie,rmSync as nA,writeFileSync as iA}from"node:fs";import{isAbsolute as _ie,join as Rg}from"node:path";import{spawnSync as Tie}from"node:child_process";var Die="",Bie=64*1024*1024,xDe=["%H","%h","%P","%D","%an","%aI","%s","%B"].join(Die);function Re(t,e={}){let r=Tie("git",t,{cwd:e.cwd,input:e.input,encoding:"utf8",maxBuffer:Bie,env:e.env});if(r.status!==0)throw new Dr(t,r.stderr.trim());return r.stdout}function qt(t=process.cwd()){return Re(["rev-parse","--show-toplevel"],{cwd:t}).trim()}function Nie(t,e={}){let r=e.cwd??process.cwd(),n=sA(r,"hunsu-move-"),i=Rg(n,"message.txt");try{return iA(i,t,"utf8"),Re(["commit","-F",i],{cwd:r}),{commitSha:Xr(Re(["rev-parse","HEAD"],{cwd:r}).trim()),message:t}}finally{nA(n,{recursive:!0,force:!0})}}function Q8(t,e={}){let r=e.cwd??process.cwd();if(!Re(["status","--porcelain=v1"],{cwd:r}).trim())throw new du("Cannot create MOVE commit without worktree changes");return Re(["add","--all"],{cwd:r}),Nie(t,{cwd:r})}function Oie(t){let e=t.finalizerMessage.trim();if(!e)throw new du("MOVE finalizer returned an empty commit message");let r=rA({"Hunsu-Event":"move","Hunsu-Run":t.runId,"Hunsu-Move":t.moveId,"Hunsu-Goal":t.goal,"Hunsu-Role":"move-finalizer","Hunsu-Actor":t.actor??"agent:codex","Hunsu-Status":"complete"});return`${e}
185
+
186
+ ${r}
187
+ `}function oA(t){let e=t.cwd??process.cwd(),r=sA(e,"hunsu-final-move-"),n=Rg(r,"message.txt"),i=Oie(t);try{return iA(n,i,"utf8"),Re(["commit","--allow-empty","-F",n],{cwd:e}),{commitSha:Xr(Re(["rev-parse","--verify","HEAD"],{cwd:e}).trim()),message:i}}finally{nA(r,{recursive:!0,force:!0})}}function Mie(t){let e=Array.isArray(t.requires)?t.requires.join(","):t.requires,r=rA({"Hunsu-Event":"member-path","Hunsu-Run":t.runId,"Hunsu-Path":t.pathId,"Hunsu-Member":t.executorId,"Hunsu-Goal":t.goal,"Hunsu-Requires":e});return[`path: ${t.pathId} (${t.executorId})`,"",`Goal: ${t.goal}`,"",`Requires: ${e}`,"",r].join(`
188
+ `)+`
189
+ `}function db(t){let e=t.cwd??process.cwd(),r=sA(e,"hunsu-path-"),n=Rg(r,"message.txt"),i=Mie(t);try{let o=Lie(e),s=Re(["rev-parse","--verify",`${o}^{tree}`],{cwd:e}).trim();iA(n,i,"utf8");let a=t.paths?.filter(d=>d.trim()!=="");a&&a.length>0?Re(["add","--all","--",...a],{cwd:e}):Re(["add","--all"],{cwd:e}),Re(["commit","--allow-empty","-F",n],{cwd:e});let c=Xr(Re(["rev-parse","--verify","HEAD"],{cwd:e}).trim()),u=Re(["rev-parse","--verify",`${c}^{tree}`],{cwd:e}).trim();return{commitSha:c,parentSha:o,treeSha:u,parentTreeSha:s,treeChanged:u!==s,message:i}}finally{nA(r,{recursive:!0,force:!0})}}function Lie(t){try{return Xr(Re(["rev-parse","--verify","HEAD"],{cwd:t}).trim())}catch{return Re(["commit","--allow-empty","-m","hunsu: initialize repository worktree"],{cwd:t}),Xr(Re(["rev-parse","--verify","HEAD"],{cwd:t}).trim())}}function sA(t,e){let r=Re(["rev-parse","--git-path","hunsu/tmp"],{cwd:t}).trim(),n=_ie(r)?r:Rg(t,r);return Cie(n,{recursive:!0}),Pie(Rg(n,e))}var lA=".hunsu/completed-destinations.hunsu",hb=".hunsu/destinations.hunsu",fA=".hunsu/harness.hunsu",pA=".hunsu/executors.hunsu",mA=".hunsu/resources.hunsu",hA=".hunsu/artifact-actions.hunsu",Xi=".hunsu/current-execution.hunsu",cp=".hunsu/previous-execution.hunsu",_g=".hunsu/hunsu-draft.hunsu",mu=[lA,hb,fA,pA,mA,hA],cA=".hunsu/state.hunsu",tM="gzip+base64url";var gA={type:"self"},pu="__HUNSU_SELF_COMMIT__",gb="HUNSU_RUNTIME_FILE_V1",Wie="HUNSU_STATE_V1",Vie="refs/hunsu/events",Gie="%(refname) %(objectname) %(objecttype)",zie=" ";function Bn(t=process.cwd()){let e=qt(t),r=oM(e),n=wA(e);if(r&&(!n||mb(r.runtime)>=mb(n.runtime)))return Ag(e,r.runtime,"worktree-runtime",[],r.checksum);if(n)return Ag(e,n.runtime,"reachable-runtime",[],n.checksum,n.commit);let i=xoe(e)??Soe(e,"HEAD");if(i){let a=pb(i.state.events,void 0,i.state.events);return Ag(e,a,"legacy-state",[],aA(a))}let o=xA(e);if(o.length>0){let a=o.map(u=>Bg(Xie(e,u))),c=pb(a,void 0,a);return Ag(e,c,"legacy-refs",o,aA(c))}let s=pb([]);return Ag(e,s,"empty",[],aA(s))}function Kie(t,e=process.cwd()){let r=Bn(e),n=t.reduce((o,s)=>{let a=bg(o,s);if(!a.ok)throw new Error(a.error.message);return a.value},r.events),i=n.slice(r.events.length);return{store:r,acceptedEvents:i,board:bA(n,"dry-run commands")}}function yb(t,e={}){return Tg([t],e)}function Tg(t,e={}){let r=e.cwd??process.cwd(),{store:n,acceptedEvents:i,board:o}=Kie(t,r);if(i.length>0){let s=pb([...n.events,...i],n.runtime,i,e.previousExecution);loe(n.root,s,{selfCommitMoveIds:e.selfCommitMoveIds}),goe(n.root,e.commitMessage)}return{acceptedEvents:i,board:o}}function yo(t){let e=`${JSON.stringify(t)}
190
+ `,r=sp(Ng(e)),n=Uie(Buffer.from(e,"utf8")).toString("base64url");return{checksum:r,text:`${gb}
191
+ encoding: ${tM}
192
+ checksum: sha256:${r}
193
+
194
+ ${n}
195
+ `}}function rM(t,e){let r=vb(t,e,gb);return r.ok?S(r.value.value):r}function nM(t){let e=fb(t);return{"destinations.json":e.destinations,"harness.json":e.harness,"executors.json":e.executors,"resources.json":e.resources,"artifact-actions.json":e.artifactActions}}function fb(t){return{destinations:el(t.destinations),harness:el(t.harness),executors:el(t.executors),resources:el(t.resources),artifactActions:el(t.artifactActions)}}function yA(t,e){let r=qt(t),n=Cg(r,e,"destinations.json");if(!n.ok)return n;let i=Cg(r,e,"harness.json");if(!i.ok)return i;let o=Cg(r,e,"executors.json");if(!o.ok)return o;let s=Cg(r,e,"resources.json");if(!s.ok)return s;let a=Cg(r,e,"artifact-actions.json");return a.ok?S({destinations:n.value,harness:i.value,executors:o.value,resources:s.value,artifactActions:a.value}):a}function iM(t,e,r){let n=fb(r);if(lb(t)!==lb(n))return Dn(".hunsu-prev no longer matches the source runtime bundle");if(lb(e.destinations.compatibility)!==lb(r.destinations.compatibility))return Dn(".hunsu-request/destinations.json compatibility is Bridge-owned and must not be edited");try{let i=cM({completed:r.completed,destinations:e.destinations,harness:e.harness,executors:e.executors,resources:e.resources,artifactActions:e.artifactActions,currentExecution:r.currentExecution,previousExecution:r.previousExecution,eventLog:r.eventLog},"draft request runtime");return S({previous:fb(r),request:fb(i),requestRuntime:i})}catch(i){return Dn(i instanceof Error?i.message:String(i))}}function oM(t=process.cwd()){let e=qt(t);if(mu.every(r=>Pg(fu(e,r))))return aM(r=>dA(fu(e,r),"utf8"),"worktree",boe(e))}function sM(t=process.cwd(),e="HEAD"){let r=qt(t);try{let n=Xr(Re(["rev-parse","--verify",`${e}^{commit}`],{cwd:r}).trim());return aM(i=>Re(["show",`${n}:${i}`],{cwd:r}),n,n)}catch(n){if(n instanceof Dr)return;throw n}}function Jie(t=process.cwd()){let e=qt(t),r;try{r=Re(["rev-list","--date-order","--all","--",hb],{cwd:e}).trim().split(/\r?\n/).filter(Boolean)}catch(n){if(n instanceof Dr)return[];throw n}return r.flatMap(n=>{let i=Xr(n),o=sM(e,i);return o?[{commit:i,...o}]:[]})}function vA(t=process.cwd(),e){let r=qt(t),n=new Set,i=[],o=e??wA(r)?.commit??"HEAD";for(;o;){let s;try{s=Xr(Re(["rev-parse","--verify",`${o}^{commit}`],{cwd:r}).trim())}catch(c){if(c instanceof Dr)break;throw c}if(n.has(s))break;n.add(s);let a=sM(r,s);if(!a||a.runtime.previousExecution.type!=="present")break;i.push({commit:s,execution:a.runtime.previousExecution.value}),o=a.runtime.previousExecution.value.sourceMoveCommit}return i}function Dg(t=process.cwd()){let e=qt(t);return oM(e)!==void 0||wA(e)!==void 0}function xA(t=process.cwd()){let e=qt(t),r=Re(["for-each-ref",`--format=${Gie}`,Vie],{cwd:e}).trim();return r?r.split(/\r?\n/).map(Ioe).filter(n=>n.objectType==="blob").sort((n,i)=>n.ordinal-i.ordinal||n.ref.localeCompare(i.ref)):[]}function Xie(t,e){let r=qt(t),n=Re(["cat-file","-p",e.object],{cwd:r});return Yie(n,e.ref)}function Yie(t,e){let r=t.trim();if(!r)return Dn(`Empty Hunsu domain event object: ${e}`);let n;try{n=JSON.parse(r)}catch(o){return Dn(`Invalid Hunsu domain event JSON in ${e}: ${o instanceof Error?o.message:String(o)}`)}let i=ib(n);return i.ok?S(i.value):Dn(`Invalid Hunsu domain event object in ${e}: ${i.error.message}`)}function pb(t,e,r=[],n){let i=bA(t,"runtime events"),o={events:t,updatedAt:r.length>0?new Date().toISOString():e?.eventLog.updatedAt};return{completed:eoe(i,e?.completed,e?r:t),destinations:{schema:"hunsu.destinations.v1",order:"queue-head-is-current",destinations:roe(i),compatibility:{events:o.events,updatedAt:o.updatedAt}},...noe(i,e),artifactActions:ioe(i),currentExecution:Qie(e?.currentExecution,r),previousExecution:Zie(e?.previousExecution,r,n),eventLog:o}}function Qie(t,e){return e.some(r=>r.type==="HunsuRecorded"||r.type==="LineForkedByHunsu"||r.type==="MoveRecorded")?{type:"none"}:t??{type:"none"}}function Zie(t,e,r){return r||(e.some(n=>n.type==="HunsuRecorded"||n.type==="LineForkedByHunsu")?{type:"none"}:e.some(n=>n.type==="MoveRecorded")?{type:"none"}:t??{type:"none"})}function eoe(t,e,r){let n=e?[...e.entries]:[];for(let i of r)if(!(i.type!=="MoveRecorded"||i.move.outcome!=="arrived"))for(let o of i.move.reachedDestinationIds)n.some(s=>s.moveId===i.move.id&&s.destinationId===o)||n.push(toe(t,i.move,o));return{schema:"hunsu.completed-destinations.v1",order:"oldest-first-tail-append",entries:n}}function toe(t,e,r){let n=e.snapshot?.destinations.find(i=>i.id===r)??t.destinations.find(i=>i.id===r);return{destinationId:r,title:n?.title??r,completedAt:e.recordedAt,resultCommit:doe(e.commit),moveId:e.id,harnessId:"default",digest:{summary:e.summary,evidence:[...e.evidence],risks:e.risks?[...e.risks]:void 0}}}function roe(t){return t.destinations.filter(e=>e.status!=="reached"&&e.status!=="canceled"&&e.status!=="superseded").sort((e,r)=>(r.priority??0)-(e.priority??0)||e.id.localeCompare(r.id))}function noe(t,e){let r=t.lines.findLast(o=>o.status==="active")??t.lines.at(-1),n=r?t.nodes.find(o=>o.id===r.currentNodeId):void 0,i=n?.harnessGraph??(e?uM(e):Bs(Vn()));return{harness:{schema:"hunsu.harness.v1",origins:t.origins.map(o=>({...o})),harness:{name:"Default Harness",rootTeamId:i.rootTeamId,guardrails:i.guardrails.map(o=>({...o})),lock:n?.harnessLock?{...n.harnessLock}:e?.harness.harness.lock}},executors:{schema:"hunsu.executors.v1",executors:el(i.executors)},resources:{schema:"hunsu.resources.v1",resources:el(i.resources),bindings:t.destinations.map(o=>{let s=e?.resources.bindings.find(a=>a.destinationId===o.id);return{destinationId:o.id,executorPackageBindings:n?.executorPackageBindings?.map(a=>({executorId:a.executorId,lock:{...a.lock}}))??s?.executorPackageBindings,resourcePackageBindings:n?.resourcePackageBindings?.map(a=>({name:a.name,lock:{...a.lock}}))??s?.resourcePackageBindings}})}}}function ioe(t){return{schema:"hunsu.artifact-actions.v1",order:"display-order",actions:t.artifactActions.map(ooe).sort((e,r)=>e.displayOrder-r.displayOrder||String(e.id).localeCompare(String(r.id)))}}function ooe(t){return{...t,env:t.env?Object.fromEntries(Object.entries(t.env).map(([e,r])=>[e,{...r}])):void 0,runner:{...t.runner},aliases:t.aliases?Object.fromEntries(Object.entries(t.aliases).map(([e,r])=>[e,{...r}])):void 0,evidence:t.evidence?{...t.evidence,paths:t.evidence.paths?.slice()}:void 0}}function aM(t,e,r){let n=ap(t,lA,e),i=ap(t,hb,e),o=ap(t,fA,e),s=ap(t,pA,e),a=ap(t,mA,e),c=ap(t,hA,e);if(!n||!i||!o||!s||!a||!c)return;let u=Z8(t,Xi,e),d=Z8(t,cp,e);return{runtime:cM({completed:n.value,destinations:i.value,harness:o.value,executors:s.value,resources:a.value,artifactActions:c.value,currentExecution:u?{type:"present",value:u.value}:{type:"none"},previousExecution:d?{type:"present",value:d.value}:{type:"none"}},e,r),checksum:sp(Ng([n.checksum,i.checksum,o.checksum,s.checksum,a.checksum,c.checksum,u?.checksum??"none",d?.checksum??"none"].join(`
196
+ `)))}}function ap(t,e,r){try{let n=vb(t(e),`${r}:${e}`,gb);return n.ok?{value:n.value.value,checksum:n.value.checksum}:Bg(n)}catch(n){if(n instanceof Dr)return;throw n}}function Z8(t,e,r){try{let n=vb(t(e),`${r}:${e}`,gb);return n.ok?{value:n.value.value,checksum:n.value.checksum}:Bg(n)}catch(n){if(n instanceof Dr||woe(n))return;throw n}}function cM(t,e,r){if(t.completed.schema!=="hunsu.completed-destinations.v1"||t.completed.order!=="oldest-first-tail-append"||!Array.isArray(t.completed.entries))throw new Error(`Invalid completed Destinations runtime file in ${e}`);if(t.destinations.schema!=="hunsu.destinations.v1"||t.destinations.order!=="queue-head-is-current"||!Array.isArray(t.destinations.destinations))throw new Error(`Invalid pending Destinations runtime file in ${e}`);if(!t.destinations.compatibility||!Array.isArray(t.destinations.compatibility.events))throw new Error(`Invalid pending Destinations compatibility data in ${e}`);let n=[];for(let[u,d]of t.destinations.compatibility.events.entries()){let l=ib(uoe(d,r));if(!l.ok)throw new Error(`Invalid Hunsu runtime event ${u} in ${e}: ${l.error.message}`);n.push(l.value)}let i={events:n,updatedAt:typeof t.destinations.compatibility.updatedAt=="string"?t.destinations.compatibility.updatedAt:t.eventLog?.updatedAt};if(t.harness.schema!=="hunsu.harness.v1"||!t.harness.harness||typeof t.harness.harness.name!="string")throw new Error(`Invalid Harness runtime file in ${e}`);if(Object.prototype.hasOwnProperty.call(t.harness.harness,"executors"))throw new Error(`Invalid Harness runtime file in ${e}: Executor definitions are stored in executors.json`);if(Object.prototype.hasOwnProperty.call(t.harness.harness,"members"))throw new Error(`Invalid Harness runtime file in ${e}: members is stored in executors.json, not harness.json`);if(Object.prototype.hasOwnProperty.call(t.harness.harness,"plan"))throw new Error(`Invalid Harness runtime file in ${e}: root Team planner is stored in executors.json, not harness.json`);if(typeof t.harness.harness.rootTeamId!="string"||!t.harness.harness.rootTeamId.trim())throw new Error(`Invalid Harness runtime file in ${e}: rootTeamId must reference the locked root Team`);if(t.executors.schema!=="hunsu.executors.v1"||!Array.isArray(t.executors.executors))throw new Error(`Invalid Executors runtime file in ${e}`);if(t.resources.schema!=="hunsu.resources.v1"||!Array.isArray(t.resources.resources)||!Array.isArray(t.resources.bindings))throw new Error(`Invalid Resources runtime file in ${e}`);let o=soe(t.artifactActions,e),s=uM({...t,artifactActions:o},e);ou(s);let a=aoe(t.currentExecution,e),c=coe(t.previousExecution,e,r);return{completed:t.completed,destinations:{...t.destinations,compatibility:{...t.destinations.compatibility,events:n}},harness:{...t.harness,harness:{name:t.harness.harness.name,rootTeamId:s.rootTeamId,guardrails:s.guardrails.map(u=>({...u})),lock:t.harness.harness.lock}},executors:{...t.executors,executors:s.executors},resources:{...t.resources,resources:s.resources},artifactActions:o,currentExecution:a,previousExecution:c,eventLog:i}}function uM(t,e="runtime"){let r=Jd({rootTeamId:t.harness.harness.rootTeamId,executors:t.executors.executors,resources:t.resources.resources,guardrails:t.harness.harness.guardrails??[],artifactActions:t.artifactActions.actions},`${e} Harness graph`);if(!r.ok)throw new Error(`Invalid Harness runtime graph in ${e}: ${r.error.message}`);return r.value}function soe(t,e){if(t.schema!=="hunsu.artifact-actions.v1"||t.order!=="display-order"||!Array.isArray(t.actions))throw new Error(`Invalid Artifact Actions runtime file in ${e}`);let r=vg(t.actions,"artifactActions.actions");if(!r.ok)throw new Error(`Invalid Artifact Actions runtime file in ${e}: ${r.error.message}`);return{...t,actions:r.value}}function aoe(t,e){if(!t||t.type==="none")return{type:"none"};if(t.type!=="present"||!t.value||t.value.schema!=="hunsu.current-execution.v1")throw new Error(`Invalid current execution runtime file in ${e}`);if(!t.value.execution||typeof t.value.execution!="object")throw new Error(`Invalid current execution payload in ${e}`);return t}function coe(t,e,r){if(!t||t.type==="none")return{type:"none"};if(t.type!=="present"||!t.value||t.value.schema!=="hunsu.previous-execution.v1")throw new Error(`Invalid previous execution runtime file in ${e}`);if(!t.value.sourceMoveCommit||!t.value.targetMoveId||!t.value.executeId||!t.value.runId||!t.value.lineId)throw new Error(`Invalid previous execution identity in ${e}`);if(!t.value.plan||t.value.plan.nodeType!=="PlanNode")throw new Error(`Invalid previous execution PlanNode in ${e}`);if(!Array.isArray(t.value.paths))throw new Error(`Invalid previous execution PathNode list in ${e}`);let n=t.value.moveFinalizerCommit;if(SA(n)){if(!r)throw new Error(`Cannot resolve previous execution self commit in ${e}`);return{type:"present",value:{...t.value,moveFinalizerCommit:{type:"external",commit:r}}}}return t}function uoe(t,e){if(t.type!=="MoveRecorded")return t;let r=t.move.commit;if(SA(r)){if(!e)throw new Error("Cannot resolve self MOVE commit without containing commit");return{...t,move:{...t.move,commit:e}}}if(r===pu){if(!e)throw new Error("Cannot resolve self MOVE commit without containing commit");return{...t,move:{...t.move,commit:e}}}return t}function SA(t){return!!(t&&typeof t=="object"&&t.type==="self")}function doe(t){return SA(t)?gA:t===pu?pu:Xr(String(t))}function loe(t,e,r={}){let n=qt(t);lu(n,lA,e.completed),lu(n,hb,dM(e,r.selfCommitMoveIds??[])),lu(n,fA,e.harness),lu(n,pA,e.executors),lu(n,mA,e.resources),lu(n,hA,e.artifactActions),foe(n,e.currentExecution),poe(n,e.previousExecution,r.selfCommitMoveIds??[])}function lu(t,e,r){let n=fu(t,e);Fie(qie(n),{recursive:!0}),jie(n,yo(r).text,"utf8")}function foe(t,e){let r=fu(t,Xi);if(e.type==="none"){Pg(r)&&eM(r,{force:!0});return}lu(t,Xi,e.value)}function poe(t,e,r){let n=fu(t,cp);if(e.type==="none"){Pg(n)&&eM(n,{force:!0});return}let i=hoe(e.value,r);lu(t,cp,i)}function dM(t,e){return{...t.destinations,compatibility:{events:t.eventLog.events.map(r=>moe(r,e)),updatedAt:t.eventLog.updatedAt}}}function moe(t,e){return t.type!=="MoveRecorded"||!e.includes(String(t.move.id))?t:{...t,move:{...t.move,commit:gA}}}function hoe(t,e){return!t.moveFinalizerCommit||t.moveFinalizerCommit.type!=="external"||!e.includes(t.targetMoveId)?t:{...t,moveFinalizerCommit:gA}}function goe(t,e){if(!e)return;let r=yoe(t);r.length===0||(Re(["add","--all","--",...r],{cwd:t}),!Re(["status","--porcelain=v1","--",...r],{cwd:t}).trim())||Re(["commit","--only","-m",e,"--",...r],{cwd:t})}function yoe(t){return[...mu,Xi,cp].filter(e=>Pg(fu(t,e))||voe(t,e))}function voe(t,e){try{return Re(["ls-files","--error-unmatch",e],{cwd:t}),!0}catch(r){if(r instanceof Dr)return!1;throw r}}function Ag(t,e,r,n,i,o){let s=[...e.eventLog.events];return{root:t,eventRefs:n,events:s,board:bA(s,r),runtimePaths:mu,runtime:e,source:r,checksum:i,commit:o}}function bA(t,e){let r=uu(t);if(!r.ok)throw new Error(`Invalid Hunsu domain event stream in ${e}: ${r.error.message}`);return r.value}function wA(t){return Jie(t).sort((e,r)=>mb(r.runtime)-mb(e.runtime)).at(0)}function mb(t){return t.eventLog.events.length}function aA(t){return sp(Ng([yo(t.completed).checksum,yo(dM(t,[])).checksum,yo(t.harness).checksum,yo(t.executors).checksum,yo(t.resources).checksum,yo(t.artifactActions).checksum,t.currentExecution.type==="present"?yo(t.currentExecution.value).checksum:"none",t.previousExecution.type==="present"?yo(t.previousExecution.value).checksum:"none"].join(`
197
+ `)))}function vb(t,e,r){let n=t.replace(/\r\n/g,`
198
+ `),i=n.indexOf(`
199
+
200
+ `);if(i===-1)return Dn(`Invalid Hunsu runtime envelope in ${e}`);let o=n.slice(0,i).split(`
201
+ `),s=n.slice(i+2).trim();if(o[0]!==r)return Dn(`Invalid Hunsu runtime header in ${e}`);let a=new Map(o.slice(1).map(l=>{let f=l.indexOf(":");return f===-1?[l.trim(),""]:[l.slice(0,f).trim(),l.slice(f+1).trim()]}));if(a.get("encoding")!==tM)return Dn(`Unsupported Hunsu runtime encoding in ${e}: ${a.get("encoding")??"missing"}`);let c=a.get("checksum")?.replace(/^sha256:/,"");if(!c)return Dn(`Missing Hunsu runtime checksum in ${e}`);let u;try{u=$ie(Buffer.from(s,"base64url")).toString("utf8")}catch(l){return Dn(`Invalid Hunsu runtime payload in ${e}: ${l instanceof Error?l.message:String(l)}`)}let d=Ng(u);if(d!==c)return Dn(`Hunsu runtime checksum mismatch in ${e}`);try{return S({value:JSON.parse(u),checksum:sp(d)})}catch(l){return Dn(`Invalid Hunsu runtime JSON in ${e}: ${l instanceof Error?l.message:String(l)}`)}}function xoe(t){let e=qt(t),r=fu(e,cA);if(!Pg(r))return;let n=Bg(lM(dA(r,"utf8"),r));return{state:n,checksum:fM(n)}}function Soe(t,e){let r=qt(t);try{let n=Re(["show",`${e}:${cA}`],{cwd:r}),i=Bg(lM(n,`${e}:${cA}`));return{state:i,checksum:fM(i)}}catch(n){if(n instanceof Dr)return;throw n}}function lM(t,e){let r=vb(t,e,Wie);if(!r.ok)return r;let n=r.value.value;if(!n||typeof n!="object")return Dn(`Invalid legacy Hunsu runtime state JSON in ${e}: expected object`);let i=n;if(i.version!==1||!Array.isArray(i.events))return Dn(`Invalid legacy Hunsu runtime state in ${e}`);let o=[];for(let[s,a]of i.events.entries()){let c=ib(a);if(!c.ok)return Dn(`Invalid legacy Hunsu runtime state event ${s} in ${e}: ${c.error.message}`);o.push(c.value)}return S({version:1,events:o,...typeof i.updatedAt=="string"?{updatedAt:i.updatedAt}:{}})}function fM(t){return sp(Ng(`${JSON.stringify(t)}
202
+ `))}function Dn(t){return oe({type:"DomainStoreError",message:t})}function Cg(t,e,r){let n=fu(t,e,r);try{return S(JSON.parse(dA(n,"utf8")))}catch(i){return Dn(`Cannot read ${e}/${r}: ${i instanceof Error?i.message:String(i)}`)}}function el(t){return JSON.parse(JSON.stringify(t))}function lb(t){return JSON.stringify(uA(t))}function uA(t){return Array.isArray(t)?t.map(uA):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>[e,uA(r)])):t}function Bg(t){if(t.ok)return t.value;throw new Error(t.error.message)}function boe(t){try{return Xr(Re(["rev-parse","--verify","HEAD^{commit}"],{cwd:t}).trim())}catch(e){if(e instanceof Dr)return;throw e}}function woe(t){return t instanceof Error?"code"in t&&t.code==="ENOENT":!1}function Ng(t){return Hie("sha256").update(t).digest("hex")}function Ioe(t){let[e,r,n]=t.split(zie);return{ref:e,object:r,objectType:n,ordinal:Eoe(e)}}function Eoe(t){let r=t.slice(t.lastIndexOf("/")+1).match(/^E(\d+)(?:-|$)/);return r?Number.parseInt(r[1],10):Number.MAX_SAFE_INTEGER}import{existsSync as Ls,readFileSync as hM,readdirSync as koe,statSync as Roe,writeFileSync as Aoe}from"node:fs";import{basename as Coe,join as Fa,resolve as Poe}from"node:path";var _oe="Port Git Project",Toe="Make this project ready for Hunsu-managed MOVEs and Artifact Actions.";function IA(t=process.cwd()){let e=Poe(t),r=[],n=e,i=!1;try{n=qt(e),i=!0}catch{r.push("Not a Git repository. Hunsu Port expects an existing Git project.")}let o=Noe(n),s=o?.scripts??{},a=Boe(n,o),c=pM(n,/^Dockerfile(?:\.|$)/),u=pM(n,/^(?:docker-)?compose(?:\.[^.]+)?\.ya?ml$/),d=i&&gM(n),l=Doe(n),f=Ooe(n,s),p=[];return!o&&i&&r.push("No package.json found. Port can still create Roadmap state, but Artifact Actions may need a later Hunsu setup."),i&&!d&&r.push("Hunsu runtime state is missing. Port apply will create Initial Team state."),{root:n,isGitRepository:i,isHunsuRoadmap:d,packageManager:a,packageScripts:s,docker:{dockerfiles:c,composeFiles:u},artifactActions:l,env:f,recommendedFiles:p,issues:r}}function EA(t={}){let e=IA(t.cwd);if(!e.isGitRepository)throw new Error("Hunsu Port requires an existing Git repository");let r=t.title?.trim()||Coe(e.root)||_oe,n=t.goal?.trim()||Toe,i=t.destinations&&t.destinations.length>0?t.destinations:[{id:"destination_001",title:"Establish artifact-action-ready product execution",priority:100}],o=e.isHunsuRoadmap?[]:[{type:"CreateInitialTeam",requestId:mM("req",r),lineId:`run/${mM("req",r)}`,title:r,goal:n,destinations:i,harness:t.harness}];return{root:e.root,title:r,goal:n,destinations:i,inspection:e,files:[],commands:o}}function kA(t={}){let e=EA(t),r=[];for(let i of e.files){let o=Fa(e.root,i.path);Ls(o)||(Aoe(o,i.content,"utf8"),r.push(i.path))}let n=e.commands.length>0?Tg(e.commands,{cwd:e.root,commitMessage:`hunsu: port ${e.title}`}):{acceptedEvents:[],board:Bn(e.root).board};return{root:e.root,plan:e,writtenFiles:r,acceptedEvents:n.acceptedEvents,board:n.board}}function Doe(t){if(!gM(t))return{configured:!1,count:0,issues:[]};let e=Bn(t).board;return{configured:e.artifactActions.length>0,count:e.artifactActions.length,issues:[]}}function Boe(t,e){if(Ls(Fa(t,"pnpm-lock.yaml"))||e?.packageManager?.startsWith("pnpm@"))return"pnpm";if(Ls(Fa(t,"yarn.lock"))||e?.packageManager?.startsWith("yarn@"))return"yarn";if(Ls(Fa(t,"bun.lockb"))||Ls(Fa(t,"bun.lock"))||e?.packageManager?.startsWith("bun@"))return"bun";if(Ls(Fa(t,"package-lock.json"))||e)return"npm"}function Noe(t){let e=Fa(t,"package.json");if(Ls(e))return JSON.parse(hM(e,"utf8"))}function pM(t,e){return!Ls(t)||!Roe(t).isDirectory()?[]:koe(t).filter(r=>e.test(r)).sort()}function gM(t){try{return Dg(t)||xA(t).length>0||Re(["for-each-ref","--count=1","--format=%(refname)","refs/hunsu"],{cwd:t}).trim().length>0}catch(e){if(e instanceof Dr)return!1;throw e}}function Ooe(t,e){let r=[".env",".env.local",".env.development",".env.example"].filter(i=>Ls(Fa(t,i))),n=Object.entries(e).filter(([,i])=>/\b(?:3000|5173|8080|4187)\b|localhost|127\.0\.0\.1/.test(i)).map(([i])=>`package.json scripts.${i}`);for(let i of["vite.config.ts","vite.config.js","next.config.js","next.config.mjs"]){let o=Fa(t,i);if(!Ls(o))continue;let s=hM(o,"utf8");/\b(?:3000|5173|8080|4187)\b|localhost|127\.0\.0\.1/.test(s)&&n.push(i)}return{files:r,hardcodedHints:n}}function mM(t,e){let r=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,48);return`${t}_${r||"project"}`}import{createHash as Moe}from"node:crypto";import{spawnSync as Loe}from"node:child_process";import{existsSync as wb,mkdirSync as yM,readFileSync as Hoe,readdirSync as Uoe,rmSync as vM,writeFileSync as $oe}from"node:fs";import{tmpdir as Foe}from"node:os";import{basename as joe,join as xb,resolve as CA}from"node:path";function xM(t=process.cwd(),e){let r=qt(t),n=Bn(r);if(e){let i=n.board.moves.find(s=>s.id===e);if(!i)throw new Error(`No MOVE found for Artifact Action source: ${e}`);let o=n.board.nodes.find(s=>s.id===i.toNodeId);return bb(i.snapshot?.artifactActions??o?.artifactActions??[])}return bb(n.board.artifactActions)}function PA(t){let e=qt(t.cwd??process.cwd()),r=qoe(e,t),n=r.actions.find(d=>d.id===t.actionId);if(!n)throw new Error(`Unknown Artifact Action for selected source: ${t.actionId}`);Woe(n,r.source);let i=t.now??new Date().toISOString(),o=Xoe(n.id,r.source,i),s=t.baseActionPath??Joe(t.roadmapId,o),a=n.kind==="host"?Goe(n,s):void 0,c=_A(n,t.env,t.ambientEnv),u={runId:o,actionId:n.id,roadmapId:t.roadmapId,action:AA(n),source:r.source,status:"queued",env:Voe(n,c),aliases:a,createdAt:i,updatedAt:i};return{action:AA(n),run:u,commands:IM(e,n,u,c)}}function SM(t,e={}){let r=qt(t.cwd??process.cwd()),n=PA(t),i=t.now??new Date().toISOString(),o=Koe(r,n.run.runId,n.run.source.commit,i,t.worktreeRoot),s=t.processEnv??e.processEnv,a=e.runner??((l,f,p)=>PM(l,f,{...p,processEnv:s})),c={...n.run,status:(n.action.kind==="host","running"),sourceWorktree:o,updatedAt:i},u=_A(n.action,t.env,t.ambientEnv),d=IM(r,n.action,c,u);try{if(n.action.runner.type==="docker_compose")Og(a,d[0]),Og(a,d[1]),c.aliases=zoe(r,c,a,u),c.status="running";else{let l=Og(a,d[0]);if(c.exitCode=l.status,c.stdout=l.stdout,c.stderr=l.stderr,c.status=n.action.kind==="host"?"running":"succeeded",n.action.kind==="check"){let f=Sb(r,o.path);c.sourceWorktree={...o,removedAt:f}}}c.updatedAt=new Date().toISOString()}catch(l){c.status="failed",c.updatedAt=new Date().toISOString(),c.error=l instanceof Error?l.message:String(l);let f=Sb(r,o.path);c.sourceWorktree={...o,removedAt:f}}if(e.store!==!1&&kM(r,c),c.status==="failed")throw new Error(c.error??`Artifact Action ${c.runId} failed`);return c}function bM(t=process.cwd()){let e=qt(t),r=TA(e);return wb(r)?Uoe(r).filter(n=>n.endsWith(".json")).map(n=>Mg(e,n.slice(0,-5))).sort((n,i)=>i.updatedAt.localeCompare(n.updatedAt)):[]}function Mg(t,e){let r=qt(t),n=RM(r,e);if(!wb(n))throw new Error(`Unknown Artifact Action Run: ${e}`);return JSON.parse(Hoe(n,"utf8"))}function wM(t,e,r={}){let n=qt(t),i=Mg(n,e),o=r.runner??((u,d,l)=>PM(u,d,{...l,processEnv:r.processEnv})),s=_A(i.action,i.env,r.processEnv);i.action.runner.type==="docker_compose"?Og(o,RA(n,i,["down"],s)):i.action.runner.stopCommand&&Og(o,EM(n,i,i.action.runner.stopCommand,s));let a=i.sourceWorktree?.path?Sb(n,i.sourceWorktree.path):void 0,c={...i,sourceWorktree:i.sourceWorktree?{...i.sourceWorktree,removedAt:a}:void 0,status:"stopped",stoppedAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return r.store!==!1&&kM(n,c),c}function qoe(t,e){if(e.moveId&&e.commit)throw new Error("Artifact Action source accepts either moveId or commit, not both");let r=Bn(t);if(e.moveId){let i=r.board.moves.find(s=>s.id===e.moveId);if(!i)throw new Error(`No MOVE found for Artifact Action source: ${e.moveId}`);let o=r.board.nodes.find(s=>s.id===i.toNodeId);return{source:{moveId:i.id,commit:Re(["rev-parse","--verify",`${i.commit}^{commit}`],{cwd:t}).trim(),ref:i.commit},actions:bb(i.snapshot?.artifactActions??o?.artifactActions??[])}}let n=e.commit??"HEAD";return{source:{commit:Re(["rev-parse","--verify",`${n}^{commit}`],{cwd:t}).trim(),ref:n},actions:bb(r.board.artifactActions)}}function Woe(t,e){if(t.sourceScope==="move"&&!e.moveId)throw new Error(`Artifact Action ${t.id} can only run against a MOVE source`);if(t.sourceScope==="commit"&&e.moveId)throw new Error(`Artifact Action ${t.id} can only run against a commit source`)}function _A(t,e={},r={}){let n={},i=new Set;for(let[o,s]of Object.entries(t.env??{}))if(i.add(o),"default"in s)n[o]=e[o]??String(s.default);else if("value"in s)n[o]=e[o]??String(s.value);else if("alias"in s){let a=t.aliases?.[s.alias];if(!a)throw new Error(`Artifact Action env ${o} references unknown alias: ${s.alias}`);n[o]=String(a.containerPort??a.target??"")}else if("fromAliasUrl"in s){let a=t.aliases?.[s.fromAliasUrl];if(!a)throw new Error(`Artifact Action env ${o} references unknown alias: ${s.fromAliasUrl}`);n[o]=a.service&&a.containerPort?`http://${a.service}:${a.containerPort}`:String(a.target??"")}else if(s.required){let a=e[o]??r[o];if(!a)throw new Error(`Artifact Action env ${o} is required but not set`);n[o]=a}for(let[o,s]of Object.entries(e))i.has(o)||(n[o]=s);return n}function Voe(t,e){let r={};for(let[n,i]of Object.entries(e)){let o=t.env?.[n];r[n]=o&&"required"in o&&o.secret?"<secret>":i}return r}function IM(t,e,r,n){return e.runner.type==="docker_compose"?[RA(t,r,["build"],n),RA(t,r,["up","-d"],n)]:[EM(t,r,e.runner.command,n)]}function RA(t,e,r,n){if(e.action.runner.type!=="docker_compose")throw new Error(`Artifact Action ${e.actionId} does not use docker compose`);let i=e.source.commit.slice(0,12),o=AM(CM(e.action.runner.projectName??`hunsu-${e.actionId}-${i}`,{actionId:e.actionId,runId:e.runId,commit:e.source.commit,shortCommit:i,moveId:e.source.moveId??""}));return{command:"docker",args:["compose","-f",CA(e.sourceWorktree?.path??t,e.action.runner.file),"-p",o,...r],cwd:e.sourceWorktree?.path??t,env:n}}function EM(t,e,r,n){return{command:"sh",args:["-lc",r],cwd:e.sourceWorktree?.path??t,env:n}}function Og(t,e){let r=t(e.command,e.args,{cwd:e.cwd,env:e.env});if(r.status!==0)throw new Error(`${e.command} ${e.args.join(" ")} failed
203
+ ${r.stderr||r.stdout}`);return r}function Goe(t,e){if(t.aliases)return Object.fromEntries(Object.entries(t.aliases).map(([r,n])=>[r,{alias:r,service:n.service,containerPort:n.containerPort,healthPath:n.healthPath,target:n.target,internalUrl:n.service&&n.containerPort?`http://${n.service}:${n.containerPort}`:n.target,externalPath:`${e}/${encodeURIComponent(r)}/`}]))}function zoe(t,e,r,n){if(!e.aliases||e.action.runner.type!=="docker_compose")return e.aliases;let i=e.action.runner;return Object.fromEntries(Object.entries(e.aliases).map(([o,s])=>{if(!s.service||!s.containerPort)return[o,s];let a=r("docker",["compose","-f",CA(e.sourceWorktree?.path??t,i.file),"-p",AM(CM(i.projectName??`hunsu-${e.actionId}-${e.source.commit.slice(0,12)}`,{actionId:e.actionId,runId:e.runId,commit:e.source.commit,shortCommit:e.source.commit.slice(0,12),moveId:e.source.moveId??""})),"port",s.service,String(s.containerPort)],{cwd:e.sourceWorktree?.path??t,env:n});return a.status!==0||!a.stdout.trim()?[o,s]:[o,{...s,directUrl:Qoe(a.stdout.trim())}]}))}function Koe(t,e,r,n,i){let o=CA(i??xb(Foe(),"hunsu-action-runs",`${joe(t)}-${Yoe(t)}`)),s=xb(o,DA(e));return yM(o,{recursive:!0}),wb(s)&&(Sb(t,s),vM(s,{recursive:!0,force:!0})),Re(["worktree","add","--detach",s,r],{cwd:t}),{path:s,commit:r,createdAt:n}}function Sb(t,e){let r=new Date().toISOString();if(!wb(e))return r;try{Re(["worktree","remove","--force",e],{cwd:t})}catch{vM(e,{recursive:!0,force:!0}),Re(["worktree","prune"],{cwd:t})}return r}function kM(t,e){yM(TA(t),{recursive:!0}),$oe(RM(t,e.runId),`${JSON.stringify(e,null,2)}
204
+ `,"utf8")}function TA(t){return xb(t,".hunsu","action-runs")}function RM(t,e){return xb(TA(t),`${DA(e)}.json`)}function Joe(t,e){return t?`/api/roadmaps/${encodeURIComponent(t)}/action-runs/${encodeURIComponent(e)}/proxy`:`/api/action-runs/${encodeURIComponent(e)}/proxy`}function Xoe(t,e,r){return DA(`${t}-${e.moveId??e.commit.slice(0,12)}-${r.replace(/[^0-9A-Za-z]/g,"").slice(0,14)}`)}function DA(t){return t.toLowerCase().replace(/[^a-z0-9_.-]+/g,"-").replace(/^-+|-+$/g,"")||"action-run"}function AM(t){return t.toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,63)||"hunsu-action"}function CM(t,e){return t.replace(/\{([a-zA-Z][a-zA-Z0-9]*)\}/g,(r,n)=>e[n]??"")}function Yoe(t){return Moe("sha256").update(t).digest("hex").slice(0,12)}function Qoe(t){let e=t.split(/\r?\n/).find(Boolean)??t,r=e.match(/(?:0\.0\.0\.0|127\.0\.0\.1|localhost|\[::\]|::):(\d+)$/);return r?`http://127.0.0.1:${r[1]}`:/^https?:\/\//.test(e)?e:`http://${e}`}function PM(t,e,r){let n=Loe(t,e,{cwd:r.cwd,env:{...Zoe(r.processEnv),...r.env},encoding:"utf8",maxBuffer:16777216});return{status:n.status??1,stdout:n.stdout,stderr:n.stderr}}function Zoe(t){if(t===void 0)return;let e={};for(let[r,n]of Object.entries(t))n!==void 0&&(e[r]=n);return e}function bb(t){return t.map(AA).sort((e,r)=>e.displayOrder-r.displayOrder||String(e.id).localeCompare(String(r.id)))}function AA(t){return{...t,env:t.env?Object.fromEntries(Object.entries(t.env).map(([e,r])=>[e,{...r}])):void 0,runner:{...t.runner},aliases:t.aliases?Object.fromEntries(Object.entries(t.aliases).map(([e,r])=>[e,{...r}])):void 0,evidence:t.evidence?{...t.evidence,paths:t.evidence.paths?.slice()}:void 0}}import{createHash as ese}from"node:crypto";var tse="hunsu.hub-package-manifest.v1",_M="hunsu-json-c14n-v1+sha256:";function rse(t){MA(t);let{integrity:e,...r}=t;return JSON.stringify(OA(r,"manifest"))}function nse(t){let e=rse(t);return`${_M}${ese("sha256").update(e,"utf8").digest("hex")}`}async function Lg(t,e){if(!t.integrity.startsWith(_M))throw new Error(`Unsupported Hub package integrity prefix: ${t.integrity}`);let r=e.origins.find(a=>a.name===t.origin);if(!r)throw new Error(`Unknown Origin: ${t.origin}`);if(r.transport!=="http")throw new Error(`Origin ${r.name} uses unsupported transport ${r.transport}`);let i=await(e.fetch??fetch)(ise(r.url,t.kind,t.key,t.version));if(!i.ok)throw i.status===404?new Error(`Missing Hub package manifest: ${t.origin}/${t.kind}/${t.key}@${t.version}`):new Error(`Origin ${r.name} returned ${i.status} for ${t.kind}/${t.key}@${t.version}`);let o=await i.json();if(MA(o),o.kind!==t.kind||o.key!==t.key||o.version!==t.version)throw new Error(`Hub package manifest from ${r.name} does not match requested ${t.kind}/${t.key}@${t.version}`);let s=nse(o);if(s!==t.integrity)throw new Error(`Hub package integrity mismatch for ${t.origin}/${t.kind}/${t.key}@${t.version}: expected ${t.integrity}, got ${s}`);return{lock:{...t},manifest:o,integrity:s,origin:{...r}}}function ise(t,e,r,n){let i=new URL(t),o=`/v1/packages/${e}/${encodeURIComponent(r)}/versions/${encodeURIComponent(n)}`;return new URL(o,i).toString()}function TM(t){if(MA(t),t.kind!=="team")throw new Error(`Hub package ${t.kind}/${t.key}@${t.version} is not a team package`);return dse(t.team)}function MA(t){let e=BA(t,"manifest");if(e.schema!==tse)throw new Error(`Unsupported Hub package manifest schema: ${String(e.schema)}`);NA(e,["integrity","key","kind","team","member","manager","schema","skill","version"],"manifest");let r=use(e.kind,"manifest.kind");switch(up(e.key,"manifest.key"),up(e.version,"manifest.version"),e.integrity!==void 0&&up(e.integrity,"manifest.integrity"),r){case"team":if(ose(e.team),e.member!==void 0||e.manager!==void 0||e.skill!==void 0)throw new Error("Team package manifest must not include member, manager, or skill payloads");return;case"member":if(sse(e.member),e.team!==void 0||e.manager!==void 0||e.skill!==void 0)throw new Error("Member package manifest must not include team, manager, or skill payloads");return;case"manager":if(ase(e.manager),e.team!==void 0||e.member!==void 0||e.skill!==void 0)throw new Error("Manager package manifest must not include team, member, or skill payloads");return;case"skill":if(cse(e.skill),e.team!==void 0||e.member!==void 0||e.manager!==void 0)throw new Error("Skill package manifest must not include team, member, or manager payloads");return}}function ose(t){let e=Jd(t,"manifest.team");if(!e.ok)throw new Error(`Invalid manifest.team: ${e.error.message}`)}function sse(t){let e=p1(t,"manifest.member");if(!e.ok)throw new Error(`Invalid manifest.member: ${e.error.message}`)}function ase(t){let e=og(t,"manifest.manager");if(!e.ok)throw new Error(`Invalid manifest.manager: ${e.error.message}`)}function cse(t){let e=BA(t,"manifest.skill");if(NA(e,["contentHash","files","name"],"manifest.skill"),up(e.name,"manifest.skill.name"),up(e.contentHash,"manifest.skill.contentHash"),e.files!==void 0){if(!Array.isArray(e.files))throw new Error("manifest.skill.files must be an array");for(let[r,n]of e.files.entries()){let i=BA(n,`manifest.skill.files[${r}]`);NA(i,["path","text"],`manifest.skill.files[${r}]`),up(i.path,`manifest.skill.files[${r}].path`),DM(i.text,`manifest.skill.files[${r}].text`)}}}function use(t,e){if(t==="team"||t==="member"||t==="manager"||t==="skill")return t;throw new Error(`${e} must be team, member, manager, or skill`)}function BA(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function NA(t,e,r){let n=e.filter(o=>o!=="integrity"&&o!=="team"&&o!=="member"&&o!=="manager"&&o!=="skill"&&o!=="files"&&!(o in t));if(n.length>0)throw new Error(`${r} is missing required keys: ${n.join(", ")}`);let i=Object.keys(t).filter(o=>!e.includes(o));if(i.length>0)throw new Error(`${r} has unsupported keys: ${i.join(", ")}`)}function DM(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}function up(t,e){let r=DM(t,e);if(r.trim().length===0)throw new Error(`${e} must be non-empty`);return r}function OA(t,e){if(t===null||typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number"){if(!Number.isFinite(t))throw new Error(`${e} must be a finite number`);return t}if(Array.isArray(t))return t.map((r,n)=>{if(r===void 0)throw new Error(`${e}[${n}] must not be undefined`);return OA(r,`${e}[${n}]`)});if(typeof t=="object"&&t!==null){let r=t,n={};for(let i of Object.keys(r).sort()){let o=r[i];o!==void 0&&(n[i]=OA(o,`${e}.${i}`))}return n}throw new Error(`${e} must be JSON-serializable`)}function dse(t){return JSON.parse(JSON.stringify(t))}function wt(t,e,r){return r===void 0?{code:t,message:e}:{code:t,message:e,details:r}}function Hg(t){let e=new Error(t.message);return e.name=`ExecuteOrchestrationError:${t.code}`,t.details!==void 0&&(e.details=t.details),e}function tl(t){if(t.ok)return t.value;throw Hg(t.error)}function HA(t){let e=jM(t,"Team planning final response must be a JSON ExecutionPlan object");return e.ok?$A(e.value,"execution"):e}function NM(t){let e=jM(t,"Goal evaluator final response must be a JSON object");if(!e.ok)return e;let r=e.value;if(r.type==="pass"){if(typeof r.summary!="string"||r.summary.trim()==="")return oe(wt("goal_evaluation_invalid","pass evaluation must include a non-empty summary"));let n=LA(r.evidence,"evidence");return n.ok?S({type:"pass",summary:r.summary,evidence:n.value}):n}if(r.type==="fail"){if(typeof r.reason!="string"||r.reason.trim()==="")return oe(wt("goal_evaluation_invalid","fail evaluation must include a non-empty reason"));if(typeof r.feedback!="string"||r.feedback.trim()==="")return oe(wt("goal_evaluation_invalid","fail evaluation must include non-empty feedback"));if(r.nextGoal!==void 0&&typeof r.nextGoal!="string")return oe(wt("goal_evaluation_invalid","fail evaluation nextGoal must be a string when present"));let n=LA(r.evidence,"evidence");return n.ok?S({type:"fail",reason:r.reason,feedback:r.feedback,nextGoal:typeof r.nextGoal=="string"&&r.nextGoal.trim()!==""?r.nextGoal:void 0,evidence:n.value}):n}return oe(wt("goal_evaluation_invalid","Goal evaluator response type must be pass or fail"))}function UA(t,e,r,n){if(e==="assignee")return{id:r,executorId:t.assignee.executorId,goal:t.assignee.goal,requires:n};let i=t.evaluator;if(!i)throw new Error(`Goal ${t.id} does not define an evaluator`);return{id:r,executorId:i.executorId,goal:i.prompt,requires:n}}function OM(t,e){let[,...r]=t.items;if(e)return{...t,items:[e,...r]};if(r.length!==0)return{...t,items:r}}function $A(t,e){return Ug(t)?t.kind==="queue"?lse(t,e):t.kind==="goal"?MM(t,e):t.kind==="continuation"?fse(t,e):oe(wt("execution_plan_invalid",`${e}.kind must be queue, goal, or continuation`)):oe(wt("execution_plan_invalid",`${e} must be an object`))}function lse(t,e){let r=HM(t.id,`${e}.id`);if(!r.ok)return r;if(!Array.isArray(t.items))return oe(wt("execution_plan_invalid",`${e}.items must be an array`));let n=[];for(let[i,o]of t.items.entries()){let s=$A(o,`${e}.items[${i}]`);if(!s.ok)return s;n.push(s.value)}return S({kind:"queue",id:r.value,items:n})}function MM(t,e){return t.stage==="needs_evaluation"?LM(t,e):t.stage==="needs_execution"?pse(t,e):oe(wt("execution_plan_invalid",`${e}.stage must be needs_evaluation or needs_execution`))}function fse(t,e){let r=FA(t.id,`${e}.id`);if(!r.ok)return r;let n=UM(t.teamScopeId,`${e}.teamScopeId`);if(!n.ok)return n;let i=$A(t.execution,`${e}.execution`);if(!i.ok)return i;let o=t.continuation===void 0?S(void 0):Ug(t.continuation)?MM(t.continuation,`${e}.continuation`):oe(wt("execution_plan_invalid",`${e}.continuation must be an object`));return o.ok?S({kind:"continuation",id:r.value,teamScopeId:n.value,execution:i.value,continuation:o.value}):o}function LM(t,e){let r=FA(t.id,`${e}.id`);if(!r.ok)return r;let n=BM(t.assignee,`${e}.assignee`,"goal");if(!n.ok)return n;let i=t.evaluator===void 0||t.evaluator===null?S(void 0):BM(t.evaluator,`${e}.evaluator`,"prompt");if(!i.ok)return i;let o=G3(t.remainingAttempts,`${e}.remainingAttempts`);if(!o.ok)return oe(wt("execution_plan_invalid",o.error.message));let s=hse(t.requires,`${e}.requires`);return s.ok?S({kind:"goal",stage:"needs_evaluation",id:r.value,assignee:{executorId:n.value.executorId,goal:n.value.text},evaluator:i.value?{executorId:i.value.executorId,prompt:i.value.text}:void 0,remainingAttempts:o.value,requires:s.value}):s}function pse(t,e){let r=LM({...t,stage:"needs_evaluation"},e);if(!r.ok)return r;let n=FA(t.evaluationPathId,`${e}.evaluationPathId`);if(!n.ok)return n;let i=mse(t.evaluation,`${e}.evaluation`);if(!i.ok)return i;if(!Array.isArray(t.requires))return oe(wt("execution_plan_invalid",`${e}.requires must be an array for needs_execution`));let o=$M(t.requires,`${e}.requires`);return o.ok?o.value.length!==1||o.value[0]!==n.value?oe(wt("execution_plan_invalid",`${e}.requires must contain only ${e}.evaluationPathId`)):S({...r.value,stage:"needs_execution",evaluationPathId:n.value,evaluation:i.value,requires:o.value}):o}function BM(t,e,r){if(!Ug(t))return oe(wt("execution_plan_invalid",`${e} must be an object`));let n=UM(t.executorId,`${e}.executorId`);if(!n.ok)return n;let i=HM(t[r],`${e}.${r}`);return i.ok?S({executorId:n.value,text:i.value}):i}function mse(t,e){if(!Ug(t))return oe(wt("execution_plan_invalid",`${e} must be an object`));if(t.type!=="fail")return oe(wt("execution_plan_invalid",`${e}.type must be fail`));if(typeof t.reason!="string"||t.reason.trim()==="")return oe(wt("execution_plan_invalid",`${e}.reason must be a non-empty string`));if(typeof t.feedback!="string"||t.feedback.trim()==="")return oe(wt("execution_plan_invalid",`${e}.feedback must be a non-empty string`));if(t.nextGoal!==void 0&&typeof t.nextGoal!="string")return oe(wt("execution_plan_invalid",`${e}.nextGoal must be a string when present`));let r=LA(t.evidence,`${e}.evidence`);return r.ok?S({type:"fail",reason:t.reason,feedback:t.feedback,nextGoal:typeof t.nextGoal=="string"&&t.nextGoal.trim()!==""?t.nextGoal:void 0,evidence:r.value}):r}function HM(t,e){return typeof t!="string"||t.trim()===""?oe(wt("execution_plan_invalid",`${e} must be a non-empty string`)):S(t)}function FA(t,e){let r=Ee(t,e);return r.ok?S(r.value):oe(wt("execution_plan_invalid",r.error.message))}function UM(t,e){let r=Ee(t,e);return r.ok?S(r.value):oe(wt("execution_plan_invalid",r.error.message))}function hse(t,e){return t==="PrevMove"?S("PrevMove"):$M(t,e)}function $M(t,e){let r=FM(t,e,"execution_plan_invalid");if(!r.ok)return r;let n=[];for(let[i,o]of r.value.entries()){let s=Ee(o,`${e}[${i}]`);if(!s.ok)return oe(wt("execution_plan_invalid",s.error.message));n.push(s.value)}return S(n)}function LA(t,e){return t===void 0?S(void 0):FM(t,e,"goal_evaluation_invalid")}function FM(t,e,r){return Array.isArray(t)?t.every(n=>typeof n=="string")?S([...t]):oe(wt(r,`${e} must be an array of strings`)):oe(wt(r,`${e} must be an array of strings`))}function jM(t,e){try{let r=JSON.parse(t);return Ug(r)?S(r):oe(wt("execution_plan_invalid",e))}catch(r){return oe(wt("execution_plan_invalid",e,{cause:r instanceof Error?r.message:String(r)}))}}function Ug(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function jA(t){let{line:e,lineNode:r}=t;if(!r)return oe(wt("invalid_start_state",`No execute-ready MOVE found for Team route ${e.id}`));if(e.status==="failed"||e.status==="complete"||e.status==="abandoned")return oe(wt("invalid_start_state",`Cannot start Execute from ${e.id} because the route is ${e.status}`));if(new Set(t.board.edges.filter(a=>a.type==="move").map(a=>a.fromNodeId)).has(r.id))return oe(wt("invalid_start_state",`Cannot start Execute from ${qM(r,t.formatMovePosition)} because Arrived or Accident already exists`));if(t.existingRuns.find(a=>a.sourceNodeId===r.id&&(a.status==="running"||a.status==="paused")))return oe(wt("active_execute_exists",`A Execute is already active for ${qM(r,t.formatMovePosition)}`));let o=Ba(r.ordinal+1,"targetMoveOrdinal");if(!o.ok)return oe(wt("invalid_start_state",o.error.message));let s=gse(t.selectedDestinationIds,t.activeDestinations);return s.ok?S({lineNode:r,selectedDestinationIds:s.value,targetMoveOrdinal:o.value}):s}function WM(t){return t?S(t):oe(wt("terminal_output_missing","ExecutionPlan completed without a terminal output"))}function gse(t,e){let r=yse(e);return t&&t.length>0?t.length!==1?oe(wt("invalid_start_state","Execute must select exactly one Destination")):r&&t[0]===r.id?S([...t]):oe(wt("invalid_start_state","Execute must select the next Destination in the queue")):S(r?[r.id]:[])}function yse(t){return[...t].sort(vse)[0]}function vse(t,e){return(e.priority??0)-(t.priority??0)}function qM(t,e){return e?e(t):`${t.teamName??"Team"} MOVE ${t.ordinal}`}import{execFile as Ese,spawn as kse}from"node:child_process";import{accessSync as Rse,constants as Ase,existsSync as $g,readdirSync as Cse,statSync as Pse}from"node:fs";import{delimiter as zM,isAbsolute as Rb,join as Hs}from"node:path";import{promisify as _se}from"node:util";function Ib(t,e,r,n=process.platform){return n!=="win32"||!/\.(?:cmd|bat)$/iu.test(t)?{command:t,args:e}:{command:r.ComSpec??r.COMSPEC??"cmd.exe",args:["/d","/s","/v:off","/c",xse(t,e)],windowsVerbatimArguments:!0}}function xse(t,e){return`"${[t,...e].map(Sse).join(" ")}"`}function Sse(t){if(/[%"\u0000-\u001f\u007f]/u.test(t))throw new Error("Windows command-shim paths and arguments cannot contain percent, quote, or control characters.");return`"${t}"`}var bn="0.2.0-next.10",rl="local-bridge-v1";import{win32 as bse}from"node:path";var wse=new Set(["psmodulepath","winpsmodulepath"]);function Eb(t,e){if(/[\u0000-\u001f\u007f]/u.test(t))throw new Error("Windows ACL paths cannot contain control characters.");if(!/^[A-Za-z][A-Za-z0-9]*$/u.test(e))throw new Error("Windows ACL PowerShell variable names must be identifiers.");let r=`$${e}`,n=["$ErrorActionPreference = 'Stop'",`${r} = ${Ise(t)}`,"$sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User","$acl = [System.Security.AccessControl.FileSecurity]::new()","$acl.SetOwner($sid)","$acl.SetAccessRuleProtection($true, $false)","$rule = [System.Security.AccessControl.FileSystemAccessRule]::new($sid, [System.Security.AccessControl.FileSystemRights]::FullControl, [System.Security.AccessControl.AccessControlType]::Allow)","$acl.SetAccessRule($rule)",`[System.IO.File]::SetAccessControl(${r}, $acl)`].join("; ");return{command:"powershell.exe",args:["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(n,"utf16le").toString("base64")]}}function kb(t){let e=bse.basename(t).toLowerCase();return e==="powershell"||e==="powershell.exe"}function Ko(t){let e={};for(let[r,n]of Object.entries(t))wse.has(r.toLowerCase())||n===void 0||(e[r]=n);return e}function Ise(t){return`'${t.replace(/'/g,"''")}'`}var Cb=_se(Ese),jg=3500;async function hu(t={}){let e=t.env??Ar(),r=t.platform??process.platform,n=await Tse({env:e,platform:r,customBinaryPath:t.customBinaryPath}),i=[];for(let c of n){let u=await Dse(c,e,r,t.timeoutMs);if(i.push(u),c.rejectWhitespace&&u.error?.includes("HUNSU_CODEX_APP_SERVER_COMMAND"))return{installed:!1,source:u.source,appServerAvailable:!1,discovery:i,error:u.error};if(u.usable&&u.path)return{installed:!0,binaryPath:u.path,source:u.source,version:u.version,appServerAvailable:!0,discovery:i}}let o=i.find(c=>c.path&&c.versionOk===!0&&c.appServerOk===!1);if(o?.path)return{installed:!0,binaryPath:o.path,source:o.source,version:o.version,appServerAvailable:!1,discovery:i,error:o.error??"Codex was found, but Codex app-server is not available."};let s=i.find(c=>c.source==="windows_apps_alias"||c.path&&GA(c.path,r));if(s)return{installed:!1,binaryPath:s.path,source:"windows_apps_alias",appServerAvailable:!1,discovery:i,aliasDetected:!0,error:s.error??"Codex resolved to a WindowsApps execution alias. Select the real Codex binary path in Hunsu Bridge."};let a=i.find(c=>c.path)??i[0];return{installed:!1,binaryPath:a?.path,source:a?.source??"unknown",appServerAvailable:!1,discovery:i,error:a?.error??"Codex CLI was not found by Hunsu Bridge."}}async function Pb(t){try{let e=t.env??Ar(),r=t.platform??process.platform,n=XM(t.binaryPath,["--version"],e,r),{stdout:i,stderr:o}=await Cb(n.command,n.args,{env:YM(e,r),timeout:t.timeoutMs??jg,windowsHide:!0,windowsVerbatimArguments:n.windowsVerbatimArguments,maxBuffer:64*1024});return`${i}
205
+ ${o}`.trim().split(/\r?\n/).map(a=>a.trim()).find(Boolean)}catch{return}}async function KM(t){let e=t.env??Ar(),r=t.command?{ok:!0,value:{command:t.command,args:t.args??["app-server","--stdio"]}}:qA({env:e,cliBinaryPath:t.binaryPath});if(!r.ok)return{available:!1,error:r.error};let n=new Fg(r.value.command,t.timeoutMs??jg,{env:e,platform:t.platform,args:r.value.args});try{let i=await n.initialize();return{available:!0,initialized:Qr(i)}}catch(i){return{available:!1,error:nl(i)}}finally{n.close()}}function qA(t){let e=t.env.HUNSU_CODEX_APP_SERVER_COMMAND?.trim();if(e&&/\s/.test(e))return{ok:!1,error:"HUNSU_CODEX_APP_SERVER_COMMAND must be a binary path or command name without arguments. Put arguments in HUNSU_CODEX_APP_SERVER_ARGS."};let r=Zh(t.env);if(!r.ok)return{ok:!1,error:r.error.message};let n=t.cliBinaryPath?.trim();return{ok:!0,value:{command:r.value.command==="codex"&&n?n:r.value.command,args:r.value.args}}}function WA(t,e){if(e!=="win32")return[];let r=dp(t,"LOCALAPPDATA","LocalAppData","localappdata"),n=dp(t,"APPDATA","AppData","appdata");return Tb([r?Hs(r,"OpenAI","Codex","bin"):void 0,n?Hs(n,"npm"):void 0,r?Hs(r,"Programs","OpenAI Codex"):void 0])}function VA(t,e){return e!=="win32"?t.PATH??"":[t.PATH,t.Path,t.path,t.HUNSU_WINDOWS_USER_PATH,t.HUNSU_WINDOWS_MACHINE_PATH].filter(r=>typeof r=="string"&&r.trim().length>0).join(";")}async function Tse(t){let{env:e,platform:r}=t,n=[],i=t.customBinaryPath?.trim();i&&n.push({candidate:i,source:"custom"});let o=e.HUNSU_CODEX_BINARY_PATH?.trim();o&&n.push({candidate:o,source:e.HUNSU_CODEX_BINARY_PATH_SOURCE==="user_config"?"custom":"env"});let s=e.HUNSU_CODEX_APP_SERVER_COMMAND?.trim();if(s&&n.push({candidate:s,source:"env",rejectWhitespace:!0}),n.push(...Ab("codex",e,r,_b(e,r)).map(a=>({candidate:a,source:"process_path"}))),r==="win32"){n.push(...Ab("codex",e,r,await VM("user",e,r)).map(c=>({candidate:c,source:"registry_user_path"}))),n.push(...Ab("codex",e,r,await VM("machine",e,r)).map(c=>({candidate:c,source:"registry_machine_path"}))),n.push(...(await Mse(e)).map(c=>({candidate:c,source:"where"}))),n.push(...(await Lse(e)).map(c=>({candidate:c,source:"powershell_get_command"}))),n.push(...Ose(e,r).map(c=>({candidate:c,source:"known_install_dir"})));let a=Use(e,r);a&&n.push({candidate:a,source:"windows_apps_alias"})}return Fse(n)}async function Dse(t,e,r,n){let i=Bse(t.candidate,t.source,e,r,{rejectWhitespace:t.rejectWhitespace});if(i.kind!=="binary")return{source:i.source==="unknown"?t.source:i.source,path:i.kind==="missing"?i.binaryPath:void 0,usable:!1,error:i.error};let o=GA(i.binaryPath,r)?"windows_apps_alias":i.source;if(o==="windows_apps_alias")return{source:o,path:i.binaryPath,usable:!1,versionOk:!1,appServerOk:!1,error:"Codex resolved to a WindowsApps execution alias. Select the real Codex binary path in Hunsu Bridge."};let s=await Pb({binaryPath:i.binaryPath,timeoutMs:n,env:e,platform:r});if(!s)return{source:o,path:i.binaryPath,usable:!1,versionOk:!1,appServerOk:!1,error:"Codex candidate did not return a CLI version."};let a=await KM({binaryPath:i.binaryPath,timeoutMs:n,env:e,platform:r});return a.available?{source:o,path:i.binaryPath,usable:!0,versionOk:!0,appServerOk:!0,version:s}:{source:o,path:i.binaryPath,usable:!1,versionOk:!0,appServerOk:!1,version:s,error:a.error}}function Bse(t,e,r,n,i={}){let o=t.trim();if(!o)return{kind:"missing",installed:!1,source:e??"unknown",error:"Codex command is empty."};if(i.rejectWhitespace&&/\s/.test(o))return{kind:"unsupported_command_string",installed:!1,source:"env",error:"HUNSU_CODEX_APP_SERVER_COMMAND must be a binary path or command name without arguments. Put arguments in HUNSU_CODEX_APP_SERVER_ARGS."};let s=Rb(o)?o:Nse(o,r,n,_b(r,n));if(!s)return{kind:"missing",installed:!1,source:e??"unknown",binaryPath:Rb(o)?o:void 0,error:Rb(o)?"Configured Codex path does not exist.":`Codex command was not found on PATH: ${o}`};if(GA(s,n))return{kind:"missing",installed:!1,source:"windows_apps_alias",binaryPath:s,error:"Codex resolved to a WindowsApps execution alias. Select the real Codex binary path in Hunsu Bridge."};try{return Pse(s).isFile()?(n!=="win32"&&Rse(s,Ase.X_OK),{kind:"binary",installed:!0,binaryPath:s,source:e==="unknown"||e===void 0?"process_path":e}):{kind:"missing",installed:!1,binaryPath:s,source:e??"unknown",error:"Configured Codex path is not a file."}}catch(a){return{kind:"missing",installed:!1,binaryPath:s,source:e??"unknown",error:nl(a)}}}function Nse(t,e,r=process.platform,n=_b(e,r)){return Ab(t,e,r,n)[0]}function Ab(t,e,r=process.platform,n=_b(e,r)){if(Rb(t))return $g(t)?[t]:[];let i=r==="win32"?["",...(e.PATHEXT??e.PathExt??".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean)]:[""],o=r==="win32"?";":zM,s=[];for(let a of n.split(o).filter(Boolean))for(let c of i){let u=Hs(a,r==="win32"&&!t.toUpperCase().endsWith(c.toUpperCase())?`${t}${c}`:t);$g(u)&&s.push(u)}return Tb(s)}function Ose(t,e){if(e!=="win32")return[];let r=dp(t,"LOCALAPPDATA","LocalAppData","localappdata"),n=dp(t,"APPDATA","AppData","appdata"),i=[];if(r){let o=Hs(r,"OpenAI","Codex","bin");if($g(o))for(let s of $se(o))i.push(Hs(o,s,"codex.exe"));i.push(Hs(r,"OpenAI","Codex","bin","codex.exe"),Hs(r,"Programs","OpenAI Codex","codex.exe"))}return n&&i.push(Hs(n,"npm","codex.cmd")),Tb(i.filter($g))}async function VM(t,e,r){if(r!=="win32")return"";let n=t==="user"?e.HUNSU_WINDOWS_USER_PATH:e.HUNSU_WINDOWS_MACHINE_PATH;if(n?.trim())return GM(n,e);let i=t==="user"?"HKCU\\Environment":"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";try{let{stdout:o}=await Cb("reg.exe",["query",i,"/v","Path"],{env:e,timeout:1500,windowsHide:!0,maxBuffer:65536});return GM(Hse(o),e)}catch{return""}}async function Mse(t){try{let{stdout:e}=await Cb("where.exe",["codex"],{env:t,timeout:1500,windowsHide:!0,maxBuffer:65536});return JM(e)}catch{return[]}}async function Lse(t){let e="Get-Command codex -All | ForEach-Object { $_.Source }";for(let r of["powershell.exe","pwsh"])try{let{stdout:n}=await Cb(r,["-NoProfile","-Command",e],{env:r==="powershell.exe"?Ko(t):t,timeout:2e3,windowsHide:!0,maxBuffer:65536}),i=JM(n);if(i.length>0)return i}catch{}return[]}function Hse(t){return t.split(/\r?\n/).map(r=>r.trim()).find(r=>/^Path\s+REG_/i.test(r))?.replace(/^Path\s+REG_\w+\s+/i,"").trim()??""}function JM(t){return Tb(t.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0&&!/^[-\s]+$/.test(e)&&!/^CommandType\b|^Name\b|^Source\b/i.test(e)))}function Use(t,e){if(e!=="win32")return;let r=dp(t,"LOCALAPPDATA","LocalAppData","localappdata"),n=r?Hs(r,"Microsoft","WindowsApps","codex.exe"):void 0;return n&&$g(n)?n:void 0}function _b(t,e){return e!=="win32"?t.PATH??"":[t.PATH,t.Path,t.path].filter(r=>typeof r=="string"&&r.trim().length>0).join(";")}function $se(t){try{return Cse(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}function Fse(t){let e=new Set,r=[];for(let n of t){let i=`${n.source}:${n.candidate}`;e.has(i)||(e.add(i),r.push(n))}return r}function dp(t,...e){return e.map(r=>t[r]).find(r=>typeof r=="string"&&r.trim().length>0)?.trim()}function Tb(t){return[...new Set(t.filter(e=>typeof e=="string"&&e.length>0))]}function GA(t,e){return e==="win32"&&/(?:^|[\\/])WindowsApps[\\/]/i.test(t)}function GM(t,e){return t.replace(/%([^%]+)%/g,(r,n)=>{let i=n.trim(),o=Ar();return dp(e,i,i.toUpperCase(),i.toLowerCase())??o[i]??r})}function XM(t,e,r,n){return Ib(t,e,r,n)}function YM(t,e){let r=Ar(),n={...r,...t},i=e==="win32"?";":zM;for(let o of["PATH","Path","path"]){let s=t[o],a=r[o];if(s===""&&a){n[o]=a;continue}s&&a&&!s.split(i).includes(a)&&(n[o]=`${s}${i}${a}`)}return n}var Fg=class{command;args;timeoutMs;child;nextId=1;buffer="";pending=new Map;constructor(e,r,n={}){this.command=e,this.args=n.args??["app-server","--stdio"],this.timeoutMs=r;let i=n.env??Ar(),o=n.platform??process.platform,s=XM(this.command,this.args,i,o);this.child=kse(s.command,s.args,{env:YM(i,o),stdio:["pipe","pipe","pipe"],windowsHide:!0,windowsVerbatimArguments:s.windowsVerbatimArguments}),this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.read(a)),this.child.stderr.setEncoding("utf8"),this.child.on("error",a=>this.rejectAll(a)),this.child.on("exit",()=>this.rejectAll(new Error("Codex app-server process exited before probe completed.")))}request(e,r){let n=this.nextId;return this.nextId+=1,new Promise((i,o)=>{let s=setTimeout(()=>{this.pending.delete(n),o(new Error(`Codex app-server probe timed out: ${e}`))},this.timeoutMs);this.pending.set(n,{resolve:i,reject:o,timer:s});try{this.write({jsonrpc:"2.0",id:n,method:e,params:r})}catch(a){clearTimeout(s),this.pending.delete(n),o(a instanceof Error?a:new Error(String(a)))}})}async initialize(){let e=await this.request("initialize",{clientInfo:{name:"hunsu-bridge",title:"Hunsu Bridge",version:bn}});return this.notify("initialized",{}),e}notify(e,r){this.write({jsonrpc:"2.0",method:e,params:r})}close(){this.rejectAll(new Error("Codex app-server probe closed.")),this.child.kill()}write(e){this.child.stdin.write(`${JSON.stringify(e)}
206
+ `)}read(e){this.buffer+=e;let r=this.buffer.indexOf(`
207
+ `);for(;r>=0;){let n=this.buffer.slice(0,r).trim();if(this.buffer=this.buffer.slice(r+1),r=this.buffer.indexOf(`
208
+ `),!n)continue;let i;try{i=JSON.parse(n)}catch(s){this.rejectAll(new Error(`Invalid Codex app-server JSON-RPC line: ${nl(s)}`));continue}if(i.id===void 0||typeof i.id!="number")continue;let o=this.pending.get(i.id);o&&(clearTimeout(o.timer),this.pending.delete(i.id),i.error?o.reject(new Error(i.error.message??"Codex app-server request failed.")):o.resolve(i.result))}}rejectAll(e){for(let[r,n]of this.pending)clearTimeout(n.timer),n.reject(e),this.pending.delete(r)}};function zA(t){return Qh(t)}function nl(t){return zA(t instanceof Error?t.message:String(t))}import{existsSync as jse}from"node:fs";import{homedir as t5}from"node:os";import{join as KA}from"node:path";var qse=5e3,il;async function r5(t){let e=t.env??Ar(),r=qA({env:e,cliBinaryPath:t.binaryPath});if(!r.ok)return{appServer:{available:!1,error:r.error}};let n=new Fg(r.value.command,t.timeoutMs??jg,{env:e,platform:t.platform,args:r.value.args});try{let i=await n.initialize(),o=await Wse(n),s=await Vse(n);return{appServer:{available:!0,initialized:Qr(i)},account:o,rateLimits:s}}catch(i){return{appServer:{available:!1,error:nl(i)}}}finally{n.close()}}async function gu(t={}){let e=t.env??Ar(),r=t.platform??process.platform,n=JSON.stringify({customBinaryPath:t.customBinaryPath??e.HUNSU_CODEX_BINARY_PATH,envCommand:e.HUNSU_CODEX_APP_SERVER_COMMAND,envArgs:e.HUNSU_CODEX_APP_SERVER_ARGS,codexHome:e.CODEX_HOME,path:VA(e,r),knownWindowsInstallDirs:WA(e,r),platform:r,lastRunUsage:t.lastRunUsage});if(!t.force&&il&&il.key===n&&Date.now()-il.at<qse)return il.status;let i=await hu(t);if(!i.installed||!i.binaryPath){let C={runtime:"codex",cli:{installed:!1,source:i.source,discovery:i.discovery,installActionAvailable:!0,error:i.error},appServer:{available:!1},auth:{state:"unknown",access:"unknown"},usage:{rateLimitsAvailable:!1,lastRunUsage:t.lastRunUsage},ready:!1,recommendedAction:i.aliasDetected||i.error?.includes("WindowsApps")?"select_binary":"install_codex"};return il={at:Date.now(),key:n,status:C},C}let o=i.version??await Pb({binaryPath:i.binaryPath,timeoutMs:t.timeoutMs,env:e,platform:r}),s=await r5({binaryPath:i.binaryPath,timeoutMs:t.timeoutMs,env:e,platform:r}),a=s.appServer;if(!a.available){let C={runtime:"codex",cli:{installed:!0,binaryPath:i.binaryPath,source:i.source,version:o,discovery:i.discovery,installActionAvailable:!1,error:i.error},appServer:a,auth:{state:"unknown",access:"unknown"},usage:{rateLimitsAvailable:!1,lastRunUsage:t.lastRunUsage},ready:!1,recommendedAction:"recheck"};return il={at:Date.now(),key:n,status:C},C}let c=s.account??{ok:!1,authState:"unknown",error:"Codex account probe did not return a result."},u=s.rateLimits??{ok:!1,error:"Codex rate limit probe did not return a result."},d=c.ok?zse(c.account):{state:c.authState,access:"unknown",error:c.error},l=n5({env:e,platform:r}),f=d.state==="not_authenticated"||d.state==="expired"||d.state==="invalid"?{...d,homeDiagnostic:l}:d,p=u.ok?Xse(u.rateLimits):void 0,g=u.ok?{rateLimitsAvailable:!0,rateLimitSummary:p?.summary,rateLimited:p?.rateLimited,lastRunUsage:t.lastRunUsage}:{rateLimitsAvailable:!1,lastRunUsage:t.lastRunUsage,error:u.error},v=f.state==="authenticated"&&g.rateLimited!==!0,b={runtime:"codex",cli:{installed:!0,binaryPath:i.binaryPath,source:i.source,version:o,discovery:i.discovery,installActionAvailable:!1,error:i.error},appServer:a,auth:f,usage:g,ready:v,recommendedAction:v?"none":f.state==="not_authenticated"||f.state==="expired"||f.state==="invalid"?"login_codex":"recheck"};return il={at:Date.now(),key:n,status:b},b}async function Wse(t){try{let e=await t.request("account/read",{refreshToken:!1});return{ok:!0,account:Qr(e)}}catch(e){let r=nl(e);return{ok:!1,authState:Jse(r),error:r}}}async function Vse(t){try{let e=await t.request("account/rateLimits/read");return{ok:!0,rateLimits:Qr(e)}}catch(e){return{ok:!1,error:nl(e)}}}function n5(t={}){let e=t.env??Ar(),r=t.platform??process.platform,n=Gse(e,r,t.homeDir??t5()),i=e.CODEX_HOME?.trim()||n,o=QM(i),s=QM(n),a=!!(i&&n&&!o&&s&&ZM(i,r)!==ZM(n,r));return{effectiveCodexHome:i,defaultCodexHome:n,authFileExistsAtEffectiveHome:o,authFileExistsAtDefaultHome:s,likelyHomeMismatch:a,remediation:a?{type:"set_codex_home",message:`Codex auth was not found for CODEX_HOME=${i}. Default Codex auth appears to exist at ${n}. Set Codex Home to this path or sign in again for the current Codex Home.`,suggestedCodexHome:n}:o?void 0:{type:"login_again",message:`Codex auth was not found for CODEX_HOME=${i}. Sign in again for this Codex Home.`}}}function Gse(t,e,r=t5()){if(e==="win32"){let n=qg(t,["USERPROFILE","UserProfile","userprofile"]),i=qg(t,["HOMEDRIVE","HomeDrive","homedrive"]),o=qg(t,["HOMEPATH","HomePath","homepath"]),s=n??(i&&o?`${i}${o}`:void 0)??qg(t,["HOME","Home","home"])??r;return KA(s,".codex")}return KA(qg(t,["HOME"])??r,".codex")}function QM(t){return!!(t&&jse(KA(t,"auth.json")))}function ZM(t,e){let r=t.replace(/\\/g,"/").replace(/\/+$/,"");return e==="win32"?r.toLowerCase():r}function qg(t,e){for(let r of e){let n=t[r];if(typeof n=="string"&&n.trim())return n.trim()}}function zse(t){let e=Db(t)?t:{};if(e.requiresOpenaiAuth===!0)return{state:"not_authenticated",access:"unknown"};let r=Kse(e);return{state:"authenticated",method:r,access:r==="api_key"||r==="access_token"?"usage_based":r==="chatgpt"?"subscription":"unknown",accountSummary:{displayName:Jo(e,["displayName","name","userName"]),email:Jo(e,["email","userEmail"]),workspaceName:Jo(e,["workspaceName","organizationName","orgName"]),planLabel:Jo(e,["planLabel","plan","subscriptionPlan"])}}}function Kse(t){let e=Db(t.account)?t.account:{},r=`${Jo(t,["authMethod","method","loginMethod","accountType","type"])??Jo(e,["authMethod","method","loginMethod","accountType","type"])??""}`.toLowerCase();return r.includes("chatgpt")||r.includes("subscription")?"chatgpt":r.includes("api")?"api_key":r.includes("access")?"access_token":"unknown"}function Jse(t){let e=t.toLowerCase();return e.includes("not authenticated")||e.includes("login")||e.includes("sign in")||e.includes("unauthorized")?"not_authenticated":e.includes("expired")?"expired":e.includes("invalid")?"invalid":"error"}function Xse(t){let e=Yse(t),r={label:Jo(e,["label","status","summary"])??(e5(e)?"Rate limited":"Available"),resetAt:Jo(e,["resetAt","reset_at"]),remainingLabel:Jo(e,["remainingLabel","remaining"])};return{summary:r,rateLimited:e5(e)||i5(`${r.label} ${r.remainingLabel??""}`)}}function Yse(t){return Db(t)?Db(t.rateLimits)?{...t,...t.rateLimits}:t:{}}function e5(t){if(t.rateLimited===!0||t.limited===!0)return!0;let e=Jo(t,["rateLimitReachedType","rate_limit_reached_type"]);return e&&e.toLowerCase()!=="none"?!0:i5(Jo(t,["label","status","summary","remainingLabel","remaining"])??"")}function i5(t){return/\brate.?limited\b|quota exceeded|temporarily unavailable|no remaining/i.test(t)}function Jo(t,e){for(let r of e){let n=t[r];if(typeof n=="string"&&n.trim())return zA(n.trim());if(typeof n=="number")return String(n)}}function Db(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}import{isAbsolute as oae,resolve as sae}from"node:path";var JA=[{name:"binaryPath",envName:"HUNSU_CODEX_BINARY_PATH",label:"Codex binary",description:"Path to the Codex CLI executable used by Hunsu.",kind:"file",required:!1,secret:!1,primary:!0,validation:{mustExist:!0,executable:!0}},{name:"codexHome",envName:"CODEX_HOME",label:"Codex home",description:"Directory where Codex stores auth and configuration. Usually ~/.codex.",kind:"directory",required:!1,secret:!1,primary:!0,placeholder:"~/.codex",validation:{directory:!0}},{name:"appServerCommand",envName:"HUNSU_CODEX_APP_SERVER_COMMAND",label:"App-server command",description:"Advanced override for the Codex command used by Hunsu.",kind:"text",required:!1,secret:!1,primary:!1,advanced:!0},{name:"appServerArgs",envName:"HUNSU_CODEX_APP_SERVER_ARGS",label:"App-server args",description:"Advanced app-server arguments.",kind:"text",required:!1,secret:!1,primary:!1,advanced:!0},{name:"authenticationPreference",label:"Authentication method",kind:"select",required:!1,secret:!1,primary:!1,default:"chatgpt",options:[{value:"chatgpt",label:"ChatGPT sign-in"},{value:"device_code",label:"Device code"},{value:"api_key",label:"API key"}]}],Ob={providerId:"codex",label:"Codex",description:"OpenAI Codex CLI through the local app-server boundary.",configKeys:JA,setupSteps:["Choose the Codex executable Hunsu should use.","Choose the Codex Home that contains the auth.json file for this daemon.","Sign in or recheck after saving."]},Qse=new Set(JA.map(t=>t.name));function ol(t){return{...t.baseEnv,...t.settings.binaryPath?{HUNSU_CODEX_BINARY_PATH:t.settings.binaryPath,HUNSU_CODEX_BINARY_PATH_SOURCE:"user_config"}:{},...t.settings.codexHome?{CODEX_HOME:t.settings.codexHome}:{},...t.settings.appServerCommand?{HUNSU_CODEX_APP_SERVER_COMMAND:t.settings.appServerCommand}:{},...t.settings.appServerArgs?{HUNSU_CODEX_APP_SERVER_ARGS:t.settings.appServerArgs}:{}}}function Wg(t){return{HUNSU_CODEX_BINARY_PATH:t.HUNSU_CODEX_BINARY_PATH??null,CODEX_HOME:t.CODEX_HOME??null,HUNSU_CODEX_APP_SERVER_COMMAND:t.HUNSU_CODEX_APP_SERVER_COMMAND??null,HUNSU_CODEX_APP_SERVER_ARGS:t.HUNSU_CODEX_APP_SERVER_ARGS??null}}function Xo(t){let e=Nb(t,"binaryPath"),r=Nb(t,"codexHome"),n=Nb(t,"appServerCommand"),i=Nb(t,"appServerArgs"),o=t?.installChannel==="stable"||t?.installChannel==="latest"||t?.installChannel==="manual"?t.installChannel:void 0,s=t?.authenticationPreference==="chatgpt"||t?.authenticationPreference==="api_key"||t?.authenticationPreference==="device_code"?t.authenticationPreference:void 0;return{...e?{binaryPath:e}:{},...r?{codexHome:r}:{},...n?{appServerCommand:n}:{},...i?{appServerArgs:i}:{},...o?{installChannel:o}:{},...s?{authenticationPreference:s}:{}}}function Mb(t){return JA.map(e=>{let r=t[e.name],n=typeof r=="string"?r:void 0;return{key:e.name,value:n??e.default,isSet:!!n,isSecret:e.secret,label:e.label}})}function sl(t,e){let r={...t};for(let n of e){let i=n.key.trim();if(!Qse.has(i))throw new Error(`Unsupported Codex provider config key: ${i}`);let o=typeof n.value=="string"?n.value.trim():"";switch(i){case"binaryPath":Bb(r,"binaryPath",o);break;case"codexHome":Bb(r,"codexHome",o);break;case"appServerCommand":Bb(r,"appServerCommand",o);break;case"appServerArgs":Bb(r,"appServerArgs",o);break;case"authenticationPreference":if(o==="")delete r.authenticationPreference;else if(o==="chatgpt"||o==="api_key"||o==="device_code")r.authenticationPreference=o;else throw new Error(`Unsupported Codex authenticationPreference: ${o}`);break}}return r}function Bb(t,e,r){r?t[e]=r:delete t[e]}function Nb(t,e){let r=t?.[e];return typeof r=="string"&&r.trim()?r.trim():void 0}import{spawn as Zse,spawnSync as eae}from"node:child_process";var tae="npm is required to install Codex. Install npm and retry, or use Select Existing Codex.";function XA(t=process.platform){return t==="win32"?"npm.cmd":"npm"}function o5(t){let e=XA(t.platform),r={...Ar(),...t.env},n=a5(e,["--version"],r,t.platform),i=eae(n.command,n.args,{encoding:"utf8",stdio:["ignore","pipe","pipe"],env:r,windowsHide:!0,windowsVerbatimArguments:n.windowsVerbatimArguments});if(i.status===0){let o=`${i.stdout??""}
209
+ ${i.stderr??""}`.trim().split(/\r?\n/u).find(Boolean);return{available:!0,command:e,version:o}}return{available:!1,command:e,message:tae}}function YA(t={available:!0,command:XA()}){return{providerId:"codex",available:t.available,label:"Install Codex",command:t.command,args:["install","-g","@openai/codex@latest"],confirmationRequired:!0,instructions:t.available?["Hunsu Bridge can run the Codex npm installer after you confirm.","If Codex is already installed in a custom location, use Select Existing Codex."]:[t.message,"pnpm and yarn cannot run this npm-specific provider installer."]}}var s5=async t=>{let e=XA(),r=["install","-g","@openai/codex@latest"];return t.dryRun?{ok:!0,command:e,args:r}:new Promise(n=>{let i={...Ar(),...t.env},o=a5(e,r,i),s=Zse(o.command,o.args,{stdio:["ignore","pipe","pipe"],env:i,windowsHide:!0,windowsVerbatimArguments:o.windowsVerbatimArguments}),a="",c=u=>{a=`${a}${u.toString()}`.slice(-16*1024)};s.stdout?.on("data",c),s.stderr?.on("data",c),s.once("error",u=>{n({ok:!1,command:e,args:r,output:a.trim(),error:u.message})}),s.once("close",u=>{n({ok:u===0,command:e,args:r,exitCode:u??void 0,output:a.trim(),error:u===0?void 0:`Codex installer exited with status ${u??"unknown"}.`})})})};function a5(t,e,r,n=process.platform){return Ib(t,e,r,n)}import{spawn as tC}from"node:child_process";var yu=new WeakMap;async function Vg(t,e){let r=await hu({env:e});return!r.installed||!r.binaryPath?{started:!1,args:t,message:r.error??"Codex CLI was not found."}:(tC(r.binaryPath,t,{detached:!0,stdio:"ignore",env:{...Ar(),...e},windowsHide:!0}).unref(),{started:!0,command:r.binaryPath,args:t})}async function Lb(t,e){let r=["login"],n=await hu({env:e}),i=new Date().toISOString();if(!n.installed||!n.binaryPath){let o=ja(t,{kind:"chatgpt",startedAt:i,status:"failed",error:n.error??"Codex CLI was not found.",lastOutput:"Browser login failed to start."});return QA(void 0,r,o,!1)}try{let o=tC(n.binaryPath,r,{detached:!0,stdio:"ignore",env:{...Ar(),...e},windowsHide:!0});o.unref();let s=ja(t,{kind:"chatgpt",pid:o.pid,startedAt:i,status:"pending",lastOutput:"Browser login started. Complete sign-in, then click Recheck."});return QA(n.binaryPath,r,s)}catch(o){let s=ja(t,{kind:"chatgpt",startedAt:i,status:"failed",error:o instanceof Error?o.message:String(o),lastOutput:"Browser login failed to start."});return QA(n.binaryPath,r,s,!1)}}async function Hb(t,e,r=3e3){let n=["login","--device-auth"],i=yu.get(t);if(i&&!i.cleared)return ZA(i.child.spawnfile,n,t.codexLogin);let o=await hu({env:e});if(!o.installed||!o.binaryPath){let u=ja(t,{kind:"device",startedAt:new Date().toISOString(),status:"failed",error:o.error??"Codex CLI was not found."});return ZA(void 0,n,u,!1)}let s=tC(o.binaryPath,n,{detached:!0,stdio:["ignore","pipe","pipe"],env:{...Ar(),...e},windowsHide:!0}),a={child:s,startedAt:new Date().toISOString(),output:"",cleared:!1};yu.set(t,a),ja(t,{kind:"device",pid:s.pid,startedAt:a.startedAt,status:"starting"});let c=u=>{if(a.cleared)return;a.output=`${a.output}${u.toString()}`.slice(-64*1024);let d=eC(a.output);ja(t,{kind:"device",pid:s.pid,startedAt:a.startedAt,status:d.verificationUri||d.userCode?"device_code":"pending",...d,lastOutput:a.output.trim().slice(-4096)})};return s.stdout?.on("data",c),s.stderr?.on("data",c),s.once("error",u=>{a.cleared||(ja(t,{kind:"device",pid:s.pid,startedAt:a.startedAt,status:"failed",error:u.message,lastOutput:a.output.trim().slice(-4096)}),yu.delete(t))}),s.once("close",(u,d)=>{if(a.cleared)return;let l=eC(a.output),f=u!==0;ja(t,{kind:"device",pid:s.pid,startedAt:a.startedAt,status:f?"failed":l.verificationUri||l.userCode?"device_code":"completed",...l,lastOutput:a.output.trim().slice(-4096),error:f?`Codex device login exited with status ${u??d??"unknown"}.`:void 0}),yu.delete(t)}),await rae(t,r),ZA(o.binaryPath,n,t.codexLogin)}function c5(t){let e=yu.get(t);e&&(e.cleared=!0,yu.delete(t)),t.codexLogin=void 0}function eC(t){let e=[...t.matchAll(/https?:\/\/[^\s)'"]+/g)].map(s=>s[0].replace(/[.,;:]+$/,"")),r=e.find(s=>/[?&](user_?code|code)=/i.test(s)),n=e.find(s=>s!==r)??r,i=r?iae(r):void 0,o=t.match(/(?:user\s+code|one[-\s]?code|one[-\s]?time\s+code|code)[:\s]+([A-Z0-9][A-Z0-9\-\s]{3,}[A-Z0-9])/i)?.[1]?.trim().replace(/\s+/g,"-");return{...n?{verificationUri:n}:{},...r?{verificationUriComplete:r}:{},...i??o?{userCode:i??o}:{}}}function QA(t,e,r,n=!0){return{started:n,command:t,args:e,state:r.status,status:r.status,lastOutput:r.lastOutput,error:r.error,message:r.status==="failed"?r.error??"Codex login failed to start.":"Codex login started. Complete sign-in in your browser, then click Recheck."}}function ZA(t,e,r,n=!0){let i=r?.status??"pending";return{started:n,command:t,args:e,state:i,status:i,verificationUri:r?.verificationUri,verificationUriComplete:r?.verificationUriComplete,userCode:r?.userCode,lastOutput:r?.lastOutput,error:r?.error,message:i==="failed"?r?.error??"Codex device login failed.":r?.verificationUri||r?.userCode?"Codex device login started. Complete authorization in your browser.":i==="completed"?"Codex device login completed.":"Codex device login started."}}function ja(t,e){return t.codexLogin=e,e}async function rae(t,e){let r=t.codexLogin?.startedAt,n=Date.now()+e;for(;Date.now()<n;){let o=t.codexLogin,s=o&&o.startedAt===r?o.status:void 0;if(s==="device_code"){await nae(t,r);return}if(s==="failed"||s==="completed")return;await u5(50)}let i=yu.get(t);i&&!i.cleared&&t.codexLogin?.startedAt===i.startedAt&&t.codexLogin.status==="starting"&&ja(t,{...t.codexLogin,status:"pending"})}async function nae(t,e,r=100){let n=Date.now()+r;for(;Date.now()<n;){let i=t.codexLogin;if((i&&i.startedAt===e?i.status:void 0)!=="device_code"||!yu.has(t))return;await u5(10)}}function iae(t){try{let e=new URL(t);return e.searchParams.get("user_code")??e.searchParams.get("user-code")??e.searchParams.get("code")??void 0}catch{return}}function u5(t){return new Promise(e=>setTimeout(e,t))}function Gg(){return[rC("codex-default","Codex Default",["default","low","medium","high"],["default","fast"],"default"),rC("gpt-5.5-thinking","GPT-5.5 Thinking",["high","xhigh"],["default","fast"],"high"),rC("gpt-5.5","GPT-5.5",["default","low","medium","high"],["default","fast"],"medium")]}function rC(t,e,r,n,i){return{model:nC(t,"providerInventory.model"),label:nC(e,"providerInventory.model.label"),capabilities:{reasoningEfforts:r,serviceTiers:n,supportsReasoning:r.length>0,supportsFastTier:n.includes("fast")},defaultConfig:{providerId:"codex",model:nC(t,"providerInventory.model.defaultConfig.model"),reasoningEffort:i,serviceTier:"default",...t==="codex-default"?{experimental:!0}:{}}}}function nC(t,e){return er(Ee(t,e))}var aae={canExecute:!0,canEditFiles:!0,canRunShell:!0,supportsWorktree:!0,supportsEventStream:!0,supportsUsage:!0,supportsSubscriptionAuth:!0,supportsDeviceAuth:!0,supportsApiKeyAuth:!0,supportsRemoteAccess:!0,supportsAcp:!1},al=class{providerId="codex";kind="codex";label="Codex";settings;internalLoginState={};options;constructor(e={}){this.options=e,this.settings=Xo(e.settings)}metadata(){return Ob}async readConfig(){return Mb(this.settings)}async validateConfig(e){let r=sl(this.settings,e);return this.validateSettings(r)}async saveConfig(e){let r=sl(this.settings,e),n=await this.validateSettings(r);if(!n.valid)throw new Error(n.provider.safeMessage??n.provider.auth.error??n.provider.install?.error??"Codex provider configuration is invalid.");return this.settings=r,this.options.onConfigure?.(this.settings),n.provider}async deleteConfig(e){return this.settings=e&&e.length>0?sl(this.settings,e.map(r=>({key:r,value:"",isSet:!1,isSecret:!1}))):{},this.options.onConfigure?.(this.settings),this.status({force:!0})}effectiveEnv(e={}){return this.statusEnv(e)}async status(e={}){let r=this.statusEnv(e.env),n=await gu({force:e.force,env:r});return iC(n,{effectiveEnv:Wg(r)})}async recheck(){return this.status({force:!0})}async installPlan(){return YA(await this.installerPrerequisite(this.statusEnv()))}async install(e={}){let r=this.statusEnv(e.env),n=await this.status({force:!0,env:r}),i=await this.installerPrerequisite(r),o=YA(i);if(n.installed)return{providerId:this.providerId,confirmed:e.confirmed===!0,started:!1,status:"already_installed",message:"Codex is already installed.",plan:o,providerStatus:n};if(!i.available)return{providerId:this.providerId,confirmed:e.confirmed===!0,started:!1,status:"prerequisite_missing",message:i.message,plan:o,providerStatus:n};if(e.confirmed!==!0)return{providerId:this.providerId,confirmed:!1,started:!1,status:"confirmation_required",message:"Confirm Codex installation before Hunsu Bridge runs the installer.",plan:o,providerStatus:n};let a=await(this.options.installer??s5)({env:r,dryRun:e.dryRun===!0||r.HUNSU_CODEX_INSTALL_DRY_RUN==="1"}),c=await this.status({force:!0,env:r});return{providerId:this.providerId,confirmed:!0,started:!0,status:a.ok?a.exitCode===void 0?"dry_run":"completed":"failed",message:a.ok?a.exitCode===void 0?"Codex install dry run completed. No installer was run.":"Codex installer completed. Provider status was rechecked.":a.error??"Codex installer failed.",plan:o,command:a.command,args:a.args,exitCode:a.exitCode,output:a.output,error:a.error,providerStatus:c}}async login(e){let r=e.method==="default"?fae(this.settings.authenticationPreference):e.method,n=this.statusEnv(),i=this.options.loginState??this.internalLoginState;if(r==="device")return{providerId:this.providerId,method:r,...await Hb(i,n)};if(r==="api_key"){let o=await Vg(["login","--api-key"],n);return{providerId:this.providerId,method:r,...o,message:o.started?"Codex API-key login started.":o.message??"Codex API-key login could not start."}}return{providerId:this.providerId,method:r,...await Lb(i,n)}}async configure(e){if(e.authMethod==="api_key")return this.configureApiKey(e);if(e.clearBinaryPath){let i={...this.settings};return delete i.binaryPath,this.settings=i,this.options.onConfigure?.(this.settings),this.status({force:!0,env:e.env})}let r=e.binaryPath?.trim()||e.selectBinaryPath?.trim();if(!r)return this.status({force:!0,env:e.env});let n=oae(r)?r:sae(r);return this.saveConfig([{key:"binaryPath",value:n,isSet:!0,isSecret:!1}])}async configureApiKey(e){let r=e.apiKey?.trim(),n=r?this.statusEnv({...e.env,OPENAI_API_KEY:r}):this.statusEnv(e.env);return this.status({force:!0,env:n})}statusEnv(e={}){return ol({baseEnv:this.baseEnv(e),settings:this.settings})}installerPrerequisite(e){return Promise.resolve((this.options.installerPrerequisite??o5)({env:e}))}baseEnv(e={}){return{...Ar(),...this.options.env?.()??{},...e}}async validateSettings(e){let r=ol({baseEnv:this.baseEnv(),settings:e}),n=await gu({force:!0,env:r,customBinaryPath:e.binaryPath}),i=iC(n,{effectiveEnv:Wg(r)}),o=n.cli.installed===!0&&!!n.cli.version&&n.appServer.available===!0;return{valid:o,provider:i,diagnostics:i.diagnostics??{effectiveEnv:Wg(r)},errors:o?[]:cae(e,n)}}};function cae(t,e){return!e.cli.installed||!e.cli.version?[{field:"binaryPath",message:t.binaryPath?"Select a Codex executable that Hunsu Bridge can run.":"Select an existing Codex executable or install Codex first."}]:e.appServer.available?[]:[{field:t.appServerCommand?"appServerCommand":t.appServerArgs?"appServerArgs":"binaryPath",message:"Codex app-server could not be started with this setting."}]}function iC(t,e={}){let r=t.cli.installed,n=r&&t.appServer.available,i=t.auth.state==="authenticated"?!0:t.auth.state==="unknown"||t.auth.state==="error"?"unknown":!1;return{providerId:"codex",kind:"codex",label:"Codex",description:"OpenAI Codex CLI through the local app-server boundary.",connectionKind:"local_cli",installed:r,configured:n,authenticated:i,ready:t.ready,auth:{kind:uae(t),state:t.auth.state,access:t.auth.access,accountSummary:t.auth.accountSummary,error:t.auth.error,homeDiagnostic:t.auth.homeDiagnostic},install:{installed:r,binaryPath:t.cli.binaryPath,source:t.cli.source,version:t.cli.version,error:t.cli.error,discovery:t.cli.discovery},usage:{available:t.usage.rateLimitsAvailable,rateLimited:t.usage.rateLimited,summary:t.usage.rateLimitSummary,lastRunUsage:t.usage.lastRunUsage,error:t.usage.error},capabilities:aae,modelInventory:{state:"available",models:Gg()},recommendedAction:dae(t),diagnostics:{...e.effectiveEnv?{effectiveEnv:e.effectiveEnv}:{},...t.auth.homeDiagnostic?{codexHome:t.auth.homeDiagnostic}:{}},safeMessage:lae(t)}}async function zg(t,e,r={}){let n=await gu({env:t,force:r.force,lastRunUsage:r.lastRunUsage});return n.auth.state==="authenticated"&&e.codexLogin&&c5(e),e.codexLogin?{...n,codexLogin:e.codexLogin}:n}function uae(t){return t.auth.method==="chatgpt"?"chatgpt_oauth":t.auth.method==="api_key"||t.auth.method==="access_token"?"api_key":t.auth.state==="not_authenticated"?"chatgpt_oauth":"unknown"}function dae(t){return t.recommendedAction==="install_codex"?"install":t.recommendedAction==="select_binary"?"select_binary":t.recommendedAction==="login_codex"?"login":t.recommendedAction==="recheck"?"recheck":"none"}function lae(t){return t.recommendedAction==="select_binary"?"Select the real Codex binary path. WindowsApps aliases cannot be used for Execute.":t.cli.installed?t.appServer.available?t.auth.homeDiagnostic?.likelyHomeMismatch&&t.auth.homeDiagnostic.remediation?.message?t.auth.homeDiagnostic.remediation.message:t.auth.state==="not_authenticated"?"Sign in to Codex to enable Execute.":t.auth.state==="expired"||t.auth.state==="invalid"?"Codex sign-in needs to be refreshed.":t.usage.rateLimited?"Codex is temporarily rate limited.":t.ready?"Codex is ready.":"Codex needs attention.":"Codex is installed, but the app-server is not available.":"Codex was not found by Hunsu Bridge."}function fae(t){return t==="device_code"?"device":t==="api_key"?"api_key":"chatgpt"}import{existsSync as Cae,mkdirSync as Pae,readFileSync as _ae,renameSync as Tae,writeFileSync as Dae}from"node:fs";import{dirname as Bae}from"node:path";import{homedir as pae}from"node:os";import{posix as d5,win32 as l5}from"node:path";function mae(t={}){let e=t.platform??process.platform,r=e==="win32"?l5:d5,n=t.env??{},i=Kg(t.home)??Kg(n.HUNSU_HOME);if(i)return r.isAbsolute(i)?i:r.resolve(i);let o=Kg(t.userHome)??pae();if(e==="win32"){let s=Kg(t.localAppData)??Kg(n.LOCALAPPDATA)??r.join(o,"AppData","Local");return r.join(s,"Hunsu","Bridge")}return e==="darwin"?r.join(o,"Library","Application Support","Hunsu","Bridge"):r.join(o,".local","share","hunsu","bridge")}function Yo(t={}){let e=mae(t),r=(t.platform??process.platform)==="win32"?l5:d5,n=r.join(e,"logs"),i=r.join(e,"runtime");return{home:e,homeOwnershipFile:r.join(e,".hunsu-bridge-home.json"),configFile:r.join(e,"config.json"),workspacesFile:r.join(e,"workspaces.json"),credentialsFile:r.join(e,"credentials.json"),runtimeFile:r.join(e,"runtime.json"),logsDirectory:n,structuredLogFile:r.join(n,"bridge.jsonl"),runtimeDirectory:i,runtimeStagingDirectory:r.join(i,"staging"),runtimeVersionsDirectory:r.join(i,"versions"),runtimeInstallFile:r.join(i,"install.json"),setupTransactionFile:r.join(i,"setup-transaction.json"),setupLockFile:r.join(i,"setup.lock"),daemonLockFile:r.join(i,"daemon.lock")}}function Kg(t){let e=t?.trim();return e||void 0}import{access as Iae}from"node:fs/promises";import{mkdir as hae,open as gae,readFile as yae,rename as vae,unlink as xae}from"node:fs/promises";import{basename as Jg,dirname as Sae,join as bae}from"node:path";import{randomBytes as wae}from"node:crypto";var Kn=class extends Error{code="BRIDGE_STATE_INVALID";file;constructor(e,r,n){super(r,n),this.name="BridgeStateError",this.file=e}};async function Yi(t){let e;try{e=await yae(t,"utf8")}catch(r){if(Ot(r)&&r.code==="ENOENT")return;throw new Kn(t,`Unable to read Bridge state file: ${Jg(t)}.`,{cause:r})}try{return JSON.parse(e)}catch(r){throw new Kn(t,`Bridge state file is not valid JSON: ${Jg(t)}.`,{cause:r})}}async function wn(t,e,r={}){let n=Sae(t),i=r.mode??384;await hae(n,{recursive:!0,mode:448});let o=bae(n,`.${Jg(t)}.${process.pid}.${wae(8).toString("hex")}.tmp`),s;try{s=await gae(o,"wx",i),await s.writeFile(`${JSON.stringify(e,null,2)}
210
+ `,"utf8"),await s.sync(),await s.chmod(i),await s.close(),s=void 0,await r.prepareTemporaryFile?.(o),await vae(o,t),r.onCommitted?.()}catch(a){throw new Kn(t,`Unable to persist Bridge state file: ${Jg(t)}.`,{cause:a})}finally{await s?.close().catch(()=>{}),await xae(o).catch(a=>{if(!Ot(a)||a.code!=="ENOENT")throw a})}}function xe(t,e){return new Kn(t,`Bridge state file is invalid (${Jg(t)}): ${e}`)}function Ot(t){return t instanceof Error&&"code"in t}var $b="hunsu.bridge.config.v1",lp="hunsu.bridge.config.v2",f5=Object.freeze({schema:lp,deploymentProfile:"production",host:"127.0.0.1",port:19687,provider:Object.freeze({kind:"unconfigured"}),remote:Object.freeze({enabled:!1})});function Qo(t){let e=Promise.resolve(),r=async()=>{let i=await Yi(t.configFile);return i===void 0?m5(f5):vu(t.configFile,i)},n=i=>{let o=e.then(i,i);return e=o.then(()=>{},()=>{}),o};return{async read(){return await e,r()},async write(i){await n(async()=>{await wn(t.configFile,vu(t.configFile,i))})},async update(i){return n(async()=>{let o=vu(t.configFile,i(await r()));return await wn(t.configFile,o),o})},async ensureDeploymentProfile(i){return n(async()=>{let o=await Yi(t.configFile);if(o===void 0){if(i!=="production"&&await Rae(t))throw xe(t.configFile,"a populated HUNSU_HOME without an explicit profile is treated as production and cannot switch to preview");let a={...m5(f5),deploymentProfile:i};return await wn(t.configFile,a),a}let s=vu(t.configFile,o);if(s.deploymentProfile!==i)throw xe(t.configFile,`deploymentProfile is ${s.deploymentProfile} and cannot switch to ${i} in a populated HUNSU_HOME`);return Aae(o)&&await wn(t.configFile,s),s})}}}function vu(t,e){if(!Fb(e)||e.schema!==lp&&e.schema!==$b)throw xe(t,`expected schema ${lp} or ${$b}`);let r=e.schema===$b?"production":Eae(t,e.deploymentProfile);if(typeof e.host!="string"||e.host.trim()==="")throw xe(t,"host must be a non-empty string");if(!Number.isInteger(e.port)||e.port<0||e.port>65535)throw xe(t,"port must be an integer from 0 through 65535");if(!Fb(e.remote)||typeof e.remote.enabled!="boolean")throw xe(t,"remote.enabled must be a boolean");let n=kae(t,e.provider);return{schema:lp,deploymentProfile:r,host:e.host.trim(),port:e.port,provider:n,remote:{enabled:e.remote.enabled}}}function Eae(t,e){if(!Pn(e))throw xe(t,"deploymentProfile must be production or preview");return e}function kae(t,e){if(!Fb(e))throw xe(t,"provider must be configured explicitly");if(e.kind==="unconfigured")return{kind:"unconfigured"};if(e.kind!=="codex")throw xe(t,"provider.kind must be unconfigured or codex");let r=Ub(t,"provider.binaryPath",e.binaryPath),n=Ub(t,"provider.home",e.home),i=Ub(t,"provider.appServerCommand",e.appServerCommand),o=Ub(t,"provider.appServerArgs",e.appServerArgs),s=p5(t,"provider.installChannel",e.installChannel,["stable","latest","manual"]),a=p5(t,"provider.authenticationPreference",e.authenticationPreference,["chatgpt","api_key","device_code"]);return{kind:"codex",...r?{binaryPath:r}:{},...n?{home:n}:{},...i?{appServerCommand:i}:{},...o?{appServerArgs:o}:{},...s?{installChannel:s}:{},...a?{authenticationPreference:a}:{}}}function p5(t,e,r,n){if(r!==void 0){if(typeof r!="string"||!n.includes(r))throw xe(t,`${e} must be one of ${n.join(", ")} when present`);return r}}function Ub(t,e,r){if(r!==void 0){if(typeof r!="string"||r.trim()==="")throw xe(t,`${e} must be a non-empty string when present`);return r}}function m5(t){return{...t,provider:{...t.provider},remote:{...t.remote}}}async function Rae(t){let e=[t.homeOwnershipFile,t.credentialsFile,t.workspacesFile,t.runtimeFile,t.runtimeInstallFile,t.setupTransactionFile];return(await Promise.all(e.map(async n=>{try{return await Iae(n),!0}catch(i){if(Ot(i)&&i.code==="ENOENT")return!1;throw xe(n,"durable Bridge state could not be inspected safely")}}))).some(Boolean)}function Aae(t){return Fb(t)&&t.schema===$b}function Fb(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function jb(){return{currentProviderId:"codex",providers:{codex:{enabled:!0,settings:{}}}}}function Yg(t){let e=jb();if(!Xg(t))return e;let r=Xg(t.providers)?Object.fromEntries(Object.entries(t.providers).map(([n,i])=>{let o=Xg(i)?i:{};return[n,{enabled:n==="codex"&&o.enabled!==!1,settings:Xg(o.settings)?o.settings:{}}]})):{};return r.codex={enabled:!0,settings:Xg(r.codex?.settings)?r.codex.settings:{}},{currentProviderId:t.currentProviderId==="codex"?"codex":e.currentProviderId,providers:r}}function h5(t=Ar()){return Yo({env:t}).configFile}function Nae(t=Ar()){let e=y5(h5(t));return!e||e.provider.kind!=="codex"?jb():Yg({currentProviderId:"codex",providers:{codex:{enabled:!0,settings:{...e.provider.binaryPath?{binaryPath:e.provider.binaryPath}:{},...e.provider.home?{codexHome:e.provider.home}:{},...e.provider.appServerCommand?{appServerCommand:e.provider.appServerCommand}:{},...e.provider.appServerArgs?{appServerArgs:e.provider.appServerArgs}:{},...e.provider.installChannel?{installChannel:e.provider.installChannel}:{},...e.provider.authenticationPreference?{authenticationPreference:e.provider.authenticationPreference}:{}}}}})}function g5(t=Ar()){let e=h5(t);return{read:()=>Nae(t),write(r){let n=y5(e)??{schema:lp,deploymentProfile:"production",host:"127.0.0.1",port:19687,provider:{kind:"unconfigured"},remote:{enabled:!1}},i=Xo(r.providers.codex?.settings),o={...n,provider:{kind:"codex",...i.binaryPath?{binaryPath:i.binaryPath}:{},...i.codexHome?{home:i.codexHome}:{},...i.appServerCommand?{appServerCommand:i.appServerCommand}:{},...i.appServerArgs?{appServerArgs:i.appServerArgs}:{},...i.installChannel?{installChannel:i.installChannel}:{},...i.authenticationPreference?{authenticationPreference:i.authenticationPreference}:{}}};Oae(e,o)}}}function y5(t){if(Cae(t))try{let e=JSON.parse(_ae(t,"utf8"));return vu(t,e)}catch{return}}function Oae(t,e){Pae(Bae(t),{recursive:!0});let r=`${t}.tmp-${process.pid}-${Date.now()}`;Dae(r,`${JSON.stringify(e,null,2)}
211
+ `,{encoding:"utf8",mode:384}),Tae(r,t)}function Xg(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var v5={canExecute:!1,canEditFiles:!1,canRunShell:!1,supportsWorktree:!1,supportsEventStream:!1,supportsUsage:!1,supportsSubscriptionAuth:!1,supportsDeviceAuth:!1,supportsApiKeyAuth:!1,supportsRemoteAccess:!1,supportsAcp:!1};var Mae={codex:"Codex",claude_code:"Claude Code",gemini_cli:"Gemini CLI",openhands:"OpenHands Agent Server",acp_agent:"ACP Agent",litellm_gateway:"LiteLLM Gateway",openrouter_gateway:"OpenRouter Gateway",custom:"Custom Provider"};function oC(t={}){let e=Yg(t.providerState??t.providerStateStore?.read()??{...jb(),currentProviderId:t.currentProviderId??"codex"}),r=e.providers[e.currentProviderId]?.enabled?e.currentProviderId:"codex",n=t.providers??[new al({...t.codex,settings:e.providers.codex?.settings??{},onConfigure(i){e=Lae(e,i),t.providerStateStore?.write(e),t.codex?.onConfigure?.(i)}}),cl("claude_code"),cl("gemini_cli"),cl("openhands"),cl("acp_agent"),cl("litellm_gateway"),cl("openrouter_gateway")];return{list:()=>[...n],get:i=>n.find(o=>o.providerId===i),current:()=>n.find(i=>i.providerId===r)??n[0],async setCurrent(i){let o=n.find(s=>s.providerId===i);if(!o)throw new Error(`Unknown runtime provider: ${i}`);if(o.providerId!=="codex"||e.providers[o.providerId]?.enabled!==!0)throw new Error(`${o.label} is not an enabled runtime provider yet.`);r=o.providerId,e=Yg({...e,currentProviderId:r}),t.providerStateStore?.write(e)}}}function Lae(t,e){let r=Hae(e);return Yg({...t,providers:{...t.providers,codex:{enabled:!0,settings:r}}})}function Hae(t){let e=Xo(t),r={};for(let[n,i]of Object.entries(e))i!==void 0&&(r[n]=i);return r}function cl(t){let e=Mae[t];return{providerId:t,kind:t,label:e,hiddenByDefault:!0,metadata(){return{providerId:t,label:e,description:"Future runtime provider.",configKeys:[]}},async readConfig(){return[]},async saveConfig(){throw new Error(`${e} does not support configuration yet.`)},async status(){return{providerId:t,kind:t,label:e,description:"Future runtime provider.",connectionKind:t.includes("gateway")?"gateway":t==="openhands"||t==="acp_agent"?"remote_agent_server":"local_cli",installed:!1,configured:!1,authenticated:"unknown",ready:!1,auth:{kind:"unknown",state:"unknown",access:"unknown"},install:{installed:!1},usage:{available:!1},capabilities:v5,modelInventory:{state:"unavailable",reason:"not_supported",message:`${e} does not publish a model inventory yet.`},recommendedAction:"configure",safeMessage:"Coming later"}},async recheck(){return this.status()}}}async function b5(t,e,r,n,i){if(t.method==="GET"&&r==="/api/providers"){let o=n.searchParams.get("advanced")==="1"||n.searchParams.get("advanced")==="true",s=i.providerRegistry.list().filter(a=>o||!a.hiddenByDefault);return i.sendJson(e,200,{currentProviderId:i.providerRegistry.current().providerId,providers:await Promise.all(s.map(a=>a.status({env:i.env})))}),!0}if(t.method==="GET"&&r==="/api/codex/status"&&i.legacyCodexStatus){let o=await i.legacyCodexStatus();return i.sendJson(e,200,i.sanitizeLegacyCodexStatus?i.sanitizeLegacyCodexStatus(o):o),!0}if(t.method==="GET"&&r==="/api/runtimes/codex/status"){let o=fp(i);return i.sendJson(e,200,await zg(o,i.codexLoginState??{},{lastRunUsage:i.latestCodexRunUsage?.()})),!0}if(t.method==="POST"&&r==="/api/runtimes/codex/recheck"){let o=fp(i);return i.sendJson(e,202,await zg(o,i.codexLoginState??{},{force:!0,lastRunUsage:i.latestCodexRunUsage?.()})),!0}if(t.method==="POST"&&r==="/api/runtimes/codex/install"){let o=await S5(t,i.readJson),s=i.providerRegistry.get("codex")??i.providerRegistry.current();return i.sendJson(e,202,s.install?await s.install({confirmed:o.confirmed,dryRun:o.dryRun,env:i.env}):await s.installPlan?.()),!0}if(t.method==="POST"&&r==="/api/runtimes/codex/login/chatgpt"){let o=i.providerRegistry.get("codex")??i.providerRegistry.current();return i.sendJson(e,202,o.login?await o.login({method:"chatgpt"}):await Lb(i.codexLoginState??{},fp(i))),!0}if(t.method==="POST"&&r==="/api/runtimes/codex/login/device"){let o=i.providerRegistry.get("codex")??i.providerRegistry.current();return i.sendJson(e,202,o.login?await o.login({method:"device"}):await Hb(i.codexLoginState??{},fp(i))),!0}if(t.method==="POST"&&r==="/api/runtimes/codex/login/api-key"){let o=i.providerRegistry.get("codex")??i.providerRegistry.current();return i.sendJson(e,202,o.login?await o.login({method:"api_key"}):await Vg(["login","--api-key"],fp(i))),!0}if(t.method==="POST"&&r==="/api/runtimes/codex/logout")return i.sendJson(e,202,await Vg(["logout"],fp(i))),!0;if(t.method==="GET"&&r==="/api/providers/current")return i.sendJson(e,200,await i.providerRegistry.current().status({env:i.env})),!0;if(t.method==="GET"&&r==="/api/providers/current/metadata")return i.sendJson(e,200,i.providerRegistry.current().metadata()),!0;if(t.method==="GET"&&r==="/api/providers/current/config")return i.sendJson(e,200,await sC(i.providerRegistry.current(),i)),!0;if(t.method==="POST"&&r==="/api/providers/current/validate"){let o=await x5(t,i.readJson),s=i.providerRegistry.current();return s.validateConfig?(i.sendJson(e,200,await s.validateConfig(o.fields)),!0):(i.sendJson(e,501,{error:"Current provider does not support configuration validation yet."}),!0)}if(t.method==="POST"&&r==="/api/providers/current/config"){let o=await x5(t,i.readJson),s=i.providerRegistry.current();return await s.saveConfig(o.fields),i.sendJson(e,202,await sC(s,i)),!0}if(t.method==="DELETE"&&(r==="/api/providers/current/config"||r.startsWith("/api/providers/current/config/"))){let o=i.providerRegistry.current();return o.deleteConfig?(await o.deleteConfig(Uae(r,n)),i.sendJson(e,202,await sC(o,i)),!0):(i.sendJson(e,501,{error:"Current provider does not support configuration reset yet."}),!0)}if(t.method==="POST"&&r==="/api/providers/current/recheck")return i.sendJson(e,202,await i.providerRegistry.current().status({env:i.env,force:!0})),!0;if(t.method==="POST"&&r==="/api/providers/current/install"){let o=i.providerRegistry.current();if(!o.install)return i.sendJson(e,501,{error:"Current provider does not support installation yet."}),!0;let s=await S5(t,i.readJson);return i.sendJson(e,202,await o.install({confirmed:s.confirmed,dryRun:s.dryRun,env:i.env})),!0}if(t.method==="POST"&&r==="/api/providers/current/login"){let o=await i.readJson(t),s=i.providerRegistry.current();return s.login?(i.sendJson(e,202,await s.login({method:o.method??"default"})),!0):(i.sendJson(e,501,{error:"Current provider does not support login yet."}),!0)}if(t.method==="POST"&&r==="/api/providers/current/authenticate"){let o=await i.readJson(t),s=i.providerRegistry.current();return s.login?(i.sendJson(e,202,await s.login({method:o.method??"default"})),!0):(i.sendJson(e,501,{error:"Current provider does not support authentication yet."}),!0)}if(t.method==="POST"&&r==="/api/providers/current/configure"){let o=await i.readJson(t),s=i.providerRegistry.current();return s.configure?(i.sendJson(e,202,await s.configure({...o,env:i.env})),!0):(i.sendJson(e,501,{error:"Current provider does not support configuration yet."}),!0)}return!1}function Uae(t,e){let r="/api/providers/current/config/";if(t.startsWith(r)){let i=decodeURIComponent(t.slice(r.length)).trim();return i?[i]:void 0}let n=e.searchParams.getAll("key").map(i=>i.trim()).filter(Boolean);return n.length>0?n:void 0}function fp(t){let r=t.providerRegistry.get("codex");return r?.effectiveEnv?r.effectiveEnv(t.env):t.env}async function sC(t,e){let r=await t.status({env:e.env,force:!0});return{providerId:t.providerId,metadata:t.metadata(),fields:await t.readConfig(),status:r,diagnostics:r.diagnostics}}async function x5(t,e){let r=await e(t);return{fields:Array.isArray(r)?r:r.fields??[]}}async function S5(t,e){try{return await e(t)}catch{return{}}}import{existsSync as $ae}from"node:fs";var Fae=["local-pairing","project-finder","roadmap-registry","artifact-actions","connection-status","headless-daemon","remote-ready"],jae={minBridgeVersion:bn,requiredProtocolVersion:rl,requiredFeatures:["local-pairing","connection-status"]};function ul(){return{bridgeVersion:bn,protocolVersion:rl,supportedFeatures:[...Fae]}}function I5(t,e,r="0.1.0"){if(w5(t.bridgeVersion,e.minBridgeVersion)<0)return{compatible:!1,reason:"bridge_update_needed",message:`Bridge ${t.bridgeVersion} is older than required ${e.minBridgeVersion}.`};if(t.protocolVersion!==e.requiredProtocolVersion)return{compatible:!1,reason:"bridge_update_needed",message:`Bridge protocol ${t.protocolVersion} does not match required ${e.requiredProtocolVersion}.`};let n=e.requiredFeatures.find(i=>!t.supportedFeatures.includes(i));return n?{compatible:!1,reason:"feature_unavailable",message:`Bridge feature is unavailable: ${n}.`}:t.minSupportedStudioVersion&&w5(r,t.minSupportedStudioVersion)<0?{compatible:!1,reason:"studio_update_needed",message:`Studio ${r} is older than Bridge requires ${t.minSupportedStudioVersion}.`}:{compatible:!0}}function aC(t){let e=[];qae(t.runtimeConfig.bridgeApi.host)&&e.push("public_bind"),t.repositoryPath&&!$ae(t.repositoryPath)&&e.push("project_missing");let r=t.bridgeVersion??ul(),n=I5(r,t.requirement??jae,t.studioVersion);n.compatible||e.push("version_mismatch");let i=t.error??(n.compatible?void 0:n.message);return{mode:"local",transport:"direct",health:i===void 0?"connected":"error",auth:t.auth??"paired",projectAccess:t.projectAccess??(t.repositoryPath?"granted":"not_applicable"),bridge:{id:`local:${t.runtimeConfig.bridgeApi.host}:${t.runtimeConfig.bridgeApi.port}`,name:"Local Bridge",version:r.bridgeVersion,protocolVersion:r.protocolVersion,startedAt:t.startedAt,lastSeenAt:new Date().toISOString()},endpoint:{apiUrl:t.bridgeApiUrl},project:t.repositoryPath?{roadmapId:t.roadmapId,displayName:t.roadmapDisplayName,repositoryPath:t.repositoryPath}:void 0,warnings:e,error:i,version:r,compatibility:n}}function w5(t,e){let r=t.split(/[.-]/).map(o=>Number.parseInt(o,10)),n=e.split(/[.-]/).map(o=>Number.parseInt(o,10)),i=Math.max(r.length,n.length);for(let o=0;o<i;o+=1){let s=Number.isFinite(r[o])?r[o]:0,a=Number.isFinite(n[o])?n[o]:0;if(s!==a)return s>a?1:-1}return 0}function qae(t){return t==="0.0.0.0"||t==="::"||t==="[::]"}async function E5(t,e,r,n){if(t.method==="GET"&&r==="/api/connection/status")return n.sendJson(e,200,n.studioConnectionStatus()),!0;if(t.method==="GET"&&r==="/api/bridge/status")return n.sendJson(e,200,await n.bridgeStatus()),!0;if(t.method==="GET"&&r==="/api/connections"){let i=await n.bridgeStatus();return n.sendJson(e,200,{connections:i.connections}),!0}if(t.method==="GET"&&r==="/api/connections/local"){let i=await n.bridgeStatus();return n.sendJson(e,200,{connection:i.connections.find(o=>o.mode==="local")}),!0}return t.method==="GET"&&r==="/api/connections/remote"?(n.sendJson(e,200,{connections:[]}),!0):t.method==="POST"&&r==="/api/connections/remote/enable"?n.headlessRemote?(n.sendJson(e,202,{enabled:!0,remote:await n.headlessRemote.enable()}),!0):(n.sendJson(e,503,{error:"remote_unavailable",message:"Remote access is owned by the headless Bridge service."}),!0):t.method==="POST"&&r==="/api/connections/remote/disable"?n.headlessRemote?(n.sendJson(e,202,{enabled:!1,remote:await n.headlessRemote.disable()}),!0):(n.sendJson(e,503,{error:"remote_unavailable",message:"Remote access is owned by the headless Bridge service."}),!0):!1}function xu(t,e){let r=cC(t.lifecycle),n=e.redactPath?void 0:t.repositoryPath;return{workspaceId:t.roadmapId,roadmapId:t.roadmapId,displayName:t.displayName,path:n,pathRedacted:e.redactPath||void 0,lifecycle:r,health:Wae(t),backendId:e.backendId??"local",connectionMode:e.connectionMode??"local",provider:{providerId:e.provider.providerId,label:e.provider.label,readyForExecute:e.provider.ready},actions:Vae(r,t.primaryAction)}}function Su(t,e){return t.filter(r=>e.activeOnly!==!0||cC(r.lifecycle)==="active").filter(r=>e.remoteOnly!==!0||r.remoteAccess?.enabled===!0&&cC(r.lifecycle)==="active").map(r=>xu(r,e))}function cC(t){return t==="inactive"||t==="missing"||t==="needs_upgrade"||t==="error"?t:"active"}function Wae(t){return t.lifecycle==="missing"||t.health==="missing"?"missing":t.lifecycle==="needs_upgrade"||t.health==="needs-upgrade"||t.health==="missing-runtime"?"needs_upgrade":t.lifecycle==="error"?"error":t.health==="ok"||t.health==="git-dirty"?"ok":"unknown"}function Vae(t,e){let r=[];return t==="active"?r.push("open_studio","deactivate"):t==="inactive"?r.push("activate","remove"):r.push(e==="repair"?"repair":"remove"),r}async function R5(t,e,r,n){if(await Gae(t,e,r,n))return!0;if(t.method==="GET"&&r==="/api/workspaces"){let i=await n.bridgeStatus();return n.sendJson(e,200,i.workspaces),!0}if(t.method==="GET"&&r==="/api/workspaces/active"){let i=await n.bridgeStatus();return n.sendJson(e,200,{workspaces:i.workspaces.active}),!0}if(t.method==="GET"&&r==="/api/workspaces/managed"){let i=await n.bridgeStatus();return n.sendJson(e,200,{workspaces:i.workspaces.managed}),!0}return t.method==="POST"&&r==="/api/workspaces/add"?(n.sendJson(e,202,await Kae(await n.readJson(t),n)),!0):t.method==="POST"&&r==="/api/workspaces/activate"?(n.sendJson(e,202,await k5(await n.readJson(t),"active",n)),!0):t.method==="POST"&&r==="/api/workspaces/deactivate"?(n.sendJson(e,202,await k5(await n.readJson(t),"inactive",n)),!0):t.method==="POST"&&r==="/api/workspaces/remove"?(n.sendJson(e,202,await Jae(await n.readJson(t),n)),!0):!1}async function Gae(t,e,r,n){return t.method==="GET"&&r==="/api/roadmaps/recent"?(n.sendJson(e,200,{roadmaps:n.recentRoadmaps()}),!0):t.method==="GET"&&r==="/api/roadmaps/managed"?(n.sendJson(e,200,{roadmaps:n.managedRoadmaps()}),!0):t.method==="POST"&&r==="/api/roadmaps/recent/remove"?(n.sendJson(e,202,await n.removeRoadmap(await n.readJson(t))),!0):t.method==="POST"&&r==="/api/roadmaps/activate"?(n.sendJson(e,202,await n.activateRoadmap(await n.readJson(t))),!0):t.method==="POST"&&r==="/api/roadmaps/deactivate"?(n.sendJson(e,202,await n.deactivateRoadmap(await n.readJson(t))),!0):t.method==="POST"&&r==="/api/projects/inspect"?(n.sendJson(e,200,{project:await n.inspectProject(await n.readJson(t))}),!0):t.method==="POST"&&r==="/api/roadmaps/open"?(n.sendJson(e,202,await uC(await n.readJson(t),n.openRoadmap,n)),!0):t.method==="POST"&&r==="/api/roadmaps/port/inspect"?(n.sendJson(e,200,await n.inspectRoadmapPort(await n.readJson(t))),!0):t.method==="POST"&&r==="/api/roadmaps/port/apply"?(n.sendJson(e,202,await uC(await n.readJson(t),n.applyRoadmapPort,n)),!0):t.method==="POST"&&r==="/api/roadmaps/create"?(n.sendJson(e,202,await uC(await n.readJson(t),n.createRoadmap,n)),!0):!1}async function uC(t,e,r){let n=await e(t),i=zae(n);return i&&r.selectRepository?.(i),n}function zae(t){if(typeof t!="object"||t===null)return;let e=t.repository;if(typeof e!="object"||e===null)return;let r=e.root;return typeof r=="string"&&r.trim()?r:void 0}async function Kae(t,e){let r=await e.addWorkspace(t);r.repository?.root&&e.selectRepository?.(r.repository.root);let n=await e.currentProvider();return{workspace:xu(r.roadmap,{provider:n}),workspaces:Su(e.managedRoadmaps(),{provider:n})}}async function k5(t,e,r){let n=await r.setWorkspaceLifecycle(t,e),i=await r.currentProvider();return{workspace:n.roadmap?xu(n.roadmap,{provider:i}):void 0,workspaces:Su(n.roadmaps,{provider:i})}}async function Jae(t,e){let r=await e.removeWorkspace(t),n=await e.currentProvider();return{removed:r.removed,workspaces:Su(r.roadmaps,{provider:n})}}function dC(t){return{backendId:"local",mode:"local",label:t.label??"This computer",provider:t.provider,connection:t.running===!1?{state:"not_running"}:{state:"connected"},workspaces:t.workspaces}}import{existsSync as dce,readFileSync as lce}from"node:fs";import{constants as A5}from"node:fs";import{lstat as C5,open as Xae}from"node:fs/promises";import{execFile as Yae}from"node:child_process";import{promisify as Qae}from"node:util";import{randomBytes as Zae}from"node:crypto";import{basename as lC}from"node:path";var dl="hunsu.bridge.credentials.v2";function wu(t,e={}){let r=e.randomBytes??Zae,n=e.platform??process.platform,i=e.currentUserId??(typeof process.getuid=="function"?process.getuid():void 0),o=e.windowsAclHardener??(f=>tce(f,e.processEnv??{})),s=e.windowsAclValidator??(f=>rce(f,e.processEnv??{})),a=Promise.resolve(),c=async()=>{let f=await ece(t.credentialsFile,n,i,s);if(f!==void 0)return oce(t.credentialsFile,f)},u=async()=>(await a,c()),d=f=>{let p=a.then(f,f);return a=p.then(()=>{},()=>{}),p},l=async f=>d(async()=>{let p=await c(),g={schema:dl,controlToken:Qg(t.credentialsFile,"controlToken",f.controlToken??p?.controlToken??pC(r)),connect:f.connect===void 0?p?.connect??null:B5(t.credentialsFile,f.connect)};return await wn(t.credentialsFile,g,{mode:384,...n==="win32"?{prepareTemporaryFile:o}:{}}),g});return{read:u,async ensure(){let f=await u();return f||l({})},write:l,rotateControlToken(f={}){return d(async()=>{let p=await c(),g=pC(r);for(let b=0;g===p?.controlToken&&b<8;b+=1)g=pC(r);if(g===p?.controlToken)throw xe(t.credentialsFile,"a distinct control credential could not be generated");let v={schema:dl,controlToken:g,connect:p?.connect??null};return await wn(t.credentialsFile,v,{mode:384,...n==="win32"?{prepareTemporaryFile:o}:{},onCommitted:()=>f.onCommitted?.(v)}),v})}}}var D5=Qae(Yae);async function ece(t,e,r,n){let i;try{i=await C5(t)}catch(s){if(Ot(s)&&s.code==="ENOENT")return;throw new Kn(t,`Unable to read Bridge state file: ${lC(t)}.`,{cause:s})}if(fC(t,i,e,r),e==="win32")try{await n(t)}catch(s){throw s instanceof Kn?s:xe(t,"credentials ACL is not restricted to the current Windows user")}let o;try{let s=process.platform==="win32"?0:A5.O_NOFOLLOW??0;o=await Xae(t,A5.O_RDONLY|s);let a=await o.stat();fC(t,a,e,r);let c=await C5(t);if(fC(t,c,e,r),!P5(i,a)||!P5(c,a))throw xe(t,"credentials file changed while it was being validated");let u=await o.readFile("utf8");try{return JSON.parse(u)}catch(d){throw new Kn(t,`Bridge state file is not valid JSON: ${lC(t)}.`,{cause:d})}}catch(s){throw s instanceof Kn?s:new Kn(t,`Unable to read Bridge state file: ${lC(t)}.`,{cause:s})}finally{await o?.close().catch(()=>{})}}function fC(t,e,r,n){if(!e.isFile())throw xe(t,"credentials path must be a regular file and cannot be a symbolic link");if(r!=="win32"){if((e.mode&63)!==0)throw xe(t,"credentials permissions must grant access only to the current user");if(n!==void 0&&e.uid!==n)throw xe(t,"credentials file must be owned by the current user")}}function P5(t,e){return t.dev===e.dev&&t.ino===e.ino}async function tce(t,e){let r=nce(t);try{await D5(r.command,r.args,{env:Ko(e),windowsHide:!0})}catch{throw xe(t,"credentials ACL could not be restricted to the current Windows user")}}async function rce(t,e){let r=ice(t);try{await D5(r.command,r.args,{env:Ko(e),windowsHide:!0})}catch{throw xe(t,"credentials ACL is not restricted to the current Windows user")}}function nce(t){if(/[\u0000-\u001f\u007f]/u.test(t))throw xe(t,"credentials path cannot contain control characters");return Eb(t,"CredentialPath")}function ice(t){if(/[\u0000-\u001f\u007f]/u.test(t))throw xe(t,"credentials path cannot contain control characters");let r=["$ErrorActionPreference = 'Stop'",`$CredentialPath = ${`'${t.replace(/'/g,"''")}'`}`,"$attributes = [System.IO.File]::GetAttributes($CredentialPath)","if (($attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0 -or ($attributes -band [System.IO.FileAttributes]::Directory) -ne 0) { throw 'Credential path is not a regular file.' }","$sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User","$acl = [System.IO.File]::GetAccessControl($CredentialPath, ([System.Security.AccessControl.AccessControlSections]::Owner -bor [System.Security.AccessControl.AccessControlSections]::Access))","$owner = $acl.GetOwner([System.Security.Principal.SecurityIdentifier])","if ($owner.Value -ne $sid.Value -or -not $acl.AreAccessRulesProtected) { throw 'Credential ACL owner or inheritance is unsafe.' }","$rules = @($acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier]))","if ($rules.Count -ne 1) { throw 'Credential ACL must contain exactly one rule.' }","$rule = $rules[0]","if ($rule.IsInherited -or $rule.IdentityReference.Value -ne $sid.Value -or $rule.AccessControlType -ne [System.Security.AccessControl.AccessControlType]::Allow -or $rule.FileSystemRights -ne [System.Security.AccessControl.FileSystemRights]::FullControl) { throw 'Credential ACL rule is unsafe.' }"].join("; ");return{command:"powershell.exe",args:["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(r,"utf16le").toString("base64")]}}function pC(t){return`hunsu_control_${Buffer.from(t(32)).toString("base64url")}`}function oce(t,e){if(!mC(e)||e.schema!==dl)throw xe(t,`expected schema ${dl}`);return{schema:dl,controlToken:Qg(t,"controlToken",e.controlToken),connect:B5(t,e.connect)}}function B5(t,e){if(e===null)return null;if(!mC(e))throw xe(t,"connect must be null or a Connect credential");let r={signingPrivateKey:qb(t,"connect.signingPrivateKey",e.signingPrivateKey,!0),signingPublicKey:qb(t,"connect.signingPublicKey",e.signingPublicKey,!1),agreementPrivateKey:qb(t,"connect.agreementPrivateKey",e.agreementPrivateKey,!0),agreementPublicKey:qb(t,"connect.agreementPublicKey",e.agreementPublicKey,!1)};if(e.state==="enrolling")return{...r,state:"enrolling",enrollmentId:bu(t,"connect.enrollmentId",e.enrollmentId),deviceCode:Qg(t,"connect.deviceCode",e.deviceCode),userCode:bu(t,"connect.userCode",e.userCode),verificationUri:T5(t,"connect.verificationUri",e.verificationUri),verificationUriComplete:T5(t,"connect.verificationUriComplete",e.verificationUriComplete),interval:ace(t,"connect.interval",e.interval),expiresAt:_5(t,"connect.expiresAt",e.expiresAt)};if(e.state!=="registered")throw xe(t,"connect.state must be enrolling or registered");return{...r,state:"registered",deviceId:bu(t,"connect.deviceId",e.deviceId),accountId:bu(t,"connect.accountId",e.accountId),refreshToken:Qg(t,"connect.refreshToken",e.refreshToken),accessToken:Qg(t,"connect.accessToken",e.accessToken),expiresAt:_5(t,"connect.expiresAt",e.expiresAt),connectWsUrl:sce(t,"connect.connectWsUrl",e.connectWsUrl)}}function Qg(t,e,r){return bu(t,e,r)}function bu(t,e,r){if(typeof r!="string"||r.trim()==="")throw xe(t,`${e} must be a non-empty string`);return r}function _5(t,e,r){let n=bu(t,e,r);if(!Number.isFinite(Date.parse(n)))throw xe(t,`${e} must be a valid timestamp`);return n}function sce(t,e,r){let n=bu(t,e,r),i;try{i=new URL(n)}catch{throw xe(t,`${e} must be a valid WebSocket URL`)}let o=i.hostname==="localhost"||i.hostname==="127.0.0.1"||i.hostname==="[::1]"||i.hostname==="::1";if(i.protocol!=="wss:"&&!(i.protocol==="ws:"&&o))throw xe(t,`${e} must use WSS except for loopback fixtures`);if(i.username||i.password||i.search||i.hash)throw xe(t,`${e} must not contain credentials`);return i.toString()}function T5(t,e,r){let n=bu(t,e,r),i;try{i=new URL(n)}catch{throw xe(t,`${e} must be a valid URL`)}let o=i.hostname==="localhost"||i.hostname==="127.0.0.1"||i.hostname==="[::1]"||i.hostname==="::1";if(i.protocol!=="https:"&&!(i.protocol==="http:"&&o))throw xe(t,`${e} must use HTTPS except for loopback fixtures`);if(i.username||i.password||i.hash)throw xe(t,`${e} must not contain credentials`);return i.toString()}function ace(t,e,r){if(!Number.isInteger(r)||Number(r)<1||Number(r)>30)throw xe(t,`${e} must be an integer from 1 through 30`);return Number(r)}function qb(t,e,r,n){if(!mC(r)||r.kty!=="EC"||r.crv!=="P-256"||typeof r.x!="string"||typeof r.y!="string"||n&&typeof r.d!="string"||!n&&r.d!==void 0)throw xe(t,`${e} must be a ${n?"private":"public"} P-256 JWK`);return{kty:"EC",crv:"P-256",x:r.x,y:r.y,...n?{d:r.d}:{},ext:!0}}function mC(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var pp=["remote.access","execute.start","artifactAction.run","env.read","hostAlias.expose"];var qa="hunsu.bridge.workspaces.v1";function Wb(t){return{async read(){let e=await Yi(t.workspacesFile);return e===void 0?{schema:qa,workspaces:[]}:N5(t.workspacesFile,e)},async write(e){await wn(t.workspacesFile,N5(t.workspacesFile,e))}}}function N5(t,e){if(!hC(e)||e.schema!==qa||!Array.isArray(e.workspaces))throw xe(t,`expected schema ${qa} and a workspaces array`);let r=e.workspaces.map((o,s)=>cce(t,o,s)),n=new Set,i=new Set;for(let o of r){if(n.has(o.workspaceId))throw xe(t,`duplicate workspaceId ${o.workspaceId}`);if(i.has(o.repositoryPath))throw xe(t,"duplicate repositoryPath");n.add(o.workspaceId),i.add(o.repositoryPath)}return{schema:qa,workspaces:r}}function cce(t,e,r){if(!hC(e))throw xe(t,`workspaces[${r}] must be an object`);let n=e.lifecycle;if(n!=="active"&&n!=="inactive")throw xe(t,`workspaces[${r}].lifecycle is invalid`);return{workspaceId:mp(t,`workspaces[${r}].workspaceId`,e.workspaceId),displayName:mp(t,`workspaces[${r}].displayName`,e.displayName),repositoryPath:mp(t,`workspaces[${r}].repositoryPath`,e.repositoryPath),lifecycle:n,...uce(t,e.remoteAccess,r),createdAt:mp(t,`workspaces[${r}].createdAt`,e.createdAt),updatedAt:mp(t,`workspaces[${r}].updatedAt`,e.updatedAt)}}function uce(t,e,r){if(e===void 0)return{};if(!hC(e)||typeof e.enabled!="boolean"||!Array.isArray(e.scopes))throw xe(t,`workspaces[${r}].remoteAccess must contain enabled and scopes`);let n=e.scopes.map((i,o)=>{let s=mp(t,`workspaces[${r}].remoteAccess.scopes[${o}]`,i);if(!pp.includes(s))throw xe(t,`workspaces[${r}].remoteAccess.scopes[${o}] is unsupported`);return s});return{remoteAccess:{enabled:e.enabled,scopes:[...new Set(n)]}}}function mp(t,e,r){if(typeof r!="string"||r.trim()==="")throw xe(t,`${e} must be non-empty`);return r}function hC(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function O5(t){let e=pce(t);return!e?.connect||e.connect.state!=="registered"?{available:e!==void 0,signedIn:!1}:e.connect.refreshToken?{available:!0,signedIn:!0,userId:e.connect.accountId}:{available:!0,signedIn:!1}}function M5(t){let e=fce(t)?.provider;return e?.kind==="codex"?Xo({binaryPath:e.binaryPath,codexHome:e.home,appServerCommand:e.appServerCommand,appServerArgs:e.appServerArgs,installChannel:e.installChannel,authenticationPreference:e.authenticationPreference}):{}}function fce(t){let e=Yo({env:t}).configFile,r=L5(e);if(r!==void 0)try{return vu(e,r)}catch{return}}function pce(t){let e=L5(Yo({env:t}).credentialsFile);return e?.schema===dl?e:void 0}function L5(t){if(dce(t))try{return JSON.parse(lce(t,"utf8"))}catch{return}}async function gC(t,e,r={}){return t.current().status({env:e,force:r.force})}function mce(t,e){let r=O5(e.processEnv);return r.signedIn?{signedIn:!0,userId:r.userId,source:"daemon"}:{signedIn:!1,source:r.available?"daemon":"none"}}async function Iu(t){return hce({providerRegistry:t.providerRegistry,env:t.runtimeConfig.processEnv,managedRoadmaps:t.managedRoadmaps(),account:mce(t.request,t.runtimeConfig)})}async function hce(t){let e=await gC(t.providerRegistry,t.env),r=Su(t.managedRoadmaps,{provider:e,activeOnly:!0}),n=Su(t.managedRoadmaps,{provider:e,activeOnly:!1});return{provider:e,connections:[dC({provider:e,workspaces:r})],workspaces:{active:r,managed:n},account:t.account}}import{createServer as gce}from"node:http";function H5(t,e={}){let r=gce(t),n=e.runtimeConfig;return n?.bridgeApi.port===0&&r.once("listening",()=>{let i=r.address();!i||typeof i=="string"||yce(n,i.port)}),r}function U5(t){return new URL(t.url??"/","http://localhost")}function yce(t,e){t.bridgeApi={...t.bridgeApi,port:e},t.processEnv.HUNSU_BRIDGE_PORT=String(e),t.codexAppServer.environment.HUNSU_BRIDGE_PORT=String(e)}function yC(t){return t==="/health"}function $5(t){return yC(t)}function vC(t){return t==="/api/bridge/control/status"||t==="/api/bridge/pairing/rotate"||t==="/api/bridge/pairing/revoke"||t==="/api/bridge/control/shutdown"}async function F5(t,e,r,n){if(await vce(r,n))return!0;if(t.method==="GET"&&r==="/api/board")return n.sendJson(e,200,n.board()),!0;if(t.method==="GET"&&r==="/api/roadmap")return n.sendJson(e,200,n.roadmapView()),!0;if(t.method==="GET"&&r==="/api/events")return n.sendJson(e,200,{events:n.events()}),!0;if(t.method==="GET"&&r==="/api/repository")return n.sendJson(e,200,{repository:n.repository()}),!0;if(t.method==="POST"&&r==="/api/repository")return n.sendJson(e,202,await n.selectRepository(await n.readJson(t))),!0;if(t.method==="GET"&&r==="/api/worktree")return n.sendJson(e,200,n.worktree()),!0;if(t.method==="GET"&&r==="/api/artifacts")return n.sendJson(e,200,{artifacts:n.artifacts()}),!0;if(t.method==="GET"&&r.startsWith("/api/artifacts/")){let i=decodeURIComponent(r.slice(15)),o=n.artifact(i);return n.sendJson(e,o?200:404,o?{artifact:o}:{error:`Unknown artifact: ${i}`}),!0}if(t.method==="GET"&&r==="/api/skills")return n.sendJson(e,200,{skills:n.skills()}),!0;if(t.method==="GET"&&r.startsWith("/api/moves/")&&r.endsWith("/diff")){let i=decodeURIComponent(r.slice(11,-5));return n.sendJson(e,200,{diff:n.moveDiff(i)}),!0}return t.method==="POST"&&r==="/api/commands"?(n.sendJson(e,202,await n.executeCommands(await n.readJson(t))),!0):t.method==="POST"&&r==="/api/lines/accept"?(n.sendJson(e,202,await n.decideLine("accept",await n.readJson(t))),!0):t.method==="POST"&&r==="/api/lines/reject"?(n.sendJson(e,202,await n.decideLine("reject",await n.readJson(t))),!0):!1}async function j5(t,e,r,n){let i=xce(r);if(!i)return!1;let o=n.repositoryPath(i.roadmapId),s=i.suffix;if(t.method==="GET"&&s==="")return n.sendJson(e,200,n.loadRoadmap(i.roadmapId,o)),!0;if(t.method==="GET"&&s==="/board")return n.sendJson(e,200,n.board(i.roadmapId,o)),!0;if(t.method==="GET"&&s==="/roadmap")return n.sendJson(e,200,n.roadmapView(i.roadmapId,o)),!0;if(t.method==="GET"&&s==="/events")return n.sendJson(e,200,{events:n.events(i.roadmapId,o)}),!0;if(t.method==="GET"&&s==="/repository")return n.sendJson(e,200,{repository:n.repository(i.roadmapId,o)}),!0;if(t.method==="GET"&&s==="/worktree")return n.sendJson(e,200,n.worktree(i.roadmapId,o)),!0;if(t.method==="GET"&&s==="/artifacts")return n.sendJson(e,200,{artifacts:n.artifacts(i.roadmapId,o)}),!0;if(t.method==="GET"&&s.startsWith("/artifacts/")){let c=decodeURIComponent(s.slice(11)),u=n.artifact(i.roadmapId,o,c);return n.sendJson(e,u?200:404,u?{artifact:u}:{error:`Unknown artifact: ${c}`}),!0}if(s==="/artifact-actions"||s.startsWith("/artifact-actions/")||s==="/action-runs"||s.startsWith("/action-runs/"))return n.artifactActions(s,i.roadmapId,o);if(s==="/hunsu/drafts"||s.startsWith("/hunsu/drafts/"))return n.hunsuDrafts(s.slice(13),i.roadmapId,o);if(await n.executes(s,i.roadmapId,o))return!0;if(t.method==="GET"&&s==="/skills")return n.sendJson(e,200,{skills:n.skills(i.roadmapId,o)}),!0;let a=Sce(s);if(a&&t.method==="GET"){let u=new URL(t.url??"/","http://localhost").searchParams.get("path")??void 0;if(a.action==="tree")return n.sendJson(e,200,{tree:n.moveFileTree(i.roadmapId,o,a.moveId,u)}),!0;if(a.action==="blob")return n.sendJson(e,200,{blob:n.moveFileBlob(i.roadmapId,o,a.moveId,u??"")}),!0;if(a.action==="diff")return n.sendJson(e,200,{diff:n.moveDiff(i.roadmapId,o,a.moveId)}),!0}if(t.method==="GET"&&s.startsWith("/moves/")&&s.endsWith("/diff")){let c=decodeURIComponent(s.slice(7,-5));return n.sendJson(e,200,{diff:n.moveDiff(i.roadmapId,o,c)}),!0}return t.method==="POST"&&s==="/commands"?(n.sendJson(e,202,await n.executeCommands(i.roadmapId,o,await n.readJson(t))),!0):t.method==="POST"&&s==="/lines/accept"?(n.sendJson(e,202,await n.decideLine(i.roadmapId,o,"accept",await n.readJson(t))),!0):t.method==="POST"&&s==="/lines/reject"?(n.sendJson(e,202,await n.decideLine(i.roadmapId,o,"reject",await n.readJson(t))),!0):!1}async function vce(t,e){return t==="/api/artifact-actions"||t.startsWith("/api/artifact-actions/")||t==="/api/action-runs"||t.startsWith("/api/action-runs/")?e.artifactActions(t):!1}function xce(t){let e="/api/roadmaps/";if(!t.startsWith(e))return;let r=t.slice(e.length),[n,...i]=r.split("/");if(n)return{roadmapId:decodeURIComponent(n),suffix:i.length>0?`/${i.join("/")}`:""}}function Sce(t){if(!t.startsWith("/moves/"))return;let e=t.slice(1).split("/");if(e.length<4||e[0]!=="moves"||e[2]!=="files")return;let r=decodeURIComponent(e[1]??"");if(e[3]==="tree")return{action:"tree",moveId:r};if(e[3]==="blob")return{action:"blob",moveId:r};if(e[3]==="diff")return{action:"diff",moveId:r}}function Us(){return{"access-control-allow-methods":"GET,HEAD,POST,PUT,DELETE,OPTIONS","access-control-allow-headers":"authorization,content-type,x-hunsu-bridge-token,x-hunsu-bridge-control-token","access-control-allow-private-network":"true","access-control-max-age":"600",vary:"origin, access-control-request-method, access-control-request-headers, access-control-request-private-network"}}function q5(){let t=new WeakMap;return{set(e,r){t.set(e,r)},get(e){return t.get(e)??Us()}}}import{randomBytes as bce,timingSafeEqual as wce}from"node:crypto";var Ice=300*1e3;function Vb(t){if(!t.controlToken.trim())throw new Error("Control token is required before pairing can be enabled.");let e=t.ttlMs??Ice;if(!Number.isFinite(e)||e<=0)throw new Error("Pairing TTL must be positive.");let r=t.now??Date.now,n=t.randomBytes??bce,i;if(t.initialPairing){let a=t.initialPairing.credential.trim();if(!a||xC(t.controlToken,a))throw new Error("Initial pairing credential must be non-empty and distinct from the control token.");let c=W5(t.initialPairing.browserUrl);if(!c)throw new Error("Initial pairing browser URL is invalid.");let u=`pair_${Buffer.from(n(12)).toString("base64url")}`;c.searchParams.set("hunsuBridgeToken",a),t.initialPairing.workspaceId&&c.searchParams.set("workspace",t.initialPairing.workspaceId),i={pairingId:u,credential:a,pairingUrl:c.toString(),workspaceId:t.initialPairing.workspaceId??null,expiresAtMs:r()+e,browserOpened:!1,consumed:!1,revoked:!1}}let o=a=>({pairingId:a.pairingId,expiresAt:new Date(a.expiresAtMs).toISOString(),workspaceId:a.workspaceId,browserOpened:a.browserOpened,status:a.revoked?"revoked":r()>=a.expiresAtMs?"expired":a.consumed?"consumed":"active"}),s=a=>!i||!xC(i.credential,a)?oe({code:"PAIRING_CREDENTIAL_INVALID",message:"Pairing credential is invalid."}):i.revoked?oe({code:"PAIRING_CREDENTIAL_REVOKED",message:"Pairing credential has been revoked."}):r()>=i.expiresAtMs?oe({code:"PAIRING_CREDENTIAL_EXPIRED",message:"Pairing credential has expired."}):S({pairingId:i.pairingId,workspaceId:i.workspaceId,expiresAt:new Date(i.expiresAtMs).toISOString()});return{rotate(a){let c=W5(a.browserUrl);if(!c)return oe({code:"PAIRING_ROTATION_FAILED",message:"Browser URL is invalid."});let u=`hunsu_bridge_pair_${Buffer.from(n(32)).toString("base64url")}`;if(u===t.controlToken)return oe({code:"PAIRING_ROTATION_FAILED",message:"Pairing credential generation failed."});let d=`pair_${Buffer.from(n(12)).toString("base64url")}`;return c.searchParams.set("hunsuBridgeToken",u),a.workspaceId&&c.searchParams.set("workspace",a.workspaceId),i&&(i.revoked=!0),i={pairingId:d,credential:u,pairingUrl:c.toString(),workspaceId:a.workspaceId??null,expiresAtMs:r()+e,browserOpened:!1,consumed:!1,revoked:!1},S({safe:o(i),internal:{pairingId:d,credential:u,pairingUrl:i.pairingUrl}})},consume(a){let c=s(a);return c.ok&&i&&(i.consumed=!0),c},validate(a){return a?!i||!xC(i.credential,a)?{valid:!1,reason:"invalid"}:i.revoked?{valid:!1,reason:"revoked"}:r()>=i.expiresAtMs?{valid:!1,reason:"expired"}:{valid:!0}:{valid:!1,reason:"missing"}},revoke(a){return!i||a!==void 0&&i.pairingId!==a?!1:(i.revoked=!0,!0)},markBrowserOpened(a){return!i||i.pairingId!==a||i.revoked||r()>=i.expiresAtMs?!1:(i.browserOpened=!0,!0)},getSafeMetadata(){return i?o(i):null},getPairingUrl(a){if(!i||i.pairingId!==a)return oe({code:"PAIRING_CREDENTIAL_INVALID",message:"Pairing credential is invalid."});let c=s(i.credential);return c.ok?S(i.pairingUrl):c}}}function W5(t){try{let e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"?e:void 0}catch{return}}function xC(t,e){let r=Buffer.from(t),n=Buffer.from(e);return r.length===n.length&&wce(r,n)}var Gb="hunsu.bridge.cli-result.v1",Ece="Start Hunsu Bridge with `hunsu-bridge service start`.",De=class extends Error{code;recovery;cause;constructor(e,r,n={}){super(r),this.name="BridgeError",this.code=e,this.recovery=n.recovery,this.cause=n.cause}};function mr(t,e,r="OK"){return{schema:Gb,ok:!0,code:r,message:t,...e===void 0?{}:{value:e}}}function pr(t,e,r){return{schema:Gb,ok:!1,code:t,message:e,...r?{recovery:r}:{}}}function V5(){return pr("BRIDGE_NOT_RUNNING",Ece)}function Wa(t){return t instanceof De?pr(t.code,t.message,t.recovery):t instanceof Kn?pr(t.code,t.message):pr("BRIDGE_CONTROL_UNAVAILABLE","Hunsu Bridge command failed unexpectedly.")}import{unlink as kce}from"node:fs/promises";import{isAbsolute as Rce}from"node:path";var Zg="hunsu.bridge.runtime.v1";function zb(t){let e=async()=>{let r=await Yi(t.runtimeFile);return r===void 0?void 0:G5(t.runtimeFile,r)};return{read:e,async write(r){await wn(t.runtimeFile,G5(t.runtimeFile,r))},async clear(r){if(r!==void 0){let n=await e();if(n===void 0||n.instanceId!==r)return!1}try{return await kce(t.runtimeFile),!0}catch(n){if(Ot(n)&&n.code==="ENOENT")return!1;throw n}}}}function G5(t,e){if(!_ce(e)||e.schema!==Zg)throw xe(t,`expected schema ${Zg}`);if(!Number.isInteger(e.daemonPid)||e.daemonPid<=0)throw xe(t,"daemonPid must be a positive integer");let r=e.serviceManager;if(r!=="development"&&r!=="windows-task-scheduler"&&r!=="macos-launch-agent"&&r!=="linux-systemd-user")throw xe(t,"serviceManager is invalid");return{schema:Zg,instanceId:hp(t,"instanceId",e.instanceId),daemonPid:e.daemonPid,version:hp(t,"version",e.version),protocolVersion:Cce(t,e.protocolVersion),deploymentProfile:Ace(t,e.deploymentProfile),startedAt:hp(t,"startedAt",e.startedAt),endpoint:hp(t,"endpoint",e.endpoint),runtimePath:Pce(t,"runtimePath",e.runtimePath),serviceManager:r,lastHealthyAt:hp(t,"lastHealthyAt",e.lastHealthyAt)}}function Ace(t,e){if(e===void 0)return"production";if(!Pn(e))throw xe(t,"deploymentProfile must be production or preview");return e}function Cce(t,e){if(e!=="local-bridge-v1")throw xe(t,"protocolVersion must be local-bridge-v1");return e}function hp(t,e,r){if(typeof r!="string"||r.trim()==="")throw xe(t,`${e} must be non-empty`);return r}function Pce(t,e,r){let n=hp(t,e,r);if(!Rce(n)||/[\u0000-\u001f\u007f]/u.test(n))throw xe(t,`${e} must be an absolute path without control characters`);return n}function _ce(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function K5(t){let e={...t.env??{}},r=new Set,n=o=>new al({env:()=>e,settings:Eu(o.provider)}),i=o=>{for(let s of r)try{s(z5(o))}catch{}};return{async list(){return[{providerId:"codex",label:"Codex",configured:(await t.configStore.read()).provider.kind==="codex"}]},async configuration(){return z5((await t.configStore.read()).provider)},async status(o=!1){let s=await t.configStore.read();return n(s).status({force:o,env:e})},async setCodex(o){let a={...await t.configStore.read(),provider:{kind:"codex",...o.binaryPath?.trim()?{binaryPath:o.binaryPath.trim()}:{},...o.home?.trim()?{home:o.home.trim()}:{},...o.appServerCommand?.trim()?{appServerCommand:o.appServerCommand.trim()}:{},...o.appServerArgs?.trim()?{appServerArgs:o.appServerArgs.trim()}:{},...o.installChannel?{installChannel:o.installChannel}:{},...o.authenticationPreference?{authenticationPreference:o.authenticationPreference}:{}}},c=await n(a).status({force:!0,env:e});if(!c.installed)throw new De("PROVIDER_BINARY_NOT_FOUND",c.safeMessage??"Codex was not found by Hunsu Bridge.");if(!c.configured)throw new De("PROVIDER_CHECK_FAILED",c.safeMessage??"Codex could not initialize its app-server.");let u=await t.configStore.update(d=>({...d,provider:a.provider}));return i(u.provider),c},async resetCodex(){let o=await t.configStore.update(s=>({...s,provider:{kind:"unconfigured"}}));return i(o.provider),n(o).status({force:!0,env:e})},onConfigurationChange(o){return r.add(o),()=>r.delete(o)}}}function J5(t){let e=async()=>new al({env:t.env,settings:Eu(await t.service.configuration())}),r={providerId:"codex",kind:"codex",label:"Codex",metadata:()=>Ob,async readConfig(){return Mb(Eu(await t.service.configuration()))},async validateConfig(i){return(await e()).validateConfig(i)},async saveConfig(i){let o=Eu(await t.service.configuration());return t.service.setCodex(SC(sl(o,i)))},async deleteConfig(i){if(!i?.length)return t.service.resetCodex();let o=Eu(await t.service.configuration()),s=sl(o,i.map(a=>({key:a,value:"",isSet:!1,isSecret:!1})));return t.service.setCodex(SC(s))},status:i=>t.service.status(i?.force),async installPlan(){return(await e()).installPlan()},async install(i){return(await e()).install(i)},async login(i){return(await e()).login(i)},recheck:()=>t.service.status(!0),async configure(i){if(i.authMethod==="api_key")return(await e()).configure(i);let o=Eu(await t.service.configuration()),s=i.binaryPath?.trim()||i.selectBinaryPath?.trim(),a={...o,...s?{binaryPath:s}:{}};return i.clearBinaryPath&&delete a.binaryPath,t.service.setCodex(SC(a))},effectiveEnv:i=>({...t.env(),...i??{}})},n=t.fallback.list().map(i=>i.providerId==="codex"?r:i);return n.some(i=>i.providerId==="codex")||n.unshift(r),{list:()=>[...n],get:i=>i==="codex"?r:n.find(o=>o.providerId===i),current:()=>r,async setCurrent(i){i!=="codex"&&await t.fallback.setCurrent(i)}}}function Eu(t){return t.kind==="codex"?Xo({binaryPath:t.binaryPath,codexHome:t.home,appServerCommand:t.appServerCommand,appServerArgs:t.appServerArgs,installChannel:t.installChannel,authenticationPreference:t.authenticationPreference}):{}}function SC(t){return{...t.binaryPath?{binaryPath:t.binaryPath}:{},...t.codexHome?{home:t.codexHome}:{},...t.appServerCommand?{appServerCommand:t.appServerCommand}:{},...t.appServerArgs?{appServerArgs:t.appServerArgs}:{},...t.installChannel?{installChannel:t.installChannel}:{},...t.authenticationPreference?{authenticationPreference:t.authenticationPreference}:{}}}function z5(t){return{...t}}var Tce="/studio/settings/model-aliases",Dce="1970-01-01T00:00:00.000Z",e0={primary:"PrimaryModel",fast:"FastModel",reviewer:"ReviewerModel",cheap:"CheapModel"};function Y5(t=Dce){return[Kb(e0.primary,"Primary Model",{kind:"direct",provider:{providerId:"codex",model:"gpt-5.5-thinking",reasoningEffort:"high",serviceTier:"default"}},t),Kb(e0.fast,"Fast Model",{kind:"direct",provider:{providerId:"codex",model:"gpt-5.5",reasoningEffort:"medium",serviceTier:"fast"}},t),Kb(e0.reviewer,"Reviewer Model",{kind:"direct",provider:{providerId:"codex",model:"gpt-5.5-thinking",reasoningEffort:"xhigh",serviceTier:"default"}},t),Kb(e0.cheap,"Cheap Model",{kind:"direct",provider:{providerId:"codex",model:"gpt-5.5",reasoningEffort:"low",serviceTier:"default"}},t)]}function Bce(t,e="local"){let r=Ga(e.trim()||"local","providerInventory.backendId");return t.modelInventory.state==="unavailable"?oe({code:"PROVIDER_INVENTORY_UNAVAILABLE",backendId:r,providerId:t.providerId,message:t.modelInventory.message}):S({providerId:t.providerId,label:Ga(t.label,"providerInventory.label"),ready:t.ready,authState:t.auth.state,models:t.modelInventory.models})}function wC(){return{backendId:Ga("local","providerInventory.backendId"),providers:[{providerId:"codex",label:Ga("Codex","providerInventory.label"),ready:!0,authState:"authenticated",models:Gg()}]}}function IC(t){let e=t.backendId?.trim(),r=e?t.connections?.find(s=>s.backendId===e):t.connections?.find(s=>s.mode==="local");if(e&&!r)return $s(e);let n=r?.backendId??"local",i=r?.provider??t.provider;if(!i)return $s(n);let o=Bce(i,n);return o.ok?S({backendId:Ga(n,"providerInventory.backendId"),providers:[o.value]}):o}function $s(t,e=`Backend ${t.trim()||"local"} is not available on this Bridge.`){return oe({code:"BACKEND_UNAVAILABLE",backendId:Ga(t.trim()||"local","providerInventory.backendId"),message:e})}function Q5(t,e,r){return oe({code:"PROVIDER_INVENTORY_UNAVAILABLE",backendId:Ga(t.trim()||"local","providerInventory.backendId"),providerId:e,message:r})}function ll(t){let e=t.backendId?.trim()||"local",r=t.selection??{kind:"alias",aliasId:e0.primary},n=t.aliases===void 0?Y5():t.aliases;if(r.kind==="direct")return bC(r,t.inventories,e);let i=n.find(s=>s.aliasId===r.aliasId);if(!i)return{ok:!1,backendId:e,error:Va("MODEL_ALIAS_NOT_FOUND",`Model alias ${r.aliasId} does not exist.`,{aliasId:r.aliasId,actions:[Jb()]})};let o=t.overrides?.find(s=>s.aliasId===i.aliasId&&s.backendId===e);return bC(o?.selection??i.selection,t.inventories,e)}function bC(t,e,r="local"){let n=r.trim()||"local",i=t.provider,o=e.find(l=>l.providerId===i.providerId);if(!o)return{ok:!1,backendId:n,error:Va("PROVIDER_NOT_READY",`Provider ${i.providerId} is not available for model selection.`,{providerId:i.providerId,actions:[X5(i.providerId)]})};if(o.authState==="not_authenticated"||o.authState==="expired"||o.authState==="invalid")return{ok:!1,backendId:n,error:Va("PROVIDER_LOGIN_REQUIRED",`${o.label} login is required before this model can run.`,{providerId:i.providerId,actions:[Nce(i.providerId,o.label)]})};if(!o.ready)return{ok:!1,backendId:n,error:Va("PROVIDER_NOT_READY",`${o.label} is not ready for Execute.`,{providerId:i.providerId,actions:[X5(i.providerId)]})};let s=o.models.find(l=>l.model===i.model);if(!s)return i.experimental===!0?{ok:!0,backendId:n,selection:t,resolved:i,provider:{providerId:i.providerId,ready:o.ready},model:{providerId:i.providerId,model:i.model,experimental:!0}}:{ok:!1,backendId:n,error:Va("MODEL_UNSUPPORTED",`${o.label} does not advertise model ${i.model}.`,{providerId:i.providerId,model:i.model,actions:[Jb()]})};let a=s.capabilities.reasoningEfforts??[],c=i.reasoningEffort??s.defaultConfig?.reasoningEffort;if(c&&a.length>0&&!a.includes(c))return{ok:!1,backendId:n,error:Va("REASONING_UNSUPPORTED",`${s.label} does not support ${c} reasoning.`,{providerId:i.providerId,model:i.model,actions:[Jb()]})};let u=s.capabilities.serviceTiers??[],d=i.serviceTier??s.defaultConfig?.serviceTier;return d&&u.length>0&&!u.includes(d)?{ok:!1,backendId:n,error:Va("SERVICE_TIER_UNSUPPORTED",`${s.label} does not support the ${d} service tier.`,{providerId:i.providerId,model:i.model,actions:[Jb()]})}:{ok:!0,backendId:n,selection:t,resolved:i,provider:{providerId:i.providerId,ready:o.ready},model:s}}function fl(t){return{ok:!1,backendId:t.backendId,error:t.code==="BACKEND_UNAVAILABLE"?Va(t.code,t.message,{actions:[Mce(t.backendId)]}):Va(t.code,t.message,{providerId:t.providerId,actions:[Oce(t.providerId)]})}}function ku(t,e){if(t.error==="BACKEND_UNAVAILABLE"){let r=e.startsWith("remote:")||e==="remote";return{area:"connection",backendId:e,error:r?"REMOTE_NOT_CONNECTED":"BRIDGE_NOT_CONNECTED",message:t.message,actions:t.actions}}return{area:"model",backendId:e,providerId:t.providerId,aliasId:t.aliasId,model:t.model,error:t.error,message:t.message,actions:t.actions}}function Kb(t,e,r,n){return{aliasId:Ga(t,"modelAlias.aliasId"),displayName:Ga(e,"modelAlias.displayName"),selection:r,scope:{kind:"user"},createdAt:n,updatedAt:n}}function Va(t,e,r){return{error:t,message:e,...r}}function X5(t){return{type:"open_provider_setup",label:"Run hunsu-bridge provider status",href:"/studio/setup?next=%2Fstudio",providerId:t}}function Nce(t,e){return{type:"login_provider",label:`Check ${e} with hunsu-bridge provider check ${t}`,href:"/studio/setup?next=%2Fstudio",providerId:t}}function Oce(t){return{type:"recheck_provider",label:`Run hunsu-bridge provider check ${t}`,href:"/studio/setup?next=%2Fstudio",providerId:t}}function Mce(t){return{type:"open_connection",label:t.startsWith("remote:")||t==="remote"?"Run hunsu-bridge remote status":"Run hunsu-bridge status",href:"/studio/setup?next=%2Fstudio"}}function Jb(){return{type:"edit_model_alias",label:"Edit Model Alias",href:Tce}}function Ga(t,e){return er(Ee(t,e))}var Jn="/studio/setup?next=%2Fstudio",Z5="/studio";function Xb(t){if(!t.installed){let e=t.recommendedAction==="select_binary"?{type:"open_provider_setup",label:`Run hunsu-bridge provider set ${t.providerId} --binary <path>`,href:Jn,providerId:t.providerId}:{type:"install_provider",label:`Install ${t.label}, then run hunsu-bridge provider check ${t.providerId}`,href:Jn,providerId:t.providerId};return gp(t,"PROVIDER_MISSING",t.safeMessage??`${t.label} is not installed or could not be found.`,[e])}if(!t.configured)return gp(t,"PROVIDER_UNAVAILABLE",`${t.label} is installed but unavailable.`,[{type:"recheck_provider",label:`Run hunsu-bridge provider check ${t.providerId}`,href:Jn,providerId:t.providerId}]);if(t.auth.state==="not_authenticated")return gp(t,"PROVIDER_LOGIN_REQUIRED",`${t.label} login is required before Execute can start.`,[{type:"login_provider",label:`Run hunsu-bridge provider check ${t.providerId}`,href:Jn,providerId:t.providerId}]);if(t.auth.state==="expired"||t.auth.state==="invalid")return gp(t,"PROVIDER_AUTH_EXPIRED",`${t.label} authentication needs to be refreshed.`,[{type:"login_provider",label:`Run hunsu-bridge provider check ${t.providerId}`,href:Jn,providerId:t.providerId},{type:"recheck_provider",label:`Recheck with hunsu-bridge provider check ${t.providerId}`,href:Jn,providerId:t.providerId}]);if(t.usage?.rateLimited)return gp(t,"PROVIDER_RATE_LIMITED",`${t.label} is temporarily rate limited.`,[{type:"recheck_provider",label:`Run hunsu-bridge provider check ${t.providerId}`,href:Jn,providerId:t.providerId}]);if(!t.capabilities.canExecute)return gp(t,"PROVIDER_CAPABILITY_MISSING",`${t.label} cannot execute Hunsu workspaces.`,[{type:"open_provider_setup",label:"Run hunsu-bridge provider status",href:Jn}])}function EC(t){if(!t)return t0(void 0,"WORKSPACE_MISSING","Choose an active Workspace before starting Execute.");if(t.lifecycle==="inactive")return t0(t.workspaceId,"WORKSPACE_INACTIVE","This Workspace is inactive. Activate it in Hunsu Bridge before starting Execute.");if(t.lifecycle==="missing")return t0(t.workspaceId,"WORKSPACE_MISSING","This Workspace path is missing. Repair or remove it in Hunsu Bridge.");if(t.lifecycle==="needs_upgrade")return t0(t.workspaceId,"WORKSPACE_NEEDS_UPGRADE","This Workspace needs an upgrade before Execute can start.");if(t.lifecycle==="error"||t.health==="error"||t.health==="unknown")return t0(t.workspaceId,"WORKSPACE_UNHEALTHY","This Workspace needs attention before Execute can start.")}function tL(t,e){return EC(t?xu(t,{provider:e}):void 0)}function Lce(t,e,r){let n=Ru(t),i=Qb(e.connections,n),o=i?.provider??r.provider,s=oL(t.workspace?.workspaceId,r.workspace?.workspaceId),a=i?.workspaces.find(u=>u.workspaceId===s||u.roadmapId===s),c=i?.mode==="remote"?a:a??r.workspace;return EC(c)??Xb(o)}function kC(t,e){let r=t.aliases;if(!t.modelSelection&&!r?.length)return;let n=RC(t,e);if(!n.ok){let s=fl(n.error);return ku(s.error,s.backendId)}let i=n.value,o=ll({selection:t.modelSelection,aliases:r,backendId:i.backendId,inventories:i.providers});return o.ok?void 0:ku(o.error,o.backendId)}function RC(t,e){let r=Ru(t),n=Qb(e.connections,r);if(r.backendId&&!n)return $s(r.backendId,`Backend ${r.backendId} is not connected to this Bridge.`);if(r.remoteRequested&&!n)return $s("remote","No Remote Bridge backend is connected.");let i=e.connections.find(s=>s.mode==="local"),o=n??i;return IC({connections:e.connections,backendId:r.backendId??o?.backendId??"local"})}async function AC(t,e,r){let n=PC(t,e);if(n)return n;let i=Ru(t),o=Qb(e.connections,i)??(i.remoteRequested?void 0:e.connections.find(u=>u.mode==="local")),s=o?Xb(o.provider):void 0;if(s)return s;let a=await r.providerInventory();if(!a.ok){let u=fl(a.error);return ku(u.error,u.backendId)}let c=new Set;for(let u of await r.modelSelections()){if(!u.selection&&!u.aliases?.length)continue;let d=JSON.stringify(u);if(c.has(d))continue;c.add(d);let l=ll({selection:u.selection,aliases:u.aliases,backendId:a.value.backendId,inventories:a.value.providers});if(!l.ok)return ku(l.error,l.backendId)}}function rL(t,e){return t}function Yb(t){return!!(t.backendId?.trim()||t.connectionMode||t.workspace?.backendId?.trim()||t.workspace?.connectionMode)}async function CC(t,e,r,n){let i=await e.current().status({env:r,force:!0});return n?Lce(n.body,n.status,{provider:i,workspace:t?xu(t,{provider:i}):void 0}):tL(t,i)??Xb(i)}async function nL(t){let e=eL(t.repositoryPath),r=t.roadmaps.find(n=>eL(n.repositoryPath)===e);return CC(r,t.registry,t.env,t.selected)}function Ru(t){let e=oL(t.backendId,t.workspace?.backendId),r=e?Hce(e)?"remote":"local":t.connectionMode??t.workspace?.connectionMode;return{backendId:e,connectionMode:r,remoteRequested:r==="remote"}}function PC(t,e){let r=Ru(t),n=Qb(e.connections,r);return iL({backend:n,backendId:r.backendId,remoteRequested:r.remoteRequested,accountSignedIn:e.account.signedIn,localBridgeConnected:e.connections.some(i=>i.mode==="local"&&i.connection.state==="connected")})}function iL(t){if(t.localBridgeConnected===!1&&!t.remoteRequested)return pl(t.backendId??"local","BRIDGE_NOT_CONNECTED","Hunsu Bridge is not connected.",[{type:"open_connection",label:"Run hunsu-bridge status",href:Jn}]);if(t.remoteRequested&&t.accountSignedIn===!1)return pl(t.backendId,"REMOTE_LOGIN_REQUIRED","Sign in to Hunsu before using Remote Bridge.",[{type:"open_connection",label:"Run hunsu-bridge login",href:Jn}]);if(!t.backend)return t.remoteRequested?pl(t.backendId,"REMOTE_NOT_CONNECTED","Remote Bridge is not connected.",[{type:"open_connection",label:"Run hunsu-bridge remote status",href:Jn}]):t.backendId?pl(t.backendId,"BRIDGE_NOT_CONNECTED",`Backend ${t.backendId} is not connected to this Bridge.`,[{type:"open_connection",label:"Run hunsu-bridge status",href:Jn}]):void 0;if(t.backend.connection.state!=="connected")return t.backend.connection.state==="login_required"?pl(t.backend.backendId,"REMOTE_LOGIN_REQUIRED","Sign in to Hunsu before using Remote Bridge.",[{type:"open_connection",label:"Run hunsu-bridge login",href:Jn}]):t.backend.mode==="remote"?pl(t.backend.backendId,"REMOTE_NOT_CONNECTED","Remote Bridge is offline or unavailable.",[{type:"open_connection",label:"Run hunsu-bridge remote status",href:Jn}]):pl(t.backend.backendId,"BRIDGE_NOT_CONNECTED","Hunsu Bridge is not connected.",[{type:"open_connection",label:"Run hunsu-bridge status",href:Jn}])}function Qb(t,e){if(e.backendId)return t.find(r=>r.backendId===e.backendId);if(e.connectionMode==="local")return t.find(r=>r.mode==="local");if(e.remoteRequested)return t.find(r=>r.mode==="remote"&&r.connection.state==="connected")??t.find(r=>r.mode==="remote")}function oL(...t){return t.find(e=>e?.trim())?.trim()}function Hce(t){return t==="remote"||t.startsWith("remote:")}function eL(t){return t.replace(/\\/g,"/").replace(/\/+$/,"")}function gp(t,e,r,n){return{area:"provider",providerId:t.providerId,error:e,message:r,actions:[{type:"open_provider_setup",label:"Run hunsu-bridge provider status",href:Jn,providerId:t.providerId},...n]}}function pl(t,e,r,n){return{area:"connection",backendId:t,error:e,message:r,actions:n}}function t0(t,e,r){return{area:"workspace",workspaceId:t,error:e,message:r,actions:[{type:"open_workspaces",label:"Run hunsu-bridge workspace list",href:Z5},...t?[{type:"activate_workspace",label:`Run hunsu-bridge workspace inspect ${t}`,href:Z5,workspaceId:t}]:[]]}}async function sL(t,e,r,n){return cL(t,e,r,n,"/api")}async function aL(t,e,r,n){return cL(t,e,r,n,"")}async function cL(t,e,r,n,i){if(t.method==="GET"&&(r===`${i}/runs`||r===`${i}/executes`)){let o=n.runSummaries();return n.sendJson(e,200,{runs:o,executes:o.map(n.executeView)}),!0}if(t.method==="GET"&&(r===`${i}/runs/events`||r===`${i}/executes/events`))return n.streamLiveEvents(),!0;if(t.method==="POST"&&(r===`${i}/runs/start`||r===`${i}/executes/start`)){let o=await n.readJson(t),s=await Uce(o,n);return s?(n.sendJson(e,409,s),!0):(n.sendJson(e,202,await n.startRun(o)),!0)}if(t.method==="POST"&&(r===`${i}/runs/pause`||r===`${i}/executes/pause`))return n.sendJson(e,202,await n.pauseRun(await n.readJson(t))),!0;if(t.method==="POST"&&(r===`${i}/runs/resume`||r===`${i}/executes/resume`)){let o=await n.resumeRun(await n.readJson(t));return o.ok?(n.sendJson(e,202,o.value),!0):(n.sendJson(e,409,o.error),!0)}return t.method==="POST"&&(r===`${i}/runs/stop`||r===`${i}/executes/stop`)?(n.sendJson(e,202,await n.stopRun(await n.readJson(t))),!0):t.method==="POST"&&(r===`${i}/runs/complete-move`||r===`${i}/executes/complete-move`)?(n.sendJson(e,202,await n.completeMove(await n.readJson(t))),!0):$ce(t,e,r,n,i)}async function Uce(t,e){let r=rL(t,{localBridgeTokenPresent:e.localBridgeTokenPresent()}),n=Yb(r)||r.modelSelection||r.aliases?.length||e.modelPreflight?await e.bridgeStatus():void 0,i=n?PC(r,n):void 0;if(i)return i;let o=n?kC(r,n):void 0;if(o)return o;let s=e.modelPreflight?await e.modelPreflight(r):void 0;if(s)return s;if(e.roadmapId){let a=e.managedRoadmaps().find(c=>c.roadmapId===e.roadmapId);return CC(a,e.providerRegistry,e.env,n?{body:r,status:n}:void 0)}return nL({repositoryPath:e.repositoryPath,registry:e.providerRegistry,roadmaps:e.managedRoadmaps(),env:e.env,selected:n?{body:r,status:n}:void 0})}function $ce(t,e,r,n,i){if(t.method==="GET"&&r===`${i}/agent-sessions`)return n.sendJson(e,200,{sessions:n.agentSessions()}),!0;if(t.method==="GET"&&r===`${i}/agent-sessions/events`)return n.streamAgentSessionEvents(),!0;if(t.method==="GET"&&r.startsWith(`${i}/agent-sessions/`)){let o=Fce(r.slice(`${i}/agent-sessions`.length));if(o?.action==="show"){let s=n.findAgentSession(o.sessionId);return n.sendJson(e,s?200:404,s?{session:s}:{error:`Unknown AgentSession: ${o.sessionId}`}),!0}if(o?.action==="events")return n.streamAgentSessionEvents(o.sessionId),!0}return!1}function Fce(t){if(!t.startsWith("/"))return;if(t.endsWith("/events")){let r=t.slice(1,-7);return r?{action:"events",sessionId:decodeURIComponent(r)}:void 0}let e=t.slice(1);return e?{action:"show",sessionId:decodeURIComponent(e)}:void 0}async function uL(t,e,r,n,i){return t.method==="GET"&&r==="/api/filesystem/roots"?(i.sendJson(e,200,{roots:i.browseRootEntries(i.cwd)}),!0):t.method==="GET"&&r==="/api/filesystem/browse"?(i.sendJson(e,200,i.browse(n.searchParams.get("path")??void 0,{cwd:i.cwd,rootId:n.searchParams.get("rootId")??void 0})),!0):t.method==="POST"&&r==="/api/filesystem/grants"?(i.sendJson(e,201,i.createGrant(await i.readJson(t),{cwd:i.cwd})),!0):!1}function dL(t){return{async readEndpointConfig(){let{host:e,port:r}=await Qo(t).read();return{host:e,port:r}},async readCredential(){let e=await wu(t).read();return e?{controlToken:e.controlToken}:void 0}}}var Au="X-Hunsu-Bridge-Control-Token";function TC(t={}){let e=t.paths??Yo(t),r=t.fetchImpl??fetch,n=t.timeoutMs??2e3,i=t.stateReader??dL(e),o=async()=>{if(t.endpoint)return jce(t.endpoint);let s=await i.readEndpointConfig();return r0(s.host,s.port)};return{endpoint:o,async probe(){return(await _C(r,await o(),n)).probe},async health(){try{return(await _C(r,await o(),n)).health}catch{return}},async request(s,a={}){let c;try{c=await o()}catch(v){return Wa(v)}let u=a.timeoutMs??n,d=await _C(r,c,u);if(d.probe.state==="offline")return V5();if(d.probe.state==="foreign-listener")return pr("BRIDGE_PORT_IN_USE","The configured Hunsu Bridge endpoint is in use by another service.");if(d.probe.state==="hunsu-unhealthy")return pr("BRIDGE_CONTROL_UNAVAILABLE",d.probe.status===void 0?"Hunsu Bridge health is unavailable.":`Hunsu Bridge health is unavailable (HTTP ${d.probe.status}).`);let l;try{l=await i.readCredential()}catch(v){return Wa(v)}if(!l?.controlToken)return pr("BRIDGE_CONTROL_UNAUTHORIZED","Hunsu Bridge control credentials are missing.");let f;try{f=qce(s)}catch(v){return Wa(v)}let p;try{p=await r(new URL(f,c),{method:a.method??"GET",headers:{[Au]:l.controlToken,...a.body===void 0?{}:{"content-type":"application/json"}},...a.body===void 0?{}:{body:JSON.stringify(a.body)},redirect:"error",signal:AbortSignal.timeout(u)})}catch{return pr("BRIDGE_CONTROL_UNAVAILABLE","Hunsu Bridge was healthy, but the authenticated control request did not complete.")}if(p.status===401||p.status===403)return pr("BRIDGE_CONTROL_UNAUTHORIZED","Hunsu Bridge rejected the local control credential.");let g=await Wce(p);return g||pr("BRIDGE_CONTROL_UNAVAILABLE",`Hunsu Bridge returned an invalid control response (HTTP ${p.status}).`)}}}async function _C(t,e,r){let n;try{n=await t(new URL("/health",e),{method:"GET",redirect:"manual",signal:AbortSignal.timeout(r)})}catch{return{probe:{state:"offline"}}}let i=await n.json().catch(()=>{});return n.ok&&i?.ok===!0&&i.service==="hunsu-bridge"&&typeof i.version=="string"&&i.protocolVersion==="local-bridge-v1"&&Pn(i.deploymentProfile)?{probe:{state:"hunsu-healthy"},health:i}:i?.service==="hunsu-bridge"?{probe:{state:"hunsu-unhealthy",status:n.status}}:{probe:{state:"foreign-listener"}}}function r0(t,e){if(!lL(t))throw new De("BRIDGE_STATE_INVALID","Bridge control endpoint configuration must use a loopback host.");return`http://${t.includes(":")&&!t.startsWith("[")?`[${t}]`:t}:${e}`}function jce(t){let e;try{e=new URL(t)}catch(r){throw new De("BRIDGE_STATE_INVALID","Bridge control endpoint configuration is invalid.",{cause:r})}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new De("BRIDGE_STATE_INVALID","Bridge control endpoint configuration must use HTTP or HTTPS.");if(!lL(e.hostname))throw new De("BRIDGE_STATE_INVALID","Bridge control endpoint configuration must use a loopback host.");if(e.username||e.password)throw new De("BRIDGE_STATE_INVALID","Bridge control endpoint configuration must not contain credentials.");return e.pathname="/",e.search="",e.hash="",e.toString().replace(/\/$/,"")}function lL(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function qce(t){if(!t.startsWith("/v1/control"))throw new De("BRIDGE_CONTROL_UNAVAILABLE","The Bridge control client may call only control API routes.");return t}async function Wce(t){if(!(t.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;let r=await t.json().catch(()=>{});if(!(!r||r.schema!==Gb||typeof r.ok!="boolean"||typeof r.code!="string"||typeof r.message!="string"))return r}var QL=Zce(Vce),eue=Yn(Ci(Qce(import.meta.url)),"../../.."),fL="# HUNSU-MANAGED-CODEX-ENVIRONMENT v1",uP=".hunsu-materialized-skill",vp=".hunsu-prev",yl=".hunsu-request",d0=["destinations.json","harness.json","executors.json","resources.json","artifact-actions.json"],tue=d0.map(t=>`${vp}/${t}`),n0=d0.map(t=>`${yl}/${t}`),rue=[...tue,...n0],ZL="check-command",nue="Hello World Web Project",iue=["Create a minimal Hello World web project from this empty checkout.","Add the smallest practical web app files, package scripts, and run instructions needed to launch it locally through an Artifact Action from a clean checkout.","Keep the implementation simple and verify the project can be started or built with a concrete command."].join(" "),oue=[{id:"destination_001",title:"Create a runnable Hello World web app",acceptanceCriteria:["The repository contains a minimal runnable web app.","The app renders Hello World or an equivalent visible greeting in a browser.","A documented package script starts or builds the hosted action surface."],constraints:["Prefer the smallest static or Vite-style implementation that is easy to inspect.","Do not add unrelated product features."],priority:100}],sue=["Act as Faker, a pragmatic engineer.","Build the smallest working web project that satisfies the goal, prefer simple conventional files and scripts, and verify the result with concrete commands."].join(" "),aue=["Act as Keria, a careful reviewer.","Verify the completed web project against the goal with concrete evidence, and call out any missing run or build proof."].join(" "),pL="Plan the smallest ExecutionPlan needed for the available engineer Member to create and verify the Hello World web project.",rw=`
212
+ ...[truncated]`,Fs=8*1024,sr=128*1024,js=32*1024,cue=100,uue=256*1024,eH=50,tH=256*1024,due=512*1024,lue=256*1024,fue=1024*1024,pue=250,mue=300,hue=900*1e3,FC=256*1024,jC=new WeakMap,dw=q5(),gue="hunsuBridgeToken",qC="x-hunsu-bridge-token",yue="x-hunsu-bridge-control-token",vue=900*1e3,xue=["http://127.0.0.1:19688","http://localhost:19688"];async function dP(t,e){let r=typeof t=="function"?await t(e):t,n=r.ok?r.value.backendId:r.error.backendId,i=Ru(e);return i.backendId&&n!==i.backendId?$s(i.backendId,`Provider inventory backend ${n} does not match selected backend ${i.backendId}.`):!i.backendId&&i.connectionMode==="remote"&&n==="local"?$s("remote","A remote backend selection requires a remote provider inventory."):!i.backendId&&i.connectionMode!=="remote"&&n!=="local"?$s("local",`Provider inventory backend ${n} does not match the default local backend.`):r}function Sue(t=[]){return{events:t,runs:{},agentSessions:{},hunsuDrafts:{},hunsuDraftArtifacts:{},filesystemCapabilities:{},liveSubscribers:new Set,agentSessionSubscribers:new Set}}function rH(t,e){let r=t??Yf(L3(e)).webUrl;try{return new URL(r).toString()}catch{throw new Error(`Invalid Studio web URL: ${r}`)}}function bue(t){let e=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",r=process.platform==="win32"?["/c","start","",t]:[t];return new Promise((n,i)=>{let o=Gce(e,r,{detached:!0,stdio:"ignore",windowsHide:!0});o.once("spawn",()=>{o.unref(),n()}),o.once("error",i)})}function lP(t){return bue(t)}function wue(t,e){let r=vl(t,"host");return r?`http://${oH(e.bridgeApi.host)?r.replace(/^(0\.0\.0\.0|\[::\])(?=:|$)/,"127.0.0.1"):r}`:IS(e.bridgeApi)}function Iue(t,e){let r=typeof t?.controlToken=="function"?hl(t.controlToken()):hl(t?.controlToken),n=hl(t?.authToken),i=Math.max(1,t?.pairingTokenTtlMs??vue),o=t?.pairingService??(r?Vb({controlToken:r,ttlMs:i,...n?{initialPairing:{credential:n,browserUrl:rH(void 0,e.processEnv)}}:{}}):void 0);if(t?.pairingService&&n&&!t.pairingService.validate(n).valid)throw new Error("The supplied pairing service must own the explicit browser auth token.");return{authToken:o?void 0:n,controlToken:typeof t?.controlToken=="function"?t.controlToken:hl(t?.controlToken),pairingService:o,allowedOrigins:Pue([...xue,...Aue(e.processEnv),...t?.allowedOrigins??[]].map(iH).filter(s=>s!==void 0)),allowNoOrigin:t?.allowNoOrigin??!0,requirePairing:t?.requirePairing??!!(t?.authToken||o||t?.pairingValidator),pairingValidator:t?.pairingValidator}}function Eue(t,e,r,n={}){let i=vl(t,"origin"),o=kue(i,r);if(i&&o===void 0)return{allowed:!1,status:403,error:`Origin is not allowed for Hunsu Bridge: ${i}`,code:"origin_not_allowed",corsHeaders:Us()};if(!i&&!r.allowNoOrigin)return{allowed:!1,status:403,error:"Requests without an Origin header are not allowed.",code:"origin_missing",corsHeaders:Us()};let s=o??Us(),a=!n.skipAuth&&r.requirePairing&&!$5(e.pathname)?Rue(t,e,r):{valid:!0};return a.valid?{allowed:!0,corsHeaders:s}:{allowed:!1,status:401,error:a.error,code:a.code,corsHeaders:s}}function kue(t,e){if(!t)return Us();let r=iH(t);if(!(!r||!e.allowedOrigins.includes(r)))return{...Us(),"access-control-allow-origin":r}}function mL(t,e){let r=typeof e.controlToken=="function"?hl(e.controlToken()):e.controlToken;if(!r)return{allowed:!1,status:404,error:"Bridge control endpoint is not enabled.",code:"bridge_control_unavailable",corsHeaders:Us()};let n=vl(t,yue);return!n||!nH(n,r)?{allowed:!1,status:401,error:"Missing or invalid Hunsu Bridge control token.",code:"bridge_control_token_invalid",corsHeaders:Us()}:{allowed:!0,corsHeaders:Us()}}function Rue(t,e,r){let n=r.authToken,o=vl(t,"authorization")?.match(/^Bearer\s+(.+)$/i)?.[1]?.trim(),s=vl(t,qC),a=e.searchParams.get(gue)??void 0,c=[o,s,a].find(d=>d!==void 0);if(c===void 0)return{valid:!1,code:"pairing_token_missing",error:"Missing Hunsu Bridge pairing token."};let u=r.pairingService?.validate(c)??r.pairingValidator?.(c);if(u?.valid)return{valid:!0};if(u?.valid===!1||!n||!nH(c,n)){let d=u?.valid===!1?u.reason:"invalid";return{valid:!1,code:d==="expired"?"pairing_token_expired":d==="revoked"?"pairing_token_revoked":"pairing_token_invalid",error:d==="expired"?"Hunsu Bridge pairing token expired. Pair again with `hunsu-bridge pair`.":d==="revoked"?"Hunsu Bridge pairing token was revoked. Pair again with `hunsu-bridge pair`.":"Invalid Hunsu Bridge pairing token."}}return{valid:!0}}function nH(t,e){let r=Buffer.from(t),n=Buffer.from(e);return r.length===n.length&&Yce(r,n)}function vl(t,e){let n=(t.headers??{})[e.toLowerCase()];return Array.isArray(n)?n[0]:n}function Aue(t){let e=hl(t.HUNSU_WEB_PORT),r=hl(t.HUNSU_WEB_HOST);return[...Cue(t.HUNSU_BRIDGE_ALLOWED_ORIGINS),e?`http://127.0.0.1:${e}`:void 0,e?`http://localhost:${e}`:void 0,r&&e&&!oH(r)?`http://${r}:${e}`:void 0].filter(n=>n!==void 0)}function Cue(t){return t?.split(",").map(e=>e.trim()).filter(Boolean)??[]}function iH(t){if(t?.trim())try{return new URL(t.trim()).origin}catch{return}}function hl(t){return t?.trim()?t.trim():void 0}function Pue(t){return[...new Set(t)]}function oH(t){return t==="0.0.0.0"||t==="::"||t==="[::]"}function DC(t){if(t.testRunner==="deterministic")return new WC;let e=t.processEnv.HUNSU_CODEX_BINARY_PATH?.trim(),r=e&&t.codexAppServer.command==="codex"?e:t.codexAppServer.command;return Zd({clientOptions:{command:r,args:t.codexAppServer.args,environment:t.codexAppServer.environment},threadOptions:t.codexThreadOptions})}async function _ue(t,e){let r=e?await zg(t,e,{lastRunUsage:sH(e)}):await gu({env:t});return{bridge:{connected:!0,version:ul().bridgeVersion,protocolVersion:ul().protocolVersion},runtimes:{codex:r},...e?.codexLogin?{codexLogin:e.codexLogin}:{},tools:{git:await hL("git",["--version"]),node:await hL(process.execPath,["--version"])}}}function Tue(t){let e="account"in t?Due(t.account):void 0,r="rateLimits"in t?Bue(t.rateLimits):void 0,n=["accountError"in t?t.accountError:void 0,"rateLimitsError"in t?t.rateLimitsError:void 0,t.error].filter(i=>typeof i=="string"&&i.trim().length>0);return{backend:t.backend,available:t.available,initialized:"initialized"in t?t.initialized!==void 0:void 0,auth:e?.auth,accountSummary:e?.summary,rateLimitSummary:r?.summary,rateLimited:r?.rateLimited,accountError:"accountError"in t?ew(t.accountError):void 0,rateLimitsError:"rateLimitsError"in t?ew(t.rateLimitsError):void 0,error:n.length>0?ew(n.join("; ")):void 0}}function Due(t){if(!nw(t))return;let r={...nw(t.account)?t.account:{},...t},n=r.requiresOpenaiAuth===!0,i=Nue(r);return{auth:{state:n?"not_authenticated":"authenticated",method:i,access:i==="chatgpt"?"subscription":i==="api_key"||i==="access_token"?"usage_based":"unknown"},summary:n?void 0:{displayName:za(r,["displayName","name","userName"]),email:za(r,["email","userEmail"]),workspaceName:za(r,["workspaceName","organizationName","orgName"]),planLabel:za(r,["planLabel","plan","planType","subscriptionPlan"])}}}function Bue(t){if(!nw(t))return;let e=nw(t.rateLimits)?t.rateLimits:{},r={...t,...e},n=za(r,["rateLimitReachedType","rate_limit_reached_type"]),i=za(r,["label","status","summary"])??(n&&n.toLowerCase()!=="none"?"Rate limited":"Available"),o=za(r,["remainingLabel","remaining"]),s=r.rateLimited===!0||r.limited===!0||n!==void 0&&n.toLowerCase()!=="none"||/\brate.?limited\b|quota exceeded|temporarily unavailable|no remaining/i.test(`${i} ${o??""}`);return{summary:{label:i,resetAt:za(r,["resetAt","reset_at"]),remainingLabel:o},rateLimited:s}}function Nue(t){let e=`${za(t,["authMethod","method","loginMethod","accountType","type"])??""}`.toLowerCase();return e.includes("chatgpt")||e.includes("subscription")?"chatgpt":e.includes("api")?"api_key":e.includes("access")?"access_token":"unknown"}function za(t,e){for(let r of e){let n=t[r];if(typeof n=="string"&&n.trim())return ew(n.trim());if(typeof n=="number")return String(n)}}function ew(t){if(!t)return;let e=Qr(t);return typeof e=="string"?e:void 0}function nw(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function hL(t,e){try{let{stdout:r,stderr:n}=await QL(t,e,{timeout:2e3,windowsHide:!0}),i=`${r}
213
+ ${n}`.trim().split(/\r?\n/).find(Boolean);return{installed:!0,binaryPath:t,version:i}}catch(r){return{installed:!1,binaryPath:t,error:r instanceof Error?r.message:String(r)}}}function sH(t){return Object.values(t.runs).filter(r=>r.lastRunUsage).sort((r,n)=>n.updatedAt.localeCompare(r.updatedAt))[0]?.lastRunUsage}function Oue(t){if(t)return{inputTokens:t.input_tokens,cachedInputTokens:t.cached_input_tokens,outputTokens:t.output_tokens,reasoningTokens:t.reasoning_output_tokens}}var WC=class{async runTeamPlanning(e){return{runId:e.runId,provider:"codex",providerThreadId:this.threadId(e.runId,"team"),providerTurnId:this.turnId(e.runId,"plan"),finalResponse:JSON.stringify({kind:"queue",id:"deterministic-e2e-execute",items:[{kind:"goal",stage:"needs_evaluation",id:"hello-world-web-app",assignee:{executorId:"faker",goal:"Create the smallest static Hello World web app with package scripts."},evaluator:{executorId:"keria",prompt:"Verify the static Hello World app files and scripts exist."},remainingAttempts:1,requires:"PrevMove"}]},null,2)}}async runMemberPath(e){return e.outputSchema?{runId:e.runId,provider:"codex",providerThreadId:this.threadId(e.runId,"evaluator"),providerTurnId:this.turnId(e.runId,e.memberPath.id),finalResponse:JSON.stringify(this.evaluateHelloWorldApp(e.repositoryPath),null,2)}:(Mue(e.repositoryPath),{runId:e.runId,provider:"codex",providerThreadId:this.threadId(e.runId,"member"),providerTurnId:this.turnId(e.runId,e.memberPath.id),finalResponse:"Created a minimal static Hello World web app with index.html, package.json, and README.md."})}async runMoveFinalizer(e){return{runId:e.runId,provider:"codex",providerThreadId:this.threadId(e.runId,"finalizer"),providerTurnId:this.turnId(e.runId,`finalize-${e.moveId}`),finalResponse:["move: create runnable Hello World web app","",e.completionSummary,"","Evidence:",...e.pathOutputs.map(r=>`- ${r.pathId}: ${r.finalResponse??"completed"}`)].join(`
214
+ `)}}async prepareHunsuDraftSession(e){return{runId:e.runId,provider:"codex",providerThreadId:this.threadId(e.runId,"hunsu-draft")}}async runHunsuDraftTurn(e){return{runId:e.runId,provider:"codex",providerThreadId:e.providerThreadId??this.threadId(e.runId,"hunsu-draft"),providerTurnId:this.turnId(e.runId,"hunsu-draft-turn"),finalResponse:"Updated the decoded Hunsu request files. Run the supplied Draft check command to create a DiffArtifact."}}resumeRun(e){return this.runTeamPlanning(e)}pauseRun(e){return Promise.resolve()}stopRun(e){return Promise.resolve()}providerStatus(){return Promise.resolve({backend:"app-server",available:!0,initialized:{runner:"deterministic"}})}async*events(e){if(e.startsWith("hunsu-draft:")){yield*this.hunsuDraftEvents(e);return}yield{type:"runner.status.changed",runId:e,phase:"working",headline:"Deterministic E2E runner"}}async*hunsuDraftEvents(e){let r=this.threadId(e,"hunsu-draft"),n=this.turnId(e,"hunsu-draft-turn"),i=Date.now();yield{type:"runner.turn.started",runId:e,providerThreadId:r,providerTurnId:n,startedAtMs:i},await Zo(80),yield{type:"runner.item.started",runId:e,providerThreadId:r,providerTurnId:n,itemId:"reasoning_001",item:{id:"reasoning_001",type:"reasoning",raw:{type:"reasoning",id:"reasoning_001"}},startedAtMs:i+80},await Zo(80),yield{type:"runner.item.delta",runId:e,providerThreadId:r,providerTurnId:n,itemId:"reasoning_001",deltaKind:"reasoningSummary",delta:"Inspecting decoded request runtime files."},await Zo(80),yield{type:"runner.item.delta",runId:e,providerThreadId:r,providerTurnId:n,itemId:"reasoning_001",deltaKind:"reasoningText",delta:"Mapping the request to the editable Hunsu runtime surface."},await Zo(80),yield{type:"runner.item.completed",runId:e,providerThreadId:r,providerTurnId:n,itemId:"reasoning_001",item:{id:"reasoning_001",type:"reasoning",summary:["Inspecting decoded request runtime files."],content:["Mapping the request to the editable Hunsu runtime surface."],durationMs:240,raw:{type:"reasoning",id:"reasoning_001"}},completedAtMs:i+320},await Zo(80),yield{type:"runner.item.started",runId:e,providerThreadId:r,providerTurnId:n,itemId:"cmd_check_001",item:{id:"cmd_check_001",type:"commandExecution",command:"node --input-type=module -e <draft-check-command>",commandActions:[{type:"unknown",command:"node --input-type=module -e <draft-check-command>"}],raw:{type:"commandExecution",id:"cmd_check_001"}},startedAtMs:i+400},await Zo(80),yield{type:"runner.item.delta",runId:e,providerThreadId:r,providerTurnId:n,itemId:"cmd_check_001",deltaKind:"commandOutput",delta:`Draft check command completed.
215
+ `},await Zo(80),yield{type:"runner.item.completed",runId:e,providerThreadId:r,providerTurnId:n,itemId:"cmd_check_001",item:{id:"cmd_check_001",type:"commandExecution",status:"completed",command:"node --input-type=module -e <draft-check-command>",aggregatedOutput:`Draft check command completed.
216
+ `,durationMs:160,raw:{type:"commandExecution",id:"cmd_check_001",status:"completed"}},completedAtMs:i+560},await Zo(80),yield{type:"runner.item.started",runId:e,providerThreadId:r,providerTurnId:n,itemId:"file_change_001",item:{id:"file_change_001",type:"fileChange",changes:[{path:".hunsu-request/destinations.json",kind:"updated"}],raw:{type:"fileChange",id:"file_change_001"}},startedAtMs:i+640},await Zo(80),yield{type:"runner.item.completed",runId:e,providerThreadId:r,providerTurnId:n,itemId:"file_change_001",item:{id:"file_change_001",type:"fileChange",changes:[{path:".hunsu-request/destinations.json",kind:"updated"}],durationMs:80,raw:{type:"fileChange",id:"file_change_001"}},completedAtMs:i+720},await Zo(80),yield{type:"runner.item.started",runId:e,providerThreadId:r,providerTurnId:n,itemId:"assistant_001",item:{id:"assistant_001",type:"agentMessage",raw:{type:"agentMessage",id:"assistant_001"}},startedAtMs:i+800};for(let o of["Updated decoded Hunsu request files. ","DiffArtifact review is ready when the check output appears."])await Zo(60),yield{type:"runner.item.delta",runId:e,providerThreadId:r,providerTurnId:n,itemId:"assistant_001",deltaKind:"agentMessage",delta:o};yield{type:"runner.item.completed",runId:e,providerThreadId:r,providerTurnId:n,itemId:"assistant_001",item:{id:"assistant_001",type:"agentMessage",text:"Updated decoded Hunsu request files. DiffArtifact review is ready when the check output appears.",durationMs:120,raw:{type:"agentMessage",id:"assistant_001"}},completedAtMs:i+920},yield{type:"runner.turn.completed",runId:e,providerThreadId:r,providerTurnId:n,completedAtMs:i+940}}evaluateHelloWorldApp(e){let r=at(e,"index.html"),n=at(e,"package.json"),i=Qt(r)?Vs(r,"utf8"):"",o=Qt(n)?Vs(n,"utf8"):"",s=/hello\s+world/i.test(i),a=/"scripts"\s*:/.test(o);return s&&a?{type:"pass",summary:"The static Hello World web app files and package scripts are present.",reason:"",feedback:"",nextGoal:"",evidence:["index.html renders Hello World","package.json defines runnable scripts"]}:{type:"fail",summary:"",reason:"The Hello World app files are not complete yet.",feedback:"Create index.html with a visible Hello World greeting and package.json with scripts.",nextGoal:"Create the minimal static Hello World app files.",evidence:[s?"index.html greeting present":"index.html greeting missing",a?"package scripts present":"package scripts missing"]}}threadId(e,r){return`thread-${r}-${ui(ci("sha256").update(e)).slice(0,12)}`}turnId(e,r){return`turn-${ui(ci("sha256").update(`${e}:${r}`)).slice(0,12)}`}};function Mue(t){bo(t,{recursive:!0}),es(at(t,"index.html"),["<!doctype html>",'<html lang="en">'," <head>",' <meta charset="utf-8">',' <meta name="viewport" content="width=device-width, initial-scale=1">'," <title>Hello World</title>"," </head>"," <body>"," <main>"," <h1>Hello World</h1>"," </main>"," </body>","</html>",""].join(`
217
+ `),"utf8"),es(at(t,"package.json"),`${JSON.stringify({scripts:{start:"python3 -m http.server 4173",build:`node -e "console.log('static build ok')"`}},null,2)}
218
+ `,"utf8"),es(at(t,"README.md"),["# Hello World","","Run `npm run start` to serve the static page or `npm run build` for a simple build check.",""].join(`
219
+ `),"utf8")}function aH(t={}){let e=t.state??Sue(),r=t.persist??!0,n=t.cwd??eue,i=t.runtimeConfig??Yf(wS(process.env,{cwd:n,roadmapRegistryPath:t.roadmapRegistryPath})),o={...i.processEnv},s={...i.codexAppServer,environment:{...i.codexAppServer.environment}},a=M5(o);BC(i,o,s,a);let c=t.roadmapRegistryPath??i.roadmapRegistryPath,u=t.runner??DC(i),d=t.runner===void 0,l=t.actionRunner,f=Iue(t.security,i),p=Lue(t.controlStatus),g=oC({providerStateStore:g5(i.processEnv),codex:{env:()=>i.processEnv,loginState:e,onConfigure(_){a=_,BC(i,o,s,a),d&&(u=DC(i))}}}),v=t.providerService?J5({service:t.providerService,fallback:g,env:()=>i.processEnv}):g,b=t.providerService?.onConfigurationChange(_=>{a=Eu(_),BC(i,o,s,a),d&&(u=DC(i))}),C=async(_,F)=>{if(t.providerInventory)return dP(t.providerInventory,F);let he=await Iu({request:_,runtimeConfig:i,providerRegistry:v,managedRoadmaps:()=>vo({roadmapRegistryPath:c})});return RC(F,he)},D=H5(async(_,F)=>{try{let he=U5(_),z=he.pathname;if(t.controlRouteHandler&&await t.controlRouteHandler(_,F,he))return;let Ce=mL(_,f).allowed,de=Eue(_,he,f,{skipAuth:_.method==="OPTIONS"||vC(z)||Ce});if(dw.set(F,de.corsHeaders),_.method==="OPTIONS"){At(F,de.allowed?204:de.status??403,de.allowed?{}:{error:de.error??"Origin is not allowed.",code:de.code});return}if(!de.allowed){At(F,de.status??403,{error:de.error??"Bridge API request is not allowed.",code:de.code});return}if(_.method==="GET"&&yC(z)){At(F,200,{ok:!0,service:"hunsu-bridge",version:ul().bridgeVersion,protocolVersion:"local-bridge-v1",deploymentProfile:t.deploymentProfile??"production"});return}if(vC(z)){let R=mL(_,f);if(!R.allowed){At(F,R.status??401,{error:R.error??"Bridge control request is not allowed.",code:R.code});return}if(_.method==="GET"&&z==="/api/bridge/control/status"){At(F,200,p);return}if(_.method!=="POST"){At(F,405,{error:"method_not_allowed"});return}if(z==="/api/bridge/control/shutdown"){At(F,202,{shuttingDown:!0}),setTimeout(()=>{try{D.close()}catch(me){if(!(me instanceof Error&&"code"in me&&me.code==="ERR_SERVER_NOT_RUNNING"))throw me}},0);return}if(z==="/api/bridge/pairing/revoke"){let me=f.pairingService;if(!me){At(F,404,{error:"Bridge pairing is not enabled.",code:"pairing_unavailable"});return}let Pe=me.revoke();At(F,202,{pairing:me.getSafeMetadata(),revoked:Pe});return}let V=await Qi(_),le=f.pairingService;if(!le){At(F,404,{error:"Bridge pairing is not enabled.",code:"pairing_unavailable"});return}let se=typeof V.webUrl=="string"&&V.webUrl.trim()?V.webUrl:void 0,H=typeof V.roadmapId=="string"&&V.roadmapId.trim()?V.roadmapId:void 0,G=new URL(rH(se,i.processEnv));if(H){let me=G.pathname.replace(/\/$/u,"");G.pathname=`${me.endsWith("/studio")?me:"/studio"}/roadmaps/${encodeURIComponent(H)}`}let j=le.rotate({browserUrl:G.toString(),...H?{workspaceId:H}:{}});if(!j.ok){At(F,400,{error:j.error.message,code:j.error.code});return}At(F,202,{bridgeApiUrl:wue(_,i),studioUrl:j.value.internal.pairingUrl,authToken:j.value.internal.credential,pairing:j.value.safe});return}if(_.method==="GET"&&z==="/api/prerequisites"){At(F,200,await _ue(i.processEnv,e));return}if(_.method==="GET"&&z==="/api/providers/inventory"){At(F,200,await C(_,{backendId:he.searchParams.get("backendId")??void 0}));return}if(_.method==="POST"&&(z==="/api/model-aliases/validate"||z==="/api/model-aliases/resolve")){let R=await Qi(_),V=await C(_,{backendId:R.backendId}),le=V.ok?ll({selection:R.modelSelection,aliases:R.aliases,backendId:V.value.backendId,inventories:V.value.providers}):fl(V.error);At(F,200,le.ok?{ok:!0,backendId:le.backendId,resolved:le.resolved,provider:le.provider}:{ok:!1,backendId:le.backendId,error:le.error.error,message:le.error.message,actions:le.error.actions});return}if(await b5(_,F,z,he,{providerRegistry:v,env:i.processEnv,codexLoginState:e,latestCodexRunUsage:()=>sH(e),legacyCodexStatus:async()=>u.providerStatus?await u.providerStatus():{backend:"sdk",available:!0},sanitizeLegacyCodexStatus:R=>Tue(R),readJson:Qi,sendJson:At})||await E5(_,F,z,{studioConnectionStatus:()=>{let R=TH(n,{roadmapRegistryPath:c});return aC({bridgeApiUrl:IS(i.bridgeApi),repositoryPath:n,roadmapId:R?.roadmapId,roadmapDisplayName:R?.displayName,runtimeConfig:i})},bridgeStatus:()=>Iu({request:_,runtimeConfig:i,providerRegistry:v,managedRoadmaps:()=>vo({roadmapRegistryPath:c})}),headlessRemote:t.headlessRemote,sendJson:At})||await R5(_,F,z,{bridgeStatus:()=>Iu({request:_,runtimeConfig:i,providerRegistry:v,managedRoadmaps:()=>vo({roadmapRegistryPath:c})}),currentProvider:()=>gC(v,i.processEnv),managedRoadmaps:()=>vo({roadmapRegistryPath:c}),addWorkspace:R=>$ue(R,e,{persist:r,roadmapRegistryPath:c}),selectRepository:R=>{n=R},setWorkspaceLifecycle:(R,V)=>OC(R,V,{roadmapRegistryPath:c}),removeWorkspace:R=>kL(R,{roadmapRegistryPath:c}),recentRoadmaps:()=>kH({roadmapRegistryPath:c}),removeRoadmap:R=>kL(R,{roadmapRegistryPath:c}),activateRoadmap:R=>OC(R,"active",{roadmapRegistryPath:c}),deactivateRoadmap:R=>OC(R,"inactive",{roadmapRegistryPath:c}),inspectProject:R=>hP(yp(R,e),{roadmapRegistryPath:c}),openRoadmap:R=>AH(R,e,{persist:r,roadmapRegistryPath:c}),inspectRoadmapPort:R=>Vde(yp(R,e)),applyRoadmapPort:R=>PH(yp(R,e),e,{roadmapRegistryPath:c}),createRoadmap:R=>CH(R,e,{persist:r,roadmapRegistryPath:c}),readJson:Qi,sendJson:At})||await uL(_,F,z,he,{cwd:n,browseRootEntries:gP,browse:Kde,createGrant:(R,V)=>Xde(R,e,V),readJson:Qi,sendJson:At})||await F5(_,F,z,{board:()=>rr(e,{cwd:n,persist:r}),roadmapView:()=>IL(rr(e,{cwd:n,persist:r})),events:()=>YC(e,{cwd:n,persist:r}),repository:()=>Xn(n),selectRepository:R=>{let V=NH(R.cwd,e,{persist:r});return n=V.repository.root,V},worktree:()=>Xn(n),artifacts:()=>rr(e,{cwd:n,persist:r}).artifacts,artifact:R=>EL(rr(e,{cwd:n,persist:r}),R),artifactActions:R=>wL(R,_,F,{cwd:n,actionRunner:l,ambientEnv:i.processEnv,processEnv:i.processEnv,worktreeRoot:i.actionWorktreeRoot}),skills:()=>aw(i.processEnv),moveDiff:R=>KC(rr(e,{cwd:n,persist:r}),R,n),executeCommands:R=>JC(HL(R),e,{cwd:n,persist:r}),decideLine:(R,V)=>LL(R,V,e,{cwd:n,persist:r}),readJson:Qi,sendJson:At})||await j5(_,F,z,{repositoryPath:R=>_H(R,{roadmapRegistryPath:c}),loadRoadmap:R=>Gde(R,e,{persist:r,roadmapRegistryPath:c}),board:(R,V)=>rr(e,{cwd:V,persist:r}),roadmapView:(R,V)=>IL(rr(e,{cwd:V,persist:r})),events:(R,V)=>YC(e,{cwd:V,persist:r}),repository:(R,V)=>Xn(V),worktree:(R,V)=>Xn(V),artifacts:(R,V)=>rr(e,{cwd:V,persist:r}).artifacts,artifact:(R,V,le)=>EL(rr(e,{cwd:V,persist:r}),le),artifactActions:(R,V,le)=>wL(R,_,F,{cwd:le,roadmapId:V,actionRunner:l,ambientEnv:i.processEnv,processEnv:i.processEnv,worktreeRoot:i.actionWorktreeRoot}),hunsuDrafts:(R,V,le)=>Fue(R,_,F,e,{cwd:le,persist:r,roadmapId:V,runner:u,bridgeApiBaseUrl:IS(i.bridgeApi),bridgeApiAuthToken:f.authToken,apmSkillRegistryClient:t.apmSkillRegistryClient,routeWorktreeRoot:i.routeWorktreeRoot,providerInventory:se=>C(_,se)}),executes:(R,V,le)=>aL(_,F,R,{repositoryPath:le,roadmapId:V,providerRegistry:v,env:i.processEnv,managedRoadmaps:()=>vo({roadmapRegistryPath:c}),bridgeStatus:()=>Iu({request:_,runtimeConfig:i,providerRegistry:v,managedRoadmaps:()=>vo({roadmapRegistryPath:c})}),localBridgeTokenPresent:()=>!!vl(_,qC),runSummaries:()=>wp(e,le).filter(se=>!se.roadmapId||se.roadmapId===V).map(Ai),executeView:se=>Zi(se),modelPreflight:se=>TL(se,e,{cwd:le,persist:r,providerInventory:H=>C(_,H)}),startRun:se=>DL(se,e,{cwd:le,persist:r,roadmapId:V,runner:u,apmSkillRegistryClient:t.apmSkillRegistryClient,routeWorktreeRoot:i.routeWorktreeRoot,providerInventory:H=>C(_,H)}),pauseRun:se=>BL(se,e,{cwd:le,persist:r,runner:u}),resumeRun:async se=>NL(se,e,{cwd:le,persist:r,runner:u,apmSkillRegistryClient:t.apmSkillRegistryClient,bridgeStatus:await Iu({request:_,runtimeConfig:i,providerRegistry:v,managedRoadmaps:()=>vo({roadmapRegistryPath:c})}),providerInventory:H=>C(_,H)}),stopRun:se=>OL(se,e,{cwd:le,persist:r,runner:u}),completeMove:se=>ML(se,e,{cwd:le,persist:r}),streamLiveEvents:()=>UL(_,F,e,{cwd:le}),agentSessions:()=>iP(e,le).filter(se=>bU(se,V)).map(sP),findAgentSession:se=>oP(e,se,{cwd:le,roadmapId:V}),streamAgentSessionEvents:se=>$L(_,F,e,{cwd:le,roadmapId:V,sessionId:se}),readJson:Qi,sendJson:At}),skills:()=>aw(i.processEnv),moveFileTree:(R,V,le,se)=>Tle(rr(e,{cwd:V,persist:r}),le,V,se),moveFileBlob:(R,V,le,se)=>Ble(rr(e,{cwd:V,persist:r}),le,V,se),moveDiff:(R,V,le)=>KC(rr(e,{cwd:V,persist:r}),le,V),executeCommands:(R,V,le)=>JC(HL(le),e,{cwd:V,persist:r}),decideLine:(R,V,le,se)=>LL(le,se,e,{cwd:V,persist:r}),readJson:Qi,sendJson:At})||await sL(_,F,z,{repositoryPath:n,providerRegistry:v,env:i.processEnv,managedRoadmaps:()=>vo({roadmapRegistryPath:c}),bridgeStatus:()=>Iu({request:_,runtimeConfig:i,providerRegistry:v,managedRoadmaps:()=>vo({roadmapRegistryPath:c})}),localBridgeTokenPresent:()=>!!vl(_,qC),runSummaries:()=>wp(e,n).map(Ai),executeView:R=>Zi(R),modelPreflight:R=>TL(R,e,{cwd:n,persist:r,providerInventory:V=>C(_,V)}),startRun:R=>DL(R,e,{cwd:n,persist:r,runner:u,apmSkillRegistryClient:t.apmSkillRegistryClient,routeWorktreeRoot:i.routeWorktreeRoot,providerInventory:V=>C(_,V)}),pauseRun:R=>BL(R,e,{cwd:n,persist:r,runner:u}),resumeRun:async R=>NL(R,e,{cwd:n,persist:r,runner:u,apmSkillRegistryClient:t.apmSkillRegistryClient,bridgeStatus:await Iu({request:_,runtimeConfig:i,providerRegistry:v,managedRoadmaps:()=>vo({roadmapRegistryPath:c})}),providerInventory:V=>C(_,V)}),stopRun:R=>OL(R,e,{cwd:n,persist:r,runner:u}),completeMove:R=>ML(R,e,{cwd:n,persist:r}),streamLiveEvents:()=>UL(_,F,e,{cwd:n}),agentSessions:()=>iP(e,n).map(sP),findAgentSession:R=>oP(e,R,{cwd:n}),streamAgentSessionEvents:R=>$L(_,F,e,{cwd:n,sessionId:R}),readJson:Qi,sendJson:At}))return;At(F,404,{error:"Not found"})}catch(he){let z=he instanceof Error?he.message:String(he);At(F,400,{error:z})}},{runtimeConfig:i});return b&&D.once("close",b),D}function Lue(t){let e=ul();return{ok:!0,instanceId:t?.instanceId?.trim()||`bridge_instance_${Xce(18).toString("base64url")}`,protocolVersion:e.protocolVersion,bridgeVersion:e.bridgeVersion,daemonPid:Hue(t?.daemonPid)??process.pid,startedAt:t?.startedAt??new Date().toISOString(),state:"running",deploymentProfile:t?.deploymentProfile??"production"}}function Hue(t){let e=typeof t=="string"&&/^\d+$/.test(t.trim())?Number(t):t;return typeof e=="number"&&Number.isInteger(e)&&e>0?e:void 0}function BC(t,e,r,n){Uue(t.processEnv,ol({baseEnv:e,settings:n})),t.codexAppServer=Yf(Zh(t.processEnv,{...n.appServerCommand?{}:{command:r.command},...n.appServerArgs?{}:{args:r.args},environment:{...r.environment,...t.processEnv}}))}function Uue(t,e){for(let r of Object.keys(t))delete t[r];for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]=n)}function $ue(t,e,r){let n=yp(t,e),i=hP(n,{roadmapRegistryPath:r.roadmapRegistryPath});if(i.kind==="hunsu-roadmap")return AH({path:i.path,title:t.title},e,r);if(i.kind==="git-project")return PH({path:i.path,title:t.title??ts(i.path),goal:`Port ${ts(i.path)} into Hunsu.`},e,r);if(i.kind==="new-project")return CH({path:i.path,title:t.title??ts(i.path)},e,r);throw new Error(i.reason)}async function Fue(t,e,r,n,i){if(e.method==="GET"&&t==="")return At(r,200,{drafts:lde(n,i)}),!0;if(e.method==="POST"&&t===""){let s=await Qi(e),a=await Wue(s,n,i);return At(r,202,a),!0}let o=jue(t);if(!o)return!1;if(e.method==="GET"&&o.action==="show"){let s=VC(n,o.draftSessionId,i);return At(r,s?200:404,s?{draft:s}:{error:`Unknown HUNSU Draft: ${o.draftSessionId}`}),!0}if(e.method==="POST"&&o.action==="messages"){let s=await Qi(e);return At(r,202,await dH(o.draftSessionId,s,n,i)),!0}if(e.method==="POST"&&o.action==="diff-artifacts"){let s=await zue(o.draftSessionId,n,i);if(Que(e)){if(!s.diffArtifact)throw new Error("HUNSU Draft check command did not create a DiffArtifact.");return At(r,202,Zue(s.diffArtifact)),!0}return At(r,202,s),!0}if(e.method==="GET"&&o.action==="diff-artifact"){let s=VC(n,o.draftSessionId,i),a=s?tw(s.diffArtifacts[o.diffArtifactId]):void 0;return At(r,a?200:404,a?{diffArtifact:a}:{error:`Unknown HUNSU Draft DiffArtifact: ${o.diffArtifactId}`}),!0}if(e.method==="POST"&&o.action==="approve"){let s=await Qi(e);return At(r,202,await Vue(o.draftSessionId,s,n,i)),!0}return e.method==="POST"&&o.action==="discard"?(At(r,202,await dde(o.draftSessionId,n,i)),!0):!1}function jue(t){let e=t.split("/").filter(Boolean).map(decodeURIComponent);if(e.length===1)return{action:"show",draftSessionId:e[0]};if(e.length===3&&e[1]==="diff-artifacts")return{action:"diff-artifact",draftSessionId:e[0],diffArtifactId:e[2]};if(e.length!==2)return;let r=e[1];if(r==="messages"||r==="diff-artifacts"||r==="approve"||r==="discard")return{action:r,draftSessionId:e[0]}}async function que(t,e){if(!t.managerLock)return{manager:tp()};if(t.managerLock.kind!=="manager")throw new Error(`HUNSU Draft managerLock must reference a manager package, got ${t.managerLock.kind}`);let r=await Lg(t.managerLock,{origins:e.origins});if(r.manifest.kind!=="manager")throw new Error(`Hub package ${r.manifest.kind}/${r.manifest.key}@${r.manifest.version} is not a Manager package`);return{managerLock:{...r.lock},manager:cH(r.manifest.manager)}}function cH(t){let e=og(t,"Manager");if(!e.ok)throw new Error(e.error.message);return e.value}async function uH(t,e,r){if(t.modelSelection)return IP({backendId:"local",connectionMode:"local",modelSelection:t.modelSelection,aliases:r},{providerInventory:e.providerInventory},t.modelSelection)}async function Wue(t,e,r){fP(e,r.cwd);let n=rr(e,r),i=gH(n,t),o=await que(t,n),s=new Date().toISOString(),a=Pde(e),c=hde(a),u=r.persist?SP(n,i.node,r.cwd):void 0,d=r.persist?DH(r.cwd,c,s,u,r.routeWorktreeRoot):mU(r.cwd,c,s),l=vH(i),f=pde(e,{kind:"source-protocol",repositoryPath:r.cwd,roadmapId:r.roadmapId,draftSessionId:a,value:fde(n,i,l),createdAt:s}),p={draftSessionId:a,roadmapId:r.roadmapId,repositoryPath:r.cwd,sourceLineId:String(i.line.id),sourceNodeId:String(i.node.id),sourceMoveId:i.move?String(i.move.id):void 0,routeId:c,worktree:d,agentSessionIds:[],sourceArtifactId:f.artifactId,currentArtifactId:f.artifactId,managerLock:o.managerLock,manager:o.manager,aliases:t.aliases,messages:[],diffArtifacts:{},status:"draft",createdAt:s,updatedAt:s};e.hunsuDrafts[p.draftSessionId]=p,Jue(p,i.node,Bn(r.cwd).runtime),await lH(p,r),Ja(p,r,"Hunsu draft route start",rue);let g=mP(e,p,s);if(r.runner.prepareHunsuDraftSession){g.state={type:"starting",startedAt:s},Xa(g,s),Gs(e,g);try{let v=await uH(p.manager,r,p.aliases),b=n.requests.find(D=>D.id===i.line.requestId)??n.requests[0],C=await r.runner.prepareHunsuDraftSession({runId:`hunsu-draft:${p.draftSessionId}`,repositoryPath:SH(p,r),requestGoal:String(b?.goal??"No Roadmap request goal is available."),activeDestinations:Du(n,p.sourceLineId).filter(Qa),selectedDestinationIds:yU(i.node.destinations),harness:i.node.harness,board:n,resolvedModelSelection:v?.provider,draftSessionId:p.draftSessionId,manager:p.manager,sourceArtifactId:p.sourceArtifactId,baseArtifactId:p.currentArtifactId,draftCheckCommand:fH(p,r),sourceSnapshot:l,messages:xH(p),providerThreadId:p.providerThreadId});p.providerThreadId=C.providerThreadId??p.providerThreadId,Ws(e,p,C)}catch(v){throw bH(p,v),Ja(p,r,"Hunsu draft route failed"),Ws(e,p),v}}return t.message?.trim()?dH(p.draftSessionId,{message:t.message},e,r):{draft:p,board:n}}async function dH(t,e,r,n){let i=pP(r,t,n),o=e.message?.trim();if(!o)throw new Error("HUNSU Draft message cannot be empty");let s=new Date().toISOString();bL(i,"user",o,s),Ws(r,i);let a=rr(r,n),c=yH(a,i),u=a.requests.find(d=>d.id===c.line.requestId)??a.requests[0];try{let d=`hunsu-draft:${i.draftSessionId}`;await lH(i,n);let l=await uH(i.manager,n,i.aliases),f=await vfe(n.runner,d,r,i,()=>n.runner.runHunsuDraftTurn({runId:d,repositoryPath:SH(i,n),requestGoal:String(u?.goal??"No Roadmap request goal is available."),activeDestinations:Du(a,i.sourceLineId).filter(Qa),selectedDestinationIds:yU(c.node.destinations),harness:c.node.harness,board:a,resolvedModelSelection:l?.provider,draftSessionId:i.draftSessionId,manager:i.manager,sourceArtifactId:i.sourceArtifactId,baseArtifactId:i.currentArtifactId,draftCheckCommand:fH(i,n),sourceSnapshot:vH(c),messages:xH(i),userMessage:o,providerThreadId:i.providerThreadId}));i.providerThreadId=f.providerThreadId??i.providerThreadId;let p=f.finalResponse?.trim();p&&bL(i,"draft-agent",p,new Date().toISOString());let g=i.latestDiffArtifactId?i.diffArtifacts[i.latestDiffArtifactId]:void 0,v=!!(g&&p&&p.includes(`diffArtifactId="${g.diffArtifactId}"`));return(!g||!v||g.status!=="pass")&&(i.status=i.status==="failed"||i.status==="ready"?"draft":i.status,i.readyDraft=void 0),i.error=void 0,i.updatedAt=new Date().toISOString(),Ws(r,i,f),Ja(i,n,"Hunsu draft route message",n0),{draft:i,board:rr(r,n)}}catch(d){throw bH(i,d),Ja(i,n,"Hunsu draft route failed"),Ws(r,i),d}}async function Vue(t,e,r,n){let i=pP(r,t,n),o=e.diffArtifactId?.trim();if(!o)throw new Error("Confirm HUNSU requires a DiffArtifact id");let s=i.diffArtifacts[o];if(!s)throw new Error(`Unknown HUNSU Draft DiffArtifact: ${o}`);if(s.status!=="pass"||!s.readyDraft)throw new Error(s.failedReason??`HUNSU Draft DiffArtifact ${o} is not ready for approval`);if(pH(i)!==s.draftSurfaceHash)throw new Error("HUNSU Draft request files changed after this DiffArtifact was created. Ask the Draft agent to check the request files again.");let c=Gue(s.readyDraft,e.teamName,rr(r,n)),u={type:"ConfirmHunsuDraft",draft:c,actor:"DIRECTOR",at:new Date().toISOString()},d=n.persist?await yb(u,{cwd:n.cwd,commitMessage:`Hunsu intervention ${c.hunsuId}`}):await xl(u,r,{cwd:n.cwd,persist:!1});n.persist&&(r.events=Bn(n.cwd).events),s.readyDraft=c,i.readyDraft=c,i.latestDiffArtifactId=s.diffArtifactId,i.status="confirmed",i.updatedAt=new Date().toISOString();let l=d.board.hunsus.find(f=>String(f.id)===String(c.hunsuId));return l&&(i.confirmedHunsuId=String(l.id),i.confirmedNodeId=String(l.toNodeId)),Ja(i,n,`Hunsu draft route confirmed ${c.hunsuId}`),Ws(r,i),{draft:i,board:d.board,acceptedEvents:d.acceptedEvents,hunsu:l}}function Gue(t,e,r){let n=e?.trim();if(e!==void 0&&!n)throw new Error("teamName must be a non-empty string");let i=n?jt(un(n)):t.newTeamName;if(r.lines.some(o=>o.teamName===i))throw new Error(`Team name is already used: ${i}`);return{...t,newTeamName:i,teamSnapshot:{...t.teamSnapshot,teamName:i}}}async function zue(t,e,r){let n=pP(e,t,r),i=rr(e,r),o=yH(i,n),s=new Date().toISOString(),a=pH(n),c=rde(n,o.node,Bn(r.cwd).runtime,s),u=c.changes;if(!u.ok){n.readyDraft=void 0,n.status=n.status==="failed"||n.status==="ready"?"draft":n.status,n.error=u.errors[0];let g=NC(n,{status:"failed",summary:u.summary,files:u.files,errors:u.errors,failedReason:u.errors[0],checkedAt:s,draftSurfaceHash:a});return n.updatedAt=s,Ja(n,r,"Hunsu draft route diff artifact failed",n0),Ws(e,n),{draft:n,board:i,diffArtifact:tw(g)}}if(!c.validation)throw new Error("HUNSU Draft DiffArtifact succeeded without a validated runtime bundle");let d=Ade(n,u,i,o,c.validation,n.providerThreadId,s),l={type:"ConfirmHunsuDraft",draft:d,actor:"DIRECTOR",at:s},f=Kue(YC(e,r),l);if(!f.ok){n.readyDraft=void 0,n.status=n.status==="ready"?"draft":n.status,n.error=f.error;let g=NC(n,{status:"failed",summary:u.summary,files:u.files,errors:[f.error],failedReason:f.error,checkedAt:s,draftSurfaceHash:a});return n.updatedAt=s,Ja(n,r,"Hunsu draft route diff artifact failed",n0),Ws(e,n),{draft:n,board:i,diffArtifact:tw(g)}}n.readyDraft=d,n.status="ready",n.error=void 0;let p=NC(n,{status:"pass",summary:u.summary,files:u.files,errors:[],checkedAt:s,draftSurfaceHash:a,readyDraft:d});return n.updatedAt=s,Ja(n,r,"Hunsu draft route diff artifact created",n0),Ws(e,n),{draft:n,board:i,diffArtifact:tw(p)}}function Kue(t,e){let r=bg(t,e);if(!r.ok)return{ok:!1,error:r.error.message};let n=uu(r.value);return n.ok?{ok:!0,board:n.value}:{ok:!1,error:n.error.message}}function Jue(t,e,r){if(!t.worktree||t.worktree.baseRef==="virtual")return;let n=mH(r,e),i=nM(n);for(let o of d0)gL(at(t.worktree.path,vp,o),i[o]),gL(at(t.worktree.path,yl,o),i[o])}async function lH(t,e){if(!t.worktree||t.worktree.baseRef==="virtual")return;let r=Vn("Prepare HUNSU Draft Manager resources.");r.members=[Ii(String(t.manager.id),t.manager.promptTemplate.template,t.manager.skills,{kind:"worktree_write",network:"enabled"},{policy:"never"},t.manager.plugins)],await p0(t.worktree.path,r,{phase:"member",executorId:String(t.manager.id),apmSkillRegistryClient:e.apmSkillRegistryClient})}function gL(t,e){bo(Ci(t),{recursive:!0}),es(t,`${JSON.stringify(e,null,2)}
220
+ `,"utf8")}function fH(t,e){let r=`${e.bridgeApiBaseUrl}/api/roadmaps/${encodeURIComponent(e.roadmapId)}/hunsu/drafts/${encodeURIComponent(t.draftSessionId)}/diff-artifacts?response=${ZL}`,n={"content-type":"application/json"};e.bridgeApiAuthToken&&(n.authorization=`Bearer ${e.bridgeApiAuthToken}`);let i=[`const url = ${JSON.stringify(r)};`,`const headers = ${JSON.stringify(n)};`,'const response = await fetch(url, { method: "POST", headers, body: "{}" });',"const text = await response.text();","console.log(text);","if (!response.ok) process.exit(1);"].join(" ");return`node --input-type=module -e ${Xue(i)}`}function Xue(t){return`'${t.replaceAll("'","'\\''")}'`}function NC(t,e){let r=Yue(t.draftSessionId,e),n={diffArtifactId:r,draftSessionId:t.draftSessionId,...e};return t.diffArtifacts[r]=n,t.latestDiffArtifactId=r,n}function Yue(t,e){return`hdd_${ui(ci("sha256").update(xp({draftSessionId:t,status:e.status,summary:e.summary,files:e.files,errors:e.errors,failedReason:e.failedReason,checkedAt:e.checkedAt,draftSurfaceHash:e.draftSurfaceHash}))).slice(0,16)}`}function tw(t){if(t)return{diffArtifactId:t.diffArtifactId,draftSessionId:t.draftSessionId,status:t.status,newTeamName:t.readyDraft?String(t.readyDraft.newTeamName):void 0,files:t.files.map(tde),errors:t.errors,failedReason:t.failedReason,checkedAt:t.checkedAt,draftSurfaceHash:t.draftSurfaceHash}}function Que(t){return new URL(t.url??"/","http://localhost").searchParams.get("response")===ZL}function Zue(t){let e={draftSessionId:t.draftSessionId,diffArtifactId:t.diffArtifactId,marker:ede(t),checkedAt:t.checkedAt};return t.status==="pass"?{...e,status:"pass",changedFiles:t.files.map(r=>({path:r.path,kind:r.kind}))}:{...e,status:"failed",failedReason:t.failedReason??t.errors[0]??"HUNSU Draft DiffArtifact failed.",errors:t.errors}}function ede(t){return`::hunsu-diff{draftSessionId="${t.draftSessionId}" diffArtifactId="${t.diffArtifactId}" status="${t.status}"}`}function tde(t){return{path:t.path,kind:t.kind,diff:t.diff}}function pH(t){let e=ci("sha256");if(e.update(`draft:${t.draftSessionId}
221
+ `),!t.worktree||t.worktree.baseRef==="virtual")return e.update(`worktree:virtual-or-missing
222
+ `),ui(e);for(let r of[vp,yl])for(let n of d0){let i=at(t.worktree.path,r,n);e.update(`${r}/${n}\0`),e.update(Qt(i)?Vs(i,"utf8"):"<missing>"),e.update("\0")}return ui(e)}function rde(t,e,r,n){let i={draftSessionId:t.draftSessionId,sourceNodeId:t.sourceNodeId,requestDir:yl,previousDir:vp,checkedAt:n};if(!t.worktree||t.worktree.baseRef==="virtual")return{changes:{...i,ok:!1,summary:"HUNSU Draft changes require a route worktree.",errors:["HUNSU Draft changes require a persisted route worktree."],files:[]}};let o=mH(r,e),s=yA(t.worktree.path,vp),a=yA(t.worktree.path,yl),c=[...s.ok?[]:[s.error.message],...a.ok?[]:[a.error.message]];if(c.length>0||!s.ok||!a.ok)return{changes:{...i,ok:!1,summary:"HUNSU Draft runtime files have validation errors.",errors:c,files:[]}};let u=iM(s.value,a.value,o);if(!u.ok)return{changes:{...i,ok:!1,summary:"HUNSU Draft runtime files have validation errors.",errors:[u.error.message],files:[]}};let d=nde(u.value.previous,u.value.request);return d.length===0?{changes:{...i,ok:!1,summary:"No runtime file changes detected.",errors:["No runtime file changes detected in .hunsu-request."],files:[]},validation:u.value}:{changes:{...i,ok:!0,summary:ode(d),errors:[],files:d},validation:u.value}}function mH(t,e){let r=go(e.harnessGraph),n=new Map(t.resources.bindings.map(i=>[i.destinationId,i]));return{...Ir(t),destinations:{schema:"hunsu.destinations.v1",order:"queue-head-is-current",destinations:e.destinations.map(i=>Ir(i)),compatibility:{events:t.eventLog.events.map(i=>Ir(i)),updatedAt:t.eventLog.updatedAt}},harness:{schema:"hunsu.harness.v1",origins:t.harness.origins?.map(i=>Ir(i)),harness:{name:t.harness.harness.name,rootTeamId:r.rootTeamId,guardrails:r.guardrails.map(i=>Ir(i)),lock:e.harnessLock?Ir(e.harnessLock):Ir(t.harness.harness.lock)}},executors:{schema:"hunsu.executors.v1",executors:r.executors.map(i=>Ir(i))},resources:{schema:"hunsu.resources.v1",resources:r.resources.map(i=>Ir(i)),bindings:e.destinations.map(i=>{let o=n.get(String(i.id));return{destinationId:String(i.id),executorPackageBindings:e.executorPackageBindings?.map(s=>Ir(s))??Ir(o?.executorPackageBindings),resourcePackageBindings:e.resourcePackageBindings?.map(s=>Ir(s))??Ir(o?.resourcePackageBindings)}})},artifactActions:{schema:"hunsu.artifact-actions.v1",order:"display-order",actions:e.artifactActions.map(i=>Ir(i)).sort((i,o)=>i.displayOrder-o.displayOrder||String(i.id).localeCompare(String(o.id)))}}}function nde(t,e){let r=[];for(let n of d0){let i=yL(t,n),o=yL(e,n);xp(i)!==xp(o)&&r.push({path:`${yl}/${n}`,kind:"updated",summary:ide(n,i,o),diff:sde(n,i,o)})}return r}function yL(t,e){switch(e){case"destinations.json":return t.destinations;case"harness.json":return t.harness;case"executors.json":return t.executors;case"resources.json":return t.resources;case"artifact-actions.json":return t.artifactActions}}function ide(t,e,r){switch(t){case"destinations.json":return vL("Destinations",e.destinations??[],r.destinations??[]);case"artifact-actions.json":return vL("Artifact Actions",e.actions??[],r.actions??[]);case"harness.json":return"Harness runtime changed.";case"executors.json":return"Executors runtime changed.";case"resources.json":return"Resources runtime changed."}}function vL(t,e,r){let n=new Set(e.map(u=>String(u.id))),i=new Set(r.map(u=>String(u.id))),o=[...i].filter(u=>!n.has(u)).length,s=[...n].filter(u=>!i.has(u)).length,a=r.filter(u=>n.has(String(u.id))).length===e.filter(u=>i.has(String(u.id))).length?r.filter(u=>n.has(String(u.id))).length:0,c=[o?`${o} added`:void 0,s?`${s} removed`:void 0,!o&&!s&&a?"content updated":void 0].filter(Boolean);return c.length>0?`${t} ${c.join(", ")}.`:`${t} changed.`}function ode(t){return t.length===1?t[0].summary:`${t.length} runtime files changed: ${t.map(e=>ts(e.path)).join(", ")}.`}function sde(t,e,r){let n=`${vp}/${t}`,i=`${yl}/${t}`,o=SL(xL(e)),s=SL(xL(r)),a=ade(o,s),c=cde(a);return[`diff --git a/${n} b/${i}`,`--- a/${n}`,`+++ b/${i}`,...c.flatMap(u=>[`@@ -${u.oldStart},${u.oldCount} +${u.newStart},${u.newCount} @@`,...u.lines.map(d=>`${ude(d)}${d.text}`)])].join(`
223
+ `)}function xL(t){return`${JSON.stringify(t,null,2)}
224
+ `}function SL(t){let e=t.endsWith(`
225
+ `)?t.slice(0,-1):t;return e.length===0?[]:e.split(`
226
+ `)}function ade(t,e){let r=Array.from({length:t.length+1},()=>Array(e.length+1).fill(0));for(let c=t.length-1;c>=0;c-=1)for(let u=e.length-1;u>=0;u-=1)r[c][u]=t[c]===e[u]?r[c+1][u+1]+1:Math.max(r[c+1][u],r[c][u+1]);let n=[],i=0,o=0;for(;i<t.length||o<e.length;)i<t.length&&o<e.length&&t[i]===e[o]?(n.push({kind:"same",text:t[i]}),i+=1,o+=1):i<t.length&&(o>=e.length||r[i+1][o]>=r[i][o+1])?(n.push({kind:"remove",text:t[i]}),i+=1):o<e.length&&(n.push({kind:"add",text:e[o]}),o+=1);let s=1,a=1;return n.map(c=>c.kind==="same"?{kind:"same",text:c.text,oldLine:s++,newLine:a++}:c.kind==="remove"?{kind:"remove",text:c.text,oldLine:s++}:{kind:"add",text:c.text,newLine:a++})}function cde(t,e=3){let r=[];for(let[n,i]of t.entries()){if(i.kind==="same")continue;let o=Math.max(0,n-e),s=Math.min(t.length-1,n+e),a=r.at(-1);a&&o<=a.end+1?a.end=Math.max(a.end,s):r.push({start:o,end:s})}return r.map(n=>{let i=t.slice(n.start,n.end+1),o=i.flatMap(u=>"oldLine"in u?[u.oldLine]:[]),s=i.flatMap(u=>"newLine"in u?[u.newLine]:[]),a=i.filter(u=>u.kind!=="add").length,c=i.filter(u=>u.kind!=="remove").length;return{oldStart:o[0]??0,oldCount:a,newStart:s[0]??0,newCount:c,lines:i}})}function ude(t){return t.kind==="add"?"+":t.kind==="remove"?"-":" "}function Ir(t){return t===void 0?t:JSON.parse(JSON.stringify(t))}async function dde(t,e,r){let n=hH(e,t,r);return n.status="discarded",n.updatedAt=new Date().toISOString(),Ja(n,r,"Hunsu draft route discarded"),Ws(e,n),{draft:n,board:rr(e,r)}}function lde(t,e){return fP(t,e.cwd),Object.values(t.hunsuDrafts).filter(r=>r.repositoryPath===e.cwd&&(!r.roadmapId||r.roadmapId===e.roadmapId)).sort((r,n)=>n.updatedAt.localeCompare(r.updatedAt))}function VC(t,e,r){fP(t,r.cwd);let n=t.hunsuDrafts[e];if(!(!n||n.repositoryPath!==r.cwd)&&!(n.roadmapId&&n.roadmapId!==r.roadmapId))return n}function fP(t,e){if(!Qt(e))return;let r;try{r=qt(e)}catch(i){if(i instanceof Dr)return;throw i}let n="";try{n=Re(["for-each-ref","--format=%(refname)","refs/heads/hunsu/routes"],{cwd:r})}catch(i){if(i instanceof Dr)return;throw i}for(let i of n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean)){let o;try{o=Re(["show",`${i}:${_g}`],{cwd:r})}catch(c){if(c instanceof Dr)continue;throw c}let s=rM(o,`${i}:${_g}`);if(!s.ok||s.value.schema!=="hunsu.hunsu-draft-route.v1"||s.value.repositoryPath!==r)continue;let a=t.hunsuDrafts[s.value.draftSessionId];a&&a.updatedAt>=s.value.updatedAt||(t.hunsuDrafts[s.value.draftSessionId]=vde(s.value))}}function hH(t,e,r){let n=VC(t,e,r);if(!n)throw new Error(`Unknown HUNSU Draft: ${e}`);return n}function pP(t,e,r){let n=hH(t,e,r);if(n.status==="confirmed"||n.status==="discarded")throw new Error(`HUNSU Draft ${e} is already ${n.status}`);return n}function gH(t,e){let r=e.sourceMoveId?t.moves.find(c=>String(c.id)===e.sourceMoveId):void 0,n=e.sourceNodeId?t.nodes.find(c=>String(c.id)===e.sourceNodeId):r?t.nodes.find(c=>String(c.id)===String(r.toNodeId)):void 0,i=e.sourceLineId?t.lines.find(c=>String(c.id)===e.sourceLineId):t.lines.find(c=>c.status==="active")??t.lines[0],o=n??(i?t.nodes.find(c=>String(c.id)===String(i.currentNodeId)):void 0)??t.nodes[0];if(!o)throw new Error("Cannot start HUNSU Draft without a source node");let s=e.sourceLineId?t.lines.find(c=>String(c.id)===e.sourceLineId):epe(t,o)??i;if(!s)throw new Error(`Cannot resolve route for HUNSU Draft source node ${o.id}`);let a=r??PP(t,o);return{line:s,node:o,move:a}}function yH(t,e){return gH(t,{sourceLineId:e.sourceLineId,sourceNodeId:e.sourceNodeId,sourceMoveId:e.sourceMoveId})}function vH(t){return{sourceLineId:String(t.line.id),sourceNodeId:String(t.node.id),sourceMoveId:t.move?String(t.move.id):void 0,moveOrdinal:t.move?.ordinal??t.node.ordinal,teamName:String(t.line.teamName??t.node.teamName??""),summary:String(t.move?.summary??"Initial immutable Team Snapshot"),destinationSummaries:t.node.destinations.map(e=>({id:String(e.id),title:String(e.title),status:String(e.status)}))}}function fde(t,e,r){let n=t.requests.find(i=>i.id===e.line.requestId);return{kind:"source-protocol",request:n?{id:String(n.id),title:String(n.title),goal:String(n.goal)}:void 0,source:r,team:{lineId:String(e.line.id),teamName:String(e.line.teamName??e.node.teamName??r.teamName??""),currentNodeId:String(e.line.currentNodeId),moveOrdinal:r.moveOrdinal},destinations:e.node.destinations,harness:e.node.harness}}function pde(t,e){let r=mde(e.kind,e.value),n={...e,artifactId:r};return t.hunsuDraftArtifacts[r]=n,n}function mde(t,e){return`hda_${ui(ci("sha256").update(xp({kind:t,value:e}))).slice(0,16)}`}function xp(t){if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(xp).join(",")}]`;let e=t;return`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${xp(e[r])}`).join(",")}}`}function xH(t){return t.messages.map(e=>({role:e.role,text:e.text,createdAt:e.createdAt}))}function bL(t,e,r,n=new Date().toISOString()){t.messages.push({messageId:`${t.draftSessionId}:msg:${String(t.messages.length+1).padStart(4,"0")}`,role:e,text:r,createdAt:n}),t.updatedAt=n}function hde(t){return`hunsu-draft:${t}`}function SH(t,e){return t.worktree?.path??e.cwd}function gde(t){return{kind:"Route",routeKind:"HunsuDraft",routeId:t.routeId,draftSessionId:t.draftSessionId,sourceLineId:t.sourceLineId,sourceNodeId:t.sourceNodeId,targetNodeId:t.confirmedNodeId,worktree:t.worktree}}function yde(t){return{schema:"hunsu.hunsu-draft-route.v1",draftSessionId:t.draftSessionId,roadmapId:t.roadmapId,repositoryPath:t.repositoryPath,routeId:t.routeId,sourceLineId:t.sourceLineId,sourceNodeId:t.sourceNodeId,sourceMoveId:t.sourceMoveId,sourceArtifactId:t.sourceArtifactId,currentArtifactId:t.currentArtifactId,managerLock:t.managerLock,manager:t.manager,aliases:t.aliases,confirmedHunsuId:t.confirmedHunsuId,confirmedNodeId:t.confirmedNodeId,status:t.status,readyDraft:t.readyDraft,latestDiffArtifactId:t.latestDiffArtifactId,diffArtifacts:t.diffArtifacts,worktree:t.worktree,updatedAt:t.updatedAt}}function vde(t){return{draftSessionId:t.draftSessionId,roadmapId:t.roadmapId,repositoryPath:t.repositoryPath,sourceLineId:t.sourceLineId,sourceNodeId:t.sourceNodeId,sourceMoveId:t.sourceMoveId,routeId:t.routeId,worktree:t.worktree,agentSessionIds:[],sourceArtifactId:t.sourceArtifactId,currentArtifactId:t.currentArtifactId,managerLock:t.managerLock,manager:cH(t.manager),aliases:t.aliases,confirmedHunsuId:t.confirmedHunsuId,confirmedNodeId:t.confirmedNodeId,messages:[],readyDraft:t.readyDraft,latestDiffArtifactId:t.latestDiffArtifactId,diffArtifacts:t.diffArtifacts??{},status:t.status,createdAt:t.updatedAt,updatedAt:t.updatedAt}}function Ja(t,e,r,n=[]){if(!e.persist||!t.worktree||t.worktree.baseRef==="virtual")return;let i=at(t.worktree.path,_g);bo(Ci(i),{recursive:!0}),es(i,yo(yde(t)).text,"utf8"),xde(t.worktree.path,r,[...n,_g])}function xde(t,e,r){let n=r.filter(o=>Qt(at(t,o))||$H(t,o));if(!(n.length===0||(Re(["add","--all","--",...n],{cwd:t}),!Re(["status","--porcelain=v1","--",...n],{cwd:t}).trim())))return Re(["commit","--only","-m",e,"--",...n],{cwd:t}),Re(["rev-parse","--verify","HEAD"],{cwd:t}).trim()}function mP(t,e,r=new Date().toISOString()){let n={kind:"HunsuDraft",draftSessionId:e.draftSessionId},i=qH(n),o=t.agentSessions[i];if(o)return e.draftAgentSessionId=o.sessionId,e.activeAgentSessionId=o.sessionId,e.agentSessionIds.includes(o.sessionId)||e.agentSessionIds.push(o.sessionId),o;let s={sessionId:i,roadmapId:e.roadmapId,routeRef:gde(e),owner:n,state:{type:"waiting",reason:"Waiting for HUNSU Draft message"},messages:[],activeItemIds:[],revision:1,createdAt:r,updatedAt:r};return t.agentSessions[s.sessionId]=s,e.draftAgentSessionId=s.sessionId,e.activeAgentSessionId=s.sessionId,e.agentSessionIds.push(s.sessionId),Gs(t,s),s}function Ws(t,e,r){let n=e.draftAgentSessionId?t.agentSessions[e.draftAgentSessionId]:mP(t,e);if(!n)return;let i=e.updatedAt;r?.providerThreadId&&r.providerTurnId?n.provider={providerThreadId:r.providerThreadId,providerTurnId:r.providerTurnId}:e.providerThreadId&&!n.provider&&(n.provider={providerThreadId:e.providerThreadId,providerTurnId:"draft"});let o=bde(n,e);n.error=e.error,n.finalResponse=e.messages.at(-1)?.text,n.state=Sde(e,n.provider),Xa(n,i),Gs(t,n);for(let s of o)pfe(t,n,s)}function Sde(t,e){return t.status==="failed"?{type:"failed",provider:e,error:t.error??"HUNSU Draft failed",completedAt:t.updatedAt}:t.status==="confirmed"||t.status==="discarded"?{type:"completed",provider:e,finalResponse:t.messages.at(-1)?.text,completedAt:t.updatedAt}:{type:"waiting",reason:t.status==="ready"?"Waiting for approval":"Waiting for HUNSU Draft message"}}function bde(t,e){let r=new Map(t.messages.map(i=>[i.itemId,i])),n=[];for(let i of e.messages){if(r.has(i.messageId))continue;let o=wde(t.sessionId,i);t.messages.push(o),n.push(o)}return n}function wde(t,e){return{sessionId:t,messageId:e.messageId,itemId:e.messageId,role:e.role==="user"?"user":e.role==="system"?"system":"assistant",type:`hunsuDraft.${e.role}`,status:"completed",title:e.role==="user"?"Prompt":"Reply",text:e.text,revision:1,createdAt:e.createdAt,updatedAt:e.createdAt,completedAt:e.createdAt}}function bH(t,e){t.status="failed",t.error=e instanceof Error?e.message:String(e),t.updatedAt=new Date().toISOString()}function Ide(t,e,r){if(e.kind!=="registry-package"||e.registryKind!=="apm")throw new Error(`APM resolver returned unsupported metadata for ${r}`);if(e.name!==t.name||e.registry!==t.registry||e.package!==t.package||e.version!==t.version)throw new Error(`APM resolver returned a different skill lock for ${t.package}@${t.version}`);if(!e.integrity.trim()||!e.contentHash.trim())throw new Error(`APM resolver returned an incomplete skill lock for ${t.package}@${t.version}`);if(!Rde(e.version))throw new Error(`APM resolver returned a non-exact version for ${t.package}: ${e.version}`)}function Ede(t=fetch){return{async resolveSkill(e){let r=new URL("/v1/skills/resolve",e.registry);r.searchParams.set("package",e.package),r.searchParams.set("version",e.version);let n=await t(r);if(!n.ok)throw new Error(`APM registry failed to resolve ${e.package}@${e.version}: HTTP ${n.status}`);let i=await n.json(),o=GC(i,"APM resolve response"),s={kind:"registry-package",registryKind:"apm",name:ml(typeof o.name=="string"&&o.name.trim()?o.name:e.name,"APM resolve response.name"),registry:ml(typeof o.registry=="string"&&o.registry.trim()?o.registry:e.registry,"APM resolve response.registry"),package:ml(o.package,"APM resolve response.package"),version:ml(o.version,"APM resolve response.version"),integrity:ml(o.integrity,"APM resolve response.integrity"),contentHash:ml(o.contentHash,"APM resolve response.contentHash")};return Ide(e,s,"APM resolve response"),s},async fetchSkillFiles(e){let r=new URL("/v1/skills/files",e.registry);r.searchParams.set("package",e.package),r.searchParams.set("version",e.version);let n=await t(r);if(!n.ok)throw new Error(`APM registry failed to fetch ${e.package}@${e.version}: HTTP ${n.status}`);let i=await n.json(),o=GC(i,"APM files response");if(o.integrity!==void 0&&o.integrity!==e.integrity)throw new Error(`APM integrity mismatch for ${e.package}@${e.version}`);if(o.contentHash!==void 0&&o.contentHash!==e.contentHash)throw new Error(`APM contentHash mismatch for ${e.package}@${e.version}`);let s=kde(o.files,"APM files response.files");if(e.contentHash.startsWith("sha256:")&&wH(s)!==e.contentHash)throw new Error(`APM contentHash mismatch for ${e.package}@${e.version}`);return s}}}function ml(t,e){if(typeof t!="string"||!t.trim())throw new Error(`${e} must be a non-empty string`);return jt(Ee(t.trim(),e))}function GC(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function kde(t,e){if(!Array.isArray(t)||t.length===0)throw new Error(`${e} must be a non-empty array`);return t.map((r,n)=>{let i=GC(r,`${e}[${n}]`);return{path:ml(i.path,`${e}[${n}].path`),text:typeof i.text=="string"?i.text:(()=>{throw new Error(`${e}[${n}].text must be a string`)})()}})}function wH(t){let e=ci("sha256");for(let r of t)e.update(r.path),e.update("\0"),e.update(r.text),e.update("\0");return`sha256:${e.digest("hex")}`}function Rde(t){return/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(t)}function Ade(t,e,r,n,i,o,s){let a=_de(r),c=jt(lr(`${t.sourceLineId}/fork-${a}`)),u=Ms(r);return{id:jt(eg(t.draftSessionId)),status:"ready",sourceLineId:jt(lr(t.sourceLineId)),sourceNodeId:jt(Zr(t.sourceNodeId)),sourceMoveId:t.sourceMoveId?jt(_n(t.sourceMoveId)):void 0,target:{type:"node",id:jt(Zr(t.sourceNodeId))},newTeamName:u,summary:jt(qo(e.summary,"summary")),teamSnapshot:Cde(i.requestRuntime,n.node,u),changedFiles:e.files.map(d=>({path:jt(Ee(d.path,"changedFile.path")),kind:d.kind,summary:jt(qo(d.summary,"changedFile.summary"))})),hunsuId:a,newLineId:c,conversationRef:{provider:"codex",threadId:o?jt(Ee(o,"conversation.threadId")):void 0,conversationHash:jt(tg(fU({draftSessionId:t.draftSessionId,sourceLineId:t.sourceLineId,sourceNodeId:t.sourceNodeId,at:s}))),contextHash:jt(Ee(pU(r,n.node,t.draftSessionId),"conversation.contextHash")),worktreeHash:jt(zd(tpe(t.repositoryPath))),startedAt:t.createdAt,endedAt:s},createdAt:t.createdAt,updatedAt:s}}function Cde(t,e,r){let n=t.resources.bindings.find(s=>e.destinations.some(a=>String(a.id)===s.destinationId)),i={rootTeamId:t.harness.harness.rootTeamId,executors:t.executors.executors.map(s=>Ir(s)),resources:t.resources.resources.map(s=>Ir(s)),guardrails:(t.harness.harness.guardrails??[]).map(s=>Ir(s)),artifactActions:t.artifactActions.actions.map(s=>Ir(s))},o=ou(i);return{teamName:r,moveOrdinal:e.ordinal,destinations:t.destinations.destinations.map(s=>Ir(s)),harness:o,harnessGraph:i,harnessLock:t.harness.harness.lock?Ir(t.harness.harness.lock):void 0,executorPackageBindings:n?.executorPackageBindings?.map(s=>Ir(s))??e.executorPackageBindings?.map(s=>Ir(s)),resourcePackageBindings:n?.resourcePackageBindings?.map(s=>Ir(s))??e.resourcePackageBindings?.map(s=>Ir(s)),artifactActions:t.artifactActions.actions.map(s=>Ir(s))}}function Pde(t){let e=Object.keys(t.hunsuDrafts).reduce((r,n)=>{let i=n.match(/^hd(\d+)$/i);return i?Math.max(r,Number(i[1])):r},0);return`hd${String(e+1).padStart(4,"0")}`}function _de(t){let e=t.hunsus.reduce((r,n)=>{let i=String(n.id).match(/^H(\d+)$/i);return i?Math.max(r,Number(i[1])):r},0);return jt(Vo(`H${String(e+1).padStart(4,"0")}`))}async function wL(t,e,r,n){let i=Tde(t),o=i.split("/").filter(Boolean);if(e.method==="GET"&&o.length===1&&o[0]==="artifact-actions")return At(r,200,{actions:xM(n.cwd)}),!0;if(e.method==="GET"&&o.length===1&&o[0]==="action-runs")return At(r,200,{runs:bM(n.cwd)}),!0;let s=Nde(i);if(!s)return!1;if(s.resource==="action"&&s.action==="run"&&e.method==="POST"){let a=await Qi(e),c={...a,actionId:a.actionId??s.actionId};return a.dryRun?(At(r,200,{plan:Dde(c,n)}),!0):(At(r,202,{run:Bde(c,n)}),!0)}return s.resource==="run"&&s.action==="proxy"?(await Ode(e,r,n.cwd,s.runId,s.alias,s.path),!0):s.resource==="run"&&e.method==="GET"&&s.action==="show"?(At(r,200,{run:Mg(n.cwd,s.runId)}),!0):s.resource==="run"&&e.method==="POST"&&s.action==="stop"?(At(r,202,{run:wM(n.cwd,s.runId,{runner:n.actionRunner,processEnv:n.processEnv})}),!0):!1}function Tde(t){let e=t.split("/").filter(Boolean),r=e[0]==="api"?1:0,n=e.findIndex((i,o)=>o>=r&&(i==="artifact-actions"||i==="action-runs"));return n>=0?`/${e.slice(n).join("/")}`:t}function Dde(t,e){return PA(IH(t,e))}function Bde(t,e){return SM(IH(t,e),{runner:e.actionRunner,processEnv:e.processEnv})}function IH(t,e){if(!t.actionId)throw new Error("Artifact Action run requires actionId");return{cwd:e.cwd,roadmapId:e.roadmapId,actionId:t.actionId,moveId:t.moveId,commit:t.commit,env:t.env,ambientEnv:e.ambientEnv,processEnv:e.processEnv,worktreeRoot:e.worktreeRoot}}function Nde(t){if(!t.startsWith("/"))return;let e=t.slice(1).split("/");if(e[0]==="artifact-actions"&&e[1]&&e[2]==="runs"&&e.length===3)return{resource:"action",actionId:decodeURIComponent(e[1]),action:"run"};if(e[0]==="action-runs"&&e[1]){let r=decodeURIComponent(e[1]);if(e.length===2||e[2]==="")return{resource:"run",runId:r,action:"show"};if(e[2]==="stop"&&e.length===3)return{resource:"run",runId:r,action:"stop"};if(e[2]==="proxy"&&e[3])return{resource:"run",runId:r,action:"proxy",alias:decodeURIComponent(e[3]),path:`/${e.slice(4).map(n=>decodeURIComponent(n)).join("/")}`}}}async function Ode(t,e,r,n,i,o){let a=Mg(r,n).aliases?.[i];if(!a){At(e,404,{error:`Unknown Artifact Action alias: ${i}`});return}if(!a.directUrl){At(e,503,{error:`Artifact Action alias has no direct URL yet: ${i}`});return}let c=new URL(t.url??"/","http://localhost"),u=new URL(a.directUrl),d=u.pathname.replace(/\/$/,""),l=o==="/"?"/":`/${o.replace(/^\/+/,"")}`;u.pathname=`${d}${l}`.replace(/\/{2,}/g,"/"),u.search=c.search;let f=t.method==="GET"||t.method==="HEAD"?void 0:await Mde(t),p=await fetch(u,{method:t.method,headers:Lde(t),body:f?new Uint8Array(f):void 0});e.statusCode=p.status;for(let[g,v]of p.headers)Ude(g)||e.setHeader(g,v);e.end(Buffer.from(await p.arrayBuffer()))}async function Mde(t){let e=[];for await(let r of t)e.push(Buffer.isBuffer(r)?r:Buffer.from(r));return Buffer.concat(e)}function Lde(t){let e=new Headers;for(let[r,n]of Object.entries(t.headers))n===void 0||Hde(r)||e.set(r,Array.isArray(n)?n.join(", "):n);return e}function Hde(t){return["host","connection","content-length","transfer-encoding","upgrade"].includes(t.toLowerCase())}function Ude(t){return["connection","content-encoding","content-length","transfer-encoding","upgrade"].includes(t.toLowerCase())}function EH(t){if(t.length===0)return cu();let e=uu(t);if(!e.ok)throw new Error(e.error.message);return e.value}function $de(t,e,r={}){let n=r.cwd?o=>{if(!(o.type==="run.updated"&&!a0(o.run,r.cwd))){if(o.type==="runs.snapshot"){let s=o.runs.filter(a=>a0(a,r.cwd)).map(Ai);e({type:"runs.snapshot",runs:s,executes:s.map(Zi)});return}if(o.type==="run.updated"){let s=Ai(o.run);e({type:"run.updated",run:s,execute:Zi(s),board:o.board});return}e(o)}}:e;t.liveSubscribers.add(n);let i=(r.cwd?wp(t,r.cwd):Object.values(t.runs)).map(Ai);return e({type:"runs.snapshot",runs:i,executes:i.map(Zi)}),()=>{t.liveSubscribers.delete(n)}}function Fde(t,e,r={}){let n=r.cwd||r.roadmapId||r.sessionId?o=>{if(o.type==="agentSession.snapshot"){e({type:"agentSession.snapshot",sessions:o.sessions.filter(a=>Ip(a,t,r))});return}let s=oP(t,o.sessionId,r);!s||!Hpe(o,s,t,r)||e(o)}:e;t.agentSessionSubscribers.add(n);let i=jde(t,r);return n({type:"agentSession.snapshot",sessions:i}),()=>{t.agentSessionSubscribers.delete(n)}}function jde(t,e){return(e.cwd?iP(t,e.cwd):SU(t)).filter(n=>Ip(n,t,e))}function IL(t){return{...t,roadmap:t,destinations:t.destinations,teams:t.lines,moves:t.moves,hunsus:t.hunsus}}function Zi(t){let e=Ai(t);return{...e,executeId:e.executeId,teamRouteId:e.lineId,selectedDestinationIds:e.selectedDestinationIds,statusLabel:nP(e.status),outcomeLabel:e.outcome==="arrived"?"Arrived":e.outcome==="accident"?"Accident":void 0,memberEvaluations:e.memberEvaluations??[]}}function EL(t,e){return t.artifacts.find(r=>r.id===e)}function Xn(t=process.cwd()){let e=qt(t),r=Re(["status","--porcelain=v1","--branch"],{cwd:e}).split(/\r?\n/).filter(Boolean),n=r.find(o=>o.startsWith("## ")),i=r.filter(o=>!o.startsWith("## ")).map(o=>({status:o.slice(0,2),path:o.slice(3)}));return{root:e,branch:qde(n?n.slice(3):void 0),clean:i.length===0,changes:i}}function qde(t){return t?t.match(/^No commits yet on (.+)$/)?.[1]??t:"unknown"}function kH(t={}){let e=Ep(t).roadmaps.map(r=>RH(r,t));return t.activeOnly===!1?e:e.filter(r=>r.lifecycle==="active")}function vo(t={}){return kH({...t,activeOnly:!1})}function RH(t,e={}){let r=hP({path:t.repositoryPath},e);return r.kind==="missing-roadmap"?{...t,repositoryPath:r.path,health:r.health==="missing-path"?"missing":r.health,lifecycle:r.health==="missing-path"?"missing":"error",type:"missing",primaryAction:r.recommendedAction}:r.kind==="hunsu-roadmap"?{...t,roadmapId:r.roadmapId,displayName:r.displayName,repositoryPath:r.path,health:r.health,kind:"hunsu-roadmap",lifecycle:t.lifecycle==="inactive"?"inactive":r.health==="needs-upgrade"?"needs_upgrade":"active",localAccess:t.localAccess??{enabled:!0},remoteAccess:t.remoteAccess??{enabled:!1,scopes:[]},type:"roadmap",primaryAction:r.health==="ok"||r.health==="git-dirty"?"open":"repair"}:r.kind==="git-project"?{...t,repositoryPath:r.path,lastKnownBranch:r.branch??t.lastKnownBranch,health:"missing-runtime",kind:"git-project",lifecycle:t.lifecycle==="inactive"?"inactive":"error",type:"git-project",primaryAction:"repair"}:{...t,health:r.kind==="unsupported"?"unknown":"missing-runtime",lifecycle:t.lifecycle==="inactive"?"inactive":"error",type:r.kind==="unsupported"?"missing":"roadmap",primaryAction:r.kind==="unsupported"?"remove":"repair"}}function kL(t,e={}){let r=Ep(e),n=t.path?_u(t.path):void 0,i=r.roadmaps.filter(s=>!(t.roadmapId&&s.roadmapId===t.roadmapId||n&&_u(s.repositoryPath)===n)),o=i.length!==r.roadmaps.length;return o&&wP({version:1,roadmaps:i},e),{removed:o,roadmaps:vo(e)}}function OC(t,e,r={}){let n=t.roadmapId?.trim();if(!n)throw new Error("Roadmap id is required.");let i=Ep(r),o=new Date().toISOString(),s,a=i.roadmaps.map(c=>c.roadmapId!==n?c:(s={...c,lifecycle:e,localAccess:{enabled:e==="active"},remoteAccess:e==="active"?c.remoteAccess??{enabled:!1,scopes:[]}:{enabled:!1,scopes:c.remoteAccess?.scopes??[]},lastOpenedAt:e==="active"?o:c.lastOpenedAt},s));if(!s)throw new Error(`Unknown Roadmap: ${n}`);return wP({version:1,roadmaps:a},r),{roadmap:RH(s,r),roadmaps:vo(r)}}function hP(t,e={}){let r=typeof t=="string"?t:t.path??t.cwd;if(!r?.trim())return{kind:"unsupported",path:"",reason:"Choose a folder before Hunsu can inspect it.",recommendedAction:"explain"};let n=Yn(r),i=TH(n,e),o=xo(n);if(!o)return i?{kind:"missing-roadmap",path:n,roadmapId:i.roadmapId,displayName:i.displayName,health:"missing-path",reason:"This Roadmap was registered before, but its last known path is missing.",recommendedAction:"remove"}:ile(n)?{kind:"new-project",path:n,recommendedAction:"create"}:{kind:"unsupported",path:n,reason:"This path is not accessible from the local Bridge.",recommendedAction:"explain"};let s;try{s=Tu(o)}catch(c){return{kind:"unsupported",path:n,reason:c instanceof Error?c.message:"This path could not be inspected.",recommendedAction:"explain"}}if(!s.isDirectory())return{kind:"unsupported",path:o,reason:"Choose a folder, not a file.",recommendedAction:"explain"};let a=rle(o);if(a){let c=cle(a);if(vP(a)||i){let d=RL(a),l=nle(a);return i&&!l?{kind:"missing-roadmap",path:a,roadmapId:i.roadmapId,displayName:i.displayName,health:"missing-runtime",reason:"This registered Roadmap is missing Hunsu runtime files.",recommendedAction:"repair"}:{kind:"hunsu-roadmap",path:a,roadmapId:i?.roadmapId??MH(a),displayName:i?.displayName??ts(a),health:l?d?.clean===!1?"git-dirty":"ok":"missing-runtime",recommendedAction:"open",stackHints:c}}let u=RL(a);return{kind:"git-project",path:a,branch:u?.branch,clean:u?.clean,stackHints:c,recommendedAction:"port"}}return sle(o)?{kind:"new-project",path:o,recommendedAction:"create"}:{kind:"unsupported",path:o,reason:"This folder is not a Git repository or an empty folder that Hunsu can initialize.",recommendedAction:"explain"}}function AH(t,e,r={}){let n=yp(t,e),i=n.path??n.cwd;if(!i?.trim())throw new Error("Roadmap path is required");let o=hle(i),s=Xn(o);return{roadmap:o0(s,n.title,r),repository:s,board:rr(e,{cwd:s.root,persist:r.persist??!0})}}function CH(t,e,r={}){let n=yp(t,e),i=n.path??n.cwd;if(!i?.trim())throw new Error("Roadmap path is required");let o=NH(i,e,{persist:r.persist,forceRoot:!0});if(vP(o.repository.root)){let u=Xn(o.repository.root),d=o0(u,n.title,r);return e.events=Bn(o.repository.root).events,{roadmap:d,repository:u,board:rr(e,{cwd:o.repository.root,persist:r.persist??!0})}}let s=kA({cwd:o.repository.root,title:n.title?.trim()||nue,goal:iue,destinations:oue,harness:Wde()}),a=Xn(o.repository.root),c=o0(a,n.title,r);return e.events=Bn(o.repository.root).events,{roadmap:c,repository:a,board:s.board}}function Wde(){let t=Vn(pL);return t.kind!=="team_execution_plan"?t:{...t,team:{promptTemplate:ep(pL)},members:[Ii("faker",sue,[],{kind:"worktree_write",network:"disabled"},{policy:"on_request",reviewer:"auto_review"}),Ii("keria",aue,[],{kind:"worktree_write",network:"disabled"},{policy:"never"})]}}function Vde(t){let e=t.path??t.cwd;if(!e?.trim())throw new Error("Roadmap path is required");let r=IA(e),n=r.isGitRepository?EA({cwd:r.root,title:t.title,goal:t.goal,destinations:t.destinations}):void 0;return{port:r,plan:n}}function PH(t,e,r={}){let n=t.path??t.cwd;if(!n?.trim())throw new Error("Roadmap path is required");let i=kA({cwd:n,title:t.title,goal:t.goal,destinations:t.destinations}),o=Xn(i.root),s=o0(o,t.title,r);return e.events=Bn(i.root).events,{roadmap:s,repository:o,board:i.board,port:i}}function Gde(t,e,r={}){let n=_H(t,r),i=Xn(n);return{roadmap:o0(i,void 0,r),repository:i,board:rr(e,{cwd:i.root,persist:r.persist??!0})}}function _H(t,e={}){let r=Ep(e).roadmaps.find(n=>n.roadmapId===t);if(!r)throw new Error(`Unknown Roadmap: ${t}`);if(!Qt(r.repositoryPath))throw new Error(`Roadmap path is missing: ${r.repositoryPath}`);return r.repositoryPath}function zde(t=process.cwd()){return _P([xo(at(qs(),"code")),xo(uw()),xo(t),xo(process.cwd()),xo(qs())])}function gP(t=process.cwd()){return zde(t).map(e=>({rootId:Zde(e),path:e,label:tle(e)}))}function Kde(t,e={}){let r=Jde(t,e);if(!r.ok)throw new Error(r.error.message);return r.value}function Jde(t,e={}){let r=gP(e.cwd),n=e.rootId?r.find(l=>l.rootId===e.rootId):void 0;if(e.rootId&&!n)return oe({code:"invalid_root",message:`Unknown filesystem browse root: ${e.rootId}`});let i=n??r[0],o=t?.trim()?t:i?.path;if(!o)return oe({code:"no_roots",message:"No filesystem browse roots are available"});let s=n?[n.path]:r.map(l=>l.path),a=xo(o)??dle(o,s);if(!a||!gl(a,s))return oe({code:"outside_root",message:`Folder is outside allowed browse roots: ${o}`});if(zC(a))return oe({code:"protected_path",message:`Folder is protected from browsing: ${a}`});if(!Tu(a).isDirectory())return oe({code:"not_directory",message:`Browse path is not a directory: ${a}`});let c=r.find(l=>gl(a,[l.path]));if(!c)return oe({code:"outside_root",message:`Folder is outside allowed browse roots: ${o}`});let u=c0(a,{withFileTypes:!0}).filter(l=>l.isDirectory()).filter(l=>!fle(l.name)).filter(l=>!zC(at(a,l.name))).slice(0,mue).map(l=>{let f=at(a,l.name);return{kind:"directory",name:l.name,path:f,rootId:c.rootId,type:"directory",isGitRepository:Qt(at(f,".git")),isRoadmap:mle(f)}}).sort((l,f)=>Number(f.isRoadmap)-Number(l.isRoadmap)||Number(f.isGitRepository)-Number(l.isGitRepository)||l.name.localeCompare(f.name)),d=Ci(a);return S({path:a,parent:d!==a&&gl(d,[c.path])?d:void 0,rootId:c.rootId,roots:r,entries:u})}function Xde(t,e,r={}){let n=Yde(t,e,r);if(!n.ok)throw new Error(n.error.message);return n.value}function Yde(t,e,r={}){let n=gP(r.cwd),i=t.rootId?n.find(g=>g.rootId===t.rootId):void 0;if(t.rootId&&!i)return oe({code:"invalid_root",message:`Unknown filesystem browse root: ${t.rootId}`});let o=i??n[0],s=t.path?.trim()?t.path:o?.path;if(!s)return oe({code:"no_roots",message:"No filesystem browse roots are available"});let a=i?[i.path]:n.map(g=>g.path),c=lle(s,a);if(!c||!gl(c,a))return oe({code:"outside_root",message:`Folder is outside allowed browse roots: ${s}`});if(zC(c))return oe({code:"protected_path",message:`Folder is protected from browsing: ${c}`});if(Qt(c)&&!Tu(c).isDirectory())return oe({code:"not_directory",message:`Browse grant path is not a directory: ${c}`});let u=n.find(g=>gl(c,[g.path]));if(!u)return oe({code:"outside_root",message:`Folder is outside allowed browse roots: ${s}`});let d=new Date,l=new Date(d.getTime()+hue),f=ele(`${u.rootId}:${c}:${d.toISOString()}:${yP(c).slice(0,16)}`),p={browseToken:f,rootId:u.rootId,path:c,displayPath:c,issuedAt:d.toISOString(),expiresAt:l.toISOString()};return e.filesystemCapabilities[f]=p,S({capability:p})}function yp(t,e){if(!t.browseToken)return t;let r=Qde(t.browseToken,e);return{...t,path:r.path,cwd:r.path}}function Qde(t,e){let r=e.filesystemCapabilities[t];if(!r)throw new Error("Filesystem browse token is unknown or expired.");if(Date.parse(r.expiresAt)<Date.now())throw delete e.filesystemCapabilities[t],new Error("Filesystem browse token has expired.");return r}function Zde(t){return`root_${yP(t).slice(0,16)}`}function ele(t){return`browse_${yP(t).slice(0,32)}`}function tle(t){return t===qs()?"Home":t===uw()?"Temporary":ts(t)||t}function yP(t){return ui(ci("sha256").update(t))}function xo(t){try{return Kce(t)}catch{return}}function rle(t){try{return qt(t)}catch{return}}function RL(t){try{return Xn(t)}catch{return}}function nle(t){try{return Dg(t)}catch{return!1}}function TH(t,e={}){let r=_u(t);return Ep(e).roadmaps.find(n=>_u(n.repositoryPath)===r)}function ile(t){let e=ole(t);if(!e)return!1;try{return Tu(e).isDirectory()}catch{return!1}}function ole(t){let e=Yn(t);for(;;){let r=Ci(e);if(r===e)return xo(e);let n=xo(r);if(n)return n;e=r}}function sle(t){try{return c0(t).filter(e=>!ale.has(e)).length===0}catch{return!1}}var ale=new Set([".DS_Store","Thumbs.db"]);function cle(t){let e=new Set,r=ule(at(t,"package.json"));if(r){e.add("Node");let n=new Set([...Object.keys(r.dependencies??{}),...Object.keys(r.devDependencies??{})]),i=Object.values(r.scripts??{}).join(`
227
+ `);(n.has("vite")||Zb(t,["vite.config.ts","vite.config.js","vite.config.mjs"])||/\bvite\b/.test(i))&&e.add("Vite"),(n.has("next")||Zb(t,["next.config.ts","next.config.js","next.config.mjs"]))&&e.add("Next.js"),n.has("react")&&e.add("React")}return Zb(t,["pyproject.toml","requirements.txt","setup.py","uv.lock"])&&e.add("Python"),Qt(at(t,"Cargo.toml"))&&e.add("Rust"),Qt(at(t,"go.mod"))&&e.add("Go"),Zb(t,["deno.json","deno.jsonc"])&&e.add("Deno"),[...e]}function Zb(t,e){return e.some(r=>Qt(at(t,r)))}function ule(t){if(Qt(t))try{return JSON.parse(Vs(t,"utf8"))}catch{return}}function dle(t,e){let r=Yn(t);for(;;){let n=xo(r);if(n&&gl(n,e)&&Tu(n).isDirectory())return n;let i=Ci(r);if(i===r)return;r=i}}function lle(t,e){let r=Yn(t),n=r;for(;;){let i=xo(n);if(i){if(!gl(i,e)||n!==r&&!Tu(i).isDirectory())return;let s=cP(n,r);return s.startsWith("..")||i0(s)?void 0:Yn(i,s)}let o=Ci(n);if(o===n)return;n=o}}function gl(t,e){return e.some(r=>t===r||t.startsWith(`${r}/`))}function fle(t){return t==="node_modules"||t===".git"||t===".cache"||t===".npm"||t===".pnpm-store"||t==="dist"||t==="build"||t==="out"||t==="target"||t==="coverage"||t==="__pycache__"||t.startsWith(".")}function zC(t){return aP(t).split(/[\\/]/).filter(Boolean).some(r=>ple.has(r))}var ple=new Set([".ssh",".gnupg",".aws",".config",".local",".password-store","Library","AppData"]);function mle(t){return Qt(at(t,".git"))?mu.every(e=>Qt(at(t,e))):!1}function vP(t){if(!Qt(at(t,".git")))return!1;try{return Dg(t)||Re(["for-each-ref","--count=1","--format=%(refname)","refs/hunsu"],{cwd:t}).trim().length>0}catch{return!1}}function hle(t){let e=qt(t);if(!vP(e))throw new Error(`Not a Hunsu Roadmap. Use Hunsu Port or Create Roadmap first: ${e}`);return e}function ui(t){return t.digest("hex")}function jt(t){if(t.ok)return t.value;throw new Error(t.error.message)}function Sp(t,e){return jt(Ba(t,e))}function DH(t,e,r=new Date().toISOString(),n,i){let o=qt(t),s=xP(o,n),a=Ile(e),c=ui(ci("sha256").update(o)).slice(0,12),u=ui(ci("sha256").update(JSON.stringify({root:o,routeId:e,baseRef:s,createdAt:r}))).slice(0,16),d=Yn(i??at(uw(),"hunsu-routes",`${ts(o)}-${c}`)),l=at(d,a),f=`hunsu/routes/${a}`;return bo(d,{recursive:!0}),ble(o,f),Qt(l)&&u0(l,{recursive:!0,force:!0}),Re(["worktree","add","-b",f,l,s],{cwd:o}),{worktreeHash:jt(zd(u)),path:jt(Ee(l,"worktree.path")),branch:jt(Ee(f,"worktree.branch")),baseRef:jt(Ee(s,"worktree.baseRef")),createdAt:r}}function gle(t,e,r=new Date().toISOString(),n,i){return DH(t,e,r,n,i)}function xP(t,e){if(e)return Re(["rev-parse","--verify",`${e}^{commit}`],{cwd:t}).trim();try{return Re(["rev-parse","--verify","HEAD"],{cwd:t}).trim()}catch{return Re(["commit","--allow-empty","-m","hunsu: initialize repository worktree"],{cwd:t}),Re(["rev-parse","--verify","HEAD"],{cwd:t}).trim()}}function SP(t,e,r){let n=PP(t,e);if(n?.commit)return yle(r,n.id)??n.commit;let i=e.source;if(i.type==="hunsu"){let o=t.nodes.find(s=>s.id===i.fromNodeId);if(o)return SP(t,o,r)}return xP(r)}function yle(t,e){try{return Re(["rev-parse","--verify",`refs/hunsu/moves/${e}^{commit}`],{cwd:t}).trim()}catch{return}}function bP(t,e){let r=qt(t);return Qt(e.path)&&Re(["worktree","remove","--force",e.path],{cwd:r}),{...e,removedAt:new Date().toISOString()}}function vle(t,e,r){let n=qt(t);Re(["update-ref",`refs/hunsu/moves/${e}`,r],{cwd:n})}function xle(t){let e=Re(["status","--porcelain=v1","--",".hunsu"],{cwd:t}).trim();if(!e)return;let r=e.split(/\r?\n/).map(n=>n.slice(3).replace(/^"|"$/g,"")).filter(n=>n.startsWith(".hunsu/")&&(n.endsWith(".hunsu")||mu.includes(n)));if(r.length!==0)throw new Error(`Team modified Hunsu runtime files; refusing to trust agent-owned .hunsu changes: ${r.join(", ")}`)}function Sle(t){let e=Xn(t).changes.map(r=>r.path).filter(r=>r===".hunsu"||r.startsWith(".hunsu/"));if(e.length!==0)throw new Error(`Team modified Hunsu control-plane files; refusing to commit agent-owned .hunsu changes: ${e.join(", ")}`)}function AL(t,e){let r={schema:"hunsu.current-execution.v1",execution:e,updatedAt:new Date().toISOString()},n=at(t,Xi);bo(Ci(n),{recursive:!0}),es(n,yo(r).text,"utf8")}function CL(t){u0(at(t,Xi),{force:!0})}function ble(t,e){try{Re(["show-ref","--verify",`refs/heads/${e}`],{cwd:t})}catch{return}throw new Error(`Git branch already exists: ${e}`)}function wle(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"execute"}function Ile(t){return t.split("/").map(e=>wle(e)).filter(Boolean).join("/")}function MC(t){try{Re(["init","-b","main"],{cwd:t})}catch{Re(["init"],{cwd:t})}PL(t,"user.email","hunsu@example.invalid"),PL(t,"user.name","Hunsu Studio")}function PL(t,e,r){try{Re(["config","--local","--get",e],{cwd:t})}catch{Re(["config",e,r],{cwd:t})}}function KC(t,e,r=process.cwd()){let n=t.moves.find(u=>u.id===e);if(!n)throw new Error(`Unknown MOVE: ${e}`);let i=Ele(t,n,r),o=i.baseCommit?["diff","--stat","--patch","--find-renames","--no-ext-diff",i.baseCommit,i.headCommit]:["show","--root","--stat","--patch","--find-renames","--format=medium","--no-ext-diff",i.headCommit],s=i.baseCommit?["diff","--name-status","--find-renames","-z",i.baseCommit,i.headCommit]:["diff-tree","--root","--no-commit-id","--name-status","--find-renames","-r","-z",i.headCommit],a=Re(o,{cwd:r}),c=Rle(s,a,r);return{moveId:e,commit:n.commit,headCommit:i.headCommit,baseCommit:i.baseCommit,baseMoveId:i.baseMoveId,files:c,tree:_le(c),text:c.map(u=>u.patch).filter(Boolean).join(`
228
+ `)}}function Ele(t,e,r){let n=vA(r,e.commit).map(s=>s.execution).find(s=>String(s.targetMoveId)===String(e.id)),i=n?.terminalPathCommit??n?.paths.slice().reverse().find(s=>s.commit)?.commit;if(n?.sourceMoveCommit&&i)return{headCommit:i,baseCommit:n.sourceMoveCommit,baseMoveId:n.sourceMoveId?String(n.sourceMoveId):void 0};let o=kle(t,String(e.id));return o?{headCommit:e.commit,baseCommit:o.commit,baseMoveId:String(o.id)}:{headCommit:e.commit}}function kle(t,e){let r=t.moves.find(a=>a.id===e);if(!r)return;let n=t.lines.find(a=>a.id===r.lineId),i=n?.moveIds.indexOf(r.id)??-1;if(n&&i>0){let a=n.moveIds[i-1];return t.moves.find(c=>c.id===a)}let s=t.nodes.find(a=>a.id===r.fromNodeId)?.source;if(s?.type==="move")return t.moves.find(a=>a.id===s.moveId)}function Rle(t,e,r){let n=Ale(Re(t,{cwd:r})),i=Ple(e);return n.map((o,s)=>({...o,patch:i[s]??""})).filter(o=>!iw(o.path)&&(!o.oldPath||!iw(o.oldPath)))}function Ale(t){let e=t.split("\0").filter(Boolean),r=[];for(let n=0;n<e.length;){let i=e[n++]??"";if(!i)continue;let o=Cle(i);if(i.startsWith("R")||i.startsWith("C")){let a=e[n++],c=e[n++];a&&c&&r.push({path:c,oldPath:a,kind:o});continue}let s=e[n++];s&&r.push({path:s,kind:o})}return r}function Cle(t){return t.startsWith("A")?"added":t.startsWith("D")?"removed":t.startsWith("R")?"renamed":t.startsWith("C")?"copied":t.startsWith("T")?"typeChanged":"modified"}function Ple(t){let e=[],r;for(let n of t.split(/\r?\n/)){if(n.startsWith("diff --git ")){r&&e.push(r.join(`
229
+ `)),r=[n];continue}r&&r.push(n)}return r&&e.push(r.join(`
230
+ `)),e}function _le(t){let e=[],r=new Map,n=(o,s)=>{let a=r.get(o);if(a)return a;let c={kind:"directory",name:s,path:o,changedFileCount:0,children:[]};if(r.set(o,c),!o.includes("/"))e.push(c);else{let u=Ci(o).replace(/^\.$/,""),d=ts(u);n(u,d).children.push(c)}return c};for(let o of t){let s=o.path.split("/").filter(Boolean),a=e,c="";for(let u of s.slice(0,-1)){c=c?`${c}/${u}`:u;let d=n(c,u);d.changedFileCount+=1,a=d.children}a.push({kind:"file",name:s.at(-1)??o.path,path:o.path,oldPath:o.oldPath,changeKind:o.kind})}let i=o=>o.sort((s,a)=>{let c=s.kind==="directory"?0:1,u=a.kind==="directory"?0:1;return c-u||s.name.localeCompare(a.name)}).map(s=>s.kind==="directory"?{...s,children:i(s.children)}:s);return i(e)}function Tle(t,e,r=process.cwd(),n=""){let i=Dle(t,e,r,n);if(!i.ok)throw new Error(i.error.message);return i.value}function Dle(t,e,r=process.cwd(),n=""){let i=t.moves.find(c=>c.id===e);if(!i)return oe({code:"unknown_move",message:`Unknown MOVE: ${e}`});let o=BH(n);if(!o.ok)return o;let s=o.value,a=Lle(i.commit,r);try{let c=s?`${i.commit}:${s}`:`${i.commit}:`,d=Re(["ls-tree","-z","-l",c],{cwd:r}).split("\0").filter(Boolean).map(l=>Ole(l,s)).filter(l=>!!l).sort(Mle);return S({moveId:e,commit:i.commit,path:s,parent:s?Ci(s).replace(/^\.$/,""):void 0,nodes:d,changedPaths:Hle(t,e,r),runtimeCapsule:a})}catch(c){return c instanceof Dr?oe({code:"not_found",message:`MOVE file tree not found: ${s||"/"}`}):oe({code:"git_error",message:c instanceof Error?c.message:String(c)})}}function Ble(t,e,r=process.cwd(),n=""){let i=Nle(t,e,r,n);if(!i.ok)throw new Error(i.error.message);return i.value}function Nle(t,e,r=process.cwd(),n=""){let i=t.moves.find(a=>a.id===e);if(!i)return oe({code:"unknown_move",message:`Unknown MOVE: ${e}`});let o=BH(n);if(!o.ok)return o;let s=o.value;if(!s)return oe({code:"invalid_path",message:"MOVE file path is required"});if(iw(s))return S({kind:"hiddenRuntime",moveId:e,commit:i.commit,path:s});try{if(Re(["cat-file","-t",`${i.commit}:${s}`],{cwd:r}).trim()!=="blob")return oe({code:"not_file",message:`MOVE path is not a file: ${s}`});let c=Number(Re(["cat-file","-s",`${i.commit}:${s}`],{cwd:r}).trim());if(Number.isFinite(c)&&c>FC)return S({kind:"tooLarge",moveId:e,commit:i.commit,path:s,size:c,maxBytes:FC});let u=Re(["show",`${i.commit}:${s}`],{cwd:r});return Ule(u)?S({kind:"binary",moveId:e,commit:i.commit,path:s,size:Number.isFinite(c)?c:Buffer.byteLength(u)}):S({kind:"text",moveId:e,commit:i.commit,path:s,text:u,language:$le(s),size:Number.isFinite(c)?c:Buffer.byteLength(u)})}catch(a){return a instanceof Dr?oe({code:"not_found",message:`MOVE file not found: ${s}`}):oe({code:"git_error",message:a instanceof Error?a.message:String(a)})}}function BH(t){let e=aP(t.trim().replace(/^\/+/,"")).replace(/\\/g,"/");return e==="."?S(""):e.startsWith("../")||e===".."||i0(t)||e.includes("\0")?oe({code:"invalid_path",message:`Invalid MOVE file path: ${t}`}):S(e)}function Ole(t,e){let r=t.match(/^(\d+)\s+(\w+)\s+([0-9a-f]+)\s+(-|\d+)\t(.+)$/);if(!r)return;let n=r[2],i=r[5],o=e?`${e}/${i}`:i,s=ts(i);if(iw(o)||o===".hunsu")return{kind:"hiddenRuntime",name:s,path:o};if(n==="tree")return{kind:"directory",name:s,path:o};let a=r[4]==="-"?0:Number(r[4]);return Number.isFinite(a)&&a>FC?{kind:"tooLarge",name:s,path:o,size:a}:{kind:"textFile",name:s,path:o,size:Number.isFinite(a)?a:0}}function Mle(t,e){let r=t.kind==="directory"?0:t.kind==="hiddenRuntime"?2:1,n=e.kind==="directory"?0:e.kind==="hiddenRuntime"?2:1;return r-n||t.name.localeCompare(e.name)}function Lle(t,e){let r=mu.filter(n=>{try{return Re(["cat-file","-e",`${t}:${n}`],{cwd:e}),!0}catch{return!1}});return{hiddenRuntimeFileCount:r.length,runtimePaths:r,summary:r.length===0?"No encoded Hunsu runtime files are present on this MOVE commit.":`${r.length} encoded Hunsu runtime files are hidden from the file explorer.`}}function Hle(t,e,r){try{return KC(t,e,r).files.map(n=>n.path)}catch{return[]}}function iw(t){return t===".hunsu"||t.startsWith(".hunsu/")}function Ule(t){return t.includes("\0")}function $le(t){let e=t.split(".").pop()?.toLowerCase();return!e||e===t?void 0:{js:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",json:"json",md:"markdown",css:"css",html:"html",yml:"yaml",yaml:"yaml",py:"python",rb:"ruby",rs:"rust",go:"go",sh:"shell",toml:"toml"}[e]}function NH(t,e,r={}){let n=Fle(t,{forceRoot:r.forceRoot}),i=r.persist??!0;return{repository:Xn(n),board:rr(e,{cwd:n,persist:i})}}function Fle(t,e={}){let r=Yn(t);if(!Qt(r))return bo(r,{recursive:!0}),MC(r),qt(r);if(!Tu(r).isDirectory())throw new Error(`Repository path is not a directory: ${r}`);if(e.forceRoot&&!Qt(at(r,".git")))return MC(r),qt(r);try{return qt(r)}catch{return MC(r),qt(r)}}function o0(t,e,r={}){let n=Ep(r),i=new Date().toISOString(),o=n.roadmaps.find(c=>_u(c.repositoryPath)===_u(t.root))?.roadmapId??MH(t.root),s={roadmapId:o,displayName:e?.trim()||n.roadmaps.find(c=>c.roadmapId===o)?.displayName||ts(t.root),repositoryPath:t.root,kind:"hunsu-roadmap",lifecycle:"active",localAccess:{enabled:!0},remoteAccess:Gle(n.roadmaps.find(c=>c.roadmapId===o)),codex:{readyForExecute:!1},lastOpenedAt:i,lastKnownBranch:t.branch,health:"ok",type:"roadmap",primaryAction:"open"},a={version:1,roadmaps:[s,...n.roadmaps.filter(c=>c.roadmapId!==o)]};return wP(a,r),s}function Ep(t={}){let e=OH(t);if(!Qt(e))return{version:1,roadmaps:[]};try{let r=JSON.parse(Vs(e,"utf8"));return{version:1,roadmaps:r.schema==="hunsu.bridge.workspaces.v1"&&Array.isArray(r.workspaces)?r.workspaces.flatMap(i=>typeof i.workspaceId!="string"||typeof i.displayName!="string"||typeof i.repositoryPath!="string"||typeof i.updatedAt!="string"?[]:[{roadmapId:i.workspaceId,displayName:i.displayName,repositoryPath:i.repositoryPath,lifecycle:i.lifecycle==="inactive"?"inactive":"active",localAccess:{enabled:i.lifecycle!=="inactive"},remoteAccess:jle(i.remoteAccess)?{enabled:i.remoteAccess.enabled,scopes:i.remoteAccess.scopes.filter(qle)}:{enabled:!1,scopes:[]},lastOpenedAt:i.updatedAt,health:"unknown"}]):Array.isArray(r.roadmaps)?r.roadmaps.filter(Vle):[]}}catch{return{version:1,roadmaps:[]}}}function wP(t,e={}){let r=OH(e);bo(Ci(r),{recursive:!0});let n=Wle(r),i=new Date().toISOString(),o={schema:"hunsu.bridge.workspaces.v1",workspaces:t.roadmaps.map(a=>({workspaceId:a.roadmapId,displayName:a.displayName,repositoryPath:a.repositoryPath,lifecycle:a.lifecycle==="inactive"?"inactive":"active",remoteAccess:{enabled:a.remoteAccess?.enabled===!0,scopes:a.remoteAccess?.scopes??[]},createdAt:n.get(a.roadmapId)?.createdAt??a.lastOpenedAt??i,updatedAt:a.lastOpenedAt??i}))},s=`${r}.tmp-${process.pid}-${Date.now()}`;es(s,`${JSON.stringify(o,null,2)}
231
+ `,{encoding:"utf8",mode:384}),Jce(s,r)}function jle(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.enabled=="boolean"&&Array.isArray(e.scopes)&&e.scopes.every(r=>typeof r=="string")}function qle(t){return t==="execute.start"||t==="artifactAction.run"||t==="env.read"||t==="hostAlias.expose"||t==="remote.access"}function Wle(t){if(!Qt(t))return new Map;try{let e=JSON.parse(Vs(t,"utf8"));return e.schema!=="hunsu.bridge.workspaces.v1"||!Array.isArray(e.workspaces)?new Map:new Map(e.workspaces.flatMap(r=>{if(typeof r!="object"||r===null)return[];let n=r;return typeof n.workspaceId=="string"&&typeof n.createdAt=="string"?[[n.workspaceId,{createdAt:n.createdAt}]]:[]}))}catch{return new Map}}function OH(t={}){return Yn(t.roadmapRegistryPath??at(qs(),".config","hunsu","roadmaps.json"))}function Vle(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.roadmapId=="string"&&typeof e.displayName=="string"&&typeof e.repositoryPath=="string"&&typeof e.lastOpenedAt=="string"}function Gle(t){return t?.remoteAccess??{enabled:!1,scopes:[]}}function MH(t){return`roadmap_${ui(ci("sha256").update(t)).slice(0,12)}`}async function xl(t,e,r={}){return JC([t],e,r)}async function JC(t,e,r={}){let n=r.persist??!0,i=r.cwd??process.cwd();if(n){let a=`Hunsu runtime state ${t.map(c=>c.type).join(", ")}`;return t.length===1?yb(t[0],{cwd:i,commitMessage:a}):Tg(t,{cwd:i,commitMessage:a})}let o=e.events.length;return e.events=t.reduce((a,c)=>{let u=bg(a,c);if(!u.ok)throw new Error(u.error.message);return u.value},e.events),{acceptedEvents:e.events.slice(o),board:EH(e.events)}}async function lw(t,e){if(!t.harnessLock){let i=go(t.harnessGraph);if(t.harness.kind!=="team_execution_plan")return{harness:ki(t.harness),harnessGraph:i};if(!t.executorPackageBindings?.length&&!t.resourcePackageBindings?.length)return{harness:ou(i),harnessGraph:i};let o=await _L(i,t,e);return{harness:ou(o),harnessGraph:o}}let r=await Lg(t.harnessLock,{origins:e.origins});if(r.manifest.kind!=="team")throw new Error(`Hub package ${t.harnessLock.origin}/${t.harnessLock.kind}/${t.harnessLock.key}@${t.harnessLock.version} is not a team package`);let n=await _L(TM(r.manifest),t,e);return{harness:ou(n),harnessGraph:n,harnessLock:r.lock}}async function _L(t,e,r){let n=go(t);for(let i of e.executorPackageBindings??[]){let o=await Lg(i.lock,{origins:r.origins});if(o.manifest.kind!=="member")throw new Error(`Hub package ${i.lock.origin}/${i.lock.kind}/${i.lock.key}@${i.lock.version} is not a member package`);let s=o.manifest,a=n.executors.findIndex(c=>c.kind==="member"&&c.id===i.executorId);if(a<0)throw new Error(`Harness cannot bind Member package to unknown Member Executor ${i.executorId}`);n.executors[a]=zle(s.member,o.lock)}for(let i of e.resourcePackageBindings??[]){let o=await Lg(i.lock,{origins:r.origins});if(o.manifest.kind!=="skill")throw new Error(`Hub package ${i.lock.origin}/${i.lock.kind}/${i.lock.key}@${i.lock.version} is not a skill package`);let s=`resource.package.${i.name}`;n.resources=[...n.resources.filter(a=>a.id!==s),{id:s,binding:{kind:"package",lock:o.lock},packageLock:o.lock}]}return n}function zle(t,e){return{kind:"member",id:t.id,promptTemplate:{...t.promptTemplate},resources:[...t.skills.map(r=>({kind:"skill",skill:r.kind==="local-snapshot"?{...r,snapshotFiles:r.snapshotFiles?.map(n=>({...n}))}:{...r}})),...t.plugins.map(r=>({kind:"plugin",plugin:{...r}}))],runtimePolicy:{...t.modelSelection?{modelSelection:t.modelSelection}:{},model:t.model,reasoningEffort:t.reasoningEffort,serviceTier:t.serviceTier,execution:{...t.execution},approval:{...t.approval}},packageLock:e}}function LH(t,e){return{backendId:t.backendId,connectionMode:t.connectionMode,workspace:t.workspace,modelSelection:e??t.modelSelection,aliases:t.aliases}}async function HH(t,e,r){let n=t.aliases,i=r??t.modelSelection;if(!i&&!n?.length)return;let o=e.providerInventory?await dP(e.providerInventory,t):Kle(t);if(!o.ok)return fl(o.error);let s=o.value;return ll({selection:i,aliases:n,backendId:s.backendId,inventories:s.providers})}function Kle(t){let e=Ru(t);return Yb(t)?e.remoteRequested?$s(e.backendId??"remote",e.backendId?`Provider inventory is required for selected backend ${e.backendId}.`:"Provider inventory is required for the selected remote backend."):Q5(e.backendId??"local","codex","Provider inventory must be supplied for an explicit local backend selection."):S(wC())}async function IP(t,e,r){let n=await HH(t,e,r);if(n){if(!n.ok)throw new Error(ku(n.error,n.backendId).message);return{provider:n.resolved}}}async function TL(t,e,r){let n;try{let o=rr(e,r),s=kp(o,t.requestId),a=dU(o,s.id,t.lineId),c=Rp(o,a.id),u=Du(o,a.id).filter(Qa),d=tl(jA({board:o,line:a,lineNode:c,existingRuns:wp(e,r.cwd),activeDestinations:u,selectedDestinationIds:t.selectedDestinationIds,formatMovePosition:hU}));n=await lw(d.lineNode,{origins:o.origins})}catch{return}let i=UH(n.harness,n.harnessGraph);for(let o of i){let s=await HH({...t,modelSelection:o},{providerInventory:r.providerInventory},o);if(s&&!s.ok)return ku(s.error,s.backendId)}}function UH(t,e){let r=[],n=new Set,i=o=>{if(!o)return;let s=JSON.stringify(o);n.has(s)||(n.add(s),r.push(o))};if(t.kind==="team_execution_plan")for(let o of t.members)i(o.modelSelection);for(let o of e.executors)o.kind==="member"&&i(o.runtimePolicy.modelSelection);return r}async function DL(t,e,r={}){let n=r.persist??!0,i=r.cwd??process.cwd(),o=r.runner??Zd(),s=rr(e,{cwd:i,persist:n}),a=kp(s,t.requestId),c=dU(s,a.id,t.lineId),u=Rp(s,c.id),d=Du(s,c.id).filter(Qa),l=tl(jA({board:s,line:c,lineNode:u,existingRuns:wp(e,i),activeDestinations:d,selectedDestinationIds:t.selectedDestinationIds,formatMovePosition:hU})),f=l.selectedDestinationIds,p=await lw(l.lineNode,{origins:s.origins});lU(p.harness);let g=go(p.harnessGraph),v=new Date().toISOString(),b=rpe(e,s,n?i:void 0),C=PP(s,l.lineNode),D=n?SP(s,l.lineNode,i):void 0,_=n?gle(i,b,v,D,r.routeWorktreeRoot):mU(i,b,v),F={provider:"codex",conversationHash:jt(tg(fU({executeId:b,lineId:c.id,sourceNodeId:l.lineNode.id,at:v}))),contextHash:jt(Ee(pU(s,l.lineNode,b),"conversation.contextHash")),worktreeHash:_.worktreeHash,startedAt:v},he=await IP(t,r),z=t.aliases,de={runId:npe({lineId:c.id,executeId:b,roadmapId:r.roadmapId}),roadmapId:r.roadmapId,executeId:b,requestId:a.id,lineId:c.id,repositoryPath:i,backendId:t.backendId,connectionMode:t.connectionMode,workspace:t.workspace,provider:"codex",modelSelection:t.modelSelection,aliases:z,resolvedModelSelection:he?.provider,source:"live",status:"running",selectedDestinationIds:f,harnessLock:p.harnessLock,sourceNodeId:l.lineNode.id,sourceMoveId:C?.id,targetMoveOrdinal:l.targetMoveOrdinal,worktree:_,conversationRef:F,attemptCount:0,maxAttemptCount:qfe(p.harness),memberEvaluations:[],pathCommits:{},memberPathRuns:[],providerTurnIds:[],debugEvents:[],rawAppServerMessages:[],codexTurns:[],codexItems:[],agentSessions:[],activeItemIds:[],assistantTranscript:[],startedAt:v,updatedAt:v};e.runs[de.runId]=de,Br(e,de,s);let R={runId:de.runId,executeId:b,repositoryPath:_.path,worktreeHash:_.worktreeHash,sourceMoveId:C?.id,targetMoveOrdinal:l.targetMoveOrdinal,requestGoal:a.goal,teamName:c.teamName??l.lineNode.teamName,harness:p.harness,harnessGraph:g,teamScopeId:g.rootTeamId,harnessLock:p.harnessLock,activeDestinations:d,selectedDestinationIds:f,attemptOrdinal:1,maxAttemptCount:de.maxAttemptCount,futureConstraints:s.futureConstraints.filter(V=>V.lineId===c.id).map(V=>V.constraint),conversationRef:F,resolvedModelSelection:he?.provider,board:s};return rU(R,o,e,{cwd:i,persist:n,apmSkillRegistryClient:r.apmSkillRegistryClient,providerInventory:r.providerInventory}).catch(V=>aU(de.runId,V,e,{cwd:i,persist:n})),{run:Ai(de),execute:Zi(de),board:s}}async function BL(t,e,r={}){let n=bl(e,t.runId,r.cwd);await(r.runner??Zd()).pauseRun(n.runId),Ya(n,"paused"),Br(e,n);let o=await xl({type:"PauseLine",lineId:n.lineId},e,r);return{run:Ai(n),execute:Zi(n),board:o.board}}async function NL(t,e,r){let n=r.persist??!0,i=r.cwd??process.cwd(),o=bl(e,t.runId,i),s=await Jle(o,e,{cwd:i,persist:n,status:r.bridgeStatus,providerInventory:r.providerInventory});if(s)return oe(s);let a=r.runner??Zd(),c=await xl({type:"ResumeLine",lineId:o.lineId},e,r);if(Ya(o,"running"),Br(e,o),o.providerThreadId){let u=rr(e,{cwd:i,persist:n}),d=kp(u,o.requestId),l=CP(u,o.lineId),f=Rp(u,o.lineId),p=Du(u,o.lineId).filter(Qa),g=f?await lw(f,{origins:u.origins}):void 0,v=g?go(g.harnessGraph):void 0;g&&(lU(g.harness),o.harnessLock=g.harnessLock),rU({runId:o.runId,executeId:o.executeId,repositoryPath:o.worktree?.path??i,worktreeHash:o.worktree?.worktreeHash,sourceMoveId:o.sourceMoveId,targetMoveOrdinal:o.targetMoveOrdinal,requestGoal:d.goal,teamName:l.teamName??f?.teamName,harness:g?.harness??f?.harness,harnessGraph:v,teamScopeId:v?.rootTeamId,harnessLock:g?.harnessLock,activeDestinations:p,selectedDestinationIds:o.selectedDestinationIds,attemptOrdinal:(o.attemptCount??0)+1,maxAttemptCount:o.maxAttemptCount,previousMemberOutputs:o.memberEvaluations?.map(l0),futureConstraints:u.futureConstraints.filter(b=>b.lineId===o.lineId).map(b=>b.constraint),conversationRef:o.conversationRef,resolvedModelSelection:o.resolvedModelSelection,board:u},a,e,{cwd:i,persist:n,resumeProviderThreadId:o.providerTeamThreadId??o.providerThreadId,apmSkillRegistryClient:r.apmSkillRegistryClient,providerInventory:r.providerInventory}).catch(b=>aU(o.runId,b,e,{cwd:i,persist:n}))}return S({run:Ai(o),execute:Zi(o),board:c.board})}async function Jle(t,e,r){let n=LH(t);return AC(n,r.status,{providerInventory:()=>dP(r.providerInventory,n),modelSelections:async()=>{let i=[];t.resolvedModelSelection&&i.push({selection:{kind:"direct",provider:t.resolvedModelSelection}}),i.push({selection:t.modelSelection,aliases:t.aliases});let o=rr(e,{cwd:r.cwd,persist:r.persist}),s=Rp(o,t.lineId);if(s){let a=await lw(s,{origins:o.origins});for(let c of UH(a.harness,a.harnessGraph))i.push({selection:c,aliases:t.aliases})}return i}})}async function OL(t,e,r={}){let n=r.persist??!0,i=r.cwd??process.cwd(),o=bl(e,t.runId,i);return await(r.runner??Zd()).stopRun(o.runId),Ya(o,"stopped"),Br(e,o),{run:Ai(o),execute:Zi(o),board:rr(e,{cwd:i,persist:n})}}async function ML(t,e,r={}){let n=r.persist??!0,i=r.cwd??process.cwd(),o=bl(e,t.runId,i),s=rr(e,{cwd:i,persist:n});CP(s,o.lineId);let a=gU(t.destinationIds,o.selectedDestinationIds);cpe(s,o,t,a,i);let c=Re(["rev-parse","--verify",`${t.fromRef}^{commit}`],{cwd:i}).trim(),u=TP(s),d=await xl({type:"RecordMove",lineId:o.lineId,moveId:u,summary:t.summary,commit:c,reachedDestinationIds:a,evidence:t.evidence,risks:t.risks&&t.risks.length>0?t.risks:void 0,executeId:o.executeId,conversationRef:o.conversationRef,worktree:o.worktree,actor:"codex"},e,{cwd:i,persist:n});return o.finalResponse=`Recorded MOVE ${u} Arrived`,o.outcome="arrived",o.conversationRef&&(o.conversationRef={...o.conversationRef,endedAt:new Date().toISOString()}),o.worktree&&n&&(o.worktree=bP(i,o.worktree)),Ya(o,"arrived"),Br(e,o,d.board),{run:Ai(o),execute:Zi(o),board:d.board,acceptedEvents:d.acceptedEvents,moveId:u,commit:c}}async function Xle(t,e,r){let n=r.persist??!0,i=r.cwd??process.cwd(),o=bl(e,r.runId,i),s=rr(e,{cwd:i,persist:n}),a=o.worktree?.path??i,c=gU(void 0,o.selectedDestinationIds);upe(s,o,t,c,a,{promotedPathCommit:o.terminalPathCommit,prevMoveCommit:o.pathCommits?.PrevMove});let u=TP(s);!o.terminalPathCommit&&o.worktree&&n&&xle(a);let d=o.terminalPathCommit?await Yle({board:s,cwd:a,completion:t,moveId:u,runner:r.runner??Zd(),run:o,state:e}):void 0,l=d&&o.terminalPathCommit?n&&o.worktree?pu:oA({cwd:a,runId:o.runId,moveId:u,goal:kp(s,o.requestId).goal,finalizerMessage:d}).commitSha:Q8(`Hunsu move ${u}
232
+ `,{cwd:a}).commitSha,f={type:"RecordMove",lineId:o.lineId,moveId:u,summary:t.summary,commit:l,reachedDestinationIds:c,evidence:t.evidence,risks:t.risks.length>0?t.risks:void 0,executeId:o.executeId,conversationRef:o.conversationRef,worktree:o.worktree,actor:"codex"},p=o.worktree&&n?a:i,g=d&&o.terminalPathCommit&&o.worktree&&n?Qle(f,o,{board:s,cwd:p,finalizerMessage:d,moveId:u}):await xl(f,e,{cwd:p,persist:n}),v=d&&o.terminalPathCommit&&o.worktree&&n?Xr(Re(["rev-parse","--verify","HEAD"],{cwd:a}).trim()):o.worktree&&n?Xr(Re(["rev-parse","--verify","HEAD"],{cwd:a}).trim()):l===pu?Xr(Re(["rev-parse","--verify","HEAD"],{cwd:a}).trim()):Xr(l);return d&&o.terminalPathCommit&&o.worktree&&n?o.moveFinalizerCommit=v:d&&o.terminalPathCommit&&(o.moveFinalizerCommit=l===pu?v:Xr(l)),o.worktree&&n&&vle(i,u,v),o.finalResponse=`Recorded MOVE ${u} Arrived`,o.outcome="arrived",o.conversationRef&&(o.conversationRef={...o.conversationRef,endedAt:new Date().toISOString()}),o.worktree&&n&&(o.worktree=bP(i,o.worktree)),Ya(o,"arrived"),Br(e,o,g.board),{run:Ai(o),execute:Zi(o),board:g.board,acceptedEvents:g.acceptedEvents,moveId:u,commit:v}}async function Yle(t){let e=t.run.terminalPathCommit,r=t.run.pathCommits?.PrevMove;if(!e||!r)throw new Error("Cannot finalize MOVE without PrevMove and terminal Path commits");await p0(t.cwd,void 0,{phase:"move-finalizer"});let n=pw(t.state,t.run,{kind:"MoveFinalizer",runId:t.run.runId,executeId:t.run.executeId,moveId:t.moveId}),i;try{i=await gw(t.runner,t.run.runId,t.state,n.sessionId,()=>t.runner.runMoveFinalizer(Wfe({board:t.board,cwd:t.cwd,completion:t.completion,moveId:t.moveId,run:t.run,sourceMoveCommit:r,terminalPathCommit:e})))}catch(s){throw Cu(t.state,t.run,n.sessionId,s),s}t.run.providerFinalizerThreadId=i.providerThreadId??t.run.providerFinalizerThreadId,t.run.providerThreadId=i.providerThreadId??t.run.providerThreadId,f0(t.run,i.providerTurnId),hw(t.state,t.run,n,i);let o=i.finalResponse?.trim();if(!o)throw Cu(t.state,t.run,n.sessionId,"MOVE finalizer completed without a commit message"),new Error("MOVE finalizer completed without a commit message");return t.run.moveFinalizerMessage=o,t.run.updatedAt=new Date().toISOString(),mw(t.state,t.run,n.sessionId,o,t.run.updatedAt),Br(t.state,t.run),o}function Qle(t,e,r){let n=rfe(e,r.moveId),i=yb(t,{cwd:r.cwd,previousExecution:{type:"present",value:n},selfCommitMoveIds:[r.moveId]});efe(r.cwd);let o=oA({cwd:r.cwd,runId:e.runId,moveId:r.moveId,goal:kp(r.board,e.requestId).goal,finalizerMessage:r.finalizerMessage}).commitSha;return{acceptedEvents:i.acceptedEvents.map(s=>Zle(s,r.moveId,o)),board:Bn(r.cwd).board}}function Zle(t,e,r){return t.type!=="MoveRecorded"||t.move.id!==e||t.move.commit!==pu?t:{...t,move:{...t.move,commit:jt(Gd(r,"commit"))}}}function efe(t){Re(["add","--all","--",...tfe(t)],{cwd:t})}function tfe(t){return[...mu,Xi,cp].filter(e=>Qt(at(t,e))||$H(t,e))}function $H(t,e){try{return Re(["ls-files","--error-unmatch",e],{cwd:t}),!0}catch(r){if(r instanceof Dr)return!1;throw r}}function rfe(t,e){let r=t.agentSessions.find(o=>o.owner.kind==="TeamPlan"),n=t.agentSessions.find(o=>o.owner.kind==="MoveFinalizer"&&o.owner.moveId===e),i=t.pathCommits?.PrevMove;if(!i)throw new Error("Cannot persist previous execution without PrevMove commit");return{schema:"hunsu.previous-execution.v1",sourceMoveCommit:i,targetMoveId:e,executeId:t.executeId,runId:t.runId,lineId:t.lineId,sourceNodeId:t.sourceNodeId,sourceMoveId:t.sourceMoveId,targetMoveOrdinal:t.targetMoveOrdinal,selectedDestinationIds:[...t.selectedDestinationIds],worktree:t.worktree,conversationRef:t.conversationRef,plan:{nodeType:"PlanNode",lifecycle:r?.state.type==="failed"?"Failed":"Completed",session:r?XC(r,"TeamPlan"):void 0,completedAt:FH(r),error:r?.state.type==="failed"?r.state.error:void 0},paths:nfe(t),pathCommits:{...t.pathCommits??{}},terminalPathId:t.terminalMemberPathId,terminalPathCommit:t.terminalPathCommit,finalizerSession:n?XC(n,"MoveFinalizer"):void 0,moveFinalizerCommit:{type:"self"},moveFinalizerMessage:t.moveFinalizerMessage,startedAt:t.startedAt,completedAt:new Date().toISOString()}}function nfe(t){let e=t.memberPathRuns??[],r=new Map(e.map(i=>[i.pathId,i]));return e.map(i=>({id:i.pathId,executorId:i.executorId,goal:i.goal,requires:i.requires})).map(i=>{let o=r.get(i.id),s=o?.agentSessionId?t.agentSessions.find(a=>a.sessionId===o.agentSessionId):t.agentSessions.find(a=>a.owner.kind==="ExecutionPlan"&&a.owner.pathId===i.id);return{nodeType:"PathNode",pathId:i.id,executorId:i.executorId,goal:i.goal,requires:i.requires,lifecycle:ife(o),session:s?XC(s,"ExecutionPlan"):void 0,commit:o&&"commit"in o?o.commit:void 0,parentCommit:o&&"parentCommit"in o?o.parentCommit:void 0,treeChanged:o&&"treeChanged"in o?o.treeChanged:void 0,startedAt:o?.startedAt,completedAt:o&&"completedAt"in o?o.completedAt:void 0,error:o&&o.status==="failed"?o.error:void 0}})}function ife(t){return!t||t.status==="planned"?"Waiting":t.status==="starting"||t.status==="executing"?"Executing":t.status==="failed"?"Failed":"Completed"}function XC(t,e){return{sessionId:t.sessionId,ownerKind:e,providerThreadId:t.provider?.providerThreadId,providerTurnId:t.provider?.providerTurnId,state:t.state.type,startedAt:t.createdAt,completedAt:FH(t),error:t.state.type==="failed"?t.state.error:void 0}}function FH(t){if(t&&(t.state.type==="completed"||t.state.type==="failed"))return t.state.completedAt}async function EP(t,e,r,n){let i=n.persist??!0,o=n.cwd??process.cwd(),s=bl(r,n.runId,o),a=rr(r,{cwd:o,persist:i}),c=s.worktree?.path??o,u=TP(a),d=Zfe(c,s.worktree),l=await xl({type:"RecordAccident",lineId:s.lineId,moveId:u,summary:n.summary??`Execute failed after ${s.attemptCount??0} attempt${s.attemptCount===1?"":"s"}`,commit:d,evidence:e,failureReason:t,risks:n.risks&&n.risks.length>0?n.risks:void 0,executeId:s.executeId,conversationRef:s.conversationRef,worktree:s.worktree,actor:"codex"},r,{cwd:o,persist:i});return s.finalResponse=`Recorded MOVE ${u} Accident`,s.outcome="accident",s.conversationRef&&(s.conversationRef={...s.conversationRef,endedAt:new Date().toISOString()}),s.worktree&&i&&(s.worktree=bP(o,s.worktree)),Ya(s,"accident"),Br(r,s,l.board),{run:Ai(s),execute:Zi(s),board:l.board,acceptedEvents:l.acceptedEvents,moveId:u,commit:d}}async function LL(t,e,r,n={}){let i=await xl({type:t==="accept"?"AcceptLine":"RejectLine",lineId:e.lineId,reason:e.reason},r,n),o=xU(r,e.lineId,n.cwd);return o&&(Ya(o,t==="accept"?"finished":"stopped"),Br(r,o)),i}function ofe(t){return typeof t=="object"&&t!==null&&"commands"in t&&Array.isArray(t.commands)}function HL(t){let e=t;return ofe(e)?e.commands:[e]}function YC(t,e){return e.persist?Bn(e.cwd).events:t.events}function rr(t,e){return e.persist?Bn(e.cwd).board:EH(t.events)}function UL(t,e,r,n={}){e.writeHead(200,{...dw.get(e),"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache, no-transform",connection:"keep-alive"}),e.flushHeaders?.(),e.write(`: connected
233
+
234
+ `);let i=$de(r,o=>jH(e,o),n);t.on("close",i)}function $L(t,e,r,n={}){e.writeHead(200,{...dw.get(e),"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache, no-transform",connection:"keep-alive"}),e.flushHeaders?.(),e.write(`: connected
235
+
236
+ `);let i=Fde(r,o=>jH(e,o),n);t.on("close",i)}function jH(t,e){t.write(`event: ${e.type}
237
+ `),t.write(`data: ${JSON.stringify(e)}
238
+
239
+ `)}function Br(t,e,r){sfe(t,e.runId),s0(e);let n=Ai(e);afe(t,{type:"run.updated",run:n,execute:Zi(n),board:r})}function FL(t,e){let r=jC.get(t);if(r||(r=new Map,jC.set(t,r)),r.has(e.runId))return;let n=setTimeout(()=>{r?.delete(e.runId),t.runs[e.runId]===e&&Br(t,e)},pue);n.unref?.(),r.set(e.runId,n)}function sfe(t,e){let r=jC.get(t),n=r?.get(e);n&&(clearTimeout(n),r?.delete(e))}function afe(t,e){for(let r of t.liveSubscribers)r(e)}function fw(t,e){for(let r of t.agentSessionSubscribers)r(e)}function pw(t,e,r,n=new Date().toISOString()){e.agentSessions??=[],e.agentSessionIds??=[];let i=qH(r),o=t.agentSessions[i]??e.agentSessions.find(c=>c.sessionId===i);if(o)return e.activeAgentSessionId=o.sessionId,e.agentSessionIds.includes(o.sessionId)||e.agentSessionIds.push(o.sessionId),e.agentSessions.some(c=>c.sessionId===o.sessionId)||e.agentSessions.push(o),t.agentSessions[o.sessionId]=o,o;let s=cfe(e,r),a={sessionId:i,roadmapId:e.roadmapId,routeRef:s,runId:s.runId,executeId:s.executeId,owner:r,state:{type:"starting",startedAt:n},messages:[],activeItemIds:[],revision:1,createdAt:n,updatedAt:n};return t.agentSessions[a.sessionId]=a,e.agentSessions.push(a),e.agentSessionIds.push(a.sessionId),e.activeAgentSessionId=a.sessionId,Gs(t,a),a}function qH(t){switch(t.kind){case"TeamPlan":return`${t.executeId}:plan:${t.attempt}`;case"ExecutionPlan":return`${t.executeId}:path:${t.attempt}:${t.pathId}`;case"MoveFinalizer":return`${t.executeId}:finalizer:${t.moveId??"move"}`;case"HunsuDraft":return`hunsu-draft:${t.draftSessionId}:draft`}}function cfe(t,e){switch(e.kind){case"TeamPlan":return LC(t,"Plan");case"ExecutionPlan":return LC(t,"Path");case"MoveFinalizer":return LC(t,"Path");case"HunsuDraft":return{kind:"Route",routeKind:"HunsuDraft",routeId:`hunsu-draft:${e.draftSessionId}`,draftSessionId:e.draftSessionId,sourceLineId:"",sourceNodeId:""}}}function LC(t,e){return{kind:"Route",routeKind:e,routeId:t.executeId,runId:t.runId,executeId:t.executeId,sourceLineId:t.lineId,sourceNodeId:String(t.sourceNodeId??""),worktree:t.worktree}}function mw(t,e,r,n,i=new Date().toISOString()){let o=r?e.agentSessions?.find(a=>a.sessionId===r):void 0;if(!o)return;let s=jr(n,sr);o.finalResponse=s,o.state={type:"completed",provider:o.provider,finalResponse:s,completedAt:i},o.activeItemIds=[],Xa(o,i),Sl(o),e.activeAgentSessionId===o.sessionId&&(e.activeAgentSessionId=void 0),Gs(t,o)}function Cu(t,e,r,n,i=new Date().toISOString()){let o=r?e.agentSessions?.find(a=>a.sessionId===r):void 0;if(!o)return;let s=xr(n instanceof Error?n.message:String(n),sr);o.error=s,o.state={type:"failed",provider:o.provider,error:s,completedAt:i},o.activeItemIds=[],Xa(o,i),Sl(o),e.activeAgentSessionId===o.sessionId&&(e.activeAgentSessionId=void 0),Gs(t,o)}function WH(t,e,r,n,i=new Date().toISOString()){r&&(r.provider=n,r.state={type:"executing",provider:n,activeItemIds:r.activeItemIds},Xa(r,i),e.activeAgentSessionId=r.sessionId,Gs(t,r))}function hw(t,e,r,n,i=new Date().toISOString()){if(!n.providerThreadId||!n.providerTurnId)return;let o={providerThreadId:n.providerThreadId,providerTurnId:n.providerTurnId};return WH(t,e,r,o,i),o}function ufe(t,e,r){let n="providerTurnId"in e?e.providerTurnId:void 0;if(n){let o=t.agentSessions?.find(s=>s.provider?.providerTurnId===n);if(o)return o}let i=r??t.activeAgentSessionId;return i?t.agentSessions?.find(o=>o.sessionId===i):void 0}function VH(t,e){return t?`${t}:${e}`:e}function jL(t,e,r,n,i,o,s){if(!e)return;let a=s?new Date(s).toISOString():new Date().toISOString(),c=VH(r,n),u=e.messages.find(d=>d.itemId===c);return u||(u={sessionId:e.sessionId,messageId:`${e.sessionId}:${c}`,itemId:c,role:qL(i.type),type:i.type,status:o,title:ZC(i),revision:1,createdAt:a,updatedAt:a},e.messages.push(u)),u.type=i.type,u.role=qL(i.type),u.status=o,u.title=ZC(i),u.command=i.command??u.command,u.cwd=i.cwd??u.cwd,u.commandActions=i.commandActions??u.commandActions,o!=="completed"?(u.text=i.text??u.text,u.summary=i.summary??u.summary,u.content=i.content??u.content,u.output=i.aggregatedOutput??u.output,u.changes=i.changes??u.changes):(u.text=u.text??i.text,u.summary=u.summary??i.summary,u.content=u.content??i.content,u.output=u.output??i.aggregatedOutput,u.changes=u.changes??i.changes),u.completedAt=o==="completed"?a:u.completedAt,u.durationMs=JH(KH(u.createdAt,u.completedAt,i.durationMs,u.durationMs)),AP(u),zH(e,u,a),o==="started"&&GH(e,c,a),Sl(e),o==="completed"?(e.activeItemIds=e.activeItemIds.filter(d=>d!==c),fw(t,{type:"agentMessage.completed",sessionId:e.sessionId,roadmapId:e.roadmapId,routeRef:e.routeRef,runId:e.runId,executeId:e.executeId,messageId:u.messageId,itemId:u.itemId,role:u.role,messageType:u.type,title:u.title,status:"completed",text:u.text,summary:u.summary,content:u.content,command:u.command,cwd:u.cwd,commandActions:u.commandActions,output:u.output,changes:u.changes,messageRevision:u.revision,sessionRevision:e.revision,createdAt:u.createdAt,completedAt:u.completedAt??a,durationMs:u.durationMs,updatedAt:u.updatedAt})):Gs(t,e),u}function dfe(t,e,r){if(!e)return;let n=new Date().toISOString(),i=VH(r.providerTurnId,r.itemId),o=e.messages.find(c=>c.itemId===i);o||(o={sessionId:e.sessionId,messageId:`${e.sessionId}:${i}`,itemId:i,role:hfe(r.deltaKind),type:QH(r.deltaKind),status:"streaming",title:ZH(r.deltaKind),revision:1,createdAt:n,updatedAt:n},e.messages.push(o));let s=mfe(r.deltaKind),a=xr(r.delta,sr);o.status=o.status==="completed"?"completed":"streaming",s==="text"?o.text=xr(`${o.text??""}${a}`,sr):s==="output"?o.output=xr(`${o.output??""}${a}`,sr):s==="summary"?o.summary=Pu(ow(o.summary,a,r.contentIndex)):o.content=Pu(ow(o.content,a,r.contentIndex)),AP(o),zH(e,o,n),GH(e,i,n),Sl(e),fw(t,{type:"agentMessage.delta",sessionId:e.sessionId,roadmapId:e.roadmapId,routeRef:e.routeRef,runId:e.runId,executeId:e.executeId,messageId:o.messageId,itemId:i,role:o.role,messageType:o.type,title:o.title,field:s,delta:a,contentIndex:r.contentIndex,messageRevision:o.revision,sessionRevision:e.revision,createdAt:o.createdAt,updatedAt:n})}function GH(t,e,r=new Date().toISOString()){t.activeItemIds.includes(e)||t.activeItemIds.push(e),t.provider&&(t.state.type==="starting"||t.state.type==="executing")&&(t.state={type:"executing",provider:t.provider,activeItemIds:t.activeItemIds}),Xa(t,r)}function zH(t,e,r=new Date().toISOString()){e.revision+=1,e.updatedAt=r,Xa(t,r)}function Xa(t,e=new Date().toISOString()){t.revision+=1,t.updatedAt=e}function KH(t,e,r,n){let i=ffe(t,e);return lfe([{source:"lifecycle",value:i},{source:"itemMetadata",value:r},{source:"previous",value:n}])}function lfe(t){let e=t.find(n=>typeof n.value=="number"&&Number.isFinite(n.value)&&n.value>0);if(e?.value!==void 0)return{ok:!0,value:e.value,source:e.source};let r=t.find(n=>typeof n.value=="number"&&Number.isFinite(n.value));return r?.value!==void 0?{ok:!0,value:r.value,source:r.source}:{ok:!1,error:"missing-duration"}}function JH(t){return t.ok?t.value:void 0}function ffe(t,e){if(!t||!e)return;let r=Date.parse(t),n=Date.parse(e);if(!(!Number.isFinite(r)||!Number.isFinite(n)))return Math.max(0,n-r)}function Gs(t,e){fw(t,{type:"agentSession.lifecycle",sessionId:e.sessionId,roadmapId:e.roadmapId,routeRef:e.routeRef,runId:e.runId,executeId:e.executeId,owner:e.owner,state:e.state,provider:e.provider,activeItemIds:e.activeItemIds,finalResponse:e.finalResponse,error:e.error,sessionRevision:e.revision,updatedAt:e.updatedAt})}function pfe(t,e,r){fw(t,{type:"agentMessage.completed",sessionId:e.sessionId,roadmapId:e.roadmapId,routeRef:e.routeRef,runId:e.runId,executeId:e.executeId,messageId:r.messageId,itemId:r.itemId,role:r.role,messageType:r.type,title:r.title,status:"completed",text:r.text,summary:r.summary,content:r.content,command:r.command,cwd:r.cwd,commandActions:r.commandActions,output:r.output,changes:r.changes,messageRevision:r.revision,sessionRevision:e.revision,createdAt:r.createdAt,completedAt:r.completedAt??r.updatedAt,durationMs:r.durationMs,updatedAt:r.updatedAt})}function mfe(t){switch(t){case"agentMessage":case"plan":return"text";case"commandOutput":case"fileChangeOutput":return"output";case"reasoningSummary":return"summary";case"reasoningText":return"content"}}function hfe(t){switch(t){case"agentMessage":case"plan":return"assistant";case"reasoningText":case"reasoningSummary":return"reasoning";case"commandOutput":case"fileChangeOutput":return"tool"}}function qL(t){switch(t){case"userMessage":return"user";case"agentMessage":case"plan":return"assistant";case"reasoning":return"reasoning";case"commandExecution":case"fileChange":case"mcpToolCall":case"webSearch":return"tool";default:return"system"}}async function gfe(t,e,r,n){try{for await(let i of t.events(e)){let o=r.runs[e];if(!o)return;if(i.runId===e){if(i.type==="runner.appServer.message"){XH(o,i),o.updatedAt=new Date().toISOString(),s0(o),FL(r,o);continue}YH(o,i,r,n),o.debugEvents.push(RP(i)),o.updatedAt=new Date().toISOString(),i.type==="runner.final"&&So(o.status)&&(o.finalResponse=xr(i.finalResponse,sr)),i.type==="runner.error"&&So(o.status)&&(o.error=xr(i.error,sr)),s0(o),yfe(i)?FL(r,o):Br(r,o)}}}catch(i){jfe(e,i,r)}}function yfe(t){return t.type==="runner.item.delta"}async function gw(t,e,r,n,i){let o=gfe(t,e,r,n);try{return await i()}finally{await o}}async function vfe(t,e,r,n,i){let o=n.draftAgentSessionId?r.agentSessions[n.draftAgentSessionId]:mP(r,n),s=Sfe(n,o),a=xfe(t,e,r,s,o?.sessionId);try{return await i()}finally{await a}}async function xfe(t,e,r,n,i){try{for await(let o of t.events(e))if(o.runId===e){if(o.type==="runner.appServer.message"){XH(n,o),n.updatedAt=new Date().toISOString(),s0(n);continue}YH(n,o,r,i),n.debugEvents.push(RP(o)),n.updatedAt=new Date().toISOString(),o.type==="runner.final"&&So(n.status)&&(n.finalResponse=xr(o.finalResponse,sr)),o.type==="runner.error"&&So(n.status)&&(n.error=xr(o.error,sr)),s0(n)}}catch(o){let s=i?r.agentSessions[i]:void 0;s&&bfe(r,s,o)}}function Sfe(t,e){let r=new Date().toISOString();return{runId:`hunsu-draft:${t.draftSessionId}`,roadmapId:t.roadmapId,executeId:t.routeId,requestId:t.sourceLineId,lineId:t.sourceLineId,repositoryPath:t.repositoryPath,provider:"codex",status:t.status==="failed"?"failed":"running",selectedDestinationIds:[],sourceNodeId:t.sourceNodeId,sourceMoveId:t.sourceMoveId,worktree:t.worktree,providerThreadId:t.providerThreadId,debugEvents:[],rawAppServerMessages:[],codexTurns:[],codexItems:[],agentSessionIds:e?[e.sessionId]:[],agentSessions:e?[e]:[],activeItemIds:[],activeAgentSessionId:e?.sessionId,assistantTranscript:[],startedAt:r,updatedAt:r}}function bfe(t,e,r){let n=xr(r instanceof Error?r.message:String(r),sr),i=new Date().toISOString();e.error=n,e.state={type:"failed",provider:e.provider,error:n,completedAt:i},e.activeItemIds=[],Xa(e,i),Sl(e),Gs(t,e)}function wfe(t,e){t.assistantTranscript??=[];let r=t.assistantTranscript.find(i=>i.itemId===e.itemId&&i.providerTurnId===e.providerTurnId&&i.providerThreadId===e.providerThreadId),n=new Date().toISOString();if(r){r.text=xr(`${r.text}${e.delta}`,sr),r.status="streaming",r.updatedAt=n;return}t.assistantTranscript.push({itemId:e.itemId,providerThreadId:e.providerThreadId,providerTurnId:e.providerTurnId,text:xr(e.delta,sr),status:"streaming",updatedAt:n})}function Ife(t,e){t.assistantTranscript??=[];let r=t.assistantTranscript.find(i=>i.itemId===e.itemId&&i.providerTurnId===e.providerTurnId&&i.providerThreadId===e.providerThreadId),n=new Date().toISOString();if(r){r.status="completed",r.updatedAt=n;return}}function XH(t,e){t.rawAppServerMessages??=[],t.rawAppServerMessages.push(uU({direction:e.direction,method:e.method,providerThreadId:e.providerThreadId,providerTurnId:e.providerTurnId,message:e.message,at:new Date().toISOString()})),rP(t.rawAppServerMessages,eH,tH)}function YH(t,e,r,n){let i=ufe(t,e,n);switch(e.type){case"runner.status.changed":t.liveStatus={phase:e.phase,headline:e.headline,detail:e.detail,itemId:e.itemId,providerTurnId:e.providerTurnId,updatedAt:new Date().toISOString()};break;case"runner.turn.started":WL(t,{providerThreadId:e.providerThreadId,providerTurnId:e.providerTurnId,status:"started",startedAt:e.startedAtMs?new Date(e.startedAtMs).toISOString():new Date().toISOString()}),f0(t,e.providerTurnId),WH(r,t,i,{providerThreadId:e.providerThreadId,providerTurnId:e.providerTurnId},e.startedAtMs?new Date(e.startedAtMs).toISOString():new Date().toISOString()),Efe(t,{providerThreadId:e.providerThreadId,providerTurnId:e.providerTurnId});break;case"runner.turn.completed":t.lastRunUsage=Oue(e.usage)??t.lastRunUsage,e.providerTurnId&&WL(t,{providerThreadId:e.providerThreadId,providerTurnId:e.providerTurnId,status:"completed",completedAt:e.completedAtMs?new Date(e.completedAtMs).toISOString():new Date().toISOString()});break;case"runner.item.started":VL(t,GL(e.itemId,e.item,"started",e.providerThreadId,e.providerTurnId,e.startedAtMs)),jL(r,i,e.providerTurnId,e.itemId,e.item,"started",e.startedAtMs),Cfe(t,e.itemId),t.liveStatus=tU(t.codexItems.find(o=>o.itemId===e.itemId),"started");break;case"runner.item.delta":Pfe(t,e),dfe(r,i,e),e.deltaKind==="agentMessage"&&wfe(t,{itemId:e.itemId,providerThreadId:e.providerThreadId,providerTurnId:e.providerTurnId,delta:e.delta});break;case"runner.item.completed":VL(t,GL(e.itemId,e.item,"completed",e.providerThreadId,e.providerTurnId,e.completedAtMs)),jL(r,i,e.providerTurnId,e.itemId,e.item,"completed",e.completedAtMs),e.item.type==="agentMessage"&&e.item.text&&Ife(t,{itemId:e.itemId,providerThreadId:e.providerThreadId,providerTurnId:e.providerTurnId,text:e.item.text}),t.activeItemIds=(t.activeItemIds??[]).filter(o=>o!==e.itemId),t.liveStatus=Nfe(t);break;default:break}}function Efe(t,e){let r=[...t.memberPathRuns??[]].reverse().find(n=>n.status==="starting");r&&Object.assign(r,{status:"executing",session:e})}function kfe(t){return"session"in t?t.session:void 0}function Rfe(t,e){if(!t.providerThreadId||!t.providerTurnId)throw new Error(`Member Path ${e} completed without a provider session`);return{providerThreadId:t.providerThreadId,providerTurnId:t.providerTurnId}}function Afe(t,e){let r=new Date().toISOString(),n=xr(e,sr);for(let i of t.memberPathRuns??[]){let o=i.status;o!=="starting"&&o!=="executing"&&o!=="running"||Object.assign(i,{status:"failed",error:n,completedAt:r})}}function QC(t,e,r){let n=new Date().toISOString(),i=xr(r,sr);for(let o of e.agentSessions??[])o.state.type==="completed"||o.state.type==="failed"||(o.error=i,o.state={type:"failed",provider:o.provider,error:i,completedAt:n},o.activeItemIds=[],Xa(o,n),Sl(o),Gs(t,o));e.activeAgentSessionId=void 0}function WL(t,e){t.codexTurns??=[];let r=t.codexTurns.find(n=>n.providerTurnId===e.providerTurnId);if(!r){t.codexTurns.push(e);return}Object.assign(r,e)}function VL(t,e){t.codexItems??=[];let r=t.codexItems.find(s=>s.itemId===e.itemId);if(!r){t.codexItems.push(sw(e));return}let n=e.type==="commandExecution"&&e.commandActions===void 0&&r.commandActions!==void 0,i=r.startedAt??e.startedAt,o=e.completedAt??r.completedAt;Object.assign(r,{itemId:e.itemId,providerThreadId:e.providerThreadId??r.providerThreadId,providerTurnId:e.providerTurnId??r.providerTurnId,type:e.type,status:e.status,title:n?r.title:e.title,detail:e.detail??r.detail,text:e.text??r.text,summary:e.summary??r.summary,content:e.content??r.content,command:e.command??r.command,cwd:e.cwd??r.cwd,commandActions:e.commandActions??r.commandActions,output:e.output??r.output,changes:e.changes??r.changes,rawItem:e.rawItem??r.rawItem,durationMs:JH(KH(i,o,e.durationMs,r.durationMs)),startedAt:i,completedAt:o,updatedAt:e.updatedAt}),sw(r)}function Cfe(t,e){t.activeItemIds??=[],t.activeItemIds.includes(e)||t.activeItemIds.push(e)}function GL(t,e,r,n,i,o){let s=o?new Date(o).toISOString():new Date().toISOString();return{itemId:t,providerThreadId:n,providerTurnId:i,type:e.type,status:r,title:ZC(e),detail:_fe(e),text:e.text,summary:e.summary,content:e.content,command:e.command,cwd:e.cwd,commandActions:e.commandActions,output:e.aggregatedOutput,changes:e.changes,rawItem:e,durationMs:e.durationMs,...r==="started"?{startedAt:s}:{completedAt:s},updatedAt:s}}function Pfe(t,e){t.codexItems??=[];let r=t.codexItems.find(o=>o.itemId===e.itemId),n=new Date().toISOString();r||(r={itemId:e.itemId,providerThreadId:e.providerThreadId,providerTurnId:e.providerTurnId,type:QH(e.deltaKind),status:"streaming",title:ZH(e.deltaKind),updatedAt:n},t.codexItems.push(r)),r.status=r.status==="completed"?"completed":"streaming",r.updatedAt=n;let i=xr(e.delta,sr);switch(e.deltaKind){case"agentMessage":r.text=xr(`${r.text??""}${i}`,sr);break;case"plan":r.text=xr(`${r.text??""}${i}`,sr);break;case"reasoningText":r.content=Pu(ow(r.content,i,e.contentIndex));break;case"reasoningSummary":r.summary=Pu(ow(r.summary,i,e.contentIndex));break;case"commandOutput":case"fileChangeOutput":r.output=xr(`${r.output??""}${i}`,sr);break}sw(r),t.liveStatus=Bfe(e)}function ow(t,e,r){let n=[...t??[]],i=r??Math.max(n.length-1,0);return n[i]=`${n[i]??""}${e}`,n}function QH(t){switch(t){case"agentMessage":return"agentMessage";case"plan":return"plan";case"reasoningText":case"reasoningSummary":return"reasoning";case"fileChangeOutput":return"fileChange";case"commandOutput":return"commandExecution"}}function ZH(t){switch(t){case"agentMessage":return"Assistant";case"plan":return"Planning";case"reasoningText":case"reasoningSummary":return"Reasoning";case"fileChangeOutput":return"Applying file changes";case"commandOutput":return"Running command"}}function ZC(t){switch(t.type){case"userMessage":return"Prompt";case"agentMessage":return"Assistant";case"reasoning":return"Reasoning";case"plan":return"Plan";case"commandExecution":return eU(t)?"Exploring":"Running command";case"fileChange":return"File changes";case"mcpToolCall":return t.server&&t.tool?`Tool ${t.server}.${t.tool}`:"Tool call";case"webSearch":return"Web search";default:return t.type}}function _fe(t){switch(t.type){case"commandExecution":return Tfe(t);case"fileChange":return Dfe(t.changes);case"mcpToolCall":return t.server&&t.tool?`${t.server}.${t.tool}`:void 0;case"webSearch":return t.query;case"plan":case"userMessage":case"agentMessage":return t.text;case"reasoning":return[...t.summary??[],...t.content??[]].join(`
240
+ `);default:return}}function Tfe(t){let e=t.commandActions?.[0];if(!e)return t.command;switch(e.type){case"read":return e.path??e.name??t.command;case"listFiles":return e.path??t.command;case"search":return[e.query,e.path].filter(Boolean).join(" in ")||t.command;case"unknown":return e.command??t.command}}function Dfe(t){if(Array.isArray(t))return t.map(e=>typeof e=="object"&&e!==null&&"path"in e?String(e.path):void 0).filter(Boolean).join(", ")}function eU(t){let e=t?.commandActions;return!!(e&&e.length>0&&e.every(r=>r.type==="read"||r.type==="listFiles"||r.type==="search"))}function tU(t,e){let r=new Date().toISOString();return t?t.type==="reasoning"||t.type==="plan"?{phase:"thinking",headline:t.type==="plan"?"Planning":"Reasoning",detail:t.detail,itemId:t.itemId,providerTurnId:t.providerTurnId,updatedAt:r}:t.type==="commandExecution"&&eU(t)?{phase:"exploring",headline:t.status==="completed"?"Explored":"Exploring",detail:t.detail,itemId:t.itemId,providerTurnId:t.providerTurnId,updatedAt:r}:t.type==="commandExecution"||t.type==="mcpToolCall"||t.type==="webSearch"?{phase:"running",headline:t.title,detail:t.detail,itemId:t.itemId,providerTurnId:t.providerTurnId,updatedAt:r}:{phase:"working",headline:t.title,detail:t.detail,itemId:t.itemId,providerTurnId:t.providerTurnId,updatedAt:r}:{phase:"working",headline:e==="completed"?"Working":"Starting",updatedAt:r}}function Bfe(t){let e=new Date().toISOString();switch(t.deltaKind){case"reasoningText":case"reasoningSummary":return{phase:"thinking",headline:"Reasoning",detail:Ka(t.delta.trim(),160),itemId:t.itemId,providerTurnId:t.providerTurnId,updatedAt:e};case"commandOutput":return{phase:"running",headline:"Running command",detail:Ka(t.delta.trim(),160),itemId:t.itemId,providerTurnId:t.providerTurnId,updatedAt:e};case"fileChangeOutput":return{phase:"working",headline:"Applying file changes",detail:Ka(t.delta.trim(),160),itemId:t.itemId,providerTurnId:t.providerTurnId,updatedAt:e};case"plan":return{phase:"thinking",headline:"Planning",detail:Ka(t.delta.trim(),160),itemId:t.itemId,providerTurnId:t.providerTurnId,updatedAt:e};case"agentMessage":return{phase:"working",headline:"Responding",itemId:t.itemId,providerTurnId:t.providerTurnId,updatedAt:e}}}function Nfe(t){let e=t.activeItemIds??[],r=(t.codexItems??[]).find(n=>e.includes(n.itemId));return r?tU(r,r.status):{phase:So(t.status)?"working":"idle",headline:So(t.status)?"Working":"Idle",updatedAt:new Date().toISOString()}}async function rU(t,e,r,n){let i=r.runs[t.runId];if(!i||i.status==="stopped")return;let o=i.maxAttemptCount??tP(t.maxAttemptCount);i.maxAttemptCount=o,i.memberEvaluations??=[];let s=Sp((i.attemptCount??0)+1,"attempt");i.attemptCount=s,i.updatedAt=new Date().toISOString(),Br(r,i);let a={...t,attemptOrdinal:s,maxAttemptCount:o,previousMemberOutputs:i.memberEvaluations?.map(l0),repositoryPath:i.worktree?.path??t.repositoryPath,worktreeHash:i.worktree?.worktreeHash??t.worktreeHash,conversationRef:i.conversationRef??t.conversationRef};await p0(a.repositoryPath,a.harness,{phase:"team",apmSkillRegistryClient:n.apmSkillRegistryClient});let c=n.resumeProviderThreadId;n.resumeProviderThreadId=void 0;let u=pw(r,i,{kind:"TeamPlan",runId:i.runId,executeId:i.executeId,attempt:s}),d;try{d=await gw(e,i.runId,r,u.sessionId,()=>c?e.resumeRun({...a,providerThreadId:c}):e.runTeamPlanning(a))}catch(v){throw Cu(r,i,u.sessionId,v),v}if(!So(i.status))return;if(i.providerTeamThreadId=d.providerThreadId??i.providerTeamThreadId,i.providerTeamPlanningTurnId=d.providerTurnId??i.providerTeamPlanningTurnId,i.providerThreadId=d.providerThreadId??i.providerThreadId,f0(i,d.providerTurnId),hw(r,i,u,d,i.updatedAt),i.conversationRef?.provider==="codex"&&d.providerThreadId&&(i.conversationRef={...i.conversationRef,threadId:jt(Ee(d.providerThreadId,"conversation.threadId"))}),i.finalResponse=d.finalResponse,i.updatedAt=new Date().toISOString(),Br(r,i),!d.finalResponse)throw Cu(r,i,u.sessionId,"Team planning completed without a ExecutionPlan"),Hg(wt("team_output_invalid","Team planning completed without a ExecutionPlan"));let l;try{l=tl(HA(d.finalResponse))}catch(v){throw Cu(r,i,u.sessionId,v),v}let f=i.worktree?.path??n.cwd,p=i.pathCommits?.PrevMove??Gfe(f,i.worktree);i.pathCommits={PrevMove:p},i.currentExecution=l,i.executionPlanPlan=void 0,i.terminalMemberPathId=void 0,i.terminalPathCommit=void 0,i.updatedAt=new Date().toISOString(),AL(f,l);let g=db({cwd:f,runId:i.runId,pathId:"current-execution.plan",executorId:"team",goal:"Materialize current ExecutionPlan.",requires:"PrevMove",paths:[Xi]});for(i.pathCommits["current-execution.plan"]=g.commitSha,mw(r,i,u.sessionId,d.finalResponse,i.updatedAt),Br(r,i);So(i.status);){let v=await eP(l,{attempt:s,attemptInput:a,currentExecution:l,runner:e,state:r,run:i,worktreeCwd:f,options:n});if(!So(i.status))return;if(v.type==="next"){if(l=v.execution,i.currentExecution=l,AL(f,l),v.terminalPath)HC(i,v.terminalPath,v.finalResponse??"",f,r);else{let Ce=db({cwd:f,runId:i.runId,pathId:"current-execution.next",executorId:"team",goal:"Materialize next ExecutionPlan.",requires:"PrevMove",paths:[Xi]});i.pathCommits??={},i.pathCommits["current-execution.next"]=Ce.commitSha}i.updatedAt=new Date().toISOString(),Br(r,i);continue}if(v.type==="fail"){CL(f),v.terminalPath&&HC(i,v.terminalPath,v.finalResponse??v.reason.message,f,r),await EP(v.reason.message,kP(i),r,{cwd:n.cwd,persist:n.persist,runId:i.runId,summary:"ExecutionPlan failed"});return}CL(f),v.terminalPath&&HC(i,v.terminalPath,v.finalResponse??"",f,r);let b=v.terminalPath;if(!b)throw Hg(wt("terminal_output_missing","ExecutionPlan completed without a terminal Path"));let C=i.memberPathRuns?.filter(Ce=>Ce.attempt===s&&Ce.pathId===b.id).at(-1),D=C&&"commit"in C?C.commit:void 0;D&&(i.terminalMemberPathId=b.id,i.terminalPathCommit=D,i.updatedAt=new Date().toISOString(),Br(r,i));let _=C&&"finalResponse"in C?C.finalResponse:void 0,F=tl(WM(_??v.finalResponse)),he=Ffe({finalResponse:F,run:i,terminalPath:b,terminalPathRun:C}),z={...he,terminalPathId:b.id,terminalPathCommit:D,attempt:s,at:new Date().toISOString()};i.memberEvaluations.push(z),i.currentExecution=void 0,i.updatedAt=z.at,Br(r,i),await Jfe(he,r,{cwd:n.cwd,persist:n.persist,runId:i.runId,runner:e});return}}async function eP(t,e){switch(t.kind){case"queue":{let[r]=t.items;if(!r)return{type:"done"};let n=await eP(r,e);if(n.type==="fail")return n;let i=n.type==="next"?n.execution:void 0,o=OM(t,i);return o?{type:"next",execution:o,terminalPath:n.terminalPath,finalResponse:n.finalResponse}:{type:"done",terminalPath:n.terminalPath,finalResponse:n.finalResponse}}case"goal":return Ofe(t,e);case"continuation":{let r=await eP(t.execution,{...e,attemptInput:{...e.attemptInput,teamScopeId:t.teamScopeId}});return r.type==="fail"?r:r.type==="next"?{type:"next",execution:{...t,execution:r.execution},terminalPath:r.terminalPath,finalResponse:r.finalResponse}:r.terminalPath?t.continuation?{type:"next",execution:{...t.continuation,requires:[r.terminalPath.id]},terminalPath:r.terminalPath,finalResponse:r.finalResponse}:{type:"done",terminalPath:r.terminalPath,finalResponse:r.finalResponse}:{type:"fail",reason:wt("terminal_output_missing",`Nested Team ${t.id} completed without a terminal Path`),finalResponse:r.finalResponse}}}}async function Ofe(t,e){if(t.stage==="needs_execution")return Mfe(t,e);if(!t.evaluator)return nU(t,e,t.assignee.goal,t.requires,"done");let r=UA(t,"evaluator",oU(e.run,t.id,"evaluate"),t.requires),n=await iU(r,e,{outputSchema:L8}),i=tl(NM(n.finalResponse));return i.type==="pass"?{type:"done",terminalPath:r,finalResponse:i.summary||n.finalResponse}:t.remainingAttempts<1?{type:"fail",reason:wt("max_attempts_exhausted",i.reason,{feedback:i.feedback}),terminalPath:r,finalResponse:n.finalResponse}:{type:"next",execution:{...t,stage:"needs_execution",evaluationPathId:r.id,evaluation:i,requires:[r.id]},terminalPath:r,finalResponse:n.finalResponse}}async function Mfe(t,e){let r=[t.evaluation.nextGoal??t.assignee.goal,"","Evaluator feedback:",t.evaluation.feedback].join(`
241
+ `).trim(),n=await nU(t,e,r,t.requires,"next");if(n.type==="next"&&n.execution.kind!=="goal")return n;let i=n.terminalPath;if(!i)return n;let o=sU(t.remainingAttempts-1);return{type:"next",execution:{kind:"goal",stage:"needs_evaluation",id:t.id,assignee:{...t.assignee,goal:t.evaluation.nextGoal??t.assignee.goal},evaluator:t.evaluator,remainingAttempts:o,requires:[i.id]},terminalPath:i,finalResponse:n.finalResponse}}async function nU(t,e,r,n,i){let o=Hfe(e,t.assignee.executorId);if(o?.kind==="team"){let u=await Lfe(o.id,r,e);return i==="next"?{type:"next",execution:{kind:"continuation",id:`${t.id}.${o.id}.continuation`,teamScopeId:o.id,execution:u,continuation:{kind:"goal",stage:"needs_evaluation",id:t.id,assignee:{...t.assignee,goal:r},evaluator:t.evaluator,remainingAttempts:sU(t.remainingAttempts-1),requires:[]}}}:{type:"next",execution:{kind:"continuation",id:`${t.id}.${o.id}.continuation`,teamScopeId:o.id,execution:u}}}let s={...t,assignee:{...t.assignee,goal:r}},a=UA(s,"assignee",oU(e.run,t.id,"execute"),n),c=await iU(a,e);return{type:i,terminalPath:a,finalResponse:c.finalResponse,execution:i==="next"?s:void 0}}async function Lfe(t,e,r){let n=Ufe(r),i=Xd(n,t),o={...r.attemptInput,requestGoal:e,harness:i,harnessGraph:n,teamScopeId:t,previousMemberOutputs:r.run.memberEvaluations?.map(l0)};await p0(r.worktreeCwd,i,{phase:"team",apmSkillRegistryClient:r.options.apmSkillRegistryClient});let s=pw(r.state,r.run,{kind:"TeamPlan",runId:r.run.runId,executeId:r.run.executeId,attempt:r.attempt});try{let a=await gw(r.runner,r.run.runId,r.state,s.sessionId,()=>r.runner.runTeamPlanning(o));if(r.run.providerTeamThreadId=a.providerThreadId??r.run.providerTeamThreadId,r.run.providerTeamPlanningTurnId=a.providerTurnId??r.run.providerTeamPlanningTurnId,r.run.providerThreadId=a.providerThreadId??r.run.providerThreadId,f0(r.run,a.providerTurnId),hw(r.state,r.run,s,a,r.run.updatedAt),!a.finalResponse)throw Cu(r.state,r.run,s.sessionId,`Team ${t} planning completed without a ExecutionPlan`),Hg(wt("team_output_invalid",`Team ${t} planning completed without a ExecutionPlan`));let c=tl(HA(a.finalResponse));return mw(r.state,r.run,s.sessionId,a.finalResponse,new Date().toISOString()),c}catch(a){throw Cu(r.state,r.run,s.sessionId,a),a}}function Hfe(t,e){let r=t.attemptInput.harnessGraph;if(!r)return;let n=t.attemptInput.teamScopeId??r.rootTeamId,i=DS(r,n);if(!i||i.kind!=="team")throw new Error(`Harness Team scope is unavailable: ${n}`);if(!i.members.some(s=>s.executorId===e))throw new Error(`Team ${n} cannot delegate to Executor ${e}; it is not a direct Membership`);let o=DS(r,e);if(!o)throw new Error(`Team ${n} references unknown Executor ${e}`);return o}function Ufe(t){let e=t.attemptInput.harnessGraph;if(!e)throw new Error("Nested Team delegation requires a Harness Executor graph");return e}async function iU(t,e,r={}){let n=[],i=pw(e.state,e.run,{kind:"ExecutionPlan",runId:e.run.runId,executeId:e.run.executeId,attempt:e.attempt,pathId:t.id,executorId:t.executorId}),o={pathId:t.id,executorId:t.executorId,goal:t.goal,requires:t.requires,attempt:e.attempt,agentSessionId:i.sessionId,status:"starting",dependencyPathIds:t.requires==="PrevMove"?[]:t.requires,dependencyOutputs:n,startedAt:new Date().toISOString()};e.run.memberPathRuns??=[],e.run.memberPathRuns.push(o),e.run.updatedAt=o.startedAt,Br(e.state,e.run);let s=$fe(e),a=s?rp(s,t.executorId):void 0,c=a?.modelSelection?await IP(LH(e.run,a.modelSelection),{providerInventory:e.options.providerInventory},a.modelSelection):void 0,u={...e.attemptInput,board:rr(e.state,{cwd:e.options.cwd,persist:e.options.persist}),harness:s,resolvedModelSelection:c?.provider??e.attemptInput.resolvedModelSelection,memberPath:t,dependencyOutputs:n,worktreeStatus:cU(e.worktreeCwd),worktreeDiff:zfe(e.worktreeCwd),attemptTranscript:Kfe(e.run.debugEvents),outputSchema:r.outputSchema};try{await p0(e.worktreeCwd,s,{phase:"member",executorId:t.executorId,apmSkillRegistryClient:e.options.apmSkillRegistryClient});let d=await gw(e.runner,e.run.runId,e.state,i.sessionId,()=>e.runner.runMemberPath(u));if(!So(e.run.status))return{pathRun:o,finalResponse:""};e.run.providerMemberThreadId=d.providerThreadId??e.run.providerMemberThreadId,e.run.providerThreadId=d.providerThreadId??e.run.providerThreadId,f0(e.run,d.providerTurnId);let l=kfe(o)??hw(e.state,e.run,i,d)??Rfe(d,t.id),f=d.finalResponse??"";Sle(e.worktreeCwd);let p=new Date().toISOString();return Object.assign(o,{status:"completed",session:l,finalResponse:f,completedAt:p}),mw(e.state,e.run,i.sessionId,f,p),e.run.updatedAt=p,Br(e.state,e.run),{pathRun:o,finalResponse:f}}catch(d){let l=new Date().toISOString();throw Object.assign(o,{status:"failed",error:d instanceof Error?d.message:String(d),completedAt:l}),Cu(e.state,e.run,i.sessionId,d,l),e.run.updatedAt=l,Br(e.state,e.run),d}}function $fe(t){let e=t.attemptInput.harnessGraph;return e?Xd(e,t.attemptInput.teamScopeId??e.rootTeamId):t.attemptInput.harness}function HC(t,e,r,n,i){let o=[...t.memberPathRuns??[]].reverse().find(a=>a.pathId===e.id),s=db({cwd:n,runId:t.runId,pathId:e.id,executorId:e.executorId,goal:e.goal,requires:e.requires});t.pathCommits??={},t.pathCommits[e.id]=s.commitSha,o&&Object.assign(o,{status:"completed",finalResponse:r,commit:s.commitSha,parentCommit:s.parentSha,treeChanged:s.treeChanged,completedAt:new Date().toISOString()}),t.updatedAt=new Date().toISOString(),Br(i,t)}function oU(t,e,r){return`${e}.${r}.${(t.memberPathRuns?.length??0)+1}`}function sU(t){return Number.isInteger(t)&&t>0?t:0}function Ffe(t){let e=t.terminalPathRun,r=e&&"session"in e?e.session:void 0,n=e&&"commit"in e?e.commit:void 0,i=e&&"treeChanged"in e?e.treeChanged:void 0,o=Ka(ope(t.finalResponse)??`Completed terminal Path ${t.terminalPath.id}`,240),s=[`Terminal Path ${t.terminalPath.id} completed`,n?`Terminal Path commit ${n}`:void 0,i===void 0?void 0:`Terminal Path tree changed: ${i?"yes":"no"}`,r?`Terminal Path session ${r.providerThreadId}/${r.providerTurnId}`:void 0,t.run.selectedDestinationIds.length===1?`Selected Destination: ${t.run.selectedDestinationIds[0]}`:void 0].filter(a=>!!(a&&a.trim()));return{summary:o,evidence:s,risks:[]}}function jfe(t,e,r){let n=r.runs[t];n&&n.status!=="stopped"&&(n.error=e instanceof Error?e.message:String(e),QC(r,n,n.error),Ya(n,"failed"),Br(r,n))}async function aU(t,e,r,n){let i=r.runs[t];if(!i||i.status==="stopped"||i.status==="arrived"||i.status==="accident")return;let o=e instanceof Error?e.message:String(e);i.error=o,QC(r,i,o);try{await EP(o,[`runner error: ${o}`,...kP(i)],r,{cwd:n.cwd,persist:n.persist,runId:t,summary:"Execute failed during execution"})}catch(s){i.error=`${o}; failed to record Accident: ${s instanceof Error?s.message:String(s)}`,QC(r,i,i.error),Ya(i,"failed"),Br(r,i)}}function tP(t){if(t===void 0)return Sp(5,"maxAttemptCount");if(!Number.isInteger(t)||t<1)throw new Error("maxAttemptCount must be a positive integer");return Sp(t,"maxAttemptCount")}function qfe(t){switch(t.kind){case"team_execution_plan":return tP(t.maxAttemptCount);case"role_squad":case"council_vote":case"court_debate":return tP(t.maxRoundCount)}}function Wfe(t){let e=kp(t.board,t.run.requestId),r=CP(t.board,t.run.lineId),n=Rp(t.board,t.run.lineId),i=Du(t.board,t.run.lineId).filter(Qa);return{runId:t.run.runId,executeId:t.run.executeId,repositoryPath:t.cwd,worktreeHash:t.run.worktree?.worktreeHash,sourceMoveId:t.run.sourceMoveId,targetMoveOrdinal:t.run.targetMoveOrdinal,requestGoal:e.goal,teamName:r.teamName??n?.teamName,harness:n?.harness,harnessLock:t.run.harnessLock??n?.harnessLock,activeDestinations:i,selectedDestinationIds:t.run.selectedDestinationIds,futureConstraints:t.board.futureConstraints.filter(o=>o.lineId===t.run.lineId).map(o=>o.constraint),attemptOrdinal:t.run.attemptCount,maxAttemptCount:t.run.maxAttemptCount,previousMemberOutputs:t.run.memberEvaluations?.map(l0),conversationRef:t.run.conversationRef,board:t.board,moveId:t.moveId,sourceMoveCommit:t.sourceMoveCommit,terminalPathCommit:t.terminalPathCommit,terminalMemberPathId:t.run.terminalMemberPathId,pathCommits:t.run.pathCommits??{},pathOutputs:Vfe(t.run),completionSummary:t.completion.summary,diffStat:UC(t.cwd,t.sourceMoveCommit,t.terminalPathCommit,"stat"),diffNameStatus:UC(t.cwd,t.sourceMoveCommit,t.terminalPathCommit,"name-status"),diffPatch:UC(t.cwd,t.sourceMoveCommit,t.terminalPathCommit,"patch")}}function Vfe(t){return(t.memberPathRuns??[]).filter(e=>e.status==="completed").map(e=>({pathId:e.pathId,executorId:e.executorId,goal:e.goal,commit:e.commit,finalResponse:e.finalResponse}))}function UC(t,e,r,n){try{return n==="stat"?Re(["diff","--stat",e,r],{cwd:t}).trim():n==="name-status"?Re(["diff","--name-status",e,r],{cwd:t}).trim():Ka(Re(["diff",e,r,"--","."],{cwd:t}),16e3).trim()}catch(i){return`diff unavailable: ${i instanceof Error?i.message:String(i)}`}}function Gfe(t,e){return e?.baseRef&&e.baseRef!=="virtual"?Xr(Re(["rev-parse","--verify",`${e.baseRef}^{commit}`],{cwd:t}).trim()):Xr(xP(t))}function cU(t){try{let e=Xn(t),r=e.changes.map(n=>`${n.status} ${n.path}`).join(`
242
+ `);return[`root: ${e.root}`,`branch: ${e.branch}`,`clean: ${e.clean}`,"changes:",r||"- none"].join(`
243
+ `)}catch(e){return`status unavailable: ${e instanceof Error?e.message:String(e)}`}}function zfe(t){try{let e=Re(["diff","--stat"],{cwd:t}).trim(),r=Re(["diff","--cached","--stat"],{cwd:t}).trim(),n=Re(["diff","--","."],{cwd:t}),i=Re(["diff","--cached","--","."],{cwd:t});return Ka([e?`Unstaged stat:
244
+ ${e}`:"",r?`Staged stat:
245
+ ${r}`:"",n?`Unstaged diff:
246
+ ${n}`:"",i?`Staged diff:
247
+ ${i}`:""].filter(Boolean).join(`
248
+
249
+ `),12e3)||"No worktree diff."}catch(e){return`diff unavailable: ${e instanceof Error?e.message:String(e)}`}}function Kfe(t){return Ka(t.slice(-40).map(e=>e.type==="runner.final"?`${e.type}: ${e.finalResponse}`:e.type==="runner.error"?`${e.type}: ${e.error}`:e.type==="runner.status.changed"?`${e.type}: ${e.headline}${e.detail?` - ${e.detail}`:""}`:e.type==="runner.turn.started"||e.type==="runner.turn.completed"?`${e.type}: ${e.providerTurnId??"unknown turn"}`:e.type==="runner.item.started"||e.type==="runner.item.completed"?`${e.type}: ${e.item.type} ${e.itemId}`:e.type==="runner.item.delta"?`${e.type}: ${e.deltaKind} ${Ka(e.delta,200)}`:e.type==="runner.appServer.message"?`${e.type}: ${e.direction} ${e.method??"unknown"}`:"unknown runner event").join(`
250
+ `),8e3)}function l0(t){return[`attempt ${t.attempt}`,`summary: ${t.summary}`,t.terminalPathId?`terminalPath: ${t.terminalPathId}`:void 0,t.terminalPathCommit?`terminalCommit: ${t.terminalPathCommit}`:void 0,`evidence: ${t.evidence.join("; ")||"none"}`,`risks: ${t.risks.join("; ")||"none"}`].filter(e=>e!==void 0).join(" | ")}function kP(t){let e=t.memberEvaluations??[],r=e.flatMap(n=>n.evidence);return[`attempts: ${t.attemptCount??0}/${t.maxAttemptCount??5}`,...e.map(l0),...r].filter((n,i,o)=>n.trim()!==""&&o.indexOf(n)===i)}async function Jfe(t,e,r){try{await Xle(t,e,r);return}catch(n){let i=n instanceof Error?n.message:String(n),o=Xfe(i);if(!o)throw n;let s=bl(e,r.runId,r.cwd);await EP(o,[o,...kP(s),cU(s.worktree?.path??r.cwd)],e,{cwd:r.cwd,persist:r.persist,runId:s.runId,summary:"Path completion could not be recorded"})}}function Xfe(t){if(t==="Cannot auto-record MOVE without worktree changes")return"Terminal Path completed, but Studio could not record Arrived MOVE because the Route worktree had no product file changes.";if(t==="Cannot auto-record MOVE when the Team changed Hunsu control-plane files")return"Terminal Path completed, but Studio declined Arrived MOVE because the Execute changed Hunsu control-plane files."}function Ka(t,e){return t.length<=e?t:`${t.slice(0,e)}
251
+ ...[truncated]`}function xr(t,e){if(Buffer.byteLength(t,"utf8")<=e)return t;let r=Buffer.byteLength(rw,"utf8"),n=Math.max(0,e-r),i=0,o=t.length,s=0;for(;i<=o;){let a=Math.floor((i+o)/2),c=t.slice(0,a);Buffer.byteLength(c,"utf8")<=n?(s=a,i=a+1):o=a-1}return`${t.slice(0,s)}${rw}`}function jr(t,e){return t===void 0?void 0:xr(t,e)}function Pu(t,e=js){return t?.map(r=>xr(r,e))}function yw(t){try{return Buffer.byteLength(JSON.stringify(t)??"null","utf8")}catch{return Number.MAX_SAFE_INTEGER}}function rP(t,e,r){for(t.length>e&&t.splice(0,t.length-e);t.length>0&&yw(t)>r;)t.shift()}function bp(t,e=sr,r=0){if(typeof t=="string")return xr(t,e);if(t==null||typeof t!="object")return t;if(r>=8)return`...${rw}`;if(Array.isArray(t)){let o=t.slice(0,200).map(s=>bp(s,e,r+1));return t.length>o.length&&o.push(`...${rw}`),o}let n={},i=Object.entries(t);for(let[o,s]of i.slice(0,200))n[o]=bp(s,e,r+1);return i.length>200&&(n.__truncated=!0),n}function RP(t){return bp(t,js)}function uU(t){return{...t,method:jr(t.method,js),providerThreadId:jr(t.providerThreadId,js),providerTurnId:jr(t.providerTurnId,js),message:bp(t.message,js)}}function sw(t){return t.title=xr(t.title,js),t.detail=jr(t.detail,sr),t.text=jr(t.text,sr),t.summary=Pu(t.summary),t.content=Pu(t.content),t.command=jr(t.command,sr),t.cwd=jr(t.cwd,js),t.output=jr(t.output,sr),t.changes=bp(t.changes),t.rawItem=void 0,t}function AP(t){return t.title=xr(t.title,js),t.text=jr(t.text,sr),t.summary=Pu(t.summary),t.content=Pu(t.content),t.command=jr(t.command,sr),t.cwd=jr(t.cwd,js),t.output=jr(t.output,sr),t.changes=bp(t.changes),t}function Sl(t){for(t.finalResponse=jr(t.finalResponse,sr),t.error=jr(t.error,sr),t.messages.forEach(AP);t.messages.length>0&&yw(t.messages)>fue;){let e=t.messages.findIndex(r=>!t.activeItemIds.includes(r.itemId));t.messages.splice(e>=0?e:0,1)}}function Yfe(t){for(t.forEach(sw);t.length>0&&yw(t)>due;)t.shift()}function Qfe(t){for(let e of t)e.text=xr(e.text,sr);for(;t.length>0&&yw(t)>lue;)t.shift()}function s0(t){t.debugEvents??=[],t.rawAppServerMessages??=[],t.codexItems??=[],t.agentSessions??=[],t.assistantTranscript??=[];for(let e=0;e<t.debugEvents.length;e+=1)t.debugEvents[e]=RP(t.debugEvents[e]);for(let e=0;e<t.rawAppServerMessages.length;e+=1)t.rawAppServerMessages[e]=uU(t.rawAppServerMessages[e]);rP(t.debugEvents,cue,uue),rP(t.rawAppServerMessages,eH,tH),Yfe(t.codexItems),Qfe(t.assistantTranscript),t.agentSessions.forEach(Sl)}function Ya(t,e){t.status=e,t.updatedAt=new Date().toISOString(),(e==="failed"||e==="accident")&&Afe(t,t.error??nP(e)),So(e)||(t.activeItemIds=[],t.liveStatus={phase:"idle",headline:nP(e),detail:t.error,updatedAt:t.updatedAt})}function f0(t,e){e&&(t.providerTurnIds??=[],t.providerTurnIds.includes(e)||t.providerTurnIds.push(e))}function So(t){return t==="running"||t==="paused"}function nP(t){switch(t){case"running":return"Executing";case"paused":return"Paused";case"arrived":return"Arrived";case"accident":return"Accident";case"failed":return"Failed";case"discarded":return"Discarded";case"finished":return"Finished";case"stopped":return"Stopped"}}function Zfe(t,e){try{return Re(["rev-parse","--verify","HEAD"],{cwd:t}).trim()}catch{return e?.baseRef&&e.baseRef!=="virtual"?e.baseRef:"uncommitted"}}function kp(t,e){let r=e?t.requests.find(n=>n.id===e):t.requests[0];if(!r)throw new Error(e?`Unknown request: ${e}`:"No request exists");return r}function dU(t,e,r){let n=t.lines.filter(o=>o.requestId===e),i=r?t.lines.find(o=>o.id===r):n.findLast(o=>o.status==="active")??n.at(-1);if(!i)throw new Error(r?`Unknown line: ${r}`:`No line exists for request: ${e}`);return i}function CP(t,e){let r=t.lines.find(n=>n.id===e);if(!r)throw new Error(`Unknown line: ${e}`);return r}function epe(t,e){return t.lines.find(r=>String(r.currentNodeId)===String(e.id)||String(r.rootNodeId)===String(e.id)||!!(e.lineId&&String(e.lineId)===String(r.id)))}function PP(t,e){let r=e.source;return r.type==="move"?t.moves.find(n=>n.id===r.moveId):t.moves.find(n=>n.toNodeId===e.id)}function lU(t){let e=TS(t);if(!e.ok)throw new Error(e.error.message);return e.value}function fU(t){return`conv_${ui(ci("sha256").update(JSON.stringify(t))).slice(0,16)}`}function pU(t,e,r){return ui(ci("sha256").update(JSON.stringify({requestId:e.requestId,nodeId:e.id,ordinal:e.ordinal,destinations:e.destinations.map(n=>[n.id,n.title,n.status]),harness:e.harness,lineCount:t.lines.length,moveCount:t.moves.length,hunsuCount:t.hunsus.length,message:r})))}function tpe(t){try{let e=Xn(t);return ui(ci("sha256").update(JSON.stringify(e)))}catch{return}}function rpe(t,e,r){let i=[...(r?wp(t,r):Object.values(t.runs)).map(o=>o.executeId??o.runId),...e.moves.flatMap(o=>o.executeId?[String(o.executeId)]:[]),...ipe(r)].reduce((o,s)=>{let a=s.match(/^F(\d+)$/i);return a?Math.max(o,Number(a[1])):o},0);return`F${String(i+1).padStart(4,"0")}`}function npe(t){return t.roadmapId?`${t.roadmapId}:${t.executeId}:${t.lineId}`:t.lineId}function ipe(t){if(!t)return[];try{let e=qt(t);return Re(["for-each-ref","--format=%(refname:short)","refs/heads/hunsu/routes"],{cwd:e}).trim().split(/\r?\n/).map(r=>r.trim().split("/").at(-1)??"").filter(Boolean)}catch{return[]}}function mU(t,e,r){let n=ui(ci("sha256").update(JSON.stringify({cwd:t,executeId:e,createdAt:r}))).slice(0,16);return{worktreeHash:jt(zd(n)),path:jt(Ee(t,"worktree.path")),branch:jt(Ee(`virtual/${e}`,"worktree.branch")),baseRef:jt(Ee("virtual","worktree.baseRef")),createdAt:r}}function ope(t){return t.split(/\r?\n/).map(e=>e.trim()).find(e=>e.length>0)}function hU(t){return`${t.teamName??"Team"} MOVE ${t.ordinal}`}function gU(t,e){let r=t&&t.length>0?t:e;if(r.length!==1)throw new Error("MOVE completion requires exactly one Destination");return[r[0]]}function yU(t){let e=spe(t.filter(Qa));return e?[String(e.id)]:[]}function spe(t){return[...t].sort(ape)[0]}function ape(t,e){return(e.priority??0)-(t.priority??0)}function cpe(t,e,r,n,i){if(!r.summary.trim())throw new Error("MOVE completion requires a summary");if(r.evidence.length===0||r.evidence.some(s=>s.trim()===""))throw new Error("MOVE completion requires evidence");if(r.risks&&r.risks.length>0&&!r.approvedRisks)throw new Error("MOVE completion with risks requires explicit approval");for(let s of n){let a=Du(t,e.lineId).find(c=>c.id===s);if(!a)throw new Error(`Unknown Destination: ${s}`);if(a.requestId!==e.requestId)throw new Error(`Destination ${s} does not belong to request ${e.requestId}`);if(!e.selectedDestinationIds.includes(s))throw new Error(`Destination ${s} was not selected for run ${e.runId}`);if(!Qa(a))throw new Error(`Destination ${s} is not open`)}if(!Xn(i).clean)throw new Error("Cannot record MOVE while worktree has uncommitted changes")}function upe(t,e,r,n,i,o={}){if(!r.summary.trim())throw new Error("MOVE completion requires a summary");if(r.evidence.length===0||r.evidence.some(c=>c.trim()===""))throw new Error("MOVE completion requires evidence");for(let c of n){let u=Du(t,e.lineId).find(d=>d.id===c);if(!u)throw new Error(`Unknown Destination: ${c}`);if(u.requestId!==e.requestId)throw new Error(`Destination ${c} does not belong to request ${e.requestId}`);if(!e.selectedDestinationIds.includes(c))throw new Error(`Destination ${c} was not selected for run ${e.runId}`);if(!Qa(u))throw new Error(`Destination ${c} is not open`)}if(o.promotedPathCommit){if(!o.prevMoveCommit)throw new Error("Cannot auto-record MOVE without PrevMove commit for ExecutionPlan promotion");if(!dpe(i,o.prevMoveCommit,o.promotedPathCommit))throw new Error("Cannot auto-record MOVE without worktree changes");lpe(i,o.prevMoveCommit,o.promotedPathCommit);return}let s=Xn(i);if(s.clean)throw new Error("Cannot auto-record MOVE without worktree changes");if(s.changes.find(c=>c.path===".hunsu"||c.path.startsWith(".hunsu/")))throw new Error("Cannot auto-record MOVE when the Team changed Hunsu control-plane files")}function dpe(t,e,r){let n=Re(["rev-parse","--verify",`${e}^{tree}`],{cwd:t}).trim(),i=Re(["rev-parse","--verify",`${r}^{tree}`],{cwd:t}).trim();return n!==i}function lpe(t,e,r){if(Re(["diff","--name-only",`${e}..${r}`,"--",".hunsu"],{cwd:t}).trim())throw new Error("Cannot auto-record MOVE when the Team changed Hunsu control-plane files")}async function p0(t,e,r={}){if(!Qt(t))return;let n=r.executorId&&e?fpe(e,r.executorId):void 0,i=n?bpe(n.skills):[],o=n?wpe(n.plugins??[]):[],s=aw(r.env??process.env,r.home??qs()),a=Ape(t,r.env??process.env,r.home??qs()),c=Ppe(r.env??process.env,r.home??qs()),u=[];if(Epe(t),vpe(t),i.length>0){Ipe(t);let d=at(t,".agents","skills");bo(d,{recursive:!0});for(let l of i){let f=await ppe(l,s,r);if(f.length===0)continue;let p=at(d,kpe(l.name));ype(p);for(let g of f){let v=Rpe(p,g.path);bo(Ci(v),{recursive:!0}),es(v,g.text,"utf8")}es(at(p,uP),`hunsu-managed
252
+ `,"utf8"),u.push(at(p,"SKILL.md"))}}for(let d of o)if(!c.includes(d.id))throw new Error(`Member Codex Environment missing Plugin: ${d.id}`);xpe(t,{enabledSkillPaths:u,disabledSkillPaths:a.map(d=>at(d.sourcePath,"SKILL.md")),enabledPluginIds:o.map(d=>d.id),disabledPluginIds:c})}function fpe(t,e){let r=t.members.find(n=>n.id===e);if(!r)throw new Error(`Member Codex Environment cannot find Member ${e}`);return r}async function ppe(t,e,r){if(t.kind==="skillMeta"){let n=await mpe(t,r),i=JL(n)??[];if(i.length===0)throw new Error(`Member Codex Environment Skill ${t.name} has no readable files after npx skills add`);return i}if(t.kind==="local-root-installed"){let n=gpe(t,e),i=JL(n)??[];if(i.length===0)throw new Error(`Member Codex Environment Skill ${t.name} has no readable files`);return i}return Spe(t,r.apmSkillRegistryClient)}async function mpe(t,e){let r=zce(at(uw(),"hunsu-skill-meta-"));try{await(e.skillMetaInstaller??hpe()).install(t,r,{env:e.env,home:e.home});let o=cw(at(r,".agents","skills")).filter(s=>s.name===t.name);if(o.length===0)throw new Error(`Member Codex Environment missing Skill ${t.name} after npx skills add ${t.source}`);if(o.length>1)throw new Error(`Member Codex Environment Skill ${t.name} is ambiguous after npx skills add ${t.source}`);return o[0]}finally{u0(r,{recursive:!0,force:!0})}}function hpe(t="npx"){return{async install(e,r,n){let i={...process.env,...n.env};n.home&&(i.HOME=n.home,i.USERPROFILE=n.home);try{await QL(t,["--yes","skills","add",e.source,"--skill",e.name,"--agent",e.agent,"--copy","--yes"],{cwd:r,env:i,maxBuffer:2*1024*1024})}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`npx skills add failed for ${e.name}: ${s}`)}}}}function gpe(t,e){if(t.sourcePath){let n=Yn(t.sourcePath),i=e.filter(o=>Yn(o.sourcePath)===n);if(i.length===0)throw new Error(`Member Codex Environment missing Skill ${t.name} at ${t.sourcePath}`);if(i.length>1)throw new Error(`Member Codex Environment Skill ${t.name} is ambiguous at ${t.sourcePath}`);if(i[0].name!==t.name)throw new Error(`Member Codex Environment Skill ${t.sourcePath} resolved as ${i[0].name}, not ${t.name}`);return i[0]}let r=e.filter(n=>n.name===t.name);if(r.length===0)throw new Error(`Member Codex Environment missing Skill: ${t.name}`);if(r.length>1)throw new Error(`Member Codex Environment Skill ${t.name} is ambiguous across local roots`);return r[0]}function ype(t){if(Qt(t)&&!Qt(at(t,uP)))throw new Error(`Member Codex Environment cannot overwrite non-Hunsu Skill folder: ${t}`);u0(t,{recursive:!0,force:!0}),bo(t,{recursive:!0})}function vpe(t){let e=at(t,".agents","skills");if(Qt(e))for(let r of c0(e,{withFileTypes:!0})){if(!r.isDirectory())continue;let n=at(e,r.name);Qt(at(n,uP))&&u0(n,{recursive:!0,force:!0})}}function xpe(t,e){let r=at(t,".codex","config.toml");if(Qt(r)&&!Vs(r,"utf8").startsWith(fL))throw new Error(`Member Codex Environment cannot overwrite non-Hunsu Codex config: ${r}`);bo(Ci(r),{recursive:!0});let n=new Set(e.enabledSkillPaths.map(c=>Yn(c))),i=[...Array.from(n).map(c=>({path:c,enabled:!0})),...Array.from(new Set(e.disabledSkillPaths.map(c=>Yn(c)))).filter(c=>!n.has(c)).map(c=>({path:c,enabled:!1}))].sort((c,u)=>c.path.localeCompare(u.path)),o=new Set(e.enabledPluginIds),s=[...Array.from(o).map(c=>({id:c,enabled:!0})),...Array.from(new Set(e.disabledPluginIds)).filter(c=>!o.has(c)).map(c=>({id:c,enabled:!1}))].sort((c,u)=>c.id.localeCompare(u.id)),a=[fL,"# Generated by Hunsu Bridge for a Route worktree. Do not edit by hand.",""];for(let c of i)a.push("[[skills.config]]",`path = ${zL(c.path)}`,`enabled = ${c.enabled?"true":"false"}`,"");for(let c of s)a.push(`[plugins.${zL(c.id)}]`,`enabled = ${c.enabled?"true":"false"}`,"");es(r,`${a.join(`
253
+ `).trimEnd()}
254
+ `,"utf8")}async function Spe(t,e){if(t.kind==="local-snapshot")return t.snapshotFiles?.map(i=>({...i}))??[];if(t.kind!=="registry-package")throw new Error(`Skill ${t.name} must be resolved before materialization`);let n=await(e??Ede()).fetchSkillFiles(t);if(t.contentHash.startsWith("sha256:")&&wH(n)!==t.contentHash)throw new Error(`APM contentHash mismatch for ${t.package}@${t.version}`);return n.map(i=>({...i}))}function bpe(t){let e=new Set,r=[];for(let n of t){let i=n.kind==="local-root-installed"&&n.sourcePath?`${n.name}\0${Yn(n.sourcePath)}`:n.name;e.has(i)||(e.add(i),r.push(n))}return r}function wpe(t){let e=new Set,r=[];for(let n of t)e.has(n.id)||(e.add(n.id),r.push({...n}));return r}function Ipe(t){vU(t,[".agents/skills/"])}function Epe(t){vU(t,[".agents/skills/",".codex/config.toml"])}function vU(t,e){try{let r=Re(["rev-parse","--git-path","info/exclude"],{cwd:t}).trim(),n=i0(r)?r:at(t,r);bo(Ci(n),{recursive:!0});let i=Qt(n)?Vs(n,"utf8"):"",o=new Set(i.split(/\r?\n/)),s=e.filter(c=>!o.has(c));if(s.length===0)return;let a=i.length>0&&!i.endsWith(`
255
+ `)?`
256
+ `:"";es(n,`${i}${a}${s.join(`
257
+ `)}
258
+ `,"utf8")}catch{}}function zL(t){return JSON.stringify(t)}function kpe(t){let e=t.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!e||e==="."||e==="..")throw new Error(`Invalid Skill name for Codex materialization: ${t}`);return e}function Rpe(t,e){if(!e.trim()||e.includes("\0")||i0(e))throw new Error(`Invalid Skill snapshot file path: ${e}`);let r=aP(e);if(KL(r))throw new Error(`Invalid Skill snapshot file path: ${e}`);let n=at(t,r),i=cP(t,n);if(KL(i)||i0(i))throw new Error(`Invalid Skill snapshot file path: ${e}`);return n}function KL(t){return t===".."||t.startsWith("../")||t.startsWith("..\\")}function aw(t={},e=qs()){return _P([t.CODEX_HOME?at(t.CODEX_HOME,"skills"):void 0,at(e,".codex","skills"),at(e,".agents","skills"),"/etc/codex/skills"]).flatMap(n=>cw(n)).sort((n,i)=>n.name.localeCompare(i.name))}function Ape(t,e={},r=qs()){return Cpe([...aw(e,r),...cw(at(t,".agents","skills")),...cw(at(t,".codex","skills"))])}function cw(t){if(!Qt(t))return[];let e=[],r=n=>{if(Qt(at(n,"SKILL.md"))){e.push(n);return}for(let i of c0(n,{withFileTypes:!0}))!i.isDirectory()||i.name==="node_modules"||i.name===".git"||r(at(n,i.name))};try{r(t)}catch{return[]}return e.flatMap(n=>_pe(n,ts(n)))}function Cpe(t){let e=new Set,r=[];for(let n of t){let i=Yn(n.sourcePath);e.has(i)||(e.add(i),r.push(n))}return r.sort((n,i)=>n.name.localeCompare(i.name)||n.sourcePath.localeCompare(i.sourcePath))}function Ppe(t={},e=qs()){let r=_P([t.CODEX_HOME?at(t.CODEX_HOME,"config.toml"):void 0,at(e,".codex","config.toml")]),n=new Set;for(let i of r){if(!Qt(i))continue;let o=Vs(i,"utf8");for(let s of o.matchAll(/^\s*\[plugins\."([^"]+)"\]\s*$/gm))s[1]?.trim()&&n.add(s[1])}return Array.from(n).sort()}function _pe(t,e){let r=Tpe(t);if(r.length===0)return[];let n=ci("sha256");for(let o of r)n.update(o.path),n.update("\0"),n.update(o.text??""),n.update("\0");let i=ui(n);return[{kind:"local-snapshot",name:jt(Ee(e,"skill.name")),sourcePath:jt(Ee(t,"skill.sourcePath")),contentHash:jt(Ee(i,"skill.contentHash")),snapshotRef:jt(Ee(`codex-skill:${i}`,"skill.snapshotRef")),snapshotFiles:r.filter(o=>typeof o.text=="string").map(o=>({path:jt(Ee(o.path,"skill.snapshotFiles.path")),text:o.text})),files:r}]}function JL(t){if(t.kind==="local-snapshot"&&t.snapshotFiles)return t.snapshotFiles.map(e=>({...e}));if("files"in t)return t.files.filter(e=>typeof e.text=="string").map(e=>({path:jt(Ee(e.path,"skill.snapshotFiles.path")),text:e.text}))}function Tpe(t){let e=[],r=n=>{for(let i of c0(n,{withFileTypes:!0})){let o=at(n,i.name);if(i.isDirectory()){if(i.name==="node_modules"||i.name===".git")continue;r(o);continue}if(!i.isFile())continue;let s=Tu(o),a=cP(t,o),c=s.size<=64e3?Vs(o,"utf8"):void 0;e.push({path:a,size:s.size,text:c})}};return r(t),e.sort((n,i)=>n.path.localeCompare(i.path))}function _P(t){return Array.from(new Set(t.filter(e=>!!e)))}function TP(t){let e=t.moves.reduce((r,n)=>{let i=n.id.match(/^M(\d+)$/i);return i?Math.max(r,Number(i[1])):r},0);return jt(_n(`M${String(e+1).padStart(4,"0")}`))}function Qa(t){return t.status!=="reached"&&t.status!=="canceled"&&t.status!=="superseded"}function Du(t,e){return Rp(t,e)?.destinations??t.destinations.filter(r=>{let n=t.lines.find(i=>i.id===e);return!n||r.requestId===n.requestId})}function Rp(t,e){let r=t.lines.find(n=>n.id===e);return r?.currentNodeId?t.nodes.find(n=>n.id===r.currentNodeId):void 0}function bl(t,e,r){let n=xU(t,e,r);if(!n)throw new Error(`Unknown run: ${e}`);return n}function xU(t,e,r){let n=t.runs[e]??Object.values(t.runs).find(i=>i.runId===e);return r?n&&a0(n,r)?n:void 0:n}function wp(t,e){return Dpe(t,e),Object.values(t.runs).filter(r=>a0(r,e))}function Dpe(t,e){if(!Qt(e))return;let r;try{r=vA(e)}catch(n){if(n instanceof Dr)return;throw n}for(let n of r){let i=Bpe(n.execution),o=t.runs[i]??Object.values(t.runs).find(s=>s.executeId===n.execution.executeId);o&&o.source!=="rehydrated"||(t.runs[i]=Npe(n.execution,e,n.commit))}}function Bpe(t){return`${t.runId}:${t.executeId}`}function Npe(t,e,r){let n=[t.plan.session?.providerTurnId,...t.paths.flatMap(s=>s.session?.providerTurnId?[s.session.providerTurnId]:[]),t.finalizerSession?.providerTurnId].filter(s=>!!s),i=Mpe(t),o=t.completedAt??new Date(0).toISOString();return{runId:t.runId,executeId:t.executeId,lineId:t.lineId,requestId:Lpe(t.lineId),repositoryPath:e,provider:"codex",source:"rehydrated",status:"arrived",selectedDestinationIds:t.selectedDestinationIds,sourceNodeId:t.sourceNodeId,sourceMoveId:t.sourceMoveId,targetMoveOrdinal:t.targetMoveOrdinal,worktree:t.worktree,conversationRef:t.conversationRef,outcome:"arrived",providerThreadId:t.plan.session?.providerThreadId??t.finalizerSession?.providerThreadId,providerTeamThreadId:t.plan.session?.providerThreadId,providerTeamPlanningTurnId:t.plan.session?.providerTurnId,providerFinalizerThreadId:t.finalizerSession?.providerThreadId,providerTurnIds:n,attemptCount:Sp(1,"attempt"),pathCommits:{...t.pathCommits},memberPathRuns:t.paths.map(s=>Ope(s,t)),terminalMemberPathId:t.terminalPathId,terminalPathCommit:t.terminalPathCommit,moveFinalizerCommit:t.moveFinalizerCommit?.type==="external"?t.moveFinalizerCommit.commit:r,moveFinalizerMessage:t.moveFinalizerMessage,debugEvents:[],rawAppServerMessages:[],codexTurns:[],codexItems:[],agentSessions:i,activeItemIds:[],assistantTranscript:[],startedAt:t.startedAt??o,updatedAt:o}}function Ope(t,e){let r=Sp(1,"attempt"),n={pathId:t.pathId,executorId:t.executorId,goal:t.goal,requires:t.requires,attempt:r,agentSessionId:t.session?.sessionId,dependencyPathIds:Array.isArray(t.requires)?t.requires:[],dependencyOutputs:[],startedAt:t.startedAt??e.startedAt??new Date(0).toISOString()},i=t.session?.providerThreadId&&t.session.providerTurnId?{providerThreadId:t.session.providerThreadId,providerTurnId:t.session.providerTurnId}:void 0;switch(t.lifecycle){case"Failed":return{...n,status:"failed",session:i,error:t.error??"Path failed before server restart",commit:t.commit,parentCommit:t.parentCommit,treeChanged:t.treeChanged,completedAt:t.completedAt??e.completedAt??new Date(0).toISOString()};case"Executing":return i?{...n,status:"executing",session:i}:{...n,status:"starting"};case"Waiting":return{...n,status:"planned"};case"Completed":return{...n,status:"completed",session:i??{providerThreadId:"unknown",providerTurnId:t.session?.sessionId??t.pathId},finalResponse:"",commit:t.commit,parentCommit:t.parentCommit,treeChanged:t.treeChanged,completedAt:t.completedAt??e.completedAt??new Date(0).toISOString()}}}function Mpe(t){let e=[],r=Sp(1,"attempt");t.plan.session&&e.push($C(t.plan.session,{kind:"TeamPlan",runId:t.runId,executeId:t.executeId,attempt:r},t));for(let n of t.paths)n.session&&e.push($C(n.session,{kind:"ExecutionPlan",runId:t.runId,executeId:t.executeId,attempt:r,pathId:n.pathId,executorId:n.executorId},t));return t.finalizerSession&&e.push($C(t.finalizerSession,{kind:"MoveFinalizer",runId:t.runId,executeId:t.executeId,moveId:t.targetMoveId},t)),e}function $C(t,e,r){let n=t.providerThreadId&&t.providerTurnId?{providerThreadId:t.providerThreadId,providerTurnId:t.providerTurnId}:void 0,i=t.completedAt??r.completedAt??new Date(0).toISOString();return{sessionId:t.sessionId,routeRef:{kind:"Route",routeKind:e.kind==="TeamPlan"?"Plan":"Path",routeId:r.executeId,runId:r.runId,executeId:r.executeId,sourceLineId:r.lineId,sourceNodeId:String(r.sourceNodeId??""),worktree:r.worktree},runId:r.runId,executeId:r.executeId,owner:e,state:t.state==="failed"?{type:"failed",provider:n,error:t.error??"Session failed before server restart",completedAt:i}:{type:"completed",provider:n,completedAt:i},provider:n,messages:[],activeItemIds:[],revision:0,createdAt:t.startedAt??r.startedAt??i,updatedAt:i}}function Lpe(t){return t.startsWith("run/")?t.slice(4).split("/")[0]??t:t}function iP(t,e){return SU(t).filter(r=>Ip(r,t,{cwd:e}))}function oP(t,e,r={}){let n=t.agentSessions[e];if(n&&Ip(n,t,r))return n;for(let i of Object.values(t.runs)){let o=i.agentSessions?.find(s=>s.sessionId===e);if(o&&Ip(o,t,r))return o}}function SU(t){let e=new Map;for(let r of Object.values(t.agentSessions))e.set(r.sessionId,r);for(let r of Object.values(t.runs))for(let n of r.agentSessions??[])e.set(n.sessionId,n);return[...e.values()].sort((r,n)=>r.createdAt.localeCompare(n.createdAt))}function Ip(t,e,r){if(!t||r.sessionId&&t.sessionId!==r.sessionId||r.roadmapId&&!bU(t,r.roadmapId))return!1;if(!r.cwd)return!0;if(t.routeRef.routeKind==="HunsuDraft"&&t.routeRef.draftSessionId)return e.hunsuDrafts[t.routeRef.draftSessionId]?.repositoryPath===r.cwd;let n=Upe(e,t);return!!(n&&a0(n,r.cwd))}function Hpe(t,e,r,n){return t.type==="agentSession.snapshot"||n.sessionId&&t.sessionId!==n.sessionId||n.roadmapId&&"roadmapId"in t&&t.roadmapId&&t.roadmapId!==n.roadmapId?!1:Ip(e,r,n)}function bU(t,e){return t.roadmapId===e}function Upe(t,e){if(e.routeRef.runId){let r=t.runs[e.routeRef.runId];if(r)return r}return Object.values(t.runs).find(r=>r.agentSessions?.some(n=>n===e)||e.runId&&r.runId===e.runId&&(!e.roadmapId||r.roadmapId===e.roadmapId))}function sP(t){let e=jr(t.finalResponse,Fs),r=jr(t.error,Fs),n=t.state;return n.type==="completed"?n={...n,finalResponse:jr(n.finalResponse,Fs)}:n.type==="failed"&&(n={...n,error:xr(n.error,Fs)}),{...t,state:n,messages:[],finalResponse:e,error:r}}function Ai(t){let e=$pe(t)?t:void 0,r=e?void 0:t,n=t.pathCommits?{...t.pathCommits}:void 0,i=e?Fpe(t.repositoryPath,e):t.planExecutionTransition,o=e?e.memberPathRuns?.map(s=>XL(jpe(e.repositoryPath,e,s))):t.memberPathRuns?.map(XL);return{runId:t.runId,roadmapId:t.roadmapId,executeId:t.executeId,requestId:t.requestId,lineId:t.lineId,repositoryPath:t.repositoryPath,provider:t.provider,source:t.source,status:t.status,selectedDestinationIds:[...t.selectedDestinationIds],harnessLock:t.harnessLock,sourceNodeId:t.sourceNodeId,sourceMoveId:t.sourceMoveId,targetMoveOrdinal:t.targetMoveOrdinal,worktree:t.worktree,conversationRef:t.conversationRef,outcome:t.outcome,providerThreadId:t.providerThreadId,providerTeamThreadId:t.providerTeamThreadId,providerTeamPlanningTurnId:t.providerTeamPlanningTurnId,providerMemberThreadId:t.providerMemberThreadId,providerFinalizerThreadId:t.providerFinalizerThreadId,providerTurnIds:t.providerTurnIds?[...t.providerTurnIds]:void 0,lastRunUsage:t.lastRunUsage,finalResponse:jr(t.finalResponse,Fs),attemptCount:t.attemptCount,maxAttemptCount:t.maxAttemptCount,memberEvaluations:t.memberEvaluations?[...t.memberEvaluations]:void 0,executionPlanPlan:t.executionPlanPlan?[...t.executionPlanPlan]:void 0,pathCommits:n,planExecutionTransition:i,memberPathRuns:o,terminalMemberPathId:t.terminalMemberPathId,terminalPathCommit:t.terminalPathCommit,moveFinalizerMessage:jr(t.moveFinalizerMessage,Fs),moveFinalizerCommit:t.moveFinalizerCommit,error:jr(t.error,Fs),codexTurns:t.codexTurns?[...t.codexTurns]:[],agentSessions:t.agentSessions.map(sP),activeItemIds:[...t.activeItemIds],activeAgentSessionId:t.activeAgentSessionId,liveStatus:t.liveStatus,startedAt:t.startedAt,updatedAt:t.updatedAt,debugEventCount:e?e.debugEvents.length:r.debugEventCount,rawAppServerMessageCount:e?e.rawAppServerMessages.length:r.rawAppServerMessageCount,codexItemCount:e?e.codexItems.length:r.codexItemCount,assistantTranscriptCount:e?e.assistantTranscript.length:r.assistantTranscriptCount}}function $pe(t){return"debugEvents"in t}function XL(t){return t.status==="completed"?{...t,finalResponse:xr(t.finalResponse,Fs)}:t.status==="failed"?{...t,error:xr(t.error,Fs),finalResponse:jr(t.finalResponse,Fs)}:t}function Fpe(t,e){if(!t)return e.planExecutionTransition;let r=e.pathCommits?.["current-execution.plan"],n=e.pathCommits?.PrevMove??Wpe(e.worktree?.baseRef);return wU(t,n,r,{nextPending:So(e.status)&&!r&&!e.currentExecution})??e.planExecutionTransition}function jpe(t,e,r){if(!t||r.currentExecutionTransition)return r;let n="commit"in r?r.commit:void 0,i=("parentCommit"in r?r.parentCommit:void 0)??qpe(e,r),o=wU(t,i,n,{nextPending:!n&&(r.status==="starting"||r.status==="executing")});return o?{...r,currentExecutionTransition:o,currentExecutionFile:r.currentExecutionFile??o.next}:r}function qpe(t,e){let r=t.memberPathRuns??[],n=r.findIndex(i=>i===e);for(let i=n-1;i>=0;i-=1){let o=r[i];if(o&&o.status==="completed"&&"commit"in o&&o.commit)return o.commit}return t.pathCommits?.["current-execution.plan"]}function Wpe(t){if(t)try{return Xr(t)}catch{return}}function wU(t,e,r,n={}){if(!e&&!r&&!n.nextPending)return;let i=e?YL(t,e):void 0,o=r?YL(t,r):void 0;return{path:Xi,previousCommit:e,previous:i,previousState:i?"present":"none",nextCommit:r,next:o,nextState:n.nextPending&&!r?"pending":o?"present":"none"}}function YL(t,e){try{return{path:Xi,commit:e,text:Re(["show",`${e}:${Xi}`],{cwd:t})}}catch{return}}function a0(t,e){return!e||!t.repositoryPath?!1:Vpe(t.repositoryPath,e)}function Vpe(t,e){return _u(t)===_u(e)}function _u(t){return xo(t)??Yn(t)}function At(t,e,r){t.writeHead(e,{...dw.get(t),"content-type":"application/json; charset=utf-8"}),t.end(`${JSON.stringify(r,null,2)}
259
+ `)}async function Qi(t){let e=[];for await(let r of t)e.push(Buffer.isBuffer(r)?r:Buffer.from(r));return JSON.parse(Buffer.concat(e).toString("utf8"))}function Zo(t){return new Promise(e=>setTimeout(e,t))}import{createHash as Gpe}from"node:crypto";import{realpath as zpe,stat as IU}from"node:fs/promises";import{basename as Kpe,normalize as Jpe,resolve as EU}from"node:path";function vw(t){let e=t.now??(()=>new Date),r=t.platform??process.platform,n=Promise.resolve(),i=a=>{let c=n.then(a,a);return n=c.then(()=>{},()=>{}),c},o=async()=>{try{await n;let a=await t.store.read();return S(await Promise.all(a.workspaces.map(c=>m0(c))))}catch(a){return oe(h0(a))}},s=async a=>{try{await n;let u=(await t.store.read()).workspaces.find(d=>d.workspaceId===a);return u?S(await m0(u)):oe(DP(a))}catch(c){return oe(h0(c))}};return{async add(a,c={}){let u=await Ype(a);if(!u.ok)return u;let d=Xpe(u.value,r);return i(async()=>{try{let l=await t.store.read(),f=l.workspaces.find(b=>b.workspaceId===d||BP(b.repositoryPath,r)===BP(u.value,r));if(f)return oe({code:"WORKSPACE_ALREADY_REGISTERED",message:"Workspace is already registered.",workspaceId:f.workspaceId});let p=e().toISOString(),g=c.displayName?.trim()||Kpe(u.value),v={workspaceId:d,displayName:g,repositoryPath:u.value,lifecycle:"active",remoteAccess:{enabled:!1,scopes:[]},createdAt:p,updatedAt:p};return await t.store.write({schema:qa,workspaces:[...l.workspaces,v]}),S(await m0(v))}catch(l){return oe(h0(l))}})},list:o,get:s,async remove(a){return i(async()=>{try{let c=await t.store.read(),u=c.workspaces.findIndex(l=>l.workspaceId===a);if(u<0)return oe(DP(a));let d=c.workspaces[u];return await t.store.write({schema:qa,workspaces:c.workspaces.filter((l,f)=>f!==u)}),S(await m0(d))}catch(c){return oe(h0(c))}})},async open(a){let c=await s(a);return c.ok?c.value.lifecycle==="missing"?oe({code:"WORKSPACE_PATH_INVALID",message:"Workspace path no longer exists.",reason:"missing"}):c.value.lifecycle==="error"?oe({code:"WORKSPACE_PATH_INVALID",message:"Workspace path is not readable.",reason:"unreadable"}):S({workspaceId:c.value.workspaceId,displayName:c.value.displayName,repositoryPath:c.value.repositoryPath}):c},async setRemoteAccess(a,c){return i(async()=>{try{let u=await t.store.read(),d=u.workspaces.findIndex(p=>p.workspaceId===a);if(d<0)return oe(DP(a));let f={...u.workspaces[d],remoteAccess:{enabled:c.enabled,scopes:[...new Set(c.scopes)]},updatedAt:e().toISOString()};return await t.store.write({schema:qa,workspaces:u.workspaces.map((p,g)=>g===d?f:p)}),S(await m0(f))}catch(u){return oe(h0(u))}})}}}function Xpe(t,e=process.platform){let r=BP(EU(t),e);return`ws_${Gpe("sha256").update(r).digest("hex")}`}function kU(t){return{workspaceId:t.workspaceId,displayName:t.displayName,lifecycle:t.lifecycle,pathRedacted:!0}}async function Ype(t){if(!t.trim())return oe({code:"WORKSPACE_PATH_INVALID",message:"Workspace path is required.",reason:"empty"});try{let e=await zpe(EU(t));return(await IU(e)).isDirectory()?S(e):oe({code:"WORKSPACE_PATH_INVALID",message:"Workspace path must be a directory.",reason:"not_directory"})}catch(e){return Ot(e)&&e.code==="ENOENT"?oe({code:"WORKSPACE_PATH_INVALID",message:"Workspace path does not exist.",reason:"missing"}):oe({code:"WORKSPACE_PATH_INVALID",message:"Workspace path is not readable.",reason:"unreadable"})}}async function m0(t){let e={workspaceId:t.workspaceId,displayName:t.displayName,repositoryPath:t.repositoryPath,remoteAccess:t.remoteAccess??{enabled:!1,scopes:[]},createdAt:t.createdAt,updatedAt:t.updatedAt};try{return(await IU(t.repositoryPath)).isDirectory()?{...e,lifecycle:t.lifecycle}:{...e,lifecycle:"error",issue:"unreadable"}}catch(r){return Ot(r)&&r.code==="ENOENT"?{...e,lifecycle:"missing"}:{...e,lifecycle:"error",issue:"unreadable"}}}function BP(t,e){let r=Jpe(t);return e==="win32"?r.toLowerCase():r}function DP(t){return{code:"WORKSPACE_NOT_FOUND",message:"Workspace was not found.",workspaceId:t}}function h0(t){return{code:"BRIDGE_STATE_INVALID",message:t instanceof Kn?t.message:"Workspace state is unavailable."}}import{randomUUID as cme}from"node:crypto";import{link as ume,lstat as dme,mkdir as CU,open as lme,readFile as fme,realpath as Za,rmdir as pme,unlink as Iw}from"node:fs/promises";import{basename as BU,dirname as LP,isAbsolute as bw,join as NU,relative as mme,resolve as eo,sep as hme}from"node:path";import{randomUUID as Qpe}from"node:crypto";import{unlink as Zpe}from"node:fs/promises";import{isAbsolute as eme,win32 as tme}from"node:path";var rme=bn,S3e=`@hunsu/bridge@${rme}`,NP="hunsu.bridge.runtime-install.v1",g0="hunsu.bridge.runtime-install.v2";function RU(){return`install_${Qpe()}`}function Bu(t){return{async read(){let e=await Yi(t.runtimeInstallFile);return e===void 0?void 0:xw(t.runtimeInstallFile,e)},async write(e){await wn(t.runtimeInstallFile,xw(t.runtimeInstallFile,e),{mode:384})},async clear(){try{await Zpe(t.runtimeInstallFile)}catch(e){if(!Ot(e)||e.code!=="ENOENT")throw e}}}}function AU(t,e,r="production"){return{nodePath:t.nodePath,cliPath:t.cliPath,hunsuHome:e,packageVersion:t.packageVersion,runtimePath:t.runtimePath,deploymentProfile:r}}function xw(t,e){if(!OP(e)||e.schema!==g0&&e.schema!==NP)throw xe(t,`expected schema ${g0} or ${NP}`);let r=e.schema===NP;return{schema:g0,installationId:nme(t,e.installationId),current:Sw(t,"current",e.current,{legacy:r}),previous:e.previous===null?null:Sw(t,"previous",e.previous,{legacy:r}),serviceInput:ome(t,e.serviceInput),updatedAt:Ap(t,"updatedAt",e.updatedAt)}}function nme(t,e){if(e==null)return null;let r=Ap(t,"installationId",e);if(!/^install_[A-Za-z0-9_-]{8,}$/u.test(r))throw xe(t,"installationId must be a Hunsu installation id");return r}function Sw(t,e,r,n={}){if(!OP(r))throw xe(t,`${e} must be an installation record`);return{packageVersion:Ap(t,`${e}.packageVersion`,r.packageVersion),runtimePath:wl(t,`${e}.runtimePath`,r.runtimePath),nodePath:wl(t,`${e}.nodePath`,r.nodePath),cliPath:wl(t,`${e}.cliPath`,r.cliPath),cliSha256:ime(t,`${e}.cliSha256`,r.cliSha256,n),installedAt:Ap(t,`${e}.installedAt`,r.installedAt)}}function ime(t,e,r,n){if(n.legacy||r==null&&n.allowUnverified||r===null)return null;if(typeof r!="string"||!/^[a-f0-9]{64}$/u.test(r))throw xe(t,`${e} must be a lowercase SHA-256 digest or null`);return r}function ome(t,e){if(!OP(e))throw xe(t,"serviceInput must be an object");return{nodePath:wl(t,"serviceInput.nodePath",e.nodePath),cliPath:wl(t,"serviceInput.cliPath",e.cliPath),hunsuHome:wl(t,"serviceInput.hunsuHome",e.hunsuHome),packageVersion:Ap(t,"serviceInput.packageVersion",e.packageVersion),runtimePath:wl(t,"serviceInput.runtimePath",e.runtimePath),deploymentProfile:sme(t,e.deploymentProfile)}}function sme(t,e){if(e===void 0)return"production";if(!Pn(e))throw xe(t,"serviceInput.deploymentProfile must be production or preview");return e}function wl(t,e,r){let n=Ap(t,e,r);if(!eme(n)&&!tme.isAbsolute(n))throw xe(t,`${e} must be absolute`);return n}function Ap(t,e,r){if(typeof r!="string"||!r.trim()||ame(r))throw xe(t,`${e} must be a non-empty safe string`);return r}function OP(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ame(t){return/[\u0000-\u001f\u007f]/u.test(t)}var y0="hunsu.bridge.setup-transaction.v1",HP="hunsu.bridge.setup-lock.v1",zs=class extends Error{code="SETUP_IN_PROGRESS";constructor(){super("Another Hunsu Bridge setup, removal, or service mutation is already in progress."),this.name="SetupInProgressError"}};function gme(t){return t.setupTransactionFile}function yme(t){return t.setupLockFile}function Ew(t){let e=gme(t);return{async read(){let r=await Yi(e);return r===void 0?void 0:PU(e,r)},async write(r){await wn(e,PU(e,r),{mode:384})},async clear(){try{await Iw(e)}catch(r){if(!Ot(r)||r.code!=="ENOENT")throw r}}}}async function Cp(t,e,r={}){let n=yme(t),i=r.now??(()=>new Date),o=r.pid??process.pid,s=r.isProcessAlive??Ame,a={schema:HP,token:cme(),operation:e,pid:o,createdAt:i().toISOString()},c=`${n}.${o}.${a.token}.tmp`,u=await xme(t),d,l=!1;try{try{let f=await lme(c,"wx",384);try{d=kw(await f.stat()),await f.writeFile(`${JSON.stringify(a)}
260
+ `,"utf8"),await f.sync(),await f.chmod(384)}finally{await f.close()}for(let p=0;p<2;p+=1)try{await Sme(t,u),await ume(c,n),l=!0;let g=await v0(n,u.canonicalRuntime,2);if(!g||!x0(g,d))throw xe(n,"the atomic setup lock has an unexpected file identity");let v=!1;return{operation:e,async release(){if(v)return;let b=await _U(n,u.canonicalRuntime,!1);if(!b){v=!0,await MP(t,u);return}if(b.document?.token!==a.token)throw xe(n,"setup lock ownership changed before release");await TU(n,u.canonicalRuntime,b.identity),v=!0,await MP(t,u)}}}catch(g){if(!Ot(g)||g.code!=="EEXIST")throw g;let v=await _U(n,u.canonicalRuntime,!0);if(!v)continue;if(v.document&&s(v.document.pid))throw new zs;await TU(n,u.canonicalRuntime,v.identity)}}finally{d&&await Ime(c,u.canonicalRuntime,d)}throw new zs}catch(f){throw l&&d&&await Eme(n,u.canonicalRuntime,d),await MP(t,u),f}}function PU(t,e){if(!OU(e)||e.schema!==y0)throw xe(t,`expected schema ${y0}`);if(!kme(e.phase))throw xe(t,"phase is invalid");return{schema:y0,transactionId:$P(t,"transactionId",e.transactionId),phase:e.phase,candidate:Sw(t,"candidate",e.candidate,{allowUnverified:!0}),previous:e.previous===null?null:xw(t,e.previous),createdAt:UP(t,"createdAt",e.createdAt),updatedAt:UP(t,"updatedAt",e.updatedAt)}}function vme(t,e){let r;try{r=JSON.parse(e)}catch{throw xe(t,"setup lock is not valid JSON")}if(!OU(r)||r.schema!==HP||!Rme(r.operation)||!Number.isSafeInteger(r.pid)||Number(r.pid)<=0)throw xe(t,"setup lock has an invalid schema");return{schema:HP,token:$P(t,"token",r.token),operation:r.operation,pid:Number(r.pid),createdAt:UP(t,"createdAt",r.createdAt)}}async function xme(t){bme(t);let e=await El(t.home);e&&Il(t.home,e,"Hunsu home"),e||await CU(t.home,{recursive:!0,mode:448});let r=await ww(t.home,"Hunsu home");Il(t.home,r,"Hunsu home");let n=eo(await Za(t.home));await wme(t.home,n);let i=await El(t.runtimeDirectory);if(i&&Il(t.runtimeDirectory,i,"setup runtime directory"),!i)try{await CU(t.runtimeDirectory,{mode:448})}catch(a){if(!Ot(a)||a.code!=="EEXIST")throw a}let o=await ww(t.runtimeDirectory,"setup runtime directory");Il(t.runtimeDirectory,o,"setup runtime directory");let s=eo(await Za(t.runtimeDirectory));if(!kl(s,NU(n,BU(t.runtimeDirectory))))throw xe(t.runtimeDirectory,"setup runtime directory is not a direct contained directory");return await v0(t.setupLockFile,s,1),{canonicalHome:n,canonicalRuntime:s,createdHome:!e,createdRuntime:!i}}async function Sme(t,e){let r=await ww(t.home,"Hunsu home");Il(t.home,r,"Hunsu home");let n=eo(await Za(t.home));if(!kl(n,e.canonicalHome))throw xe(t.home,"Hunsu home changed while acquiring the setup lock");let i=await ww(t.runtimeDirectory,"setup runtime directory");Il(t.runtimeDirectory,i,"setup runtime directory");let o=eo(await Za(t.runtimeDirectory));if(!kl(o,e.canonicalRuntime)||!Rw(e.canonicalHome,o,!1))throw xe(t.runtimeDirectory,"setup runtime directory changed while acquiring the setup lock")}function bme(t){if(!bw(t.home)||!bw(t.runtimeDirectory)||!bw(t.setupLockFile)||!kl(LP(t.runtimeDirectory),t.home)||!kl(LP(t.setupLockFile),t.runtimeDirectory))throw xe(t.setupLockFile,"setup lock paths are not absolute direct children of the Hunsu home")}async function wme(t,e){let r=eo(await Za(LP(t)));if(!kl(e,NU(r,BU(t))))throw xe(t,"directory resolves through a symbolic link, junction, or reparse point")}function Il(t,e,r){if(e.isSymbolicLink()||!e.isDirectory())throw xe(t,`${r} has an unsafe filesystem type`)}async function v0(t,e,r){let n=await El(t);if(!n)return;if(n.isSymbolicLink()||!n.isFile()||n.nlink!==r)throw xe(t,"setup lock has an unsafe linked or non-file filesystem type");let i=eo(await Za(t));if(!Rw(e,i,!1))throw xe(t,"setup lock resolves outside the setup runtime directory");return kw(n)}async function _U(t,e,r){let n=await v0(t,e,1);if(!n)return;let i;try{i=await fme(t,"utf8")}catch(s){if(Ot(s)&&s.code==="ENOENT")return;throw s}let o=await v0(t,e,1);if(!o||!x0(n,o))throw xe(t,"setup lock changed while it was being inspected");try{return{document:vme(t,i),identity:n}}catch(s){if(!r)throw s;return{document:void 0,identity:n}}}async function TU(t,e,r){let n=await v0(t,e,1);if(!n||!x0(n,r))throw xe(t,"setup lock changed before safe unlink");await Iw(t)}async function Ime(t,e,r){let n=await El(t);if(!n)return;if(n.isSymbolicLink()||!n.isFile()||!x0(kw(n),r))throw xe(t,"temporary setup lock changed before cleanup");let i=eo(await Za(t));if(!Rw(e,i,!1))throw xe(t,"temporary setup lock resolves outside the setup runtime directory");await Iw(t)}async function Eme(t,e,r){let n=await El(t);if(!n)return;if(n.isSymbolicLink()||!n.isFile()||n.nlink!==1&&n.nlink!==2||!x0(kw(n),r))throw xe(t,"failed setup lock changed before cleanup");let i=eo(await Za(t));if(!Rw(e,i,!1))throw xe(t,"failed setup lock resolves outside the setup runtime directory");await Iw(t)}async function MP(t,e){e.createdRuntime&&await DU(t.runtimeDirectory,e.canonicalRuntime),e.createdHome&&await DU(t.home,e.canonicalHome)}async function DU(t,e){let r=await El(t);if(!r)return;Il(t,r,"created setup lock directory");let n=eo(await Za(t));if(!kl(n,e))throw xe(t,"created setup lock directory changed before cleanup");try{await pme(t)}catch(i){if(!Ot(i)||i.code!=="ENOENT"&&i.code!=="ENOTEMPTY"&&i.code!=="EEXIST")throw i}}async function El(t){try{return await dme(t)}catch(e){if(Ot(e)&&e.code==="ENOENT")return;throw e}}async function ww(t,e){let r=await El(t);if(!r)throw xe(t,`${e} disappeared during setup lock acquisition`);return r}function kw(t){return{dev:t.dev,ino:t.ino}}function x0(t,e){return e!==void 0&&t.dev===e.dev&&t.ino===e.ino}function Rw(t,e,r){let n=mme(eo(t),eo(e));return n===""?r:n!==".."&&!n.startsWith(`..${hme}`)&&!bw(n)}function kl(t,e){let r=eo(t),n=eo(e);return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function $P(t,e,r){if(typeof r!="string"||!r.trim()||/[\u0000-\u001f\u007f]/u.test(r))throw xe(t,`${e} must be a non-empty safe string`);return r}function UP(t,e,r){let n=$P(t,e,r);if(!Number.isFinite(Date.parse(n)))throw xe(t,`${e} must be an ISO timestamp`);return n}function kme(t){return t==="preparing"||t==="candidate-staged"||t==="previous-stopped"||t==="service-switched"||t==="candidate-started"||t==="candidate-verified"||t==="committing"||t==="rolling-back"}function Rme(t){return t==="setup"||t==="remove"||t==="service-mutation"||t==="runtime-upgrade"}function OU(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ame(t){try{return process.kill(t,0),!0}catch(e){return Ot(e)&&e.code==="EPERM"}}async function Aw(t){let e=[],r=!0,n="production";try{n=(await Qo(t.paths).read()).deploymentProfile}catch{r=!1,e.push({code:"BRIDGE_STATE_INVALID",message:"Bridge configuration is invalid."})}let i=!1;try{i=await wu(t.paths).read()!==void 0}catch{i=!0,e.push({code:"BRIDGE_STATE_INVALID",message:"Bridge credentials file is invalid or inaccessible."})}let o=await zb(t.paths).read().catch(()=>{});o&&o.deploymentProfile!==n&&e.push({code:"BRIDGE_PROFILE_MISMATCH",message:"The running Bridge deployment profile does not match its durable configuration."});let s;try{s=(await Ew(t.paths).read())?.phase,s&&e.push({code:"SETUP_TRANSACTION_INCOMPLETE",message:`Bridge setup has an incomplete ${s} transaction.`})}catch{e.push({code:"BRIDGE_STATE_INVALID",message:"Bridge setup transaction state is invalid."})}let a=await vw({store:Wb(t.paths)}).list(),c=a.ok?a.value.map(kU):[];a.ok||e.push({code:a.error.code,message:a.error.message});let u=t.providerService?await t.providerService.status(!1).catch(()=>{}):void 0,d={schema:"hunsu.bridge.doctor.v1",mode:t.online===!1?"offline":"online",version:bn,protocolVersion:rl,deploymentProfile:n,home:t.paths.home,state:{config:r?"valid":"invalid",credentialsPresent:i,runtimePresent:o!==void 0,workspaceCount:c.length,...s?{setupTransactionPhase:s}:{}},...u?{provider:{providerId:u.providerId,installed:u.installed,configured:u.configured,authenticated:u.authenticated,ready:u.ready,...u.safeMessage?{message:u.safeMessage}:{}}}:{},workspaces:c,issues:e},l=Qr(d);return Ds(l),l}import{appendFile as Cme,chmod as Pme,mkdir as _me,readFile as Tme,rename as Dme,stat as Bme,unlink as MU}from"node:fs/promises";var FP="hunsu.bridge.log.v1",Nme=1048576,Ome=3;function UU(t){let e=HU(t.maxBytes??Nme,"maxBytes"),r=HU(t.maxFiles??Ome,"maxFiles"),n=t.now??(()=>new Date),i=Promise.resolve();return{append:async s=>{let a=i.then(async()=>{if(!s.event.trim())throw new Error("Structured log event name must be non-empty.");let c={schema:FP,timestamp:n().toISOString(),level:s.level,event:s.event,...s.message===void 0?{}:{message:s.message},...s.data===void 0?{}:{data:s.data}},u=jP(c),d=`${JSON.stringify(u)}
261
+ `;if(Buffer.byteLength(d)>e&&(u=jP({schema:FP,timestamp:c.timestamp,level:c.level,event:c.event,message:"Structured log event exceeded the configured size limit.",data:{truncated:!0}}),d=`${JSON.stringify(u)}
262
+ `),Buffer.byteLength(d)>e)throw new Error("Structured log maxBytes is too small for a valid record.");return await _me(t.paths.logsDirectory,{recursive:!0,mode:448}),await Lme(t.paths.structuredLogFile,Buffer.byteLength(d),e,r),await Cme(t.paths.structuredLogFile,d,{encoding:"utf8",mode:384}),await Pme(t.paths.structuredLogFile,384),u});return i=a.then(()=>{},()=>{}),a},async read(s={}){await i;let a=[];for(let d of Hme(t.paths.structuredLogFile,r)){let l=await Ume(d);if(l!==void 0)for(let f of l.split(/\r?\n/u)){if(!f.trim())continue;let p=Mme(f);p&&a.push(p)}}let c=s.limit;if(c===void 0)return a;let u=Math.max(0,Math.trunc(c));return u===0?[]:a.slice(-u)}}}function jP(t){let e=Qr(t);return Ds(e),e}function Mme(t){try{let e=JSON.parse(t);return $me(e)?jP(e):void 0}catch{return}}async function Lme(t,e,r,n){let i=0;try{i=(await Bme(t)).size}catch(o){if(!Ot(o)||o.code!=="ENOENT")throw o}if(!(i===0||i+e<=r)){if(n===1){await MU(t).catch(o=>{if(!Ot(o)||o.code!=="ENOENT")throw o});return}await MU(`${t}.${n-1}`).catch(o=>{if(!Ot(o)||o.code!=="ENOENT")throw o});for(let o=n-2;o>=1;o-=1)await LU(`${t}.${o}`,`${t}.${o+1}`);await LU(t,`${t}.1`)}}async function LU(t,e){try{await Dme(t,e)}catch(r){if(!Ot(r)||r.code!=="ENOENT")throw r}}function Hme(t,e){let r=[];for(let n=e-1;n>=1;n-=1)r.push(`${t}.${n}`);return r.push(t),r}async function Ume(t){try{return await Tme(t,"utf8")}catch(e){if(Ot(e)&&e.code==="ENOENT")return;throw e}}function HU(t,e){if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer.`);return t}function $me(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;return e.schema===FP&&typeof e.timestamp=="string"&&(e.level==="debug"||e.level==="info"||e.level==="warn"||e.level==="error")&&typeof e.event=="string"}import{Buffer as Qc}from"node:buffer";import{hostname as xCe}from"node:os";import{randomBytes as SCe,webcrypto as LO}from"node:crypto";import{Buffer as ec}from"node:buffer";import{randomBytes as Fme,webcrypto as jme}from"node:crypto";var Sr=jme.subtle,qme="hunsu.connect.signal.v1",Wme="hunsu.peer.data.v1",Vme=Number.MAX_SAFE_INTEGER;async function qU(){let t=await Sr.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),e=await Sr.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);return{signingPrivateKey:Pw(await Sr.exportKey("jwk",t.privateKey)),signingPublicKey:en(await Sr.exportKey("jwk",t.publicKey)),agreementPrivateKey:Pw(await Sr.exportKey("jwk",e.privateKey)),agreementPublicKey:en(await Sr.exportKey("jwk",e.publicKey))}}async function WU(t){let e=["hunsu.connect.enrollment-proof.v1",t.deviceName,t.issuedAt,t.nonce,JSON.stringify(en(t.signingPublicJwk)),JSON.stringify(en(t.agreementPublicJwk))].join(`
263
+ `),r=await YU(t.signingPrivateKey),n=await Sr.sign({name:"ECDSA",hash:"SHA-256"},r,Pi(e));return Nu(n)}async function VU(t){let e=await QU(t.browserAgreementPublicJwk),r=await Sr.importKey("jwk",Pw(t.deviceAgreementPrivateKey),{name:"ECDH",namedCurve:"P-256"},!1,["deriveBits"]),n=await Sr.deriveBits({name:"ECDH",public:e},r,256),i=await Sr.importKey("raw",n,"HKDF",!1,["deriveBits"]),o=await Sr.deriveBits({name:"HKDF",hash:"SHA-256",salt:Pi(t.sessionId),info:Pi(qme)},i,256),s=await Sr.importKey("raw",o,{name:"AES-GCM"},!1,["encrypt","decrypt"]),a={key:s,noncePrefix:(await _p(Pi("hunsu.connect.signal.nonce/bridge"))).slice(0,4),sequence:0},c=0;return{async encrypt(u){let d=await JU(a,u,$U(t.sessionId));return{schema:ip,sessionId:t.sessionId,sequence:d.sequence,iv:d.nonce,ciphertext:d.ciphertext}},async decrypt(u){if(u.schema!==ip||u.sessionId!==t.sessionId||u.sequence!==c+1)throw ar("Connect signaling sequence or binding is invalid.");let d=VP((await _p(Pi("hunsu.connect.signal.nonce/browser"))).slice(0,4),u.sequence),l=await XU(s,u.sequence,u.iv,u.ciphertext,$U(t.sessionId),d);return c=u.sequence,l}}}async function GU(t){if(t.ticketClaims.sessionId!==t.sessionId)throw ar("Ticket session binding is invalid.");let e=t.now??(()=>new Date),r=t.randomBytes??Fme,n=await Sr.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),i=await QU(t.ticketClaims.browserAgreementPublicJwk),o=await Sr.deriveBits({name:"ECDH",public:i},n.privateKey,256),s=en(await Sr.exportKey("jwk",n.publicKey)),a=Nu(r(24)),c=new Date(e().getTime()+w8).toISOString(),u=Nu(await _p(Pi(t.ticket))),d=Gme({sessionId:t.sessionId,accountId:t.ticketClaims.accountId,deviceId:t.ticketClaims.deviceId,ticketDigest:u,browserAgreementPublicJwk:t.ticketClaims.browserAgreementPublicJwk,bridgeEphemeralPublicJwk:s,browserNonce:t.browserNonce,bridgeNonce:a,leaseExpiresAt:c}),l=await _p(d),f=Nu(l),p=await YU(t.deviceSigningPrivateKey),g=Nu(await Sr.sign({name:"ECDSA",hash:"SHA-256"},p,l)),v=await Sr.importKey("raw",o,"HKDF",!1,["deriveBits"]),b=new Uint8Array(await Sr.deriveBits({name:"HKDF",hash:"SHA-256",salt:l,info:Pi(Wme)},v,1024)),C=await Cw(b.slice(0,32),"control/browser"),D=await Cw(b.slice(32,64),"control/bridge"),_=await Cw(b.slice(64,96),"stream/browser"),F=await Cw(b.slice(96,128),"stream/bridge");return{serverHello:{type:"peer.server-hello",protocolVersion:La,sessionId:t.sessionId,bridgeEphemeralPublicJwk:s,bridgeNonce:a,leaseExpiresAt:c,transcriptHash:f,signature:g},accountId:t.ticketClaims.accountId,transcriptHash:f,ticketId:t.ticketClaims.jti,async encrypt(he,z){let de=await JU(he==="control"?D:F,z,FU(t.sessionId,he)),R={version:La,sessionId:t.sessionId,channel:he,sequence:de.sequence,nonce:de.nonce,ciphertext:de.ciphertext};return JSON.stringify(R)},async decrypt(he,z){let Ce=typeof z=="string"?z:ec.from(z).toString("utf8");if(ec.byteLength(Ce,"utf8")>wg*2)throw ar("Peer frame exceeds its encoded bound.");let de;try{de=JSON.parse(Ce)}catch{throw ar("Peer frame is not valid JSON.")}let R=zme(de,t.sessionId,he),V=he==="control"?C:_;if(R.sequence!==V.sequence+1)throw ar("Peer frame sequence is not contiguous.");let le=VP(V.noncePrefix,R.sequence),se=await XU(V.key,R.sequence,R.nonce,R.ciphertext,FU(t.sessionId,he),le);return V.sequence=R.sequence,se}}}async function zU(t){let e=t.ticket.split(".");if(e.length!==3||e.some(d=>!/^[A-Za-z0-9_-]+$/u.test(d)))throw ar("Connect ticket encoding is invalid.");let r=jU(e[0],"Connect ticket header"),n=jU(e[1],"Connect ticket claims");if(!qP(r,["alg","typ","kid"])||r.alg!=="ES256"||r.typ!=="hunsu-connect-session+jwt"||r.kid!==t.expectedKeyId)throw ar("Connect ticket protected header is invalid.");if(!qP(n,["iss","aud","sub","jti","environment","sessionId","accountId","deviceId","browserAgreementPublicJwk","iat","exp"]))throw ar("Connect ticket claims are invalid.");let i=en(n.browserAgreementPublicJwk),o=Math.floor(t.now.getTime()/1e3);if(n.iss!==t.expectedIssuer||n.aud!=="hunsu-bridge"||n.environment!==t.expectedEnvironment||n.sessionId!==t.expectedSessionId||n.sub!==t.expectedDeviceId||n.deviceId!==t.expectedDeviceId||!Rl(n.jti,256)||!Rl(n.accountId,256)||!Number.isSafeInteger(n.iat)||!Number.isSafeInteger(n.exp)||Number(n.iat)>o+15||Number(n.exp)<=o||Number(n.exp)<=Number(n.iat)||Number(n.exp)-Number(n.iat)>90||t.expectedBrowserAgreementPublicJwk&&!Kme(i,t.expectedBrowserAgreementPublicJwk))throw ar("Connect ticket claim binding is invalid.");let s=await Sr.importKey("jwk",en(t.signingPublicKey),{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),a=Pp(e[2],64,64);if(!await Sr.verify({name:"ECDSA",hash:"SHA-256"},s,a,Pi(`${e[0]}.${e[1]}`)))throw ar("Connect ticket signature is invalid.");let u=Nu(await _p(Pi(t.ticket)));if(!await t.consume(n.jti,u))throw ar("Connect ticket was already used.");return{iss:n.iss,aud:"hunsu-bridge",sub:n.sub,jti:n.jti,environment:n.environment,sessionId:n.sessionId,accountId:n.accountId,deviceId:n.deviceId,browserAgreementPublicJwk:i,iat:n.iat,exp:n.exp}}function WP(t,e){if(typeof e!="string"||!e.startsWith(`v=0\r
264
+ `)||ec.byteLength(e,"utf8")>64*1024||/[\u0000\u000b\u000c]/u.test(e))throw ar("Peer SDP is invalid.");let r=e.split(`\r
265
+ `).filter(Boolean),n=r.filter(s=>s.startsWith("m="));if(n.length!==1||!/^m=application \d+ UDP\/DTLS\/SCTP webrtc-datachannel$/u.test(n[0]))throw ar("Peer SDP must contain exactly one WebRTC DataChannel section.");if(r.some(s=>/^m=(audio|video)\b/u.test(s)))throw ar("Peer SDP requested unsupported media.");let i=r.filter(s=>s.startsWith("a=candidate:"));if(i.length>64||i.some(s=>!/ typ (?:host|srflx)(?: |$)/u.test(s)))throw ar("Peer SDP contains invalid ICE candidates.");if(!r.some(s=>/^a=ice-ufrag:[A-Za-z0-9+/]{4,256}$/u.test(s))||!r.some(s=>/^a=ice-pwd:[A-Za-z0-9+/]{22,256}$/u.test(s))||!r.some(s=>t==="offer"?s==="a=setup:actpass":/^a=setup:(?:active|passive)$/u.test(s)))throw ar("Peer SDP ICE or DTLS setup is invalid.");let o=[...new Set(r.flatMap(s=>{let a=s.match(/^a=fingerprint:sha-256 ((?:[0-9A-F]{2}:){31}[0-9A-F]{2})$/u);return a?.[1]?[a[1]]:[]}))];if(o.length!==1)throw ar("Peer SDP must contain one consistent SHA-256 fingerprint.");return{fingerprint:o[0]}}function KU(t){if(typeof t!="string"||t.length>2048||!/^candidate:[^\r\n]+ typ (?:host|srflx)(?: |$)/u.test(t))throw ar("Peer ICE candidate is invalid.")}function Gme(t){return Pi(JSON.stringify({v:1,sessionId:t.sessionId,accountId:t.accountId,deviceId:t.deviceId,ticketDigest:t.ticketDigest,browserAgreementPublicJwk:en(t.browserAgreementPublicJwk),bridgeEphemeralPublicJwk:en(t.bridgeEphemeralPublicJwk),browserNonce:t.browserNonce,bridgeNonce:t.bridgeNonce,leaseExpiresAt:t.leaseExpiresAt}))}async function Cw(t,e){return{key:await Sr.importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"]),noncePrefix:(await _p(Pi(`hunsu.peer.data.nonce/${e}`))).slice(0,4),sequence:0}}async function JU(t,e,r){let n=Pi(JSON.stringify(e));if(n.byteLength>wg-16)throw ar("Peer plaintext exceeds its bound.");let i=t.sequence+1;if(i>Vme)throw ar("Peer frame sequence is exhausted.");let o=VP(t.noncePrefix,i),s=await Sr.encrypt({name:"AES-GCM",iv:o,additionalData:Pi(`${r}:${i}`),tagLength:128},t.key,n);return t.sequence=i,{sequence:i,nonce:Nu(o),ciphertext:Nu(s)}}async function XU(t,e,r,n,i,o){let s=Pp(r,12,12);if(!ec.from(s).equals(ec.from(o)))throw ar("Peer frame nonce is invalid.");let a=Pp(n,16,wg),c;try{c=await Sr.decrypt({name:"AES-GCM",iv:o,additionalData:Pi(`${i}:${e}`),tagLength:128},t,a)}catch{throw ar("Peer frame authentication failed.")}try{return JSON.parse(ec.from(c).toString("utf8"))}catch{throw ar("Peer frame plaintext is invalid.")}}function zme(t,e,r){if(!GP(t)||!qP(t,["version","sessionId","channel","sequence","nonce","ciphertext"])||t.version!==La||t.sessionId!==e||t.channel!==r||!Number.isSafeInteger(t.sequence)||Number(t.sequence)<1||!Rl(t.nonce,16)||!Rl(t.ciphertext,Math.ceil(wg*4/3)))throw ar("Peer frame fields are invalid.");return t}function VP(t,e){let r=new Uint8Array(12);return r.set(t,0),new DataView(r.buffer).setBigUint64(4,BigInt(e),!1),r}function $U(t){return`${ip}:${t}`}function FU(t,e){return`${La}:${t}:${e}`}function jU(t,e){try{let r=Pp(t,2,8192),n=JSON.parse(ec.from(r).toString("utf8"));if(!GP(n))throw new Error;return n}catch{throw ar(`${e} is invalid.`)}}async function YU(t){return Sr.importKey("jwk",Pw(t),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"])}async function QU(t){return Sr.importKey("jwk",en(t),{name:"ECDH",namedCurve:"P-256"},!1,[])}function Pw(t){if(!Rl(t.d,128))throw ar("P-256 private key is invalid.");return{...en({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),d:t.d,ext:!0}}function en(t){if(!GP(t)||t.kty!=="EC"||t.crv!=="P-256"||!Rl(t.x,128)||!Rl(t.y,128)||t.d!==void 0)throw ar("P-256 public key is invalid.");return Pp(t.x,32,32),Pp(t.y,32,32),{crv:"P-256",kty:"EC",x:t.x,y:t.y}}function Kme(t,e){let r=en(t),n=en(e);return r.x===n.x&&r.y===n.y}function qP(t,e){let r=Object.keys(t).sort(),n=[...e].sort();return r.length===n.length&&r.every((i,o)=>i===n[o])}function Pp(t,e,r){if(!/^[A-Za-z0-9_-]+$/u.test(t)||t.length%4===1)throw ar("Base64url value is invalid.");let n=ec.from(t,"base64url");if(n.byteLength<e||n.byteLength>r||n.toString("base64url")!==t)throw ar("Base64url value has an invalid size or encoding.");return new Uint8Array(n)}function Nu(t){return ec.from(t instanceof Uint8Array?t:new Uint8Array(t)).toString("base64url")}function Pi(t){return new TextEncoder().encode(t)}async function _p(t){return new Uint8Array(await Sr.digest("SHA-256",t))}function Rl(t,e){return typeof t=="string"&&t.length>0&&t.length<=e&&!/[\u0000-\u001f\u007f]/u.test(t)}function GP(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ar(t){return new Error(t)}import{Buffer as W1e}from"node:buffer";function ZY(t={}){return async()=>{let e=await(t.loadWerift??Y1e)(),r=new e.RTCPeerConnection({iceServers:[{urls:b8}],iceTransportPolicy:"all",maxMessageSize:128*1024});return V1e(r,t.channelTimeoutMs??1e4)}}async function mR(t){let e=t.highWaterMark??1048576,r=t.lowWaterMark??256*1024;if(t.channel.readyState!=="open")throw new Error("Peer DataChannel is not open.");if(t.channel.bufferedAmount>e&&(t.channel.bufferedAmountLowThreshold=r,await J1e(t.channel,t.signal,t.timeoutMs??1e4)),t.signal.aborted||t.channel.readyState!=="open")throw new Error("Peer DataChannel send was canceled.");if(t.channel.send(t.value),t.channel.bufferedAmount>e*2)throw new Error("Peer DataChannel backpressure bound was exceeded.")}function V1e(t,e){let r=new Map,n,i=!1,o=t.onDataChannel.subscribe(s=>{try{let a=G1e(s);if(!s.isCreatedByRemote||a.label!==z1&&a.label!==K1||r.has(a.label))throw new Error("Peer offered an unexpected DataChannel.");mO(a),r.set(a.label,a)}catch(a){n=a instanceof Error?a:new Error("Peer DataChannel is invalid."),t.close()}});return{async acceptOffer(s,a){if(i)throw new Error("Peer transport is closed.");if(WP("offer",s),await t.setRemoteDescription({type:"offer",sdp:s}),n)throw n;let c=await t.createAnswer();await t.setLocalDescription(c),await K1e(t,a,e);let u=t.localDescription?.sdp;if(!u)throw new Error("Peer answer SDP is unavailable.");return WP("answer",u),{answerSdp:u}},waitForChannels(s){return i?Promise.reject(new Error("Peer transport is closed.")):z1e(r,()=>n,s,e)},async addIceCandidate(s){if(i)throw new Error("Peer transport is closed.");KU(s.candidate),await t.addIceCandidate(s)},async close(){if(!i){i=!0,o.unSubscribe();for(let s of r.values())s.close();r.clear(),await t.close()}}}}function G1e(t){return{get label(){return t.label},get ordered(){return t.ordered},get maxRetransmits(){return t.maxRetransmits},get maxPacketLifeTime(){return t.maxPacketLifeTime},get readyState(){return t.readyState},get bufferedAmount(){return t.bufferedAmount},get bufferedAmountLowThreshold(){return t.bufferedAmountLowThreshold},set bufferedAmountLowThreshold(e){t.bufferedAmountLowThreshold=e},send(e){t.send(typeof e=="string"?e:W1e.from(e))},close(){t.close()},onMessage(e){let r=t.onMessage.subscribe(n=>e(typeof n=="string"?n:new Uint8Array(n)));return()=>r.unSubscribe()},onStateChange(e){let r=t.stateChange.subscribe(e);return()=>r.unSubscribe()},onBufferedAmountLow(e){let r=t.bufferedAmountLow.subscribe(e);return()=>r.unSubscribe()}}}function mO(t){if(!t.ordered||t.maxRetransmits!==void 0||t.maxPacketLifeTime!==void 0)throw new Error("Peer DataChannels must be reliable and ordered.")}async function z1e(t,e,r,n){let i=Date.now()+n;for(;Date.now()<i;){if(r?.aborted)throw new Error("Peer negotiation was canceled.");let o=e();if(o)throw o;let s=t.get(z1),a=t.get(K1);if(s&&a)return mO(s),mO(a),{control:s,stream:a};await X1e(r)}throw new Error("Peer did not open both required DataChannels.")}async function K1e(t,e,r){t.iceGatheringState!=="complete"&&await new Promise((n,i)=>{let o=setTimeout(()=>c(new Error("Peer ICE gathering timed out.")),r);o.unref?.();let s=t.iceGatheringStateChange.subscribe(u=>{u==="complete"&&c()}),a=()=>c(new Error("Peer ICE gathering was canceled."));e?.addEventListener("abort",a,{once:!0});function c(u){clearTimeout(o),s.unSubscribe(),e?.removeEventListener("abort",a),u?i(u):n()}})}function J1e(t,e,r){return new Promise((n,i)=>{let o=setTimeout(()=>u(new Error("Peer DataChannel remained backpressured.")),r);o.unref?.();let s=t.onBufferedAmountLow(()=>u()),a=t.onStateChange(d=>{d!=="open"&&u(new Error("Peer DataChannel closed while backpressured."))}),c=()=>u(new Error("Peer DataChannel send was canceled."));e.addEventListener("abort",c,{once:!0});function u(d){clearTimeout(o),s(),a(),e.removeEventListener("abort",c),d?i(d):n()}})}function X1e(t){return new Promise((e,r)=>{let n=setTimeout(()=>{t?.removeEventListener("abort",i),e()},5),i=()=>{clearTimeout(n),t?.removeEventListener("abort",i),r(new Error("Peer negotiation was canceled."))};t?.addEventListener("abort",i,{once:!0})})}async function Y1e(){return await Promise.resolve().then(()=>(QY(),YY))}function hZ(t){let e=t.fetchImpl??fetch,r=t.sleep??OCe,n=t.now??(()=>new Date),i=t.randomBytes??SCe,o=DCe(t.connectApiUrl),s=BCe(t.connectWsUrl),a=t.socketFactory??CCe,c=t.peerTransportFactory??ZY(),u="disabled",d,l,f=!1,p=0,g=0,v,b=Promise.resolve(),C=new Map,D=R=>{let V=b.then(R,R);return b=V.then(()=>{},()=>{}),V},_=async()=>{let[R,V,le]=await Promise.all([t.configStore.read(),t.credentialStore.read(),t.workspaceService.list()]),se=V?.connect?.state==="registered"?V.connect:void 0,H=le.ok?le.value.filter(G=>G.lifecycle==="active"&&G.remoteAccess.enabled&&G.remoteAccess.scopes.includes("remote.access")).map(G=>G.workspaceId):[];return{enabled:R.remote.enabled,signedIn:!!se?.refreshToken,...se?.accountId?{accountId:se.accountId}:{},connection:se?R.remote.enabled?u:"disabled":"signed_out",...se?.deviceId?{deviceId:se.deviceId}:{},...l?{peerSessionId:l.sessionId}:{},grantedWorkspaceIds:R.remote.enabled&&se?H:[],protocolVersion:La}},F=(R="canceled")=>{p+=1;let V=d;d=void 0,V?.close(1e3,R);let le=l;l=void 0,le?.close(R),v=void 0},he=(R,V)=>C.has(R)||C.size>=1024?!1:(C.set(R,V),!0),z=async()=>{let R=++p;if(f||!(await t.configStore.read()).remote.enabled)return;u="connecting";let le=await fZ(t.credentialStore);if(le=await wCe({credential:le,credentialStore:t.credentialStore,connectApiUrl:o,fetchImpl:e,now:n,secureRandom:i}),f||R!==p)return;let se=yZ(s),H=await UO({method:"GET",url:se,signingPrivateKey:le.signingPrivateKey,signingPublicKey:le.signingPublicKey,accessToken:le.accessToken,now:n(),randomBytes:i}),G=await a({url:s,headers:{authorization:`DPoP ${le.accessToken}`,dpop:H}});if(await ACe(G,1e4),f||R!==p){G.close(1e3,"superseded");return}d=G,g=0;let j=Promise.resolve(),me=Te=>{j=j.then(()=>de(Te.data,le,G,R)).catch(()=>{G.close(1008,"invalid_connect_frame")})},Pe=()=>{if(d===G&&(d=void 0),R!==p||f)return;u="offline",v=void 0;let Te=l;l=void 0,Te?.close("protocol_error"),Ce(R)};G.addEventListener("message",me),G.addEventListener("close",Pe),G.addEventListener("error",Pe)},Ce=R=>{let V=g++,le=Math.min(3e4,1e3*2**Math.min(V,5));r(le).then(async()=>{f||R!==p||!(await t.configStore.read()).remote.enabled||await z().catch(()=>{f||Ce(p)})})},de=async(R,V,le,se)=>{if(le!==d||se!==p)return;let H=RCe(R);if(kCe(H)){if(H.type==="connect.authenticated"){if(H.deviceId!==V.deviceId||H.accountId!==V.accountId||Date.parse(H.expiresAt)<=n().getTime())throw new Error("Connect authentication binding is invalid.");v=H.accountId,u="connected";return}if(H.type==="connect.session"){if(v!==V.accountId||Date.parse(H.expiresAt)<=n().getTime())throw new Error("Connect session arrived before authentication.");let j=await zU({ticket:H.ticket,signingPublicKey:t.connectTicketSigningPublicJwk,expectedKeyId:t.connectTicketSigningKeyId,expectedIssuer:t.connectTicketIssuer,expectedEnvironment:t.deploymentProfile,expectedSessionId:H.sessionId,expectedDeviceId:V.deviceId,now:n(),consume:he});if(j.accountId!==V.accountId)throw new Error("Connect ticket account binding is invalid.");let me=await VU({sessionId:H.sessionId,browserAgreementPublicJwk:j.browserAgreementPublicJwk,deviceAgreementPrivateKey:V.agreementPrivateKey}),Pe=l,Te=new HO({sessionId:H.sessionId,ticket:H.ticket,ticketClaims:j,signalCrypto:me,deviceSigningPrivateKey:V.signingPrivateKey,workspaceService:t.workspaceService,peerTransportFactory:c,onCommand:t.onCommand,onCommandStream:t.onCommandStream,now:n,randomBytes:i,sendSignal:P=>{if(le!==d||l!==Te)throw new Error("Connect session is no longer active.");le.send(JSON.stringify(P))},onClosed:()=>{l===Te&&(l=void 0)}});l=Te,Pe&&await Pe.close("replaced");return}if(H.type==="connect.ready"){if(l?.sessionId!==H.sessionId)throw new Error("Connect ready session binding is invalid.");return}if(l?.sessionId===H.sessionId){let j=l;l=void 0,await j.close(H.reason==="replaced"?"replaced":"protocol_error")}return}let G=v8(H);if(!G.ok||!l||G.value.sessionId!==l.sessionId)throw new Error("Connect signaling frame is invalid.");await l.handleSignal(G.value)};return{status:_,async login(R={}){return D(async()=>{f=!1;let V=await t.credentialStore.ensure();if(V.connect?.state==="registered")throw new De("REMOTE_CONNECTION_FAILED","This Bridge is already enrolled with Hunsu Connect.");let le=V.connect??await qU(),se=n().toISOString(),H=Qc.from(i(24)).toString("base64url"),G=TCe(t.deviceName??xCe()),j={schema:h8,deviceName:G,signingPublicJwk:en(le.signingPublicKey),agreementPublicJwk:en(le.agreementPublicKey),issuedAt:se,nonce:H,proof:await WU({deviceName:G,signingPublicJwk:le.signingPublicKey,agreementPublicJwk:le.agreementPublicKey,issuedAt:se,nonce:H,signingPrivateKey:le.signingPrivateKey})},me=await e(new URL("/v1/device-enrollments",o),{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify(j),redirect:"error",signal:AbortSignal.timeout(1e4)});if(!me.ok)throw new De("REMOTE_CONNECTION_FAILED",`Hunsu Connect enrollment could not start (HTTP ${me.status}).`);let Pe=ECe(await me.json().catch(()=>{}),n()),Te={...le,state:"enrolling",enrollmentId:Pe.enrollmentId,deviceCode:Pe.deviceCode,userCode:Pe.userCode,verificationUri:Pe.verificationUri,verificationUriComplete:Pe.verificationUriComplete,interval:Pe.interval,expiresAt:new Date(n().getTime()+Pe.expiresIn*1e3).toISOString()};await t.credentialStore.write({connect:Te});let P=!1;if(R.openBrowser!==!1&&t.openBrowser)try{await t.openBrowser(Te.verificationUriComplete),P=!0}catch{P=!1}let B=p;return bCe({enrollment:Te,credentialStore:t.credentialStore,connectApiUrl:o,connectWsUrl:s,fetchImpl:e,sleep:r,now:n,randomBytes:i,canceled:()=>f||B!==p}).catch(()=>{}),{state:"pending",verificationUri:Te.verificationUri,verificationUriComplete:Te.verificationUriComplete,userCode:Te.userCode,expiresAt:Te.expiresAt,browserOpened:P}})},async logout(){return D(async()=>{F("canceled"),u="disabled",await t.configStore.update(R=>({...R,remote:{enabled:!1}})),await t.credentialStore.write({connect:null})})},async enable(){return D(async()=>(f=!1,await fZ(t.credentialStore),await t.configStore.update(R=>({...R,remote:{enabled:!0}})),await z().catch(R=>{throw u="offline",new De("REMOTE_ENABLE_FAILED","Remote Bridge could not connect to Hunsu Connect.",{cause:R})}),_()))},async disable(){return D(async()=>(F("canceled"),u="disabled",await t.configStore.update(R=>({...R,remote:{enabled:!1}})),_()))},stop(){f=!0,F("canceled")}}}var HO=class{sessionId;input;transport;control;stream;crypto;confirmed=!1;closed=!1;signalSendQueue=Promise.resolve();controlReceiveQueue=Promise.resolve();streamReceiveQueue=Promise.resolve();controlSendQueue=Promise.resolve();streamSendQueue=Promise.resolve();requests=new Map;seenRequestIds=new Set;lifetime=new AbortController;leaseTimer;constructor(e){this.input=e,this.sessionId=e.sessionId}async handleSignal(e){if(this.closed)throw new Error("Peer session is closed.");let r=await this.input.signalCrypto.decrypt(e),n=k8(r);if(!n.ok)throw new Error(n.error.message);let i=n.value;if(i.type==="peer.offer"){if(this.transport)throw new Error("Peer offer was repeated.");let o=await this.input.peerTransportFactory();this.transport=o;try{let s=await o.acceptOffer(i.sdp);if(this.closed||this.transport!==o)throw new Error("Peer session was superseded.");await this.sendSignal({type:"peer.answer",sdp:s.answerSdp}),o.waitForChannels(this.lifetime.signal).then(a=>{this.closed||this.transport!==o||(this.control=a.control,this.stream=a.stream,this.attachChannels(a.control,a.stream))}).catch(()=>this.close("protocol_error"))}catch(s){throw await this.close("protocol_error"),s}return}if(i.type==="peer.ice"){if(!this.transport)throw new Error("Peer ICE arrived before the offer.");await this.transport.addIceCandidate(i);return}if(i.type==="peer.answer")throw new Error("Browser cannot send a peer answer.");await this.close(i.reason==="expired"?"protocol_error":"canceled")}async close(e){if(!this.closed){this.closed=!0,this.leaseTimer&&clearTimeout(this.leaseTimer);for(let r of this.requests.values())r.abort(e);this.requests.clear(),this.confirmed&&this.crypto&&this.control?.readyState==="open"&&await this.sendEncryptedControl({type:"session.close",sessionId:this.sessionId,reason:e==="replaced"?"replaced":e==="canceled"?"canceled":"protocol_error"}).catch(()=>{}),this.lifetime.abort(e),this.control?.close(),this.stream?.close(),await this.transport?.close().catch(()=>{}),this.input.onClosed()}}attachChannels(e,r){e.onMessage(n=>{this.controlReceiveQueue=this.controlReceiveQueue.then(()=>this.handleControlData(n)).catch(()=>this.close("protocol_error"))}),r.onMessage(n=>{this.streamReceiveQueue=this.streamReceiveQueue.then(()=>this.handleUnexpectedStreamData(n)).catch(()=>this.close("protocol_error"))}),e.onStateChange(n=>{n==="closed"&&this.close("protocol_error")}),r.onStateChange(n=>{n==="closed"&&this.close("protocol_error")})}async handleControlData(e){if(!this.crypto){let i=_Ce(e,16384),o;try{o=JSON.parse(i)}catch{throw new Error("Peer hello is invalid.")}let s=R8(o);if(!s.ok||s.value.sessionId!==this.sessionId||s.value.ticket!==this.input.ticket||!PCe(s.value.browserAgreementPublicJwk,this.input.ticketClaims.browserAgreementPublicJwk))throw new Error("Peer hello binding is invalid.");this.crypto=await GU({sessionId:this.sessionId,ticket:this.input.ticket,ticketClaims:this.input.ticketClaims,browserNonce:s.value.browserNonce,deviceSigningPrivateKey:this.input.deviceSigningPrivateKey,now:this.input.now,randomBytes:this.input.randomBytes}),await this.sendPlainControl(JSON.stringify(this.crypto.serverHello));return}let r=await this.crypto.decrypt("control",e),n=A8(r);if(!n.ok||n.value.sessionId!==this.sessionId)throw new Error("Peer control message is invalid.");if(!this.confirmed){if(n.value.type!=="session.confirm"||n.value.transcriptHash!==this.crypto.transcriptHash)throw new Error("Peer did not confirm the signed transcript.");this.confirmed=!0;let i=await this.pathFreeWorkspaces();await this.sendEncryptedControl({type:"session.ready",sessionId:this.sessionId,deviceId:this.input.ticketClaims.deviceId,transcriptHash:this.crypto.transcriptHash,leaseExpiresAt:this.crypto.serverHello.leaseExpiresAt,workspaces:i});let o=Math.max(1,Date.parse(this.crypto.serverHello.leaseExpiresAt)-this.input.now().getTime());this.leaseTimer=setTimeout(()=>{this.closeForExpiredLease()},o),this.leaseTimer.unref?.();return}await this.handleConfirmedControl(n.value)}async handleConfirmedControl(e){if(e.type==="session.close"){await this.close("canceled");return}if(e.type==="stream.cancel"){let s=this.requests.get(e.requestId);s&&s.abort(e.reason??"browser_cancel");return}if(e.type!=="command.request")throw new Error("Peer sent a server-only control message.");if(this.requests.size>=I8||this.seenRequestIds.has(e.requestId)||this.seenRequestIds.size>=1024){await this.sendCommandResult(e,{ok:!1,status:429,error:"Peer command concurrency or identity bound was exceeded."});return}let r=Date.parse(e.deadline);if(!Number.isFinite(r)||r<=this.input.now().getTime()||r>Date.parse(this.crypto.serverHello.leaseExpiresAt)){await this.sendCommandResult(e,{ok:!1,status:408,error:"Peer command deadline is invalid or expired."});return}this.seenRequestIds.add(e.requestId);let n=new AbortController;this.requests.set(e.requestId,n);let i=setTimeout(()=>n.abort("deadline"),r-this.input.now().getTime());i.unref?.();let o={requestId:e.requestId,workspaceId:e.workspaceId,command:e.command,deadline:e.deadline,...e.payload===void 0?{}:{payload:e.payload}};try{if(e.command==="agentSession.events"||e.command==="live.events")await this.runStreamCommand(e,o,n);else{let s=this.input.onCommand?await this.input.onCommand(o):{ok:!1,status:503,error:"Peer command router is unavailable."};await this.sendCommandResult(e,s)}}finally{clearTimeout(i),this.requests.delete(e.requestId)}}async runStreamCommand(e,r,n){let i=`stream_${Qc.from(this.input.randomBytes(18)).toString("base64url")}`;await this.sendEncryptedControl({type:"command.result",sessionId:this.sessionId,requestId:e.requestId,workspaceId:e.workspaceId,status:202,ok:!0,body:{streamId:i}}),await this.sendEncryptedStream({type:"stream.open",sessionId:this.sessionId,requestId:e.requestId,streamId:i,workspaceId:e.workspaceId});let o=0,s=this.input.onCommandStream?await this.input.onCommandStream(r,{signal:n.signal,emit:a=>{o+=1,this.sendEncryptedStream({type:"stream.chunk",sessionId:this.sessionId,requestId:e.requestId,streamId:i,workspaceId:e.workspaceId,chunkSequence:o,event:a.event,...a.data===void 0?{}:{data:a.data}}).catch(()=>n.abort("stream_send_failed"))}}):{ok:!1,status:503,error:"Peer stream router is unavailable."};await this.streamSendQueue,await this.sendEncryptedStream({type:"stream.end",sessionId:this.sessionId,requestId:e.requestId,streamId:i,workspaceId:e.workspaceId,status:s.status,...s.ok?{}:{error:s.error}})}sendCommandResult(e,r){return this.sendEncryptedControl({type:"command.result",sessionId:this.sessionId,requestId:e.requestId,workspaceId:e.workspaceId,status:r.status,ok:r.ok,...r.ok&&r.body!==void 0?{body:r.body}:{},...r.ok?{}:{error:r.error}})}async handleUnexpectedStreamData(e){throw!this.confirmed||!this.crypto?new Error("Peer stream data arrived before authentication."):(await this.crypto.decrypt("stream",e),new Error("Browser-to-Bridge stream messages are not supported."))}sendSignal(e){let r=this.signalSendQueue.then(async()=>{let n=await this.input.signalCrypto.encrypt(e);this.input.sendSignal(n)});return this.signalSendQueue=r.catch(()=>{}),r}sendPlainControl(e){return this.control?mR({channel:this.control,value:e,signal:this.lifetime.signal}):Promise.reject(new Error("Peer control channel is unavailable."))}sendEncryptedControl(e){let r=this.controlSendQueue.then(async()=>{if(!this.crypto||!this.control)throw new Error("Peer control channel is unavailable.");let n=await this.crypto.encrypt("control",e);await mR({channel:this.control,value:n,signal:this.lifetime.signal})});return this.controlSendQueue=r.catch(()=>{}),r}sendEncryptedStream(e){let r=this.streamSendQueue.then(async()=>{if(!this.crypto||!this.stream)throw new Error("Peer stream channel is unavailable.");let n=await this.crypto.encrypt("stream",e);await mR({channel:this.stream,value:n,signal:this.lifetime.signal})});return this.streamSendQueue=r.catch(()=>{}),r}async pathFreeWorkspaces(){let e=await this.input.workspaceService.list();if(!e.ok)throw new Error("Workspace registry is unavailable.");return e.value.flatMap(r=>r.lifecycle==="active"&&r.remoteAccess.enabled&&r.remoteAccess.scopes.includes("remote.access")?[{workspaceId:r.workspaceId,displayName:r.displayName,scopes:[...r.remoteAccess.scopes]}]:[])}async closeForExpiredLease(){this.closed||(this.crypto&&this.control?.readyState==="open"&&await this.sendEncryptedControl({type:"session.close",sessionId:this.sessionId,reason:"lease_expired"}).catch(()=>{}),await this.close("protocol_error"))}};async function bCe(t){let e=t.enrollment.interval;for(;!t.canceled()&&t.now().getTime()<Date.parse(t.enrollment.expiresAt);){if(await t.sleep(e*1e3),t.canceled())return;let r=new URL("/v1/device-enrollment-tokens",t.connectApiUrl),n=await UO({method:"POST",url:r.toString(),signingPrivateKey:t.enrollment.signingPrivateKey,signingPublicKey:t.enrollment.signingPublicKey,now:t.now(),randomBytes:t.randomBytes}),i=await t.fetchImpl(r,{method:"POST",headers:{accept:"application/json","content-type":"application/json",dpop:n},body:JSON.stringify({enrollmentId:t.enrollment.enrollmentId,deviceCode:t.enrollment.deviceCode}),redirect:"error",signal:AbortSignal.timeout(1e4)});if(i.ok){let a=gZ(await i.json().catch(()=>{}));await t.credentialStore.write({connect:ICe(t.enrollment,a,t.connectWsUrl,t.now())});return}let o=await i.json().catch(()=>{}),s=DR(o)&&typeof o.error=="string"?o.error:void 0;if(s!=="authorization_pending"){if(s==="slow_down"){e=Math.min(30,e+5);continue}if(s==="expired_token"||s==="access_denied")return;if(!(i.status>=500))return}}}async function wCe(t){if(Date.parse(t.credential.expiresAt)>t.now().getTime()+6e4)return t.credential;let e=new URL("/v1/device-tokens",t.connectApiUrl),r=await UO({method:"POST",url:e.toString(),signingPrivateKey:t.credential.signingPrivateKey,signingPublicKey:t.credential.signingPublicKey,now:t.now(),randomBytes:t.secureRandom}),n=await t.fetchImpl(e,{method:"POST",headers:{accept:"application/json","content-type":"application/json",dpop:r},body:JSON.stringify({refreshToken:t.credential.refreshToken}),redirect:"error",signal:AbortSignal.timeout(1e4)});if(!n.ok)throw new De("ACCOUNT_LOGIN_REQUIRED","Hunsu Connect device credentials could not be refreshed.");let i=gZ(await n.json().catch(()=>{}));if(i.deviceId!==t.credential.deviceId||i.accountId!==t.credential.accountId)throw new Error("Refreshed Connect credential binding changed.");let o={...t.credential,accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:new Date(t.now().getTime()+i.expiresIn*1e3).toISOString()};return await t.credentialStore.write({connect:o}),o}async function UO(t){let e={typ:"dpop+jwt",alg:"ES256",jwk:en(t.signingPublicKey)},r={jti:Qc.from(t.randomBytes(24)).toString("base64url"),htm:t.method.toUpperCase(),htu:yZ(t.url),iat:Math.floor(t.now.getTime()/1e3),...t.accessToken?{ath:PR(await LO.subtle.digest("SHA-256",_R(t.accessToken)))}:{}},n=PR(_R(JSON.stringify(e))),i=PR(_R(JSON.stringify(r))),o=await LO.subtle.importKey("jwk",NCe(t.signingPrivateKey),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),s=await LO.subtle.sign({name:"ECDSA",hash:"SHA-256"},o,_R(`${n}.${i}`));return`${n}.${i}.${PR(s)}`}async function fZ(t){let e=await t.read();if(!e?.connect||e.connect.state!=="registered")throw new De("ACCOUNT_LOGIN_REQUIRED","Enroll this Bridge with Hunsu Connect before enabling Remote access.");return e.connect}function ICe(t,e,r,n){return{signingPrivateKey:t.signingPrivateKey,signingPublicKey:t.signingPublicKey,agreementPrivateKey:t.agreementPrivateKey,agreementPublicKey:t.agreementPublicKey,state:"registered",deviceId:e.deviceId,accountId:e.accountId,accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:new Date(n.getTime()+e.expiresIn*1e3).toISOString(),connectWsUrl:r}}function ECe(t,e){if(!DR(t)||t.schema!=="hunsu.connect.enrollment-created.v1"||!xi(t.enrollmentId,256)||!xi(t.deviceCode,512)||!xi(t.userCode,64)||!Number.isInteger(t.expiresIn)||Number(t.expiresIn)<60||Number(t.expiresIn)>900||!Number.isInteger(t.interval)||Number(t.interval)<1||Number(t.interval)>30)throw new Error("Connect enrollment response is invalid.");let r=pZ(t.verificationUri),n=pZ(t.verificationUriComplete);if(new URL(r).origin!==new URL(n).origin)throw new Error("Connect verification origins do not match.");return{schema:"hunsu.connect.enrollment-created.v1",enrollmentId:t.enrollmentId,deviceCode:t.deviceCode,userCode:t.userCode,verificationUri:r,verificationUriComplete:n,expiresIn:Number(t.expiresIn),interval:Number(t.interval)}}function gZ(t){if(!DR(t)||t.schema!=="hunsu.connect.device-token.v1"||t.tokenType!=="DPoP"||!xi(t.accessToken,8*1024)||!xi(t.refreshToken,8*1024)||!xi(t.deviceId,256)||!xi(t.accountId,256)||t.expiresIn!==300)throw new Error("Connect device token response is invalid.");return t}function kCe(t){return!DR(t)||t.schema!==g8||typeof t.type!="string"?!1:t.type==="connect.authenticated"?TR(t,["schema","type","deviceId","accountId","expiresAt"])&&xi(t.deviceId,256)&&xi(t.accountId,256)&&mZ(t.expiresAt):t.type==="connect.session"?TR(t,["schema","type","sessionId","ticket","expiresAt"])&&xi(t.sessionId,256)&&xi(t.ticket,8*1024)&&mZ(t.expiresAt):t.type==="connect.ready"?TR(t,["schema","type","sessionId"])&&xi(t.sessionId,256):t.type==="connect.closed"?TR(t,["schema","type","sessionId","reason"])&&xi(t.sessionId,256)&&(t.reason==="expired"||t.reason==="replaced"||t.reason==="revoked"||t.reason==="peer_disconnected"||t.reason==="protocol_error"):!1}function RCe(t){let e=typeof t=="string"?t:t instanceof ArrayBuffer?Qc.from(t).toString("utf8"):ArrayBuffer.isView(t)?Qc.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):void 0;if(!e||Qc.byteLength(e,"utf8")>128*1024)throw new Error("Connect frame is invalid or too large.");try{return JSON.parse(e)}catch{throw new Error("Connect frame is not valid JSON.")}}async function ACe(t,e){t.readyState!==1&&await new Promise((r,n)=>{let i=setTimeout(()=>a(new Error("Connect WebSocket open timed out.")),e);i.unref?.();let o=()=>a(),s=()=>a(new Error("Connect WebSocket could not open."));t.addEventListener("open",o),t.addEventListener("close",s),t.addEventListener("error",s);function a(c){clearTimeout(i),t.removeEventListener?.("open",o),t.removeEventListener?.("close",s),t.removeEventListener?.("error",s),c?n(c):r()}})}async function CCe(t){let e=await Promise.resolve().then(()=>(lZ(),dZ));return new e.WebSocket(t.url,{headers:t.headers})}function PCe(t,e){let r=en(t),n=en(e);return r.x===n.x&&r.y===n.y}function _Ce(t,e){let r=typeof t=="string"?t:Qc.from(t).toString("utf8");if(Qc.byteLength(r,"utf8")>e)throw new Error("Peer plaintext frame is too large.");return r}function TCe(t){let e=t.trim();if(!e||e.length>128||/[\u0000-\u001f\u007f]/u.test(e))throw new Error("Bridge device name is invalid.");return e}function DCe(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&$O(e.hostname)))throw new Error("Connect API URL must use HTTPS.");if(e.username||e.password||e.search||e.hash)throw new Error("Connect API URL is invalid.");return e.toString()}function BCe(t){let e=new URL(t);if(e.protocol!=="wss:"&&!(e.protocol==="ws:"&&$O(e.hostname)))throw new Error("Connect WebSocket URL must use WSS.");if(e.username||e.password||e.search||e.hash)throw new Error("Connect WebSocket URL is invalid.");return e.toString()}function pZ(t){if(typeof t!="string")throw new Error("Connect verification URL is invalid.");let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&$O(e.hostname)))throw new Error("Connect verification URL must use HTTPS.");if(e.username||e.password||e.hash)throw new Error("Connect verification URL is invalid.");return e.toString()}function yZ(t){let e=new URL(t);return e.protocol==="wss:"&&(e.protocol="https:"),e.protocol==="ws:"&&(e.protocol="http:"),e.hash="",e.toString()}function NCe(t){if(!xi(t.d,128))throw new Error("Device signing private key is invalid.");return{...en({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),d:t.d,ext:!0}}function PR(t){return Qc.from(t instanceof Uint8Array?t:new Uint8Array(t)).toString("base64url")}function _R(t){return new TextEncoder().encode(t)}function TR(t,e){let r=Object.keys(t);return r.length===e.length&&r.every(n=>e.includes(n))}function xi(t,e){return typeof t=="string"&&t.length>0&&t.length<=e&&!/[\u0000-\u001f\u007f]/u.test(t)}function mZ(t){return xi(t,64)&&Number.isFinite(Date.parse(t))}function $O(t){return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}function DR(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function OCe(t){return new Promise(e=>{setTimeout(e,t).unref?.()})}import{isAbsolute as xZ,normalize as MCe,resolve as wYe}from"node:path";function SZ(t){let e=t.fetchImpl??fetch;return async r=>{let n=t.endpoint();if(!n)return qi(503,"Bridge is still starting.");let i=await wZ(t.workspaceService,r);if(!i.ok)return i.error;let o=LCe(r,i.value);if(!o)return qi(400,"Remote command is not supported by this Bridge protocol.");try{let s=await e(new URL(o.path,n),{method:o.method,headers:{[Au]:t.controlToken(),...o.body===void 0?{}:{"content-type":"application/json"}},...o.body===void 0?{}:{body:JSON.stringify(o.body)},redirect:"error",signal:AbortSignal.timeout(9e3)}),a=await s.json().catch(()=>{});if(!s.ok)return qi(s.status,"Local Bridge command failed.");let c=FO(a,o.workspaceId),u=Qr(BR(c,o.resultScope==="workspace"?o.authorizedRoot:void 0));return Ds(u),{ok:!0,status:s.status,...a===void 0?{}:{body:u}}}catch{return qi(503,"Local Bridge command is unavailable.")}}}function bZ(t){let e=t.fetchImpl??fetch;return async(r,n)=>{let i=t.endpoint();if(!i)return qi(503,"Bridge is still starting.");let o=await wZ(t.workspaceService,r);if(!o.ok||!o.value)return o.ok?qi(403,"Remote command Workspace is not granted."):o.error;let s=o.value,a=HCe(r,s);if(!a)return qi(400,"Remote event command is not supported by this Bridge protocol.");let c=AbortSignal.timeout(t.timeoutMs??5*6e4),u=AbortSignal.any([n.signal,c]);try{let d=await e(new URL(a.path,i),{method:"GET",headers:{[Au]:t.controlToken(),accept:"text/event-stream"},redirect:"error",signal:u});return!d.ok||!d.body?qi(d.ok?502:d.status,"Local Bridge event stream is unavailable."):(await qCe(d.body,l=>{let f=Qr(BR(l.data,s.repositoryPath));Ds(f),n.emit({event:l.event,...l.data===void 0?{}:{data:f}})}),{ok:!0,status:200})}catch(d){return n.signal.aborted?qi(499,"Remote event stream was canceled."):c.aborted||d instanceof Error&&d.name==="TimeoutError"?qi(504,"Remote event stream timed out."):qi(503,"Local Bridge event stream is unavailable.")}}}async function wZ(t,e){let r=await t.list();if(!r.ok)return{ok:!1,error:qi(503,"Workspace registry is unavailable.")};let n=r.value.find(o=>o.lifecycle==="active"&&o.remoteAccess.enabled&&o.remoteAccess.scopes.includes("remote.access")&&o.workspaceId===e.workspaceId),i=E8(e.command);return n&&i.some(o=>!n.remoteAccess.scopes.includes(o))?{ok:!1,error:qi(403,"Remote command scope is not granted.")}:n?{ok:!0,value:n}:{ok:!1,error:qi(403,"Remote command Workspace is not granted.")}}function LCe(t,e){if(!e||t.workspaceId!==e.workspaceId)return;let r=IZ(t.payload);if(NR(r))return;let n=UCe(t.command,r,e);if(n)return n;let i=e.workspaceId,o=ni(r,"roadmapId");if(o&&o!==i)return;let s={...r??{},roadmapId:i},a=`/api/roadmaps/${encodeURIComponent(i)}`,c=$Ce(t.command,a,s);return c?{...c,authorizedRoot:e.repositoryPath,workspaceId:e.workspaceId,resultScope:"workspace"}:void 0}function HCe(t,e){let r=IZ(t.payload);if(NR(r))return;let n=ni(r,"roadmapId");if(n&&n!==e.workspaceId)return;let i=`/api/roadmaps/${encodeURIComponent(e.workspaceId)}`;if(t.command==="live.events")return{path:`${i}/runs/events`};if(t.command==="agentSession.events"){let o=ni(r,"sessionId");return o?{path:`${i}/agent-sessions/${encodeURIComponent(o)}/events`}:void 0}}function UCe(t,e,r){let n=o=>({...o,workspaceId:r.workspaceId,resultScope:"global"}),i=o=>({...o,authorizedRoot:r.repositoryPath,workspaceId:r.workspaceId,resultScope:"workspace"});switch(t){case"health":return n({method:"GET",path:"/health"});case"bridge.status":return n({method:"GET",path:"/api/bridge/status"});case"connection.status":return n({method:"GET",path:"/api/connection/status"});case"provider.inventory":{let o=ni(e,"backendId");return n({method:"GET",path:`/api/providers/inventory${o?`?backendId=${encodeURIComponent(o)}`:""}`})}case"modelAlias.validate":return n({method:"POST",path:"/api/model-aliases/validate",body:e??{}});case"modelAlias.resolve":return n({method:"POST",path:"/api/model-aliases/resolve",body:e??{}});case"roadmap.registry.list":return n({method:"GET",path:"/api/roadmaps/recent"});case"roadmap.registry.remove":return i({method:"POST",path:"/api/roadmaps/recent/remove",body:{roadmapId:r.workspaceId}});case"roadmap.open":return i({method:"POST",path:"/api/roadmaps/open",body:{path:r.repositoryPath}});case"roadmap.port.inspect":return i({method:"POST",path:"/api/roadmaps/port/inspect",body:{...e??{},path:r.repositoryPath}});case"roadmap.port.apply":return i({method:"POST",path:"/api/roadmaps/port/apply",body:{...e??{},path:r.repositoryPath}});case"roadmap.create":return i({method:"POST",path:"/api/roadmaps/create",body:{...e??{},path:r.repositoryPath}});default:return}}function $Ce(t,e,r){switch(t){case"roadmap.board":return{method:"GET",path:`${e}/board`};case"roadmap.worktree":return{method:"GET",path:`${e}/worktree`};case"roadmap.skills":return{method:"GET",path:`${e}/skills`};case"roadmap.commands":return{method:"POST",path:`${e}/commands`,body:r};case"execute.status":return{method:"GET",path:`${e}/runs`};case"execute.start":return{method:"POST",path:`${e}/runs/start`,body:r};case"execute.pause":return{method:"POST",path:`${e}/runs/pause`,body:r};case"execute.resume":return{method:"POST",path:`${e}/runs/resume`,body:r};case"execute.stop":return{method:"POST",path:`${e}/runs/stop`,body:r};case"execute.completeMove":return{method:"POST",path:`${e}/runs/complete-move`,body:r};case"artifactAction.list":return{method:"GET",path:`${e}/artifact-actions`};case"artifactAction.runs":return{method:"GET",path:`${e}/action-runs`};case"artifactAction.start":{let n=ni(r,"actionId");return n?{method:"POST",path:`${e}/artifact-actions/${encodeURIComponent(n)}/runs`,body:r}:void 0}case"artifactAction.stop":{let n=ni(r,"runId");return n?{method:"POST",path:`${e}/action-runs/${encodeURIComponent(n)}/stop`,body:r}:void 0}case"moveFile.tree":case"moveFile.blob":case"moveFile.diff":{let n=ni(r,"moveId");if(!n)return;let i=t.slice(9),o=ni(r,"path");return{method:"GET",path:`${e}/moves/${encodeURIComponent(n)}/files/${i}${o?`?path=${encodeURIComponent(o)}`:""}`}}case"hunsuDraft.list":return{method:"GET",path:`${e}/hunsu/drafts`};case"hunsuDraft.start":return{method:"POST",path:`${e}/hunsu/drafts`,body:r};case"hunsuDraft.get":return oS("GET",e,r);case"hunsuDraft.message":return oS("POST",e,r,"messages");case"hunsuDraft.diffArtifact.create":return oS("POST",e,r,"diff-artifacts");case"hunsuDraft.diffArtifact.get":{let n=ni(r,"draftSessionId"),i=ni(r,"diffArtifactId");return n&&i?{method:"GET",path:`${e}/hunsu/drafts/${encodeURIComponent(n)}/diff-artifacts/${encodeURIComponent(i)}`}:void 0}case"hunsuDraft.approve":return oS("POST",e,r,"approve");case"hunsuDraft.discard":return oS("POST",e,r,"discard");case"line.accept":return{method:"POST",path:`${e}/lines/accept`,body:r};case"line.reject":return{method:"POST",path:`${e}/lines/reject`,body:r};case"agentSession.list":return{method:"GET",path:`${e}/agent-sessions`};case"agentSession.get":{let n=ni(r,"sessionId");return n?{method:"GET",path:`${e}/agent-sessions/${encodeURIComponent(n)}`}:void 0}case"agentSession.events":case"live.events":return;default:return}}function oS(t,e,r,n){let i=ni(r,"draftSessionId");return i?{method:t,path:`${e}/hunsu/drafts/${encodeURIComponent(i)}${n?`/${n}`:""}`,...t==="POST"?{body:r}:{}}:void 0}function BR(t,e){if(Array.isArray(t))return t.map(i=>BR(i,e));if(typeof t=="string")return jCe(t,e);if(!sS(t))return t;let r={},n=!1;for(let[i,o]of Object.entries(t)){if(VCe(i)&&typeof o=="string"&&!FCe(o,e)){n=!0;continue}r[i]=BR(o,e)}return n&&(r.pathRedacted=!0),r}function FCe(t,e){if(!e||xZ(t))return!1;let r=MCe(t);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)}function jCe(t,e){let r=t;if(e){r=r.replaceAll(e,"[redacted-path]");let n=e.replace(/\\/gu,"/");n!==e&&(r=r.replaceAll(n,"[redacted-path]"))}return r.replace(/(?<![:\w])\/(?:home|Users|tmp|var|private|opt|srv|mnt|Volumes)\/[^\s"'<>]+/gu,"[redacted-path]").replace(/\b[A-Za-z]:\\[^\r\n"'<>]+/gu,"[redacted-path]")}async function qCe(t,e){let r=t.getReader(),n=new TextDecoder,i="";try{for(;;){let o=await r.read();if(i+=o.value?n.decode(o.value,{stream:!o.done}):n.decode(),i.length>1048576)throw new Error("Remote event buffer exceeded its bound.");for(;;){let s=WCe(i);if(!s)break;let a=i.slice(0,s.index);i=i.slice(s.index+s.length);let c=vZ(a);c&&e(c)}if(o.done){let s=vZ(i);s&&e(s);return}}}finally{r.releaseLock()}}function WCe(t){let e=t.indexOf(`
266
+
267
+ `),r=t.indexOf(`\r
268
+ \r
269
+ `);if(!(e<0&&r<0))return r>=0&&(e<0||r<e)?{index:r,length:4}:{index:e,length:2}}function vZ(t){let e="message",r=[];for(let o of t.split(/\r?\n/gu)){if(!o||o.startsWith(":"))continue;let s=o.indexOf(":"),a=s<0?o:o.slice(0,s),c=s<0?"":o.slice(s+1).replace(/^ /u,"");a==="event"&&c.trim()&&(e=c.trim().slice(0,128)),a==="data"&&r.push(c)}if(r.length===0)return;let n=r.join(`
270
+ `),i=n;try{i=JSON.parse(n)}catch{}return{event:e,data:i}}function FO(t,e){return Array.isArray(t)?t.filter(r=>!sS(r)||(ni(r,"workspaceId")??ni(r,"roadmapId"))===void 0||(ni(r,"workspaceId")??ni(r,"roadmapId"))===e).map(r=>FO(r,e)):sS(t)?Object.fromEntries(Object.entries(t).map(([r,n])=>[r,FO(n,e)])):t}function NR(t){return Array.isArray(t)?t.some(NR):sS(t)?Object.entries(t).some(([e,r])=>typeof r=="string"&&(e==="repositoryPath"||e==="projectPath"||e==="repositoryRoot"||e==="cwd"||e==="worktreePath"||e==="path"&&xZ(r))?!0:NR(r)):!1}function VCe(t){return t==="path"||t==="repositoryPath"||t==="projectPath"||t==="repositoryRoot"||t==="root"||t==="cwd"||t==="worktreePath"||t==="runtimePath"}function qi(t,e){return{ok:!1,status:t,error:e}}function IZ(t){return sS(t)?t:void 0}function ni(t,e){let r=t?.[e];return typeof r=="string"&&r.trim()?r.trim():void 0}function sS(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}import{timingSafeEqual as GCe}from"node:crypto";function kZ(t){return async(e,r,n)=>{if(!n.pathname.startsWith("/v1/control"))return!1;if(!zCe(e,t.controlToken()))return Yr(r,401,pr("BRIDGE_CONTROL_UNAUTHORIZED","Hunsu Bridge rejected the local control credential.")),!0;try{let i=n.pathname;if(e.method==="GET"&&i==="/v1/control/status")return Yr(r,200,mr("Hunsu Bridge is running.",t.runtimeIdentity())),!0;if(e.method==="POST"&&i==="/v1/control/credential/rotate")return await t.rotateControlToken(),Yr(r,200,mr("Hunsu Bridge control credential was rotated.",{rotated:!0,pairingPreserved:!0},"CONTROL_CREDENTIAL_ROTATED")),!0;if(e.method==="GET"&&i==="/v1/control/provider"){let[s,a]=await Promise.all([t.providerService.list(),t.providerService.status(n.searchParams.get("force")==="1")]);return Yr(r,200,mr("Codex provider status is available.",{providers:s,provider:a})),!0}if(e.method==="PUT"&&i==="/v1/control/provider"){let s=await $h(e);if(s.providerId!=="codex")throw new De("PROVIDER_NOT_CONFIGURED","The first headless Bridge prerelease supports only Codex.");let a=s.reset===!0?await t.providerService.resetCodex():await t.providerService.setCodex({binaryPath:Ff(s.binaryPath),home:Ff(s.home)});return Yr(r,200,mr(s.reset===!0?"Codex provider configuration was reset.":"Codex provider was configured.",{provider:a})),!0}if(e.method==="POST"&&i==="/v1/control/provider/check"){let s=await t.providerService.status(!0);if(!s.installed)throw new De("PROVIDER_BINARY_NOT_FOUND",s.safeMessage??"Codex was not found.");if(!s.configured)throw new De("PROVIDER_CHECK_FAILED",s.safeMessage??"Codex could not initialize.");return Yr(r,200,mr(s.ready?"Codex is ready.":"Codex was checked and needs attention.",{provider:s})),!0}if(e.method==="GET"&&i==="/v1/control/workspaces")return $f(r,await t.workspaceService.list(),"Workspaces are available."),!0;if(e.method==="POST"&&i==="/v1/control/workspaces"){let s=await $h(e);return $f(r,await t.workspaceService.add(XCe(s.path,"Workspace path"),{displayName:Ff(s.displayName)}),"Workspace was added.",201),!0}let o=KCe(i);if(o&&e.method==="GET"&&o.action==="inspect")return $f(r,await t.workspaceService.get(o.workspaceId),"Workspace is available."),!0;if(o&&e.method==="DELETE"&&o.action==="inspect")return $f(r,await t.workspaceService.remove(o.workspaceId),"Workspace was removed."),!0;if(o&&e.method==="POST"&&o.action==="open"){let s=await t.workspaceService.open(o.workspaceId);if(!s.ok)return $f(r,s,"Workspace could not be opened."),!0;let a=EZ(t.pairingService.rotate({browserUrl:t.webUrl??"https://hunsu.app/studio",workspaceId:o.workspaceId})),c=!1;try{await t.openBrowser(a.internal.pairingUrl),c=!0,t.pairingService.markBrowserOpened(a.safe.pairingId)}catch{c=!1}return Yr(r,c?200:503,c?mr("Workspace was opened in Hunsu Web.",{workspace:s.value,...a.safe,browserOpened:c}):pr("BROWSER_OPEN_FAILED","The Workspace is paired, but the browser could not be opened.")),!0}if(o&&e.method==="PUT"&&o.action==="remote-access"){let s=await $h(e);if(typeof s.enabled!="boolean")throw new De("BRIDGE_STATE_INVALID","Workspace Remote access requires an enabled boolean.");let a=s.enabled?JCe(s.scopes):[];return $f(r,await t.workspaceService.setRemoteAccess(o.workspaceId,{enabled:s.enabled,scopes:a}),s.enabled?"Workspace Remote access was granted.":"Workspace Remote access was revoked."),!0}if(e.method==="POST"&&(i==="/v1/control/pair"||o?.action==="pair")){let s=await $h(e,!0),a=o?.workspaceId??Ff(s.workspaceId);if(a){let d=await t.workspaceService.get(a);if(!d.ok)return $f(r,d,"Workspace was not found."),!0}let c=EZ(t.pairingService.rotate({browserUrl:Ff(s.webUrl)??t.webUrl??"https://hunsu.app/studio",...a?{workspaceId:a}:{}})),u=!1;if(s.openBrowser===!0)try{await t.openBrowser(c.internal.pairingUrl),u=!0,t.pairingService.markBrowserOpened(c.safe.pairingId)}catch{throw new De("BROWSER_OPEN_FAILED","Pairing was created, but the browser could not be opened.")}return Yr(r,201,mr("A short-lived Hunsu Web pairing was created.",{...c.safe,browserOpened:u})),!0}if(e.method==="POST"&&i==="/v1/control/pair/revoke"){let s=await $h(e,!0),a=t.pairingService.revoke(Ff(s.pairingId));return Yr(r,a?200:404,a?mr("The active browser pairing credential was revoked.",{revoked:!0}):pr("PAIRING_ROTATION_FAILED","No matching active browser pairing credential was found.")),!0}if(e.method==="POST"&&i==="/v1/control/login"){let s=await $h(e,!0),a=await t.remoteService.login({openBrowser:s.openBrowser!==!1});return Yr(r,202,mr("Hunsu sign-in is waiting for browser or device-code approval.",a)),!0}if(e.method==="POST"&&i==="/v1/control/logout")return await t.remoteService.logout(),Yr(r,200,mr("Signed out of Hunsu and disabled Remote Bridge.")),!0;if(e.method==="GET"&&i==="/v1/control/remote")return Yr(r,200,mr("Remote Bridge status is available.",await t.remoteService.status())),!0;if(e.method==="POST"&&i==="/v1/control/remote/enable")return Yr(r,200,mr("Remote Bridge is enabled.",await t.remoteService.enable())),!0;if(e.method==="POST"&&i==="/v1/control/remote/disable")return Yr(r,200,mr("Remote Bridge is disabled.",await t.remoteService.disable())),!0;if(e.method==="GET"&&i==="/v1/control/doctor")return Yr(r,200,mr("Bridge diagnostics completed.",await t.doctor())),!0;if(e.method==="GET"&&i==="/v1/control/logs"){let s=Number.parseInt(n.searchParams.get("limit")??"200",10);return Yr(r,200,mr("Bridge logs are available.",{events:await t.structuredLog.read({limit:Number.isFinite(s)?Math.max(1,Math.min(1e3,s)):200})})),!0}return e.method==="POST"&&i==="/v1/control/shutdown"?(Yr(r,202,mr("Hunsu Bridge is shutting down.")),setImmediate(t.onShutdown),!0):(Yr(r,404,pr("BRIDGE_CONTROL_UNAVAILABLE","Unknown Hunsu Bridge control route.")),!0)}catch(i){let o=Wa(i);return Yr(r,YCe(o.code),o),!0}}}function zCe(t,e){let r=t.headers[Au.toLowerCase()],n=Array.isArray(r)?r[0]:r;if(!n)return!1;let i=Buffer.from(n),o=Buffer.from(e);return i.length===o.length&&GCe(i,o)}function Yr(t,e,r){let n=JSON.stringify(r);t.writeHead(e,{"content-type":"application/json; charset=utf-8","content-length":Buffer.byteLength(n),"cache-control":"no-store"}),t.end(n)}function $f(t,e,r,n=200){e.ok?Yr(t,n,mr(r,e.value)):Yr(t,e.error.code==="WORKSPACE_NOT_FOUND"?404:400,pr(e.error.code,e.error.message))}async function $h(t,e=!1){let r=[],n=0;for await(let i of t){let o=Buffer.isBuffer(i)?i:Buffer.from(i);if(n+=o.length,n>1048576)throw new De("BRIDGE_STATE_INVALID","Control request body is too large.");r.push(o)}if(r.length===0&&e)return{};try{let i=JSON.parse(Buffer.concat(r).toString("utf8"));if(!i||typeof i!="object"||Array.isArray(i))throw new Error("object required");return i}catch{throw new De("BRIDGE_STATE_INVALID","Control request body must be a JSON object.")}}function KCe(t){let e=t.match(/^\/v1\/control\/workspaces\/([^/]+)(?:\/(pair|open|remote-access))?$/);if(e?.[1])return{workspaceId:decodeURIComponent(e[1]),action:e[2]==="pair"?"pair":e[2]==="open"?"open":e[2]==="remote-access"?"remote-access":"inspect"}}function JCe(t){if(!Array.isArray(t)||t.length===0)throw new De("BRIDGE_STATE_INVALID","Workspace Remote access requires at least one explicit scope.");let e=t.map(r=>{if(typeof r!="string"||!pp.includes(r))throw new De("BRIDGE_STATE_INVALID","Workspace Remote access contains an unsupported scope.");return r});if(!e.includes("remote.access"))throw new De("BRIDGE_STATE_INVALID","Workspace Remote access requires the remote.access scope.");return[...new Set(e)]}function XCe(t,e){let r=Ff(t);if(!r)throw new De("BRIDGE_STATE_INVALID",`${e} is required.`);return r}function Ff(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function YCe(t){return t==="WORKSPACE_NOT_FOUND"?404:t==="BRIDGE_CONTROL_UNAUTHORIZED"?401:t==="PROVIDER_BINARY_NOT_FOUND"||t==="PROVIDER_LOGIN_REQUIRED"||t==="ACCOUNT_LOGIN_REQUIRED"?409:400}function EZ(t){if(!t.ok)throw new De(t.error.code,t.error.message);return t.value}import{constants as jO}from"node:fs";import{mkdir as QCe,open as ZCe,readFile as ePe,unlink as tPe}from"node:fs/promises";import{dirname as rPe}from"node:path";async function AZ(t){let e=t.pid??process.pid,r=t.now??(()=>new Date),n=t.processAlive??nPe,i=t.fetchImpl??fetch;await QCe(rPe(t.paths.daemonLockFile),{recursive:!0});for(let o=0;o<2;o+=1)try{let s=await ZCe(t.paths.daemonLockFile,jO.O_CREAT|jO.O_EXCL|jO.O_WRONLY,384);try{await s.writeFile(`${JSON.stringify({pid:e,createdAt:r().toISOString()})}
271
+ `,"utf8")}finally{await s.close()}let a=await OR({endpoint:t.endpoint,controlToken:t.controlToken,fetchImpl:i});if(a.kind!=="unreachable")throw await qO(t.paths.daemonLockFile),RZ(a);let c=!1;return{async release(){c||(c=!0,await qO(t.paths.daemonLockFile))}}}catch(s){if(s instanceof De||!oPe(s))throw s;let a=await iPe(t.paths.daemonLockFile),c=await OR({endpoint:t.endpoint,controlToken:t.controlToken,fetchImpl:i});if(a!==void 0&&!n(a)&&c.kind==="unreachable"&&o===0){await qO(t.paths.daemonLockFile);continue}throw c.kind!=="unreachable"?RZ(c):new De("BRIDGE_ALREADY_RUNNING","Another Hunsu Bridge daemon startup is already in progress.")}throw new De("BRIDGE_ALREADY_RUNNING","Another Hunsu Bridge daemon startup is already in progress.")}async function OR(t){let e=t.fetchImpl??fetch,r=t.timeoutMs??750,n;try{n=await e(new URL("/health",t.endpoint),{redirect:"error",signal:AbortSignal.timeout(r)})}catch{return{kind:"unreachable"}}if(!n.ok)return{kind:"foreign"};let i=await n.json().catch(()=>{});if(i?.ok!==!0||i.service!=="hunsu-bridge"||i.protocolVersion!=="local-bridge-v1")return{kind:"foreign"};try{let o=await e(new URL("/v1/control/status",t.endpoint),{headers:{[Au]:t.controlToken},redirect:"error",signal:AbortSignal.timeout(r)});if(!o.ok)return{kind:"hunsu-unauthenticated"};let s=await o.json().catch(()=>{});return s?.ok===!0?{kind:"hunsu-authenticated",...typeof s.value?.instanceId=="string"?{instanceId:s.value.instanceId}:{}}:{kind:"hunsu-unauthenticated"}}catch{return{kind:"hunsu-unauthenticated"}}}function nPe(t){if(!Number.isSafeInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return WO(e,"EPERM")}}function RZ(t){return t.kind==="hunsu-authenticated"?new De("BRIDGE_ALREADY_RUNNING","Hunsu Bridge is already running."):new De("BRIDGE_PORT_IN_USE","The configured Hunsu Bridge port is already in use by another service.")}async function iPe(t){try{let e=JSON.parse(await ePe(t,"utf8"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}async function qO(t){try{await tPe(t)}catch(e){if(!WO(e,"ENOENT"))throw e}}function oPe(t){return WO(t,"EEXIST")}function WO(t,e){return t instanceof Error&&"code"in t&&t.code===e}async function dPe(t){try{await t.credentialStore.rotateControlToken({onCommitted:e=>t.activate(e.controlToken)})}catch(e){let r=await t.credentialStore.read().catch(()=>{});throw r&&t.activate(r.controlToken),e}}async function PZ(t={}){let e={...process.env,...t.env??{}},r=Yo({...t,env:e}),n=t.runtimePath??t.cwd??process.cwd();if(t.runtimePath!==void 0&&!cPe(t.runtimePath)||/[\u0000-\u001f\u007f]/u.test(n))throw new De("BRIDGE_STATE_INVALID","Bridge runtime path must be absolute and contain no control characters.");let i=uPe(n);await aPe(r.home,{recursive:!0,mode:448});let o=Qo(r),s=wu(r,{processEnv:e}),a=zb(r),c=t.deploymentProfile??"production";if(!Pn(c))throw new De("BRIDGE_STATE_INVALID","Bridge deployment profile must be production or preview.");let u=await o.ensureDeploymentProfile(c),d=lPe({profile:u.deploymentProfile,development:t.development===!0,environment:e,webUrl:t.webUrl}),l=t.host??u.host,f=t.port??u.port;if(hPe(l),!Number.isInteger(f)||f<0||f>65535)throw new De("BRIDGE_STATE_INVALID","Bridge port must be an integer from 0 through 65535.");let p=await s.read(),g=r0(VO(u.host),u.port),v=await AZ({paths:r,endpoint:g,controlToken:p?.controlToken??"hunsu_control_unavailable",fetchImpl:t.fetchImpl}),b;try{b=await s.ensure();let B=r0(VO(l),f);if(B!==g){let K=await OR({endpoint:B,controlToken:b.controlToken,fetchImpl:t.fetchImpl});if(K.kind!=="unreachable")throw K.kind==="hunsu-authenticated"?new De("BRIDGE_ALREADY_RUNNING","Hunsu Bridge is already running."):new De("BRIDGE_PORT_IN_USE","The configured Hunsu Bridge port is already in use by another service.")}(l!==u.host||f!==u.port)&&await o.update(K=>({...K,host:l,port:f}))}catch(B){throw await v.release().catch(()=>{}),B}let C=b.controlToken,D=UU({paths:r}),_=vw({store:Wb(r)}),F=K5({configStore:o,env:{...e,HUNSU_HOME:r.home}}),he=Vb({controlToken:b.controlToken}),z,Ce=SZ({workspaceService:_,endpoint:()=>z?.endpoint,controlToken:()=>C,fetchImpl:t.fetchImpl}),de=bZ({workspaceService:_,endpoint:()=>z?.endpoint,controlToken:()=>C,fetchImpl:t.fetchImpl}),R=hZ({configStore:o,credentialStore:s,workspaceService:_,deploymentProfile:u.deploymentProfile,connectApiUrl:d.connectApiUrl,connectWsUrl:d.connectWsUrl,connectTicketIssuer:d.connectTicketIssuer,connectTicketSigningKeyId:d.connectTicketSigningKeyId,connectTicketSigningPublicJwk:d.connectTicketSigningPublicJwk,fetchImpl:t.fetchImpl,socketFactory:t.socketFactory,peerTransportFactory:t.peerTransportFactory,openBrowser:t.openBrowser??lP,onCommand:Ce,onCommandStream:de}),V=new Date().toISOString(),le=t.serviceManager??gPe(t.development===!0,t.platform??process.platform),se=`bridge_${sPe(16).toString("base64url")}`,H,G,j=!1,me,Pe=new Promise(B=>{me=B}),Te=async()=>{j||(j=!0,G&&clearInterval(G),R.stop(),z&&await a.clear(z.instanceId).catch(()=>!1),await v.release().catch(()=>{}),await D.append({level:"info",event:"daemon.stopped",message:"Hunsu Bridge stopped."}).catch(()=>{}),me())},P=async()=>{let B=H;if(!B||!B.listening){await Te();return}await new Promise((K,T)=>{B.close($=>$?T($):K())}),await Pe};try{let B={...e,HUNSU_HOME:r.home,HUNSU_BRIDGE_HOST:l,HUNSU_BRIDGE_PORT:String(f),HUNSU_ROADMAP_REGISTRY_PATH:r.workspacesFile,HUNSU_WEB_URL:d.webUrl,HUNSU_CONNECT_API_BASE_URL:d.connectApiUrl,HUNSU_CONNECT_WS_URL:d.connectWsUrl},K=Yf(wS(B,{cwd:t.cwd??process.cwd(),roadmapRegistryPath:r.workspacesFile,processEnv:B})),T=d.webUrl,$=new URL(T).origin,ye=kZ({controlToken:()=>C,rotateControlToken:async()=>{await dPe({credentialStore:s,activate:_t=>{C=_t}}),await D.append({level:"info",event:"control.credential_rotated",message:"Hunsu Bridge control credential was rotated."}).catch(()=>{})},runtimeIdentity:()=>{if(!z)throw new De("BRIDGE_CONTROL_UNAVAILABLE","Hunsu Bridge is still starting.");return z},providerService:F,workspaceService:_,pairingService:he,remoteService:R,structuredLog:D,webUrl:T,openBrowser:t.openBrowser??lP,doctor:()=>Aw({paths:r,providerService:F,online:!0}),onShutdown:()=>{P()}});H=aH({cwd:t.cwd??process.cwd(),roadmapRegistryPath:r.workspacesFile,runtimeConfig:K,deploymentProfile:u.deploymentProfile,controlStatus:{deploymentProfile:u.deploymentProfile},security:{controlToken:()=>C,allowedOrigins:[$],requirePairing:!0,pairingService:he},controlRouteHandler:ye,providerService:F,headlessRemote:{enable:()=>R.enable(),disable:()=>R.disable()}}),H.once("close",()=>{Te()}),await mPe(H,l,f);let be=H.address();if(!be||typeof be=="string")throw new De("BRIDGE_CONTROL_UNAVAILABLE","Bridge listener address is unavailable.");let ct=r0(VO(l),be.port),It=new Date().toISOString();return z={schema:Zg,instanceId:se,daemonPid:process.pid,version:bn,protocolVersion:rl,deploymentProfile:u.deploymentProfile,startedAt:V,endpoint:ct,runtimePath:i,serviceManager:le,lastHealthyAt:It},await a.write(z),f===0&&await o.update(_t=>({..._t,host:l,port:be.port})),await v.release(),await D.append({level:"info",event:"daemon.started",message:"Hunsu Bridge is ready.",data:{instanceId:se,endpoint:ct,version:bn,serviceManager:le,deploymentProfile:u.deploymentProfile}}),G=setInterval(()=>{z&&(z={...z,lastHealthyAt:new Date().toISOString()},a.write(z).catch(_t=>D.append({level:"error",event:"runtime.write_failed",message:_t instanceof Error?_t.message:"Runtime identity update failed."}).then(()=>{})))},3e4),G.unref(),(await o.read()).remote.enabled&&R.enable().catch(_t=>D.append({level:"warn",event:"remote.connect_failed",message:_t instanceof Error?_t.message:"Remote Bridge could not connect."}).then(()=>{})),{identity:z,paths:r,server:H,close:P,waitUntilClosed:()=>Pe}}catch(B){throw H?.listening&&await new Promise(K=>H.close(()=>K())),await Te(),yPe(B,"EADDRINUSE")?new De("BRIDGE_PORT_IN_USE","The configured Hunsu Bridge port is already in use.",{cause:B}):B}}function lPe(t){let e=B3(t.profile),r=fPe(t.environment);if(!t.development){if(r.present)throw new De("BRIDGE_STATE_INVALID","Installed Bridge daemons reject development Connect signing-trust overrides.");if(t.webUrl!==void 0&&t.webUrl!==e.webUrl)throw new De("BRIDGE_STATE_INVALID",`Installed ${t.profile} Bridge daemons use the allowlisted Web URL for that profile.`);return e}let n=t.environment.HUNSU_CONNECT_API_BASE_URL??e.connectApiUrl,i=t.environment.HUNSU_CONNECT_WS_URL??e.connectWsUrl,o=r.present?pPe(r,n,i):{connectTicketIssuer:e.connectTicketIssuer,connectTicketSigningKeyId:e.connectTicketSigningKeyId,connectTicketSigningPublicJwk:e.connectTicketSigningPublicJwk};return{webUrl:t.webUrl??t.environment.HUNSU_WEB_URL??e.webUrl,connectApiUrl:n,connectWsUrl:i,...o}}function fPe(t){let e=t.HUNSU_DEVELOPMENT_CONNECT_TICKET_ISSUER,r=t.HUNSU_DEVELOPMENT_CONNECT_TICKET_SIGNING_KEY_ID,n=t.HUNSU_DEVELOPMENT_CONNECT_TICKET_SIGNING_PUBLIC_JWK,i=e?.trim()||void 0,o=r?.trim()||void 0,s=n?.trim()||void 0;return{present:e!==void 0||r!==void 0||n!==void 0,issuer:i,keyId:o,publicJwk:s}}function pPe(t,e,r){if(!t.issuer||!t.keyId||!t.publicJwk)throw new De("BRIDGE_STATE_INVALID","Development Connect signing trust requires issuer, key id, and public JWK together.");let n,i,o;try{n=new URL(e),i=new URL(r),o=new URL(t.issuer)}catch(u){throw new De("BRIDGE_STATE_INVALID","Development Connect fixture URLs are invalid.",{cause:u})}let s=new URL(i.toString());if(s.protocol="http:",n.protocol!=="http:"||i.protocol!=="ws:"||!CZ(n.hostname)||!CZ(i.hostname)||n.pathname!=="/"||n.search||n.hash||i.pathname!=="/v1/connect/device"||i.search||i.hash||s.origin!==n.origin||o.origin!==n.origin||o.pathname!=="/"||o.search||o.hash||n.username||n.password||i.username||i.password||o.username||o.password)throw new De("BRIDGE_STATE_INVALID","Development Connect signing trust is limited to an exact loopback HTTP/WS fixture.");if(!/^connect-[A-Za-z0-9_-]{16,64}$/u.test(t.keyId))throw new De("BRIDGE_STATE_INVALID","Development Connect signing key id is invalid.");let a;try{a=JSON.parse(t.publicJwk)}catch(u){throw new De("BRIDGE_STATE_INVALID","Development Connect signing public JWK is invalid.",{cause:u})}let c=y8(a,"developmentConnectTicketSigningPublicJwk");if(!c.ok)throw new De("BRIDGE_STATE_INVALID","Development Connect signing public JWK must be a public P-256 key.");return{connectTicketIssuer:o.origin,connectTicketSigningKeyId:t.keyId,connectTicketSigningPublicJwk:c.value}}function CZ(t){return t==="127.0.0.1"||t==="localhost"||t==="::1"||t==="[::1]"}function mPe(t,e,r){return new Promise((n,i)=>{let o=s=>i(s);t.once("error",o),t.listen(r,e,()=>{t.off("error",o),n()})})}function hPe(t){if(t!=="127.0.0.1"&&t!=="localhost"&&t!=="::1"&&t!=="[::1]")throw new De("BRIDGE_STATE_INVALID","Hunsu Bridge must bind to a loopback address.")}function VO(t){return t==="localhost"?"127.0.0.1":t==="[::1]"?"::1":t}function gPe(t,e){return t?"development":e==="win32"?"windows-task-scheduler":e==="darwin"?"macos-launch-agent":"linux-systemd-user"}function yPe(t,e){return t instanceof Error&&"code"in t&&t.code===e}var _Z=new Set(["home","json","help","version"]),DZ=new Set(["json","help","version","follow","delete-data","confirm-delete-data","no-open","dry-run"]),vPe=new Set(["home","host","port","cwd","web-url","profile","channel","runtime-package","runtime-path","binary","codex-home","workspace","scopes"]);function GO(t){let e=new Map,r=[];for(let i=0;i<t.length;i+=1){let o=t[i];if(!o.startsWith("--")){r.push(o);continue}let s=o.slice(2);if(!s)throw Fh("Invalid empty command option.");let a=s.indexOf("="),c=a>=0?s.slice(0,a):s;if(xPe(c),e.has(c))throw Fh(`Duplicate option: --${c}.`);if(DZ.has(c)){if(a>=0)throw Fh(`--${c} does not accept a value.`);e.set(c,!0);continue}let u=a>=0?s.slice(a+1):t[i+1];if(!u||a<0&&u.startsWith("--"))throw Fh(`--${c} requires a value.`);e.set(c,u),a<0&&(i+=1)}let n={positionals:r,flags:e};return SPe(n),n}function BZ(t){return t.some(e=>e==="--json"||e.startsWith("--json="))}function Mr(t,e){let r=t.flags.get(e);return typeof r=="string"?r:void 0}function Cs(t,e){return t.flags.get(e)===!0}function xPe(t){if(!DZ.has(t)&&!vPe.has(t))throw Fh(`Unknown option: --${t}.`)}function SPe(t){let e=t.positionals[0];if(!e){TZ(t,_Z,"help");return}let r=new Set(_Z);switch(e){case"dev":case"daemon":Zc(r,"host","port","cwd","web-url","runtime-path","profile");break;case"setup":Zc(r,"channel","runtime-package","dry-run","profile");break;case"remove":Zc(r,"delete-data","confirm-delete-data","dry-run","profile");break;case"status":case"doctor":Zc(r,"profile");break;case"logs":Zc(r,"follow");break;case"provider":t.positionals[1]==="set"&&Zc(r,"binary","codex-home");break;case"workspace":t.positionals[1]==="grant"&&Zc(r,"scopes");break;case"pair":case"open":Zc(r,"workspace");break;case"login":Zc(r,"no-open");break;default:break}TZ(t,r,e)}function Zc(t,...e){for(let r of e)t.add(r)}function TZ(t,e,r){for(let n of t.flags.keys())if(!e.has(n))throw Fh(`Option --${n} is not supported by ${r}.`)}function Fh(t){return new De("BRIDGE_STATE_INVALID",t)}var bPe=new Set(["status","doctor","logs","provider","workspace","credential","pair","open","login","logout","remote"]),MR=2e4;function NZ(t){return bPe.has(t)}async function OZ(t){let{parsed:e,paths:r,client:n,emit:i}=t,o=e.positionals[0];if(o==="status")return i(await n.request("/v1/control/status"));if(o==="doctor"){let s=await n.request("/v1/control/doctor"),a=!s.ok&&(s.code==="BRIDGE_NOT_RUNNING"||s.code==="BRIDGE_STATE_INVALID")?mr("Offline Bridge diagnostics completed.",await Aw({paths:r,online:!1})):s;return i(a)}if(o==="logs"){let s=await n.request("/v1/control/logs"),a=i(s);return a!==0||!Cs(e,"follow")?a:kPe(n,i)}if(o==="provider")return i(await wPe(e,n));if(o==="workspace")return i(await IPe(e,n));if(o==="credential"){let s=e.positionals[1];if(s!=="rotate")throw new De("BRIDGE_STATE_INVALID",`Unknown credential command: ${s??""}`);return i(await n.request("/v1/control/credential/rotate",{method:"POST"}))}if(o==="pair"||o==="open")return o==="pair"&&e.positionals[1]==="revoke"?i(await n.request("/v1/control/pair/revoke",{method:"POST"})):i(await n.request("/v1/control/pair",{method:"POST",body:{...Mr(e,"workspace")?{workspaceId:Mr(e,"workspace")}:{},openBrowser:o==="open"}}));if(o==="login")return i(await n.request("/v1/control/login",{method:"POST",body:{openBrowser:!Cs(e,"no-open")}}));if(o==="logout")return i(await n.request("/v1/control/logout",{method:"POST"}));if(o==="remote"){let s=e.positionals[1]??"status";if(s==="status")return i(await n.request("/v1/control/remote"));if(s==="enable"||s==="disable")return i(await n.request(`/v1/control/remote/${s}`,{method:"POST"}));throw new De("BRIDGE_STATE_INVALID",`Unknown remote command: ${s}`)}throw new De("BRIDGE_STATE_INVALID",`Unknown client command: ${o}`)}async function wPe(t,e){let r=t.positionals[1]??"status";if(r==="list"||r==="status")return e.request(`/v1/control/provider${r==="status"?"":"?list=1"}`,{timeoutMs:MR});if(r==="check")return zO(t.positionals[2]),e.request("/v1/control/provider/check",{method:"POST",timeoutMs:MR});if(r==="set"){zO(t.positionals[2]);let n=await e.request("/v1/control/provider",{method:"PUT",timeoutMs:MR,body:{providerId:"codex",...Mr(t,"binary")?{binaryPath:Mr(t,"binary")}:{},...Mr(t,"codex-home")?{home:Mr(t,"codex-home")}:{}}});return!n.ok&&n.code==="BRIDGE_NOT_RUNNING"&&Mr(t,"home")&&!Mr(t,"codex-home")?pr("BRIDGE_NOT_RUNNING","Hunsu Bridge is not running at the selected HUNSU_HOME. --home selects HUNSU_HOME; use --codex-home to configure Codex Home."):n}if(r==="reset")return zO(t.positionals[2]),e.request("/v1/control/provider",{method:"PUT",timeoutMs:MR,body:{providerId:"codex",reset:!0}});throw new De("BRIDGE_STATE_INVALID",`Unknown provider command: ${r}`)}async function IPe(t,e){let r=t.positionals[1]??"list";if(r==="list")return e.request("/v1/control/workspaces");if(r==="add"){let o=t.positionals[2];if(!o)throw new De("WORKSPACE_PATH_INVALID","Workspace path is required.");return e.request("/v1/control/workspaces",{method:"POST",body:{path:o}})}let n=t.positionals[2];if(!n)throw new De("WORKSPACE_NOT_FOUND","Workspace id is required.");let i=encodeURIComponent(n);if(r==="inspect")return e.request(`/v1/control/workspaces/${i}`);if(r==="remove")return e.request(`/v1/control/workspaces/${i}`,{method:"DELETE"});if(r==="open")return e.request(`/v1/control/workspaces/${i}/open`,{method:"POST"});if(r==="grant"||r==="revoke"){let o=r==="revoke"?[]:EPe(Mr(t,"scopes"));return e.request(`/v1/control/workspaces/${i}/remote-access`,{method:"PUT",body:{enabled:r==="grant",scopes:o}})}throw new De("BRIDGE_STATE_INVALID",`Unknown workspace command: ${r}`)}function EPe(t){let r=(t??"remote.access").split(",").map(n=>n.trim()).filter(Boolean).map(n=>{if(!pp.includes(n))throw new De("BRIDGE_STATE_INVALID",`Unsupported Workspace Remote scope: ${n}`);return n});if(!r.includes("remote.access"))throw new De("BRIDGE_STATE_INVALID","Workspace Remote grants require remote.access.");return[...new Set(r)]}async function kPe(t,e){let r=!1,n=()=>{r=!0};process.once("SIGINT",n),process.once("SIGTERM",n);try{for(;!r&&(await new Promise(o=>setTimeout(o,1e3)),!r);){let i=await t.request("/v1/control/logs?limit=50");if(e(i)!==0)return 1}return 0}finally{process.off("SIGINT",n),process.off("SIGTERM",n)}}function zO(t){if(t!=="codex")throw new De("PROVIDER_NOT_CONFIGURED","The first headless Bridge prerelease supports only Codex.")}import{homedir as jPe}from"node:os";import{homedir as OPe}from"node:os";import{join as MPe}from"node:path";import{execFile as RPe}from"node:child_process";import{access as APe,mkdir as MZ,readFile as CPe,rm as PPe,writeFile as _Pe}from"node:fs/promises";import{dirname as HZ,isAbsolute as TPe,win32 as DPe}from"node:path";function qh(t,e){let r=e.sleep??(u=>new Promise(d=>setTimeout(d,u))),n=Math.max(1,e.stopTimeoutMs??8e3),i=Math.max(1,e.pollIntervalMs??100),o,s=async()=>{let[u,d,l]=await Promise.all([KO(t),UZ(e.probeHealth),o?Promise.resolve(o):e.readInstalledRuntime?.().catch(()=>{})??Promise.resolve(void 0)]),f=d==="healthy"?await NPe(e.probeAuthenticatedStatus):"unavailable";return{installed:u.installed,manager:t.manager,managerState:u.state,health:d,authentication:f,definitionPath:t.definitionPath,packageVersion:l?.packageVersion,runtimePath:l?.runtimePath,deploymentProfile:l?.deploymentProfile,detail:u.detail}},a=async()=>{let u=!1;try{u=await e.requestAuthenticatedShutdown()}catch{u=!1}if(u&&await LZ(e.probeHealth,r,n,i)==="offline")return jf(t.manager,"Hunsu Bridge stopped through its authenticated control API.",!0);try{await t.stopOwned()}catch{return qf(t.manager,"SERVICE_STOP_FAILED","The owned Hunsu Bridge service could not be stopped.")}return await LZ(e.probeHealth,r,n,i)==="healthy"?qf(t.manager,"SERVICE_STOP_FAILED","The owned Hunsu Bridge service stopped, but the Bridge endpoint remained healthy."):jf(t.manager,"Hunsu Bridge stopped through its OS user service manager.",!0)},c={async install(u){try{BPe(u,t.platform);let d=await t.install(u);return o={packageVersion:u.packageVersion,runtimePath:u.runtimePath,deploymentProfile:u.deploymentProfile},d.changed?jf(t.manager,"Hunsu Bridge user service installed. It was not started.",!0):jf(t.manager,"Hunsu Bridge user service is already installed.",!1,"SERVICE_ALREADY_INSTALLED")}catch{return qf(t.manager,"SERVICE_INSTALL_FAILED","Hunsu Bridge user service installation failed.")}},async uninstall(){if(!(await KO(t)).installed)return jf(t.manager,"Hunsu Bridge user service is not installed.",!1);if(!(await a()).ok)return qf(t.manager,"SERVICE_STOP_FAILED","Hunsu Bridge must stop before its user service can be uninstalled.");try{let l=await t.uninstall();return jf(t.manager,"Hunsu Bridge user service uninstalled.",l.changed)}catch{return qf(t.manager,"SERVICE_INSTALL_FAILED","Hunsu Bridge user service uninstallation failed.")}},async start(){if(!(await KO(t)).installed)return qf(t.manager,"SERVICE_NOT_INSTALLED","Install the Hunsu Bridge user service before starting it.");try{return await t.start(),jf(t.manager,"Hunsu Bridge start requested through its OS user service manager.",!0)}catch{return qf(t.manager,"SERVICE_START_FAILED","The Hunsu Bridge user service could not be started.")}},stop:a,async restart(){let u=await a();return u.ok?c.start():u},status:s};return c}var LR={async exists(t){try{return await APe(t),!0}catch{return!1}},async readText(t){try{return await CPe(t,"utf8")}catch{return}},async mkdir(t,e){await MZ(t,{recursive:!0,mode:e?.mode})},async writeText(t,e,r){await MZ(HZ(t),{recursive:!0,mode:448}),await _Pe(t,e,{encoding:"utf8",mode:r?.mode})},async remove(t){await PPe(t,{force:!0})}},JO=(t={})=>e=>new Promise(r=>{RPe(e.command,e.args,{encoding:"utf8",...kb(e.command)?{env:Ko(t)}:{},windowsHide:!0,maxBuffer:1024*1024},(n,i,o)=>{let s=n&&"code"in n&&typeof n.code=="number"?n.code:n?1:0;r({exitCode:s,stdout:i??"",stderr:o??(n instanceof Error?n.message:"")})})}),HR=JO();async function UR(t,e,r){return await t.readText(e)===r?!1:(await t.mkdir(HZ(e),{mode:448}),await t.writeText(e,r,{mode:384}),!0)}function BPe(t,e){let r=e==="win32"?DPe.isAbsolute:TPe;for(let[n,i]of Object.entries({nodePath:t.nodePath,cliPath:t.cliPath,hunsuHome:t.hunsuHome,runtimePath:t.runtimePath}))if(!i||!r(i)||jh(i))throw new Error(`${n} must be an absolute path without control characters.`);if(!t.packageVersion.trim()||jh(t.packageVersion))throw new Error("packageVersion must be non-empty and contain no control characters.");if(!Pn(t.deploymentProfile))throw new Error("deploymentProfile must be production or preview.")}function XO(t){if(jh(t))throw new Error("systemd values cannot contain control characters.");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`}function Md(t){if(jh(t))throw new Error("plist values cannot contain control characters.");return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Ca(t){if(jh(t))throw new Error("PowerShell values cannot contain control characters.");return`'${t.replace(/'/g,"''")}'`}function $R(t){if(jh(t)||t.includes('"'))throw new Error("Windows command arguments cannot contain control characters or quotes.");return`"${t.replace(/(\\+)$/u,"$1$1")}"`}async function KO(t){try{return await t.status()}catch{return{installed:!1,state:"unknown",detail:"Service-manager status is unavailable."}}}async function UZ(t){try{return await t()?"healthy":"offline"}catch{return"unavailable"}}async function NPe(t){if(!t)return"unavailable";try{return(await t()).state}catch{return"unavailable"}}async function LZ(t,e,r,n){let i=Math.max(1,Math.ceil(r/n));for(let o=0;o<i;o+=1){let s=await UZ(t);if(s!=="healthy")return s;o+1<i&&await e(n)}return"healthy"}function jf(t,e,r,n="OK"){return{ok:!0,code:n,message:e,manager:t,changed:r}}function qf(t,e,r){return{ok:!1,code:e,message:r,manager:t}}function jh(t){return/[\u0000-\u001f\u007f]/u.test(t)}var Wh="hunsu-bridge.service";function $Z(t){let e=t.commandRunner??HR,r=t.fileSystem??LR,n=t.unitPath??MPe(t.homeDirectory??OPe(),".config","systemd","user",Wh);return qh({manager:"systemd-user",definitionPath:n,platform:"linux",async install(o){let s=await UR(r,n,LPe(o));return aS(await e({command:"systemctl",args:["--user","daemon-reload"]}),"reload systemd user units"),aS(await e({command:"systemctl",args:["--user","enable",Wh]}),"enable the systemd user unit"),{changed:s}},async uninstall(){let o=await r.exists(n);return await e({command:"systemctl",args:["--user","disable",Wh]}),await r.remove(n),aS(await e({command:"systemctl",args:["--user","daemon-reload"]}),"reload systemd user units"),{changed:o}},async start(){aS(await e({command:"systemctl",args:["--user","start",Wh]}),"start the systemd user unit")},async stopOwned(){aS(await e({command:"systemctl",args:["--user","stop",Wh]}),"stop the systemd user unit")},async status(){if(!await r.exists(n))return{installed:!1,state:"stopped"};let o=await e({command:"systemctl",args:["--user","is-active",Wh]});return{installed:!0,state:o.exitCode===0&&o.stdout.trim()==="active"?"running":/^(inactive|failed|deactivating)$/u.test(o.stdout.trim())||o.exitCode===3?"stopped":"unknown",detail:o.stdout.trim()||o.stderr.trim()||void 0}}},t)}function LPe(t){return["[Unit]","Description=Hunsu Bridge","After=network-online.target","","[Service]","Type=simple",`ExecStart=${[t.nodePath,t.cliPath,"daemon","--runtime-path",t.runtimePath,"--profile",t.deploymentProfile].map(XO).join(" ")}`,`Environment=${XO(`HUNSU_HOME=${t.hunsuHome}`)}`,"Restart=on-failure","RestartSec=2","","[Install]","WantedBy=default.target",""].join(`
272
+ `)}function aS(t,e){if(t.exitCode!==0)throw new Error(`Unable to ${e}.`)}import{homedir as HPe}from"node:os";import{join as FR}from"node:path";var QO="app.hunsu.bridge";function FZ(t){let e=t.commandRunner??HR,r=t.fileSystem??LR,n=t.homeDirectory??HPe(),i=t.plistPath??FR(n,"Library","LaunchAgents",`${QO}.plist`),s=`gui/${t.uid??(typeof process.getuid=="function"?process.getuid():0)}`,a=`${s}/${QO}`;return qh({manager:"launchd-user",definitionPath:i,platform:"darwin",async install(u){await r.mkdir(FR(u.hunsuHome,"logs"),{mode:448});let d=UPe(u);return await r.readText(i)!==d&&(await e({command:"launchctl",args:["print",a]})).exitCode===0&&YO(await e({command:"launchctl",args:["bootout",a]}),"reload the changed LaunchAgent definition"),{changed:await UR(r,i,d)}},async uninstall(){let u=await r.exists(i);return await e({command:"launchctl",args:["bootout",a]}),await r.remove(i),{changed:u}},async start(){let d=(await e({command:"launchctl",args:["print",a]})).exitCode===0?await e({command:"launchctl",args:["kickstart",a]}):await e({command:"launchctl",args:["bootstrap",s,i]});YO(d,"start the LaunchAgent")},async stopOwned(){YO(await e({command:"launchctl",args:["bootout",a]}),"stop the LaunchAgent")},async status(){if(!await r.exists(i))return{installed:!1,state:"stopped"};let u=await e({command:"launchctl",args:["print",a]}),l=u.stdout.match(/^\s*state\s*=\s*([^\r\n]+)\s*$/imu)?.[1]?.trim().toLowerCase();return{installed:!0,state:u.exitCode!==0?"stopped":l==="running"?"running":l?"stopped":"unknown",detail:u.exitCode===0?l??"loaded; state unavailable":"not loaded"}}},t)}function UPe(t){let e=FR(t.hunsuHome,"logs","bridge.stdout.log"),r=FR(t.hunsuHome,"logs","bridge.stderr.log");return['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>"," <key>Label</key>",` <string>${QO}</string>`," <key>ProgramArguments</key>"," <array>",` <string>${Md(t.nodePath)}</string>`,` <string>${Md(t.cliPath)}</string>`," <string>daemon</string>"," <string>--runtime-path</string>",` <string>${Md(t.runtimePath)}</string>`," <string>--profile</string>",` <string>${Md(t.deploymentProfile)}</string>`," </array>"," <key>EnvironmentVariables</key>"," <dict>"," <key>HUNSU_HOME</key>",` <string>${Md(t.hunsuHome)}</string>`," </dict>"," <key>RunAtLoad</key>"," <true/>"," <key>KeepAlive</key>"," <dict>"," <key>SuccessfulExit</key>"," <false/>"," </dict>"," <key>StandardOutPath</key>",` <string>${Md(e)}</string>`," <key>StandardErrorPath</key>",` <string>${Md(r)}</string>`,"</dict>","</plist>",""].join(`
273
+ `)}function YO(t,e){if(t.exitCode!==0)throw new Error(`Unable to ${e}.`)}var jZ="Hunsu Bridge";function qZ(t){let e=t.commandRunner??JO(t.processEnv??{}),r=t.taskName??jZ,n=t.powershellPath??"powershell.exe",i=!1,o=u=>e({command:n,args:["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",u]}),s=async()=>o(["$ErrorActionPreference = 'Stop'",`Get-ScheduledTask -TaskName ${Ca(r)} | Select-Object -ExpandProperty State`].join("; ")),a=async()=>o(["$ErrorActionPreference = 'Stop'",`$Task = Get-ScheduledTask -TaskName ${Ca(r)}`,"@{ Execute = $Task.Actions[0].Execute; Arguments = $Task.Actions[0].Arguments; WorkingDirectory = $Task.Actions[0].WorkingDirectory } | ConvertTo-Json -Compress"].join("; ")),c={manager:"windows-task-scheduler",definitionPath:`Task Scheduler: ${r}`,platform:"win32",async install(u){let d=await a(),l=!FPe(d,u),f=await o($Pe(u,r));return jR(f,"register the current-user scheduled task"),i=!0,{changed:l}},async uninstall(){let u=await s(),d=await o(["$ErrorActionPreference = 'Stop'",`Unregister-ScheduledTask -TaskName ${Ca(r)} -Confirm:$false`].join("; "));return u.exitCode===0&&jR(d,"unregister the current-user scheduled task"),i=!1,{changed:u.exitCode===0}},async start(){jR(await o(`Start-ScheduledTask -TaskName ${Ca(r)}`),"start the current-user scheduled task")},async stopOwned(){jR(await o(`Stop-ScheduledTask -TaskName ${Ca(r)}`),"stop the current-user scheduled task")},async status(){let u=await s();if(u.exitCode!==0)return{installed:i,state:"stopped",detail:"task not registered"};i=!0;let d=u.stdout.trim().toLowerCase();return{installed:!0,state:d==="running"?"running":d?"stopped":"unknown",detail:d||void 0}}};return qh(c,t)}function $Pe(t,e=jZ){let r=WZ(t);return["$ErrorActionPreference = 'Stop'","$CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name",`$Action = New-ScheduledTaskAction -Execute ${Ca(t.nodePath)} -Argument ${Ca(r)} -WorkingDirectory ${Ca(t.runtimePath)}`,"$Trigger = New-ScheduledTaskTrigger -AtLogOn -User $CurrentUser","$Principal = New-ScheduledTaskPrincipal -UserId $CurrentUser -LogonType Interactive -RunLevel Limited","$Settings = New-ScheduledTaskSettingsSet -Hidden -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1)",`Register-ScheduledTask -TaskName ${Ca(e)} -Action $Action -Trigger $Trigger -Principal $Principal -Settings $Settings -Description 'Hunsu Bridge current-user daemon' -Force | Out-Null`].join("; ")}function WZ(t){return[$R(t.cliPath),"daemon","--runtime-path",$R(t.runtimePath),"--home",$R(t.hunsuHome),"--profile",t.deploymentProfile].join(" ")}function FPe(t,e){if(t.exitCode!==0)return!1;try{let r=JSON.parse(t.stdout.trim().replace(/^\uFEFF/u,""));return typeof r.Execute=="string"&&r.Execute.toLowerCase()===e.nodePath.toLowerCase()&&r.Arguments===WZ(e)&&typeof r.WorkingDirectory=="string"&&r.WorkingDirectory.toLowerCase()===e.runtimePath.toLowerCase()}catch{return!1}}function jR(t,e){if(t.exitCode!==0)throw new Error(`Unable to ${e}.`)}function VZ(t){let e=t.platform??process.platform;if(e==="linux"&&t.linux)return $Z(t.linux);if(e==="darwin"&&t.macos)return FZ(t.macos);if(e==="win32"&&t.windows)return qZ(t.windows);throw new Error(`Hunsu Bridge does not have a configured user service manager for ${e}.`)}function GZ(t){let e=t.platform??process.platform,r={requestAuthenticatedShutdown:async()=>(await t.controlClient.request("/v1/control/shutdown",{method:"POST"})).ok,probeHealth:async()=>await t.controlClient.health()!==void 0,probeAuthenticatedStatus:async()=>{let i=await t.controlClient.request("/v1/control/status");return i.ok?{state:"authenticated",value:i.value}:i.code==="BRIDGE_CONTROL_UNAUTHORIZED"?{state:"unauthorized"}:{state:"unavailable"}},readInstalledRuntime:async()=>{let i=await Bu(t.paths).read();return i?{packageVersion:i.current.packageVersion,runtimePath:i.current.runtimePath,deploymentProfile:i.serviceInput.deploymentProfile}:void 0}},n=t.userHome??jPe();return VZ({platform:e,...e==="linux"?{linux:{...r,homeDirectory:n}}:{},...e==="darwin"?{macos:{...r,homeDirectory:n}}:{},...e==="win32"?{windows:{...r,processEnv:t.processEnv}}:{}})}import{isAbsolute as zZ}from"node:path";import{fileURLToPath as qPe,pathToFileURL as KZ}from"node:url";var Pa=class extends Error{code="RUNTIME_INSTALL_FAILED";constructor(e){super(e),this.name="RuntimePackageSourceError"}};function qR(){return{kind:"registry-exact",packageName:"@hunsu/bridge",version:bn}}function JZ(t,e=bn){if(QZ(t)||!zZ(t)||!t.toLowerCase().endsWith(".tgz"))throw new Pa("--runtime-package requires an absolute local .tgz path.");if(!ZO(e))throw new Pa("The local runtime package requires an exact expected version.");return{kind:"local-tarball",fileUrl:KZ(t).href,expectedVersion:e}}function XZ(t){return cS(t),"@hunsu/bridge"}function YZ(t){let e=cS(t);return e.kind==="registry-exact"?e.version:e.expectedVersion}function e3(t){let e=cS(t);return e.kind==="local-tarball"?e.fileUrl:`${e.packageName}@${e.version}`}function cS(t){if(t.kind==="registry-exact"){if(t.packageName!=="@hunsu/bridge"||!ZO(t.version))throw new Pa("Bridge setup requires one exact @hunsu/bridge package version.");return{kind:"registry-exact",packageName:"@hunsu/bridge",version:t.version}}if(t.kind!=="local-tarball"||!ZO(t.expectedVersion))throw new Pa("Bridge setup requires one exact @hunsu/bridge package version.");let e;try{e=new URL(t.fileUrl)}catch{throw new Pa("The local runtime package must be a file URL created from an absolute .tgz path.")}if(e.protocol!=="file:"||e.username||e.password||e.search||e.hash)throw new Pa("The local runtime package must be a credential-free local file URL.");let r;try{r=qPe(e)}catch{throw new Pa("The local runtime package file URL is invalid.")}if(!zZ(r)||!r.toLowerCase().endsWith(".tgz")||QZ(r))throw new Pa("The local runtime package must resolve to an absolute .tgz path.");return{kind:"local-tarball",fileUrl:KZ(r).href,expectedVersion:t.expectedVersion}}function ZO(t){return/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.test(t)}function QZ(t){return/[\u0000-\u001f\u007f]/u.test(t)}import{isAbsolute as f_e,join as l3,relative as p_e,resolve as fS,sep as m_e}from"node:path";import{execFile as WPe}from"node:child_process";import{lstat as ZZ,mkdir as VPe,realpath as GPe}from"node:fs/promises";import{isAbsolute as zPe,resolve as r3,win32 as KPe}from"node:path";import{promisify as JPe}from"node:util";var WR="hunsu.bridge.home-ownership.v1",tr=class extends Error{constructor(e,r){super(e,r),this.name="HomeOwnershipError"}};function VR(t,e={}){let r=e.platform??process.platform,n=e.windowsAclHardener??(i=>YPe(i,e.processEnv??{}));return{async read(){let i;try{i=await ZZ(t.homeOwnershipFile)}catch(s){if(Ot(s)&&s.code==="ENOENT")return;throw new tr("The Hunsu home ownership marker could not be inspected.",{cause:s})}if(!i.isFile()||i.isSymbolicLink())throw new tr("The Hunsu home ownership marker has an unsafe filesystem type.");let o=await Yi(t.homeOwnershipFile);return o===void 0?void 0:eee(t.homeOwnershipFile,o)},async write(i){await wn(t.homeOwnershipFile,eee(t.homeOwnershipFile,i),{mode:384,...r==="win32"?{prepareTemporaryFile:n}:{}})},async canonicalHome(i){try{i&&await VPe(t.home,{recursive:!0,mode:448});let o=await ZZ(t.home);if(!o.isDirectory()||o.isSymbolicLink())throw new tr("The configured Hunsu home has an unsafe filesystem type.");return r3(await GPe(t.home))}catch(o){throw o instanceof tr?o:new tr("The canonical Hunsu home could not be established.",{cause:o})}}}}async function tee(t){let e=await t.store.canonicalHome(!0),r=await t.store.read();if(r){if(!Ld(r.home,e))throw new tr("The Hunsu home ownership marker does not match the canonical home.");if(t.expectedInstallationId&&r.installationId!==t.expectedInstallationId)throw new tr("The Hunsu home ownership marker does not match the installed runtime.");return await t.store.write(r),r}let n=t.expectedInstallationId??(t.createInstallationId??RU)();ree(n);let i={schema:WR,installationId:n,createdAt:(t.now??(()=>new Date))().toISOString(),home:e};return await t.store.write(i),i}function Ld(t,e){let r=r3(t),n=r3(e);return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}var XPe=JPe(WPe);async function YPe(t,e){let r=QPe(t);try{await XPe(r.command,r.args,{env:Ko(e),windowsHide:!0})}catch{throw new tr("The Hunsu home ownership marker ACL could not be restricted to the current Windows user.")}}function QPe(t){if(/[\u0000-\u001f\u007f]/u.test(t))throw new tr("The Hunsu home ownership marker path cannot contain control characters.");return Eb(t,"OwnershipMarkerPath")}function eee(t,e){if(!ZPe(e)||e.schema!==WR)throw xe(t,`expected schema ${WR}`);let r=t3(t,"installationId",e.installationId);ree(r,t);let n=t3(t,"createdAt",e.createdAt);if(!Number.isFinite(Date.parse(n)))throw xe(t,"createdAt must be an ISO timestamp");let i=t3(t,"home",e.home);if(!zPe(i)&&!KPe.isAbsolute(i))throw xe(t,"home must be an absolute path");return{schema:WR,installationId:r,createdAt:n,home:i}}function ree(t,e){if(!/^install_[A-Za-z0-9_-]{8,}$/u.test(t))throw e?xe(e,"installationId must be a Hunsu installation id"):new tr("The Hunsu installation identity is invalid.")}function t3(t,e,r){if(typeof r!="string"||!r.trim()||/[\u0000-\u001f\u007f]/u.test(r))throw xe(t,`${e} must be a non-empty safe string`);return r}function ZPe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}import{lstat as e_e,readdir as t_e,realpath as r_e,rmdir as n_e,unlink as i_e}from"node:fs/promises";import{homedir as o_e}from"node:os";import{basename as s_e,isAbsolute as a_e,join as Hd,parse as c_e,relative as oee,resolve as Si,sep as see}from"node:path";var o3=Object.freeze(["config.json","workspaces.json","credentials.json","runtime.json","runtime","logs",".hunsu-bridge-home.json"]),aee=Object.freeze(["runtime.json","runtime"]),s3={"config.json":"file","workspaces.json":"file","credentials.json":"file","runtime.json":"file",runtime:"directory",logs:"directory",".hunsu-bridge-home.json":"file"},Vr=class extends Error{constructor(e,r){super(e,r),this.name="OwnedDataSafetyError"}},Vf={async lstat(t){try{return await e_e(t)}catch(e){if(Ot(e)&&e.code==="ENOENT")return;throw e}},realpath:r_e,readdir:t_e,unlink:i_e,rmdir:n_e};async function GR(t){let e=t.fileSystem??Vf,r=Si(t.canonicalHome);await l_e({canonicalHome:r,fileSystem:e,userHome:t.userHome,currentDirectory:t.currentDirectory});let n=await $d(e,r),i=[];for(let c of t.entries)dS(c),await dee(e,r,Hd(r,c),s3[c])&&i.push(c);let o=c3(n),s=new Set(t.entries),a=n.every(c=>s.has(c));return{canonicalHome:r,entries:[...t.entries],existingEntries:i,preservedUnknownEntries:o,homeDirectoryRemoved:a}}async function cee(t,e=Vf,r={}){let n=new Set((r.preservePaths??[]).map(a=>(uS(t.canonicalHome,a),Si(a)))),i=new Set;for(let a of t.entries)await lee(e,t.canonicalHome,Hd(t.canonicalHome,a),s3[a],n)&&i.add(a);let o=await $d(e,t.canonicalHome),s=!1;if(o.length===0)try{await e.rmdir(t.canonicalHome),s=!0}catch(a){if(!Ot(a)||a.code!=="ENOENT"&&a.code!=="ENOTEMPTY"&&a.code!=="EEXIST")throw a;s=a.code==="ENOENT"}return{deleted:t.existingEntries.filter(a=>a!==".hunsu-bridge-home.json"&&i.has(a)),preservedUnknownEntries:c3(o),homeDirectoryRemoved:s}}async function uee(t,e=Vf){for(let s of t.entries)s3[s]==="directory"&&await u_e(e,t.canonicalHome,Hd(t.canonicalHome,s));let r=await $d(e,t.canonicalHome),n=!1;r.length===0&&(n=await d_e(e,t.canonicalHome));let i=n?[]:await $d(e,t.canonicalHome),o=[];for(let s of t.existingEntries)s!==".hunsu-bridge-home.json"&&(await eu(e,Hd(t.canonicalHome,s))||o.push(s));return{deleted:o,preservedUnknownEntries:c3(i),homeDirectoryRemoved:n,runtimeDirectoryRemoved:!await eu(e,Hd(t.canonicalHome,"runtime"))}}async function a3(t){let e=t.fileSystem??Vf;uS(t.canonicalHome,t.path);let r=oee(Si(t.canonicalHome),Si(t.path)).split(see),n=Si(t.canonicalHome);for(let o of r.slice(0,-1)){dS(o),n=Hd(n,o);let s=await eu(e,n);if(!s?.isDirectory()||s.isSymbolicLink())throw new Vr("An installation identity directory has an unsafe filesystem type.");await Ud(e,t.canonicalHome,n)}let i=await eu(e,t.path);if(!i||i.isSymbolicLink()||!i.isFile())throw new Vr("An installation identity file has an unsafe filesystem type.");await Ud(e,t.canonicalHome,t.path)}async function dee(t,e,r,n){uS(e,r);let i=await eu(t,r);if(!i)return!1;if(i.isSymbolicLink())return!0;if(i.isFile()){if(n==="directory")throw Wf();return await Ud(t,e,r),!0}if(i.isDirectory()){if(n==="file")throw Wf();await Ud(t,e,r);let o=await $d(t,r);for(let s of o)dS(s),await dee(t,e,Hd(r,s),"any");return!0}throw Wf()}async function lee(t,e,r,n,i){if(uS(e,r),i.has(Si(r)))return!1;let o=await eu(t,r);if(!o)return!0;if(o.isSymbolicLink())return await t.unlink(r),!0;if(o.isFile()){if(n==="directory")throw Wf();return await Ud(t,e,r),await t.unlink(r),!0}if(!o.isDirectory()||n==="file")throw Wf();await Ud(t,e,r);let s=!0;for(let a of await $d(t,r))dS(a),await nee(t,e,r),await lee(t,e,Hd(r,a),"any",i)||(s=!1);if(await nee(t,e,r),!s)return!1;try{return await t.rmdir(r),!0}catch(a){if(Ot(a)&&a.code==="ENOENT")return!0;if(Ot(a)&&(a.code==="ENOTEMPTY"||a.code==="EEXIST"))return!1;throw a}}async function u_e(t,e,r){uS(e,r);let n=await eu(t,r);if(!n)return!0;if(n.isSymbolicLink()||!n.isDirectory())throw Wf();if(await Ud(t,e,r),(await $d(t,r)).length>0)return!1;try{return await t.rmdir(r),!0}catch(i){if(Ot(i)&&i.code==="ENOENT")return!0;if(Ot(i)&&(i.code==="ENOTEMPTY"||i.code==="EEXIST"))return!1;throw i}}async function d_e(t,e){let r=await eu(t,e);if(!r)return!0;if(r.isSymbolicLink()||!r.isDirectory())throw Wf();let n;try{n=Si(await t.realpath(e))}catch(i){throw new Vr("Canonical containment could not be re-established for the Hunsu home.",{cause:i})}if(!i3(e,n))throw new Vr("The canonical Hunsu home changed during removal.");if((await $d(t,e)).length>0)return!1;try{return await t.rmdir(e),!0}catch(i){if(Ot(i)&&i.code==="ENOENT")return!0;if(Ot(i)&&(i.code==="ENOTEMPTY"||i.code==="EEXIST"))return!1;throw i}}async function nee(t,e,r){let n=await eu(t,r);if(!n?.isDirectory()||n.isSymbolicLink())throw new Vr("A Hunsu-owned directory changed type during removal.");await Ud(t,e,r)}async function Ud(t,e,r){let n;try{n=Si(await t.realpath(r))}catch(i){throw new Vr("Canonical containment could not be established for Hunsu-owned data.",{cause:i})}if(!u3(e,n,!1))throw new Vr("A Hunsu-owned entry resolves outside the canonical Hunsu home.")}async function l_e(t){let e=c_e(t.canonicalHome).root;if(i3(t.canonicalHome,e))throw n3();let r=await iee(t.fileSystem,t.userHome??o_e());if(i3(t.canonicalHome,r))throw n3();let n=await iee(t.fileSystem,t.currentDirectory??process.cwd());if(u3(t.canonicalHome,n,!0))throw n3()}async function iee(t,e){try{return Si(await t.realpath(e))}catch{return Si(e)}}async function eu(t,e){try{return await t.lstat(e)}catch(r){throw new Vr("A Hunsu-owned entry could not be inspected safely.",{cause:r})}}async function $d(t,e){try{let r=await t.readdir(e);for(let n of r)dS(n);return r.sort((n,i)=>n.localeCompare(i))}catch(r){if(Ot(r)&&r.code==="ENOENT")return[];throw r instanceof Vr?r:new Vr("A Hunsu-owned directory could not be inspected safely.",{cause:r})}}function c3(t){let e=new Set(o3);return t.filter(r=>!e.has(r))}function uS(t,e){if(!u3(t,Si(e),!1))throw new Vr("A Hunsu-owned path is outside the canonical Hunsu home.")}function u3(t,e,r){let n=oee(Si(t),Si(e));return n===""?r:n!==".."&&!n.startsWith(`..${see}`)&&!a_e(n)}function i3(t,e){let r=Si(t),n=Si(e);return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function dS(t){if(!t||t==="."||t===".."||s_e(t)!==t)throw new Vr("A directory entry is not safe to report or remove.")}function n3(){return new Vr("Hunsu Bridge refuses to remove data from a protected directory.")}function Wf(){return new Vr("A Hunsu-owned entry has an unexpected filesystem type.")}async function pee(t,e){if(t.deleteData&&t.confirmed!==!0)return{ok:!1,code:"CONFIRMATION_REQUIRED",message:"Deleting Hunsu Bridge data requires explicit confirmation."};if(t.dryRun)return(await d3(t,e)).result;if(t.deleteData){let o=(await d3({...t,dryRun:!0},e)).result;if(!o.ok)return o}let r;try{r=await(e.acquireOperationLock?e.acquireOperationLock(e.paths):Cp(e.paths,"remove"))}catch(o){return o instanceof zs?{ok:!1,code:o.code,message:o.message}:Gf()}let n;try{n=await d3(t,e,!0)}catch{n={result:Gf()}}try{await r.release()}catch{return Gf()}if(!n.result.ok)return n.result;let i=e.fileSystem??Vf;if(n.cleanupPlan)try{let o=await uee(n.cleanupPlan,i);return KR({removedRuntime:o.runtimeDirectoryRemoved,deletedData:t.deleteData===!0,deleted:o.deleted,preservedUnknownEntries:o.preservedUnknownEntries,homeDirectoryRemoved:o.homeDirectoryRemoved,dryRun:!1})}catch(o){return o instanceof Vr&&t.deleteData?zR(o.message):Gf()}try{let o=await i.lstat(e.paths.home);return KR({...n.result.value,homeDirectoryRemoved:o===void 0})}catch{return Gf()}}async function d3(t,e,r=!1){if(t.deleteData&&t.confirmed!==!0)return{result:{ok:!1,code:"CONFIRMATION_REQUIRED",message:"Deleting Hunsu Bridge data requires explicit confirmation."}};let n=e.installStore??Bu(e.paths),i=e.ownershipStore??VR(e.paths),o=e.fileSystem??Vf,s,a=[],c=!0;try{let d=await o.lstat(e.paths.home);if(d){if(d.isSymbolicLink())throw new Vr("Hunsu Bridge refuses to remove data through a symbolic-link or junction home.");if(!d.isDirectory())throw new Vr("The configured Hunsu home has an unexpected filesystem type.");let l=await i.canonicalHome(!1);if(c=!1,t.deleteData)s=await GR({canonicalHome:l,entries:o3,fileSystem:o,userHome:e.userHome,currentDirectory:e.currentDirectory}),await y_e({canonicalHome:l,installStore:n,ownershipStore:i,fileSystem:o}),a=s.preservedUnknownEntries;else{try{a=(await GR({canonicalHome:l,entries:[],fileSystem:o,userHome:e.userHome,currentDirectory:e.currentDirectory})).preservedUnknownEntries}catch{}try{await h_e({canonicalHome:l,installStore:n,fileSystem:o}),s=await GR({canonicalHome:l,entries:aee,fileSystem:o,userHome:e.userHome,currentDirectory:e.currentDirectory}),a=s.preservedUnknownEntries}catch{s=void 0}}}else if(t.deleteData)return{result:zR("Hunsu Bridge refused to delete data because installation ownership is unknown.")}}catch(d){return d instanceof Vr||d instanceof tr||t.deleteData?{result:zR(d instanceof Error?d.message:"Hunsu Bridge could not verify ownership of the data directory.")}:{result:Gf()}}if(t.dryRun)return{result:KR({removedRuntime:s!==void 0,deletedData:t.deleteData===!0,deleted:v_e(s),preservedUnknownEntries:a,homeDirectoryRemoved:s?.homeDirectoryRemoved??c,dryRun:!0})};let u=await e.serviceManager.uninstall();if(!u.ok)return{result:{ok:!1,code:u.code,message:u.message}};try{let d=s?await cee(s,o,r?{preservePaths:[e.paths.setupLockFile]}:{}):{deleted:[],preservedUnknownEntries:a,homeDirectoryRemoved:c};return{result:KR({removedRuntime:s!==void 0&&!r,deletedData:t.deleteData===!0,deleted:d.deleted,preservedUnknownEntries:d.preservedUnknownEntries,homeDirectoryRemoved:d.homeDirectoryRemoved,dryRun:!1}),...s&&r?{cleanupPlan:s}:{}}}catch(d){return d instanceof Vr?{result:zR(d.message)}:{result:Gf()}}}async function h_e(t){await a3({canonicalHome:t.canonicalHome,path:l3(t.canonicalHome,"runtime","install.json"),fileSystem:t.fileSystem});let e=await t.installStore.read();if(!e)throw new tr("Hunsu Bridge runtime ownership could not be established.");let r;try{r=await t.fileSystem.realpath(e.serviceInput.hunsuHome)}catch(n){throw new tr("The installed Hunsu home cannot be verified.",{cause:n})}if(!Ld(r,t.canonicalHome))throw new tr("The installed Hunsu home does not match the configured home.");await g_e({canonicalHome:t.canonicalHome,installation:e,fileSystem:t.fileSystem})}async function g_e(t){let e=l3(t.installation.serviceInput.hunsuHome,"runtime"),r=await t.fileSystem.lstat(e);if(!r?.isDirectory()||r.isSymbolicLink())throw new tr("The installed runtime root has an unsafe filesystem type.");let n;try{n=fS(await t.fileSystem.realpath(e))}catch(o){throw new tr("The installed runtime root cannot be verified.",{cause:o})}if(!lS(t.canonicalHome,n,!1))throw new tr("The installed runtime root is outside the configured home.");await fee({value:t.installation.current,lexicalRuntimeRoot:e,canonicalRuntimeRoot:n,fileSystem:t.fileSystem}),t.installation.previous&&await fee({value:t.installation.previous,lexicalRuntimeRoot:e,canonicalRuntimeRoot:n,fileSystem:t.fileSystem});let i=t.installation.serviceInput;if(!Ld(i.runtimePath,t.installation.current.runtimePath)||!Ld(i.cliPath,t.installation.current.cliPath)||!Ld(i.nodePath,t.installation.current.nodePath)||i.packageVersion!==t.installation.current.packageVersion)throw new tr("The installed service paths do not match the current runtime.")}async function fee(t){if(!lS(t.lexicalRuntimeRoot,t.value.runtimePath,!1)||!lS(t.value.runtimePath,t.value.cliPath,!1))throw new tr("An installed runtime path is outside the Hunsu runtime root.");let e=await t.fileSystem.lstat(t.value.runtimePath);if(!e?.isDirectory()||e.isSymbolicLink())throw new tr("An installed runtime directory has an unsafe filesystem type.");let r=await t.fileSystem.lstat(t.value.cliPath);if(!r?.isFile()||r.isSymbolicLink())throw new tr("An installed runtime CLI has an unsafe filesystem type.");let n,i;try{n=fS(await t.fileSystem.realpath(t.value.runtimePath)),i=fS(await t.fileSystem.realpath(t.value.cliPath))}catch(o){throw new tr("An installed runtime path cannot be verified.",{cause:o})}if(!lS(t.canonicalRuntimeRoot,n,!1)||!lS(n,i,!1))throw new tr("An installed runtime path resolves outside the Hunsu runtime root.")}function lS(t,e,r){let n=p_e(fS(t),fS(e));return n===""?r:n!==".."&&!n.startsWith(`..${m_e}`)&&!f_e(n)}async function y_e(t){await a3({canonicalHome:t.canonicalHome,path:l3(t.canonicalHome,"runtime","install.json"),fileSystem:t.fileSystem});let e=await t.installStore.read();if(!e?.installationId)throw new tr("Hunsu Bridge refused to delete data because installation ownership is unknown.");let r=await t.ownershipStore.read();if(!r)throw new tr("Hunsu Bridge refused to delete data because the ownership marker is missing.");if(r.installationId!==e.installationId)throw new tr("Hunsu Bridge refused to delete data because the installation identity does not match.");if(!Ld(r.home,t.canonicalHome))throw new tr("Hunsu Bridge refused to delete data because the canonical home does not match.");let n;try{n=await t.fileSystem.realpath(e.serviceInput.hunsuHome)}catch(i){throw new tr("Hunsu Bridge refused to delete data because the installed home cannot be verified.",{cause:i})}if(!Ld(n,t.canonicalHome))throw new tr("Hunsu Bridge refused to delete data because the installed home does not match.")}function v_e(t){return t?.existingEntries.filter(e=>e!==".hunsu-bridge-home.json")??[]}function zR(t){return{ok:!1,code:"BRIDGE_DATA_DELETE_REFUSED",message:t}}function Gf(){return{ok:!1,code:"RUNTIME_INSTALL_FAILED",message:"Hunsu Bridge runtime files could not be removed safely."}}function KR(t){let e=t.preservedUnknownEntries.length>0?` ${t.preservedUnknownEntries.length} unknown home entries were preserved.`:"";return{ok:!0,code:"OK",message:t.dryRun?`Hunsu Bridge removal dry run completed.${e}`:t.deletedData?`Hunsu Bridge and its owned user data were removed.${e}`:t.removedRuntime?`Hunsu Bridge runtime removed; config, Workspaces, and credentials were preserved.${e}`:`Hunsu Bridge service removed; runtime and user data were preserved because runtime ownership was not verified.${e}`,value:t}}import{randomUUID as B_e}from"node:crypto";import{execFile as x_e}from"node:child_process";import{createHash as S_e}from"node:crypto";import{lstat as b_e,mkdir as w_e,readFile as I_e,readdir as E_e,realpath as k_e,rename as R_e,rmdir as A_e,unlink as C_e}from"node:fs/promises";import{isAbsolute as h3,posix as yee,relative as vee,resolve as Ps,win32 as p3}from"node:path";var Gr=class extends Error{code="RUNTIME_INSTALL_FAILED";constructor(e,r){super(e,r),this.name="StagedRuntimeInstallError"}},bi=class extends Error{code="ROLLBACK_FAILED";constructor(e="The failed staged runtime could not be restored or removed safely.",r){super(e,r),this.name="StagedRuntimeCleanupError"}},g3={async lstat(t){try{return await b_e(t)}catch(e){if(D_e(e)&&e.code==="ENOENT")return;throw e}},realpath:k_e,readdir:E_e,async mkdir(t){await w_e(t,{recursive:!0,mode:448})},unlink:C_e,rmdir:A_e,rename:R_e,readFile:I_e},xee=(t={})=>e=>new Promise(r=>{x_e(e.command,e.args,{encoding:"utf8",...kb(e.command)?{env:Ko(t)}:{},windowsHide:!0,maxBuffer:1024*1024},(n,i,o)=>{r({exitCode:n&&"code"in n&&typeof n.code=="number"?n.code:n?1:0,stdout:i??"",stderr:o??(n instanceof Error?n.message:"")})})}),pZe=xee();function y3(t){let e=t.platform??process.platform,r=e==="win32"?p3:yee;if(!(e==="win32"?p3.isAbsolute:h3)(t.nodePath)||S3(t.nodePath))throw new Gr("The Node executable path must be absolute.");if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(t.transactionId))throw new Gr("The setup transaction id is invalid.");let i=cS(t.source??qR()),o=YZ(i),s=t.paths.runtimeStagingDirectory,a=r.join(s,t.transactionId),c=r.join(t.paths.runtimeVersionsDirectory,o),u=r.join(t.paths.runtimeVersionsDirectory,`.${o}.previous`),d=["node_modules","@hunsu","bridge"],l=r.join(a,...d),f=r.join(c,...d),p=["install","--ignore-scripts","--omit=dev","--no-audit","--no-fund","--prefix",a,e3(i)];return{source:i,packageName:XZ(i),packageVersion:o,packageSpec:e3(i),transactionId:t.transactionId,home:t.paths.home,runtimeDirectory:t.paths.runtimeDirectory,stagingRoot:s,stagingPath:a,stagingCliPath:r.join(l,"dist","cli.js"),stagingManifestPath:r.join(l,"package.json"),runtimeVersionsDirectory:t.paths.runtimeVersionsDirectory,runtimePath:c,quarantinePath:u,cliPath:r.join(f,"dist","cli.js"),manifestPath:r.join(f,"package.json"),nodePath:t.nodePath,npmCommand:e==="win32"?P_e(t.npmCommand??"npm.cmd",p):{command:t.npmCommand??"npm",args:p}}}async function See(t){let e=t.fileSystem??g3,r=t.commandRunner??xee(t.processEnv??{}),n=t.now??(()=>new Date),i=await x3(t.plan,e);await wee(t.plan,e,i,t.nodeVersion??process.version),await Fd(t.plan.stagingRoot,t.plan.stagingPath,e,i),await e.mkdir(t.plan.stagingPath);let o=!1;try{if(await zf(t.plan.stagingPath,i,e),await t.onPhase?.("npm-install"),(await r(t.plan.npmCommand)).exitCode!==0)throw new Gr("npm could not install the exact Hunsu Bridge runtime package.");await t.onPhase?.("candidate-verification");let a=await JR({root:t.plan.stagingPath,manifestPath:t.plan.stagingManifestPath,cliPath:t.plan.stagingCliPath,expectedName:t.plan.packageName,expectedVersion:t.plan.packageVersion,fileSystem:e,canonicalHome:i,nodeVersion:t.nodeVersion??process.version});if(await e.lstat(t.plan.runtimePath)){let c;try{c=await JR({root:t.plan.runtimePath,manifestPath:t.plan.manifestPath,cliPath:t.plan.cliPath,expectedName:t.plan.packageName,expectedVersion:t.plan.packageVersion,fileSystem:e,canonicalHome:i,nodeVersion:t.nodeVersion??process.version})}catch(u){if(m3(t.protectedRuntimePath,t.plan.runtimePath))throw new Gr("The currently recorded runtime is incomplete or invalid; preserve it and run offline repair before retrying setup.",{cause:u})}if(c?.cliSha256===a.cliSha256)return await Fd(t.plan.stagingRoot,t.plan.stagingPath,e,i),{installation:hee(t.plan,c.cliSha256,n),reused:!0};await zf(t.plan.runtimePath,i,e),await e.rename(t.plan.runtimePath,t.plan.quarantinePath),o=!0}try{await t.onPhase?.("staging-rename"),await e.rename(t.plan.stagingPath,t.plan.runtimePath)}catch(c){if(o)try{await e.rename(t.plan.quarantinePath,t.plan.runtimePath),o=!1}catch(u){throw new bi("The staged runtime activation failed and the previous version directory could not be restored.",{cause:u})}throw c}if(o)try{await Fd(t.plan.runtimeVersionsDirectory,t.plan.quarantinePath,e,i)}catch(c){try{await Fd(t.plan.runtimeVersionsDirectory,t.plan.runtimePath,e,i),await e.rename(t.plan.quarantinePath,t.plan.runtimePath)}catch(u){throw new bi("The replacement runtime could not be committed or rolled back safely.",{cause:u})}throw new bi("The replacement runtime could not remove its quarantine directory.",{cause:c})}return{installation:hee(t.plan,a.cliSha256,n),reused:!1}}catch(s){try{await Fd(t.plan.stagingRoot,t.plan.stagingPath,e,i)}catch(a){throw new bi("The failed staged runtime could not be removed; remove the runtime staging directory before retrying setup.",{cause:a})}throw s instanceof Gr||s instanceof bi?s:new Gr("The staged Hunsu Bridge runtime could not be verified and activated.",{cause:s})}}async function v3(t){if(t.previous&&m3(t.previous.runtimePath,t.installation.runtimePath))return{removed:!1};let e=t.fileSystem??g3,r=y3({paths:t.paths,transactionId:"candidate-cleanup",nodePath:t.installation.nodePath,source:{kind:"registry-exact",packageName:"@hunsu/bridge",version:t.installation.packageVersion}}),n=await x3(r,e);if(!m3(r.runtimePath,t.installation.runtimePath))throw new bi("The candidate runtime path is not the exact owned version directory.");return await Fd(r.runtimeVersionsDirectory,r.runtimePath,e,n),{removed:!0}}async function bee(t){let e=t.fileSystem??g3,r=await x3(t.plan,e);return await wee(t.plan,e,r,t.nodeVersion??process.version),JR({root:t.plan.runtimePath,manifestPath:t.plan.manifestPath,cliPath:t.plan.cliPath,expectedName:t.plan.packageName,expectedVersion:t.plan.packageVersion,fileSystem:e,canonicalHome:r,nodeVersion:t.nodeVersion??process.version})}function P_e(t,e){if(!t.trim()||S3(t))throw new Gr("The npm command is invalid.");let r=e.map(gee).join(", "),n=["$ErrorActionPreference = 'Stop'",`$npm = ${gee(t)}`,`$arguments = @(${r})`,"& $npm @arguments","if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }"].join(`
274
+ `);return{command:"powershell.exe",args:["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(n,"utf16le").toString("base64")]}}async function x3(t,e){let r=await e.lstat(t.home);if(!r?.isDirectory()||r.isSymbolicLink())throw new Gr("The configured Hunsu home has an unsafe filesystem type.");let n=Ps(await e.realpath(t.home));for(let i of[t.runtimeDirectory,t.stagingRoot,t.runtimeVersionsDirectory])await e.lstat(i)||await e.mkdir(i),await zf(i,n,e);return pS(t.stagingRoot,t.stagingPath),pS(t.runtimeVersionsDirectory,t.runtimePath),pS(t.runtimeVersionsDirectory,t.quarantinePath),n}async function wee(t,e,r,n){if(!await e.lstat(t.quarantinePath))return;if(await zf(t.quarantinePath,r,e),!await e.lstat(t.runtimePath)){await e.rename(t.quarantinePath,t.runtimePath);return}let i=!1;try{await JR({root:t.runtimePath,manifestPath:t.manifestPath,cliPath:t.cliPath,expectedName:t.packageName,expectedVersion:t.packageVersion,fileSystem:e,canonicalHome:r,nodeVersion:n}),i=!0}catch{i=!1}if(i){await Fd(t.runtimeVersionsDirectory,t.quarantinePath,e,r);return}await Fd(t.runtimeVersionsDirectory,t.runtimePath,e,r),await e.rename(t.quarantinePath,t.runtimePath)}async function JR(t){await zf(t.root,t.canonicalHome,t.fileSystem),await mee(t.manifestPath,t.root,t.canonicalHome,t.fileSystem),await mee(t.cliPath,t.root,t.canonicalHome,t.fileSystem);let e=await t.fileSystem.readFile(t.manifestPath),r;try{r=JSON.parse(e.toString("utf8"))}catch(o){throw new Gr("The installed runtime package manifest is invalid.",{cause:o})}if(!f3(r)||r.name!==t.expectedName||r.version!==t.expectedVersion)throw new Gr("The installed runtime package name or exact version does not match the candidate.");let n=f3(r.engines)&&typeof r.engines.node=="string"?r.engines.node:void 0;if(!n||!__e(t.nodeVersion,n))throw new Gr("The installed runtime package has an unsupported Node engine contract.");for(let o of["dependencies","optionalDependencies","peerDependencies"]){let s=r[o];if(s!==void 0){if(!f3(s))throw new Gr("The installed runtime dependency contract is invalid.");for(let a of Object.values(s))if(typeof a!="string"||/^(?:workspace:|link:|file:)/u.test(a))throw new Gr("The installed runtime contains an unresolved workspace dependency.")}}let i=await t.fileSystem.readFile(t.cliPath);if(i.byteLength===0)throw new Gr("The installed runtime CLI is empty.");return{cliSha256:S_e("sha256").update(i).digest("hex")}}async function mee(t,e,r,n){pS(e,t);let i=await n.lstat(t);if(!i?.isFile()||i.isSymbolicLink())throw new Gr("The installed runtime contains an unsafe manifest or CLI filesystem type.");let o=Ps(await n.realpath(t));if(!XR(r,o,!1)||!XR(Ps(await n.realpath(e)),o,!1))throw new Gr("The installed runtime manifest or CLI resolves outside its owned directory.")}async function zf(t,e,r){let n=await r.lstat(t);if(!n?.isDirectory()||n.isSymbolicLink())throw new Gr("A runtime directory has an unsafe filesystem type.");let i=Ps(await r.realpath(t));if(!XR(e,i,!1))throw new Gr("A runtime directory resolves outside the canonical Hunsu home.")}async function Fd(t,e,r,n){pS(t,e);let i=await r.lstat(e);if(i){if(!i.isDirectory()||i.isSymbolicLink())throw new bi("A runtime cleanup target has an unsafe filesystem type.");await Iee(e,r,n)}}async function Iee(t,e,r){let n=await e.lstat(t);if(n){if(n.isSymbolicLink()){await e.unlink(t);return}if(n.isFile()){let i=Ps(await e.realpath(t));if(!XR(r,i,!1))throw new bi("A runtime file resolves outside the canonical Hunsu home.");await e.unlink(t);return}if(!n.isDirectory())throw new bi("A runtime cleanup entry has an unsupported filesystem type.");await zf(t,r,e);for(let i of await e.readdir(t)){if(!i||i==="."||i===".."||i.includes("/")||i.includes("\\"))throw new bi("A runtime directory contains an invalid entry name.");await Iee(T_e(t,i),e,r)}await zf(t,r,e),await e.rmdir(t)}}function hee(t,e,r){return{packageVersion:t.packageVersion,runtimePath:t.runtimePath,nodePath:t.nodePath,cliPath:t.cliPath,cliSha256:e,installedAt:r().toISOString()}}function __e(t,e){let r=t.trim().match(/^v?(\d+)\.(\d+)\.(\d+)/u),n=e.trim().match(/^>=(\d+)\.(\d+)(?:\.(\d+))?$/u);if(!r||!n)return!1;let i=r.slice(1,4).map(Number),o=[Number(n[1]),Number(n[2]),Number(n[3]??0)];for(let s=0;s<i.length;s+=1){if(i[s]>o[s])return!0;if(i[s]<o[s])return!1}return!0}function gee(t){if(S3(t))throw new Gr("The npm command contains an unsafe value.");return`'${t.replaceAll("'","''")}'`}function pS(t,e){let r=vee(Ps(t),Ps(e));if(!r||r.startsWith("..")||h3(r))throw new Gr("The runtime path is outside its Hunsu-owned directory.")}function XR(t,e,r){let n=vee(Ps(t),Ps(e));return n===""?r:!n.startsWith("..")&&!h3(n)}function m3(t,e){if(!t)return!1;let r=Ps(t),n=Ps(e);return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function T_e(t,e){return t.includes("\\")?p3.join(t,e):yee.join(t,e)}function S3(t){return/[\u0000-\u001f\u007f]/u.test(t)}function D_e(t){return t instanceof Error&&"code"in t}function f3(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var b3=Object.freeze({major:24,minor:18,patch:0});async function Aee(t){let e=t.deploymentProfile??"production";if(!Pn(e))return Fn("RUNTIME_INSTALL_FAILED","Bridge deployment profile must be production or preview.");let r=t.nodeVersion??process.version;if(!O_e(r))return Fn("NODE_VERSION_UNSUPPORTED","Hunsu Bridge requires Node 24.18 or newer.");let n=t.createTransactionId?.()??`setup_${B_e()}`,i;try{i=y3({paths:t.paths,transactionId:n,nodePath:t.nodePath??process.execPath,source:t.runtimeSource??qR(),...t.npmCommand?{npmCommand:t.npmCommand}:{},...t.platform?{platform:t.platform}:{}})}catch{return Fn("RUNTIME_INSTALL_FAILED","The exact Hunsu Bridge runtime source or executable path is invalid.")}if(t.dryRun)return _ee(i,e,{idempotent:!1,upgraded:!1,started:!1,dryRun:!0});let o;try{o=await(t.acquireOperationLock?t.acquireOperationLock(t.paths):Cp(t.paths,"setup",t.now?{now:t.now}:{}))}catch(a){return a instanceof zs?Fn(a.code,a.message):Fn("RUNTIME_INSTALL_FAILED","The Bridge setup lock could not be acquired safely.")}let s;try{s=await N_e(t,i,r,e)}catch{s=Fn("RUNTIME_INSTALL_FAILED","Hunsu Bridge setup failed unexpectedly before activation.")}try{await o.release()}catch{return Fn("ROLLBACK_FAILED","Bridge setup finished but its operation lock could not be released; run `hunsu-bridge doctor --json` before retrying.")}return s}async function N_e(t,e,r,n){let i=t.installStore??Bu(t.paths),o=t.transactionStore??Ew(t.paths),s=t.ownershipStore??VR(t.paths,{...t.platform?{platform:t.platform}:{},...t.processEnv?{processEnv:t.processEnv}:{}}),a=t.now??(()=>new Date),c;try{c=await o.read()}catch{return Fn("RUNTIME_INSTALL_FAILED","The pending Bridge setup transaction is invalid.")}if(c){let v=await Eee({options:t,transaction:c,transactionStore:o,installStore:i,installationId:c.previous?.installationId??null});if(!v.ok)return Ree(v.failures)}try{await xn(t,"profile-persistence"),await(t.configStore??Qo(t.paths)).ensureDeploymentProfile(n)}catch{return Fn("RUNTIME_INSTALL_FAILED",`HUNSU_HOME is already bound to a different Bridge deployment profile; use a clean home for ${n}.`)}let u;try{u=await i.read()}catch{return Fn("RUNTIME_INSTALL_FAILED","The installed Hunsu Bridge runtime record is invalid.")}if(u&&u.serviceInput.deploymentProfile!==n)return Fn("RUNTIME_INSTALL_FAILED",`The installed Bridge runtime is ${u.serviceInput.deploymentProfile} and cannot switch to ${n} in the same HUNSU_HOME.`);let d;try{await xn(t,"ownership-marker"),d=(await tee({store:s,...u?.installationId?{expectedInstallationId:u.installationId}:{},...t.now?{now:t.now}:{},...t.createInstallationId?{createInstallationId:t.createInstallationId}:{}})).installationId}catch{return Fn("RUNTIME_INSTALL_FAILED","The Hunsu home ownership marker could not be created or verified.")}try{await xn(t,"credential-ensure"),await t.credentialStore.ensure()}catch{return Fn("RUNTIME_INSTALL_FAILED","Hunsu Bridge credentials could not be created or preserved.")}let l,f,p=!1,g=!1;try{if(u&&u.current.packageVersion===e.packageVersion&&_s(u.current.runtimePath,e.runtimePath)&&_s(u.current.cliPath,e.cliPath))try{let z=await bee({plan:e,...t.stagedFileSystem?{fileSystem:t.stagedFileSystem}:{},nodeVersion:r});u.current.cliSha256!==null&&u.current.cliSha256===z.cliSha256&&(l={...u.current,nodePath:e.nodePath,runtimePath:e.runtimePath,cliPath:e.cliPath,cliSha256:z.cliSha256},p=!0)}catch{}if(!l){let z=await See({plan:e,...t.npmRunner?{commandRunner:t.npmRunner}:{},...t.processEnv?{processEnv:t.processEnv}:{},...t.stagedFileSystem?{fileSystem:t.stagedFileSystem}:{},...t.now?{now:t.now}:{},nodeVersion:r,...u?{protectedRuntimePath:u.current.runtimePath}:{},onPhase:Ce=>xn(t,Ce)});l=z.installation,p=z.reused,g=!!(u&&_s(u.current.runtimePath,l.runtimePath)&&!z.reused)}let v=a().toISOString();f={schema:y0,transactionId:e.transactionId,phase:"candidate-staged",candidate:l,previous:u??null,createdAt:v,updatedAt:v},await xn(t,"transaction-write"),await o.write(f);let b=AU(l,t.paths.home,n);if(u&&!F_e(u.serviceInput,b)){await xn(t,"previous-service-stop");let z=await t.serviceManager.stop();if(!z.ok&&z.code!=="SERVICE_NOT_INSTALLED")throw YR(z);f=await mS(o,f,"previous-stopped",a)}await xn(t,"service-definition-install");let C=await t.serviceManager.install(b);if(!C.ok)throw YR(C);f=await mS(o,f,"service-switched",a);let D=!1,_=await t.serviceManager.status().catch(()=>{});if(!_)throw ru("SERVICE_STATUS_UNAVAILABLE","The candidate service status could not be read.");if((C.changed||g)&&(_.managerState==="running"||_.health==="healthy")){await xn(t,"service-start");let z=await t.serviceManager.restart();if(!z.ok)throw YR(z);D=!0}else if(_.managerState!=="running"&&_.health!=="healthy"){await xn(t,"service-start");let z=await t.serviceManager.start();if(!z.ok)throw YR(z);D=!0}f=await mS(o,f,"candidate-started",a);let F=await Cee(t.verifyRuntime,l);if(await xn(t,"health-verification"),!F.health)throw ru("SETUP_VERIFICATION_FAILED","The candidate runtime health check failed.");if(await xn(t,"authentication-verification"),!F.authenticated)throw ru("SETUP_VERIFICATION_FAILED","The candidate runtime control authentication check failed.");if(await xn(t,"version-verification"),F.version!==l.packageVersion||!_s(F.runtimePath,l.runtimePath))throw ru("SETUP_VERIFICATION_FAILED","The candidate runtime version or stable path check failed.");if(await xn(t,"profile-verification"),F.deploymentProfile!==n)throw ru("SETUP_VERIFICATION_FAILED","The candidate runtime deployment profile check failed.");f=await mS(o,f,"candidate-verified",a),f=await mS(o,f,"committing",a);let he=M_e(d,l,u,b,a);return await xn(t,"install-record-commit"),await i.write(he),await o.clear(),_ee(e,n,{idempotent:!!(u&&p&&_s(u.current.runtimePath,l.runtimePath)),upgraded:!!(u&&u.current.packageVersion!==l.packageVersion),started:D,dryRun:!1})}catch(v){let b=H_e(v);if(!l||!f)return Fn(b.code,b.message);let C=await Eee({options:t,transaction:f,transactionStore:o,installStore:i,installationId:d});return C.ok?f.previous?Fn("SETUP_VERIFICATION_FAILED",`${b.message} The previous verified runtime was restored.`):Fn(b.code,b.message):Ree(C.failures)}}async function Eee(t){let{options:e,transaction:r,transactionStore:n,installStore:i}=t,o=[],s=e.now??(()=>new Date);await n.write({...r,phase:"rolling-back",updatedAt:s().toISOString()}).catch(()=>{});let a=r.previous;return a?(await e.serviceManager.stop().catch(()=>{}),await tu(o,"previous service definition restore",async()=>{await xn(e,"previous-definition-restore");let c=await e.serviceManager.install(a.serviceInput);if(!c.ok)throw new Error(c.code)}),await tu(o,"previous runtime restart",async()=>{await xn(e,"previous-runtime-restart");let c=await e.serviceManager.start();if(!c.ok)throw new Error(c.code)}),await tu(o,"previous runtime verification",async()=>{let c=await Cee(e.verifyRuntime,a.current);if(!L_e(c,a.current,a.serviceInput.deploymentProfile))throw new Error("previous runtime verification failed")}),await tu(o,"previous install record restore",()=>i.write({...a,installationId:a.installationId??t.installationId})),await tu(o,"candidate runtime cleanup",async()=>{await xn(e,"candidate-runtime-cleanup"),await v3({paths:e.paths,installation:r.candidate,previous:a.current,...e.stagedFileSystem?{fileSystem:e.stagedFileSystem}:{}})})):(await tu(o,"candidate service cleanup",async()=>{await xn(e,"candidate-service-cleanup"),await e.serviceManager.stop().catch(()=>{}),await e.serviceManager.uninstall().catch(()=>{});let c=await e.serviceManager.status();if(c.installed||c.managerState==="running"||c.health==="healthy")throw new Error("candidate service remains active")}),await tu(o,"install record cleanup",()=>i.clear()),await tu(o,"candidate runtime cleanup",async()=>{await xn(e,"candidate-runtime-cleanup"),await v3({paths:e.paths,installation:r.candidate,previous:null,...e.stagedFileSystem?{fileSystem:e.stagedFileSystem}:{}})})),o.length===0&&await tu(o,"transaction journal cleanup",()=>n.clear()),o.length===0?{ok:!0}:{ok:!1,failures:o}}function O_e(t){let e=t.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/u);if(!e)return!1;let r=[Number(e[1]),Number(e[2]),Number(e[3])],n=[b3.major,b3.minor,b3.patch];for(let i=0;i<n.length;i+=1){if(r[i]>n[i])return!0;if(r[i]<n[i])return!1}return!0}async function mS(t,e,r,n){let i={...e,phase:r,updatedAt:n().toISOString()};return await t.write(i),i}function M_e(t,e,r,n,i){let o=r&&r.current.packageVersion===e.packageVersion&&_s(r.current.runtimePath,e.runtimePath);return{schema:g0,installationId:t,current:e,previous:o?r.previous:r?.current??null,serviceInput:n,updatedAt:i().toISOString()}}async function Cee(t,e){try{return await t(e)}catch{return{health:!1,authenticated:!1,version:"unavailable",runtimePath:"unavailable",deploymentProfile:"production"}}}function L_e(t,e,r){return t.health&&t.authenticated&&t.version===e.packageVersion&&_s(t.runtimePath,e.runtimePath)&&t.deploymentProfile===r}async function xn(t,e){await t.onPhase?.(e)}async function tu(t,e,r){try{await r()}catch{t.push(e)}}function YR(t){return ru(t.code,t.message)}function ru(t,e){return{code:t,message:e}}function H_e(t){if(U_e(t))return t;if(t instanceof bi)return ru(t.code,t.message);if(t instanceof Error&&"code"in t&&typeof t.code=="string"){let e=t.code;if(Pee(e))return ru(e,$_e(t))}return ru("RUNTIME_INSTALL_FAILED","The Hunsu Bridge runtime transaction failed.")}function U_e(t){return typeof t=="object"&&t!==null&&"code"in t&&Pee(t.code)&&"message"in t&&typeof t.message=="string"}function Pee(t){return t==="NODE_VERSION_UNSUPPORTED"||t==="RUNTIME_INSTALL_FAILED"||t==="SETUP_IN_PROGRESS"||t==="SETUP_VERIFICATION_FAILED"||t==="ROLLBACK_FAILED"||t==="SERVICE_NOT_INSTALLED"||t==="SERVICE_ALREADY_INSTALLED"||t==="SERVICE_INSTALL_FAILED"||t==="SERVICE_START_FAILED"||t==="SERVICE_STOP_FAILED"||t==="SERVICE_STATUS_UNAVAILABLE"}function $_e(t){return t instanceof bi||t.message.includes("runtime")||t.message.includes("Bridge")?t.message:"The Hunsu Bridge runtime transaction failed."}function F_e(t,e){return _s(t.nodePath,e.nodePath)&&_s(t.cliPath,e.cliPath)&&_s(t.hunsuHome,e.hunsuHome)&&t.packageVersion===e.packageVersion&&_s(t.runtimePath,e.runtimePath)&&t.deploymentProfile===e.deploymentProfile}function _s(t,e){let r=kee(t),n=kee(e);return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function kee(t){return t.replaceAll("\\","/").replace(/\/$/u,"")}function Ree(t){return Fn("ROLLBACK_FAILED",`Bridge setup rollback could not restore: ${t.join(", ")}. Run \`hunsu-bridge doctor --json\` before retrying.`)}function _ee(t,e,r){let n=xS(e);return{ok:!0,code:"OK",message:r.dryRun?"Hunsu Bridge setup dry run completed.":r.idempotent?"Hunsu Bridge is already installed and verified.":"Hunsu Bridge installed and verified.",value:{packageVersion:t.packageVersion,deploymentProfile:e,runtimePath:t.runtimePath,cliPath:t.cliPath,npmCommand:t.npmCommand,commands:{status:`npx @hunsu/bridge@${n} status --profile ${e}`,doctor:`npx @hunsu/bridge@${n} doctor --profile ${e}`,remove:`npx @hunsu/bridge@${n} remove --profile ${e}`},...r}}}function Fn(t,e){return{ok:!1,code:t,message:e}}async function Bee(t=process.argv.slice(2),e=K_e){let r;try{r=GO(t)}catch(i){return nu(Wa(i),BZ(t),e)}let n=Cs(r,"json");try{if(Cs(r,"version")||r.positionals[0]==="version")return nu(mr(`Hunsu Bridge ${bn}.`,{version:bn}),n,e);if(Cs(r,"help")||r.positionals[0]==="help"||r.positionals.length===0)return n?nu(mr("Hunsu Bridge command help.",{usage:Dee()}),!0,e):(e.stdout(Dee()),0);let i=r.positionals[0],o=Mr(r,"home"),s={...process.env},a=Yo({home:o,env:s}),c=TC({paths:a});if((i==="status"||i==="doctor"||i==="remove")&&await z_e(a,Mr(r,"profile")),i==="dev"||i==="daemon"){let d=w3(Mr(r,"profile")),l=await PZ({home:o,host:Mr(r,"host"),port:G_e(Mr(r,"port")),cwd:Mr(r,"cwd"),runtimePath:Mr(r,"runtime-path"),webUrl:Mr(r,"web-url"),deploymentProfile:d,development:i==="dev",env:s}),f=mr(i==="dev"?"Hunsu Bridge development daemon is ready.":"Hunsu Bridge daemon is ready.",{endpoint:l.identity.endpoint,version:l.identity.version,protocolVersion:l.identity.protocolVersion,deploymentProfile:l.identity.deploymentProfile});return nu(f,n,e),await W_e(l),0}let u=GZ({paths:a,controlClient:c,processEnv:s});if(i==="setup"){let d=w3(Mr(r,"profile")),l=xS(d);if((Mr(r,"channel")??l)!==l)throw new De("RUNTIME_INSTALL_FAILED",`The ${d} profile requires the ${l} channel.`);let p=await Aee({paths:a,deploymentProfile:d,credentialStore:wu(a,{processEnv:s}),serviceManager:u,processEnv:s,...Mr(r,"runtime-package")?{runtimeSource:JZ(Mr(r,"runtime-package"))}:{},dryRun:Cs(r,"dry-run"),verifyRuntime:g=>q_e(c,g.packageVersion,g.runtimePath,d)});return nu(p.ok?mr(p.message,p.value):pr(p.code,p.message),n,e)}if(i==="remove"){let d=await pee({deleteData:Cs(r,"delete-data"),confirmed:Cs(r,"confirm-delete-data"),dryRun:Cs(r,"dry-run")},{paths:a,serviceManager:u});return nu(d.ok?mr(d.message,d.value):pr(d.code,d.message),n,e)}if(i==="service")return nu(await j_e(r,u,a),n,e);if(NZ(i))return OZ({parsed:r,paths:a,client:c,emit:d=>nu(d,n,e)});throw new De("BRIDGE_STATE_INVALID",`Unknown command: ${i}`)}catch(i){return nu(Wa(i),n,e)}}async function j_e(t,e,r){let n=t.positionals[1]??"status";if(n==="status")return mr("Hunsu Bridge service status is available.",await e.status());if(n==="install")return Tee(r,async()=>{let i=await Bu(r).read();return i?hS(await e.install(i.serviceInput)):pr("SERVICE_INSTALL_FAILED","Run `hunsu-bridge setup` before installing the service definition.")});if(n==="uninstall")return Tee(r,async()=>hS(await e.uninstall()));if(n==="start")return hS(await e.start());if(n==="stop")return hS(await e.stop());if(n==="restart")return hS(await e.restart());throw new De("BRIDGE_STATE_INVALID",`Unknown service command: ${n}`)}async function Tee(t,e){let r;try{r=await Cp(t,"service-mutation")}catch(o){return o instanceof zs?pr(o.code,o.message):pr("SERVICE_INSTALL_FAILED","The Bridge service mutation lock could not be acquired safely.")}let n,i;try{n=await e()}catch(o){i=o}try{await r.release()}catch{return pr("SERVICE_INSTALL_FAILED","The Bridge service mutation lock could not be released safely.")}if(i!==void 0)throw i;return n}function hS(t){return t.ok?mr(t.message,{manager:t.manager,changed:t.changed},t.code):pr(t.code,t.message)}async function q_e(t,e,r,n){for(let i=0;i<100;i+=1){let o=await t.health();if(o){let s=await t.request("/v1/control/status");return{health:!0,authenticated:s.ok,version:s.ok&&typeof s.value?.version=="string"?s.value.version:o.version,runtimePath:s.ok&&typeof s.value?.runtimePath=="string"?s.value.runtimePath:"unavailable",deploymentProfile:s.ok&&Pn(s.value?.deploymentProfile)?s.value.deploymentProfile:o.deploymentProfile}}await new Promise(s=>setTimeout(s,100))}return{health:!1,authenticated:!1,version:e,runtimePath:r,deploymentProfile:n}}async function W_e(t){let e=()=>{t.close()};process.once("SIGINT",e),process.once("SIGTERM",e);try{await t.waitUntilClosed()}finally{process.off("SIGINT",e),process.off("SIGTERM",e)}}function nu(t,e,r){let n=V_e(t);return e?r.stdout(JSON.stringify(n)):n.ok?(r.stdout(n.message),n.value!==void 0&&r.stdout(JSON.stringify(n.value,null,2))):(r.stderr(`${n.code}: ${n.message}`),n.recovery?.command&&r.stderr(`Recovery: ${n.recovery.command}`)),n.ok?0:1}function V_e(t){try{let e=Qr(t);return Ds(e),e}catch{return pr("DIAGNOSTICS_SENSITIVE_DATA_DETECTED","Sensitive data was removed from Bridge command output.")}}function G_e(t){if(t===void 0)return;let e=Number(t);if(!Number.isInteger(e)||e<0||e>65535)throw new De("BRIDGE_STATE_INVALID","--port must be an integer from 0 through 65535.");return e}function w3(t){let e=t??"production";if(!Pn(e))throw new De("BRIDGE_STATE_INVALID","--profile must be production or preview.");return e}async function z_e(t,e){if(e===void 0)return;let r=w3(e),n=(await Qo(t).read()).deploymentProfile;if(n!==r)throw new De("BRIDGE_STATE_INVALID",`This HUNSU_HOME uses the ${n} deployment profile, not ${r}.`)}function Dee(){return`Usage: hunsu-bridge <command> [options]
275
+
276
+ Lifecycle:
277
+ setup [--profile production|preview] [--channel next|candidate-next]
278
+ Install an exact stable runtime and user service.
279
+ remove [--delete-data --confirm-delete-data]
280
+ service install|uninstall|start|stop|restart|status
281
+ dev [--host 127.0.0.1] [--port 0] [--home <path>] [--profile production|preview]
282
+ daemon [--profile production|preview]
283
+
284
+ Client commands (never start a daemon):
285
+ status | doctor | logs [--follow]
286
+ provider list|status|set codex [--binary <path>] [--codex-home <path>]|check codex|reset codex
287
+ workspace add <path>|list|inspect <id>|remove <id>|open <id>
288
+ workspace grant <id> [--scopes <csv>] | revoke <id>
289
+ credential rotate Rotate and revoke the local control credential.
290
+ pair [--workspace <id>] | pair revoke | open [--workspace <id>]
291
+ login | logout | remote enable|disable|status
292
+
293
+ Common options:
294
+ --json Emit the stable hunsu.bridge.cli-result.v1 schema.
295
+ --home <path> Use an explicit HUNSU_HOME for this invocation.
296
+ --help Show help.
297
+ --version Show the package version.`}var K_e={stdout:t=>process.stdout.write(`${t}
298
+ `),stderr:t=>process.stderr.write(`${t}
299
+ `)};Bee().then(t=>{process.exitCode=t}).catch(()=>{process.stderr.write(`Hunsu Bridge command failed unexpectedly.
300
+ `),process.exitCode=1});
301
+ /*! Bundled license information:
302
+
303
+ reflect-metadata/Reflect.js:
304
+ (*! *****************************************************************************
305
+ Copyright (C) Microsoft. All rights reserved.
306
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
307
+ this file except in compliance with the License. You may obtain a copy of the
308
+ License at http://www.apache.org/licenses/LICENSE-2.0
309
+
310
+ THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
311
+ KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
312
+ WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
313
+ MERCHANTABLITY OR NON-INFRINGEMENT.
314
+
315
+ See the Apache Version 2.0 License for specific language governing permissions
316
+ and limitations under the License.
317
+ ***************************************************************************** *)
318
+
319
+ pvtsutils/build/index.js:
320
+ (*!
321
+ * MIT License
322
+ *
323
+ * Copyright (c) 2017-2024 Peculiar Ventures, LLC
324
+ *
325
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
326
+ * of this software and associated documentation files (the "Software"), to deal
327
+ * in the Software without restriction, including without limitation the rights
328
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
329
+ * copies of the Software, and to permit persons to whom the Software is
330
+ * furnished to do so, subject to the following conditions:
331
+ *
332
+ * The above copyright notice and this permission notice shall be included in all
333
+ * copies or substantial portions of the Software.
334
+ *
335
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
336
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
337
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
338
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
339
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
340
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
341
+ * SOFTWARE.
342
+ *
343
+ *)
344
+
345
+ pvutils/build/utils.js:
346
+ (*!
347
+ Copyright (c) Peculiar Ventures, LLC
348
+ *)
349
+
350
+ asn1js/build/index.js:
351
+ (*!
352
+ * Copyright (c) 2014, GMO GlobalSign
353
+ * Copyright (c) 2015-2022, Peculiar Ventures
354
+ * All rights reserved.
355
+ *
356
+ * Author 2014-2019, Yury Strozhevsky
357
+ *
358
+ * Redistribution and use in source and binary forms, with or without modification,
359
+ * are permitted provided that the following conditions are met:
360
+ *
361
+ * * Redistributions of source code must retain the above copyright notice, this
362
+ * list of conditions and the following disclaimer.
363
+ *
364
+ * * Redistributions in binary form must reproduce the above copyright notice, this
365
+ * list of conditions and the following disclaimer in the documentation and/or
366
+ * other materials provided with the distribution.
367
+ *
368
+ * * Neither the name of the copyright holder nor the names of its
369
+ * contributors may be used to endorse or promote products derived from
370
+ * this software without specific prior written permission.
371
+ *
372
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
373
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
374
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
375
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
376
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
377
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
378
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
379
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
380
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
381
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
382
+ *
383
+ *)
384
+
385
+ tslib/tslib.js:
386
+ (*! *****************************************************************************
387
+ Copyright (c) Microsoft Corporation.
388
+
389
+ Permission to use, copy, modify, and/or distribute this software for any
390
+ purpose with or without fee is hereby granted.
391
+
392
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
393
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
394
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
395
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
396
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
397
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
398
+ PERFORMANCE OF THIS SOFTWARE.
399
+ ***************************************************************************** *)
400
+
401
+ @peculiar/x509/build/x509.cjs.js:
402
+ (*!
403
+ * MIT License
404
+ *
405
+ * Copyright (c) Peculiar Ventures. All rights reserved.
406
+ *
407
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
408
+ * of this software and associated documentation files (the "Software"), to deal
409
+ * in the Software without restriction, including without limitation the rights
410
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
411
+ * copies of the Software, and to permit persons to whom the Software is
412
+ * furnished to do so, subject to the following conditions:
413
+ *
414
+ * The above copyright notice and this permission notice shall be included in all
415
+ * copies or substantial portions of the Software.
416
+ *
417
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
418
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
419
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
420
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
421
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
422
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
423
+ * SOFTWARE.
424
+ *
425
+ *)
426
+
427
+ isobject/index.js:
428
+ (*!
429
+ * isobject <https://github.com/jonschlinkert/isobject>
430
+ *
431
+ * Copyright (c) 2014-2017, Jon Schlinkert.
432
+ * Released under the MIT License.
433
+ *)
434
+
435
+ is-plain-object/index.js:
436
+ (*!
437
+ * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
438
+ *
439
+ * Copyright (c) 2014-2017, Jon Schlinkert.
440
+ * Released under the MIT License.
441
+ *)
442
+
443
+ @noble/hashes/esm/utils.js:
444
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
445
+
446
+ @noble/curves/esm/utils.js:
447
+ @noble/curves/esm/abstract/modular.js:
448
+ @noble/curves/esm/abstract/curve.js:
449
+ @noble/curves/esm/abstract/weierstrass.js:
450
+ @noble/curves/esm/_shortw_utils.js:
451
+ @noble/curves/esm/nist.js:
452
+ @noble/curves/esm/p256.js:
453
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
454
+
455
+ aes-js/index.js:
456
+ (*! MIT License. Copyright 2015-2018 Richard Moore <me@ricmoo.com>. See LICENSE.txt. *)
457
+ */