shadow-claw 1.24.0 → 1.24.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/public/AGENTS.md +7 -0
- package/dist/public/agent.worker.js +49 -49
- package/dist/public/backup-controller-CvzDOq4T.js +1 -0
- package/dist/public/{configurePeerJs-CxpZeDJJ.js → configurePeerJs-UfQ6HUlv.js} +1 -1
- package/dist/public/docs/example/article/index.html +1 -1
- package/dist/public/docs/publishing/index.html +1 -1
- package/dist/public/docs/skill-creator/index.html +1 -1
- package/dist/public/docs/subsystems/control-plane.md +11 -0
- package/dist/public/{downloadGroupFile-By0GR6eV.js → downloadGroupFile-9niHBj9n.js} +1 -1
- package/dist/public/{e2e-bridge-IGWsRl4i.js → e2e-bridge-D28tOggc.js} +1 -1
- package/dist/public/{file-viewer-D0eflgt6.js → file-viewer-BVg3B_JH.js} +1 -1
- package/dist/public/index.html +1 -1
- package/dist/public/index.js +1 -1
- package/dist/public/initControlPlane-DKNht5ph.js +1 -0
- package/dist/public/main/index.html +1 -1
- package/dist/public/main/memory/index.html +1 -1
- package/dist/public/{markdown-BnpKxSxl.js → markdown-SiFq0PTy.js} +1 -1
- package/dist/public/{orchestrator-nJj59RqD.js → orchestrator-8w9-exfN.js} +1 -1
- package/dist/public/{orchestrator-3h9xxHUm.js → orchestrator-tHWrqi_F.js} +5 -5
- package/dist/public/{peerjs-BP4laMXj.js → peerjs-D8hck8Ih.js} +1 -1
- package/dist/public/push-client-D0lkwrK0.js +1 -0
- package/dist/public/service-worker/fetch-proxy.js +1 -1
- package/dist/public/service-worker.js +1 -1
- package/dist/public/{shadow-claw-CbwETBWf.js → shadow-claw-Cs8wbk3d.js} +2 -2
- package/dist/public/{shadow-claw-channels-BDWG5Qa3.js → shadow-claw-channels-mY-JMvib.js} +1 -1
- package/dist/public/{shadow-claw-chat-Crv0DTCY.js → shadow-claw-chat-DGPKpmU5.js} +1 -1
- package/dist/public/{shadow-claw-control-plane-CX1IGbh9.js → shadow-claw-control-plane-B1F0jnPk.js} +2 -2
- package/dist/public/{shadow-claw-conversations-_9qAaRXk.js → shadow-claw-conversations-0Q-VC_7N.js} +1 -1
- package/dist/public/{shadow-claw-file-viewer-Blf6yGVD.js → shadow-claw-file-viewer-AZfG4D-u.js} +1 -1
- package/dist/public/{shadow-claw-files-CYySBDCl.js → shadow-claw-files-Bx4v0Ggp.js} +1 -1
- package/dist/public/{shadow-claw-git-v8S0JjuR.js → shadow-claw-git-DD7iQRxq.js} +2 -2
- package/dist/public/{shadow-claw-llm-GWgoVfhI.js → shadow-claw-llm-CfeDBZKB.js} +1 -1
- package/dist/public/{shadow-claw-networking-qHbP95z9.js → shadow-claw-networking-e0EarDVs.js} +1 -1
- package/dist/public/{shadow-claw-notifications-YyHOK2Fr.js → shadow-claw-notifications-BkxuDEQI.js} +3 -3
- package/dist/public/{shadow-claw-pages-DFZHhzFZ.js → shadow-claw-pages-BWSE91I1.js} +1 -1
- package/dist/public/{shadow-claw-settings-DhxrKIfA.js → shadow-claw-settings-D6lPBn6m.js} +2 -2
- package/dist/public/{shadow-claw-storage-BFynbP0j.js → shadow-claw-storage-Crs6LY15.js} +1 -1
- package/dist/public/{shadow-claw-task-server-3BIeb5oZ.js → shadow-claw-task-server-CKm_Ennl.js} +1 -1
- package/dist/public/{shadow-claw-tasks-Caxc9atL.js → shadow-claw-tasks-Czx6Ucf5.js} +1 -1
- package/dist/public/{shadow-claw-terminal-Beb5qF-U.js → shadow-claw-terminal-Dmtr9KY1.js} +1 -1
- package/dist/public/{shadow-claw-tools-BfJx3A9W.js → shadow-claw-tools-t3Qq4TDO.js} +1 -1
- package/dist/public/{shadow-claw-webvm-BCS8ykeP.js → shadow-claw-webvm-CIuSywD_.js} +1 -1
- package/dist/public/{syncWebMcpRegistration-B_M2fCjH.js → syncWebMcpRegistration-DzC80wVG.js} +1 -1
- package/dist/server.js +3 -3
- package/package.json +1 -1
- package/src/components/settings/shadow-claw-notifications/shadow-claw-notifications.test.ts +3 -0
- package/src/components/settings/shadow-claw-notifications/shadow-claw-notifications.ts +43 -9
- package/src/core/backup-controller.ts +33 -4
- package/src/core/control-plane-client.test.ts +9 -2
- package/src/core/control-plane-client.ts +18 -2
- package/src/core/orchestrator/utils/operations/task.ts +46 -15
- package/src/server/app.ts +2 -0
- package/src/server/control-plane.test.ts +36 -0
- package/src/server/control-plane.ts +39 -13
- package/src/server/middleware/pna.test.ts +15 -3
- package/src/server/middleware/pna.ts +6 -2
- package/src/server/routes/backup.test.ts +14 -0
- package/src/server/routes/backup.ts +44 -15
- package/src/server/server.ts +2 -0
- package/src/service-worker/fetch-proxy-rules.test.ts +41 -0
- package/src/service-worker/fetch-proxy-rules.ts +15 -8
- package/src/service-worker/fetch-proxy.ts +18 -2
- package/src/subsystems/notifications/push-client.test.ts +5 -1
- package/src/subsystems/notifications/push-client.ts +50 -12
- package/dist/public/backup-controller-C_s9in2t.js +0 -1
- package/dist/public/initControlPlane-C9jpnWev.js +0 -1
- package/dist/public/push-client-CrjEXK3U.js +0 -1
package/dist/server.js
CHANGED
|
@@ -88,7 +88,7 @@ import e,{createRequire as t}from"node:module";import n from"process";import{env
|
|
|
88
88
|
/*! @license DOMPurify 3.4.13 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.13/LICENSE */
|
|
89
89
|
function It(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Lt(e){if(Array.isArray(e))return e}function Rt(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function zt(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
90
90
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Bt(e,t){return Lt(e)||Rt(e,t)||Vt(e,t)||zt()}function Vt(e,t){if(e){if(typeof e==`string`)return It(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?It(e,t):void 0}}const Ht=Object.entries,Ut=Object.setPrototypeOf,Wt=Object.isFrozen,Gt=Object.getPrototypeOf,Kt=Object.getOwnPropertyDescriptor;let qt=Object.freeze,Jt=Object.seal,Yt=Object.create,Xt=typeof Reflect<`u`&&Reflect,Zt=Xt.apply,Qt=Xt.construct;qt||=function(e){return e},Jt||=function(e){return e},Zt||=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)},Qt||=function(e){return new e(...[...arguments].slice(1))};const $t=bn(Array.prototype.forEach),en=bn(Array.prototype.lastIndexOf),tn=bn(Array.prototype.pop),nn=bn(Array.prototype.push),rn=bn(Array.prototype.splice),an=Array.isArray,on=bn(String.prototype.toLowerCase),sn=bn(String.prototype.toString),cn=bn(String.prototype.match),ln=bn(String.prototype.replace),un=bn(String.prototype.indexOf),dn=bn(String.prototype.trim),fn=bn(Number.prototype.toString),pn=bn(Boolean.prototype.toString),mn=typeof BigInt>`u`?null:bn(BigInt.prototype.toString),hn=typeof Symbol>`u`?null:bn(Symbol.prototype.toString),gn=bn(Object.prototype.hasOwnProperty),_n=bn(Object.prototype.toString),vn=bn(RegExp.prototype.test),yn=xn(TypeError);function bn(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return Zt(e,t,n)}}function xn(e){return function(){return Qt(e,[...arguments])}}function Sn(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:on;if(Ut&&Ut(e,null),!an(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(Wt(t)||(t[r]=e),i=e)}e[i]=!0}return e}function Cn(e){for(let t=0;t<e.length;t++)gn(e,t)||(e[t]=null);return e}function wn(e){let t=Yt(null);for(let r of Ht(e)){var n=Bt(r,2);let i=n[0],a=n[1];gn(e,i)&&(an(a)?t[i]=Cn(a):a&&typeof a==`object`&&a.constructor===Object?t[i]=wn(a):t[i]=a)}return t}function Tn(e){switch(typeof e){case`string`:return e;case`number`:return fn(e);case`boolean`:return pn(e);case`bigint`:return mn?mn(e):`0`;case`symbol`:return hn?hn(e):`Symbol()`;case`undefined`:return _n(e);case`function`:case`object`:{if(e===null)return _n(e);let t=e,n=En(t,`toString`);if(typeof n==`function`){let e=n(t);return typeof e==`string`?e:_n(e)}return _n(e)}default:return _n(e)}}function En(e,t){for(;e!==null;){let n=Kt(e,t);if(n){if(n.get)return bn(n.get);if(typeof n.value==`function`)return bn(n.value)}e=Gt(e)}function n(){return null}return n}function Dn(e){try{return vn(e,``),!0}catch{return!1}}const On=qt(`a.abbr.acronym.address.area.article.aside.audio.b.bdi.bdo.big.blink.blockquote.body.br.button.canvas.caption.center.cite.code.col.colgroup.content.data.datalist.dd.decorator.del.details.dfn.dialog.dir.div.dl.dt.element.em.fieldset.figcaption.figure.font.footer.form.h1.h2.h3.h4.h5.h6.head.header.hgroup.hr.html.i.img.input.ins.kbd.label.legend.li.main.map.mark.marquee.menu.menuitem.meter.nav.nobr.ol.optgroup.option.output.p.picture.pre.progress.q.rp.rt.ruby.s.samp.search.section.select.shadow.slot.small.source.spacer.span.strike.strong.style.sub.summary.sup.table.tbody.td.template.textarea.tfoot.th.thead.time.tr.track.tt.u.ul.var.video.wbr`.split(`.`)),kn=qt(`svg.a.altglyph.altglyphdef.altglyphitem.animatecolor.animatemotion.animatetransform.circle.clippath.defs.desc.ellipse.enterkeyhint.exportparts.filter.font.g.glyph.glyphref.hkern.image.inputmode.line.lineargradient.marker.mask.metadata.mpath.part.path.pattern.polygon.polyline.radialgradient.rect.stop.style.switch.symbol.text.textpath.title.tref.tspan.view.vkern`.split(`.`)),An=qt([`feBlend`,`feColorMatrix`,`feComponentTransfer`,`feComposite`,`feConvolveMatrix`,`feDiffuseLighting`,`feDisplacementMap`,`feDistantLight`,`feDropShadow`,`feFlood`,`feFuncA`,`feFuncB`,`feFuncG`,`feFuncR`,`feGaussianBlur`,`feImage`,`feMerge`,`feMergeNode`,`feMorphology`,`feOffset`,`fePointLight`,`feSpecularLighting`,`feSpotLight`,`feTile`,`feTurbulence`]),jn=qt([`animate`,`color-profile`,`cursor`,`discard`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`foreignobject`,`hatch`,`hatchpath`,`mesh`,`meshgradient`,`meshpatch`,`meshrow`,`missing-glyph`,`script`,`set`,`solidcolor`,`unknown`,`use`]),Mn=qt(`math.menclose.merror.mfenced.mfrac.mglyph.mi.mlabeledtr.mmultiscripts.mn.mo.mover.mpadded.mphantom.mroot.mrow.ms.mspace.msqrt.mstyle.msub.msup.msubsup.mtable.mtd.mtext.mtr.munder.munderover.mprescripts`.split(`.`)),Nn=qt([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),Pn=qt([`#text`]),Fn=qt(`accept.action.align.alt.autocapitalize.autocomplete.autopictureinpicture.autoplay.background.bgcolor.border.capture.cellpadding.cellspacing.checked.cite.class.clear.color.cols.colspan.command.commandfor.controls.controlslist.coords.crossorigin.datetime.decoding.default.dir.disabled.disablepictureinpicture.disableremoteplayback.download.draggable.enctype.enterkeyhint.exportparts.face.for.headers.height.hidden.high.href.hreflang.id.inert.inputmode.integrity.ismap.kind.label.lang.list.loading.loop.low.max.maxlength.media.method.min.minlength.multiple.muted.name.nonce.noshade.novalidate.nowrap.open.optimum.part.pattern.placeholder.playsinline.popover.popovertarget.popovertargetaction.poster.preload.pubdate.radiogroup.readonly.rel.required.rev.reversed.role.rows.rowspan.spellcheck.scope.selected.shape.size.sizes.slot.span.srclang.start.src.srcset.step.style.summary.tabindex.title.translate.type.usemap.valign.value.width.wrap.xmlns`.split(`.`)),In=qt(`accent-height.accumulate.additive.alignment-baseline.amplitude.ascent.attributename.attributetype.azimuth.basefrequency.baseline-shift.begin.bias.by.class.clip.clippathunits.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.cx.cy.d.dx.dy.diffuseconstant.direction.display.divisor.dominant-baseline.dur.edgemode.elevation.end.exponent.fill.fill-opacity.fill-rule.filter.filterunits.flood-color.flood-opacity.font-family.font-size.font-size-adjust.font-stretch.font-style.font-variant.font-weight.fx.fy.g1.g2.glyph-name.glyphref.gradientunits.gradienttransform.height.href.id.image-rendering.in.in2.intercept.k.k1.k2.k3.k4.kerning.keypoints.keysplines.keytimes.lang.lengthadjust.letter-spacing.kernelmatrix.kernelunitlength.lighting-color.local.marker-end.marker-mid.marker-start.markerheight.markerunits.markerwidth.maskcontentunits.maskunits.max.mask.mask-type.media.method.mode.min.name.numoctaves.offset.operator.opacity.order.orient.orientation.origin.overflow.paint-order.path.pathlength.patterncontentunits.patterntransform.patternunits.points.preservealpha.preserveaspectratio.primitiveunits.r.rx.ry.radius.refx.refy.repeatcount.repeatdur.restart.result.rotate.scale.seed.shape-rendering.slope.specularconstant.specularexponent.spreadmethod.startoffset.stddeviation.stitchtiles.stop-color.stop-opacity.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke.stroke-width.style.surfacescale.systemlanguage.tabindex.tablevalues.targetx.targety.transform.transform-origin.text-anchor.text-decoration.text-orientation.text-rendering.textlength.type.u1.u2.unicode.values.viewbox.visibility.version.vert-adv-y.vert-origin-x.vert-origin-y.width.word-spacing.wrap.writing-mode.xchannelselector.ychannelselector.x.x1.x2.xmlns.y.y1.y2.z.zoomandpan`.split(`.`)),Ln=qt(`accent.accentunder.align.bevelled.close.columnalign.columnlines.columnspacing.columnspan.denomalign.depth.dir.display.displaystyle.encoding.fence.frame.height.href.id.largeop.length.linethickness.lquote.lspace.mathbackground.mathcolor.mathsize.mathvariant.maxsize.minsize.movablelimits.notation.numalign.open.rowalign.rowlines.rowspacing.rowspan.rspace.rquote.scriptlevel.scriptminsize.scriptsizemultiplier.selection.separator.separators.stretchy.subscriptshift.supscriptshift.symmetric.voffset.width.xmlns`.split(`.`)),Rn=qt([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),zn=Jt(/{{[\w\W]*|^[\w\W]*}}/g),Bn=Jt(/<%[\w\W]*|^[\w\W]*%>/g),Vn=Jt(/\${[\w\W]*/g),Hn=Jt(/^data-[\-\w.\u00B7-\uFFFF]+$/),Un=Jt(/^aria-[\-\w]+$/),Wn=Jt(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Gn=Jt(/^(?:\w+script|data):/i),Kn=Jt(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),qn=Jt(/^html$/i),Jn=Jt(/^[a-z][.\w]*(-[.\w]+)+$/i),Yn=Jt(/<[/\w!]/g),Xn=Jt(/<[/\w]/g),Zn=Jt(/<\/no(script|embed|frames)/i),Qn=Jt(/\/>/i),$n={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},er=function(){return typeof window>`u`?null:window},tr=function(e,t){if(typeof e!=`object`||typeof e.createPolicy!=`function`)return null;let n=null,r=`data-tt-policy-suffix`;t&&t.hasAttribute(r)&&(n=t.getAttribute(r));let i=`dompurify`+(n?`#`+n:``);try{return e.createPolicy(i,{createHTML(e){return e},createScriptURL(e){return e}})}catch{return console.warn(`TrustedTypes policy `+i+` could not be created.`),null}},nr=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},rr=function(e,t,n,r){return gn(e,t)&&an(e[t])?Sn(r.base?wn(r.base):{},e[t],r.transform):n};function ir(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:er(),t=e=>ir(e);if(t.version=`3.4.13`,t.removed=[],!e||!e.document||e.document.nodeType!==$n.document||!e.Element)return t.isSupported=!1,t;let n=e.document,r=n,i=r.currentScript;e.DocumentFragment;let a=e.HTMLTemplateElement,o=e.Node,s=e.Element,c=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let l=e.DOMParser,u=e.trustedTypes,d=s.prototype,f=En(d,`cloneNode`),p=En(d,`remove`),m=En(d,`nextSibling`),h=En(d,`childNodes`),g=En(d,`parentNode`),_=En(d,`shadowRoot`),v=En(d,`attributes`),y=o&&o.prototype?En(o.prototype,`nodeType`):null,b=o&&o.prototype?En(o.prototype,`nodeName`):null,x=o&&o.prototype?En(o.prototype,`ownerDocument`):null;if(typeof a==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let S,C=``,w,T=!1,E=0,D=function(){if(E>0)throw yn(`A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.`)},O=function(e){D(),E++;try{return S.createHTML(e)}finally{E--}},k=function(e){D(),E++;try{return S.createScriptURL(e)}finally{E--}},A=function(){return T||=(w=tr(u,i),!0),w},j=n,M=j.implementation,N=j.createNodeIterator,P=j.createDocumentFragment,F=j.getElementsByTagName,I=r.importNode,L=nr();t.isSupported=typeof Ht==`function`&&typeof g==`function`&&M&&M.createHTMLDocument!==void 0;let ee=zn,te=Bn,ne=Vn,R=Hn,re=Un,ie=Gn,ae=Kn,oe=Jn,se=Wn,ce=null,le=Sn({},[...On,...kn,...An,...Mn,...Pn]),ue=null,de=Sn({},[...Fn,...In,...Ln,...Rn]),fe=Object.seal(Yt(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),pe=null,me=null,he=Object.seal(Yt(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),ge=!0,_e=!0,ve=!1,ye=!0,be=!1,xe=!0,Se=!1,Ce=!1,we=null,Te=null,Ee=!1,De=!1,Oe=!1,ke=!1,z=!0,B=!1,Ae=`user-content-`,je=!0,Me=!1,V={},Ne=null,Pe=Sn({},`annotation-xml.audio.colgroup.desc.foreignobject.head.iframe.math.mi.mn.mo.ms.mtext.noembed.noframes.noscript.plaintext.script.selectedcontent.style.svg.template.thead.title.video.xmp`.split(`.`)),Fe=null,Ie=Sn({},[`audio`,`video`,`img`,`source`,`image`,`track`]),Le=null,Re=Sn({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),ze=`http://www.w3.org/1998/Math/MathML`,Be=`http://www.w3.org/2000/svg`,Ve=`http://www.w3.org/1999/xhtml`,He=Ve,Ue=!1,We=null,Ge=Sn({},[ze,Be,Ve],sn),Ke=qt([`mi`,`mo`,`mn`,`ms`,`mtext`]),qe=Sn({},Ke),Je=qt([`annotation-xml`]),Ye=Sn({},Je),Xe=Sn({},[`title`,`style`,`font`,`a`,`script`]),Ze=null,Qe=[`application/xhtml+xml`,`text/html`],$e=null,et=null,tt=n.createElement(`form`),nt=function(e){return e instanceof RegExp||e instanceof Function},rt=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(et&&et===e)return;(!e||typeof e!=`object`)&&(e={}),e=wn(e),Ze=Qe.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,$e=Ze===`application/xhtml+xml`?sn:on,ce=rr(e,`ALLOWED_TAGS`,le,{transform:$e}),ue=rr(e,`ALLOWED_ATTR`,de,{transform:$e}),We=rr(e,`ALLOWED_NAMESPACES`,Ge,{transform:sn}),Le=rr(e,`ADD_URI_SAFE_ATTR`,Re,{transform:$e,base:Re}),Fe=rr(e,`ADD_DATA_URI_TAGS`,Ie,{transform:$e,base:Ie}),Ne=rr(e,`FORBID_CONTENTS`,Pe,{transform:$e}),pe=rr(e,`FORBID_TAGS`,wn({}),{transform:$e}),me=rr(e,`FORBID_ATTR`,wn({}),{transform:$e}),V=gn(e,`USE_PROFILES`)?e.USE_PROFILES&&typeof e.USE_PROFILES==`object`?wn(e.USE_PROFILES):e.USE_PROFILES:!1,ge=e.ALLOW_ARIA_ATTR!==!1,_e=e.ALLOW_DATA_ATTR!==!1,ve=e.ALLOW_UNKNOWN_PROTOCOLS||!1,ye=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,be=e.SAFE_FOR_TEMPLATES||!1,xe=e.SAFE_FOR_XML!==!1,Se=e.WHOLE_DOCUMENT||!1,De=e.RETURN_DOM||!1,Oe=e.RETURN_DOM_FRAGMENT||!1,ke=e.RETURN_TRUSTED_TYPE||!1,Ee=e.FORCE_BODY||!1,z=e.SANITIZE_DOM!==!1,B=e.SANITIZE_NAMED_PROPS||!1,je=e.KEEP_CONTENT!==!1,Me=e.IN_PLACE||!1,se=Dn(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:Wn,He=typeof e.NAMESPACE==`string`?e.NAMESPACE:Ve,qe=gn(e,`MATHML_TEXT_INTEGRATION_POINTS`)&&e.MATHML_TEXT_INTEGRATION_POINTS&&typeof e.MATHML_TEXT_INTEGRATION_POINTS==`object`?wn(e.MATHML_TEXT_INTEGRATION_POINTS):Sn({},Ke),Ye=gn(e,`HTML_INTEGRATION_POINTS`)&&e.HTML_INTEGRATION_POINTS&&typeof e.HTML_INTEGRATION_POINTS==`object`?wn(e.HTML_INTEGRATION_POINTS):Sn({},Je);let t=gn(e,`CUSTOM_ELEMENT_HANDLING`)&&e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING==`object`?wn(e.CUSTOM_ELEMENT_HANDLING):Yt(null);if(fe=Yt(null),gn(t,`tagNameCheck`)&&nt(t.tagNameCheck)&&(fe.tagNameCheck=t.tagNameCheck),gn(t,`attributeNameCheck`)&&nt(t.attributeNameCheck)&&(fe.attributeNameCheck=t.attributeNameCheck),gn(t,`allowCustomizedBuiltInElements`)&&typeof t.allowCustomizedBuiltInElements==`boolean`&&(fe.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),Jt(fe),be&&(_e=!1),Oe&&(De=!0),V&&(ce=Sn({},Pn),ue=Yt(null),V.html===!0&&(Sn(ce,On),Sn(ue,Fn)),V.svg===!0&&(Sn(ce,kn),Sn(ue,In),Sn(ue,Rn)),V.svgFilters===!0&&(Sn(ce,An),Sn(ue,In),Sn(ue,Rn)),V.mathMl===!0&&(Sn(ce,Mn),Sn(ue,Ln),Sn(ue,Rn))),he.tagCheck=null,he.attributeCheck=null,gn(e,`ADD_TAGS`)&&(typeof e.ADD_TAGS==`function`?he.tagCheck=e.ADD_TAGS:an(e.ADD_TAGS)&&(ce===le&&(ce=wn(ce)),Sn(ce,e.ADD_TAGS,$e))),gn(e,`ADD_ATTR`)&&(typeof e.ADD_ATTR==`function`?he.attributeCheck=e.ADD_ATTR:an(e.ADD_ATTR)&&(ue===de&&(ue=wn(ue)),Sn(ue,e.ADD_ATTR,$e))),gn(e,`ADD_URI_SAFE_ATTR`)&&an(e.ADD_URI_SAFE_ATTR)&&Sn(Le,e.ADD_URI_SAFE_ATTR,$e),gn(e,`FORBID_CONTENTS`)&&an(e.FORBID_CONTENTS)&&(Ne===Pe&&(Ne=wn(Ne)),Sn(Ne,e.FORBID_CONTENTS,$e)),gn(e,`ADD_FORBID_CONTENTS`)&&an(e.ADD_FORBID_CONTENTS)&&(Ne===Pe&&(Ne=wn(Ne)),Sn(Ne,e.ADD_FORBID_CONTENTS,$e)),je&&(ce[`#text`]=!0),Se&&Sn(ce,[`html`,`head`,`body`]),ce.table&&(Sn(ce,[`tbody`]),delete pe.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw yn(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw yn(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);let t=S;S=e.TRUSTED_TYPES_POLICY;try{C=O(``)}catch(e){throw S=t,e}}else e.TRUSTED_TYPES_POLICY===null?(S=void 0,C=``):(S===void 0&&(S=A()),S&&typeof C==`string`&&(C=O(``)));qt&&qt(e),et=e},it=Sn({},[...kn,...An,...jn]),H=Sn({},[...Mn,...Nn]),at=function(e,t,n){return t.namespaceURI===Ve?e===`svg`:t.namespaceURI===ze?e===`svg`&&(n===`annotation-xml`||qe[n]):!!it[e]},ot=function(e,t,n){return t.namespaceURI===Ve?e===`math`:t.namespaceURI===Be?e===`math`&&Ye[n]:!!H[e]},st=function(e,t,n){return t.namespaceURI===Be&&!Ye[n]||t.namespaceURI===ze&&!qe[n]?!1:!H[e]&&(Xe[e]||!it[e])},ct=function(e){let t=g(e);(!t||!t.tagName)&&(t={namespaceURI:He,tagName:`template`});let n=on(e.tagName),r=on(t.tagName);return We[e.namespaceURI]?e.namespaceURI===Be?at(n,t,r):e.namespaceURI===ze?ot(n,t,r):e.namespaceURI===Ve?st(n,t,r):!!(Ze===`application/xhtml+xml`&&We[e.namespaceURI]):!1},lt=function(e){nn(t.removed,{element:e});try{g(e).removeChild(e)}catch{if(p(e),!g(e))throw yn(`a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place`)}},ut=function(e){pt(e);let t=h(e);if(t){let e=[];$t(t,t=>{nn(e,t)}),$t(e,e=>{try{p(e)}catch{}})}let n=v(e);if(n)for(let t=n.length-1;t>=0;--t){let r=n[t],i=r&&r.name;if(typeof i==`string`)try{e.removeAttribute(i)}catch{}}},dt=function(e,n){try{nn(t.removed,{attribute:n.getAttributeNode(e),from:n})}catch{nn(t.removed,{attribute:null,from:n})}if(n.removeAttribute(e),e===`is`)if(De||Oe)try{lt(n)}catch{}else try{n.setAttribute(e,``)}catch{}},ft=function(e){let t=v(e);if(t)for(let n=t.length-1;n>=0;--n){let r=t[n],i=r&&r.name;if(!(typeof i!=`string`||ue[$e(i)]))try{e.removeAttribute(i)}catch{}}},pt=function(e){let t=[e];for(;t.length>0;){let e=t.pop();(y?y(e):e.nodeType)===$n.element&&ft(e);let n=h(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},mt=function(e){if(!xe)return;let t=[e];for(;t.length>0;){let e=t.pop(),n=y?y(e):e.nodeType;if(n===$n.processingInstruction||n===$n.comment&&vn(Xn,e.data)){try{p(e)}catch{}continue}if(n===$n.element){let t=e,n=$e(b?b(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute(`patchsrc`)&&t.removeAttribute(`patchsrc`),t.hasAttribute&&t.hasAttribute(`for`)&&n!==`label`&&n!==`output`&&t.removeAttribute(`for`)}catch{}}let r=h(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}},ht=function(e){let t=null,r=null;if(Ee)e=`<remove></remove>`+e;else{let t=cn(e,/^[\r\n\t ]+/);r=t&&t[0]}Ze===`application/xhtml+xml`&&He===Ve&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=S?O(e):e;if(He===Ve)try{t=new l().parseFromString(i,Ze)}catch{}if(!t||!t.documentElement){t=M.createDocument(He,`template`,null);try{t.documentElement.innerHTML=Ue?C:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),He===Ve?F.call(t,Se?`html`:`body`)[0]:Se?t.documentElement:a},gt=function(e){let t=x?x(e):e.ownerDocument;return N.call(t||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},_t=function(e){return e=ln(e,ee,` `),e=ln(e,te,` `),e=ln(e,ne,` `),e},vt=function(e){e.normalize();let t=x?x(e):e.ownerDocument,n=N.call(t||e,e,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null),r=n.nextNode();for(;r;)r.data=_t(r.data),r=n.nextNode();let i=e.querySelectorAll?.call(e,`template`);i&&$t(i,e=>{bt(e.content)&&vt(e.content)})},yt=function(e){let t=b?b(e):null;return typeof t!=`string`||$e(t)!==`form`?!1:typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||e.attributes!==v(e)||typeof e.removeAttribute!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`||e.nodeType!==y(e)||e.childNodes!==h(e)},bt=function(e){if(!y||typeof e!=`object`||!e)return!1;try{return y(e)===$n.documentFragment}catch{return!1}},xt=function(e){if(!y||typeof e!=`object`||!e)return!1;try{return typeof y(e)==`number`}catch{return!1}};function St(e,n,r){e.length!==0&&$t(e,e=>{e.call(t,n,r,et)})}let Ct=function(e,t){return!!(xe&&e.hasChildNodes()&&!xt(e.firstElementChild)&&vn(Yn,e.textContent)&&vn(Yn,e.innerHTML)||xe&&e.namespaceURI===Ve&&t===`style`&&xt(e.firstElementChild)||e.nodeType===$n.processingInstruction||xe&&e.nodeType===$n.comment&&vn(Xn,e.data))},wt=function(e,t,n){if(!pe[t]&&kt(t)&&(fe.tagNameCheck instanceof RegExp&&vn(fe.tagNameCheck,t)||fe.tagNameCheck instanceof Function&&fe.tagNameCheck(t)))return!1;if(je&&!Ne[t]){let t=g(e),r=h(e);if(r&&t){let i=r.length;for(let a=i-1;a>=0;--a){let i=e===n?f(r[a],!0):r[a];t.insertBefore(i,m(e))}}}return lt(e),!0},Tt=function(e,t,n,r){return e.length===0?t:t===n||t===r?wn(t):t},Et=function(e,n){if(St(L.beforeSanitizeElements,e,null),e!==n&&g(e)===null)return Me&&pt(e),!0;if(yt(e))return lt(e),!0;let r=$e(b?b(e):e.nodeName);if(ce=Tt(L.uponSanitizeElement,ce,le,we),St(L.uponSanitizeElement,e,{tagName:r,allowedTags:ce}),e!==n&&g(e)===null)return Me&&pt(e),!0;if(Ct(e,r))return lt(e),!0;if(pe[r]||!(he.tagCheck instanceof Function&&he.tagCheck(r))&&!ce[r]){let t=wt(e,r,n);return t===!1&&St(L.afterSanitizeElements,e,null),t}if((y?y(e):e.nodeType)===$n.element&&!ct(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&vn(Zn,e.innerHTML))return lt(e),!0;if(be&&e.nodeType===$n.text){let n=_t(e.textContent);e.textContent!==n&&(nn(t.removed,{element:e.cloneNode()}),e.textContent=n)}return St(L.afterSanitizeElements,e,null),!1},Dt=function(e,t,r){if(me[t]||xe&&t===`patchsrc`||xe&&t===`for`&&e!==`label`&&e!==`output`||z&&(t===`id`||t===`name`)&&(r in n||r in tt))return!1;let i=ue[t]||he.attributeCheck instanceof Function&&he.attributeCheck(t,e);if(!(_e&&vn(R,t))&&!(ge&&vn(re,t))){if(!i){if(!(kt(e)&&(fe.tagNameCheck instanceof RegExp&&vn(fe.tagNameCheck,e)||fe.tagNameCheck instanceof Function&&fe.tagNameCheck(e))&&(fe.attributeNameCheck instanceof RegExp&&vn(fe.attributeNameCheck,t)||fe.attributeNameCheck instanceof Function&&fe.attributeNameCheck(t,e))||t===`is`&&fe.allowCustomizedBuiltInElements&&(fe.tagNameCheck instanceof RegExp&&vn(fe.tagNameCheck,r)||fe.tagNameCheck instanceof Function&&fe.tagNameCheck(r))))return!1}else if(!Le[t]&&!vn(se,ln(r,ae,``))&&!((t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&un(r,`data:`)===0&&Fe[e])&&!(ve&&!vn(ie,ln(r,ae,``)))&&r)return!1}return!0},Ot=Sn({},[`annotation-xml`,`color-profile`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`missing-glyph`]),kt=function(e){return!Ot[on(e)]&&vn(oe,e)},At=function(e,t,n,r){if(S&&typeof u==`object`&&typeof u.getAttributeType==`function`&&!n)switch(u.getAttributeType(e,t)){case`TrustedHTML`:return O(r);case`TrustedScriptURL`:return k(r)}return r},jt=function(e,n,r,i){try{r?e.setAttributeNS(r,n,i):e.setAttribute(n,i),yt(e)?lt(e):tn(t.removed)}catch{dt(n,e)}},Mt=function(e){St(L.beforeSanitizeAttributes,e,null);let t=e.attributes;if(!t||yt(e))return;ue=Tt(L.uponSanitizeAttribute,ue,de,Te);let n={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:ue,forceKeepAttr:void 0},r=t.length,i=$e(e.nodeName);for(;r--;){let a=t[r],o=a.name,s=a.namespaceURI,c=a.value,l=$e(o),u=c,d=o===`value`?u:dn(u);if(n.attrName=l,n.attrValue=d,n.keepAttr=!0,n.forceKeepAttr=void 0,St(L.uponSanitizeAttribute,e,n),d=n.attrValue,B&&(l===`id`||l===`name`)&&un(d,Ae)!==0&&(dt(o,e),d=Ae+d),xe&&vn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,d)){dt(o,e);continue}if(l===`attributename`&&cn(d,`href`)){dt(o,e);continue}if(!n.forceKeepAttr){if(!n.keepAttr){dt(o,e);continue}if(!ye&&vn(Qn,d)){dt(o,e);continue}if(be&&(d=_t(d)),!Dt(i,l,d)){dt(o,e);continue}d=At(i,l,s,d),d!==u&&jt(e,o,s,d)}}St(L.afterSanitizeAttributes,e,null)},Nt=function(e){let t=null,n=gt(e);for(St(L.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(St(L.uponSanitizeShadowNode,t,null),Et(t,e),Mt(t),bt(t.content)&&Nt(t.content),(y?y(t):t.nodeType)===$n.element){let e=_(t);bt(e)&&(Pt(e),Nt(e))}St(L.afterSanitizeShadowDOM,e,null)},Pt=function(e){let t=[{node:e,shadow:null}];for(;t.length>0;){let e=t.pop();if(e.shadow){Nt(e.shadow);continue}let n=e.node,r=(y?y(n):n.nodeType)===$n.element,i=h(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){let e=b?b(n):null;if(typeof e==`string`&&$e(e)===`template`){let e=n.content;bt(e)&&t.push({node:e,shadow:null})}}if(r){let e=_(n);bt(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,a=null,o=null,s=null;if(Ue=!e,Ue&&(e=`<!-->`),typeof e!=`string`&&!xt(e)&&(e=Tn(e),typeof e!=`string`))throw yn(`dirty is not a string, aborting`);if(!t.isSupported)return e;Ce?(ce=we,ue=Te):rt(n),(L.uponSanitizeElement.length>0||L.uponSanitizeAttribute.length>0)&&(ce=wn(ce)),L.uponSanitizeAttribute.length>0&&(ue=wn(ue)),t.removed=[];let c=Me&&typeof e!=`string`&&xt(e);if(c){mt(e);let t=b?b(e):e.nodeName;if(typeof t==`string`){let n=$e(t);if(!ce[n]||pe[n])throw ut(e),yn(`root node is forbidden and cannot be sanitized in-place`)}if(yt(e))throw ut(e),yn(`root node is clobbered and cannot be sanitized in-place`);try{Pt(e)}catch(t){throw ut(e),t}}else if(xt(e))i=ht(`<!---->`),a=i.ownerDocument.importNode(e,!0),a.nodeType===$n.element&&a.nodeName===`BODY`||a.nodeName===`HTML`?i=a:i.appendChild(a),Pt(a);else{if(!De&&!be&&!Se&&e.indexOf(`<`)===-1)return S&&ke?O(e):e;if(i=ht(e),!i)return De?null:ke?C:``}i&&Ee&<(i.firstChild);let l=c?e:i;try{let e=gt(l);for(;o=e.nextNode();)Et(o,l),Mt(o),bt(o.content)&&Nt(o.content)}catch(n){throw c&&(ut(e),$t(t.removed,e=>{e.element&&pt(e.element)})),n}if(c)return $t(t.removed,e=>{e.element&&pt(e.element)}),be&&vt(e),e;if(De){if(be&&vt(i),Oe)for(s=P.call(i.ownerDocument);i.firstChild;)s.appendChild(i.firstChild);else s=i;return(ue.shadowroot||ue.shadowrootmode)&&(s=I.call(r,s,!0)),s}let u=Se?i.outerHTML:i.innerHTML;return Se&&ce[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&vn(qn,i.ownerDocument.doctype.name)&&(u=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
|
|
91
|
-
`+u),be&&(u=_t(u)),S&&ke?O(u):u},t.setConfig=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};rt(e),Ce=!0,we=ce,Te=ue},t.clearConfig=function(){et=null,Ce=!1,we=null,Te=null,S=w,C=``},t.isValidAttribute=function(e,t,n){et||rt({});let r=$e(e),i=$e(t);return Dt(r,i,n)},t.addHook=function(e,t){typeof t==`function`&&gn(L,e)&&nn(L[e],t)},t.removeHook=function(e,t){if(gn(L,e)){if(t!==void 0){let n=en(L[e],t);return n===-1?void 0:rn(L[e],n,1)[0]}return tn(L[e])}},t.removeHooks=function(e){gn(L,e)&&(L[e]=[])},t.removeAllHooks=function(){L=nr()},t}ir(),new Promise(e=>{});let ar=[`youtube.com`,`youtube-nocookie.com`,`youtu.be`,`xt-ml.github.io`,`kherrick.github.io`];function or(e){e.map(e=>sr(e)).filter(Boolean)}or(ar);function sr(e){let t=e.trim();if(!t)return()=>!1;if(t.startsWith(`/`)&&(t.endsWith(`/`)||/\/[gimuy]*$/.test(t)))try{let e=t.lastIndexOf(`/`),n=t.slice(1,e),r=t.slice(e+1),i=new RegExp(n,r||`i`);return e=>i.test(e)}catch{}if(t.includes(`^`)||t.includes(`$`)||t.includes(`(`)&&t.includes(`)`))try{let e=new RegExp(t,`i`);return t=>e.test(t)}catch{}if(t.startsWith(`*.`)){let e=t.slice(2).toLowerCase();return t=>{let n=t.toLowerCase();return n===e||n.endsWith(`.`+e)}}let n=t.toLowerCase();return e=>{let t=e.toLowerCase();return t===n||t.endsWith(`.`+n)}}const cr=[],lr=[];new Set(cr.map(e=>e.toLowerCase().trim()));let ur=[...lr];function dr(e){e.map(e=>sr(e)).filter(Boolean)}dr(ur);const fr=[`'self'`,`blob:`,`data:`],pr=[`'self'`,`blob:`,`data:`],mr=[`'self'`,`'unsafe-inline'`,`https:`,`http:`],hr=[`'self'`,`blob:`,`data:`,`https:`,`http:`];[...fr],[...pr],[...mr],[...hr];function gr(){return`shadowclaw`}function _r(e={}){let t=e.includeTrustedTypes??!0,n=[`default-src 'self'`,`base-uri 'self'`,`frame-ancestors 'none'`,`frame-src 'self' https://www.youtube.com`,`object-src 'none'`,`img-src 'self' data: blob: https: http:`,`media-src 'self' data: blob: https: http:`,`font-src 'self' data: https://fonts.googleapis.com https://fonts.gstatic.com`,`style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://fonts.googleapis.com`,`script-src 'self' 'unsafe-inline'`,`worker-src 'self' blob:`,`connect-src 'self' https: wss: ws: data:`,`report-uri /__cspreport`];return t&&n.push(`trusted-types ${gr()} shadowclaw-sandbox dompurify default`,`require-trusted-types-for 'script'`),n.join(`; `)}function vr(e,t={}){e.setHeader(`Content-Security-Policy-Report-Only`,_r(t))}function yr(e){return!/\bfirefox\//i.test(e)}function br(){return(e,t,n)=>{vr(t,{includeTrustedTypes:yr(e.get(`user-agent`)??``)}),n()}}function xr(e,t){return(n,r,i)=>{n.headers[`access-control-request-private-network`]===`true`&&(t&&e.log(`VERBOSE`,`[PNA] Allowing Private Network Access`),r.setHeader(`Access-Control-Allow-Private-Network`,`true`)),i()}}function Sr(e,t,n,r){let i=t*2**e,a=Math.min(i,n),o=a*r*Math.random();return Math.max(0,a-o)}function Cr(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new DOMException(`Aborted`,`AbortError`));return}let i=setTimeout(n,e);if(t){let e=()=>{clearTimeout(i),r(t.reason??new DOMException(`Aborted`,`AbortError`))};t.addEventListener(`abort`,e,{once:!0});let a=n;n=(n=>{t.removeEventListener(`abort`,e),a(n)})}})}async function wr(e,t={}){let{maxRetries:n=3,baseDelayMs:r=1e3,maxDelayMs:i=3e4,jitterFactor:a=.5,shouldRetry:o=()=>!0,onRetry:s,signal:c}=t,l;for(let t=0;t<=n;t++){if(c?.aborted)throw c.reason??new DOMException(`Aborted`,`AbortError`);try{return await e()}catch(e){if(l=e,e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`)throw e;if(t>=n||!o(e,t+1))break;let u=Sr(t,r,i,a);s&&s(t+1,n,u,e),await Cr(u,c)}}throw l}const Tr=new Set([408,429,500,502,503,504]);function Er(e){if(e instanceof TypeError)return!0;if(typeof e?.status==`number`)return Tr.has(e.status);if(e instanceof Error){let t=e.message,n=t.match(/\b(4\d{2}|5\d{2})\b/);if(n)return Tr.has(Number(n[1]));if(/network|ECONNRESET|ECONNREFUSED|ETIMEDOUT|fetch failed|EAI_AGAIN|EAI_NONAME|getaddrinfo/i.test(t))return!0}return!1}const Dr=n.env.SHADOWCLAW_USER_AGENT||`ShadowClaw/1.0`;function Or(e){return Array.isArray(e)?e[0]||``:typeof e==`string`?e:``}function kr(e,t){let n=Number.parseInt(e??``,10);return!Number.isFinite(n)||n<=0?t:n}function Ar(e,t){let n=Number.parseInt(e??``,10);return!Number.isFinite(n)||n<0?t:n}function jr(e){return/^\/telegram\/(?:bot|file\/bot)[^/]+\//.test(e)}function Mr(e){try{let t=new URL(e);return t.hostname===`api.telegram.org`&&jr(t.pathname)&&(t.pathname=t.pathname.replace(/^\/telegram\/(?:bot|file\/bot)[^/]+\//,e=>e.includes(`/file/`)?`/telegram/file/bot[REDACTED]/`:`/telegram/bot[REDACTED]/`)),t.toString()}catch{return e.replace(/\/file\/bot[^/]+\//,`/file/bot[REDACTED]/`).replace(/\/bot[^/]+\//,`/bot[REDACTED]/`)}}function Nr(e){return e===`localhost`||e===`::1`||/^127\./.test(e)||/^10\./.test(e)||/^192\.168\./.test(e)||/^172\.(1[6-9]|2\d|3[01])\./.test(e)||/^169\.254\./.test(e)}async function Pr(e,t,n){if(!n||n<=0)return fetch(e,t);let r=new AbortController,i=t.signal,a=i?AbortSignal.any([i,r.signal]):r.signal,o=setTimeout(()=>{r.abort()},n);try{return await fetch(e,{...t,signal:a})}catch(e){throw e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`?Error(`Upstream request timed out after ${n}ms`):e}finally{clearTimeout(o)}}function Fr(e){return Array.isArray(e.tools)&&e.tools.length>0}function Ir(e){let t={...e};return delete t.tools,delete t.tool_choice,t}function Lr(e){return/does not support tools/i.test(e||``)}async function Rr(e,t,n){let{targetUrl:r,method:i,headers:a,body:o,verbose:s,maxRetries:c,requestTimeoutMs:l,forwardAuth:u,allowPrivate:d,fromServiceWorker:f}=n;s&&console.log(`[Proxy] Forwarding ${i} request to: ${Mr(r)}`);try{let e;try{e=new URL(r)}catch{t.status(400).json({error:`Invalid URL`});return}if(e.protocol!==`http:`&&e.protocol!==`https:`){t.status(400).json({error:`Unsupported URL scheme — only http and https are allowed`});return}if(Nr(e.hostname)&&!d&&!f){t.status(403).json({error:`Requests to private or internal addresses are blocked`});return}let n={...a};n[`User-Agent`]=Dr,delete n.host,delete n.origin,delete n.referer,u||(delete n.Authorization,delete n.authorization),delete n[`accept-encoding`],delete n[`content-length`],delete n.connection;let p=await wr(()=>Pr(e.toString(),{method:i,headers:n,body:i===`GET`||i===`HEAD`?void 0:o instanceof E?o:o?.toString()},l),{maxRetries:c??3,shouldRetry:Er,onRetry:(e,t,n,r)=>{s&&console.log(`[Proxy] Retry ${e}/${t} after ${n}ms due to: ${r.message||r}`)}});t.status(p.status),p.headers.forEach((e,n)=>{let r=n.toLowerCase();r===`content-encoding`||r===`transfer-encoding`||r===`content-length`||r===`connection`||t.setHeader(n,e)}),t.setHeader(`Access-Control-Allow-Origin`,`*`);let m=E.from(await p.arrayBuffer());t.send(m)}catch(e){console.error(`Proxy error:`,e),t.status(500).json({error:`Proxy request failed`})}}async function zr(e,t,n){let{targetUrl:r,headers:i,body:a,verbose:o,maxRetries:s,requestTimeoutMs:c,allowPrivate:l,fromServiceWorker:u}=n;o&&console.log(`[Proxy] Streaming POST request to: ${Mr(r)}`);try{let e;try{e=new URL(r)}catch{t.status(400).json({error:`Invalid URL`});return}if(e.protocol!==`http:`&&e.protocol!==`https:`){t.status(400).json({error:`Unsupported URL scheme — only http and https are allowed`});return}if(Nr(e.hostname)&&!l&&!u){t.status(403).json({error:`Requests to private or internal addresses are blocked`});return}let n={...i};delete n.host,delete n.origin,delete n.referer,delete n[`accept-encoding`],delete n[`content-length`],delete n.connection;let d=await wr(()=>Pr(e.toString(),{method:`POST`,headers:{...n,"User-Agent":Dr},body:a},c),{maxRetries:s??3,shouldRetry:Er,onRetry:(e,t,n,r)=>{o&&console.log(`[Proxy] Streaming Retry ${e}/${t} after ${n}ms due to: ${r.message||r}`)}});if(!d.ok){let e=await d.text();t.status(d.status),t.setHeader(`Access-Control-Allow-Origin`,`*`),t.json({error:e});return}if(t.status(200),t.setHeader(`Content-Type`,`text/event-stream`),t.setHeader(`Cache-Control`,`no-cache`),t.setHeader(`Connection`,`keep-alive`),t.setHeader(`Access-Control-Allow-Origin`,`*`),t.flushHeaders(),!d.body){t.end();return}let f=d.body.getReader();try{for(;;){let{done:e,value:n}=await f.read();if(e)break;t.write(E.from(n))}}finally{f.releaseLock()}t.end()}catch(e){console.error(`Streaming proxy error:`,e),t.headersSent?t.end():t.status(500).json({error:`Streaming proxy request failed`})}}function Br(e){let t=e.trim();if(!t)return{};let n=[],r=``,i=null;for(let e=0;e<t.length;e+=1){let a=t[e];if((a===`"`||a===`'`)&&t[e-1]!==`\\`){i===a?i=null:i||=a,r+=a;continue}if(a===`,`&&!i){r.trim()&&n.push(r.trim()),r=``;continue}r+=a}r.trim()&&n.push(r.trim());let a={};for(let e of n){let t=e.indexOf(`:`),n=e.indexOf(`=`),r=t>0?t:n;if(r<=0)continue;let i=e.slice(0,r).trim().replace(/^['"]|['"]$/g,``),o=e.slice(r+1).trim();if(i){if(o.startsWith(`"`)&&o.endsWith(`"`)||o.startsWith(`'`)&&o.endsWith(`'`)){o=o.slice(1,-1),a[i]=o.replace(/\\(["'\\])/g,`$1`);continue}if(o===`true`){a[i]=!0;continue}if(o===`false`){a[i]=!1;continue}if(o===`null`){a[i]=null;continue}if(/^-?\d+(\.\d+)?$/.test(o)){a[i]=Number(o);continue}a[i]=o}}return a}function Vr(e){let t=e.trim();if(!t)return{};let n=[],r=``,i=null,a=0;for(let e=0;e<t.length;e+=1){let o=t[e];if((o===`"`||o===`'`)&&t[e-1]!==`\\`){i===o?i=null:i||=o,r+=o;continue}if(!i){if(o===`(`||o===`{`||o===`[`)a+=1;else if((o===`)`||o===`}`||o===`]`)&&a>0)--a;else if(o===`,`&&a===0){r.trim()&&n.push(r.trim()),r=``;continue}}r+=o}r.trim()&&n.push(r.trim());let o={};for(let e of n){if(e=e.trim(),!e)continue;let t=e.indexOf(`=`),n=e.indexOf(`:`),r=t>0?t:n;if(r<=0)continue;let i=e.slice(0,r).trim().replace(/^['"]|['"]$/g,``),a=e.slice(r+1).trim();if(!i)continue;if(a.startsWith(`"`)&&a.endsWith(`"`)||a.startsWith(`'`)&&a.endsWith(`'`)){a=a.slice(1,-1),o[i]=a.replace(/\\(["'\\])/g,`$1`);continue}if(a===`true`){o[i]=!0;continue}if(a===`false`){o[i]=!1;continue}if(a===`null`){o[i]=null;continue}let s=Number(a);if(!Number.isNaN(s)&&a!==``){o[i]=s;continue}o[i]=a}return o}function Hr(e,t){return(n,r,i)=>{let a=Date.now(),o=Or(n.headers[`x-forwarded-for`])||n.socket?.remoteAddress||n.ip||`unknown`,s=Or(n.headers.origin)||`-`,c=Or(n.headers.host)||`-`,l=Or(n.headers[`access-control-request-method`])||`-`,u=Or(n.headers[`access-control-request-headers`])||`-`,d=Or(n.headers[`access-control-request-private-network`])||`-`,f=n.originalUrl.replace(/\/telegram\/(?:bot|file\/bot)[^/]+\//,e=>e.startsWith(`/telegram/file/`)?`/telegram/file/bot[REDACTED]/`:`/telegram/bot[REDACTED]/`);e.log(`DEFAULT`,`--> ${n.method} ${f} ip=${o} host=${c} origin=${s}`),n.method===`OPTIONS`&&e.log(`DEFAULT`,` [Preflight] request-method=${l} request-headers=${u} private-network=${d}`),r.on(`finish`,()=>{let i=Date.now()-a,o=r.statusCode,s=r.getHeader(`access-control-allow-origin`)||`-`,c=r.getHeader(`access-control-allow-private-network`)||`-`;e.log(`DEFAULT`,`<-- ${n.method} ${f} ${o} (${i}ms) allow-origin=${s} allow-private-network=${c}`),t&&(e.log(`VERBOSE`,` Query:`,n.query),n.body&&Object.keys(n.body).length>0&&e.log(`VERBOSE`,` Body keys:`,Object.keys(n.body)))}),i()}}const Ur=new Set([`chat`,`files`,`pages`,`tasks`,`settings`,`tools`,`channels`]);function Wr(e,t){let n=(e.method||`GET`).toUpperCase();if(n!==`GET`&&n!==`HEAD`)return!1;let r=String(e.headers[`sec-fetch-dest`]||``).toLowerCase();if(r&&r!==`document`)return!1;let i=String(e.headers[`sec-fetch-mode`]||``).toLowerCase(),a=String(e.headers[`sec-fetch-user`]||``).toLowerCase(),o=r===`document`||i===`navigate`||a===`?1`,s=String(e.headers.accept||``);if(!o&&!s.includes(`text/html`))return!1;let c=t.replace(/^\/+|\/+$/g,``);if(!c)return!1;let l=c.split(`/`,1)[0]||``;return Ur.has(l)}function Gr(e,t){e.use(D(/^(.+)\/index\.html$/,`$1/`)),e.use((e,n,r)=>{n.setHeader(`Access-Control-Allow-Origin`,`*`),n.setHeader(`Access-Control-Allow-Methods`,`GET, HEAD, OPTIONS`);let i=new URL(e.originalUrl,`http://localhost`).pathname;i.startsWith(`/assets/v86.9pfs/`)||i.startsWith(`/assets/v86.ext2/`)?n.setHeader(`Cache-Control`,`public, max-age=31536000, immutable`):n.setHeader(`Cache-Control`,`no-cache`);let a=o.join(t,e.url);h.stat(a,(s,c)=>{if(s||!c){if(Wr(e,i)){n.sendFile(o.join(t,`index.html`));return}let a=i.replace(/^\/[^/]+/,``);if(a){let e=o.join(t,a);try{if(h.existsSync(e)&&h.statSync(e).isFile()){n.sendFile(e);return}}catch{}}if(i.startsWith(`/files/main/`)){let e=o.resolve(`pages/main`,i.slice(12));h.stat(e,(t,i)=>{if(!t&&i&&i.isFile()){n.sendFile(e);return}r()});return}if(i.startsWith(`/static-main/`)){let e=o.resolve(`pages/main`,i.slice(13));h.stat(e,(t,i)=>{if(!t&&i&&i.isFile()){n.sendFile(e);return}r()});return}if(i.startsWith(`/pages/`)){let e=o.resolve(`pages`,i.slice(7));h.stat(e,(t,i)=>{if(!t&&i&&i.isFile()){n.sendFile(e);return}r()});return}r();return}if(c.isDirectory()){let e=o.join(a,`index.html`);h.access(e,h.constants.F_OK,t=>{t?r():n.sendFile(e)})}else n.sendFile(a)})}),e.use(m.static(t,{etag:!0}))}function Kr(e,t={}){let n=t.verbose??!1,r=t.allowPrivateProxy??!1;e.all(/^\/proxy(\/(.*))?$/,async(e,t)=>{let i=typeof e.query.url==`string`?e.query.url:void 0,a=(e.body&&typeof e.body.url==`string`?e.body.url:void 0)||i;if(!a){let t=e.params[1];if(t){a=t;let n={...e.query};if(delete n.url,Object.keys(n).length>0){let e=a.includes(`?`)?`&`:`?`;a+=e+new URLSearchParams(n).toString()}}}if(!a)return t.status(400).json({error:`Missing 'url' parameter`});let o=(e.body&&typeof e.body.method==`string`&&e.body.method||e.method).toUpperCase(),s=!!(e.body&&e.body.headers&&typeof e.body.headers==`object`),c=(s?e.body.headers:e.headers)||{},l;e.body&&typeof e.body.body==`string`&&(l=e.body.body);let u=s&&!!(c.Authorization||c.authorization);await Rr(e,t,{targetUrl:a,method:o,headers:c,body:l,verbose:n,forwardAuth:u,fromServiceWorker:s,allowPrivate:r})}),e.all(/^\/telegram\/((?:bot.*)|(?:file\/bot.*))$/,async(e,t)=>{t.setHeader(`Cache-Control`,`no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0`),t.setHeader(`Pragma`,`no-cache`),t.setHeader(`Expires`,`0`);let r=`https://api.telegram.org/${e.params[0]}${Object.keys(e.query).length>0?`?`+new URLSearchParams(e.query).toString():``}`,i=e.method.toUpperCase(),a=e.headers||{},o;if((a[`content-type`]||``).includes(`multipart/form-data`)){let t=[];for await(let n of e)t.push(n);o=E.concat(t)}else e.body&&typeof e.body.body==`string`?o=e.body.body:e.body&&typeof e.body==`object`&&Object.keys(e.body).length>0&&!(`url`in e.body)&&!(`method`in e.body)&&!(`headers`in e.body)&&(o=JSON.stringify(e.body));await Rr(e,t,{targetUrl:r,method:i,headers:a,body:o,verbose:n})}),e.all(/^\/git-proxy\/(.*)/,async(e,t)=>{let r=e.params[0],i=Object.keys(e.query).length>0?`?`+new URLSearchParams(e.query).toString():``,a=`https://`+r+i,o=[];for await(let t of e)o.push(t);let s=E.concat(o);await Rr(e,t,{targetUrl:a,method:e.method,headers:e.headers,body:s.length>0?s:void 0,verbose:n,forwardAuth:!0})})}const qr=r.BEDROCK_REGION||``,Jr=r.BEDROCK_PROFILE||``,Yr=new Map;function Xr(e){return{region:qr||Or(e.headers[`x-bedrock-region`])?.trim()||``,profile:Jr||Or(e.headers[`x-bedrock-profile`])?.trim()||``,authMode:Or(e.headers[`x-bedrock-auth-mode`])?.trim()||`provider_chain`}}function Zr(e,t){return t===`sso`?F({profile:e}):P({profile:e})}function Qr(e,t){if(/^[a-z]+\.anthropic\./.test(e))return e;let n=t.split(`-`)[0];if(!n)throw Error(`Bedrock region is not configured. Set BEDROCK_REGION or provide x-bedrock-region header.`);return`${n}.${e}`}function $r(e){if(e.type===`text`)return{text:e.text};if(e.type===`image`){let t=e.source.data;return{image:{format:e.source.media_type.split(`/`)[1],source:{bytes:E.from(t,`base64`)}}}}if(e.type===`tool_use`)return{toolUse:{toolUseId:e.id,name:e.name,input:e.input}};if(e.type===`tool_result`){let t=typeof e.content==`string`?[{text:e.content}]:Array.isArray(e.content)?e.content.map(e=>e.type===`text`?{text:e.text}:{text:JSON.stringify(e)}):[{text:JSON.stringify(e.content)}];return{toolResult:{toolUseId:e.tool_use_id,content:t}}}return e.type===`thinking`?typeof e.signature!=`string`||e.signature.length===0?void 0:{reasoningContent:{reasoningText:{text:e.thinking||``,signature:e.signature}}}:e.type===`redacted_thinking`?{reasoningContent:{redactedContent:{data:e.data||``}}}:{text:JSON.stringify(e)}}function ei(e){return!!(e&&typeof e==`object`&&e.cache_control)}function ti(e){let t=e?.ttl;return{cachePoint:{type:`default`,...t===`1h`||t===`5m`?{ttl:t}:{}}}}function ni(e=4){let t=e;return{take(){return t<=0?!1:(--t,!0)}}}function ri(e,t){let n=`(continue)`;if(!Array.isArray(e)||e.length===0)return[];let r=(e||[]).map(e=>{let n=Array.isArray(e.content)?e.content:[{type:`text`,text:typeof e.content==`string`?e.content:``}],r=Array.isArray(e.content)?e.content.map($r):[{text:typeof e.content==`string`?e.content:``}],i=[];return r.forEach((e,r)=>{if(e===void 0||e&&typeof e.text==`string`&&e.text.trim().length===0)return;i.push(e);let a=n[r];ei(a)&&t?.take()&&i.push(ti(a.cache_control))}),{role:e.role,content:i}}),i=r.filter(e=>e.content.length>0);if(i.length===0&&r.length>0){let e=r[r.length-1];return[{role:e.role===`assistant`?`user`:e.role,content:[{text:n}]}]}let a=[];for(let e of i){let t=a[a.length-1];if(t&&t.role===e.role){t.content.push(...e.content);continue}a.push(e)}return a.length>0&&a[0].role===`assistant`&&a.shift(),a.length===0?[{role:`user`,content:[{text:n}]}]:(a[a.length-1].role===`assistant`&&a.push({role:`user`,content:[{text:n}]}),a)}function ii(e){switch(e){case`tool_use`:return`tool_use`;case`max_tokens`:return`max_tokens`;case`stop_sequence`:return`stop_sequence`;default:return`end_turn`}}function ai(){return`msg_`+Math.random().toString(36).substring(2,10)}function oi(e){if(typeof e!=`string`)return;let t=e.trim().toLowerCase();if(t===`low`||t===`medium`||t===`high`||t===`xhigh`||t===`max`)return t;if(t===`minimal`||t===`none`)return`low`}function si(e,t){let n=typeof e==`number`&&Number.isFinite(e)?Math.max(1,e):0,r=n>0?n/(typeof t==`number`&&Number.isFinite(t)?Math.max(1,t):8192):.5;return r>=.95?`max`:r>=.85?`xhigh`:r>=.7?`high`:r>=.35?`medium`:`low`}function ci(e){if(typeof e!=`string`||e.trim().length===0)return;let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``);if(t.includes(`claude-sonnet-5`)||t.includes(`claude-opus-4-7`)||t.includes(`claude-opus-5`)||t.includes(`claude-opus-4-8`)||t.includes(`claude-mythos-5`))return!0;if(t.includes(`claude-sonnet-4-6`))return!1}function li(e,t){if(typeof e!=`string`||e.trim().length===0)return;let n=ci(e),r=ci(t)??n;typeof r==`boolean`&&Yr.set(e.toLowerCase(),r)}function ui(e,t){let n=e.toLowerCase(),r=t.toLowerCase();if(Yr.has(n))return Yr.get(n)===!0;if(Yr.has(r))return Yr.get(r)===!0;let i=ci(n);if(typeof i==`boolean`)return i;let a=ci(r);return typeof a==`boolean`&&a}function di(e,t,n){if(!e?.thinking)return;let r=e.thinking;if(!ui(t,n)||(typeof r?.type==`string`?r.type.toLowerCase():``)===`disabled`)return{thinking:r};let i=oi(e?.output_config?.effort),a=si(r?.budget_tokens,e?.max_tokens);return{thinking:{type:`adaptive`},output_config:{effort:i||a}}}function fi(e,t={}){e.get(`/bedrock-proxy/models`,async(e,t)=>{try{let n=Xr(e);if(!n.region||!n.profile)return t.status(400).json({error:`Bedrock is not configured. Set BEDROCK_REGION and BEDROCK_PROFILE environment variables or provide Bedrock fallback settings in the UI.`});let r=new O({region:n.region,credentials:Zr(n.profile,n.authMode)}),i=((await r.send(new k({byProvider:`Anthropic`}))).modelSummaries||[]).filter(e=>e.modelLifecycle?.status===`ACTIVE`).map(e=>(li(e.modelId,e.modelName),{id:e.modelId,name:e.modelName}));try{let e=((await r.send(new A({}))).inferenceProfileSummaries||[]).filter(e=>e.status===`ACTIVE`).filter(e=>e.inferenceProfileId?.includes(`anthropic`)||e.inferenceProfileName?.toLowerCase().includes(`anthropic`)).map(e=>({id:e.inferenceProfileId||``,name:`${e.inferenceProfileName||`Unnamed Profile`} (Profile)`})).map(e=>(li(e.id,e.name),e));i.push(...e)}catch(e){(e&&typeof e==`object`&&`name`in e?e.name:``)!==`AccessDeniedException`&&console.warn(`Failed to list Bedrock inference profiles:`,e instanceof Error?e.message:String(e))}t.json({models:i})}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Bedrock models discovery error:`,n),t.status(502).json({error:`Failed to list Bedrock models: ${n}`})}}),e.post(`/bedrock-proxy/invoke`,async(e,t)=>{try{let n=Xr(e);if(!n.region||!n.profile)return t.status(400).json({error:`Bedrock is not configured. Set BEDROCK_REGION and BEDROCK_PROFILE environment variables or provide Bedrock fallback settings in the UI.`});let r=e.body;if(!r||typeof r!=`object`)return t.status(400).json({error:`Missing request body`});let i=r.model;if(typeof i!=`string`||!i.startsWith(`anthropic.`)&&!/^[a-z]+\.anthropic\./.test(i))return t.status(400).json({error:`Invalid model ID: '${String(i||``)}'. Must be an Anthropic Bedrock model ID.`});let a=Qr(i,n.region),o=r.stream===!0,{model:s,stream:c,...l}=r,u=new j({region:n.region,credentials:Zr(n.profile,n.authMode),maxAttempts:3,retryMode:`adaptive`,requestHandler:{requestTimeout:6e4}}),d=ni(),f;if(l.tools&&l.tools.length>0){let e=[];for(let t of l.tools)e.push({toolSpec:{name:t.name,description:t.description,inputSchema:{json:t.input_schema}}}),ei(t)&&d.take()&&e.push(ti(t.cache_control));if(f={tools:e},l.tool_choice){let e=l.tool_choice;e.type===`tool`?f.toolChoice={tool:{name:e.name}}:e.type===`any`?f.toolChoice={any:{}}:f.toolChoice={auto:{}}}}let p=[];if(Array.isArray(l.system))for(let e of l.system){let t=typeof e?.text==`string`?e.text:``;t.trim().length!==0&&(p.push({text:t}),ei(e)&&d.take()&&p.push(ti(e.cache_control)))}else typeof l.system==`string`&&l.system.trim().length>0&&p.push({text:l.system});let m=p.length>0?p:void 0,h=ri(l.messages||[],d),g={};l.max_tokens&&(g.maxTokens=l.max_tokens),l.temperature!==void 0&&(g.temperature=l.temperature),l.top_p!==void 0&&(g.topP=l.top_p),l.stop_sequences&&(g.stopSequences=l.stop_sequences);let _={modelId:a,messages:h,system:m,inferenceConfig:Object.keys(g).length>0?g:void 0,toolConfig:f,additionalModelRequestFields:di(l,i,a)};if(o){let e=new N(_),n=await u.send(e);if(t.status(200),t.setHeader(`Content-Type`,`text/event-stream`),t.setHeader(`Cache-Control`,`no-cache`),t.setHeader(`Connection`,`keep-alive`),t.setHeader(`Access-Control-Allow-Origin`,`*`),t.flushHeaders(),t.write(`data: ${JSON.stringify({type:`message_start`,message:{id:ai(),type:`message`,role:`assistant`,model:a,content:[],usage:{input_tokens:0,output_tokens:0}}})}\n\n`),n.stream){let e=new Set;for await(let r of n.stream)if(r.contentBlockStart){let n=r.contentBlockStart.start,i=r.contentBlockStart.contentBlockIndex??0;if(e.add(i),n?.toolUse)t.write(`data: ${JSON.stringify({type:`content_block_start`,index:i,content_block:{type:`tool_use`,id:n.toolUse.toolUseId,name:n.toolUse.name,input:{}}})}\n\n`);else if(n?.reasoningContent!==void 0){let e=typeof n?.reasoningContent?.signature==`string`?n.reasoningContent.signature:typeof n?.reasoningContent?.reasoningText?.signature==`string`?n.reasoningContent.reasoningText.signature:void 0;t.write(`data: ${JSON.stringify({type:`content_block_start`,index:i,content_block:{type:`thinking`,thinking:``,...e?{signature:e}:{}}})}\n\n`)}else t.write(`data: ${JSON.stringify({type:`content_block_start`,index:i,content_block:{type:`text`,text:``}})}\n\n`)}else if(r.contentBlockDelta){let n=r.contentBlockDelta.delta,i=r.contentBlockDelta.contentBlockIndex??0;if(!e.has(i)){e.add(i);let r=n?.toolUse===void 0?`text`:`tool_use`;t.write(`data: ${JSON.stringify({type:`content_block_start`,index:i,content_block:r===`text`?{type:`text`,text:``}:{type:`tool_use`,id:``,name:``,input:{}}})}\n\n`)}if(n?.text!==void 0)t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`text_delta`,text:n.text}})}\n\n`);else if(n?.reasoningContent?.text!==void 0)t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`thinking_delta`,thinking:n.reasoningContent.text}})}\n\n`);else if(typeof n?.reasoningContent?.signature==`string`||typeof n?.reasoningContent?.reasoningText?.signature==`string`){let e=typeof n.reasoningContent.signature==`string`?n.reasoningContent.signature:n.reasoningContent.reasoningText.signature;t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`signature_delta`,signature:e}})}\n\n`)}else n?.reasoningContent?.redactedContent===void 0?n?.toolUse?.input!==void 0&&t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`input_json_delta`,partial_json:n.toolUse.input}})}\n\n`):t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`redacted_thinking_delta`,data:n.reasoningContent.redactedContent}})}\n\n`)}else if(r.contentBlockStop)t.write(`data: ${JSON.stringify({type:`content_block_stop`,index:r.contentBlockStop.contentBlockIndex??0})}\n\n`);else if(r.messageStop){let e=ii(r.messageStop.stopReason);t.write(`data: ${JSON.stringify({type:`message_delta`,delta:{stop_reason:e,stop_sequence:null}})}\n\n`),t.write(`data: ${JSON.stringify({type:`message_stop`})}\n\n`)}else if(r.metadata?.usage){let e=r.metadata.usage;t.write(`data: ${JSON.stringify({type:`message_delta`,usage:{input_tokens:e.inputTokens??0,output_tokens:e.outputTokens??0,cache_read_input_tokens:e.cacheReadInputTokens??0,cache_creation_input_tokens:e.cacheWriteInputTokens??0}})}\n\n`)}}t.end()}else{let e=new M(_),n=await u.send(e),r=(n.output?.message?.content||[]).map(e=>e.text===void 0?e.reasoningContent?.reasoningText?{type:`thinking`,thinking:e.reasoningContent.reasoningText.text||``,...typeof e.reasoningContent.reasoningText.signature==`string`?{signature:e.reasoningContent.reasoningText.signature}:{}}:e.reasoningContent?.redactedContent?{type:`redacted_thinking`,data:e.reasoningContent.redactedContent.data||``}:e.toolUse?{type:`tool_use`,id:e.toolUse.toolUseId,name:e.toolUse.name,input:e.toolUse.input}:{type:`text`,text:JSON.stringify(e)}:{type:`text`,text:e.text});t.json({id:ai(),type:`message`,role:`assistant`,model:a,content:r,stop_reason:ii(n.stopReason),stop_sequence:null,usage:{input_tokens:n.usage?.inputTokens??0,output_tokens:n.usage?.outputTokens??0,cache_read_input_tokens:n.usage?.cacheReadInputTokens??0,cache_creation_input_tokens:n.usage?.cacheWriteInputTokens??0}})}}catch(e){let n=e,r=e instanceof Error?e.message:String(e),i=n?.name??`UnknownError`,a=n?.$metadata?.httpStatusCode,o=n?.$metadata?.requestId;console.error(`Bedrock invoke error [${i} http=${a??`?`}] requestId=${o??`?`}];`,r);let s=i===`ThrottlingException`||a===429,c=r.includes(`expired`)||r.includes(`credentials`)?401:s?429:502;t.headersSent?(t.write(`data: ${JSON.stringify({type:`error`,error:{type:`server_error`,message:r}})}\n\n`),t.end()):t.status(c).json({error:`Bedrock invocation failed: ${r}`})}})}var pi=B(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!1;var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),mi=B((e=>{var t=pi();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*Math.max(t.minTimeout,1)*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),hi=B(((e,t)=>{t.exports=mi()})),gi=B(((e,t)=>{let n=hi(),r=[`Failed to fetch`,`NetworkError when attempting to fetch resource.`,`The Internet connection appears to be offline.`,`Network request failed`];var i=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name=`AbortError`,this.message=e}};let a=(e,t,n)=>{let r=n.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=r,e},o=e=>r.includes(e),s=(e,t)=>new Promise((r,s)=>{t={onFailedAttempt:()=>{},retries:10,...t};let c=n.operation(t);c.attempt(async n=>{try{r(await e(n))}catch(e){if(!(e instanceof Error)){s(TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));return}if(e instanceof i)c.stop(),s(e.originalError);else if(e instanceof TypeError&&!o(e.message))c.stop(),s(e);else{a(e,n,t);try{await t.onFailedAttempt(e)}catch(e){s(e);return}c.retry(e)||s(c.mainError())}}})});t.exports=s,t.exports.default=s,t.exports.AbortError=i})),_i=B(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=Object.prototype.toString,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=function(e){return typeof Array.isArray==`function`?Array.isArray(e):r.call(e)===`[object Array]`},s=function(e){if(!e||r.call(e)!==`[object Object]`)return!1;var t=n.call(e,`constructor`),i=e.constructor&&e.constructor.prototype&&n.call(e.constructor.prototype,`isPrototypeOf`);if(e.constructor&&!t&&!i)return!1;for(var a in e);return a===void 0||n.call(e,a)},c=function(e,t){i&&t.name===`__proto__`?i(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},l=function(e,t){if(t===`__proto__`){if(!n.call(e,t))return;if(a)return a(e,t).value}return e[t]};t.exports=function e(){var t,n,r,i,a,u,d=arguments[0],f=1,p=arguments.length,m=!1;for(typeof d==`boolean`&&(m=d,d=arguments[1]||{},f=2),(d==null||typeof d!=`object`&&typeof d!=`function`)&&(d={});f<p;++f)if(t=arguments[f],t!=null)for(n in t)r=l(d,n),i=l(t,n),d!==i&&(m&&i&&(s(i)||(a=o(i)))?(a?(a=!1,u=r&&o(r)?r:[]):u=r&&s(r)?r:{},c(d,{name:n,newValue:e(m,u,i)})):i!==void 0&&c(d,{name:n,newValue:i}));return d}})),vi=B(((e,t)=>{t.exports={name:`gaxios`,version:`7.1.4`,description:`A simple common HTTP client specifically for Google APIs and services.`,main:`build/cjs/src/index.js`,types:`build/cjs/src/index.d.ts`,files:[`build/`],exports:{".":{import:{types:`./build/esm/src/index.d.ts`,default:`./build/esm/src/index.js`},require:{types:`./build/cjs/src/index.d.ts`,default:`./build/cjs/src/index.js`}}},scripts:{lint:`gts check --no-inline-config`,test:`c8 mocha build/esm/test`,"presystem-test":`npm run compile`,"system-test":`mocha build/esm/system-test --timeout 80000`,compile:`tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs`,fix:`gts fix`,prepare:`npm run compile`,pretest:`npm run compile`,webpack:`webpack`,"prebrowser-test":`npm run compile`,"browser-test":`node build/browser-test/browser-test-runner.js`,docs:`jsdoc -c .jsdoc.js`,"docs-test":`linkinator docs`,"predocs-test":`npm run docs`,"samples-test":`cd samples/ && npm link ../ && npm test && cd ../`,prelint:`cd samples; npm link ../; npm install`,clean:`gts clean`},repository:{type:`git`,directory:`packages/gaxios`,url:`https://github.com/googleapis/google-cloud-node-core.git`},keywords:[`google`],engines:{node:`>=18`},author:`Google, LLC`,license:`Apache-2.0`,devDependencies:{"@babel/plugin-proposal-private-methods":`^7.18.6`,"@types/cors":`^2.8.6`,"@types/express":`^5.0.0`,"@types/extend":`^3.0.1`,"@types/mocha":`^10.0.10`,"@types/multiparty":`4.2.1`,"@types/mv":`^2.1.0`,"@types/ncp":`^2.0.8`,"@types/node":`^22.13.1`,"@types/sinon":`^17.0.3`,"@types/tmp":`^0.2.6`,assert:`^2.0.0`,browserify:`^17.0.0`,c8:`^10.1.3`,cors:`^2.8.5`,express:`^5.0.0`,gts:`^6.0.2`,"is-docker":`^3.0.0`,jsdoc:`^4.0.4`,"jsdoc-fresh":`^5.0.0`,"jsdoc-region-tag":`^4.0.0`,karma:`^6.0.0`,"karma-chrome-launcher":`^3.0.0`,"karma-coverage":`^2.0.0`,"karma-firefox-launcher":`^2.0.0`,"karma-mocha":`^2.0.0`,"karma-remap-coverage":`^0.1.5`,"karma-sourcemap-loader":`^0.4.0`,"karma-webpack":`^5.0.1`,linkinator:`^6.1.2`,mocha:`^11.1.0`,multiparty:`^4.2.1`,mv:`^2.1.1`,ncp:`^2.0.0`,nock:`^14.0.5`,"null-loader":`^4.0.1`,"pack-n-play":`^4.0.0`,puppeteer:`^24.0.0`,sinon:`^21.0.0`,"stream-browserify":`^3.0.0`,tmp:`0.2.5`,"ts-loader":`^9.5.2`,typescript:`5.8.3`,webpack:`^5.97.1`,"webpack-cli":`^6.0.1`},dependencies:{extend:`^3.0.2`,"https-proxy-agent":`^7.0.1`,"node-fetch":`^3.3.2`},homepage:`https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios`}})),yi=B(((e,t)=>{t.exports={pkg:vi()}})),bi=B((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.GaxiosError=e.GAXIOS_ERROR_SYMBOL=void 0,e.defaultErrorRedactor=a;let n=t(_i()),r=t(yi()).default.pkg;e.GAXIOS_ERROR_SYMBOL=Symbol.for(`${r.name}-gaxios-error`),e.GaxiosError=class t extends Error{config;response;code;status;error;[e.GAXIOS_ERROR_SYMBOL]=r.version;static[Symbol.hasInstance](n){return n&&typeof n==`object`&&e.GAXIOS_ERROR_SYMBOL in n&&n[e.GAXIOS_ERROR_SYMBOL]===r.version?!0:Function.prototype[Symbol.hasInstance].call(t,n)}constructor(e,t,r,a){if(super(e,{cause:a}),this.config=t,this.response=r,this.error=a instanceof Error?a:void 0,this.config=(0,n.default)(!0,{},t),this.response&&(this.response.config=(0,n.default)(!0,{},this.response.config)),this.response){try{this.response.data=i(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}a instanceof DOMException?this.code=a.name:a&&typeof a==`object`&&`code`in a&&(typeof a.code==`string`||typeof a.code==`number`)&&(this.code=a.code)}static extractAPIErrorFromResponse(e,t=`The request failed`){let n=t;if(typeof e.data==`string`&&(n=e.data),e.data&&typeof e.data==`object`&&`error`in e.data&&e.data.error&&!e.ok){if(typeof e.data.error==`string`)return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error==`object`){n=`message`in e.data.error&&typeof e.data.error.message==`string`?e.data.error.message:n;let t=`status`in e.data.error&&typeof e.data.error.status==`string`?e.data.error.status:e.statusText,r=`code`in e.data.error&&typeof e.data.error.code==`number`?e.data.error.code:e.status;if(`errors`in e.data.error&&Array.isArray(e.data.error.errors)){let i=[];for(let t of e.data.error.errors)typeof t==`object`&&`message`in t&&typeof t.message==`string`&&i.push(t.message);return Object.assign({message:i.join(`
|
|
91
|
+
`+u),be&&(u=_t(u)),S&&ke?O(u):u},t.setConfig=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};rt(e),Ce=!0,we=ce,Te=ue},t.clearConfig=function(){et=null,Ce=!1,we=null,Te=null,S=w,C=``},t.isValidAttribute=function(e,t,n){et||rt({});let r=$e(e),i=$e(t);return Dt(r,i,n)},t.addHook=function(e,t){typeof t==`function`&&gn(L,e)&&nn(L[e],t)},t.removeHook=function(e,t){if(gn(L,e)){if(t!==void 0){let n=en(L[e],t);return n===-1?void 0:rn(L[e],n,1)[0]}return tn(L[e])}},t.removeHooks=function(e){gn(L,e)&&(L[e]=[])},t.removeAllHooks=function(){L=nr()},t}ir(),new Promise(e=>{});let ar=[`youtube.com`,`youtube-nocookie.com`,`youtu.be`,`xt-ml.github.io`,`kherrick.github.io`];function or(e){e.map(e=>sr(e)).filter(Boolean)}or(ar);function sr(e){let t=e.trim();if(!t)return()=>!1;if(t.startsWith(`/`)&&(t.endsWith(`/`)||/\/[gimuy]*$/.test(t)))try{let e=t.lastIndexOf(`/`),n=t.slice(1,e),r=t.slice(e+1),i=new RegExp(n,r||`i`);return e=>i.test(e)}catch{}if(t.includes(`^`)||t.includes(`$`)||t.includes(`(`)&&t.includes(`)`))try{let e=new RegExp(t,`i`);return t=>e.test(t)}catch{}if(t.startsWith(`*.`)){let e=t.slice(2).toLowerCase();return t=>{let n=t.toLowerCase();return n===e||n.endsWith(`.`+e)}}let n=t.toLowerCase();return e=>{let t=e.toLowerCase();return t===n||t.endsWith(`.`+n)}}const cr=[],lr=[];new Set(cr.map(e=>e.toLowerCase().trim()));let ur=[...lr];function dr(e){e.map(e=>sr(e)).filter(Boolean)}dr(ur);const fr=[`'self'`,`blob:`,`data:`],pr=[`'self'`,`blob:`,`data:`],mr=[`'self'`,`'unsafe-inline'`,`https:`,`http:`],hr=[`'self'`,`blob:`,`data:`,`https:`,`http:`];[...fr],[...pr],[...mr],[...hr];function gr(){return`shadowclaw`}function _r(e={}){let t=e.includeTrustedTypes??!0,n=[`default-src 'self'`,`base-uri 'self'`,`frame-ancestors 'none'`,`frame-src 'self' https://www.youtube.com`,`object-src 'none'`,`img-src 'self' data: blob: https: http:`,`media-src 'self' data: blob: https: http:`,`font-src 'self' data: https://fonts.googleapis.com https://fonts.gstatic.com`,`style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://fonts.googleapis.com`,`script-src 'self' 'unsafe-inline'`,`worker-src 'self' blob:`,`connect-src 'self' https: wss: ws: data:`,`report-uri /__cspreport`];return t&&n.push(`trusted-types ${gr()} shadowclaw-sandbox dompurify default`,`require-trusted-types-for 'script'`),n.join(`; `)}function vr(e,t={}){e.setHeader(`Content-Security-Policy-Report-Only`,_r(t))}function yr(e){return!/\bfirefox\//i.test(e)}function br(){return(e,t,n)=>{vr(t,{includeTrustedTypes:yr(e.get(`user-agent`)??``)}),n()}}function xr(e,t){return(n,r,i)=>{let a=n.headers[`access-control-request-private-network`]===`true`,o=!!n.headers.origin;(a||o)&&(t&&a&&e.log(`VERBOSE`,`[PNA] Allowing Private Network Access`),r.setHeader(`Access-Control-Allow-Private-Network`,`true`)),i()}}function Sr(e,t,n,r){let i=t*2**e,a=Math.min(i,n),o=a*r*Math.random();return Math.max(0,a-o)}function Cr(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new DOMException(`Aborted`,`AbortError`));return}let i=setTimeout(n,e);if(t){let e=()=>{clearTimeout(i),r(t.reason??new DOMException(`Aborted`,`AbortError`))};t.addEventListener(`abort`,e,{once:!0});let a=n;n=(n=>{t.removeEventListener(`abort`,e),a(n)})}})}async function wr(e,t={}){let{maxRetries:n=3,baseDelayMs:r=1e3,maxDelayMs:i=3e4,jitterFactor:a=.5,shouldRetry:o=()=>!0,onRetry:s,signal:c}=t,l;for(let t=0;t<=n;t++){if(c?.aborted)throw c.reason??new DOMException(`Aborted`,`AbortError`);try{return await e()}catch(e){if(l=e,e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`)throw e;if(t>=n||!o(e,t+1))break;let u=Sr(t,r,i,a);s&&s(t+1,n,u,e),await Cr(u,c)}}throw l}const Tr=new Set([408,429,500,502,503,504]);function Er(e){if(e instanceof TypeError)return!0;if(typeof e?.status==`number`)return Tr.has(e.status);if(e instanceof Error){let t=e.message,n=t.match(/\b(4\d{2}|5\d{2})\b/);if(n)return Tr.has(Number(n[1]));if(/network|ECONNRESET|ECONNREFUSED|ETIMEDOUT|fetch failed|EAI_AGAIN|EAI_NONAME|getaddrinfo/i.test(t))return!0}return!1}const Dr=n.env.SHADOWCLAW_USER_AGENT||`ShadowClaw/1.0`;function Or(e){return Array.isArray(e)?e[0]||``:typeof e==`string`?e:``}function kr(e,t){let n=Number.parseInt(e??``,10);return!Number.isFinite(n)||n<=0?t:n}function Ar(e,t){let n=Number.parseInt(e??``,10);return!Number.isFinite(n)||n<0?t:n}function jr(e){return/^\/telegram\/(?:bot|file\/bot)[^/]+\//.test(e)}function Mr(e){try{let t=new URL(e);return t.hostname===`api.telegram.org`&&jr(t.pathname)&&(t.pathname=t.pathname.replace(/^\/telegram\/(?:bot|file\/bot)[^/]+\//,e=>e.includes(`/file/`)?`/telegram/file/bot[REDACTED]/`:`/telegram/bot[REDACTED]/`)),t.toString()}catch{return e.replace(/\/file\/bot[^/]+\//,`/file/bot[REDACTED]/`).replace(/\/bot[^/]+\//,`/bot[REDACTED]/`)}}function Nr(e){return e===`localhost`||e===`::1`||/^127\./.test(e)||/^10\./.test(e)||/^192\.168\./.test(e)||/^172\.(1[6-9]|2\d|3[01])\./.test(e)||/^169\.254\./.test(e)}async function Pr(e,t,n){if(!n||n<=0)return fetch(e,t);let r=new AbortController,i=t.signal,a=i?AbortSignal.any([i,r.signal]):r.signal,o=setTimeout(()=>{r.abort()},n);try{return await fetch(e,{...t,signal:a})}catch(e){throw e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`?Error(`Upstream request timed out after ${n}ms`):e}finally{clearTimeout(o)}}function Fr(e){return Array.isArray(e.tools)&&e.tools.length>0}function Ir(e){let t={...e};return delete t.tools,delete t.tool_choice,t}function Lr(e){return/does not support tools/i.test(e||``)}async function Rr(e,t,n){let{targetUrl:r,method:i,headers:a,body:o,verbose:s,maxRetries:c,requestTimeoutMs:l,forwardAuth:u,allowPrivate:d,fromServiceWorker:f}=n;s&&console.log(`[Proxy] Forwarding ${i} request to: ${Mr(r)}`);try{let e;try{e=new URL(r)}catch{t.status(400).json({error:`Invalid URL`});return}if(e.protocol!==`http:`&&e.protocol!==`https:`){t.status(400).json({error:`Unsupported URL scheme — only http and https are allowed`});return}if(Nr(e.hostname)&&!d&&!f){t.status(403).json({error:`Requests to private or internal addresses are blocked`});return}let n={...a};n[`User-Agent`]=Dr,delete n.host,delete n.origin,delete n.referer,u||(delete n.Authorization,delete n.authorization),delete n[`accept-encoding`],delete n[`content-length`],delete n.connection;let p=await wr(()=>Pr(e.toString(),{method:i,headers:n,body:i===`GET`||i===`HEAD`?void 0:o instanceof E?o:o?.toString()},l),{maxRetries:c??3,shouldRetry:Er,onRetry:(e,t,n,r)=>{s&&console.log(`[Proxy] Retry ${e}/${t} after ${n}ms due to: ${r.message||r}`)}});t.status(p.status),p.headers.forEach((e,n)=>{let r=n.toLowerCase();r===`content-encoding`||r===`transfer-encoding`||r===`content-length`||r===`connection`||t.setHeader(n,e)}),t.setHeader(`Access-Control-Allow-Origin`,`*`);let m=E.from(await p.arrayBuffer());t.send(m)}catch(e){console.error(`Proxy error:`,e),t.status(500).json({error:`Proxy request failed`})}}async function zr(e,t,n){let{targetUrl:r,headers:i,body:a,verbose:o,maxRetries:s,requestTimeoutMs:c,allowPrivate:l,fromServiceWorker:u}=n;o&&console.log(`[Proxy] Streaming POST request to: ${Mr(r)}`);try{let e;try{e=new URL(r)}catch{t.status(400).json({error:`Invalid URL`});return}if(e.protocol!==`http:`&&e.protocol!==`https:`){t.status(400).json({error:`Unsupported URL scheme — only http and https are allowed`});return}if(Nr(e.hostname)&&!l&&!u){t.status(403).json({error:`Requests to private or internal addresses are blocked`});return}let n={...i};delete n.host,delete n.origin,delete n.referer,delete n[`accept-encoding`],delete n[`content-length`],delete n.connection;let d=await wr(()=>Pr(e.toString(),{method:`POST`,headers:{...n,"User-Agent":Dr},body:a},c),{maxRetries:s??3,shouldRetry:Er,onRetry:(e,t,n,r)=>{o&&console.log(`[Proxy] Streaming Retry ${e}/${t} after ${n}ms due to: ${r.message||r}`)}});if(!d.ok){let e=await d.text();t.status(d.status),t.setHeader(`Access-Control-Allow-Origin`,`*`),t.json({error:e});return}if(t.status(200),t.setHeader(`Content-Type`,`text/event-stream`),t.setHeader(`Cache-Control`,`no-cache`),t.setHeader(`Connection`,`keep-alive`),t.setHeader(`Access-Control-Allow-Origin`,`*`),t.flushHeaders(),!d.body){t.end();return}let f=d.body.getReader();try{for(;;){let{done:e,value:n}=await f.read();if(e)break;t.write(E.from(n))}}finally{f.releaseLock()}t.end()}catch(e){console.error(`Streaming proxy error:`,e),t.headersSent?t.end():t.status(500).json({error:`Streaming proxy request failed`})}}function Br(e){let t=e.trim();if(!t)return{};let n=[],r=``,i=null;for(let e=0;e<t.length;e+=1){let a=t[e];if((a===`"`||a===`'`)&&t[e-1]!==`\\`){i===a?i=null:i||=a,r+=a;continue}if(a===`,`&&!i){r.trim()&&n.push(r.trim()),r=``;continue}r+=a}r.trim()&&n.push(r.trim());let a={};for(let e of n){let t=e.indexOf(`:`),n=e.indexOf(`=`),r=t>0?t:n;if(r<=0)continue;let i=e.slice(0,r).trim().replace(/^['"]|['"]$/g,``),o=e.slice(r+1).trim();if(i){if(o.startsWith(`"`)&&o.endsWith(`"`)||o.startsWith(`'`)&&o.endsWith(`'`)){o=o.slice(1,-1),a[i]=o.replace(/\\(["'\\])/g,`$1`);continue}if(o===`true`){a[i]=!0;continue}if(o===`false`){a[i]=!1;continue}if(o===`null`){a[i]=null;continue}if(/^-?\d+(\.\d+)?$/.test(o)){a[i]=Number(o);continue}a[i]=o}}return a}function Vr(e){let t=e.trim();if(!t)return{};let n=[],r=``,i=null,a=0;for(let e=0;e<t.length;e+=1){let o=t[e];if((o===`"`||o===`'`)&&t[e-1]!==`\\`){i===o?i=null:i||=o,r+=o;continue}if(!i){if(o===`(`||o===`{`||o===`[`)a+=1;else if((o===`)`||o===`}`||o===`]`)&&a>0)--a;else if(o===`,`&&a===0){r.trim()&&n.push(r.trim()),r=``;continue}}r+=o}r.trim()&&n.push(r.trim());let o={};for(let e of n){if(e=e.trim(),!e)continue;let t=e.indexOf(`=`),n=e.indexOf(`:`),r=t>0?t:n;if(r<=0)continue;let i=e.slice(0,r).trim().replace(/^['"]|['"]$/g,``),a=e.slice(r+1).trim();if(!i)continue;if(a.startsWith(`"`)&&a.endsWith(`"`)||a.startsWith(`'`)&&a.endsWith(`'`)){a=a.slice(1,-1),o[i]=a.replace(/\\(["'\\])/g,`$1`);continue}if(a===`true`){o[i]=!0;continue}if(a===`false`){o[i]=!1;continue}if(a===`null`){o[i]=null;continue}let s=Number(a);if(!Number.isNaN(s)&&a!==``){o[i]=s;continue}o[i]=a}return o}function Hr(e,t){return(n,r,i)=>{let a=Date.now(),o=Or(n.headers[`x-forwarded-for`])||n.socket?.remoteAddress||n.ip||`unknown`,s=Or(n.headers.origin)||`-`,c=Or(n.headers.host)||`-`,l=Or(n.headers[`access-control-request-method`])||`-`,u=Or(n.headers[`access-control-request-headers`])||`-`,d=Or(n.headers[`access-control-request-private-network`])||`-`,f=n.originalUrl.replace(/\/telegram\/(?:bot|file\/bot)[^/]+\//,e=>e.startsWith(`/telegram/file/`)?`/telegram/file/bot[REDACTED]/`:`/telegram/bot[REDACTED]/`);e.log(`DEFAULT`,`--> ${n.method} ${f} ip=${o} host=${c} origin=${s}`),n.method===`OPTIONS`&&e.log(`DEFAULT`,` [Preflight] request-method=${l} request-headers=${u} private-network=${d}`),r.on(`finish`,()=>{let i=Date.now()-a,o=r.statusCode,s=r.getHeader(`access-control-allow-origin`)||`-`,c=r.getHeader(`access-control-allow-private-network`)||`-`;e.log(`DEFAULT`,`<-- ${n.method} ${f} ${o} (${i}ms) allow-origin=${s} allow-private-network=${c}`),t&&(e.log(`VERBOSE`,` Query:`,n.query),n.body&&Object.keys(n.body).length>0&&e.log(`VERBOSE`,` Body keys:`,Object.keys(n.body)))}),i()}}const Ur=new Set([`chat`,`files`,`pages`,`tasks`,`settings`,`tools`,`channels`]);function Wr(e,t){let n=(e.method||`GET`).toUpperCase();if(n!==`GET`&&n!==`HEAD`)return!1;let r=String(e.headers[`sec-fetch-dest`]||``).toLowerCase();if(r&&r!==`document`)return!1;let i=String(e.headers[`sec-fetch-mode`]||``).toLowerCase(),a=String(e.headers[`sec-fetch-user`]||``).toLowerCase(),o=r===`document`||i===`navigate`||a===`?1`,s=String(e.headers.accept||``);if(!o&&!s.includes(`text/html`))return!1;let c=t.replace(/^\/+|\/+$/g,``);if(!c)return!1;let l=c.split(`/`,1)[0]||``;return Ur.has(l)}function Gr(e,t){e.use(D(/^(.+)\/index\.html$/,`$1/`)),e.use((e,n,r)=>{n.setHeader(`Access-Control-Allow-Origin`,`*`),n.setHeader(`Access-Control-Allow-Methods`,`GET, HEAD, OPTIONS`);let i=new URL(e.originalUrl,`http://localhost`).pathname;i.startsWith(`/assets/v86.9pfs/`)||i.startsWith(`/assets/v86.ext2/`)?n.setHeader(`Cache-Control`,`public, max-age=31536000, immutable`):n.setHeader(`Cache-Control`,`no-cache`);let a=o.join(t,e.url);h.stat(a,(s,c)=>{if(s||!c){if(Wr(e,i)){n.sendFile(o.join(t,`index.html`));return}let a=i.replace(/^\/[^/]+/,``);if(a){let e=o.join(t,a);try{if(h.existsSync(e)&&h.statSync(e).isFile()){n.sendFile(e);return}}catch{}}if(i.startsWith(`/files/main/`)){let e=o.resolve(`pages/main`,i.slice(12));h.stat(e,(t,i)=>{if(!t&&i&&i.isFile()){n.sendFile(e);return}r()});return}if(i.startsWith(`/static-main/`)){let e=o.resolve(`pages/main`,i.slice(13));h.stat(e,(t,i)=>{if(!t&&i&&i.isFile()){n.sendFile(e);return}r()});return}if(i.startsWith(`/pages/`)){let e=o.resolve(`pages`,i.slice(7));h.stat(e,(t,i)=>{if(!t&&i&&i.isFile()){n.sendFile(e);return}r()});return}r();return}if(c.isDirectory()){let e=o.join(a,`index.html`);h.access(e,h.constants.F_OK,t=>{t?r():n.sendFile(e)})}else n.sendFile(a)})}),e.use(m.static(t,{etag:!0}))}function Kr(e,t={}){let n=t.verbose??!1,r=t.allowPrivateProxy??!1;e.all(/^\/proxy(\/(.*))?$/,async(e,t)=>{let i=typeof e.query.url==`string`?e.query.url:void 0,a=(e.body&&typeof e.body.url==`string`?e.body.url:void 0)||i;if(!a){let t=e.params[1];if(t){a=t;let n={...e.query};if(delete n.url,Object.keys(n).length>0){let e=a.includes(`?`)?`&`:`?`;a+=e+new URLSearchParams(n).toString()}}}if(!a)return t.status(400).json({error:`Missing 'url' parameter`});let o=(e.body&&typeof e.body.method==`string`&&e.body.method||e.method).toUpperCase(),s=!!(e.body&&e.body.headers&&typeof e.body.headers==`object`),c=(s?e.body.headers:e.headers)||{},l;e.body&&typeof e.body.body==`string`&&(l=e.body.body);let u=s&&!!(c.Authorization||c.authorization);await Rr(e,t,{targetUrl:a,method:o,headers:c,body:l,verbose:n,forwardAuth:u,fromServiceWorker:s,allowPrivate:r})}),e.all(/^\/telegram\/((?:bot.*)|(?:file\/bot.*))$/,async(e,t)=>{t.setHeader(`Cache-Control`,`no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0`),t.setHeader(`Pragma`,`no-cache`),t.setHeader(`Expires`,`0`);let r=`https://api.telegram.org/${e.params[0]}${Object.keys(e.query).length>0?`?`+new URLSearchParams(e.query).toString():``}`,i=e.method.toUpperCase(),a=e.headers||{},o;if((a[`content-type`]||``).includes(`multipart/form-data`)){let t=[];for await(let n of e)t.push(n);o=E.concat(t)}else e.body&&typeof e.body.body==`string`?o=e.body.body:e.body&&typeof e.body==`object`&&Object.keys(e.body).length>0&&!(`url`in e.body)&&!(`method`in e.body)&&!(`headers`in e.body)&&(o=JSON.stringify(e.body));await Rr(e,t,{targetUrl:r,method:i,headers:a,body:o,verbose:n})}),e.all(/^\/git-proxy\/(.*)/,async(e,t)=>{let r=e.params[0],i=Object.keys(e.query).length>0?`?`+new URLSearchParams(e.query).toString():``,a=`https://`+r+i,o=[];for await(let t of e)o.push(t);let s=E.concat(o);await Rr(e,t,{targetUrl:a,method:e.method,headers:e.headers,body:s.length>0?s:void 0,verbose:n,forwardAuth:!0})})}const qr=r.BEDROCK_REGION||``,Jr=r.BEDROCK_PROFILE||``,Yr=new Map;function Xr(e){return{region:qr||Or(e.headers[`x-bedrock-region`])?.trim()||``,profile:Jr||Or(e.headers[`x-bedrock-profile`])?.trim()||``,authMode:Or(e.headers[`x-bedrock-auth-mode`])?.trim()||`provider_chain`}}function Zr(e,t){return t===`sso`?F({profile:e}):P({profile:e})}function Qr(e,t){if(/^[a-z]+\.anthropic\./.test(e))return e;let n=t.split(`-`)[0];if(!n)throw Error(`Bedrock region is not configured. Set BEDROCK_REGION or provide x-bedrock-region header.`);return`${n}.${e}`}function $r(e){if(e.type===`text`)return{text:e.text};if(e.type===`image`){let t=e.source.data;return{image:{format:e.source.media_type.split(`/`)[1],source:{bytes:E.from(t,`base64`)}}}}if(e.type===`tool_use`)return{toolUse:{toolUseId:e.id,name:e.name,input:e.input}};if(e.type===`tool_result`){let t=typeof e.content==`string`?[{text:e.content}]:Array.isArray(e.content)?e.content.map(e=>e.type===`text`?{text:e.text}:{text:JSON.stringify(e)}):[{text:JSON.stringify(e.content)}];return{toolResult:{toolUseId:e.tool_use_id,content:t}}}return e.type===`thinking`?typeof e.signature!=`string`||e.signature.length===0?void 0:{reasoningContent:{reasoningText:{text:e.thinking||``,signature:e.signature}}}:e.type===`redacted_thinking`?{reasoningContent:{redactedContent:{data:e.data||``}}}:{text:JSON.stringify(e)}}function ei(e){return!!(e&&typeof e==`object`&&e.cache_control)}function ti(e){let t=e?.ttl;return{cachePoint:{type:`default`,...t===`1h`||t===`5m`?{ttl:t}:{}}}}function ni(e=4){let t=e;return{take(){return t<=0?!1:(--t,!0)}}}function ri(e,t){let n=`(continue)`;if(!Array.isArray(e)||e.length===0)return[];let r=(e||[]).map(e=>{let n=Array.isArray(e.content)?e.content:[{type:`text`,text:typeof e.content==`string`?e.content:``}],r=Array.isArray(e.content)?e.content.map($r):[{text:typeof e.content==`string`?e.content:``}],i=[];return r.forEach((e,r)=>{if(e===void 0||e&&typeof e.text==`string`&&e.text.trim().length===0)return;i.push(e);let a=n[r];ei(a)&&t?.take()&&i.push(ti(a.cache_control))}),{role:e.role,content:i}}),i=r.filter(e=>e.content.length>0);if(i.length===0&&r.length>0){let e=r[r.length-1];return[{role:e.role===`assistant`?`user`:e.role,content:[{text:n}]}]}let a=[];for(let e of i){let t=a[a.length-1];if(t&&t.role===e.role){t.content.push(...e.content);continue}a.push(e)}return a.length>0&&a[0].role===`assistant`&&a.shift(),a.length===0?[{role:`user`,content:[{text:n}]}]:(a[a.length-1].role===`assistant`&&a.push({role:`user`,content:[{text:n}]}),a)}function ii(e){switch(e){case`tool_use`:return`tool_use`;case`max_tokens`:return`max_tokens`;case`stop_sequence`:return`stop_sequence`;default:return`end_turn`}}function ai(){return`msg_`+Math.random().toString(36).substring(2,10)}function oi(e){if(typeof e!=`string`)return;let t=e.trim().toLowerCase();if(t===`low`||t===`medium`||t===`high`||t===`xhigh`||t===`max`)return t;if(t===`minimal`||t===`none`)return`low`}function si(e,t){let n=typeof e==`number`&&Number.isFinite(e)?Math.max(1,e):0,r=n>0?n/(typeof t==`number`&&Number.isFinite(t)?Math.max(1,t):8192):.5;return r>=.95?`max`:r>=.85?`xhigh`:r>=.7?`high`:r>=.35?`medium`:`low`}function ci(e){if(typeof e!=`string`||e.trim().length===0)return;let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``);if(t.includes(`claude-sonnet-5`)||t.includes(`claude-opus-4-7`)||t.includes(`claude-opus-5`)||t.includes(`claude-opus-4-8`)||t.includes(`claude-mythos-5`))return!0;if(t.includes(`claude-sonnet-4-6`))return!1}function li(e,t){if(typeof e!=`string`||e.trim().length===0)return;let n=ci(e),r=ci(t)??n;typeof r==`boolean`&&Yr.set(e.toLowerCase(),r)}function ui(e,t){let n=e.toLowerCase(),r=t.toLowerCase();if(Yr.has(n))return Yr.get(n)===!0;if(Yr.has(r))return Yr.get(r)===!0;let i=ci(n);if(typeof i==`boolean`)return i;let a=ci(r);return typeof a==`boolean`&&a}function di(e,t,n){if(!e?.thinking)return;let r=e.thinking;if(!ui(t,n)||(typeof r?.type==`string`?r.type.toLowerCase():``)===`disabled`)return{thinking:r};let i=oi(e?.output_config?.effort),a=si(r?.budget_tokens,e?.max_tokens);return{thinking:{type:`adaptive`},output_config:{effort:i||a}}}function fi(e,t={}){e.get(`/bedrock-proxy/models`,async(e,t)=>{try{let n=Xr(e);if(!n.region||!n.profile)return t.status(400).json({error:`Bedrock is not configured. Set BEDROCK_REGION and BEDROCK_PROFILE environment variables or provide Bedrock fallback settings in the UI.`});let r=new O({region:n.region,credentials:Zr(n.profile,n.authMode)}),i=((await r.send(new k({byProvider:`Anthropic`}))).modelSummaries||[]).filter(e=>e.modelLifecycle?.status===`ACTIVE`).map(e=>(li(e.modelId,e.modelName),{id:e.modelId,name:e.modelName}));try{let e=((await r.send(new A({}))).inferenceProfileSummaries||[]).filter(e=>e.status===`ACTIVE`).filter(e=>e.inferenceProfileId?.includes(`anthropic`)||e.inferenceProfileName?.toLowerCase().includes(`anthropic`)).map(e=>({id:e.inferenceProfileId||``,name:`${e.inferenceProfileName||`Unnamed Profile`} (Profile)`})).map(e=>(li(e.id,e.name),e));i.push(...e)}catch(e){(e&&typeof e==`object`&&`name`in e?e.name:``)!==`AccessDeniedException`&&console.warn(`Failed to list Bedrock inference profiles:`,e instanceof Error?e.message:String(e))}t.json({models:i})}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Bedrock models discovery error:`,n),t.status(502).json({error:`Failed to list Bedrock models: ${n}`})}}),e.post(`/bedrock-proxy/invoke`,async(e,t)=>{try{let n=Xr(e);if(!n.region||!n.profile)return t.status(400).json({error:`Bedrock is not configured. Set BEDROCK_REGION and BEDROCK_PROFILE environment variables or provide Bedrock fallback settings in the UI.`});let r=e.body;if(!r||typeof r!=`object`)return t.status(400).json({error:`Missing request body`});let i=r.model;if(typeof i!=`string`||!i.startsWith(`anthropic.`)&&!/^[a-z]+\.anthropic\./.test(i))return t.status(400).json({error:`Invalid model ID: '${String(i||``)}'. Must be an Anthropic Bedrock model ID.`});let a=Qr(i,n.region),o=r.stream===!0,{model:s,stream:c,...l}=r,u=new j({region:n.region,credentials:Zr(n.profile,n.authMode),maxAttempts:3,retryMode:`adaptive`,requestHandler:{requestTimeout:6e4}}),d=ni(),f;if(l.tools&&l.tools.length>0){let e=[];for(let t of l.tools)e.push({toolSpec:{name:t.name,description:t.description,inputSchema:{json:t.input_schema}}}),ei(t)&&d.take()&&e.push(ti(t.cache_control));if(f={tools:e},l.tool_choice){let e=l.tool_choice;e.type===`tool`?f.toolChoice={tool:{name:e.name}}:e.type===`any`?f.toolChoice={any:{}}:f.toolChoice={auto:{}}}}let p=[];if(Array.isArray(l.system))for(let e of l.system){let t=typeof e?.text==`string`?e.text:``;t.trim().length!==0&&(p.push({text:t}),ei(e)&&d.take()&&p.push(ti(e.cache_control)))}else typeof l.system==`string`&&l.system.trim().length>0&&p.push({text:l.system});let m=p.length>0?p:void 0,h=ri(l.messages||[],d),g={};l.max_tokens&&(g.maxTokens=l.max_tokens),l.temperature!==void 0&&(g.temperature=l.temperature),l.top_p!==void 0&&(g.topP=l.top_p),l.stop_sequences&&(g.stopSequences=l.stop_sequences);let _={modelId:a,messages:h,system:m,inferenceConfig:Object.keys(g).length>0?g:void 0,toolConfig:f,additionalModelRequestFields:di(l,i,a)};if(o){let e=new N(_),n=await u.send(e);if(t.status(200),t.setHeader(`Content-Type`,`text/event-stream`),t.setHeader(`Cache-Control`,`no-cache`),t.setHeader(`Connection`,`keep-alive`),t.setHeader(`Access-Control-Allow-Origin`,`*`),t.flushHeaders(),t.write(`data: ${JSON.stringify({type:`message_start`,message:{id:ai(),type:`message`,role:`assistant`,model:a,content:[],usage:{input_tokens:0,output_tokens:0}}})}\n\n`),n.stream){let e=new Set;for await(let r of n.stream)if(r.contentBlockStart){let n=r.contentBlockStart.start,i=r.contentBlockStart.contentBlockIndex??0;if(e.add(i),n?.toolUse)t.write(`data: ${JSON.stringify({type:`content_block_start`,index:i,content_block:{type:`tool_use`,id:n.toolUse.toolUseId,name:n.toolUse.name,input:{}}})}\n\n`);else if(n?.reasoningContent!==void 0){let e=typeof n?.reasoningContent?.signature==`string`?n.reasoningContent.signature:typeof n?.reasoningContent?.reasoningText?.signature==`string`?n.reasoningContent.reasoningText.signature:void 0;t.write(`data: ${JSON.stringify({type:`content_block_start`,index:i,content_block:{type:`thinking`,thinking:``,...e?{signature:e}:{}}})}\n\n`)}else t.write(`data: ${JSON.stringify({type:`content_block_start`,index:i,content_block:{type:`text`,text:``}})}\n\n`)}else if(r.contentBlockDelta){let n=r.contentBlockDelta.delta,i=r.contentBlockDelta.contentBlockIndex??0;if(!e.has(i)){e.add(i);let r=n?.toolUse===void 0?`text`:`tool_use`;t.write(`data: ${JSON.stringify({type:`content_block_start`,index:i,content_block:r===`text`?{type:`text`,text:``}:{type:`tool_use`,id:``,name:``,input:{}}})}\n\n`)}if(n?.text!==void 0)t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`text_delta`,text:n.text}})}\n\n`);else if(n?.reasoningContent?.text!==void 0)t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`thinking_delta`,thinking:n.reasoningContent.text}})}\n\n`);else if(typeof n?.reasoningContent?.signature==`string`||typeof n?.reasoningContent?.reasoningText?.signature==`string`){let e=typeof n.reasoningContent.signature==`string`?n.reasoningContent.signature:n.reasoningContent.reasoningText.signature;t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`signature_delta`,signature:e}})}\n\n`)}else n?.reasoningContent?.redactedContent===void 0?n?.toolUse?.input!==void 0&&t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`input_json_delta`,partial_json:n.toolUse.input}})}\n\n`):t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`redacted_thinking_delta`,data:n.reasoningContent.redactedContent}})}\n\n`)}else if(r.contentBlockStop)t.write(`data: ${JSON.stringify({type:`content_block_stop`,index:r.contentBlockStop.contentBlockIndex??0})}\n\n`);else if(r.messageStop){let e=ii(r.messageStop.stopReason);t.write(`data: ${JSON.stringify({type:`message_delta`,delta:{stop_reason:e,stop_sequence:null}})}\n\n`),t.write(`data: ${JSON.stringify({type:`message_stop`})}\n\n`)}else if(r.metadata?.usage){let e=r.metadata.usage;t.write(`data: ${JSON.stringify({type:`message_delta`,usage:{input_tokens:e.inputTokens??0,output_tokens:e.outputTokens??0,cache_read_input_tokens:e.cacheReadInputTokens??0,cache_creation_input_tokens:e.cacheWriteInputTokens??0}})}\n\n`)}}t.end()}else{let e=new M(_),n=await u.send(e),r=(n.output?.message?.content||[]).map(e=>e.text===void 0?e.reasoningContent?.reasoningText?{type:`thinking`,thinking:e.reasoningContent.reasoningText.text||``,...typeof e.reasoningContent.reasoningText.signature==`string`?{signature:e.reasoningContent.reasoningText.signature}:{}}:e.reasoningContent?.redactedContent?{type:`redacted_thinking`,data:e.reasoningContent.redactedContent.data||``}:e.toolUse?{type:`tool_use`,id:e.toolUse.toolUseId,name:e.toolUse.name,input:e.toolUse.input}:{type:`text`,text:JSON.stringify(e)}:{type:`text`,text:e.text});t.json({id:ai(),type:`message`,role:`assistant`,model:a,content:r,stop_reason:ii(n.stopReason),stop_sequence:null,usage:{input_tokens:n.usage?.inputTokens??0,output_tokens:n.usage?.outputTokens??0,cache_read_input_tokens:n.usage?.cacheReadInputTokens??0,cache_creation_input_tokens:n.usage?.cacheWriteInputTokens??0}})}}catch(e){let n=e,r=e instanceof Error?e.message:String(e),i=n?.name??`UnknownError`,a=n?.$metadata?.httpStatusCode,o=n?.$metadata?.requestId;console.error(`Bedrock invoke error [${i} http=${a??`?`}] requestId=${o??`?`}];`,r);let s=i===`ThrottlingException`||a===429,c=r.includes(`expired`)||r.includes(`credentials`)?401:s?429:502;t.headersSent?(t.write(`data: ${JSON.stringify({type:`error`,error:{type:`server_error`,message:r}})}\n\n`),t.end()):t.status(c).json({error:`Bedrock invocation failed: ${r}`})}})}var pi=B(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!1;var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),mi=B((e=>{var t=pi();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*Math.max(t.minTimeout,1)*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),hi=B(((e,t)=>{t.exports=mi()})),gi=B(((e,t)=>{let n=hi(),r=[`Failed to fetch`,`NetworkError when attempting to fetch resource.`,`The Internet connection appears to be offline.`,`Network request failed`];var i=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name=`AbortError`,this.message=e}};let a=(e,t,n)=>{let r=n.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=r,e},o=e=>r.includes(e),s=(e,t)=>new Promise((r,s)=>{t={onFailedAttempt:()=>{},retries:10,...t};let c=n.operation(t);c.attempt(async n=>{try{r(await e(n))}catch(e){if(!(e instanceof Error)){s(TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));return}if(e instanceof i)c.stop(),s(e.originalError);else if(e instanceof TypeError&&!o(e.message))c.stop(),s(e);else{a(e,n,t);try{await t.onFailedAttempt(e)}catch(e){s(e);return}c.retry(e)||s(c.mainError())}}})});t.exports=s,t.exports.default=s,t.exports.AbortError=i})),_i=B(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=Object.prototype.toString,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=function(e){return typeof Array.isArray==`function`?Array.isArray(e):r.call(e)===`[object Array]`},s=function(e){if(!e||r.call(e)!==`[object Object]`)return!1;var t=n.call(e,`constructor`),i=e.constructor&&e.constructor.prototype&&n.call(e.constructor.prototype,`isPrototypeOf`);if(e.constructor&&!t&&!i)return!1;for(var a in e);return a===void 0||n.call(e,a)},c=function(e,t){i&&t.name===`__proto__`?i(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},l=function(e,t){if(t===`__proto__`){if(!n.call(e,t))return;if(a)return a(e,t).value}return e[t]};t.exports=function e(){var t,n,r,i,a,u,d=arguments[0],f=1,p=arguments.length,m=!1;for(typeof d==`boolean`&&(m=d,d=arguments[1]||{},f=2),(d==null||typeof d!=`object`&&typeof d!=`function`)&&(d={});f<p;++f)if(t=arguments[f],t!=null)for(n in t)r=l(d,n),i=l(t,n),d!==i&&(m&&i&&(s(i)||(a=o(i)))?(a?(a=!1,u=r&&o(r)?r:[]):u=r&&s(r)?r:{},c(d,{name:n,newValue:e(m,u,i)})):i!==void 0&&c(d,{name:n,newValue:i}));return d}})),vi=B(((e,t)=>{t.exports={name:`gaxios`,version:`7.1.4`,description:`A simple common HTTP client specifically for Google APIs and services.`,main:`build/cjs/src/index.js`,types:`build/cjs/src/index.d.ts`,files:[`build/`],exports:{".":{import:{types:`./build/esm/src/index.d.ts`,default:`./build/esm/src/index.js`},require:{types:`./build/cjs/src/index.d.ts`,default:`./build/cjs/src/index.js`}}},scripts:{lint:`gts check --no-inline-config`,test:`c8 mocha build/esm/test`,"presystem-test":`npm run compile`,"system-test":`mocha build/esm/system-test --timeout 80000`,compile:`tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs`,fix:`gts fix`,prepare:`npm run compile`,pretest:`npm run compile`,webpack:`webpack`,"prebrowser-test":`npm run compile`,"browser-test":`node build/browser-test/browser-test-runner.js`,docs:`jsdoc -c .jsdoc.js`,"docs-test":`linkinator docs`,"predocs-test":`npm run docs`,"samples-test":`cd samples/ && npm link ../ && npm test && cd ../`,prelint:`cd samples; npm link ../; npm install`,clean:`gts clean`},repository:{type:`git`,directory:`packages/gaxios`,url:`https://github.com/googleapis/google-cloud-node-core.git`},keywords:[`google`],engines:{node:`>=18`},author:`Google, LLC`,license:`Apache-2.0`,devDependencies:{"@babel/plugin-proposal-private-methods":`^7.18.6`,"@types/cors":`^2.8.6`,"@types/express":`^5.0.0`,"@types/extend":`^3.0.1`,"@types/mocha":`^10.0.10`,"@types/multiparty":`4.2.1`,"@types/mv":`^2.1.0`,"@types/ncp":`^2.0.8`,"@types/node":`^22.13.1`,"@types/sinon":`^17.0.3`,"@types/tmp":`^0.2.6`,assert:`^2.0.0`,browserify:`^17.0.0`,c8:`^10.1.3`,cors:`^2.8.5`,express:`^5.0.0`,gts:`^6.0.2`,"is-docker":`^3.0.0`,jsdoc:`^4.0.4`,"jsdoc-fresh":`^5.0.0`,"jsdoc-region-tag":`^4.0.0`,karma:`^6.0.0`,"karma-chrome-launcher":`^3.0.0`,"karma-coverage":`^2.0.0`,"karma-firefox-launcher":`^2.0.0`,"karma-mocha":`^2.0.0`,"karma-remap-coverage":`^0.1.5`,"karma-sourcemap-loader":`^0.4.0`,"karma-webpack":`^5.0.1`,linkinator:`^6.1.2`,mocha:`^11.1.0`,multiparty:`^4.2.1`,mv:`^2.1.1`,ncp:`^2.0.0`,nock:`^14.0.5`,"null-loader":`^4.0.1`,"pack-n-play":`^4.0.0`,puppeteer:`^24.0.0`,sinon:`^21.0.0`,"stream-browserify":`^3.0.0`,tmp:`0.2.5`,"ts-loader":`^9.5.2`,typescript:`5.8.3`,webpack:`^5.97.1`,"webpack-cli":`^6.0.1`},dependencies:{extend:`^3.0.2`,"https-proxy-agent":`^7.0.1`,"node-fetch":`^3.3.2`},homepage:`https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios`}})),yi=B(((e,t)=>{t.exports={pkg:vi()}})),bi=B((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.GaxiosError=e.GAXIOS_ERROR_SYMBOL=void 0,e.defaultErrorRedactor=a;let n=t(_i()),r=t(yi()).default.pkg;e.GAXIOS_ERROR_SYMBOL=Symbol.for(`${r.name}-gaxios-error`),e.GaxiosError=class t extends Error{config;response;code;status;error;[e.GAXIOS_ERROR_SYMBOL]=r.version;static[Symbol.hasInstance](n){return n&&typeof n==`object`&&e.GAXIOS_ERROR_SYMBOL in n&&n[e.GAXIOS_ERROR_SYMBOL]===r.version?!0:Function.prototype[Symbol.hasInstance].call(t,n)}constructor(e,t,r,a){if(super(e,{cause:a}),this.config=t,this.response=r,this.error=a instanceof Error?a:void 0,this.config=(0,n.default)(!0,{},t),this.response&&(this.response.config=(0,n.default)(!0,{},this.response.config)),this.response){try{this.response.data=i(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}a instanceof DOMException?this.code=a.name:a&&typeof a==`object`&&`code`in a&&(typeof a.code==`string`||typeof a.code==`number`)&&(this.code=a.code)}static extractAPIErrorFromResponse(e,t=`The request failed`){let n=t;if(typeof e.data==`string`&&(n=e.data),e.data&&typeof e.data==`object`&&`error`in e.data&&e.data.error&&!e.ok){if(typeof e.data.error==`string`)return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error==`object`){n=`message`in e.data.error&&typeof e.data.error.message==`string`?e.data.error.message:n;let t=`status`in e.data.error&&typeof e.data.error.status==`string`?e.data.error.status:e.statusText,r=`code`in e.data.error&&typeof e.data.error.code==`number`?e.data.error.code:e.status;if(`errors`in e.data.error&&Array.isArray(e.data.error.errors)){let i=[];for(let t of e.data.error.errors)typeof t==`object`&&`message`in t&&typeof t.message==`string`&&i.push(t.message);return Object.assign({message:i.join(`
|
|
92
92
|
`)||n,code:r,status:t},e.data.error)}return Object.assign({message:n,code:r,status:t},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}};function i(e,t){switch(e){case`stream`:return t;case`json`:return JSON.parse(JSON.stringify(t));case`arraybuffer`:return JSON.parse(E.from(t).toString(`utf8`));case`blob`:return JSON.parse(t.text());default:return t}}function a(e){let t="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(e){e&&e.forEach((n,r)=>{(/^authentication$/i.test(r)||/^authorization$/i.test(r)||/secret/i.test(r))&&e.set(r,t)})}function r(e,n){if(typeof e==`object`&&e&&typeof e[n]==`string`){let r=e[n];(/grant_type=/i.test(r)||/assertion=/i.test(r)||/secret/i.test(r))&&(e[n]=t)}}function i(e){!e||typeof e!=`object`||(e instanceof FormData||e instanceof URLSearchParams||`forEach`in e&&`set`in e?e.forEach((n,r)=>{([`grant_type`,`assertion`].includes(r)||/secret/.test(r))&&e.set(r,t)}):(`grant_type`in e&&(e.grant_type=t),`assertion`in e&&(e.assertion=t),`client_secret`in e&&(e.client_secret=t)))}return e.config&&(n(e.config.headers),r(e.config,`data`),i(e.config.data),r(e.config,`body`),i(e.config.body),e.config.url.searchParams.has(`token`)&&e.config.url.searchParams.set(`token`,t),e.config.url.searchParams.has(`client_secret`)&&e.config.url.searchParams.set(`client_secret`,t)),e.response&&(a({config:e.response.config}),n(e.response.headers),e.response.bodyUsed&&(r(e.response,`data`),i(e.response.data))),e}})),xi=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRetryConfig=t;async function t(e){let t=r(e);if(!e||!e.config||!t&&!e.config.retry)return{shouldRetry:!1};if(t||={},t.currentRetryAttempt=t.currentRetryAttempt||0,t.retry=t.retry===void 0||t.retry===null?3:t.retry,t.httpMethodsToRetry=t.httpMethodsToRetry||[`GET`,`HEAD`,`PUT`,`OPTIONS`,`DELETE`],t.noResponseRetries=t.noResponseRetries===void 0||t.noResponseRetries===null?2:t.noResponseRetries,t.retryDelayMultiplier=t.retryDelayMultiplier?t.retryDelayMultiplier:2,t.timeOfFirstRequest=t.timeOfFirstRequest?t.timeOfFirstRequest:Date.now(),t.totalTimeout=t.totalTimeout?t.totalTimeout:2**53-1,t.maxRetryDelay=t.maxRetryDelay?t.maxRetryDelay:2**53-1,t.statusCodesToRetry=t.statusCodesToRetry||[[100,199],[408,408],[429,429],[500,599]],e.config.retryConfig=t,!await(t.shouldRetry||n)(e))return{shouldRetry:!1,config:e.config};let a=i(t);e.config.retryConfig.currentRetryAttempt+=1;let o=t.retryBackoff?t.retryBackoff(e,a):new Promise(e=>{setTimeout(e,a)});return t.onRetryAttempt&&await t.onRetryAttempt(e),await o,{shouldRetry:!0,config:e.config}}function n(e){let t=r(e);if(e.config.signal?.aborted&&e.code!==`TimeoutError`||e.code===`AbortError`||!t||t.retry===0||!e.response&&(t.currentRetryAttempt||0)>=t.noResponseRetries||!t.httpMethodsToRetry||!t.httpMethodsToRetry.includes(e.config.method?.toUpperCase()||`GET`))return!1;if(e.response&&e.response.status){let n=!1;for(let[r,i]of t.statusCodesToRetry){let t=e.response.status;if(t>=r&&t<=i){n=!0;break}}if(!n)return!1}return t.currentRetryAttempt=t.currentRetryAttempt||0,!(t.currentRetryAttempt>=t.retry)}function r(e){if(e&&e.config&&e.config.retryConfig)return e.config.retryConfig}function i(e){let t=(e.currentRetryAttempt?0:e.retryDelay??100)+(e.retryDelayMultiplier**+e.currentRetryAttempt-1)/2*1e3,n=e.totalTimeout-(Date.now()-e.timeOfFirstRequest);return Math.min(t,n,e.maxRetryDelay)}})),Si=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.GaxiosInterceptorManager=void 0,e.GaxiosInterceptorManager=class extends Set{}})),Ci=B(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),wi=B(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=Ci(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){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 n.enable(n.load()),n}t.exports=n})),Ti=B(((e,t)=>{e.formatArgs=i,e.save=a,e.load=o,e.useColors=r,e.storage=s(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!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`."))}})(),e.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`.split(`.`);function r(){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 e;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&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function i(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function a(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function o(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&n!==void 0&&`env`in n&&(t=n.env.DEBUG),t}function s(){try{return localStorage}catch{}}t.exports=wi()(e);let{formatters:c}=t.exports;c.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),Ei=B(((e,t)=>{t.exports=(e,t=n.argv)=>{let r=e.startsWith(`-`)?``:e.length===1?`-`:`--`,i=t.indexOf(r+e),a=t.indexOf(`--`);return i!==-1&&(a===-1||i<a)}})),Di=B(((e,t)=>{let r=V(`os`),i=V(`tty`),a=Ei(),{env:o}=n,s;a(`no-color`)||a(`no-colors`)||a(`color=false`)||a(`color=never`)?s=0:(a(`color`)||a(`colors`)||a(`color=true`)||a(`color=always`))&&(s=1),`FORCE_COLOR`in o&&(s=o.FORCE_COLOR===`true`?1:o.FORCE_COLOR===`false`?0:o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function c(e){return e!==0&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function l(e,t){if(s===0)return 0;if(a(`color=16m`)||a(`color=full`)||a(`color=truecolor`))return 3;if(a(`color=256`))return 2;if(e&&!t&&s===void 0)return 0;let i=s||0;if(o.TERM===`dumb`)return i;if(n.platform===`win32`){let e=r.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in o)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in o)||o.CI_NAME===`codeship`?1:i;if(`TEAMCITY_VERSION`in o)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION);if(o.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in o){let e=parseInt((o.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(o.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||`COLORTERM`in o?1:i}function u(e){return c(l(e,e&&e.isTTY))}t.exports={supportsColor:u,stdout:c(l(!0,i.isatty(1))),stderr:c(l(!0,i.isatty(2)))}})),Oi=B(((e,t)=>{let r=V(`tty`),i=V(`util`);e.init=d,e.log=c,e.formatArgs=o,e.save=l,e.load=u,e.useColors=a,e.destroy=i.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=Di();t&&(t.stderr||t).level>=2&&(e.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{}e.inspectOpts=Object.keys(n.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let r=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),i=n.env[t];return i=/^(yes|on|true|enabled)$/i.test(i)?!0:/^(no|off|false|disabled)$/i.test(i)?!1:i===`null`?null:Number(i),e[r]=i,e},{});function a(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:r.isatty(n.stderr.fd)}function o(e){let{namespace:n,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${n} \u001B[0m`;e[0]=a+e[0].split(`
|
|
93
93
|
`).join(`
|
|
94
94
|
`+a),e.push(i+`m+`+t.exports.humanize(this.diff)+`\x1B[0m`)}else e[0]=s()+n+` `+e[0]}function s(){return e.inspectOpts.hideDate?``:new Date().toISOString()+` `}function c(...t){return n.stderr.write(i.formatWithOptions(e.inspectOpts,...t)+`
|
|
@@ -968,7 +968,7 @@ Invalid`)}},FromEmailAddress:`invalid@invalid`,Destination:{ToAddresses:[`invali
|
|
|
968
968
|
<body>
|
|
969
969
|
<p>OAuth authorization complete. You can close this window.</p>
|
|
970
970
|
</body>
|
|
971
|
-
</html>`)}),e.get(`/oauth/session/:state`,(e,t)=>{let n=typeof e.params.state==`string`?e.params.state.trim():``;if(!n){t.status(400).json({error:`Missing state`});return}let r=s(n);if(!r){t.status(404).json({error:`OAuth session not found`});return}t.json({providerId:r.providerId,status:r.status,expiresAt:r.expiresAt,error:r.authorizationError,errorDescription:r.authorizationErrorDescription})}),e.post(`/oauth/token`,async(e,t)=>{o();let n=typeof e.body?.state==`string`?e.body.state.trim():``;if(!n){t.status(400).json({error:`Missing required state`});return}let i=s(n);if(!i){t.status(400).json({error:`Invalid or expired OAuth state`});return}if(i.status!==`authorized`||!i.authorizationCode){t.status(400).json({error:`OAuth callback not completed for this state`});return}let c=Je(i.providerId);if(!c){a.delete(n),t.status(400).json({error:`Unsupported OAuth provider`});return}let l=new URLSearchParams;l.set(`grant_type`,`authorization_code`),l.set(`code`,i.authorizationCode),l.set(`client_id`,i.clientId),l.set(`redirect_uri`,i.redirectUri),i.clientSecret&&(c.clientAuthMethod||`request_body`)!==`basic_header`&&l.set(`client_secret`,i.clientSecret),i.codeVerifier&&l.set(`code_verifier`,i.codeVerifier);try{let e=await r(i.tokenUrl,{method:`POST`,headers:Jk(c.clientAuthMethod,i.clientId,i.clientSecret),body:l.toString()}),o=await e.text(),s={};try{s=o?JSON.parse(o):{}}catch{s={}}if(!e.ok){a.delete(n),t.status(502).json({error:`OAuth token exchange failed`,status:e.status,upstreamError:s.error||s.error_description||`unknown_error`});return}let u=typeof s.access_token==`string`?s.access_token:``;if(!u){a.delete(n),t.status(502).json({error:`OAuth token exchange returned no access_token`});return}a.delete(n),t.json({providerId:i.providerId,accessToken:u,tokenType:typeof s.token_type==`string`?s.token_type:`Bearer`,refreshToken:typeof s.refresh_token==`string`?s.refresh_token:void 0,expiresIn:typeof s.expires_in==`number`?s.expires_in:void 0,scope:typeof s.scope==`string`?s.scope:void 0})}catch{a.delete(n),t.status(502).json({error:`OAuth token exchange network error`})}}),e.post(`/oauth/refresh`,async(e,t)=>{let n=e.body||{};if(!n.providerId||typeof n.providerId!=`string`){t.status(400).json({error:`Missing required providerId`});return}let i=Je(n.providerId);if(!i){t.status(400).json({error:`Unsupported OAuth provider`,providerId:n.providerId});return}let a=n.providerId===`custom_mcp`&&Wk(n.tokenUrl)?n.tokenUrl:i.tokenUrl;if(!n.clientId||typeof n.clientId!=`string`){t.status(400).json({error:`Missing required clientId`});return}if(!n.refreshToken||typeof n.refreshToken!=`string`){t.status(400).json({error:`Missing required refreshToken`});return}let o=Kk(n.scope);if(!qk(i.defaultScopes,o)){t.status(400).json({error:`Requested scopes are not allowed for this provider`});return}let s=new URLSearchParams;if(s.set(`grant_type`,`refresh_token`),s.set(`refresh_token`,n.refreshToken),s.set(`client_id`,n.clientId),n.clientSecret&&(i.clientAuthMethod||`request_body`)!==`basic_header`&&s.set(`client_secret`,n.clientSecret),o.length>0){let e=i.scopeSeparator===`comma`?`,`:` `;s.set(`scope`,o.join(e))}try{let e=await r(a,{method:`POST`,headers:Jk(i.clientAuthMethod,n.clientId,n.clientSecret),body:s.toString()}),o=await e.text(),c={};try{c=o?JSON.parse(o):{}}catch{c={}}if(!e.ok){t.status(502).json({error:`OAuth refresh failed`,status:e.status,upstreamError:c.error||c.error_description||`unknown_error`});return}let l=typeof c.access_token==`string`?c.access_token:``;if(!l){t.status(502).json({error:`OAuth refresh returned no access_token`});return}t.json({providerId:i.id,accessToken:l,tokenType:typeof c.token_type==`string`?c.token_type:`Bearer`,refreshToken:typeof c.refresh_token==`string`?c.refresh_token:void 0,expiresIn:typeof c.expires_in==`number`?c.expires_in:void 0,scope:typeof c.scope==`string`?c.scope:void 0})}catch{t.status(502).json({error:`OAuth refresh network error`})}})}function Zk(e){if(!e||typeof e!=`string`)return!1;let t=o.normalize(e).replace(/^(\.\.[\/\\])+/,``);return!(o.isAbsolute(e)||e.startsWith(`..`)||t!==e)}function Qk(e){let t=e.headers.host||`127.0.0.1`,n=e.headers.origin,r=e.headers.referer;if(n)try{let e=new l(n);if(e.host===t||e.hostname===`127.0.0.1`||e.hostname===`localhost`)return!0}catch{}if(r)try{let e=new l(r);if(e.host===t||e.hostname===`127.0.0.1`||e.hostname===`localhost`)return!0}catch{}let i=e.headers[`sec-fetch-site`];return i===`same-origin`||i===`same-site`}function $k(e,t){let{backupsDir:n}=t,r=t.token||gt(),i=(e,t,n)=>{let i=e.headers.host||`127.0.0.1`,a=new l(e.url,`http://${i}`).searchParams.get(`token`),o=e.headers[`x-control-token`],s=e.headers.authorization,c=s&&s.startsWith(`Bearer `)?s.slice(7).trim():null,u=a||o||c;if(!(u?u===r:Qk(e))){t.status(401).json({error:`Unauthorized: Invalid control token`});return}n()};e.post(`/api/backup/upload`,i,(e,t)=>{let{clientId:r,backupId:i,path:a,content:s,encoding:c}=e.body||{};if(!r||!i||!a){t.status(400).json({error:`clientId, backupId, and path are required`});return}if(!Zk(a)){t.status(400).json({error:`Invalid path: ${a}`});return}let l=o.resolve(n,r,i),u=o.resolve(l,a);if(!u.startsWith(l+o.sep)&&u!==l){t.status(400).json({error:`Invalid path: ${a}`});return}try{let e=o.dirname(u);h.existsSync(e)||h.mkdirSync(e,{recursive:!0});let n=c===`base64`?E.from(s||``,`base64`):E.from(s||``,`utf-8`);h.writeFileSync(u,n),t.json({success:!0,path:a,bytesWritten:n.length})}catch(e){t.status(500).json({error:`Failed to write file: ${e.message}`})}}),e.post(`/api/backup/complete`,i,(e,t)=>{let{clientId:n,backupId:r,fileCount:i,totalBytes:a,manifest:o}=e.body||{};if(!n||!r){t.status(400).json({error:`clientId and backupId are required`});return}try{let e=_t({id:r,clientId:n,fileCount:Number(i)||0,totalBytes:Number(a)||0,manifest:o});t.json({success:!0,backupId:e.id,clientId:e.clientId,timestamp:e.timestamp,fileCount:e.fileCount,totalBytes:e.totalBytes})}catch(e){t.status(500).json({error:`Failed to complete backup: ${e.message}`})}}),e.get(`/api/backup/list`,i,(e,t)=>{let n=vt(e.query.clientId||void 0);t.json({backups:n})}),e.delete(`/api/backup/:id`,i,(e,t)=>{let r=Array.isArray(e.params.id)?e.params.id[0]:e.params.id,i=e.query.clientId||e.body?.clientId;if(!r){t.status(400).json({error:`Backup id is required`});return}try{if(i){let e=o.resolve(n,i,r);h.existsSync(e)&&h.rmSync(e,{recursive:!0,force:!0})}yt(r,i),t.json({success:!0,deleted:r})}catch(e){t.status(500).json({error:`Failed to delete backup: ${e.message}`})}})}function eA(e){let t=m(),n=Nt(e.verbose),{verbose:r}=e;t.use(Hr(n,r)),t.use(xr(n,r)),t.use(Ft(e,n,r)),t.use(br()),t.use(p({filter(e,t){return t.getHeader(`Content-Type`)!==`text/event-stream`&&p.filter(e,t)}})),t.use(m.json({limit:`1000mb`})),h.existsSync(e.databaseDir)||h.mkdirSync(e.databaseDir,{recursive:!0}),Xe(o.join(e.databaseDir,`push-subscriptions.db`)),ot(o.join(e.databaseDir,`clients.db`)),St(o.join(e.databaseDir,`scheduled-tasks.db`)),Ik(t,{verbose:r,allowPrivateProxy:e.allowPrivateProxy}),Xk(t),Bk(t,{logsDir:o.resolve(e.databaseDir,`..`,`.cache`,`logs`)}),$k(t,{backupsDir:o.resolve(e.databaseDir,`..`,`.cache`,`backups`),token:e.controlToken}),Vk(t,{logsDir:o.resolve(e.databaseDir,`..`,`.cache`,`logs`),logger:n}),it(t),kt(t);let i=new Mt({getEnabledTasks:Dt,updateLastRun:Ot,broadcastTaskTrigger:e=>rt({type:`scheduled-task`,taskId:e.id,groupId:e.groupId,prompt:e.prompt,taskType:e.type,tools:e.tools,channel:e.channel})});return Gr(t,e.rootPath),t.use((e,t,n)=>{e.method===`GET`&&e.headers.accept?.includes(`text/html`)?t.redirect(e.baseUrl||`/`):n()}),{app:t,scheduler:i}}function tA(e){return e&&e.__esModule?e.default:e}var nA={host:`::`,port:9e3,expire_timeout:5e3,alive_timeout:9e4,key:`peerjs`,path:`/`,concurrent_limit:5e3,allow_discovery:!1,proxied:!1,cleanup_out_msgs:1e3,corsOptions:{origin:!0}},rA=class{lastReadAt=new Date().getTime();messages=[];getLastReadAt(){return this.lastReadAt}addMessage(e){this.messages.push(e)}readMessage(){if(this.messages.length>0)return this.lastReadAt=new Date().getTime(),this.messages.shift()}getMessages(){return this.messages}},iA=class{clients=new Map;messageQueues=new Map;getClientsIds(){return[...this.clients.keys()]}getClientById(e){return this.clients.get(e)}getClientsIdsWithQueue(){return[...this.messageQueues.keys()]}setClient(e,t){this.clients.set(t,e)}removeClientById(e){return this.getClientById(e)?(this.clients.delete(e),!0):!1}getMessageQueueById(e){return this.messageQueues.get(e)}addMessageToQueue(e,t){this.getMessageQueueById(e)||this.messageQueues.set(e,new rA),this.getMessageQueueById(e)?.addMessage(t)}clearMessageQueue(e){this.messageQueues.delete(e)}generateClientId(e){let t=e||w,n=t();for(;this.getClientById(n);)n=t();return n}},aA=class{timeoutId=null;constructor({realm:e,config:t,checkInterval:n=300,onClose:r}){this.realm=e,this.config=t,this.onClose=r,this.checkInterval=n}start(){this.timeoutId&&clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.checkConnections(),this.timeoutId=null,this.start()},this.checkInterval)}stop(){this.timeoutId&&=(clearTimeout(this.timeoutId),null)}checkConnections(){let e=this.realm.getClientsIds(),t=new Date().getTime(),{alive_timeout:n}=this.config;for(let r of e){let e=this.realm.getClientById(r);if(e&&!(t-e.getLastPing()<n))try{e.getSocket()?.close()}finally{this.realm.clearMessageQueue(r),this.realm.removeClientById(r),e.setSocket(null),this.onClose?.(e)}}}};let oA;(function(e){e.INVALID_KEY=`Invalid key provided`,e.INVALID_TOKEN=`Invalid token provided`,e.INVALID_WS_PARAMETERS=`No id, token, or key supplied to websocket server`,e.CONNECTION_LIMIT_EXCEED=`Server has reached its concurrent user limit`})(oA||={});let sA;(function(e){e.OPEN=`OPEN`,e.LEAVE=`LEAVE`,e.CANDIDATE=`CANDIDATE`,e.OFFER=`OFFER`,e.ANSWER=`ANSWER`,e.EXPIRE=`EXPIRE`,e.HEARTBEAT=`HEARTBEAT`,e.ID_TAKEN=`ID-TAKEN`,e.ERROR=`ERROR`})(sA||={});var cA=class{timeoutId=null;constructor({realm:e,config:t,messageHandler:n}){this.realm=e,this.config=t,this.messageHandler=n}startMessagesExpiration(){this.timeoutId&&clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.pruneOutstanding(),this.timeoutId=null,this.startMessagesExpiration()},this.config.cleanup_out_msgs)}stopMessagesExpiration(){this.timeoutId&&=(clearTimeout(this.timeoutId),null)}pruneOutstanding(){let e=this.realm.getClientsIdsWithQueue(),t=new Date().getTime(),n=this.config.expire_timeout,r={};for(let i of e){let e=this.realm.getMessageQueueById(i);if(!e||t-e.getLastReadAt()<n)continue;let a=e.getMessages();for(let e of a){let t=`${e.src}_${e.dst}`;r[t]||(this.messageHandler.handle(void 0,{type:sA.EXPIRE,src:e.dst,dst:e.src}),r[t]=!0)}this.realm.clearMessageQueue(i)}}},lA=class{socket=null;lastPing=new Date().getTime();constructor({id:e,token:t}){this.id=e,this.token=t}getId(){return this.id}getToken(){return this.token}getSocket(){return this.socket}setSocket(e){this.socket=e}getLastPing(){return this.lastPing}setLastPing(e){this.lastPing=e}send(e){this.socket?.send(JSON.stringify(e))}},uA=class extends Ce{constructor({server:e,realm:t,config:n}){super(),this.setMaxListeners(0),this.realm=t,this.config=n;let r=this.config.path;this.path=`${r}${r.endsWith(`/`)?``:`/`}peerjs`;let i={path:this.path,server:e};this.socketServer=n.createWebSocketServer?n.createWebSocketServer(i):new lc.default(i),this.socketServer.on(`connection`,(e,t)=>{this._onSocketConnection(e,t)}),this.socketServer.on(`error`,e=>{this._onSocketError(e)})}_onSocketConnection(e,t){e.on(`error`,e=>{this._onSocketError(e)});let{searchParams:n}=new URL(t.url??``,`https://peerjs`),{id:r,token:i,key:a}=Object.fromEntries(n.entries());if(!r||!i||!a){this._sendErrorAndClose(e,oA.INVALID_WS_PARAMETERS);return}if(a!==this.config.key){this._sendErrorAndClose(e,oA.INVALID_KEY);return}let o=this.realm.getClientById(r);if(o){if(i!==o.getToken()){e.send(JSON.stringify({type:sA.ID_TAKEN,payload:{msg:`ID is taken`}})),e.close();return}this._configureWS(e,o);return}this._registerClient({socket:e,id:r,token:i})}_onSocketError(e){this.emit(`error`,e)}_registerClient({socket:e,id:t,token:n}){if(this.realm.getClientsIds().length>=this.config.concurrent_limit){this._sendErrorAndClose(e,oA.CONNECTION_LIMIT_EXCEED);return}let r=new lA({id:t,token:n});this.realm.setClient(r,t),e.send(JSON.stringify({type:sA.OPEN})),this._configureWS(e,r)}_configureWS(e,t){t.setSocket(e),e.on(`close`,()=>{t.getSocket()===e&&(this.realm.removeClientById(t.getId()),this.emit(`close`,t))}),e.on(`message`,e=>{try{let n=JSON.parse(e.toString());n.src=t.getId(),this.emit(`message`,t,n)}catch(e){this.emit(`error`,e)}}),this.emit(`connection`,t)}_sendErrorAndClose(e,t){e.send(JSON.stringify({type:sA.ERROR,payload:{msg:t}})),e.close()}};const dA=e=>{if(e){let t=new Date().getTime();e.setLastPing(t)}return!0},fA=({realm:e})=>{let t=(n,r)=>{let i=r.type,a=r.src,o=r.dst,s=e.getClientById(o);if(s){let i=s.getSocket();try{if(i){let e=JSON.stringify(r);i.send(e)}else throw Error(`Peer dead`)}catch{i?i.close():e.removeClientById(s.getId()),t(n,{type:sA.LEAVE,src:o,dst:a})}}else![sA.LEAVE,sA.EXPIRE].includes(i)&&o?e.addMessageToQueue(o,r):i===sA.LEAVE&&!o&&e.removeClientById(a);return!0};return t};var pA=class{handlers=new Map;registerHandler(e,t){this.handlers.has(e)||this.handlers.set(e,t)}handle(e,t){let{type:n}=t,r=this.handlers.get(n);return r?r(e,t):!1}},mA=class{constructor(e,t=new pA){this.handlersRegistry=t;let n=fA({realm:e}),r=dA,i=(e,{type:t,src:r,dst:i,payload:a})=>n(e,{type:t,src:r,dst:i,payload:a});this.handlersRegistry.registerHandler(sA.HEARTBEAT,(e,t)=>r(e,t)),this.handlersRegistry.registerHandler(sA.OFFER,i),this.handlersRegistry.registerHandler(sA.ANSWER,i),this.handlersRegistry.registerHandler(sA.CANDIDATE,i),this.handlersRegistry.registerHandler(sA.LEAVE,i),this.handlersRegistry.registerHandler(sA.EXPIRE,i)}handle(e,t){return this.handlersRegistry.handle(e,t)}},hA={};hA=JSON.parse(`{"name":"PeerJS Server","description":"A server side element to broker connections between PeerJS clients.","website":"https://peerjs.com/"}`);var gA=({config:e,realm:t})=>{let n=m.Router();return n.get(`/id`,(n,r)=>{r.contentType(`html`),r.send(t.generateClientId(e.generateClientId))}),n.get(`/peers`,(n,r)=>{if(e.allow_discovery){let e=t.getClientsIds();return r.send(e)}return r.sendStatus(401)}),n};const _A=({config:e,realm:t,corsOptions:n})=>{let r=m.Router();return r.use(T(n)),r.get(`/`,(e,t)=>{t.send(tA(hA))}),r.use(`/:key`,gA({config:e,realm:t})),r},vA=({app:e,server:t,options:n})=>{let r=n,i=new iA,a=new mA(i),s=_A({config:r,realm:i,corsOptions:n.corsOptions}),c=new cA({realm:i,config:r,messageHandler:a}),l=new aA({realm:i,config:r,onClose:t=>{e.emit(`disconnect`,t)}});e.use(n.path,s);let u=new uA({server:t,realm:i,config:{...r,path:o.posix.join(e.path(),n.path,`/`)}});u.on(`connection`,t=>{let n=i.getMessageQueueById(t.getId());if(n){let e;for(;e=n.readMessage();)a.handle(t,e);i.clearMessageQueue(t.getId())}e.emit(`connection`,t)}),u.on(`message`,(t,n)=>{e.emit(`message`,t,n),a.handle(t,n)}),u.on(`close`,t=>{e.emit(`disconnect`,t)}),u.on(`error`,t=>{e.emit(`error`,t)}),c.startMessagesExpiration(),l.start()};function yA(e,t){let n=m(),r={...nA,...t};return r.proxied&&n.set(`trust proxy`,r.proxied!==`false`&&!!r.proxied),n.on(`mount`,()=>{if(!e)throw Error(`Server is not passed to constructor - can't start PeerServer`);vA({app:n,server:e,options:r})}),n}function bA(e,t){let n=yA(e,{path:`/`,allow_discovery:!1});t.use(n),n.on(`connection`,e=>{console.log(`PeerJS: client connected — ${e.getId()}`)}),n.on(`disconnect`,e=>{console.log(`PeerJS: client disconnected — ${e.getId()}`)})}const xA=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`;let SA=0,CA=[];function wA(){let e=Date.now();if(e===SA)for(let e=CA.length-1;e>=0;e--){if(CA[e]<31){CA[e]++;break}CA[e]=0}else SA=e,CA=Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e%32);let t=e,n=Array(10);for(let e=9;e>=0;e--)n[e]=xA[t%32],t=Math.floor(t/32);let r=CA.map(e=>xA[e]);return n.join(``)+r.join(``)}function TA(e){let{httpServer:t,app:n,heartbeatTimeoutMs:r=9e4,verbose:i=!1}=e,a=e.token||gt(),o=new lc.default({noServer:!0}),s=new Map,c=new Map,u=new Map,d=new Map,f=new Set,p=setInterval(()=>{dt(r)},Math.max(1e4,Math.floor(r/2)));function m(e){i&&console.log(`[control-plane] ${e}`)}function h(e){if(!e)return!1;if(e===a)return!0;try{let t=gt();if(t&&e===t)return!0}catch{}return!1}function g(e){let t=e.headers.host||`127.0.0.1`,n=e.headers.origin,r=e.headers.referer;if(n)try{let e=new l(n);if(e.host===t||e.hostname===`127.0.0.1`||e.hostname===`localhost`)return!0}catch{}if(r)try{let e=new l(r);if(e.host===t||e.hostname===`127.0.0.1`||e.hostname===`localhost`)return!0}catch{}let i=e.headers[`sec-fetch-site`];return i===`same-origin`||i===`same-site`}function _(e,t){let n=t.searchParams.get(`token`);if(n)return n;let r=e.headers[`x-control-token`];if(typeof r==`string`)return r;let i=e.headers.authorization;return i&&i.startsWith(`Bearer `)?i.slice(7).trim():null}let v=(e,t,n)=>{let r=e.headers.host||`127.0.0.1`,i=new l(e.url||`/`,`http://${r}`);if(i.pathname===`/ws/control`){let r=_(e,i);if(!(r?h(r):g(e))){m(`Rejected unauthorized WebSocket connection from ${e.socket.remoteAddress}`),o.handleUpgrade(e,t,n,e=>{e.close(4001,`Unauthorized`)});return}o.handleUpgrade(e,t,n,t=>{o.emit(`connection`,t,e)})}};t.on(`upgrade`,v);function y(e,t){let{id:n,type:r,payload:i}=t;if(r===`client:register`){let t=i;if(t?.clientId&&typeof t.clientId==`string`&&t.clientId.trim()){let r=t.clientId.trim();st({clientId:r,deviceLabel:t.deviceLabel||`Unknown device`,capabilities:t.capabilities||[],version:t.version||`1.0.0`,peerId:t.peerId}),e&&(s.set(r,e),c.set(e,r)),m(`Client registered: ${r} (${t.deviceLabel})`);let i={id:wA(),type:`server:registered`,replyTo:n,payload:{clientId:r,status:`ok`,serverTime:Date.now()}};return e&&e.readyState===cc.default.OPEN&&e.send(JSON.stringify(i)),i}else m(`Warning: received client:register without valid clientId`)}else if(r===`client:heartbeat`){let e=i;e?.clientId&&(ct(e.clientId),m(`Heartbeat from client: ${e.clientId}`))}else if(r===`command:result`){let e=i;if(e?.commandId&&d.has(e.commandId)){let t=d.get(e.commandId);clearTimeout(t.timeout),d.delete(e.commandId),t.resolve(e),m(`Command ${e.commandId} resolved: success=${e.success}`)}}}if(o.on(`connection`,e=>{m(`WebSocket client connected`),e.on(`message`,t=>{try{y(e,JSON.parse(t.toString()))}catch(e){m(`Error parsing WebSocket message: ${e.message}`)}}),e.on(`close`,()=>{let t=c.get(e);t&&(s.delete(t),c.delete(e),m(`Client disconnected: ${t}`))}),e.on(`error`,e=>{m(`WebSocket error: ${e.message}`)})}),n){let e=(e,t,n)=>{let r=e.headers.host||`127.0.0.1`;if(!h(_(e,new l(e.url,`http://${r}`)))){t.status(401).json({error:`Unauthorized: Invalid control token`});return}n()},t=(e,t,n)=>{let r=e.headers.host||`127.0.0.1`,i=_(e,new l(e.url,`http://${r}`));if(!(i?h(i):g(e))){t.status(401).json({error:`Unauthorized: Invalid control token`});return}n()};n.get(`/api/control/clients`,e,(e,t)=>{let n=ut();t.json({clients:n})}),n.post(`/api/control/command`,e,async(e,t)=>{let{clientId:n,action:r,args:i,timeoutMs:a}=e.body||{};if(!n||!r){t.status(400).json({error:`clientId and action are required`});return}try{let e=await b(n,r,i,a);t.json(e)}catch(e){t.status(e.message?.includes(`not connected`)?404:500).json({error:e.message})}}),n.post(`/api/control/messages`,t,(e,t)=>{let n=e.body;if(!n||!n.type){t.status(400).json({error:`Invalid control message payload`});return}let r=y(null,n);t.json({status:`received`,reply:r})}),n.get(`/api/control/events`,t,(e,t)=>{let n=e.headers.host||`127.0.0.1`,r=new l(e.url,`http://${n}`).searchParams.get(`clientId`)||e.headers[`x-client-id`]||void 0;t.setHeader(`Content-Type`,`text/event-stream`),t.setHeader(`Cache-Control`,`no-cache`),t.setHeader(`Connection`,`keep-alive`),t.flushHeaders?.(),f.add(t),r&&(u.set(r,t),m(`SSE client connected: ${r}`)),t.write(`event: ready\ndata: ${JSON.stringify({status:`ok`,serverTime:Date.now()})}\n\n`);let i=setInterval(()=>{t.writableEnded||t.write(`: ping
|
|
971
|
+
</html>`)}),e.get(`/oauth/session/:state`,(e,t)=>{let n=typeof e.params.state==`string`?e.params.state.trim():``;if(!n){t.status(400).json({error:`Missing state`});return}let r=s(n);if(!r){t.status(404).json({error:`OAuth session not found`});return}t.json({providerId:r.providerId,status:r.status,expiresAt:r.expiresAt,error:r.authorizationError,errorDescription:r.authorizationErrorDescription})}),e.post(`/oauth/token`,async(e,t)=>{o();let n=typeof e.body?.state==`string`?e.body.state.trim():``;if(!n){t.status(400).json({error:`Missing required state`});return}let i=s(n);if(!i){t.status(400).json({error:`Invalid or expired OAuth state`});return}if(i.status!==`authorized`||!i.authorizationCode){t.status(400).json({error:`OAuth callback not completed for this state`});return}let c=Je(i.providerId);if(!c){a.delete(n),t.status(400).json({error:`Unsupported OAuth provider`});return}let l=new URLSearchParams;l.set(`grant_type`,`authorization_code`),l.set(`code`,i.authorizationCode),l.set(`client_id`,i.clientId),l.set(`redirect_uri`,i.redirectUri),i.clientSecret&&(c.clientAuthMethod||`request_body`)!==`basic_header`&&l.set(`client_secret`,i.clientSecret),i.codeVerifier&&l.set(`code_verifier`,i.codeVerifier);try{let e=await r(i.tokenUrl,{method:`POST`,headers:Jk(c.clientAuthMethod,i.clientId,i.clientSecret),body:l.toString()}),o=await e.text(),s={};try{s=o?JSON.parse(o):{}}catch{s={}}if(!e.ok){a.delete(n),t.status(502).json({error:`OAuth token exchange failed`,status:e.status,upstreamError:s.error||s.error_description||`unknown_error`});return}let u=typeof s.access_token==`string`?s.access_token:``;if(!u){a.delete(n),t.status(502).json({error:`OAuth token exchange returned no access_token`});return}a.delete(n),t.json({providerId:i.providerId,accessToken:u,tokenType:typeof s.token_type==`string`?s.token_type:`Bearer`,refreshToken:typeof s.refresh_token==`string`?s.refresh_token:void 0,expiresIn:typeof s.expires_in==`number`?s.expires_in:void 0,scope:typeof s.scope==`string`?s.scope:void 0})}catch{a.delete(n),t.status(502).json({error:`OAuth token exchange network error`})}}),e.post(`/oauth/refresh`,async(e,t)=>{let n=e.body||{};if(!n.providerId||typeof n.providerId!=`string`){t.status(400).json({error:`Missing required providerId`});return}let i=Je(n.providerId);if(!i){t.status(400).json({error:`Unsupported OAuth provider`,providerId:n.providerId});return}let a=n.providerId===`custom_mcp`&&Wk(n.tokenUrl)?n.tokenUrl:i.tokenUrl;if(!n.clientId||typeof n.clientId!=`string`){t.status(400).json({error:`Missing required clientId`});return}if(!n.refreshToken||typeof n.refreshToken!=`string`){t.status(400).json({error:`Missing required refreshToken`});return}let o=Kk(n.scope);if(!qk(i.defaultScopes,o)){t.status(400).json({error:`Requested scopes are not allowed for this provider`});return}let s=new URLSearchParams;if(s.set(`grant_type`,`refresh_token`),s.set(`refresh_token`,n.refreshToken),s.set(`client_id`,n.clientId),n.clientSecret&&(i.clientAuthMethod||`request_body`)!==`basic_header`&&s.set(`client_secret`,n.clientSecret),o.length>0){let e=i.scopeSeparator===`comma`?`,`:` `;s.set(`scope`,o.join(e))}try{let e=await r(a,{method:`POST`,headers:Jk(i.clientAuthMethod,n.clientId,n.clientSecret),body:s.toString()}),o=await e.text(),c={};try{c=o?JSON.parse(o):{}}catch{c={}}if(!e.ok){t.status(502).json({error:`OAuth refresh failed`,status:e.status,upstreamError:c.error||c.error_description||`unknown_error`});return}let l=typeof c.access_token==`string`?c.access_token:``;if(!l){t.status(502).json({error:`OAuth refresh returned no access_token`});return}t.json({providerId:i.id,accessToken:l,tokenType:typeof c.token_type==`string`?c.token_type:`Bearer`,refreshToken:typeof c.refresh_token==`string`?c.refresh_token:void 0,expiresIn:typeof c.expires_in==`number`?c.expires_in:void 0,scope:typeof c.scope==`string`?c.scope:void 0})}catch{t.status(502).json({error:`OAuth refresh network error`})}})}function Zk(e){if(!e||typeof e!=`string`)return!1;let t=o.normalize(e).replace(/^(\.\.[\/\\])+/,``);return!(o.isAbsolute(e)||e.startsWith(`..`)||t!==e)}function Qk(e,t){let n=e.headers.host||`127.0.0.1`,r=e.headers.origin,i=e.headers.referer,a=e=>{try{let r=new l(e);if(r.host===n)return!0;let i=r.hostname.toLowerCase();if(i===`127.0.0.1`||i===`localhost`||i===`::1`||i===`[::1]`||i===`github.com`||i.endsWith(`.github.io`)||i.endsWith(`.pages.dev`)||t?.corsMode===`all`||t?.allowedOrigins&&t.allowedOrigins.has(r.origin)||t?.corsMode===`private`&&/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(i))return!0}catch{}return!1};if(r&&a(r)||i&&a(i))return!0;let o=e.headers[`sec-fetch-site`];return o===`same-origin`||o===`same-site`}function $k(e,t){let{backupsDir:n}=t,r=t.token||gt(),i=(e,n,i)=>{let a=e.headers.host||`127.0.0.1`,o=new l(e.url,`http://${a}`).searchParams.get(`token`),s=e.headers[`x-control-token`],c=e.headers.authorization,u=c&&c.startsWith(`Bearer `)?c.slice(7).trim():null,d=o||s||u;if(!(d?d===r:Qk(e,t))){n.status(401).json({error:`Unauthorized: Invalid control token`});return}i()};e.post(`/api/backup/upload`,i,(e,t)=>{let{clientId:r,backupId:i,path:a,content:s,encoding:c}=e.body||{};if(!r||!i||!a){t.status(400).json({error:`clientId, backupId, and path are required`});return}if(!Zk(a)){t.status(400).json({error:`Invalid path: ${a}`});return}let l=o.resolve(n,r,i),u=o.resolve(l,a);if(!u.startsWith(l+o.sep)&&u!==l){t.status(400).json({error:`Invalid path: ${a}`});return}try{let e=o.dirname(u);h.existsSync(e)||h.mkdirSync(e,{recursive:!0});let n=c===`base64`?E.from(s||``,`base64`):E.from(s||``,`utf-8`);h.writeFileSync(u,n),t.json({success:!0,path:a,bytesWritten:n.length})}catch(e){t.status(500).json({error:`Failed to write file: ${e.message}`})}}),e.post(`/api/backup/complete`,i,(e,t)=>{let{clientId:n,backupId:r,fileCount:i,totalBytes:a,manifest:o}=e.body||{};if(!n||!r){t.status(400).json({error:`clientId and backupId are required`});return}try{let e=_t({id:r,clientId:n,fileCount:Number(i)||0,totalBytes:Number(a)||0,manifest:o});t.json({success:!0,backupId:e.id,clientId:e.clientId,timestamp:e.timestamp,fileCount:e.fileCount,totalBytes:e.totalBytes})}catch(e){t.status(500).json({error:`Failed to complete backup: ${e.message}`})}}),e.get(`/api/backup/list`,i,(e,t)=>{let n=vt(e.query.clientId||void 0);t.json({backups:n})}),e.delete(`/api/backup/:id`,i,(e,t)=>{let r=Array.isArray(e.params.id)?e.params.id[0]:e.params.id,i=e.query.clientId||e.body?.clientId;if(!r){t.status(400).json({error:`Backup id is required`});return}try{if(i){let e=o.resolve(n,i,r);h.existsSync(e)&&h.rmSync(e,{recursive:!0,force:!0})}yt(r,i),t.json({success:!0,deleted:r})}catch(e){t.status(500).json({error:`Failed to delete backup: ${e.message}`})}})}function eA(e){let t=m(),n=Nt(e.verbose),{verbose:r}=e;t.use(Hr(n,r)),t.use(xr(n,r)),t.use(Ft(e,n,r)),t.use(br()),t.use(p({filter(e,t){return t.getHeader(`Content-Type`)!==`text/event-stream`&&p.filter(e,t)}})),t.use(m.json({limit:`1000mb`})),h.existsSync(e.databaseDir)||h.mkdirSync(e.databaseDir,{recursive:!0}),Xe(o.join(e.databaseDir,`push-subscriptions.db`)),ot(o.join(e.databaseDir,`clients.db`)),St(o.join(e.databaseDir,`scheduled-tasks.db`)),Ik(t,{verbose:r,allowPrivateProxy:e.allowPrivateProxy}),Xk(t),Bk(t,{logsDir:o.resolve(e.databaseDir,`..`,`.cache`,`logs`)}),$k(t,{backupsDir:o.resolve(e.databaseDir,`..`,`.cache`,`backups`),token:e.controlToken,allowedOrigins:e.allowedOrigins,corsMode:e.corsMode}),Vk(t,{logsDir:o.resolve(e.databaseDir,`..`,`.cache`,`logs`),logger:n}),it(t),kt(t);let i=new Mt({getEnabledTasks:Dt,updateLastRun:Ot,broadcastTaskTrigger:e=>rt({type:`scheduled-task`,taskId:e.id,groupId:e.groupId,prompt:e.prompt,taskType:e.type,tools:e.tools,channel:e.channel})});return Gr(t,e.rootPath),t.use((e,t,n)=>{e.method===`GET`&&e.headers.accept?.includes(`text/html`)?t.redirect(e.baseUrl||`/`):n()}),{app:t,scheduler:i}}function tA(e){return e&&e.__esModule?e.default:e}var nA={host:`::`,port:9e3,expire_timeout:5e3,alive_timeout:9e4,key:`peerjs`,path:`/`,concurrent_limit:5e3,allow_discovery:!1,proxied:!1,cleanup_out_msgs:1e3,corsOptions:{origin:!0}},rA=class{lastReadAt=new Date().getTime();messages=[];getLastReadAt(){return this.lastReadAt}addMessage(e){this.messages.push(e)}readMessage(){if(this.messages.length>0)return this.lastReadAt=new Date().getTime(),this.messages.shift()}getMessages(){return this.messages}},iA=class{clients=new Map;messageQueues=new Map;getClientsIds(){return[...this.clients.keys()]}getClientById(e){return this.clients.get(e)}getClientsIdsWithQueue(){return[...this.messageQueues.keys()]}setClient(e,t){this.clients.set(t,e)}removeClientById(e){return this.getClientById(e)?(this.clients.delete(e),!0):!1}getMessageQueueById(e){return this.messageQueues.get(e)}addMessageToQueue(e,t){this.getMessageQueueById(e)||this.messageQueues.set(e,new rA),this.getMessageQueueById(e)?.addMessage(t)}clearMessageQueue(e){this.messageQueues.delete(e)}generateClientId(e){let t=e||w,n=t();for(;this.getClientById(n);)n=t();return n}},aA=class{timeoutId=null;constructor({realm:e,config:t,checkInterval:n=300,onClose:r}){this.realm=e,this.config=t,this.onClose=r,this.checkInterval=n}start(){this.timeoutId&&clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.checkConnections(),this.timeoutId=null,this.start()},this.checkInterval)}stop(){this.timeoutId&&=(clearTimeout(this.timeoutId),null)}checkConnections(){let e=this.realm.getClientsIds(),t=new Date().getTime(),{alive_timeout:n}=this.config;for(let r of e){let e=this.realm.getClientById(r);if(e&&!(t-e.getLastPing()<n))try{e.getSocket()?.close()}finally{this.realm.clearMessageQueue(r),this.realm.removeClientById(r),e.setSocket(null),this.onClose?.(e)}}}};let oA;(function(e){e.INVALID_KEY=`Invalid key provided`,e.INVALID_TOKEN=`Invalid token provided`,e.INVALID_WS_PARAMETERS=`No id, token, or key supplied to websocket server`,e.CONNECTION_LIMIT_EXCEED=`Server has reached its concurrent user limit`})(oA||={});let sA;(function(e){e.OPEN=`OPEN`,e.LEAVE=`LEAVE`,e.CANDIDATE=`CANDIDATE`,e.OFFER=`OFFER`,e.ANSWER=`ANSWER`,e.EXPIRE=`EXPIRE`,e.HEARTBEAT=`HEARTBEAT`,e.ID_TAKEN=`ID-TAKEN`,e.ERROR=`ERROR`})(sA||={});var cA=class{timeoutId=null;constructor({realm:e,config:t,messageHandler:n}){this.realm=e,this.config=t,this.messageHandler=n}startMessagesExpiration(){this.timeoutId&&clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.pruneOutstanding(),this.timeoutId=null,this.startMessagesExpiration()},this.config.cleanup_out_msgs)}stopMessagesExpiration(){this.timeoutId&&=(clearTimeout(this.timeoutId),null)}pruneOutstanding(){let e=this.realm.getClientsIdsWithQueue(),t=new Date().getTime(),n=this.config.expire_timeout,r={};for(let i of e){let e=this.realm.getMessageQueueById(i);if(!e||t-e.getLastReadAt()<n)continue;let a=e.getMessages();for(let e of a){let t=`${e.src}_${e.dst}`;r[t]||(this.messageHandler.handle(void 0,{type:sA.EXPIRE,src:e.dst,dst:e.src}),r[t]=!0)}this.realm.clearMessageQueue(i)}}},lA=class{socket=null;lastPing=new Date().getTime();constructor({id:e,token:t}){this.id=e,this.token=t}getId(){return this.id}getToken(){return this.token}getSocket(){return this.socket}setSocket(e){this.socket=e}getLastPing(){return this.lastPing}setLastPing(e){this.lastPing=e}send(e){this.socket?.send(JSON.stringify(e))}},uA=class extends Ce{constructor({server:e,realm:t,config:n}){super(),this.setMaxListeners(0),this.realm=t,this.config=n;let r=this.config.path;this.path=`${r}${r.endsWith(`/`)?``:`/`}peerjs`;let i={path:this.path,server:e};this.socketServer=n.createWebSocketServer?n.createWebSocketServer(i):new lc.default(i),this.socketServer.on(`connection`,(e,t)=>{this._onSocketConnection(e,t)}),this.socketServer.on(`error`,e=>{this._onSocketError(e)})}_onSocketConnection(e,t){e.on(`error`,e=>{this._onSocketError(e)});let{searchParams:n}=new URL(t.url??``,`https://peerjs`),{id:r,token:i,key:a}=Object.fromEntries(n.entries());if(!r||!i||!a){this._sendErrorAndClose(e,oA.INVALID_WS_PARAMETERS);return}if(a!==this.config.key){this._sendErrorAndClose(e,oA.INVALID_KEY);return}let o=this.realm.getClientById(r);if(o){if(i!==o.getToken()){e.send(JSON.stringify({type:sA.ID_TAKEN,payload:{msg:`ID is taken`}})),e.close();return}this._configureWS(e,o);return}this._registerClient({socket:e,id:r,token:i})}_onSocketError(e){this.emit(`error`,e)}_registerClient({socket:e,id:t,token:n}){if(this.realm.getClientsIds().length>=this.config.concurrent_limit){this._sendErrorAndClose(e,oA.CONNECTION_LIMIT_EXCEED);return}let r=new lA({id:t,token:n});this.realm.setClient(r,t),e.send(JSON.stringify({type:sA.OPEN})),this._configureWS(e,r)}_configureWS(e,t){t.setSocket(e),e.on(`close`,()=>{t.getSocket()===e&&(this.realm.removeClientById(t.getId()),this.emit(`close`,t))}),e.on(`message`,e=>{try{let n=JSON.parse(e.toString());n.src=t.getId(),this.emit(`message`,t,n)}catch(e){this.emit(`error`,e)}}),this.emit(`connection`,t)}_sendErrorAndClose(e,t){e.send(JSON.stringify({type:sA.ERROR,payload:{msg:t}})),e.close()}};const dA=e=>{if(e){let t=new Date().getTime();e.setLastPing(t)}return!0},fA=({realm:e})=>{let t=(n,r)=>{let i=r.type,a=r.src,o=r.dst,s=e.getClientById(o);if(s){let i=s.getSocket();try{if(i){let e=JSON.stringify(r);i.send(e)}else throw Error(`Peer dead`)}catch{i?i.close():e.removeClientById(s.getId()),t(n,{type:sA.LEAVE,src:o,dst:a})}}else![sA.LEAVE,sA.EXPIRE].includes(i)&&o?e.addMessageToQueue(o,r):i===sA.LEAVE&&!o&&e.removeClientById(a);return!0};return t};var pA=class{handlers=new Map;registerHandler(e,t){this.handlers.has(e)||this.handlers.set(e,t)}handle(e,t){let{type:n}=t,r=this.handlers.get(n);return r?r(e,t):!1}},mA=class{constructor(e,t=new pA){this.handlersRegistry=t;let n=fA({realm:e}),r=dA,i=(e,{type:t,src:r,dst:i,payload:a})=>n(e,{type:t,src:r,dst:i,payload:a});this.handlersRegistry.registerHandler(sA.HEARTBEAT,(e,t)=>r(e,t)),this.handlersRegistry.registerHandler(sA.OFFER,i),this.handlersRegistry.registerHandler(sA.ANSWER,i),this.handlersRegistry.registerHandler(sA.CANDIDATE,i),this.handlersRegistry.registerHandler(sA.LEAVE,i),this.handlersRegistry.registerHandler(sA.EXPIRE,i)}handle(e,t){return this.handlersRegistry.handle(e,t)}},hA={};hA=JSON.parse(`{"name":"PeerJS Server","description":"A server side element to broker connections between PeerJS clients.","website":"https://peerjs.com/"}`);var gA=({config:e,realm:t})=>{let n=m.Router();return n.get(`/id`,(n,r)=>{r.contentType(`html`),r.send(t.generateClientId(e.generateClientId))}),n.get(`/peers`,(n,r)=>{if(e.allow_discovery){let e=t.getClientsIds();return r.send(e)}return r.sendStatus(401)}),n};const _A=({config:e,realm:t,corsOptions:n})=>{let r=m.Router();return r.use(T(n)),r.get(`/`,(e,t)=>{t.send(tA(hA))}),r.use(`/:key`,gA({config:e,realm:t})),r},vA=({app:e,server:t,options:n})=>{let r=n,i=new iA,a=new mA(i),s=_A({config:r,realm:i,corsOptions:n.corsOptions}),c=new cA({realm:i,config:r,messageHandler:a}),l=new aA({realm:i,config:r,onClose:t=>{e.emit(`disconnect`,t)}});e.use(n.path,s);let u=new uA({server:t,realm:i,config:{...r,path:o.posix.join(e.path(),n.path,`/`)}});u.on(`connection`,t=>{let n=i.getMessageQueueById(t.getId());if(n){let e;for(;e=n.readMessage();)a.handle(t,e);i.clearMessageQueue(t.getId())}e.emit(`connection`,t)}),u.on(`message`,(t,n)=>{e.emit(`message`,t,n),a.handle(t,n)}),u.on(`close`,t=>{e.emit(`disconnect`,t)}),u.on(`error`,t=>{e.emit(`error`,t)}),c.startMessagesExpiration(),l.start()};function yA(e,t){let n=m(),r={...nA,...t};return r.proxied&&n.set(`trust proxy`,r.proxied!==`false`&&!!r.proxied),n.on(`mount`,()=>{if(!e)throw Error(`Server is not passed to constructor - can't start PeerServer`);vA({app:n,server:e,options:r})}),n}function bA(e,t){let n=yA(e,{path:`/`,allow_discovery:!1});t.use(n),n.on(`connection`,e=>{console.log(`PeerJS: client connected — ${e.getId()}`)}),n.on(`disconnect`,e=>{console.log(`PeerJS: client disconnected — ${e.getId()}`)})}const xA=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`;let SA=0,CA=[];function wA(){let e=Date.now();if(e===SA)for(let e=CA.length-1;e>=0;e--){if(CA[e]<31){CA[e]++;break}CA[e]=0}else SA=e,CA=Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e%32);let t=e,n=Array(10);for(let e=9;e>=0;e--)n[e]=xA[t%32],t=Math.floor(t/32);let r=CA.map(e=>xA[e]);return n.join(``)+r.join(``)}function TA(e){let{httpServer:t,app:n,heartbeatTimeoutMs:r=9e4,verbose:i=!1}=e,a=e.token||gt(),o=new lc.default({noServer:!0}),s=new Map,c=new Map,u=new Map,d=new Map,f=new Set,p=setInterval(()=>{dt(r)},Math.max(1e4,Math.floor(r/2)));function m(e){i&&console.log(`[control-plane] ${e}`)}function h(e){if(!e)return!1;if(e===a)return!0;try{let t=gt();if(t&&e===t)return!0}catch{}return!1}function g(t){let n=t.headers.host||`127.0.0.1`,r=t.headers.origin,i=t.headers.referer,a=t=>{try{let r=new l(t);if(r.host===n)return!0;let i=r.hostname.toLowerCase();if(i===`127.0.0.1`||i===`localhost`||i===`::1`||i===`[::1]`||i===`github.com`||i.endsWith(`.github.io`)||i.endsWith(`.pages.dev`)||e.corsMode===`all`||e.allowedOrigins&&e.allowedOrigins.has(r.origin)||e.corsMode===`private`&&/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(i))return!0}catch{}return!1};if(r&&a(r)||i&&a(i))return!0;let o=t.headers[`sec-fetch-site`];return o===`same-origin`||o===`same-site`}function _(e,t){let n=t.searchParams.get(`token`);if(n)return n;let r=e.headers[`x-control-token`];if(typeof r==`string`)return r;let i=e.headers.authorization;return i&&i.startsWith(`Bearer `)?i.slice(7).trim():null}let v=(e,t,n)=>{let r=e.headers.host||`127.0.0.1`,i=new l(e.url||`/`,`http://${r}`);if(i.pathname===`/ws/control`){let r=_(e,i);if(!(r?h(r):g(e))){m(`Rejected unauthorized WebSocket connection from ${e.socket.remoteAddress}`),o.handleUpgrade(e,t,n,e=>{e.close(4001,`Unauthorized`)});return}o.handleUpgrade(e,t,n,t=>{o.emit(`connection`,t,e)})}};t.on(`upgrade`,v);function y(e,t){let{id:n,type:r,payload:i}=t;if(r===`client:register`){let t=i;if(t?.clientId&&typeof t.clientId==`string`&&t.clientId.trim()){let r=t.clientId.trim();st({clientId:r,deviceLabel:t.deviceLabel||`Unknown device`,capabilities:t.capabilities||[],version:t.version||`1.0.0`,peerId:t.peerId}),e&&(s.set(r,e),c.set(e,r)),m(`Client registered: ${r} (${t.deviceLabel})`);let i={id:wA(),type:`server:registered`,replyTo:n,payload:{clientId:r,status:`ok`,serverTime:Date.now()}};return e&&e.readyState===cc.default.OPEN&&e.send(JSON.stringify(i)),i}else m(`Warning: received client:register without valid clientId`)}else if(r===`client:heartbeat`){let e=i;e?.clientId&&(ct(e.clientId),m(`Heartbeat from client: ${e.clientId}`))}else if(r===`command:result`){let e=i;if(e?.commandId&&d.has(e.commandId)){let t=d.get(e.commandId);clearTimeout(t.timeout),d.delete(e.commandId),t.resolve(e),m(`Command ${e.commandId} resolved: success=${e.success}`)}}}if(o.on(`connection`,e=>{m(`WebSocket client connected`),e.on(`message`,t=>{try{y(e,JSON.parse(t.toString()))}catch(e){m(`Error parsing WebSocket message: ${e.message}`)}}),e.on(`close`,()=>{let t=c.get(e);t&&(s.delete(t),c.delete(e),m(`Client disconnected: ${t}`))}),e.on(`error`,e=>{m(`WebSocket error: ${e.message}`)})}),n){let e=(e,t,n)=>{let r=e.headers.host||`127.0.0.1`;if(!h(_(e,new l(e.url,`http://${r}`)))){t.status(401).json({error:`Unauthorized: Invalid control token`});return}n()},t=(e,t,n)=>{let r=e.headers.host||`127.0.0.1`,i=_(e,new l(e.url,`http://${r}`));if(!(i?h(i):g(e))){t.status(401).json({error:`Unauthorized: Invalid control token`});return}n()};n.get(`/api/control/clients`,e,(e,t)=>{let n=ut();t.json({clients:n})}),n.post(`/api/control/command`,e,async(e,t)=>{let{clientId:n,action:r,args:i,timeoutMs:a}=e.body||{};if(!n||!r){t.status(400).json({error:`clientId and action are required`});return}try{let e=await b(n,r,i,a);t.json(e)}catch(e){t.status(e.message?.includes(`not connected`)?404:500).json({error:e.message})}}),n.post(`/api/control/messages`,t,(e,t)=>{let n=e.body;if(!n||!n.type){t.status(400).json({error:`Invalid control message payload`});return}let r=y(null,n);t.json({status:`received`,reply:r})}),n.get(`/api/control/events`,t,(e,t)=>{let n=e.headers.host||`127.0.0.1`,r=new l(e.url,`http://${n}`).searchParams.get(`clientId`)||e.headers[`x-client-id`]||void 0;t.setHeader(`Content-Type`,`text/event-stream`),t.setHeader(`Cache-Control`,`no-cache`),t.setHeader(`Connection`,`keep-alive`),t.flushHeaders?.(),f.add(t),r&&(u.set(r,t),m(`SSE client connected: ${r}`)),t.write(`event: ready\ndata: ${JSON.stringify({status:`ok`,serverTime:Date.now()})}\n\n`);let i=setInterval(()=>{t.writableEnded||t.write(`: ping
|
|
972
972
|
|
|
973
973
|
`)},15e3);e.on(`close`,()=>{clearInterval(i),f.delete(t),r&&u.get(r)===t&&(u.delete(r),m(`SSE client disconnected: ${r}`))})})}function b(e,t,n={},r=3e4){let i=s.get(e),a=u.get(e),o=i&&i.readyState===cc.default.OPEN,c=a&&!a.writableEnded;if(!o&&!c)return Promise.reject(Error(`Client not connected: ${e}`));let l=wA(),f={commandId:l,action:t,args:n},p={id:wA(),type:`command:execute`,payload:f};return new Promise((n,s)=>{let u=setTimeout(()=>{d.delete(l),s(Error(`Command ${t} to client ${e} timed out after ${r}ms`))},r);d.set(l,{resolve:n,reject:s,timeout:u});try{o?i.send(JSON.stringify(p)):c&&a.write(`event: command:execute\ndata: ${JSON.stringify(p)}\n\n`)}catch(e){clearTimeout(u),d.delete(l),s(e)}})}async function x(e,t={},n=3e4){let r=new Set([...s.keys(),...u.keys()]),i=[];for(let a of r)S(a)&&i.push(b(a,e,t,n).catch(e=>({commandId:``,success:!1,error:e.message})));return Promise.all(i)}function S(e){let t=s.get(e);if(t&&t.readyState===cc.default.OPEN)return!0;let n=u.get(e);return!!(n&&!n.writableEnded)}function C(){return ut().filter(e=>S(e.clientId))}function w(){clearInterval(p),t.removeListener(`upgrade`,v);for(let[,e]of d)clearTimeout(e.timeout),e.reject(Error(`Control plane closed`));d.clear();for(let e of s.values())try{e.close()}catch{}s.clear(),c.clear();for(let e of f)try{e.end()}catch{}f.clear(),u.clear();try{o.close()}catch{}}return{sendCommand:b,broadcastCommand:x,isClientConnected:S,getConnectedClients:C,getToken:()=>a,close:w}}var EA,DA,OA,kA,AA,jA,MA,NA,PA=z((()=>{EA=e=>{throw TypeError(e)},DA=(e,t,n)=>t.has(e)||EA(`Cannot `+n),OA=(e,t,n)=>(DA(e,t,`read from private field`),n?n.call(e):t.get(e)),kA=(e,t,n)=>t.has(e)?EA(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),AA=(e,t,n,r)=>(DA(e,t,`write to private field`),t.set(e,n),n),NA=class{constructor(){kA(this,jA,0),kA(this,MA,[]),AA(this,jA,null),AA(this,MA,[])}get expires(){return OA(this,jA)}getFingerprints(){return OA(this,MA)}getAlgorithm(){return``}},jA=new WeakMap,MA=new WeakMap})),FA,IA,LA,RA,zA,BA=z((()=>{FA=class extends DOMException{constructor(e){super(e,`InvalidStateError`)}},IA=class extends DOMException{constructor(e){super(e,`OperationError`)}},LA=class extends DOMException{constructor(e){super(e,`NotFoundError`)}},RA=class extends DOMException{constructor(e){super(e,`InvalidAccessError`)}},zA=class extends DOMException{constructor(e){super(e,`SyntaxError`)}}})),VA,HA,UA,WA,GA,KA,qA,JA,YA,XA,ZA,QA,$A=z((()=>{VA=e=>{throw TypeError(e)},HA=(e,t,n)=>t.has(e)||VA(`Cannot `+n),UA=(e,t,n)=>(HA(e,t,`read from private field`),n?n.call(e):t.get(e)),WA=(e,t,n)=>t.has(e)?VA(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),GA=(e,t,n,r)=>(HA(e,t,`write to private field`),t.set(e,n),n),QA=class extends DOMException{constructor(e,t){if(super(t,`OperationError`),WA(this,KA),WA(this,qA),WA(this,JA),WA(this,YA),WA(this,XA),WA(this,ZA),!e||!e.errorDetail)throw TypeError(`Cannot construct RTCError, errorDetail is required`);if([`data-channel-failure`,`dtls-failure`,`fingerprint-failure`,`hardware-encoder-error`,`hardware-encoder-not-available`,`sctp-failure`,`sdp-syntax-error`].indexOf(e.errorDetail)===-1)throw TypeError(`Cannot construct RTCError, errorDetail is invalid`);GA(this,KA,e.errorDetail),GA(this,qA,e.receivedAlert??null),GA(this,JA,e.sctpCauseCode??null),GA(this,YA,e.sdpLineNumber??null),GA(this,XA,e.sentAlert??null),GA(this,ZA,e.httpRequestStatusCode??null)}get errorDetail(){return UA(this,KA)}set errorDetail(e){throw TypeError(`Cannot set errorDetail, it is read-only`)}get receivedAlert(){return UA(this,qA)}set receivedAlert(e){throw TypeError(`Cannot set receivedAlert, it is read-only`)}get sctpCauseCode(){return UA(this,JA)}set sctpCauseCode(e){throw TypeError(`Cannot set sctpCauseCode, it is read-only`)}get httpRequestStatusCode(){return UA(this,ZA)}get sdpLineNumber(){return UA(this,YA)}set sdpLineNumber(e){throw TypeError(`Cannot set sdpLineNumber, it is read-only`)}get sentAlert(){return UA(this,XA)}set sentAlert(e){throw TypeError(`Cannot set sentAlert, it is read-only`)}},KA=new WeakMap,qA=new WeakMap,JA=new WeakMap,YA=new WeakMap,XA=new WeakMap,ZA=new WeakMap})),ej,tj,nj,rj,ij,aj,oj,sj,cj,lj,uj,dj=z((()=>{Nj(),$A(),ej=e=>{throw TypeError(e)},tj=(e,t,n)=>t.has(e)||ej(`Cannot `+n),nj=(e,t,n)=>(tj(e,t,`read from private field`),n?n.call(e):t.get(e)),rj=(e,t,n)=>t.has(e)?ej(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),ij=(e,t,n,r)=>(tj(e,t,`write to private field`),t.set(e,n),n),cj=class extends Event{constructor(e){super(`icecandidate`),rj(this,aj),ij(this,aj,e)}get candidate(){return nj(this,aj)}get url(){return``}},aj=new WeakMap,lj=class extends Event{constructor(e=`datachannel`,t){if(super(e),rj(this,oj),arguments.length===0)throw TypeError(`Failed to construct 'RTCDataChannelEvent': 2 arguments required, but only ${arguments.length} present.`);if(typeof t!=`object`)throw TypeError(`Failed to construct 'RTCDataChannelEvent': The provided value is not of type 'RTCDataChannelEventInit'.`);if(!t.channel)throw TypeError(`Failed to construct 'RTCDataChannelEvent': Failed to read the 'channel' property from 'RTCDataChannelEventInit': Required member is undefined.`);if(t.channel.constructor!==Mj)throw TypeError(`Failed to construct 'RTCDataChannelEvent': Failed to read the 'channel' property from 'RTCDataChannelEventInit': Failed to convert value to 'RTCDataChannel'.`);ij(this,oj,t?.channel)}get channel(){return nj(this,oj)}},oj=new WeakMap,uj=class extends Event{constructor(e,t){if(arguments.length<2)throw TypeError(`Failed to construct 'RTCErrorEvent': 2 arguments required, but only ${arguments.length} present.`);if(typeof t!=`object`)throw TypeError(`Failed to construct 'RTCErrorEvent': The provided value is not of type 'RTCErrorEventInit'.`);if(!t.error)throw TypeError(`Failed to construct 'RTCErrorEvent': Failed to read the 'error' property from 'RTCErrorEventInit': Required member is undefined.`);if(t.error.constructor!==QA)throw TypeError(`Failed to construct 'RTCErrorEvent': Failed to read the 'error' property from 'RTCErrorEventInit': Failed to convert value to 'RTCError'.`);super(e||`error`),rj(this,sj),ij(this,sj,t.error)}get error(){return nj(this,sj)}},sj=new WeakMap})),fj,pj,mj,hj,gj,_j,vj,yj,bj,xj,Sj,Cj,wj,Tj,Ej,Dj,Oj,kj,Aj,jj,Mj,Nj=z((()=>{BA(),dj(),fj=Object.defineProperty,pj=e=>{throw TypeError(e)},mj=(e,t,n)=>t in e?fj(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,hj=(e,t,n)=>mj(e,typeof t==`symbol`?t:t+``,n),gj=(e,t,n)=>t.has(e)||pj(`Cannot `+n),_j=(e,t,n)=>(gj(e,t,`read from private field`),n?n.call(e):t.get(e)),vj=(e,t,n)=>t.has(e)?pj(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),yj=(e,t,n,r)=>(gj(e,t,`write to private field`),t.set(e,n),n),Mj=class extends EventTarget{constructor(e,t={}){super(),vj(this,bj),vj(this,xj),vj(this,Sj),vj(this,Cj),vj(this,wj),vj(this,Tj),vj(this,Ej),vj(this,Dj),vj(this,Oj),vj(this,kj),vj(this,Aj),vj(this,jj,!1),hj(this,`onbufferedamountlow`,null),hj(this,`onclose`,null),hj(this,`onclosing`,null),hj(this,`onerror`,null),hj(this,`onmessage`,null),hj(this,`onopen`,null),yj(this,bj,e),yj(this,Cj,`arraybuffer`),yj(this,xj,_j(this,bj).isOpen()?`open`:`connecting`),yj(this,Sj,0),yj(this,wj,t.maxPacketLifeTime??null),yj(this,Tj,t.maxRetransmits??null),yj(this,Ej,t.negotiated??!1),yj(this,Dj,t.ordered??!0),yj(this,Oj,_j(this,bj).getId()),yj(this,kj,_j(this,bj).getLabel()),yj(this,Aj,_j(this,bj).getProtocol()),_j(this,bj).onOpen(()=>{yj(this,xj,`open`),this.dispatchEvent(new Event(`open`,{}))}),_j(this,bj).onClosed(()=>{_j(this,jj)||(yj(this,xj,`closing`),this.dispatchEvent(new Event(`closing`))),setImmediate(()=>{yj(this,xj,`closed`),this.dispatchEvent(new Event(`close`))})}),_j(this,bj).onError(e=>{this.dispatchEvent(new uj(`error`,{error:new RTCError({errorDetail:`data-channel-failure`},e)}))}),_j(this,bj).onBufferedAmountLow(()=>{this.dispatchEvent(new Event(`bufferedamountlow`))}),_j(this,bj).onMessage(e=>{if(typeof e==`string`){this.dispatchEvent(new MessageEvent(`message`,{data:e}));return}let t;e instanceof ArrayBuffer?t=e:(t=e.buffer,(e.byteOffset!==0||e.byteLength!==e.buffer.byteLength)&&(t=new ArrayBuffer(e.byteLength),new Uint8Array(t,0,e.byteLength).set(e))),_j(this,Cj)===`blob`&&(t=new Blob([t])),this.dispatchEvent(new MessageEvent(`message`,{data:t}))}),this.addEventListener(`message`,e=>{this.onmessage&&this.onmessage(e)}),this.addEventListener(`bufferedamountlow`,e=>{this.onbufferedamountlow&&this.onbufferedamountlow(e)}),this.addEventListener(`error`,e=>{this.onerror&&this.onerror(e)}),this.addEventListener(`close`,e=>{this.onclose&&this.onclose(e)}),this.addEventListener(`closing`,e=>{this.onclosing&&this.onclosing(e)}),this.addEventListener(`open`,e=>{this.onopen&&this.onopen(e)})}set binaryType(e){if(e!==`blob`&&e!==`arraybuffer`)throw new DOMException(`Failed to set the 'binaryType' property on 'RTCDataChannel': Unknown binary type : `+e,`TypeMismatchError`);yj(this,Cj,e)}get binaryType(){return _j(this,Cj)}get bufferedAmount(){return _j(this,bj).bufferedAmount()}get bufferedAmountLowThreshold(){return _j(this,Sj)}set bufferedAmountLowThreshold(e){let t=Number(e)||0;yj(this,Sj,t),_j(this,bj).setBufferedAmountLowThreshold(t)}get id(){return _j(this,Oj)}get label(){return _j(this,kj)}get maxPacketLifeTime(){return _j(this,wj)}get maxRetransmits(){return _j(this,Tj)}get negotiated(){return _j(this,Ej)}get ordered(){return _j(this,Dj)}get protocol(){return _j(this,Aj)}get readyState(){return _j(this,xj)}send(e){if(_j(this,xj)!==`open`)throw new FA(`Failed to execute 'send' on 'RTCDataChannel': RTCDataChannel.readyState is not 'open'`);typeof e==`string`?_j(this,bj).sendMessage(e):e instanceof Blob?e.arrayBuffer().then(e=>{n?.versions?.bun?_j(this,bj).sendMessageBinary(E.from(e)):_j(this,bj).sendMessageBinary(new Uint8Array(e))}):e instanceof Uint8Array?_j(this,bj).sendMessageBinary(e):n?.versions?.bun?_j(this,bj).sendMessageBinary(E.from(e)):_j(this,bj).sendMessageBinary(new Uint8Array(e))}close(){yj(this,jj,!0),setImmediate(()=>{_j(this,bj).close()})}},bj=new WeakMap,xj=new WeakMap,Sj=new WeakMap,Cj=new WeakMap,wj=new WeakMap,Tj=new WeakMap,Ej=new WeakMap,Dj=new WeakMap,Oj=new WeakMap,kj=new WeakMap,Aj=new WeakMap,jj=new WeakMap})),Pj,Fj,Ij,Lj,Rj,zj,Bj,Vj,Hj,Uj,Wj,Gj,Kj,qj,Jj,Yj,Xj,Zj,Qj,$j,eM=z((()=>{Pj=e=>{throw TypeError(e)},Fj=(e,t,n)=>t.has(e)||Pj(`Cannot `+n),Ij=(e,t,n)=>(Fj(e,t,`read from private field`),n?n.call(e):t.get(e)),Lj=(e,t,n)=>t.has(e)?Pj(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),Rj=(e,t,n,r)=>(Fj(e,t,`write to private field`),t.set(e,n),n),$j=class{constructor({candidate:e,sdpMLineIndex:t,sdpMid:n,usernameFragment:r}){if(Lj(this,zj),Lj(this,Bj),Lj(this,Vj),Lj(this,Hj),Lj(this,Uj),Lj(this,Wj),Lj(this,Gj),Lj(this,Kj),Lj(this,qj),Lj(this,Jj),Lj(this,Yj),Lj(this,Xj),Lj(this,Zj),Lj(this,Qj),t==null&&n==null)throw TypeError(`At least one of sdpMLineIndex or sdpMid must be specified`);if(Rj(this,Bj,e===null?`null`:e??``),Rj(this,Jj,t??null),Rj(this,Yj,n??null),Rj(this,Qj,r??null),e){let t=e.split(` `);Rj(this,Hj,t[0].replace(`candidate:`,``)),Rj(this,Vj,t[1]==`1`?`rtp`:`rtcp`),Rj(this,Gj,t[2]),Rj(this,Wj,parseInt(t[3],10)),Rj(this,zj,t[4]),Rj(this,Uj,parseInt(t[5],10)),Rj(this,Zj,t[7]),Rj(this,Xj,null),Rj(this,Kj,null),Rj(this,qj,null);for(let e=8;e<t.length;e++){let n=t[e];n===`raddr`?Rj(this,Kj,t[e+1]):n===`rport`&&Rj(this,qj,parseInt(t[e+1],10)),Ij(this,Gj)===`tcp`&&n===`tcptype`&&Rj(this,Xj,t[e+1])}}}get address(){return Ij(this,zj)??null}get candidate(){return Ij(this,Bj)}get component(){return Ij(this,Vj)}get foundation(){return Ij(this,Hj)??null}get port(){return Ij(this,Uj)??null}get priority(){return Ij(this,Wj)??null}get protocol(){return Ij(this,Gj)??null}get relatedAddress(){return Ij(this,Kj)}get relatedPort(){return Ij(this,qj)??null}get sdpMLineIndex(){return Ij(this,Jj)}get sdpMid(){return Ij(this,Yj)}get tcpType(){return Ij(this,Xj)}get type(){return Ij(this,Zj)??null}get usernameFragment(){return Ij(this,Qj)}toJSON(){return{candidate:Ij(this,Bj),sdpMLineIndex:Ij(this,Jj),sdpMid:Ij(this,Yj),usernameFragment:Ij(this,Qj)}}},zj=new WeakMap,Bj=new WeakMap,Vj=new WeakMap,Hj=new WeakMap,Uj=new WeakMap,Wj=new WeakMap,Gj=new WeakMap,Kj=new WeakMap,qj=new WeakMap,Jj=new WeakMap,Yj=new WeakMap,Xj=new WeakMap,Zj=new WeakMap,Qj=new WeakMap})),tM,nM,rM,iM,aM,oM,sM,cM,lM,uM,dM,fM=z((()=>{eM(),tM=Object.defineProperty,nM=e=>{throw TypeError(e)},rM=(e,t,n)=>t in e?tM(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,iM=(e,t,n)=>rM(e,typeof t==`symbol`?t:t+``,n),aM=(e,t,n)=>t.has(e)||nM(`Cannot `+n),oM=(e,t,n)=>(aM(e,t,`read from private field`),n?n.call(e):t.get(e)),sM=(e,t,n)=>t.has(e)?nM(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),cM=(e,t,n,r)=>(aM(e,t,`write to private field`),t.set(e,n),n),uM=class extends EventTarget{constructor(e){super(),sM(this,lM,null),iM(this,`ongatheringstatechange`,null),iM(this,`onselectedcandidatepairchange`,null),iM(this,`onstatechange`,null),cM(this,lM,e.pc),oM(this,lM).addEventListener(`icegatheringstatechange`,()=>{let e=new Event(`gatheringstatechange`);this.dispatchEvent(e),this.ongatheringstatechange?.(e)}),oM(this,lM).addEventListener(`iceconnectionstatechange`,()=>{let e=new Event(`statechange`);this.dispatchEvent(e),this.onstatechange?.(e)})}get component(){let e=this.getSelectedCandidatePair();return e?.local?e.local.component:null}get gatheringState(){return oM(this,lM)?oM(this,lM).iceGatheringState:`new`}get role(){return oM(this,lM).localDescription.type==`offer`?`controlling`:`controlled`}get state(){return oM(this,lM)?oM(this,lM).iceConnectionState:`new`}getLocalCandidates(){return oM(this,lM)?.ext_localCandidates??[]}getLocalParameters(){return new dM(new $j({candidate:oM(this,lM).selectedCandidatePair().local.candidate,sdpMLineIndex:0}))}getRemoteCandidates(){return oM(this,lM)?.ext_remoteCandidates??[]}getRemoteParameters(){}getSelectedCandidatePair(){let e=oM(this,lM)?.selectedCandidatePair();return e?{local:new $j({candidate:e.local.candidate,sdpMid:e.local.mid}),remote:new $j({candidate:e.remote.candidate,sdpMid:e.remote.mid})}:null}},lM=new WeakMap,dM=class{constructor({usernameFragment:e,password:t=``}){iM(this,`usernameFragment`,``),iM(this,`password`,``),this.usernameFragment=e,this.password=t}}})),pM,mM,hM,gM,_M,vM,yM,bM,xM,SM,CM,wM=z((()=>{fM(),pM=Object.defineProperty,mM=e=>{throw TypeError(e)},hM=(e,t,n)=>t in e?pM(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,gM=(e,t,n)=>hM(e,typeof t==`symbol`?t:t+``,n),_M=(e,t,n)=>t.has(e)||mM(`Cannot `+n),vM=(e,t,n)=>(_M(e,t,`read from private field`),n?n.call(e):t.get(e)),yM=(e,t,n)=>t.has(e)?mM(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),bM=(e,t,n,r)=>(_M(e,t,`write to private field`),t.set(e,n),n),CM=class extends EventTarget{constructor(e){super(),yM(this,xM,null),yM(this,SM,null),gM(this,`onstatechange`,null),gM(this,`onerror`,null),bM(this,xM,e.pc),bM(this,SM,new uM({pc:e.pc})),vM(this,xM).addEventListener(`connectionstatechange`,()=>{let e=new Event(`statechange`);this.dispatchEvent(e),this.onstatechange?.(e)})}get iceTransport(){return vM(this,SM)}get state(){let e=vM(this,xM)?vM(this,xM).connectionState:`new`;return e===`disconnected`&&(e=`closed`),e}getRemoteCertificates(){return[new ArrayBuffer(0)]}},xM=new WeakMap,SM=new WeakMap})),TM=B(((e,t)=>{let r=()=>n.platform===`linux`,i=null;t.exports={isLinux:r,getReport:()=>{if(!i)if(r()&&n.report){let e=n.report.excludeNetwork;n.report.excludeNetwork=!0,i=n.report.getReport(),n.report.excludeNetwork=e}else i={};return i}}})),EM=B(((e,t)=>{let n=V(`fs`),r=2048;t.exports={LDD_PATH:`/usr/bin/ldd`,SELF_PATH:`/proc/self/exe`,readFileSync:e=>{let t=n.openSync(e,`r`),i=E.alloc(r),a=n.readSync(t,i,0,r,0);return n.close(t,()=>{}),i.subarray(0,a)},readFile:e=>new Promise((t,i)=>{n.open(e,`r`,(e,a)=>{if(e)i(e);else{let e=E.alloc(r);n.read(a,e,0,r,0,(r,i)=>{t(e.subarray(0,i)),n.close(a,()=>{})})}})})}})),DM=B(((e,t)=>{t.exports={interpreterPath:e=>{if(e.length<64||e.readUInt32BE(0)!==2135247942||e.readUInt8(4)!==2||e.readUInt8(5)!==1)return null;let t=e.readUInt32LE(32),n=e.readUInt16LE(54),r=e.readUInt16LE(56);for(let i=0;i<r;i++){let r=t+i*n;if(e.readUInt32LE(r)===3){let t=e.readUInt32LE(r+8),n=e.readUInt32LE(r+32);return e.subarray(t,t+n).toString().replace(/\0.*$/g,``)}}return null}}})),OM=B(((e,t)=>{let n=V(`child_process`),{isLinux:r,getReport:i}=TM(),{LDD_PATH:a,SELF_PATH:o,readFile:s,readFileSync:c}=EM(),{interpreterPath:l}=DM(),u,d,f,p=`getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true`,m=``,h=()=>m||new Promise(e=>{n.exec(p,(t,n)=>{m=t?` `:n,e(m)})}),g=()=>{if(!m)try{m=n.execSync(p,{encoding:`utf8`})}catch{m=` `}return m},_=`glibc`,v=/LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i,y=`musl`,b=e=>e.includes(`libc.musl-`)||e.includes(`ld-musl-`),x=()=>{let e=i();return e.header&&e.header.glibcVersionRuntime?_:Array.isArray(e.sharedObjects)&&e.sharedObjects.some(b)?y:null},S=e=>{let[t,n]=e.split(/[\r\n]+/);return t&&t.includes(_)?_:n&&n.includes(y)?y:null},C=e=>{if(e){if(e.includes(`/ld-musl-`))return y;if(e.includes(`/ld-linux-`))return _}return null},w=e=>(e=e.toString(),e.includes(`musl`)?y:e.includes(`GNU C Library`)?_:null),T=async()=>{if(d!==void 0)return d;d=null;try{let e=await s(a);d=w(e)}catch{}return d},E=()=>{if(d!==void 0)return d;d=null;try{let e=c(a);d=w(e)}catch{}return d},D=async()=>{if(u!==void 0)return u;u=null;try{let e=await s(o),t=l(e);u=C(t)}catch{}return u},O=()=>{if(u!==void 0)return u;u=null;try{let e=c(o),t=l(e);u=C(t)}catch{}return u},k=async()=>{let e=null;if(r()&&(e=await D(),!e&&(e=await T(),e||=x(),!e))){let t=await h();e=S(t)}return e},A=()=>{let e=null;if(r()&&(e=O(),!e&&(e=E(),e||=x(),!e))){let t=g();e=S(t)}return e},j=async()=>r()&&await k()!==_,M=()=>r()&&A()!==_,N=async()=>{if(f!==void 0)return f;f=null;try{let e=(await s(a)).match(v);e&&(f=e[1])}catch{}return f},P=()=>{if(f!==void 0)return f;f=null;try{let e=c(a).match(v);e&&(f=e[1])}catch{}return f},F=()=>{let e=i();return e.header&&e.header.glibcVersionRuntime?e.header.glibcVersionRuntime:null},I=e=>e.trim().split(/\s+/)[1],L=e=>{let[t,n,r]=e.split(/[\r\n]+/);return t&&t.includes(_)?I(t):n&&r&&n.includes(y)?I(r):null};t.exports={GLIBC:_,MUSL:y,family:k,familySync:A,isNonGlibcLinux:j,isNonGlibcLinuxSync:M,version:async()=>{let e=null;if(r()&&(e=await N(),e||=F(),!e)){let t=await h();e=L(t)}return e},versionSync:()=>{let e=null;if(r()&&(e=P(),e||=F(),!e)){let t=g();e=L(t)}return e}}}));function kM(){let{platform:e,arch:t}=n;if(e===`linux`)if((0,jM.familySync)()===jM.MUSL){if(t===`x64`)return`@node-datachannel/linux-x64-musl`;if(t===`arm64`)return`@node-datachannel/linux-arm64-musl`}else{if(t===`x64`)return`@node-datachannel/linux-x64-gnu`;if(t===`arm64`)return`@node-datachannel/linux-arm64-gnu`}else if(e===`darwin`){if(t===`arm64`)return`@node-datachannel/darwin-arm64`;if(t===`x64`)return`@node-datachannel/darwin-x64`}else if(e===`win32`){if(t===`x64`)return`@node-datachannel/win32-x64-msvc`;if(t===`arm64`)return`@node-datachannel/win32-arm64-msvc`}else if(e===`android`&&t===`arm64`)return`@node-datachannel/android-arm64`;return null}function AM(){let e=[de.resolve(NM,`../../build/node_datachannel.node`),de.resolve(NM,`../../../build/node_datachannel.node`),de.resolve(NM,`../../build/Release/node_datachannel.node`),de.resolve(NM,`../../../build/Release/node_datachannel.node`),de.resolve(NM,`../../build/Debug/node_datachannel.node`),de.resolve(NM,`../../../build/Debug/node_datachannel.node`)],t=null;for(let n of e)if(I.existsSync(n))try{return PM(n)}catch(e){t=e instanceof Error?e:Error(String(e))}if(t)throw Error(`Failed to load local native addon build: ${t.message}
|
|
974
974
|
Stack: ${t.stack}`);let r=kM();if(r)try{return PM(r)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Cannot load native addon for node-datachannel on ${n.platform} (${n.arch}). Attempted to require "${r}". Please ensure optionalDependencies are installed (avoid --no-optional / --omit=optional) or compile locally with "npm run compile". (Error: ${t})`)}throw Error(`Unsupported platform/architecture for node-datachannel: ${n.platform} (${n.arch}). Please compile from source using "npm run compile".`)}var jM,MM,NM,PM,FM,IM=z((()=>{jM=OM(),MM=c.fileURLToPath(import.meta.url),NM=o.dirname(MM),PM=e.createRequire(import.meta.url),FM=AM()})),LM=z((()=>{ee.Duplex})),RM=z((()=>{IM()})),zM=z((()=>{IM(),FM.WebSocket})),BM,VM=z((()=>{IM(),LM(),RM(),zM(),FM.Audio,FM.Video,FM.Track,FM.DataChannel,BM=FM.PeerConnection,FM.IceUdpMuxListener,FM.RtpPacketizationConfig,FM.PacingHandler,FM.RtcpReceivingSession,FM.RtcpNackResponder,FM.RtcpSrReporter,FM.RtpPacketizer,FM.H264RtpPacketizer,FM.H265RtpPacketizer,FM.AV1RtpPacketizer})),HM,UM,WM,GM,KM,qM,JM,YM,XM=z((()=>{HM=e=>{throw TypeError(e)},UM=(e,t,n)=>t.has(e)||HM(`Cannot `+n),WM=(e,t,n)=>(UM(e,t,`read from private field`),n?n.call(e):t.get(e)),GM=(e,t,n)=>t.has(e)?HM(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),KM=(e,t,n,r)=>(UM(e,t,`write to private field`),t.set(e,n),n),YM=class{constructor(e){GM(this,qM),GM(this,JM),KM(this,qM,e?.type),KM(this,JM,e?.sdp??``)}get type(){return WM(this,qM)}set type(e){if(e!==`offer`&&e!==`answer`&&e!==`pranswer`&&e!==`rollback`)throw TypeError(`Failed to set the 'type' property on 'RTCSessionDescription': The provided value '${e}' is not a valid enum value of type RTCSdpType.`);KM(this,qM,e)}get sdp(){return WM(this,JM)}toJSON(){return{sdp:WM(this,JM),type:WM(this,qM)}}},qM=new WeakMap,JM=new WeakMap})),ZM,QM,$M,eN,tN,nN,rN,iN,aN,oN,sN,cN=z((()=>{wM(),ZM=Object.defineProperty,QM=e=>{throw TypeError(e)},$M=(e,t,n)=>t in e?ZM(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,eN=(e,t,n)=>$M(e,t+``,n),tN=(e,t,n)=>t.has(e)||QM(`Cannot `+n),nN=(e,t,n)=>(tN(e,t,`read from private field`),n?n.call(e):t.get(e)),rN=(e,t,n)=>t.has(e)?QM(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),iN=(e,t,n,r)=>(tN(e,t,`write to private field`),t.set(e,n),n),sN=class extends EventTarget{constructor(e){super(),rN(this,aN,null),rN(this,oN,null),eN(this,`onstatechange`,null),iN(this,aN,e.pc),iN(this,oN,new CM({pc:e.pc})),nN(this,aN).addEventListener(`connectionstatechange`,()=>{let e=new Event(`statechange`);this.dispatchEvent(e),this.onstatechange?.(e)})}get maxChannels(){return this.state===`connected`?nN(this,aN).ext_maxDataChannelId:null}get maxMessageSize(){return this.state===`connected`?nN(this,aN)?.ext_maxMessageSize??65536:null}get state(){let e=nN(this,aN).connectionState;return e===`new`||e===`connecting`?e=`connecting`:(e===`disconnected`||e===`failed`||e===`closed`)&&(e=`closed`),e}get transport(){return nN(this,oN)}},aN=new WeakMap,oN=new WeakMap}));function lN(){let e,t,n=new Promise(function(n,r){e=n,t=r});return n.resolve=e,n.reject=t,n}function uN(e){return Math.random().toString(36).substring(2,2+e)}var dN,fN,pN,mN,hN,$,gN,_N,vN,yN,bN,xN,SN,CN,wN,TN,EN,DN,ON,kN,AN,jN=z((()=>{VM(),XM(),Nj(),eM(),dj(),cN(),BA(),dN=Object.defineProperty,fN=e=>{throw TypeError(e)},pN=(e,t,n)=>t in e?dN(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,mN=(e,t,n)=>pN(e,typeof t==`symbol`?t:t+``,n),hN=(e,t,n)=>t.has(e)||fN(`Cannot `+n),$=(e,t,n)=>(hN(e,t,`read from private field`),n?n.call(e):t.get(e)),gN=(e,t,n)=>t.has(e)?fN(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),_N=(e,t,n,r)=>(hN(e,t,`write to private field`),t.set(e,n),n),vN=(e,t,n,r)=>({set _(n){_N(e,t,n)},get _(){return $(e,t,r)}}),AN=class extends EventTarget{constructor(e={iceServers:[],iceTransportPolicy:`all`}){super(),gN(this,yN),gN(this,bN),gN(this,xN),gN(this,SN),gN(this,CN,0),gN(this,wN),gN(this,TN,null),gN(this,EN),gN(this,DN,!1),gN(this,ON,[]),gN(this,kN,[]),mN(this,`onconnectionstatechange`,null),mN(this,`ondatachannel`),mN(this,`onicecandidate`,null),mN(this,`onicecandidateerror`,null),mN(this,`oniceconnectionstatechange`,null),mN(this,`onicegatheringstatechange`,null),mN(this,`onnegotiationneeded`,null),mN(this,`onsignalingstatechange`,null),mN(this,`ontrack`,null),this._checkConfiguration(e),_N(this,wN,e),_N(this,bN,lN()),_N(this,xN,lN()),_N(this,SN,new Set),_N(this,TN,null);try{let t=e?.peerIdentity??`peer-${uN(7)}`;_N(this,yN,e?.peerConnection??new BM(t,{...e,iceServers:e?.iceServers?.map(e=>(Array.isArray(e.urls)?e.urls:[e.urls]).map(t=>{if(e.username&&e.credential){let[n,r]=t.split(/:(.*)/);return`${n}:${e.username}:${e.credential}@${r}`}return t})).flat()??[]}))}catch(e){throw!e||!e.message?new LA(`Unknown error`):new zA(e.message)}$(this,yN).onStateChange(()=>{this.dispatchEvent(new Event(`connectionstatechange`))}),$(this,yN).onIceStateChange(()=>{this.dispatchEvent(new Event(`iceconnectionstatechange`))}),$(this,yN).onSignalingStateChange(()=>{this.dispatchEvent(new Event(`signalingstatechange`))}),$(this,yN).onGatheringStateChange(()=>{this.dispatchEvent(new Event(`icegatheringstatechange`))}),$(this,yN).onDataChannel(e=>{let t=new Mj(e);$(this,SN).add(t),this.dispatchEvent(new lj(`datachannel`,{channel:t}))}),$(this,yN).onLocalDescription((e,t)=>{t===`offer`&&$(this,bN).resolve(new YM({sdp:e,type:t})),t===`answer`&&$(this,xN).resolve(new YM({sdp:e,type:t}))}),$(this,yN).onLocalCandidate((e,t)=>{if(t===`unspec`){$(this,xN).reject(Error(`Invalid description type ${t}`));return}$(this,ON).push(new $j({candidate:e,sdpMid:t})),this.dispatchEvent(new cj(new $j({candidate:e,sdpMid:t})))}),this.addEventListener(`connectionstatechange`,e=>{this.onconnectionstatechange?.(e)}),this.addEventListener(`signalingstatechange`,e=>{this.onsignalingstatechange?.(e)}),this.addEventListener(`iceconnectionstatechange`,e=>{this.oniceconnectionstatechange?.(e)}),this.addEventListener(`icegatheringstatechange`,e=>{this.onicegatheringstatechange?.(e)}),this.addEventListener(`datachannel`,e=>{this.ondatachannel?.(e)}),this.addEventListener(`icecandidate`,e=>{this.onicecandidate?.(e)}),this.addEventListener(`track`,e=>{this.ontrack?.(e)}),this.addEventListener(`negotiationneeded`,e=>{_N(this,DN,!0),this.onnegotiationneeded?.(e)}),_N(this,EN,new sN({pc:this}))}static async generateCertificate(){throw new DOMException(`Not implemented`)}_checkConfiguration(e){if(e&&e.iceServers===void 0&&(e.iceServers=[]),e&&e.iceTransportPolicy===void 0&&(e.iceTransportPolicy=`all`),e?.iceServers===null)throw TypeError(`IceServers cannot be null`);if(Array.isArray(e?.iceServers))for(let t=0;t<e.iceServers.length;t++){if(e.iceServers[t]===null)throw TypeError(`IceServers cannot be null`);if(e.iceServers[t]===void 0)throw TypeError(`IceServers cannot be undefined`);if(Object.keys(e.iceServers[t]).length===0)throw TypeError(`IceServers cannot be empty`);if(typeof e.iceServers[t].urls==`string`&&(e.iceServers[t].urls=[e.iceServers[t].urls]),e.iceServers[t].urls?.some(e=>e==``))throw new zA(`IceServers urls cannot be empty`);if(e.iceServers[t].urls?.some(e=>{try{let t=new URL(e);return!/^(stun:|turn:|turns:)$/.test(t.protocol)}catch{return!0}}))throw new zA(`IceServers urls wrong format`);if(e.iceServers[t].urls?.some(e=>e.startsWith(`turn`))){if(!e.iceServers[t].username)throw new RA(`IceServers username cannot be null`);if(!e.iceServers[t].credential)throw new RA(`IceServers username cannot be undefined`)}if(e.iceServers[t].urls?.length===0)throw new zA(`IceServers urls cannot be empty`)}if(e&&e.iceTransportPolicy&&e.iceTransportPolicy!==`all`&&e.iceTransportPolicy!==`relay`)throw TypeError(`IceTransportPolicy must be either "all" or "relay"`)}setConfiguration(e){this._checkConfiguration(e),_N(this,wN,e)}get ext_maxDataChannelId(){return $(this,yN).maxDataChannelId()}get ext_maxMessageSize(){return $(this,yN).maxMessageSize()}get ext_localCandidates(){return $(this,ON)}get ext_remoteCandidates(){return $(this,kN)}selectedCandidatePair(){return $(this,yN).getSelectedCandidatePair()}get canTrickleIceCandidates(){return $(this,TN)}get connectionState(){return $(this,yN).state()}get iceConnectionState(){let e=$(this,yN).iceState();return e==`completed`&&(e=`connected`),e}get iceGatheringState(){return $(this,yN).gatheringState()}get currentLocalDescription(){return new YM($(this,yN).localDescription())}get currentRemoteDescription(){return new YM($(this,yN).remoteDescription())}get localDescription(){return new YM($(this,yN).localDescription())}get pendingLocalDescription(){return new YM($(this,yN).localDescription())}get pendingRemoteDescription(){return new YM($(this,yN).remoteDescription())}get remoteDescription(){return new YM($(this,yN).remoteDescription())}get sctp(){return $(this,EN)}get signalingState(){return $(this,yN).signalingState()}async addIceCandidate(e){if(!(!e||!e.candidate)){if(e.sdpMid===null&&e.sdpMLineIndex===null||e.sdpMid===void 0&&e.sdpMLineIndex==null)throw TypeError(`sdpMid must be set`);if(e.sdpMid&&e.sdpMid.length>3)throw new IA(`Invalid sdpMid format`);if(!e.sdpMid&&e.sdpMLineIndex>1)throw new IA(`This is only for test case.`);try{$(this,yN).addRemoteCandidate(e.candidate,e.sdpMid??`0`),$(this,kN).push(new $j({candidate:e.candidate,sdpMid:e.sdpMid??`0`}))}catch(e){throw!e||!e.message?new LA(`Unknown error`):e.message.includes(`remote candidate without remote description`)?new FA(e.message):e.message.includes(`Invalid candidate format`)?new IA(e.message):new LA(e.message)}}}addTrack(e,...t){throw new DOMException(`Not implemented`)}addTransceiver(e,t){throw new DOMException(`Not implemented`)}close(){$(this,yN).close()}createAnswer(){return $(this,xN)}createDataChannel(e,t={}){let n={...t,unordered:t.ordered===!1},r=new Mj($(this,yN).createDataChannel(e,n),t);return $(this,SN).add(r),r.addEventListener(`close`,()=>{$(this,SN).delete(r),vN(this,CN)._++}),$(this,DN)??(_N(this,DN,!1),this.dispatchEvent(new Event(`negotiationneeded`))),r}createOffer(){return $(this,bN)}getConfiguration(){return $(this,wN)}getReceivers(){throw new DOMException(`Not implemented`)}getSenders(){throw new DOMException(`Not implemented`)}getStats(){return new Promise(e=>{let t=new Map,n=$(this,yN)?.getSelectedCandidatePair(),r=$(this,yN)?.bytesSent(),i=$(this,yN)?.bytesReceived(),a=$(this,yN)?.rtt();if(!n)return e(t);let o=uN(8),s=`RTCIceCandidate_`+o;t.set(s,{id:s,type:`local-candidate`,timestamp:Date.now(),candidateType:n.local.type,ip:n.local.address,port:n.local.port});let c=uN(8),l=`RTCIceCandidate_`+c;t.set(l,{id:l,type:`remote-candidate`,timestamp:Date.now(),candidateType:n.remote.type,ip:n.remote.address,port:n.remote.port});let u=`RTCIceCandidatePair_`+o+`_`+c;t.set(u,{id:u,type:`candidate-pair`,timestamp:Date.now(),localCandidateId:s,remoteCandidateId:l,state:`succeeded`,nominated:!0,writable:!0,bytesSent:r,bytesReceived:i,totalRoundTripTime:a,currentRoundTripTime:a});let d=`RTCTransport_0_1`;return t.set(d,{id:d,timestamp:Date.now(),type:`transport`,bytesSent:r,bytesReceived:i,dtlsState:`connected`,selectedCandidatePairId:u,selectedCandidatePairChanges:1}),t.set(`P`,{id:`P`,type:`peer-connection`,timestamp:Date.now(),dataChannelsOpened:$(this,SN).size,dataChannelsClosed:$(this,CN)}),e(t)})}getTransceivers(){return[]}removeTrack(){throw new DOMException(`Not implemented`)}restartIce(){throw new DOMException(`Not implemented`)}async setLocalDescription(e){e?.type===`offer`&&$(this,yN).setLocalDescription(e?.type)}async setRemoteDescription(e){if(e.sdp==null)throw new DOMException(`Remote SDP must be set`);$(this,yN).setRemoteDescription(e.sdp,e.type)}},yN=new WeakMap,bN=new WeakMap,xN=new WeakMap,SN=new WeakMap,CN=new WeakMap,wN=new WeakMap,TN=new WeakMap,EN=new WeakMap,DN=new WeakMap,ON=new WeakMap,kN=new WeakMap})),MN=Ae({RTCCertificate:()=>NA,RTCDataChannel:()=>Mj,RTCDataChannelEvent:()=>lj,RTCDtlsTransport:()=>CM,RTCError:()=>QA,RTCIceCandidate:()=>$j,RTCIceTransport:()=>uM,RTCPeerConnection:()=>AN,RTCPeerConnectionIceEvent:()=>cj,RTCSctpTransport:()=>sN,RTCSessionDescription:()=>YM,default:()=>NN}),NN,PN=z((()=>{PA(),Nj(),wM(),eM(),fM(),jN(),cN(),XM(),dj(),$A(),NN={RTCCertificate:NA,RTCDataChannel:Mj,RTCDtlsTransport:CM,RTCIceCandidate:$j,RTCIceTransport:uM,RTCPeerConnection:AN,RTCSctpTransport:sN,RTCSessionDescription:YM,RTCDataChannelEvent:lj,RTCPeerConnectionIceEvent:cj,RTCError:QA}})),FN=B(((e,t)=>{function n(e,t,n,r){Object.defineProperty(e,t,{get:n,set:r,enumerable:!0,configurable:!0})}n(t.exports,`unpack`,()=>a),n(t.exports,`pack`,()=>o),n(t.exports,`Packer`,()=>c);var r=class{constructor(){this.encoder=new TextEncoder,this._pieces=[],this._parts=[]}append_buffer(e){this.flush(),this._parts.push(e)}append(e){this._pieces.push(e)}flush(){if(this._pieces.length>0){let e=new Uint8Array(this._pieces);this._parts.push(e),this._pieces=[]}}toArrayBuffer(){let e=[];for(let t of this._parts)e.push(t);return i(e).buffer}};function i(e){let t=0;for(let n of e)t+=n.byteLength;let n=new Uint8Array(t),r=0;for(let t of e){let e=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);n.set(e,r),r+=t.byteLength}return n}function a(e){return new s(e).unpack()}function o(e){let t=new c,n=t.pack(e);return n instanceof Promise?n.then(()=>t.getBuffer()):t.getBuffer()}var s=class{constructor(e){this.index=0,this.dataBuffer=e,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}unpack(){let e=this.unpack_uint8();if(e<128)return e;if((e^224)<32)return(e^224)-32;let t;if((t=e^160)<=15)return this.unpack_raw(t);if((t=e^176)<=15)return this.unpack_string(t);if((t=e^144)<=15)return this.unpack_array(t);if((t=e^128)<=15)return this.unpack_map(t);switch(e){case 192:return null;case 193:return;case 194:return!1;case 195:return!0;case 202:return this.unpack_float();case 203:return this.unpack_double();case 204:return this.unpack_uint8();case 205:return this.unpack_uint16();case 206:return this.unpack_uint32();case 207:return this.unpack_uint64();case 208:return this.unpack_int8();case 209:return this.unpack_int16();case 210:return this.unpack_int32();case 211:return this.unpack_int64();case 212:return;case 213:return;case 214:return;case 215:return;case 216:return t=this.unpack_uint16(),this.unpack_string(t);case 217:return t=this.unpack_uint32(),this.unpack_string(t);case 218:return t=this.unpack_uint16(),this.unpack_raw(t);case 219:return t=this.unpack_uint32(),this.unpack_raw(t);case 220:return t=this.unpack_uint16(),this.unpack_array(t);case 221:return t=this.unpack_uint32(),this.unpack_array(t);case 222:return t=this.unpack_uint16(),this.unpack_map(t);case 223:return t=this.unpack_uint32(),this.unpack_map(t)}}unpack_uint8(){let e=this.dataView[this.index]&255;return this.index++,e}unpack_uint16(){let e=this.read(2),t=(e[0]&255)*256+(e[1]&255);return this.index+=2,t}unpack_uint32(){let e=this.read(4),t=((e[0]*256+e[1])*256+e[2])*256+e[3];return this.index+=4,t}unpack_uint64(){let e=this.read(8),t=((((((e[0]*256+e[1])*256+e[2])*256+e[3])*256+e[4])*256+e[5])*256+e[6])*256+e[7];return this.index+=8,t}unpack_int8(){let e=this.unpack_uint8();return e<128?e:e-256}unpack_int16(){let e=this.unpack_uint16();return e<32768?e:e-65536}unpack_int32(){let e=this.unpack_uint32();return e<2**31?e:e-2**32}unpack_int64(){let e=this.unpack_uint64();return e<2**63?e:e-2**64}unpack_raw(e){if(this.length<this.index+e)throw Error(`BinaryPackFailure: index is out of range ${this.index} ${e} ${this.length}`);let t=this.dataBuffer.slice(this.index,this.index+e);return this.index+=e,t}unpack_string(e){let t=this.read(e),n=0,r=``,i,a;for(;n<e;)i=t[n],i<160?(a=i,n++):(i^192)<32?(a=(i&31)<<6|t[n+1]&63,n+=2):(i^224)<16?(a=(i&15)<<12|(t[n+1]&63)<<6|t[n+2]&63,n+=3):(a=(i&7)<<18|(t[n+1]&63)<<12|(t[n+2]&63)<<6|t[n+3]&63,n+=4),r+=String.fromCodePoint(a);return this.index+=e,r}unpack_array(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=this.unpack();return t}unpack_map(e){let t={};for(let n=0;n<e;n++){let e=this.unpack();t[e]=this.unpack()}return t}unpack_float(){let e=this.unpack_uint32(),t=e>>31,n=(e>>23&255)-127,r=e&8388607|8388608;return(t===0?1:-1)*r*2**(n-23)}unpack_double(){let e=this.unpack_uint32(),t=this.unpack_uint32(),n=e>>31,r=(e>>20&2047)-1023,i=(e&1048575|1048576)*2**(r-20)+t*2**(r-52);return(n===0?1:-1)*i}read(e){let t=this.index;if(t+e<=this.length)return this.dataView.subarray(t,t+e);throw Error(`BinaryPackFailure: read index out of range`)}},c=class{getBuffer(){return this._bufferBuilder.toArrayBuffer()}pack(e){if(typeof e==`string`)this.pack_string(e);else if(typeof e==`number`)Math.floor(e)===e?this.pack_integer(e):this.pack_double(e);else if(typeof e==`boolean`)e===!0?this._bufferBuilder.append(195):e===!1&&this._bufferBuilder.append(194);else if(e===void 0)this._bufferBuilder.append(192);else if(typeof e==`object`)if(e===null)this._bufferBuilder.append(192);else{let t=e.constructor;if(e instanceof Array){let t=this.pack_array(e);if(t instanceof Promise)return t.then(()=>this._bufferBuilder.flush())}else if(e instanceof ArrayBuffer)this.pack_bin(new Uint8Array(e));else if(`BYTES_PER_ELEMENT`in e){let t=e;this.pack_bin(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}else if(e instanceof Date)this.pack_string(e.toString());else if(e instanceof Blob)return e.arrayBuffer().then(e=>{this.pack_bin(new Uint8Array(e)),this._bufferBuilder.flush()});else if(t==Object||t.toString().startsWith(`class`)){let t=this.pack_object(e);if(t instanceof Promise)return t.then(()=>this._bufferBuilder.flush())}else throw Error(`Type "${t.toString()}" not yet supported`)}else throw Error(`Type "${typeof e}" not yet supported`);this._bufferBuilder.flush()}pack_bin(e){let t=e.length;if(t<=15)this.pack_uint8(160+t);else if(t<=65535)this._bufferBuilder.append(218),this.pack_uint16(t);else if(t<=4294967295)this._bufferBuilder.append(219),this.pack_uint32(t);else throw Error(`Invalid length`);this._bufferBuilder.append_buffer(e)}pack_string(e){let t=this._textEncoder.encode(e),n=t.length;if(n<=15)this.pack_uint8(176+n);else if(n<=65535)this._bufferBuilder.append(216),this.pack_uint16(n);else if(n<=4294967295)this._bufferBuilder.append(217),this.pack_uint32(n);else throw Error(`Invalid length`);this._bufferBuilder.append_buffer(t)}pack_array(e){let t=e.length;if(t<=15)this.pack_uint8(144+t);else if(t<=65535)this._bufferBuilder.append(220),this.pack_uint16(t);else if(t<=4294967295)this._bufferBuilder.append(221),this.pack_uint32(t);else throw Error(`Invalid length`);let n=r=>{if(r<t){let t=this.pack(e[r]);return t instanceof Promise?t.then(()=>n(r+1)):n(r+1)}};return n(0)}pack_integer(e){if(e>=-32&&e<=127)this._bufferBuilder.append(e&255);else if(e>=0&&e<=255)this._bufferBuilder.append(204),this.pack_uint8(e);else if(e>=-128&&e<=127)this._bufferBuilder.append(208),this.pack_int8(e);else if(e>=0&&e<=65535)this._bufferBuilder.append(205),this.pack_uint16(e);else if(e>=-32768&&e<=32767)this._bufferBuilder.append(209),this.pack_int16(e);else if(e>=0&&e<=4294967295)this._bufferBuilder.append(206),this.pack_uint32(e);else if(e>=-2147483648&&e<=2147483647)this._bufferBuilder.append(210),this.pack_int32(e);else if(e>=-0x8000000000000000&&e<=0x8000000000000000)this._bufferBuilder.append(211),this.pack_int64(e);else if(e>=0&&e<=0x10000000000000000)this._bufferBuilder.append(207),this.pack_uint64(e);else throw Error(`Invalid integer`)}pack_double(e){let t=0;e<0&&(t=1,e=-e);let n=Math.floor(Math.log(e)/Math.LN2),r=e/2**n-1,i=Math.floor(r*2**52),a=2**32,o=t<<31|n+1023<<20|i/a&1048575,s=i%a;this._bufferBuilder.append(203),this.pack_int32(o),this.pack_int32(s)}pack_object(e){let t=Object.keys(e),n=t.length;if(n<=15)this.pack_uint8(128+n);else if(n<=65535)this._bufferBuilder.append(222),this.pack_uint16(n);else if(n<=4294967295)this._bufferBuilder.append(223),this.pack_uint32(n);else throw Error(`Invalid length`);let r=n=>{if(n<t.length){let i=t[n];if(e.hasOwnProperty(i)){this.pack(i);let t=this.pack(e[i]);if(t instanceof Promise)return t.then(()=>r(n+1))}return r(n+1)}};return r(0)}pack_uint8(e){this._bufferBuilder.append(e)}pack_uint16(e){this._bufferBuilder.append(e>>8),this._bufferBuilder.append(e&255)}pack_uint32(e){let t=e&4294967295;this._bufferBuilder.append((t&4278190080)>>>24),this._bufferBuilder.append((t&16711680)>>>16),this._bufferBuilder.append((t&65280)>>>8),this._bufferBuilder.append(t&255)}pack_uint64(e){let t=e/2**32,n=e%2**32;this._bufferBuilder.append((t&4278190080)>>>24),this._bufferBuilder.append((t&16711680)>>>16),this._bufferBuilder.append((t&65280)>>>8),this._bufferBuilder.append(t&255),this._bufferBuilder.append((n&4278190080)>>>24),this._bufferBuilder.append((n&16711680)>>>16),this._bufferBuilder.append((n&65280)>>>8),this._bufferBuilder.append(n&255)}pack_int8(e){this._bufferBuilder.append(e&255)}pack_int16(e){this._bufferBuilder.append((e&65280)>>8),this._bufferBuilder.append(e&255)}pack_int32(e){this._bufferBuilder.append(e>>>24&255),this._bufferBuilder.append((e&16711680)>>>16),this._bufferBuilder.append((e&65280)>>>8),this._bufferBuilder.append(e&255)}pack_int64(e){let t=Math.floor(e/2**32),n=e%2**32;this._bufferBuilder.append((t&4278190080)>>>24),this._bufferBuilder.append((t&16711680)>>>16),this._bufferBuilder.append((t&65280)>>>8),this._bufferBuilder.append(t&255),this._bufferBuilder.append((n&4278190080)>>>24),this._bufferBuilder.append((n&16711680)>>>16),this._bufferBuilder.append((n&65280)>>>8),this._bufferBuilder.append(n&255)}constructor(){this._bufferBuilder=new r,this._textEncoder=new TextEncoder}}})),IN=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.compactObject=h,e.deprecated=f,e.detectBrowser=p,e.disableLog=l,e.disableWarnings=u,e.extractVersion=s,e.filterStats=_,e.log=d,e.walkStats=g,e.wrapPeerConnectionEvent=c;function t(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function n(e){var t=r(e,`string`);return i(t)==`symbol`?t:t+``}function r(e,t){if(i(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(i(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function i(e){"@babel/helpers - typeof";return i=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},i(e)}var a=!0,o=!0;function s(e,t,n){var r=e.match(t);return r&&r.length>=n&&parseFloat(r[n],10)}function c(e,t,n){if(e.RTCPeerConnection){if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,`addEventListener`).writable){d(`Unable to polyfill events`);return}var r=e.RTCPeerConnection.prototype,i=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return i.apply(this,arguments);var a=function(e){var t=n(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,a),i.apply(this,[e,a])};var a=r.removeEventListener;r.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(n))return a.apply(this,arguments);var r=this._eventMap[t].get(n);return this._eventMap[t].delete(n),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,a.apply(this,[e,r])},Object.defineProperty(r,`on`+t,{get:function(){return this[`_on`+t]},set:function(e){this[`_on`+t]&&(this.removeEventListener(t,this[`_on`+t]),delete this[`_on`+t]),e&&this.addEventListener(t,this[`_on`+t]=e)},enumerable:!0,configurable:!0})}}function l(e){return typeof e==`boolean`?(a=e,e?`adapter.js logging disabled`:`adapter.js logging enabled`):Error(`Argument type: `+i(e)+`. Please use a boolean.`)}function u(e){return typeof e==`boolean`?(o=!e,`adapter.js deprecation warnings `+(e?`disabled`:`enabled`)):Error(`Argument type: `+i(e)+`. Please use a boolean.`)}function d(){if((typeof window>`u`?`undefined`:i(window))===`object`){if(a)return;typeof console<`u`&&typeof console.log==`function`&&console.log.apply(console,arguments)}}function f(e,t){o&&console.warn(e+` is deprecated, please use `+t+` instead.`)}function p(e){var t={browser:null,version:null};if(e===void 0||!e.navigator||!e.navigator.userAgent)return t.browser=`Not a browser.`,t;var n=e.navigator;if(n.userAgentData&&n.userAgentData.brands){var r=n.userAgentData.brands.find(function(e){return e.brand===`Chromium`});if(r)return{browser:`chrome`,version:parseInt(r.version,10)}}if(n.mozGetUserMedia)t.browser=`firefox`,t.version=parseInt(s(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser=`chrome`,t.version=parseInt(s(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else if(e.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser=`safari`,t.version=parseInt(s(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&`currentDirection`in e.RTCRtpTransceiver.prototype,t._safariVersion=s(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return t.browser=`Not a supported browser.`,t;return t}function m(e){return Object.prototype.toString.call(e)===`[object Object]`}function h(e){return m(e)?Object.keys(e).reduce(function(n,r){var i=m(e[r]),a=i?h(e[r]):e[r],o=i&&!Object.keys(a).length;return a===void 0||o?n:Object.assign(n,t({},r,a))},{}):e}function g(e,t,n){!t||n.has(t.id)||(n.set(t.id,t),Object.keys(t).forEach(function(r){r.endsWith(`Id`)?g(e,e.get(t[r]),n):r.endsWith(`Ids`)&&t[r].forEach(function(t){g(e,e.get(t),n)})}))}function _(e,t,n){var r=n?`outbound-rtp`:`inbound-rtp`,i=new Map;if(t===null)return i;var a=[];return e.forEach(function(e){e.type===`track`&&e.trackIdentifier===t.id&&a.push(e)}),a.forEach(function(t){e.forEach(function(n){n.type===r&&n.trackId===t.id&&g(e,n,i)})}),i}})),LN=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shimGetUserMedia=a;var t=n(IN());function n(e,t){if(typeof WeakMap==`function`)var i=new WeakMap,a=new WeakMap;return(n=function(e,t){if(!t&&e&&e.__esModule)return e;var n,o,s={__proto__:null,default:e};if(e===null||r(e)!=`object`&&typeof e!=`function`)return s;if(n=t?a:i){if(n.has(e))return n.get(e);n.set(e,s)}for(var c in e)c!=="default"&&{}.hasOwnProperty.call(e,c)&&((o=(n=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,c))&&(o.get||o.set)?n(s,c,o):s[c]=e[c]);return s})(e,t)}function r(e){"@babel/helpers - typeof";return r=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},r(e)}var i=t.log;function a(e,t){var n=e&&e.navigator;if(n.mediaDevices){var a=function(e){if(r(e)!==`object`||e.mandatory||e.optional)return e;var t={};return Object.keys(e).forEach(function(n){if(!(n===`require`||n===`advanced`||n===`mediaSource`)){var i=r(e[n])===`object`?e[n]:{ideal:e[n]};i.exact!==void 0&&typeof i.exact==`number`&&(i.min=i.max=i.exact);var a=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):t===`deviceId`?`sourceId`:t};if(i.ideal!==void 0){t.optional=t.optional||[];var o={};typeof i.ideal==`number`?(o[a(`min`,n)]=i.ideal,t.optional.push(o),o={},o[a(`max`,n)]=i.ideal,t.optional.push(o)):(o[a(``,n)]=i.ideal,t.optional.push(o))}i.exact!==void 0&&typeof i.exact!=`number`?(t.mandatory=t.mandatory||{},t.mandatory[a(``,n)]=i.exact):[`min`,`max`].forEach(function(e){i[e]!==void 0&&(t.mandatory=t.mandatory||{},t.mandatory[a(e,n)]=i[e])})}}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},o=function(e,o){if(t.version>=61)return o(e);if(e=JSON.parse(JSON.stringify(e)),e&&r(e.audio)===`object`){var s=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};e=JSON.parse(JSON.stringify(e)),s(e.audio,`autoGainControl`,`googAutoGainControl`),s(e.audio,`noiseSuppression`,`googNoiseSuppression`),e.audio=a(e.audio)}if(e&&r(e.video)===`object`){var c=e.video.facingMode;c&&=r(c)===`object`?c:{ideal:c};var l=t.version<66;if(c&&(c.exact===`user`||c.exact===`environment`||c.ideal===`user`||c.ideal===`environment`)&&!(n.mediaDevices.getSupportedConstraints&&n.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete e.video.facingMode;var u;if(c.exact===`environment`||c.ideal===`environment`?u=[`back`,`rear`]:(c.exact===`user`||c.ideal===`user`)&&(u=[`front`]),u)return n.mediaDevices.enumerateDevices().then(function(t){t=t.filter(function(e){return e.kind===`videoinput`});var n=t.find(function(e){return u.some(function(t){return e.label.toLowerCase().includes(t)})});return!n&&t.length&&u.includes(`back`)&&(n=t[t.length-1]),n&&(e.video.deviceId=c.exact?{exact:n.deviceId}:{ideal:n.deviceId}),e.video=a(e.video),i(`chrome: `+JSON.stringify(e)),o(e)})}e.video=a(e.video)}return i(`chrome: `+JSON.stringify(e)),o(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:`NotAllowedError`,PermissionDismissedError:`NotAllowedError`,InvalidStateError:`NotAllowedError`,DevicesNotFoundError:`NotFoundError`,ConstraintNotSatisfiedError:`OverconstrainedError`,TrackStartError:`NotReadableError`,MediaDeviceFailedDueToShutdown:`NotAllowedError`,MediaDeviceKillSwitchOn:`NotAllowedError`,TabCaptureError:`AbortError`,ScreenCaptureError:`AbortError`,DeviceCaptureError:`AbortError`}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString:function(){return this.name+(this.message&&`: `)+this.message}}};if(n.getUserMedia=function(e,t,r){o(e,function(e){n.webkitGetUserMedia(e,t,function(e){r&&r(s(e))})})}.bind(n),n.mediaDevices.getUserMedia){var c=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(e){return o(e,function(e){return c(e).then(function(t){if(e.audio&&!t.getAudioTracks().length||e.video&&!t.getVideoTracks().length)throw t.getTracks().forEach(function(e){e.stop()}),new DOMException(``,`NotFoundError`);return t},function(e){return Promise.reject(s(e))})})}}}}})),RN=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.fixNegotiationNeeded=h,e.shimAddTrackRemoveTrack=p,e.shimAddTrackRemoveTrackWithNative=f,e.shimGetSendersWithDtmf=u,Object.defineProperty(e,"shimGetUserMedia",{enumerable:!0,get:function(){return n.shimGetUserMedia}}),e.shimMediaStream=c,e.shimOnTrack=l,e.shimPeerConnection=m,e.shimSenderReceiverGetStats=d;var t=r(IN()),n=LN();function r(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,i=new WeakMap;return(r=function(e,t){if(!t&&e&&e.__esModule)return e;var r,a,o={__proto__:null,default:e};if(e===null||s(e)!=`object`&&typeof e!=`function`)return o;if(r=t?i:n){if(r.has(e))return r.get(e);r.set(e,o)}for(var c in e)c!=="default"&&{}.hasOwnProperty.call(e,c)&&((a=(r=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,c))&&(a.get||a.set)?r(o,c,a):o[c]=e[c]);return o})(e,t)}function i(e,t,n){return(t=a(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e){var t=o(e,`string`);return s(t)==`symbol`?t:t+``}function o(e,t){if(s(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(s(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function s(e){"@babel/helpers - typeof";return s=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},s(e)}function c(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function l(e,n){if(!(n.version>102))if(s(e)===`object`&&e.RTCPeerConnection&&!(`ontrack`in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(e){this._ontrack&&this.removeEventListener(`track`,this._ontrack),this.addEventListener(`track`,this._ontrack=e)},enumerable:!0,configurable:!0});var r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){var t=this;return this._ontrackpoly||(this._ontrackpoly=function(n){n.stream.addEventListener(`addtrack`,function(r){var i=e.RTCPeerConnection.prototype.getReceivers?t.getReceivers().find(function(e){return e.track&&e.track.id===r.track.id}):{track:r.track},a=new Event(`track`);a.track=r.track,a.receiver=i,a.transceiver={receiver:i},a.streams=[n.stream],t.dispatchEvent(a)}),n.stream.getTracks().forEach(function(r){var i=e.RTCPeerConnection.prototype.getReceivers?t.getReceivers().find(function(e){return e.track&&e.track.id===r.id}):{track:r},a=new Event(`track`);a.track=r,a.receiver=i,a.transceiver={receiver:i},a.streams=[n.stream],t.dispatchEvent(a)})},this.addEventListener(`addstream`,this._ontrackpoly)),r.apply(this,arguments)}}else t.wrapPeerConnectionEvent(e,`track`,function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e})}function u(e){if(s(e)===`object`&&e.RTCPeerConnection&&!(`getSenders`in e.RTCPeerConnection.prototype)&&`createDTMFSender`in e.RTCPeerConnection.prototype){var t=function(e,t){return{track:t,get dtmf(){return this._dtmf===void 0&&(t.kind===`audio`?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){var i=n.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};var r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);var t=this._senders.indexOf(e);t!==-1&&this._senders.splice(t,1)}}var i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){var n=this;this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(function(e){n._senders.push(t(n,e))})};var a=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;this._senders=this._senders||[],a.apply(this,[e]),e.getTracks().forEach(function(e){var n=t._senders.find(function(t){return t.track===e});n&&t._senders.splice(t._senders.indexOf(n),1)})}}else if(s(e)===`object`&&e.RTCPeerConnection&&`getSenders`in e.RTCPeerConnection.prototype&&`createDTMFSender`in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!(`dtmf`in e.RTCRtpSender.prototype)){var o=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){var e=this,t=o.apply(this,[]);return t.forEach(function(t){return t._pc=e}),t},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind===`audio`?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function d(e,n){if(!(n.version>=67)&&s(e)===`object`&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver){if(!(`getStats`in e.RTCRtpSender.prototype)){var r=e.RTCPeerConnection.prototype.getSenders;r&&(e.RTCPeerConnection.prototype.getSenders=function(){var e=this,t=r.apply(this,[]);return t.forEach(function(t){return t._pc=e}),t});var i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){var e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){var e=this;return this._pc.getStats().then(function(n){return t.filterStats(n,e.track,!0)})}}if(!(`getStats`in e.RTCRtpReceiver.prototype)){var a=e.RTCPeerConnection.prototype.getReceivers;a&&(e.RTCPeerConnection.prototype.getReceivers=function(){var e=this,t=a.apply(this,[]);return t.forEach(function(t){return t._pc=e}),t}),t.wrapPeerConnectionEvent(e,`track`,function(e){return e.receiver._pc=e.srcElement,e}),e.RTCRtpReceiver.prototype.getStats=function(){var e=this;return this._pc.getStats().then(function(n){return t.filterStats(n,e.track,!1)})}}if(`getStats`in e.RTCRtpSender.prototype&&`getStats`in e.RTCRtpReceiver.prototype){var o=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){var t=arguments[0],n,r,i;return this.getSenders().forEach(function(e){e.track===t&&(n?i=!0:n=e)}),this.getReceivers().forEach(function(e){return e.track===t&&(r?i=!0:r=e),e.track===t}),i||n&&r?Promise.reject(new DOMException(`There are more than one sender or receiver for the track.`,`InvalidAccessError`)):n?n.getStats():r?r.getStats():Promise.reject(new DOMException(`There is no sender or receiver for the track.`,`InvalidAccessError`))}return o.apply(this,arguments)}}}}function f(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(t){return e._shimmedLocalStreams[t][0]})};var t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var r=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?this._shimmedLocalStreams[n.id].indexOf(r)===-1&&this._shimmedLocalStreams[n.id].push(r):this._shimmedLocalStreams[n.id]=[n,r],r};var n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){var t=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(function(e){if(t.getSenders().find(function(t){return t.track===e}))throw new DOMException(`Track already exists.`,`InvalidAccessError`)});var r=this.getSenders();n.apply(this,arguments);var i=this.getSenders().filter(function(e){return r.indexOf(e)===-1});this._shimmedLocalStreams[e.id]=[e].concat(i)};var r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};var i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){var t=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(function(n){var r=t._shimmedLocalStreams[n].indexOf(e);r!==-1&&t._shimmedLocalStreams[n].splice(r,1),t._shimmedLocalStreams[n].length===1&&delete t._shimmedLocalStreams[n]}),i.apply(this,arguments)}}function p(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return f(e);var n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this,t=n.apply(this);return this._reverseStreams=this._reverseStreams||{},t.map(function(t){return e._reverseStreams[t.id]})};var r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){var n=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(function(e){if(n.getSenders().find(function(t){return t.track===e}))throw new DOMException(`Track already exists.`,`InvalidAccessError`)}),!this._reverseStreams[t.id]){var i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}r.apply(this,[t])};var a=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},a.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){var r=this;if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);var i=[].slice.call(arguments,1);if(i.length!==1||!i[0].getTracks().find(function(e){return e===t}))throw new DOMException(`The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.`,`NotSupportedError`);if(this.getSenders().find(function(e){return e.track===t}))throw new DOMException(`Track already exists.`,`InvalidAccessError`);this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var a=this._streams[n.id];if(a)a.addTrack(t),Promise.resolve().then(function(){r.dispatchEvent(new Event(`negotiationneeded`))});else{var o=new e.MediaStream([t]);this._streams[n.id]=o,this._reverseStreams[o.id]=n,this.addStream(o)}return this.getSenders().find(function(e){return e.track===t})};function o(e,t){var n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(function(t){var r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(i.id,`g`),r.id)}),new RTCSessionDescription({type:t.type,sdp:n})}function s(e,t){var n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(function(t){var r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(r.id,`g`),i.id)}),new RTCSessionDescription({type:t.type,sdp:n})}[`createOffer`,`createAnswer`].forEach(function(t){var n=e.RTCPeerConnection.prototype[t],r=i({},t,function(){var e=this,t=arguments;return arguments.length&&typeof arguments[0]==`function`?n.apply(this,[function(n){var r=o(e,n);t[0].apply(null,[r])},function(e){t[1]&&t[1].apply(null,e)},arguments[2]]):n.apply(this,arguments).then(function(t){return o(e,t)})});e.RTCPeerConnection.prototype[t]=r[t]});var c=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type||(arguments[0]=s(this,arguments[0])),c.apply(this,arguments)};var l=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,`localDescription`);Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get:function(){var e=l.get.apply(this);return e.type===``?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){var t=this;if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);if(!e._pc)throw new DOMException(`Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.`,`TypeError`);if(e._pc!==this)throw new DOMException(`Sender was not created by this connection.`,`InvalidAccessError`);this._streams=this._streams||{};var n;Object.keys(this._streams).forEach(function(r){t._streams[r].getTracks().find(function(t){return e.track===t})&&(n=t._streams[r])}),n&&(n.getTracks().length===1?this.removeStream(this._reverseStreams[n.id]):n.removeTrack(e.track),this.dispatchEvent(new Event(`negotiationneeded`)))}}function m(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){var n=e.RTCPeerConnection.prototype[t],r=i({},t,function(){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)});e.RTCPeerConnection.prototype[t]=r[t]})}function h(e,n){n.version>102||t.wrapPeerConnectionEvent(e,`negotiationneeded`,function(e){var t=e.target;if(!((n.version<72||t.getConfiguration&&t.getConfiguration().sdpSemantics===`plan-b`)&&t.signalingState!==`stable`))return e})}})),zN=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shimGetUserMedia=i;var t=n(IN());function n(e,t){if(typeof WeakMap==`function`)var i=new WeakMap,a=new WeakMap;return(n=function(e,t){if(!t&&e&&e.__esModule)return e;var n,o,s={__proto__:null,default:e};if(e===null||r(e)!=`object`&&typeof e!=`function`)return s;if(n=t?a:i){if(n.has(e))return n.get(e);n.set(e,s)}for(var c in e)c!=="default"&&{}.hasOwnProperty.call(e,c)&&((o=(n=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,c))&&(o.get||o.set)?n(s,c,o):s[c]=e[c]);return s})(e,t)}function r(e){"@babel/helpers - typeof";return r=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},r(e)}function i(e,n){var i=e&&e.navigator,a=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,n,r){t.deprecated(`navigator.getUserMedia`,`navigator.mediaDevices.getUserMedia`),i.mediaDevices.getUserMedia(e).then(n,r)},!(n.version>55&&`autoGainControl`in i.mediaDevices.getSupportedConstraints())){var o=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},s=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(e){return r(e)===`object`&&r(e.audio)===`object`&&(e=JSON.parse(JSON.stringify(e)),o(e.audio,`autoGainControl`,`mozAutoGainControl`),o(e.audio,`noiseSuppression`,`mozNoiseSuppression`)),s(e)},a&&a.prototype.getSettings){var c=a.prototype.getSettings;a.prototype.getSettings=function(){var e=c.apply(this,arguments);return o(e,`mozAutoGainControl`,`autoGainControl`),o(e,`mozNoiseSuppression`,`noiseSuppression`),e}}if(a&&a.prototype.applyConstraints){var l=a.prototype.applyConstraints;a.prototype.applyConstraints=function(e){return this.kind===`audio`&&r(e)===`object`&&(e=JSON.parse(JSON.stringify(e)),o(e,`autoGainControl`,`mozAutoGainControl`),o(e,`noiseSuppression`,`mozNoiseSuppression`)),l.apply(this,[e])}}}}})),BN=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shimGetDisplayMedia=t;function t(e,t){e.navigator.mediaDevices&&`getDisplayMedia`in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){var r=new DOMException(`getDisplayMedia without video constraints is undefined`);return r.name=`NotFoundError`,r.code=8,Promise.reject(r)}return n.video===!0?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})}})),VN=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shimAddTransceiver=S,e.shimCreateAnswer=T,e.shimCreateOffer=w,Object.defineProperty(e,"shimGetDisplayMedia",{enumerable:!0,get:function(){return r.shimGetDisplayMedia}}),e.shimGetParameters=C,e.shimGetStats=_,Object.defineProperty(e,"shimGetUserMedia",{enumerable:!0,get:function(){return n.shimGetUserMedia}}),e.shimOnTrack=h,e.shimPeerConnection=g,e.shimRTCDataChannel=x,e.shimReceiverGetStats=y,e.shimRemoveStream=b,e.shimSenderGetStats=v;var t=i(IN()),n=zN(),r=BN();function i(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(i=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||m(e)!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(var s in e)s!=="default"&&{}.hasOwnProperty.call(e,s)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,s))&&(a.get||a.set)?i(o,s,a):o[s]=e[s]);return o})(e,t)}function a(e){return l(e)||c(e)||s(e)||o()}function o(){throw TypeError(`Invalid attempt to spread non-iterable instance.
|
|
@@ -1030,4 +1030,4 @@ Expecting one of '${n.join(`', '`)}'`);return this._lifeCycleHooks[e]?this._life
|
|
|
1030
1030
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
1031
1031
|
- ${t?`searched for local subcommand relative to directory '${t}'`:`no directory for search for local subcommand, use .executableDir() to supply a custom directory`}`;throw Error(r)}_executeSubCommand(e,t){t=t.slice();let o=!1,s=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function l(e,t){let n=r.resolve(e,t);if(i.existsSync(n))return n;if(s.includes(r.extname(t)))return;let a=s.find(e=>i.existsSync(`${n}${e}`));if(a)return`${n}${a}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let u=e._executableFile||`${this._name}-${e._name}`,d=this._executableDir||``;if(this._scriptPath){let e;try{e=i.realpathSync(this._scriptPath)}catch{e=this._scriptPath}d=r.resolve(r.dirname(e),d)}if(d){let t=l(d,u);if(!t&&!e._executableFile&&this._scriptPath){let n=r.basename(this._scriptPath,r.extname(this._scriptPath));n!==this._name&&(t=l(d,`${n}-${e._name}`))}u=t||u}o=s.includes(r.extname(u));let f;a.platform===`win32`?(this._checkForMissingExecutable(u,d,e._name),t.unshift(u),t=h(a.execArgv).concat(t),f=n.spawn(a.execPath,t,{stdio:`inherit`})):o?(t.unshift(u),t=h(a.execArgv).concat(t),f=n.spawn(a.argv[0],t,{stdio:`inherit`})):f=n.spawn(u,t,{stdio:`inherit`}),f.killed||[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`].forEach(e=>{a.on(e,()=>{f.killed===!1&&f.exitCode===null&&f.kill(e)})});let p=this._exitCallback;f.on(`close`,e=>{e??=1,p?p(new c(e,`commander.executeSubCommandAsync`,`(close)`)):a.exit(e)}),f.on(`error`,t=>{if(t.code===`ENOENT`)this._checkForMissingExecutable(u,d,e._name);else if(t.code===`EACCES`)throw Error(`'${u}' not executable`);if(!p)a.exit(1);else{let e=new c(1,`commander.executeSubCommandAsync`,`(error)`);e.nestedError=t,p(e)}}),this.runningCommand=f}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0}),r._prepareForParse();let i;return i=this._chainOrCallSubCommandHook(i,r,`preSubcommand`),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(e,t,n)=>{let r=t;if(t!==null&&e.parseArg){let i=`error: command-argument value '${t}' is invalid for argument '${e.name()}'.`;r=this._callParseArg(e,t,n,i)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let i=n.defaultValue;n.variadic?r<this.args.length?(i=this.args.slice(r),n.parseArg&&(i=i.reduce((t,r)=>e(n,r,t),n.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],n.parseArg&&(i=e(n,i,n.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e?.then&&typeof e.then==`function`?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(e=>e._lifeCycleHooks[t]!==void 0).forEach(e=>{e._lifeCycleHooks[t].forEach(t=>{r.push({hookedCommand:e,callback:t})})}),t===`postAction`&&r.reverse(),r.forEach(e=>{n=this._chainOrCall(n,()=>e.callback(e.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(e=>{r=this._chainOrCall(r,()=>e(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let n;return n=this._chainOrCallHooks(n,`preAction`),n=this._chainOrCall(n,()=>this._actionHandler(this.processedArgs)),this.parent&&(n=this._chainOrCall(n,()=>{this.parent.emit(i,e,t)})),n=this._chainOrCallHooks(n,`postAction`),n}if(this.parent?.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,e,t);this.listenerCount(`command:*`)?this.emit(`command:*`,e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(e=>{let t=e.attributeName();return this.getOptionValue(t)!==void 0&&this.getOptionValueSource(t)!=="default"});e.filter(e=>e.conflictsWith.length>0).forEach(t=>{let n=e.find(e=>t.conflictsWith.includes(e.attributeName()));n&&this._conflictingOption(t,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t;function i(e){return e.length>1&&e[0]===`-`}let a=e=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(e)?!this._getCommandAndAncestors().some(e=>e.options.map(e=>e.short).some(e=>/^-\d$/.test(e))):!1,o=null,s=null,c=0;for(;c<e.length||s;){let l=s??e[c++];if(s=null,l===`--`){r===n&&r.push(l),r.push(...e.slice(c));break}if(o&&(!i(l)||a(l))){this.emit(`option:${o.name()}`,l);continue}if(o=null,i(l)){let t=this._findOption(l);if(t){if(t.required){let n=e[c++];n===void 0&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,n)}else if(t.optional){let n=null;c<e.length&&(!i(e[c])||a(e[c]))&&(n=e[c++]),this.emit(`option:${t.name()}`,n)}else this.emit(`option:${t.name()}`);o=t.variadic?t:null;continue}}if(l.length>2&&l[0]===`-`&&l[1]!==`-`){let e=this._findOption(`-${l[1]}`);if(e){e.required||e.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${e.name()}`,l.slice(2)):(this.emit(`option:${e.name()}`),s=`-${l.slice(2)}`);continue}}if(/^--[^=]+=/.test(l)){let e=l.indexOf(`=`),t=this._findOption(l.slice(0,e));if(t&&(t.required||t.optional)){this.emit(`option:${t.name()}`,l.slice(e+1));continue}}if(r===t&&i(l)&&!(this.commands.length===0&&a(l))&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),n.push(...e.slice(c));break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l,...e.slice(c));break}else if(this._defaultCommandName){n.push(l,...e.slice(c));break}}if(this._passThroughOptions){r.push(l,...e.slice(c));break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
1032
1032
|
`),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,i=n.code||`commander.error`;this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in a.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,a.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new f(this.options),t=e=>this.getOptionValue(e)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(e));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],`implied`)})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:`commander.missingArgument`})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(e,t){let n=e=>{let t=e.attributeName(),n=this.getOptionValue(t),r=this.options.find(e=>e.negate&&t===e.attributeName()),i=this.options.find(e=>!e.negate&&t===e.attributeName());return r&&(r.presetArg===void 0&&n===!1||r.presetArg!==void 0&&n===r.presetArg)?r:i||e},r=e=>{let t=n(e),r=t.attributeName();return this.getOptionValueSource(r)===`env`?`environment variable '${t.envVar}'`:`option '${t.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:`commander.conflictingOption`})}unknownOption(e){if(this._allowUnknownOption)return;let t=``;if(e.startsWith(`--`)&&this._showSuggestionAfterError){let n=[],r=this;do{let e=r.createHelp().visibleOptions(r).filter(e=>e.long).map(e=>e.long);n=n.concat(e),r=r.parent}while(r&&!r._enablePositionalOptions);t=p(e,n)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:`commander.unknownOption`})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?``:`s`,r=`error: too many arguments${this.parent?` for '${this.name()}'`:``}. Expected ${t} argument${n} but got ${e.length}.`;this.error(r,{code:`commander.excessArguments`})}unknownCommand(){let e=this.args[0],t=``;if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(e=>{n.push(e.name()),e.alias()&&n.push(e.alias())}),t=p(e,n)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:`commander.unknownCommand`})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t||=`-V, --version`,n||=`output the version number`;let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on(`option:`+r.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,`commander.version`,e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error(`Command alias can't be the same as its name`);let n=this.parent?._findCommand(e);if(n){let t=[n.name()].concat(n.aliases()).join(`|`);throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>s(e));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?e:[]).join(` `)}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}helpGroup(e){return e===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=e,this)}commandsGroup(e){return e===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=e,this)}optionsGroup(e){return e===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=r.basename(e,r.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);return n.hasColors?r:this._outputConfiguration.stripColor(r)}_getOutputContext(e){e||={};let t=!!e.error,n,r,i;return t?(n=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(n=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:t,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),n(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;typeof e==`function`&&(t=e,e=void 0);let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit(`beforeAllHelp`,r)),this.emit(`beforeHelp`,r);let i=this.helpInformation({error:n.error});if(t&&(i=t(i),typeof i!=`string`&&!E.isBuffer(i)))throw Error(`outputHelp callback must return a string or a Buffer`);n.write(i),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,r),this._getCommandAndAncestors().forEach(e=>e.emit(`afterAllHelp`,r))}helpOption(e,t){return typeof e==`boolean`?(e?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(e??`-h, --help`,t??`display help for command`),(e||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(a.exitCode??0);t===0&&e&&typeof e!=`function`&&e.error&&(t=1),this._exit(t,`commander.help`,`(outputHelp)`)}addHelpText(e,t){let n=[`beforeAll`,`before`,`after`,`afterAll`];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
|
|
1033
|
-
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function h(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function g(){if(a.env.NO_COLOR||a.env.FORCE_COLOR===`0`||a.env.FORCE_COLOR===`false`)return!1;if(a.env.FORCE_COLOR||a.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=m,e.useColor=g}));const{program:xP,createCommand:SP,createArgument:CP,createOption:wP,CommanderError:TP,InvalidArgumentError:EP,InvalidOptionArgumentError:DP,Command:OP,Argument:kP,Option:AP,Help:jP}=Me(B((e=>{let{Argument:t}=gP(),{Command:n}=bP(),{CommanderError:r,InvalidArgumentError:i}=hP(),{Help:a}=_P(),{Option:o}=vP();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i}))(),1).default,MP=u(import.meta.url),NP=o.dirname(MP);function PP(){let e=new OP;e.name(`shadow-claw`).description(`ShadowClaw Dev Server`).argument(`[port]`,`Port to listen on`).option(`-v, --verbose`,`Enable verbose request/proxy logging`,!1).option(`--host <host>`,`Bind host/IP`).option(`--ip <host>`,`Bind host/IP (alias)`).option(`--bind-ip <host>`,`Bind host/IP (alias)`).option(`--cors-mode <mode>`,`CORS policy: localhost | private | all`,`localhost`).option(`--cors-allow-origin <origin>`,`Explicit allowed origins (repeatable)`,(e,t)=>t.concat(e.split(`,`).map(e=>e.trim())),[]).option(`--peerjs`,`Enable built-in PeerJS signaling server`,!1).option(`--allow-private-proxy`,`Allow the /proxy endpoint to reach private/loopback addresses (disables SSRF block)`,!1).option(`--root-path <path>`,`Directory containing static assets to serve`).option(`--database-dir <path>`,`Directory where SQLite databases are stored`).option(`--control-token <token>`,`Secret token for control-plane authentication`),e.parse();let t=e.opts(),n=e.args,a=(r.SHADOWCLAW_ROOT_PATH||r.SHADOWCLAW_PUBLIC_DIR||``).trim(),s=o.join(NP,`..`),c=o.join(NP,`public`),l=h.existsSync(c),u=l?c:s,d=t.rootPath?o.resolve(t.rootPath):a?o.resolve(a):u,f=l?o.join(NP,`..`):o.join(NP,`..`,`..`),p=(r.SHADOWCLAW_DATABASE_DIR||``).trim(),m=t.databaseDir?o.resolve(t.databaseDir):p?o.resolve(f,p):o.join(f,`database`),g=8888;n[0]&&(g=parseInt(n[0],10)),(g<1024||g>65535)&&(console.error(`Port must be between 1024 and 65535.`),i(1));let _=r.SHADOWCLAW_DEV_IP||r.SHADOWCLAW_HOST||r.DEV_IP||r.HOST||``,v=(t.host||t.ip||t.bindIp||_||`127.0.0.1`).trim();v||(console.error(`Bind host cannot be empty. Use --host <value> or set SHADOWCLAW_DEV_IP.`),i(1));let y=(r.SHADOWCLAW_CORS_MODE||``).toLowerCase().trim(),b=(t.corsMode||y||`localhost`).trim();[`localhost`,`private`,`all`].includes(b)||(console.error(`Invalid CORS mode. Use --cors-mode localhost|private|all or SHADOWCLAW_CORS_MODE.`),i(1));let x=[...(r.SHADOWCLAW_CORS_ALLOWED_ORIGINS||`https://xt-ml.github.io`).split(`,`).map(e=>e.trim()).filter(Boolean),...t.corsAllowOrigin],S=t.peerjs||[`1`,`true`,`yes`].includes((r.SHADOWCLAW_PEERJS||``).toLowerCase().trim()),C=t.allowPrivateProxy||[`1`,`true`,`yes`].includes((r.SHADOWCLAW_ALLOW_PRIVATE_PROXY||``).toLowerCase().trim()),w=(r.SHADOWCLAW_CONTROL_TOKEN||``).trim(),T=t.controlToken?t.controlToken.trim():w||void 0;return{port:g,bindHost:v,corsMode:b,allowedOrigins:new Set(x),verbose:t.verbose||!1,peerjs:S,rootPath:d,databaseDir:m,controlToken:T,allowPrivateProxy:C}}async function FP(e){let t=e||PP(),{app:n,scheduler:r}=eA(t);await f.check(t.port,t.bindHost)&&(console.error(`Port ${t.port} is currently being used. Try passing a different port as the first argument.`),i(1)),r.start();let o=a.createServer(n),s=TA({httpServer:o,app:n,token:t.controlToken,verbose:t.verbose}),c=null;return t.peerjs&&(bA(o,n),c=new mP({host:t.bindHost,port:t.port,path:`/peerjs`,verbose:t.verbose})),new Promise(e=>{o.listen(t.port,t.bindHost,()=>{console.log(`Server running at http://${t.bindHost}:${t.port}`),t.bindHost===`127.0.0.1`?console.log(`Bind host source: default (127.0.0.1). Use --host/--ip or SHADOWCLAW_DEV_IP to override.`):console.log(`Bind host source: inferred (${t.bindHost})`),console.log(`CORS mode: ${t.corsMode}${t.allowedOrigins.size>0?` (with explicit allowlist)`:``}`),t.allowedOrigins.size>0&&console.log(`CORS allowlist origins: ${Array.from(t.allowedOrigins).join(`, `)}`),console.log(`Control plane active at http://${t.bindHost}:${t.port}/api/control/events (SSE) and ws://${t.bindHost}:${t.port}/ws/control (WebSocket)`),console.log(`Control token: ${s.getToken()}`),t.peerjs&&(console.log(`PeerJS signaling server enabled (routes at /peerjs/*)`),c&&c.start().then(e=>{console.log(`Server WebRTC peer active with ID: ${e}`)}).catch(e=>{t.verbose&&console.warn(`[server] ServerPeer start notice: ${e.message||String(e)}`)})),t.verbose&&console.log(`Verbose logging enabled.`),e(o)})})}n.argv[1]&&o.resolve(n.argv[1])===o.resolve(u(import.meta.url))&&FP().catch(e=>{console.error(e),i(1)});export{FP as startServer};
|
|
1033
|
+
Expecting one of '${n.join(`', '`)}'`);let r=`${e}Help`;return this.on(r,e=>{let n;n=typeof t==`function`?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function h(e){return e.map(e=>{if(!e.startsWith(`--inspect`))return e;let t,n=`127.0.0.1`,r=`9229`,i;return(i=e.match(/^(--inspect(-brk)?)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],r=i[4]):(t=i[1],/^\d+$/.test(i[3])?r=i[3]:n=i[3]):t=i[1],t&&r!==`0`?`${t}=${n}:${parseInt(r)+1}`:e})}function g(){if(a.env.NO_COLOR||a.env.FORCE_COLOR===`0`||a.env.FORCE_COLOR===`false`)return!1;if(a.env.FORCE_COLOR||a.env.CLICOLOR_FORCE!==void 0)return!0}e.Command=m,e.useColor=g}));const{program:xP,createCommand:SP,createArgument:CP,createOption:wP,CommanderError:TP,InvalidArgumentError:EP,InvalidOptionArgumentError:DP,Command:OP,Argument:kP,Option:AP,Help:jP}=Me(B((e=>{let{Argument:t}=gP(),{Command:n}=bP(),{CommanderError:r,InvalidArgumentError:i}=hP(),{Help:a}=_P(),{Option:o}=vP();e.program=new n,e.createCommand=e=>new n(e),e.createOption=(e,t)=>new o(e,t),e.createArgument=(e,n)=>new t(e,n),e.Command=n,e.Option=o,e.Argument=t,e.Help=a,e.CommanderError=r,e.InvalidArgumentError=i,e.InvalidOptionArgumentError=i}))(),1).default,MP=u(import.meta.url),NP=o.dirname(MP);function PP(){let e=new OP;e.name(`shadow-claw`).description(`ShadowClaw Dev Server`).argument(`[port]`,`Port to listen on`).option(`-v, --verbose`,`Enable verbose request/proxy logging`,!1).option(`--host <host>`,`Bind host/IP`).option(`--ip <host>`,`Bind host/IP (alias)`).option(`--bind-ip <host>`,`Bind host/IP (alias)`).option(`--cors-mode <mode>`,`CORS policy: localhost | private | all`,`localhost`).option(`--cors-allow-origin <origin>`,`Explicit allowed origins (repeatable)`,(e,t)=>t.concat(e.split(`,`).map(e=>e.trim())),[]).option(`--peerjs`,`Enable built-in PeerJS signaling server`,!1).option(`--allow-private-proxy`,`Allow the /proxy endpoint to reach private/loopback addresses (disables SSRF block)`,!1).option(`--root-path <path>`,`Directory containing static assets to serve`).option(`--database-dir <path>`,`Directory where SQLite databases are stored`).option(`--control-token <token>`,`Secret token for control-plane authentication`),e.parse();let t=e.opts(),n=e.args,a=(r.SHADOWCLAW_ROOT_PATH||r.SHADOWCLAW_PUBLIC_DIR||``).trim(),s=o.join(NP,`..`),c=o.join(NP,`public`),l=h.existsSync(c),u=l?c:s,d=t.rootPath?o.resolve(t.rootPath):a?o.resolve(a):u,f=l?o.join(NP,`..`):o.join(NP,`..`,`..`),p=(r.SHADOWCLAW_DATABASE_DIR||``).trim(),m=t.databaseDir?o.resolve(t.databaseDir):p?o.resolve(f,p):o.join(f,`database`),g=8888;n[0]&&(g=parseInt(n[0],10)),(g<1024||g>65535)&&(console.error(`Port must be between 1024 and 65535.`),i(1));let _=r.SHADOWCLAW_DEV_IP||r.SHADOWCLAW_HOST||r.DEV_IP||r.HOST||``,v=(t.host||t.ip||t.bindIp||_||`127.0.0.1`).trim();v||(console.error(`Bind host cannot be empty. Use --host <value> or set SHADOWCLAW_DEV_IP.`),i(1));let y=(r.SHADOWCLAW_CORS_MODE||``).toLowerCase().trim(),b=(t.corsMode||y||`localhost`).trim();[`localhost`,`private`,`all`].includes(b)||(console.error(`Invalid CORS mode. Use --cors-mode localhost|private|all or SHADOWCLAW_CORS_MODE.`),i(1));let x=[...(r.SHADOWCLAW_CORS_ALLOWED_ORIGINS||`https://xt-ml.github.io`).split(`,`).map(e=>e.trim()).filter(Boolean),...t.corsAllowOrigin],S=t.peerjs||[`1`,`true`,`yes`].includes((r.SHADOWCLAW_PEERJS||``).toLowerCase().trim()),C=t.allowPrivateProxy||[`1`,`true`,`yes`].includes((r.SHADOWCLAW_ALLOW_PRIVATE_PROXY||``).toLowerCase().trim()),w=(r.SHADOWCLAW_CONTROL_TOKEN||``).trim(),T=t.controlToken?t.controlToken.trim():w||void 0;return{port:g,bindHost:v,corsMode:b,allowedOrigins:new Set(x),verbose:t.verbose||!1,peerjs:S,rootPath:d,databaseDir:m,controlToken:T,allowPrivateProxy:C}}async function FP(e){let t=e||PP(),{app:n,scheduler:r}=eA(t);await f.check(t.port,t.bindHost)&&(console.error(`Port ${t.port} is currently being used. Try passing a different port as the first argument.`),i(1)),r.start();let o=a.createServer(n),s=TA({httpServer:o,app:n,token:t.controlToken,verbose:t.verbose,allowedOrigins:t.allowedOrigins,corsMode:t.corsMode}),c=null;return t.peerjs&&(bA(o,n),c=new mP({host:t.bindHost,port:t.port,path:`/peerjs`,verbose:t.verbose})),new Promise(e=>{o.listen(t.port,t.bindHost,()=>{console.log(`Server running at http://${t.bindHost}:${t.port}`),t.bindHost===`127.0.0.1`?console.log(`Bind host source: default (127.0.0.1). Use --host/--ip or SHADOWCLAW_DEV_IP to override.`):console.log(`Bind host source: inferred (${t.bindHost})`),console.log(`CORS mode: ${t.corsMode}${t.allowedOrigins.size>0?` (with explicit allowlist)`:``}`),t.allowedOrigins.size>0&&console.log(`CORS allowlist origins: ${Array.from(t.allowedOrigins).join(`, `)}`),console.log(`Control plane active at http://${t.bindHost}:${t.port}/api/control/events (SSE) and ws://${t.bindHost}:${t.port}/ws/control (WebSocket)`),console.log(`Control token: ${s.getToken()}`),t.peerjs&&(console.log(`PeerJS signaling server enabled (routes at /peerjs/*)`),c&&c.start().then(e=>{console.log(`Server WebRTC peer active with ID: ${e}`)}).catch(e=>{t.verbose&&console.warn(`[server] ServerPeer start notice: ${e.message||String(e)}`)})),t.verbose&&console.log(`Verbose logging enabled.`),e(o)})})}n.argv[1]&&o.resolve(n.argv[1])===o.resolve(u(import.meta.url))&&FP().catch(e=>{console.error(e),i(1)});export{FP as startServer};
|