@timqi/pier 0.0.4 → 0.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -6
- package/dist/agent/events.js +6 -1
- package/dist/agent/pi.js +28 -3
- package/dist/channels/chunk.js +34 -0
- package/dist/channels/control.js +6 -12
- package/dist/channels/dedup.js +45 -0
- package/dist/channels/lark-api.js +233 -0
- package/dist/channels/lark-outbound.js +101 -0
- package/dist/channels/lark-panel.js +95 -0
- package/dist/channels/lark-render.js +107 -0
- package/dist/channels/lark.js +501 -0
- package/dist/channels/lines.js +19 -0
- package/dist/channels/panel.js +4 -0
- package/dist/channels/receipts.js +15 -0
- package/dist/channels/routes.js +0 -1
- package/dist/channels/runtime.js +5 -1
- package/dist/channels/slack-api.js +4 -2
- package/dist/channels/slack-panel.js +3 -6
- package/dist/channels/slack-render.js +3 -23
- package/dist/channels/slack.js +39 -72
- package/dist/channels/telegram-api.js +4 -2
- package/dist/channels/telegram-panel.js +3 -3
- package/dist/channels/telegram.js +55 -51
- package/dist/channels/types.js +9 -0
- package/dist/cli.js +3 -1
- package/dist/core/inbox.js +67 -1
- package/dist/core/types.js +4 -0
- package/dist/db.js +83 -20
- package/dist/main.js +5 -0
- package/dist/service.js +1 -1
- package/dist/web/auth.js +36 -9
- package/dist/web/public/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
- package/dist/web/public/assets/ghostty-web-ODXT71Ln.js +13 -0
- package/dist/web/public/assets/index-BUNGxtMe.css +2 -0
- package/dist/web/public/assets/index-QPYgeBhQ.js +90 -0
- package/dist/web/public/index.html +10 -2
- package/dist/web/server.js +86 -19
- package/dist/web/session-state.js +59 -25
- package/dist/web/terminal.js +334 -0
- package/docs/deploy.md +33 -21
- package/package.json +10 -2
- package/dist/web/public/assets/index-B3MvJUJP.js +0 -90
- package/dist/web/public/assets/index-CwBoxtXP.css +0 -2
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var l=(e,t,n=`POST`)=>fetch(e,{method:n,headers:{"content-type":`application/json`},body:JSON.stringify(t)});async function u(e,t){return(await e.json().catch(()=>({}))).error??`${t} (${e.status})`}async function d(e,t,n,r){let i=window.prompt(e);if(!i?.trim())return{sent:!1};try{let e=await l(t,{message:i,...n});return{sent:!0,...e.ok?{}:{error:await u(e,r)}}}catch(e){return{sent:!0,error:`${r}: ${String(e)}`}}}function f(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 p(e){if(Array.isArray(e))return e}function m(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 h(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
2
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function g(e,t){return p(e)||m(e,t)||_(e,t)||h()}function _(e,t){if(e){if(typeof e==`string`)return f(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)?f(e,t):void 0}}var v=Object.entries,y=Object.setPrototypeOf,b=Object.isFrozen,x=Object.getPrototypeOf,S=Object.getOwnPropertyDescriptor,C=Object.freeze,w=Object.seal,T=Object.create,E=typeof Reflect<`u`&&Reflect,D=E.apply,O=E.construct;C||=function(e){return e},w||=function(e){return e},D||=function(e,t){var n=[...arguments].slice(2);return e.apply(t,n)},O||=function(e){return new e(...[...arguments].slice(1))};var k=F(Array.prototype.forEach),A=F(Array.prototype.lastIndexOf),ee=F(Array.prototype.pop),j=F(Array.prototype.push),M=F(Array.prototype.splice),N=Array.isArray,te=F(String.prototype.toLowerCase),ne=F(String.prototype.toString),re=F(String.prototype.match),ie=F(String.prototype.replace),ae=F(String.prototype.indexOf),oe=F(String.prototype.trim),se=F(Number.prototype.toString),ce=F(Boolean.prototype.toString),le=typeof BigInt>`u`?null:F(BigInt.prototype.toString),ue=typeof Symbol>`u`?null:F(Symbol.prototype.toString),de=F(Object.prototype.hasOwnProperty),fe=F(Object.prototype.toString),P=F(RegExp.prototype.test),pe=me(TypeError);function F(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return D(e,t,n)}}function me(e){return function(){return O(e,[...arguments])}}function I(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:te;if(y&&y(e,null),!N(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(b(t)||(t[r]=e),i=e)}e[i]=!0}return e}function he(e){for(let t=0;t<e.length;t++)de(e,t)||(e[t]=null);return e}function ge(e){let t=T(null);for(let r of v(e)){var n=g(r,2);let i=n[0],a=n[1];de(e,i)&&(t[i]=N(a)?he(a):a&&typeof a==`object`&&a.constructor===Object?ge(a):a)}return t}function _e(e){switch(typeof e){case`string`:return e;case`number`:return se(e);case`boolean`:return ce(e);case`bigint`:return le?le(e):`0`;case`symbol`:return ue?ue(e):`Symbol()`;case`undefined`:return fe(e);case`function`:case`object`:{if(e===null)return fe(e);let t=e,n=ve(t,`toString`);if(typeof n==`function`){let e=n(t);return typeof e==`string`?e:fe(e)}return fe(e)}default:return fe(e)}}function ve(e,t){for(;e!==null;){let n=S(e,t);if(n){if(n.get)return F(n.get);if(typeof n.value==`function`)return F(n.value)}e=x(e)}function n(){return null}return n}function ye(e){try{return P(e,``),!0}catch{return!1}}var be=C(`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(`.`)),xe=C(`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(`.`)),Se=C([`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`]),Ce=C([`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`]),we=C(`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(`.`)),Te=C([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),Ee=C([`#text`]),De=C(`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(`.`)),Oe=C(`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.pointer-events.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.vector-effect.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(`.`)),ke=C(`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(`.`)),Ae=C([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),je=w(/{{[\w\W]*|^[\w\W]*}}/g),Me=w(/<%[\w\W]*|^[\w\W]*%>/g),Ne=w(/\${[\w\W]*/g),Pe=w(/^data-[\-\w.\u00B7-\uFFFF]+$/),Fe=w(/^aria-[\-\w]+$/),Ie=w(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Le=w(/^(?:\w+script|data):/i),Re=w(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ze=w(/^html$/i),Be=w(/^[a-z][.\w]*(-[.\w]+)+$/i),Ve=w(/<[/\w!]/g),He=w(/<[/\w]/g),Ue=w(/<\/no(script|embed|frames)/i),We=w(/\/>/i),Ge={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Ke=[`style`,`script`,`xmp`,`iframe`,`noembed`,`noframes`,`plaintext`,`noscript`],qe=C(I({},Ke)),Je=function(){let e={};return k(Ke,t=>{e[t]=w(RegExp(`</`+t+`(?=[\\t\\n\\f\\r />])`,`i`))}),C(e)}(),Ye=function(){return typeof window>`u`?null:window},Xe=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}},Ze=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},Qe=function(e,t,n,r){return de(e,t)&&N(e[t])?I(r.base?ge(r.base):{},e[t],r.transform):n},$e=function(e,t,n){let r=de(e,t)?e[t]:void 0;return r&&typeof r==`object`?ge(r):n()};function et(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Ye(),t=e=>et(e);if(t.version=`3.4.14`,t.removed=[],!e||!e.document||e.document.nodeType!==Ge.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=ve(d,`cloneNode`),p=ve(d,`remove`),m=ve(d,`nextSibling`),h=ve(d,`childNodes`),g=ve(d,`parentNode`),_=ve(d,`shadowRoot`),y=ve(d,`attributes`),b=o&&o.prototype?ve(o.prototype,`nodeType`):null,x=o&&o.prototype?ve(o.prototype,`nodeName`):null,S=o&&o.prototype?ve(o.prototype,`ownerDocument`):null,E=function(e){return b?b(e):e.nodeType},D=function(e){return x?x(e):e.nodeName};if(typeof a==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let O,se=``,ce,le=!1,ue=0,fe=function(){if(ue>0)throw pe(`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.`)},F=function(e){fe(),ue++;try{return O.createHTML(e)}finally{ue--}},me=function(e){fe(),ue++;try{return O.createScriptURL(e)}finally{ue--}},he=function(){return le||=(ce=Xe(u,i),!0),ce},Ke=n,tt=Ke.implementation,nt=Ke.createNodeIterator,rt=Ke.createDocumentFragment,it=Ke.getElementsByTagName,at=r.importNode,L=Ze();t.isSupported=typeof v==`function`&&typeof g==`function`&&tt&&tt.createHTMLDocument!==void 0;let R=je,ot=Me,st=Ne,ct=Pe,lt=Fe,ut=Le,dt=Re,ft=Be,pt=Ie,z=null,mt=I({},[...be,...xe,...Se,...we,...Ee]),B=null,ht=I({},[...De,...Oe,...ke,...Ae]),gt=Object.seal(T(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}})),_t=null,vt=null,yt=Object.seal(T(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),bt=!0,xt=!0,St=!1,Ct=!0,wt=!1,Tt=!0,Et=!1,Dt=!1,Ot=null,kt=null,At=!1,jt=!1,Mt=!1,Nt=!1,Pt=!0,Ft=!1,It=`user-content-`,Lt=!0,Rt=!1,zt={},Bt=null,Vt=I({},`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(`.`)),Ht=null,Ut=I({},[`audio`,`video`,`img`,`source`,`image`,`track`]),Wt=null,Gt=I({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),Kt=`http://www.w3.org/1998/Math/MathML`,qt=`http://www.w3.org/2000/svg`,Jt=`http://www.w3.org/1999/xhtml`,Yt=Jt,Xt=!1,Zt=null,Qt=I({},[Kt,qt,Jt],ne),$t=C([`mi`,`mo`,`mn`,`ms`,`mtext`]),en=I({},$t),tn=C([`annotation-xml`]),nn=I({},tn),rn=I({},[`title`,`style`,`font`,`a`,`script`]),an=null,on=[`application/xhtml+xml`,`text/html`],V=null,sn=null,cn=n.createElement(`form`),ln=function(e){return e instanceof RegExp||e instanceof Function},un=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(sn&&sn===e)return;(!e||typeof e!=`object`)&&(e={}),e=ge(e),an=on.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,V=an===`application/xhtml+xml`?ne:te,z=Qe(e,`ALLOWED_TAGS`,mt,{transform:V}),B=Qe(e,`ALLOWED_ATTR`,ht,{transform:V}),Zt=Qe(e,`ALLOWED_NAMESPACES`,Qt,{transform:ne}),Wt=Qe(e,`ADD_URI_SAFE_ATTR`,Gt,{transform:V,base:Gt}),Ht=Qe(e,`ADD_DATA_URI_TAGS`,Ut,{transform:V,base:Ut}),Bt=Qe(e,`FORBID_CONTENTS`,Vt,{transform:V}),_t=Qe(e,`FORBID_TAGS`,ge({}),{transform:V}),vt=Qe(e,`FORBID_ATTR`,ge({}),{transform:V}),zt=de(e,`USE_PROFILES`)?e.USE_PROFILES&&typeof e.USE_PROFILES==`object`?ge(e.USE_PROFILES):e.USE_PROFILES:!1,bt=e.ALLOW_ARIA_ATTR!==!1,xt=e.ALLOW_DATA_ATTR!==!1,St=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Ct=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,wt=e.SAFE_FOR_TEMPLATES||!1,Tt=e.SAFE_FOR_XML!==!1,Et=e.WHOLE_DOCUMENT||!1,jt=e.RETURN_DOM||!1,Mt=e.RETURN_DOM_FRAGMENT||!1,Nt=e.RETURN_TRUSTED_TYPE||!1,At=e.FORCE_BODY||!1,Pt=e.SANITIZE_DOM!==!1,Ft=e.SANITIZE_NAMED_PROPS||!1,Lt=e.KEEP_CONTENT!==!1,Rt=e.IN_PLACE||!1,pt=ye(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:Ie,Yt=typeof e.NAMESPACE==`string`?e.NAMESPACE:Jt,en=$e(e,`MATHML_TEXT_INTEGRATION_POINTS`,()=>I({},$t)),nn=$e(e,`HTML_INTEGRATION_POINTS`,()=>I({},tn));let t=$e(e,`CUSTOM_ELEMENT_HANDLING`,()=>T(null));if(gt=T(null),de(t,`tagNameCheck`)&&ln(t.tagNameCheck)&&(gt.tagNameCheck=t.tagNameCheck),de(t,`attributeNameCheck`)&&ln(t.attributeNameCheck)&&(gt.attributeNameCheck=t.attributeNameCheck),de(t,`allowCustomizedBuiltInElements`)&&typeof t.allowCustomizedBuiltInElements==`boolean`&&(gt.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),w(gt),wt&&(xt=!1),Mt&&(jt=!0),zt&&(z=I({},Ee),B=T(null),zt.html===!0&&(I(z,be),I(B,De)),zt.svg===!0&&(I(z,xe),I(B,Oe),I(B,Ae)),zt.svgFilters===!0&&(I(z,Se),I(B,Oe),I(B,Ae)),zt.mathMl===!0&&(I(z,we),I(B,ke),I(B,Ae))),yt.tagCheck=null,yt.attributeCheck=null,de(e,`ADD_TAGS`)&&(typeof e.ADD_TAGS==`function`?yt.tagCheck=e.ADD_TAGS:N(e.ADD_TAGS)&&(z===mt&&(z=ge(z)),I(z,e.ADD_TAGS,V))),de(e,`ADD_ATTR`)&&(typeof e.ADD_ATTR==`function`?yt.attributeCheck=e.ADD_ATTR:N(e.ADD_ATTR)&&(B===ht&&(B=ge(B)),I(B,e.ADD_ATTR,V))),de(e,`ADD_FORBID_CONTENTS`)&&N(e.ADD_FORBID_CONTENTS)&&(Bt===Vt&&(Bt=ge(Bt)),I(Bt,e.ADD_FORBID_CONTENTS,V)),Lt&&(z[`#text`]=!0),Et&&I(z,[`html`,`head`,`body`]),z.table&&(I(z,[`tbody`]),delete _t.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw pe(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw pe(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);let t=O;O=e.TRUSTED_TYPES_POLICY;try{se=F(``)}catch(e){throw O=t,e}}else e.TRUSTED_TYPES_POLICY===null?(O=void 0,se=``):(O===void 0&&(O=he()),O&&typeof se==`string`&&(se=F(``)));C&&C(e),sn=e},dn=I({},[...xe,...Se,...Ce]),fn=I({},[...we,...Te]),pn=function(e,t,n){return t.namespaceURI===Jt?e===`svg`:t.namespaceURI===Kt?e===`svg`&&(n===`annotation-xml`||en[n]):!!dn[e]},mn=function(e,t,n){return t.namespaceURI===Jt?e===`math`:t.namespaceURI===qt?e===`math`&&nn[n]:!!fn[e]},hn=function(e,t,n){return t.namespaceURI===qt&&!nn[n]||t.namespaceURI===Kt&&!en[n]?!1:!fn[e]&&(rn[e]||!dn[e])},gn=function(e){let t=g(e);(!t||!t.tagName)&&(t={namespaceURI:Yt,tagName:`template`});let n=te(e.tagName),r=te(t.tagName);return Zt[e.namespaceURI]?e.namespaceURI===qt?pn(n,t,r):e.namespaceURI===Kt?mn(n,t,r):e.namespaceURI===Jt?hn(n,t,r):!!(an===`application/xhtml+xml`&&Zt[e.namespaceURI]):!1},_n=function(e){j(t.removed,{element:e});try{g(e).removeChild(e)}catch{if(p(e),!g(e))throw pe(`a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place`)}},vn=function(e,t,n){try{e.removeAttributeNode(t)}catch{try{e.removeAttribute(n)}catch{}}},yn=function(e){Sn(e);let t=h(e);if(t){let e=[];k(t,t=>{j(e,t)}),k(e,e=>{try{p(e)}catch{}})}let n=y(e);if(n)for(let t=n.length-1;t>=0;--t){let r=n[t],i=r&&r.name;typeof i==`string`&&vn(e,r,i)}},bn=function(e,n,r){if(!r)try{r=n.getAttributeNode(e)}catch{r=null}j(t.removed,{attribute:r||null,from:n});try{r?n.removeAttributeNode(r):n.removeAttribute(e)}catch{try{n.removeAttribute(e)}catch{}}if(e===`is`){if(jt||Mt)try{_n(n)}catch{}else try{n.setAttribute(e,``)}catch{}}},xn=function(e){let t=y(e);if(t)for(let n=t.length-1;n>=0;--n){let r=t[n],i=r&&r.name;typeof i!=`string`||B[V(i)]||vn(e,r,i)}},Sn=function(e){let t=[e];for(;t.length>0;){let e=t.pop();E(e)===Ge.element&&xn(e);let n=h(e);if(n)for(let e=n.length-1;e>=0;--e)t.push(n[e])}},Cn=function(e,t){return Tt?e===`patchsrc`||e===`for`&&t!==`label`&&t!==`output`:!1},wn=function(e){if(!Tt)return;let t=[e];for(;t.length>0;){let e=t.pop(),n=E(e);if(n===Ge.processingInstruction||n===Ge.comment&&P(He,e.data)){try{p(e)}catch{}continue}if(n===Ge.element){let t=e,n=V(D(e));try{t.hasAttribute&&t.hasAttribute(`patchsrc`)&&t.removeAttribute(`patchsrc`),t.hasAttribute&&t.hasAttribute(`for`)&&Cn(`for`,n)&&t.removeAttribute(`for`)}catch{}}let r=h(e);if(r)for(let e=r.length-1;e>=0;--e)t.push(r[e])}},Tn=function(e){let t=null,r=null;if(At)e=`<remove></remove>`+e;else{let t=re(e,/^[\r\n\t ]+/);r=t&&t[0]}an===`application/xhtml+xml`&&Yt===Jt&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=O?F(e):e;if(Yt===Jt)try{t=new l().parseFromString(i,an)}catch{}if(!t||!t.documentElement){t=tt.createDocument(Yt,`template`,null);try{t.documentElement.innerHTML=Xt?se:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),Yt===Jt?it.call(t,Et?`html`:`body`)[0]:Et?t.documentElement:a},En=function(e){let t=S?S(e):e.ownerDocument;return nt.call(t||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Dn=function(e){return e=ie(e,R,` `),e=ie(e,ot,` `),e=ie(e,st,` `),e},On=function(e){e.normalize();let t=S?S(e):e.ownerDocument,n=nt.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=Dn(r.data),r=n.nextNode();let i=e.querySelectorAll?.call(e,`template`);i&&k(i,e=>{An(e.content)&&On(e.content)})},kn=function(e){let t=x?x(e):null;return typeof t!=`string`||V(t)!==`form`?!1:typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||e.attributes!==y(e)||typeof e.removeAttribute!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`||e.nodeType!==b(e)||e.childNodes!==h(e)},An=function(e){if(!b||typeof e!=`object`||!e)return!1;try{return b(e)===Ge.documentFragment}catch{return!1}},jn=function(e){if(!b||typeof e!=`object`||!e)return!1;try{return typeof b(e)==`number`}catch{return!1}};function H(e,n,r){e.length!==0&&k(e,e=>{e.call(t,n,r,sn)})}let Mn=function(e,t){return!!(Tt&&e.hasChildNodes()&&!jn(e.firstElementChild)&&P(Ve,e.textContent)&&P(Ve,e.innerHTML)||Tt&&e.namespaceURI===Jt&&qe[t]&&(jn(e.firstElementChild)||typeof e.textContent==`string`&&P(Je[t],e.textContent))||e.nodeType===Ge.processingInstruction||Tt&&e.nodeType===Ge.comment&&P(He,e.data))},Nn=function(e,t){return e instanceof RegExp?P(e,t):e instanceof Function&&!!e(t,...[...arguments].slice(2))},U=function(e,t,n){if(!_t[t]&&zn(t)&&Nn(gt.tagNameCheck,t))return!1;if(Lt&&!Bt[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 _n(e),!0},Pn=function(e,t,n,r){return e.length===0?t:t===n||t===r?ge(t):t},Fn=function(e,t){return e===t||g(e)!==null?!1:(Rt&&Sn(e),!0)},In=function(e,n){if(H(L.beforeSanitizeElements,e,null),Fn(e,n))return!0;if(kn(e))return _n(e),!0;let r=V(D(e));if(z=Pn(L.uponSanitizeElement,z,mt,Ot),H(L.uponSanitizeElement,e,{tagName:r,allowedTags:z}),Fn(e,n))return!0;if(Mn(e,r))return _n(e),!0;if(_t[r]||!(yt.tagCheck instanceof Function&&yt.tagCheck(r))&&!z[r]){let t=U(e,r,n);return t===!1&&H(L.afterSanitizeElements,e,null),t}if(E(e)===Ge.element&&!gn(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&P(Ue,e.innerHTML))return _n(e),!0;if(wt&&e.nodeType===Ge.text){let n=Dn(e.textContent);e.textContent!==n&&(j(t.removed,{element:e.cloneNode()}),e.textContent=n)}return H(L.afterSanitizeElements,e,null),!1},Ln=function(e,t,r){if(vt[t]||Cn(t,e)||Pt&&(t===`id`||t===`name`)&&(r in n||r in cn))return!1;let i=B[t]||yt.attributeCheck instanceof Function&&yt.attributeCheck(t,e);return xt&&P(ct,t)||bt&&P(lt,t)?!0:i?Wt[t]||P(pt,ie(r,dt,``))||(t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&ae(r,`data:`)===0&&Ht[e]||St&&!P(ut,ie(r,dt,``))?!0:!r:zn(e)&&Nn(gt.tagNameCheck,e)&&Nn(gt.attributeNameCheck,t,e)||t===`is`&>.allowCustomizedBuiltInElements&&Nn(gt.tagNameCheck,r)},Rn=I({},[`annotation-xml`,`color-profile`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`missing-glyph`]),zn=function(e){return!Rn[te(e)]&&P(ft,e)},Bn=function(e,t,n,r){if(O&&typeof u==`object`&&typeof u.getAttributeType==`function`&&!n)switch(u.getAttributeType(e,t)){case`TrustedHTML`:return F(r);case`TrustedScriptURL`:return me(r)}return r},Vn=function(e,n,r,i){try{r?e.setAttributeNS(r,n,i):e.setAttribute(n,i),kn(e)?_n(e):ee(t.removed)}catch{bn(n,e)}},Hn=function(e){H(L.beforeSanitizeAttributes,e,null);let t=e.attributes;if(!t||kn(e))return;B=Pn(L.uponSanitizeAttribute,B,ht,kt);let n={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:B,forceKeepAttr:void 0},r=t.length,i=V(e.nodeName);for(;r--;){let a=t[r],o=a.name,s=a.namespaceURI,c=a.value,l=V(o),u=c,d=o===`value`?u:oe(u);if(n.attrName=l,n.attrValue=d,n.keepAttr=!0,n.forceKeepAttr=void 0,H(L.uponSanitizeAttribute,e,n),d=n.attrValue,Ft&&(l===`id`||l===`name`)&&ae(d,It)!==0&&(bn(o,e,a),d=It+d),Tt&&P(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,d)){bn(o,e,a);continue}if(l===`attributename`&&re(d,`href`)){bn(o,e,a);continue}if(!n.forceKeepAttr){if(!n.keepAttr){bn(o,e,a);continue}if(!Ct&&P(We,d)){bn(o,e,a);continue}if(wt&&(d=Dn(d)),!Ln(i,l,d)){bn(o,e,a);continue}d=Bn(i,l,s,d),d!==u&&Vn(e,o,s,d)}}H(L.afterSanitizeAttributes,e,null)},Un=function(e){let t=null,n=En(e);for(H(L.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(H(L.uponSanitizeShadowNode,t,null),In(t,e),Hn(t),An(t.content)&&Un(t.content),E(t)===Ge.element){let e=_(t);An(e)&&(Wn(e),Un(e))}H(L.afterSanitizeShadowDOM,e,null)},Wn=function(e){let t=[{node:e,shadow:null}];for(;t.length>0;){let e=t.pop();if(e.shadow){Un(e.shadow);continue}let n=e.node,r=E(n)===Ge.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=x?x(n):null;if(typeof e==`string`&&V(e)===`template`){let e=n.content;An(e)&&t.push({node:e,shadow:null})}}if(r){let e=_(n);An(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(Xt=!e,Xt&&(e=`<!-->`),typeof e!=`string`&&!jn(e)&&(e=_e(e),typeof e!=`string`))throw pe(`dirty is not a string, aborting`);if(!t.isSupported)return e;Dt?(z=Ot,B=kt):un(n),(L.uponSanitizeElement.length>0||L.uponSanitizeAttribute.length>0)&&(z=ge(z)),L.uponSanitizeAttribute.length>0&&(B=ge(B)),t.removed=[];let c=Rt&&typeof e!=`string`&&jn(e);if(c){wn(e);let t=D(e);if(typeof t==`string`){let n=V(t);if(!z[n]||_t[n])throw yn(e),pe(`root node is forbidden and cannot be sanitized in-place`)}if(kn(e))throw yn(e),pe(`root node is clobbered and cannot be sanitized in-place`);try{Wn(e)}catch(t){throw yn(e),t}}else if(jn(e))i=Tn(`<!---->`),a=i.ownerDocument.importNode(e,!0),a.nodeType===Ge.element&&a.nodeName===`BODY`||a.nodeName===`HTML`?i=a:i.appendChild(a),Wn(a);else{if(!jt&&!wt&&!Et&&e.indexOf(`<`)===-1)return O&&Nt?F(e):e;if(i=Tn(e),!i)return jt?null:Nt?se:``}i&&At&&_n(i.firstChild);let l=c?e:i;try{let e=En(l);for(;o=e.nextNode();)In(o,l),Hn(o),An(o.content)&&Un(o.content)}catch(n){throw c&&(yn(e),k(t.removed,e=>{e.element&&Sn(e.element)})),n}if(c)return k(t.removed,e=>{e.element&&Sn(e.element)}),wt&&On(e),e;if(jt){if(wt&&On(i),Mt)for(s=rt.call(i.ownerDocument);i.firstChild;)s.appendChild(i.firstChild);else s=i;return(B.shadowroot||B.shadowrootmode)&&(s=at.call(r,s,!0)),s}let u=Et?i.outerHTML:i.innerHTML;return Et&&z[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&P(ze,i.ownerDocument.doctype.name)&&(u=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
|
|
3
|
+
`+u),wt&&(u=Dn(u)),O&&Nt?F(u):u},t.setConfig=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};un(e),Dt=!0,Ot=z,kt=B},t.clearConfig=function(){sn=null,Dt=!1,Ot=null,kt=null,O=ce,se=``},t.isValidAttribute=function(e,t,n){sn||un({});let r=V(e),i=V(t);return Ln(r,i,n)},t.addHook=function(e,t){typeof t==`function`&&de(L,e)&&j(L[e],t)},t.removeHook=function(e,t){if(de(L,e)){if(t!==void 0){let n=A(L[e],t);return n===-1?void 0:M(L[e],n,1)[0]}return ee(L[e])}},t.removeHooks=function(e){de(L,e)&&(L[e]=[])},t.removeAllHooks=function(){L=Ze()},t}var tt=et();function nt(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var rt=nt();function it(e){rt=e}var at={exec:()=>null};function L(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function R(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(st.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var ot=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),st={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:L(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:L(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:L(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:L(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:L(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:L(e=>RegExp(`^ {0,${e}}>`))},ct=/^(?:[ \t]*(?:\n|$))+/,lt=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,ut=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,dt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ft=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,pt=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,z=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,mt=R(z).replace(/bull/g,pt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),B=R(z).replace(/bull/g,pt).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),ht=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,gt=/^[^\n]+/,_t=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,vt=R(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,_t).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),yt=R(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,pt).getRegex(),bt=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,xt=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,St=R(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,xt).replace(`tag`,bt).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ct=e=>R(ht).replace(`hr`,dt).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,e).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,bt).getRegex(),wt=Ct(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Tt=Ct(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Et={blockquote:R(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,Tt).getRegex(),code:lt,def:vt,fences:ut,heading:ft,hr:dt,html:St,lheading:mt,list:yt,newline:ct,paragraph:wt,table:at,text:gt},Dt=R(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,dt).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,bt).getRegex(),Ot={...Et,lheading:B,table:Dt,paragraph:R(ht).replace(`hr`,dt).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,Dt).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,bt).getRegex()},kt={...Et,html:R(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,xt).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:at,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:R(ht).replace(`hr`,dt).replace(`heading`,` *#{1,6} *[^
|
|
4
|
+
]`).replace(`lheading`,mt).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},At=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,jt=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Mt=/^( {2,}|\\)\n(?!\s*$)/,Nt=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Pt=/[\p{P}\p{S}]/u,Ft=/[\s\p{P}\p{S}]/u,It=/[^\s\p{P}\p{S}]/u,Lt=R(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,Ft).getRegex(),Rt=/[\p{Pi}\p{Ps}"']/u,zt=/(?!~)[\p{P}\p{S}]/u,Bt=/(?!~)[\s\p{P}\p{S}]/u,Vt=/(?:[^\s\p{P}\p{S}]|~)/u,Ht=R(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,ot?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),Ut=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Wt=R(Ut,`u`).replace(/punct/g,Pt).getRegex(),Gt=R(Ut,`u`).replace(/punct/g,zt).getRegex(),Kt=R(/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,`u`).replace(/openQuote/g,Rt).replace(/punct/g,Pt).getRegex(),qt=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,Jt=R(qt,`gu`).replace(/notPunctSpace/g,It).replace(/punctSpace/g,Ft).replace(/punct/g,Pt).getRegex(),Yt=R(qt,`gu`).replace(/notPunctSpace/g,Vt).replace(/punctSpace/g,Bt).replace(/punct/g,zt).getRegex(),Xt=R(`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,It).replace(/punctSpace/g,Ft).replace(/punct/g,Pt).getRegex(),Zt=R(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,It).replace(/punctSpace/g,Ft).replace(/punct/g,Pt).getRegex(),Qt=R(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,It).replace(/punctSpace/g,Ft).replace(/punct/g,Pt).getRegex(),$t=R(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,Pt).getRegex(),en=R(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,It).replace(/punctSpace/g,Ft).replace(/punct/g,Pt).getRegex(),tn=R(/\\(punct)/,`gu`).replace(/punct/g,Pt).getRegex(),nn=R(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace(`scheme`,/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(`email`,/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),rn=R(xt).replace(`(?:-->|$)`,`-->`).getRegex(),an=R(`^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,rn).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),on=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,V=R(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,on).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),sn=R(/^!?\[(label)\]\[(ref)\]/).replace(`label`,on).replace(`ref`,_t).getRegex(),cn=R(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,_t).getRegex(),ln=R(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,sn).replace(`nolink`,cn).getRegex(),un=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,dn={_backpedal:at,anyPunctuation:tn,autolink:nn,blockSkip:Ht,br:Mt,code:jt,del:at,delLDelim:at,delRDelim:at,emStrongLDelim:Wt,emStrongRDelimAst:Jt,emStrongRDelimUnd:Zt,escape:At,link:V,nolink:cn,punctuation:Lt,reflink:sn,reflinkSearch:ln,tag:an,text:Nt,url:at},fn={...dn,emStrongLDelim:Kt,emStrongRDelimAst:Xt,emStrongRDelimUnd:Qt,link:R(/^!?\[(label)\]\((.*?)\)/).replace(`label`,on).getRegex(),reflink:R(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,on).getRegex()},pn={...dn,emStrongRDelimAst:Yt,emStrongLDelim:Gt,delLDelim:$t,delRDelim:en,url:R(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,un).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:R(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,un).getRegex()},mn={...pn,br:R(Mt).replace(`{2,}`,`*`).getRegex(),text:R(pn.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},hn={normal:Et,gfm:Ot,pedantic:kt},gn={normal:dn,gfm:pn,breaks:mn,pedantic:fn},_n={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},vn=e=>_n[e];function yn(e,t){if(t){if(st.escapeTest.test(e))return e.replace(st.escapeReplace,vn)}else if(st.escapeTestNoEncode.test(e))return e.replace(st.escapeReplaceNoEncode,vn);return e}function bn(e){try{e=encodeURI(e).replace(st.percentDecode,`%`)}catch{return null}return e}function xn(e,t){let n=e.replace(st.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(st.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t){if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``)}for(;r<n.length;r++)n[r]=n[r].trim().replace(st.slashPipe,`|`);return n}function Sn(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function Cn(e){let t=e.split(`
|
|
5
|
+
`),n=t.length-1;for(;n>=0&&st.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
|
|
6
|
+
`)}function wn(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]===`\\`)r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function Tn(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function En(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function Dn(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
7
|
+
`).map(e=>{let t=e.match(n.other.beginningSpace);if(t===null)return e;let[r]=t;return r.length>=i.length?e.slice(i.length):e}).join(`
|
|
8
|
+
`)}var On=class{options;rules;lexer;constructor(e){this.options=e||rt}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:`space`,raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let e=this.options.pedantic?t[0]:Cn(t[0]);return{type:`code`,raw:e,codeBlockStyle:`indented`,text:e.replace(this.rules.other.codeRemoveIndent,``)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=Dn(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=Sn(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:Sn(t[0],`
|
|
9
|
+
`),depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:Sn(t[0],`
|
|
10
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=Sn(t[0],`
|
|
11
|
+
`).split(`
|
|
12
|
+
`),n=``,r=``,i=[];for(;e.length>0;){let t=!1,a=[],o;for(o=0;o<e.length;o++)if(this.rules.other.blockquoteStart.test(e[o]))a.push(e[o]),t=!0;else if(!t)a.push(e[o]);else break;e=e.slice(o);let s=a.join(`
|
|
13
|
+
`),c=s.replace(this.rules.other.blockquoteSetextReplace,`
|
|
14
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,``);n=n?`${n}
|
|
15
|
+
${s}`:s,r=r?`${r}
|
|
16
|
+
${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(c,i,!0),this.lexer.state.top=l,e.length===0)break;let u=i.at(-1);if(u?.type===`code`)break;if(u?.type===`blockquote`){let t=u,a=e.join(`
|
|
17
|
+
`),o=t.raw+`
|
|
18
|
+
`+a.replace(this.rules.other.blockquoteSetextReplace2,``),s=this.blockquote(o);i[i.length-1]=s,n=`${n}
|
|
19
|
+
${a}`,r=r.substring(0,r.length-t.text.length)+s.text;break}if(u?.type===`list`){let t=u,a=t.raw+`
|
|
20
|
+
`+e.join(`
|
|
21
|
+
`),o=this.list(a);i[i.length-1]=o,n=n.substring(0,n.length-u.raw.length)+o.raw,r=r.substring(0,r.length-t.raw.length)+o.raw,e=a.substring(i.at(-1).raw.length).split(`
|
|
22
|
+
`);continue}}return{type:`blockquote`,raw:n,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,i={type:`list`,raw:``,ordered:r,start:r?+n.slice(0,-1):``,loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:`[*+-]`);let a=this.rules.other.listItemRegex(n),o=!1;for(;e;){let n=!1,r=``,s=``;if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;r=t[0],e=e.substring(r.length);let c=Tn(t[2].split(`
|
|
23
|
+
`,1)[0],t[1].length),l=e.split(`
|
|
24
|
+
`,1)[0],u=!c.trim(),d=0;if(this.options.pedantic?(d=2,s=c.trimStart()):u?d=t[1].length+1:(d=c.search(this.rules.other.nonSpaceChar),d=d>4?1:d,s=c.slice(d),d+=t[1].length),u&&this.rules.other.blankLine.test(l)&&(r+=l+`
|
|
25
|
+
`,e=e.substring(l.length+1),n=!0),!n){let t=this.rules.other.nextBulletRegex(d),n=this.rules.other.hrRegex(d),i=this.rules.other.fencesBeginRegex(d),a=this.rules.other.headingBeginRegex(d),o=this.rules.other.htmlBeginRegex(d),f=this.rules.other.blockquoteBeginRegex(d);for(;e;){let p=e.split(`
|
|
26
|
+
`,1)[0],m;if(l=p,this.options.pedantic?(l=l.replace(this.rules.other.listReplaceNesting,` `),m=l):m=l.replace(this.rules.other.tabCharGlobal,` `),i.test(l)||a.test(l)||o.test(l)||f.test(l)||t.test(l)||n.test(l))break;if(m.search(this.rules.other.nonSpaceChar)>=d||!l.trim())s+=`
|
|
27
|
+
`+m.slice(d);else{if(u||c.replace(this.rules.other.tabCharGlobal,` `).search(this.rules.other.nonSpaceChar)>=4||i.test(c)||a.test(c)||n.test(c))break;s+=`
|
|
28
|
+
`+l}u=!l.trim(),r+=p+`
|
|
29
|
+
`,e=e.substring(p.length+1),c=m.slice(d)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(o=!0)),i.items.push({type:`list_item`,raw:r,task:!!this.options.gfm&&this.rules.other.listIsTask.test(s),loose:!1,text:s,tokens:[]}),i.raw+=r}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let e of i.items)if(this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]),!i.loose){let t=e.tokens.filter(e=>e.type===`space`);i.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}for(let e of i.items){let t=e.tokens[0];if(e.task&&(t?.type===`text`||t?.type===`paragraph`)){e.text=e.text.replace(this.rules.other.listReplaceTask,``),t.raw=t.raw.replace(this.rules.other.listReplaceTask,``),t.text=t.text.replace(this.rules.other.listReplaceTask,``);for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,``);break}let n=this.rules.other.listTaskCheckbox.exec(e.raw);if(n){let t={type:`checkbox`,raw:n[0]+` `,checked:n[0]!==`[ ]`};e.checked=t.checked,i.loose?e.tokens[0]&&[`paragraph`,`text`].includes(e.tokens[0].type)&&`tokens`in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=t.raw+e.tokens[0].raw,e.tokens[0].text=t.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(t)):e.tokens.unshift({type:`paragraph`,raw:t.raw,text:t.raw,tokens:[t]}):e.tokens.unshift(t)}}else e.task&&=!1}if(i.loose)for(let e of i.items){e.loose=!0;for(let t of e.tokens)t.type===`text`&&(t.type=`paragraph`)}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let e=Cn(t[0]);return{type:`html`,block:!0,raw:e,pre:t[1]===`pre`||t[1]===`script`||t[1]===`style`,text:e}}}def(e){let t=this.rules.block.def.exec(e);if(t){let e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,` `),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,`$1`).replace(this.rules.inline.anyPunctuation,`$1`):``,r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,`$1`):t[3];return{type:`def`,tag:e,raw:Sn(t[0],`
|
|
30
|
+
`),href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=xn(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
|
|
31
|
+
`):[],a={type:`table`,raw:Sn(t[0],`
|
|
32
|
+
`),header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e<n.length;e++)a.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:a.align[e]});for(let e of i)a.rows.push(xn(e,a.header.length).map((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let e=t[1].trim();return{type:`heading`,raw:Sn(t[0],`
|
|
33
|
+
`),depth:t[2].charAt(0)===`=`?1:2,text:e,tokens:this.lexer.inline(e)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let e=t[1].charAt(t[1].length-1)===`
|
|
34
|
+
`?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:`text`,raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:`escape`,raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:`html`,raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=Sn(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=wn(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let n=t[2],r=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):``;return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),En(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,`$1`),title:r&&r.replace(this.rules.inline.anyPunctuation,`$1`)},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `).toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return En(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,a,o,s=i,c=0,l=r[0][0],u=n===l,d=l===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+i);(r=d.exec(t))!==null;){if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a)continue;if(o=[...a].length,r[3]||r[4]){s+=o;continue}if(r[5]||r[6]){if(i%3&&!((i+o)%3)){c+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+c);let t=[...r[0]][0].length,n=e.slice(0,i+r.index+t+o);if(Math.min(i,o)%2){let e=n.slice(1,-1);return{type:`em`,raw:n,text:e,tokens:this.lexer.inlineTokens(e)}}let l=n.slice(2,-2);return{type:`strong`,raw:n,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e,t,n=``){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=this.rules.inline.delRDelim;for(s.lastIndex=0,t=t.slice(-1*e.length+n);(r=s.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(a=[...i].length,a!==n))continue;if(r[3]||r[4]){o+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o);let t=[...r[0]][0].length,s=e.slice(0,n+r.index+t+a),c=s.slice(n,-n);return{type:`del`,raw:s,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:t[0],escaped:e}}}},kn=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||rt,this.options.tokenizer=this.options.tokenizer||new On,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:st,block:hn.normal,inline:gn.normal};this.options.pedantic?(t.block=hn.pedantic,t.inline=gn.pedantic):this.options.gfm&&(t.block=hn.gfm,t.inline=this.options.breaks?gn.breaks:gn.gfm),this.tokenizer.rules=t}static get rules(){return{block:hn,inline:gn}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(st.carriageReturn,`
|
|
35
|
+
`),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){let t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(st.tabCharGlobal,` `).replace(st.spaceLine,``));let r=1/0;for(;e;){if(e.length<r)r=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let i;if(this.options.extensions?.block?.some(n=>(i=n.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let n=t.at(-1);i.raw.length===1&&n!==void 0?n.raw+=`
|
|
36
|
+
`:t.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(`
|
|
37
|
+
`)?``:`
|
|
38
|
+
`)+i.raw,n.text+=`
|
|
39
|
+
`+i.text,this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(i=this.tokenizer.fences(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.heading(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.hr(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.blockquote(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.list(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.html(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.def(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(`
|
|
40
|
+
`)?``:`
|
|
41
|
+
`)+i.raw,n.text+=`
|
|
42
|
+
`+i.raw,this.inlineQueue.at(-1).src=n.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title},t.push(i));continue}if(i=this.tokenizer.table(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.lheading(e)){e=e.substring(i.raw.length),t.push(i);continue}let a=e;if(this.options.extensions?.startBlock){let t=1/0,n=e.slice(1),r;this.options.extensions.startBlock.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(a=e.substring(0,t+1))}if(this.state.top&&(i=this.tokenizer.paragraph(a))){let r=t.at(-1);n&&r?.type===`paragraph`?(r.raw+=(r.raw.endsWith(`
|
|
43
|
+
`)?``:`
|
|
44
|
+
`)+i.raw,r.text+=`
|
|
45
|
+
`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(i),n=a.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`text`?(n.raw+=(n.raw.endsWith(`
|
|
46
|
+
`)?``:`
|
|
47
|
+
`)+i.raw,n.text+=`
|
|
48
|
+
`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e;if(this.tokens.links){let e=Object.keys(this.tokens.links);e.length>0&&(n=n.replace(this.tokenizer.rules.inline.reflinkSearch,t=>e.includes(t.slice(t.lastIndexOf(`[`)+1,-1))?`[`+`a`.repeat(t.length-2)+`]`:t))}n=n.replace(this.tokenizer.rules.inline.anyPunctuation,e=>`+`.repeat(e.length)),n=n.replace(this.tokenizer.rules.inline.blockSkip,(e,t,n)=>{let r=n?n.length:0;return e.slice(0,r)+`[`+`a`.repeat(e.length-r-2)+`]`}),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let r=!1,i=``,a=1/0;for(;e;){if(e.length<a)a=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}r||(i=``),r=!1;let o;if(this.options.extensions?.inline?.some(n=>(o=n.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))continue;if(o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.tag(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);let n=t.at(-1);o.type===`text`&&n?.type===`text`?(n.raw+=o.raw,n.text+=o.text):t.push(o);continue}if(o=this.tokenizer.emStrong(e,n,i)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.br(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.del(e,n,i)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.autolink(e)){e=e.substring(o.raw.length),t.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),t.push(o);continue}let s=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(s=e.substring(0,t+1))}if(o=this.tokenizer.inlineText(s)){e=e.substring(o.raw.length),o.raw.slice(-1)!==`_`&&(i=o.raw.slice(-1)),r=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=o.raw,n.text+=o.text):t.push(o);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t=`Infinite loop on byte: `+e;if(this.options.silent)console.error(t);else throw Error(t)}},An=class{options;parser;constructor(e){this.options=e||rt}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(st.notSpaceStart)?.[0],i=e.replace(st.endingNewline,``)+`
|
|
49
|
+
`;return r?`<pre><code class="language-`+yn(r)+`">`+(n?i:yn(i,!0))+`</code></pre>
|
|
50
|
+
`:`<pre><code>`+(n?i:yn(i,!0))+`</code></pre>
|
|
51
|
+
`}blockquote({tokens:e}){return`<blockquote>
|
|
52
|
+
${this.parser.parse(e)}</blockquote>
|
|
53
|
+
`}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
54
|
+
`}hr(e){return`<hr>
|
|
55
|
+
`}list(e){let t=e.ordered,n=e.start,r=``;for(let t=0;t<e.items.length;t++){let n=e.items[t];r+=this.listitem(n)}let i=t?`ol`:`ul`,a=t&&n!==1?` start="`+n+`"`:``;return`<`+i+a+`>
|
|
56
|
+
`+r+`</`+i+`>
|
|
57
|
+
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
58
|
+
`}checkbox({checked:e}){return`<input `+(e?`checked="" `:``)+`disabled="" type="checkbox"> `}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
59
|
+
`}table(e){let t=``,n=``;for(let t=0;t<e.header.length;t++)n+=this.tablecell(e.header[t]);t+=this.tablerow({text:n});let r=``;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];n=``;for(let e=0;e<i.length;e++)n+=this.tablecell(i[e]);r+=this.tablerow({text:n})}return r&&=`<tbody>${r}</tbody>`,`<table>
|
|
60
|
+
<thead>
|
|
61
|
+
`+t+`</thead>
|
|
62
|
+
`+r+`</table>
|
|
63
|
+
`}tablerow({text:e}){return`<tr>
|
|
64
|
+
${e}</tr>
|
|
65
|
+
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
66
|
+
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${yn(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=bn(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+yn(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=bn(e);if(i===null)return yn(n);e=i;let a=`<img src="${e}" alt="${yn(n)}"`;return t&&(a+=` title="${yn(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:yn(e.text)}},jn=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},H=class e{options;renderer;textRenderer;constructor(e){this.options=e||rt,this.options.renderer=this.options.renderer||new An,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new jn}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`checkbox`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`checkbox`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},Mn=class{options;block;constructor(e){this.options=e||rt}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?kn.lex:kn.lexInline}provideParser(e=this.block){return e?H.parse:H.parseInline}},Nn=new class{defaults=nt();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=H;Renderer=An;TextRenderer=jn;Lexer=kn;Tokenizer=On;Hooks=Mn;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new An(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new On(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new Mn;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];t[r]=Mn.passThroughHooks.has(n)?e=>{if(this.defaults.async&&Mn.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return kn.lex(e,t??this.defaults)}parser(e,t){return H.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?kn.lex:kn.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?H.parse:H.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?kn.lex:kn.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?H.parse:H.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
|
|
67
|
+
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+yn(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function U(e,t){return Nn.parse(e,t)}U.options=U.setOptions=function(e){return Nn.setOptions(e),U.defaults=Nn.defaults,it(U.defaults),U},U.getDefaults=nt,U.defaults=rt;function Pn(...e){return Nn.use(...e),U.defaults=Nn.defaults,it(U.defaults),U}U.use=Pn,U.walkTokens=function(e,t){return Nn.walkTokens(e,t)},U.parseInline=Nn.parseInline,U.Parser=H,U.parser=H.parse,U.Renderer=An,U.TextRenderer=jn,U.Lexer=kn,U.lexer=kn.lex,U.Tokenizer=On,U.Hooks=Mn,U.parse=U,U.options,U.setOptions,U.walkTokens,U.parseInline,H.parse,kn.lex;var Fn=/[\u201c\u201d"\u2018\u2019'()\uff08\uff09\u300c\u300d\u300e\u300f\u3010\u3011\u300a\u300b\u3008\u3009[\]]/;function In(e){let t=[],n=e=>`\uE010${t.push(e)-1}\uE011`,r=e.replace(/```[\s\S]*?```/g,e=>n(e)).replace(/`[^`\n]+`/g,e=>n(e));return r=r.replace(/\*\*(\S|\S[\s\S]*?\S)\*\*/g,(e,t)=>{let n=``,r=``,i=t;for(;i.length>1&&Fn.test(i[0]);)n+=i[0],i=i.slice(1);for(;i.length>1&&Fn.test(i.at(-1));)r=i.at(-1)+r,i=i.slice(0,-1);return n||r?`${n}**${i}**${r}`:e}),r.replace(/\uE010(\d+)\uE011/g,(e,n)=>t[Number(n)]??``)}var Ln=e=>!e.text.trim()&&e.suggestions.length===0,Rn=e=>e===`xhigh`?`Extra high`:e[0].toUpperCase()+e.slice(1),zn=e=>{if(e<1e3)return String(e);let t=e/1e3;return t>=9.95?`${Math.round(t)}K`:`${t.toFixed(1)}K`};function Bn(e){let t=Math.max(1,Math.round(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m${t%60}s`}var Vn=e=>`${Bn(e.durationMs)} · ${zn(e.tokens)} tok`,Hn=/(?:^|\n)[ \t]*-{3,}[ \t]*\r?\n((?:[ \t]*\[[^\]\r\n]+\][ \t]*(?:[||][ \t]*)?)+)\s*$/,Un=/\[([^\]\r\n]+)\]/g,Wn=5,Gn=/<silent>([\s\S]*?)<\/silent>/gi;function Kn(e){let t=[...e.matchAll(Gn)].map(e=>(e[1]??``).trim()).filter(Boolean);return t.length?t.join(` · `):void 0}function qn(e,t){let n=In(e.replace(Gn,``).trim()),r=Kn(e),i=Hn.exec(n);if(!i?.[1])return{text:n,suggestions:[],meta:t,silence:r};let a=[...i[1].matchAll(Un)].map(e=>(e[1]??``).trim()).filter(Boolean).slice(0,Wn);return a.length?{text:n.slice(0,i.index).trimEnd(),suggestions:a,meta:t,silence:r}:{text:n,suggestions:[],meta:t,silence:r}}var W=e=>{let t=document.querySelector(e);if(!t)throw Error(`missing element: ${e}`);return t};function Jn(e){let t=Math.round((Date.now()-e)/6e4);return t<1?`now`:t<60?`${t}m`:t<1440?`${Math.round(t/60)}h`:`${Math.round(t/1440)}d`}function G(e,t,...n){let r=document.createElement(e);return t&&(r.className=t),r.append(...n),r}var Yn=e=>e.split(`/`).filter(Boolean).pop()??e;function Xn(e){let t=Math.max(0,Math.round(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function Zn(e,t,n){return{visible:!1,show(n){this.visible=!0,e.classList.remove(`hidden`),e.classList.add(`flex`),t(n)},hide(){n?.(),this.visible=!1,e.classList.add(`hidden`),e.classList.remove(`flex`)}}}function Qn(e){let t=G(`span`,`help`);return t.innerHTML=tt.sanitize(U.parseInline(e,{async:!1})),$n(t),t}function $n(e){for(let t of e.querySelectorAll(`a`))(t.getAttribute(`href`)??``).startsWith(`#`)||(t.target=`_blank`,t.rel=`noreferrer`)}async function er(e){if(navigator.clipboard)return navigator.clipboard.writeText(e);let t=document.createElement(`textarea`);t.value=e,t.className=`fixed opacity-0`,document.body.append(t),t.select();let n=document.execCommand(`copy`);if(t.remove(),!n)throw Error(`clipboard unavailable`)}function tr(e,t){let n=G(`button`,e,`Copy`);n.title=`Copy to clipboard`;let r;return n.onclick=async e=>{e.stopPropagation(),n.textContent=await er(t()).then(()=>`Copied`,()=>`Failed`),clearTimeout(r),r=setTimeout(()=>n.textContent=`Copy`,1200)},n}function nr(e,t){let n=document.createElement(`details`);n.className=e;let r=G(`summary`,`flex cursor-pointer select-none items-center gap-1.5`);return r.append(G(`span`,`chev`,`▶`),...t),n.append(r),{el:n,summary:r}}var rr=W(`#image-dialog`),ir=W(`#image-full`),ar=W(`#image-prev`),or=W(`#image-next`),sr=[],cr=0;function lr(e){sr.length<2||(cr=(cr+e+sr.length)%sr.length,ir.src=sr[cr])}function ur(e){let t=new URL(e,location.href).href;sr=[...W(`#turns`).querySelectorAll(`img.thumb`)].map(e=>e.src),cr=Math.max(0,sr.indexOf(t)),ir.src=t;let n=sr.length<2?`none`:`flex`;ar.style.display=n,or.style.display=n,rr.showModal()}rr.onclick=()=>rr.close();var dr=(e,t)=>{e.onclick=e=>{e.stopPropagation(),lr(t)}};dr(ar,-1),dr(or,1),rr.onkeydown=e=>{(e.key===`ArrowLeft`||e.key===`ArrowRight`)&&(e.preventDefault(),lr(e.key===`ArrowLeft`?-1:1))};function fr(e){let t=e.querySelector(`:scope > .thumbs`);if(t)return t;let n=G(`div`,`thumbs`);return e.append(n),n}function pr(e){let t=document.createElement(`img`);return t.src=e,t.loading=`lazy`,t.className=`thumb`,t.onclick=()=>ur(e),t}var mr=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`,`bmp`]),hr=new Set([`txt`,`md`,`log`,`json`,`csv`,`yaml`,`yml`]),gr=524288,_r=W(`#file-dialog`),vr=W(`#file-name`),yr=W(`#file-text`),br=W(`#file-download`);W(`#file-close`).onclick=()=>_r.close();var xr=e=>e.split(`.`).pop()?.toLowerCase()??``,Sr=(e,t,n=!1)=>`/api/sessions/${encodeURIComponent(e)}/files?path=${encodeURIComponent(t)}${n?`&download=1`:``}`;function Cr(e,t){return e.replace(/\]\(\s*<?file:\/\/(\/[^)>\s]*)>?\s*\)/g,(e,n)=>{let r=n;try{r=decodeURIComponent(n)}catch{}return`](${Sr(t,r)})`})}var wr=e=>/^\/api\/sessions\/[^/]+\/files\?/.test(e);function Tr(e,t){let n=Yn(t)||`file`,r=Sr(e,t);return mr.has(xr(n))?Or(r,n):kr(r,n)}function Er(e){return new URLSearchParams(e.slice(e.indexOf(`?`)+1)).get(`path`)??``}async function Dr(e,t){vr.textContent=t,br.href=`${e}&download=1`,yr.textContent=`loading…`,_r.showModal();let n=await fetch(e),r=n.ok?await n.text():`failed to load: ${n.status}`;yr.textContent=r.length>gr?`${r.slice(0,gr)}\n…`:r}function Or(e,t){let n=pr(e);return n.alt=t,n}function kr(e,t){let n=xr(t),r=G(`span`,`inline-flex max-w-full items-center gap-2.5 rounded-lg border border-neutral-200 bg-neutral-50 px-2.5 py-1.5 no-underline`),i=G(`span`,`flex h-7 w-7 flex-none items-center justify-center rounded-md bg-indigo-50 text-[10px] font-semibold uppercase text-indigo-600`,n.slice(0,4)||`file`),a=G(`span`,`min-w-0 truncate text-[13px] font-medium text-neutral-800`,t),o=G(`span`,`ml-1 flex flex-none items-center gap-0.5`);if(hr.has(n)||n===`pdf`){let r=G(`button`,`icon-btn h-6 w-6 text-[13px]`,`◉`);r.title=`Preview`,r.onclick=r=>{r.preventDefault(),n===`pdf`?window.open(e,`_blank`,`noopener`):Dr(e,t)},o.append(r)}let s=document.createElement(`a`);return s.className=`icon-btn h-6 w-6 text-[13px] no-underline`,s.href=`${e}&download=1`,s.download=t,s.title=`Download`,s.textContent=`↓`,o.append(s),r.append(i,a,o),r}function Ar(e){let t=new Set;for(let n of e)n.parentElement&&t.add(n.parentElement);for(let n of t){let t=[...n.children].filter(t=>e.includes(t));if([...n.childNodes].every(e=>e.nodeType===Node.TEXT_NODE?!e.textContent?.trim():t.includes(e))){n.classList.add(`thumbs`);continue}let r=G(`div`,`thumbs`);r.append(...t),n.after(r)}}function jr(e){let t=[];for(let n of e.querySelectorAll(`img`)){let e=n.getAttribute(`src`)??``;if(!wr(e))continue;let r=Or(e,Yn(Er(e)));n.replaceWith(r),t.push(r)}for(let n of e.querySelectorAll(`a`)){let e=n.getAttribute(`href`)??``;if(!wr(e))continue;let r=Yn(Er(e))||n.textContent?.trim()||`file`,i=mr.has(xr(r))?Or(e,r):kr(e,r);n.replaceWith(i),t.push(i)}t.length&&Ar(t)}var Mr=e=>`[${e.split(`/`).pop()??`file`}](file://${encodeURI(e).replace(/\(/g,`%28`).replace(/\)/g,`%29`)})`,Nr=/^\[[^\]\n]*\]\(\s*<?file:\/\/(\/[^)>\s]*)>?\s*\)$/;function Pr(e){let t=e.split(`
|
|
68
|
+
`),n=t.length;for(;n>0&&Nr.test(t[n-1].trim());)n--;let r=t.slice(n).map(e=>{let t=Nr.exec(e.trim())[1];try{return decodeURIComponent(t)}catch{return t}});return{text:t.slice(0,n).join(`
|
|
69
|
+
`).trimEnd(),paths:r}}var Fr=c(o(((e,t)=>{function n(e){return e instanceof Map?e.clear=e.delete=e.set=function(){throw Error(`map is read-only`)}:e instanceof Set&&(e.add=e.clear=e.delete=function(){throw Error(`set is read-only`)}),Object.freeze(e),Object.getOwnPropertyNames(e).forEach(t=>{let r=e[t],i=typeof r;(i===`object`||i===`function`)&&!Object.isFrozen(r)&&n(r)}),e}var r=class{constructor(e){e.data===void 0&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}};function i(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function a(e,...t){let n=Object.create(null);for(let t in e)n[t]=e[t];return t.forEach(function(e){for(let t in e)n[t]=e[t]}),n}var o=`</span>`,s=e=>!!e.scope,c=(e,{prefix:t})=>{if(e.startsWith(`language:`))return e.replace(`language:`,`language-`);if(e.includes(`.`)){let n=e.split(`.`);return[`${t}${n.shift()}`,...n.map((e,t)=>`${e}${`_`.repeat(t+1)}`)].join(` `)}return`${t}${e}`},l=class{constructor(e,t){this.buffer=``,this.classPrefix=t.classPrefix,e.walk(this)}addText(e){this.buffer+=i(e)}openNode(e){if(!s(e))return;let t=c(e.scope,{prefix:this.classPrefix});this.span(t)}closeNode(e){s(e)&&(this.buffer+=o)}value(){return this.buffer}span(e){this.buffer+=`<span class="${e}">`}},u=(e={})=>{let t={children:[]};return Object.assign(t,e),t},d=class e{constructor(){this.rootNode=u(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){this.top.children.push(e)}openNode(e){let t=u({scope:e});this.add(t),this.stack.push(t)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,t){return typeof t==`string`?e.addText(t):t.children&&(e.openNode(t),t.children.forEach(t=>this._walk(e,t)),e.closeNode(t)),e}static _collapse(t){typeof t!=`string`&&t.children&&(t.children.every(e=>typeof e==`string`)?t.children=[t.children.join(``)]:t.children.forEach(t=>{e._collapse(t)}))}},f=class extends d{constructor(e){super(),this.options=e}addText(e){e!==``&&this.add(e)}startScope(e){this.openNode(e)}endScope(){this.closeNode()}__addSublanguage(e,t){let n=e.root;t&&(n.scope=`language:${t}`),this.add(n)}toHTML(){return new l(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}};function p(e){return e?typeof e==`string`?e:e.source:null}function m(e){return _(`(?=`,e,`)`)}function h(e){return _(`(?:`,e,`)*`)}function g(e){return _(`(?:`,e,`)?`)}function _(...e){return e.map(e=>p(e)).join(``)}function v(e){let t=e[e.length-1];return typeof t==`object`&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}function y(...e){return`(`+(v(e).capture?``:`?:`)+e.map(e=>p(e)).join(`|`)+`)`}function b(e){return RegExp(e.toString()+`|`).exec(``).length-1}function x(e,t){let n=e&&e.exec(t);return n&&n.index===0}var S=new RegExp(y(/\[(?:[^\\\]]|\\.)*\]/,/\(\?<(?![=!])[^>]+>/,/\(\?'[^']+'/,/\(\??/,/\\([1-9][0-9]*)/,/\\./));function C(e,{joinWith:t}){let n=0;return e.map(e=>{n+=1;let t=n,r=p(e),i=``;for(;r.length>0;){let e=S.exec(r);if(!e){i+=r;break}i+=r.substring(0,e.index),r=r.substring(e.index+e[0].length),e[0][0]===`\\`&&e[1]?i+=`\\`+String(Number(e[1])+t):(i+=e[0],(e[0]===`(`||/^\(\?[<']/.test(e[0]))&&n++)}return i}).map(e=>`(${e})`).join(t)}var w=/\b\B/,T=`[a-zA-Z]\\w*`,E=`[a-zA-Z_]\\w*`,D=`\\b\\d+(\\.\\d+)?`,O=`(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)`,k=`\\b(0b[01]+)`,A=`!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~`,ee=(e={})=>{let t=/^#![ ]*\//;return e.binary&&(e.begin=_(t,/.*\b/,e.binary,/\b.*/)),a({scope:`meta`,begin:t,end:/$/,relevance:0,"on:begin":(e,t)=>{e.index!==0&&t.ignoreMatch()}},e)},j={begin:`\\\\[\\s\\S]`,relevance:0},M={scope:`string`,begin:`'`,end:`'`,illegal:`\\n`,contains:[j]},N={scope:`string`,begin:`"`,end:`"`,illegal:`\\n`,contains:[j]},te={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},ne=function(e,t,n={}){let r=a({scope:`comment`,begin:e,end:t,contains:[]},n);r.contains.push({scope:`doctag`,begin:`[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)`,end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});let i=y(`I`,`a`,`is`,`so`,`us`,`to`,`at`,`if`,`in`,`it`,`on`,/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return r.contains.push({begin:_(/[ ]+/,`(`,i,/[.]?[:]?([.][ ]|[ ])/,`){3}`)}),r},re=ne(`//`,`$`),ie=ne(`/\\*`,`\\*/`),ae=ne(`#`,`$`),oe=Object.freeze({__proto__:null,APOS_STRING_MODE:M,BACKSLASH_ESCAPE:j,BINARY_NUMBER_MODE:{scope:`number`,begin:k,relevance:0},BINARY_NUMBER_RE:k,COMMENT:ne,C_BLOCK_COMMENT_MODE:ie,C_LINE_COMMENT_MODE:re,C_NUMBER_MODE:{scope:`number`,begin:O,relevance:0},C_NUMBER_RE:O,END_SAME_AS_BEGIN:function(e){return Object.assign(e,{"on:begin":(e,t)=>{t.data._beginMatch=e[1]},"on:end":(e,t)=>{t.data._beginMatch!==e[1]&&t.ignoreMatch()}})},HASH_COMMENT_MODE:ae,IDENT_RE:T,MATCH_NOTHING_RE:w,METHOD_GUARD:{begin:`\\.\\s*[a-zA-Z_]\\w*`,relevance:0},NUMBER_MODE:{scope:`number`,begin:D,relevance:0},NUMBER_RE:D,PHRASAL_WORDS_MODE:te,QUOTE_STRING_MODE:N,REGEXP_MODE:{scope:`regexp`,begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[j,{begin:/\[/,end:/\]/,relevance:0,contains:[j]}]},RE_STARTERS_RE:A,SHEBANG:ee,TITLE_MODE:{scope:`title`,begin:T,relevance:0},UNDERSCORE_IDENT_RE:E,UNDERSCORE_TITLE_MODE:{scope:`title`,begin:E,relevance:0}});function se(e,t){e.input[e.index-1]===`.`&&t.ignoreMatch()}function ce(e,t){e.className!==void 0&&(e.scope=e.className,delete e.className)}function le(e,t){t&&e.beginKeywords&&(e.begin=`\\b(`+e.beginKeywords.split(` `).join(`|`)+`)(?!\\.)(?=\\b|\\s)`,e.__beforeBegin=se,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,e.relevance===void 0&&(e.relevance=0))}function ue(e,t){Array.isArray(e.illegal)&&(e.illegal=y(...e.illegal))}function de(e,t){if(e.match){if(e.begin||e.end)throw Error(`begin & end are not supported with match`);e.begin=e.match,delete e.match}}function fe(e,t){e.relevance===void 0&&(e.relevance=1)}var P=(e,t)=>{if(!e.beforeMatch)return;if(e.starts)throw Error(`beforeMatch cannot be used with starts`);let n=Object.assign({},e);Object.keys(e).forEach(t=>{delete e[t]}),e.keywords=n.keywords,e.begin=_(n.beforeMatch,m(n.begin)),e.starts={relevance:0,contains:[Object.assign(n,{endsParent:!0})]},e.relevance=0,delete n.beforeMatch},pe=[`of`,`and`,`for`,`in`,`not`,`or`,`if`,`then`,`parent`,`list`,`value`],F=`keyword`;function me(e,t,n=F){let r=Object.create(null);return typeof e==`string`?i(n,e.split(` `)):Array.isArray(e)?i(n,e):Object.keys(e).forEach(function(n){Object.assign(r,me(e[n],t,n))}),r;function i(e,n){t&&(n=n.map(e=>e.toLowerCase())),n.forEach(function(t){let n=t.split(`|`);r[n[0]]=[e,I(n[0],n[1])]})}}function I(e,t){return t?Number(t):+!he(e)}function he(e){return pe.includes(e.toLowerCase())}var ge={},_e=e=>{console.error(e)},ve=(e,...t)=>{console.log(`WARN: ${e}`,...t)},ye=(e,t)=>{ge[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),ge[`${e}/${t}`]=!0)},be=Error();function xe(e,t,{key:n}){let r=0,i=e[n],a={},o={};for(let e=1;e<=t.length;e++)o[e+r]=i[e],a[e+r]=!0,r+=b(t[e-1]);e[n]=o,e[n]._emit=a,e[n]._multi=!0}function Se(e){if(Array.isArray(e.begin)){if(e.skip||e.excludeBegin||e.returnBegin)throw _e(`skip, excludeBegin, returnBegin not compatible with beginScope: {}`),be;if(typeof e.beginScope!=`object`||e.beginScope===null)throw _e(`beginScope must be object`),be;xe(e,e.begin,{key:`beginScope`}),e.begin=C(e.begin,{joinWith:``})}}function Ce(e){if(Array.isArray(e.end)){if(e.skip||e.excludeEnd||e.returnEnd)throw _e(`skip, excludeEnd, returnEnd not compatible with endScope: {}`),be;if(typeof e.endScope!=`object`||e.endScope===null)throw _e(`endScope must be object`),be;xe(e,e.end,{key:`endScope`}),e.end=C(e.end,{joinWith:``})}}function we(e){e.scope&&typeof e.scope==`object`&&e.scope!==null&&(e.beginScope=e.scope,delete e.scope)}function Te(e){we(e),typeof e.beginScope==`string`&&(e.beginScope={_wrap:e.beginScope}),typeof e.endScope==`string`&&(e.endScope={_wrap:e.endScope}),Se(e),Ce(e)}function Ee(e){function t(t,n){return new RegExp(p(t),`m`+(e.case_insensitive?`i`:``)+(e.unicodeRegex?`u`:``)+(n?`g`:``))}class n{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(e,t){t.position=this.position++,this.matchIndexes[this.matchAt]=t,this.regexes.push([t,e]),this.matchAt+=b(e)+1}compile(){this.regexes.length===0&&(this.exec=()=>null);let e=this.regexes.map(e=>e[1]);this.matcherRe=t(C(e,{joinWith:`|`}),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex;let t=this.matcherRe.exec(e);if(!t)return null;let n=t.findIndex((e,t)=>t>0&&e!==void 0),r=this.matchIndexes[n];return t.splice(0,n),Object.assign(t,r)}}class r{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){if(this.multiRegexes[e])return this.multiRegexes[e];let t=new n;return this.rules.slice(e).forEach(([e,n])=>t.addRule(e,n)),t.compile(),this.multiRegexes[e]=t,t}resumingScanAtSamePosition(){return this.regexIndex!==0}considerAll(){this.regexIndex=0}addRule(e,t){this.rules.push([e,t]),t.type===`begin`&&this.count++}exec(e){let t=this.getMatcher(this.regexIndex);t.lastIndex=this.lastIndex;let n=t.exec(e);if(this.resumingScanAtSamePosition()&&!(n&&n.index===this.lastIndex)){let t=this.getMatcher(0);t.lastIndex=this.lastIndex+1,n=t.exec(e)}return n&&(this.regexIndex+=n.position+1,this.regexIndex===this.count&&this.considerAll()),n}}function i(e){let t=new r;return e.contains.forEach(e=>t.addRule(e.begin,{rule:e,type:`begin`})),e.terminatorEnd&&t.addRule(e.terminatorEnd,{type:`end`}),e.illegal&&t.addRule(e.illegal,{type:`illegal`}),t}function o(n,r){let a=n;if(n.isCompiled)return a;[ce,de,Te,P].forEach(e=>e(n,r)),e.compilerExtensions.forEach(e=>e(n,r)),n.__beforeBegin=null,[le,ue,fe].forEach(e=>e(n,r)),n.isCompiled=!0;let s=null;return typeof n.keywords==`object`&&n.keywords.$pattern&&(n.keywords=Object.assign({},n.keywords),s=n.keywords.$pattern,delete n.keywords.$pattern),s||=/\w+/,n.keywords&&=me(n.keywords,e.case_insensitive),a.keywordPatternRe=t(s,!0),r&&(n.begin||=/\B|\b/,a.beginRe=t(a.begin),!n.end&&!n.endsWithParent&&(n.end=/\B|\b/),n.end&&(a.endRe=t(a.end)),a.terminatorEnd=p(a.end)||``,n.endsWithParent&&r.terminatorEnd&&(a.terminatorEnd+=(n.end?`|`:``)+r.terminatorEnd)),n.illegal&&(a.illegalRe=t(n.illegal)),n.contains||=[],n.contains=[].concat(...n.contains.map(function(e){return Oe(e===`self`?n:e)})),n.contains.forEach(function(e){o(e,a)}),n.starts&&o(n.starts,r),a.matcher=i(a),a}if(e.compilerExtensions||=[],e.contains&&e.contains.includes(`self`))throw Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return e.classNameAliases=a(e.classNameAliases||{}),o(e)}function De(e){return e?e.endsWithParent||De(e.starts):!1}function Oe(e){return e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(function(t){return a(e,{variants:null},t)})),e.cachedVariants?e.cachedVariants:De(e)?a(e,{starts:e.starts?a(e.starts):null}):Object.isFrozen(e)?a(e):e}var ke=`11.12.0`,Ae=class extends Error{constructor(e,t){super(e),this.name=`HTMLInjectionError`,this.html=t}},je=i,Me=a,Ne=Symbol(`nomatch`),Pe=7,Fe=function(e){let t=Object.create(null),i=Object.create(null),a=[],o=!0,s=`Could not find the language '{}', did you forget to load/include a language module?`,c={disableAutodetect:!0,name:`Plain text`,contains:[]},l={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:`hljs-`,cssSelector:`pre code`,languages:null,__emitter:f};function u(e){return l.noHighlightRe.test(e)}function d(e){let t=e.className+` `;t+=e.parentNode?e.parentNode.className:``;let n=l.languageDetectRe.exec(t);if(n){let t=M(n[1]);return t||(ve(s.replace(`{}`,n[1])),ve(`Falling back to no-highlight mode for this block.`,e)),t?n[1]:`no-highlight`}return t.split(/\s+/).find(e=>u(e)||M(e))}function p(e,t,n){let r=``,i=``;typeof t==`object`?(r=e,n=t.ignoreIllegals,i=t.language):(ye(`10.7.0`,`highlight(lang, code, ...args) has been deprecated.`),ye(`10.7.0`,`Please use highlight(code, options) instead.
|
|
70
|
+
https://github.com/highlightjs/highlight.js/issues/2277`),i=e,r=t),n===void 0&&(n=!0);let a={code:r,language:i};ae(`before:highlight`,a);let o=a.result?a.result:v(a.language,a.code,n);return o.code=a.code,ae(`after:highlight`,o),o}function v(e,n,i,a){let c=Object.create(null);function u(e,t){return e.keywords[t]}function d(){if(!A.keywords){j.addText(N);return}let e=0;A.keywordPatternRe.lastIndex=0;let t=A.keywordPatternRe.exec(N),n=``;for(;t;){n+=N.substring(e,t.index);let r=D.case_insensitive?t[0].toLowerCase():t[0],i=u(A,r);if(i){let[e,a]=i;if(j.addText(n),n=``,c[r]=(c[r]||0)+1,c[r]<=Pe&&(te+=a),e.startsWith(`_`))n+=t[0];else{let n=D.classNameAliases[e]||e;m(t[0],n)}}else n+=t[0];e=A.keywordPatternRe.lastIndex,t=A.keywordPatternRe.exec(N)}n+=N.substring(e),j.addText(n)}function f(){if(N===``)return;let e=null;if(typeof A.subLanguage==`string`){if(!t[A.subLanguage]){j.addText(N);return}e=v(A.subLanguage,N,!0,ee[A.subLanguage]),ee[A.subLanguage]=e._top}else e=S(N,A.subLanguage.length?A.subLanguage:null);A.relevance>0&&(te+=e.relevance),j.__addSublanguage(e._emitter,e.language)}function p(){A.subLanguage==null?d():f(),N=``}function m(e,t){e!==``&&(j.startScope(t),j.addText(e),j.endScope())}function h(e,t){let n=1,r=t.length-1;for(;n<=r;){if(!e._emit[n]){n++;continue}let r=D.classNameAliases[e[n]]||e[n],i=t[n];r?m(i,r):(N=i,d(),N=``),n++}}function g(e,t){return e.scope&&typeof e.scope==`string`&&j.openNode(D.classNameAliases[e.scope]||e.scope),e.beginScope&&(e.beginScope._wrap?(m(N,D.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap),N=``):e.beginScope._multi&&(h(e.beginScope,t),N=``)),A=Object.create(e,{parent:{value:A}}),A}function _(e,t,n){let i=x(e.endRe,n);if(i){if(e[`on:end`]){let n=new r(e);e[`on:end`](t,n),n.isMatchIgnored&&(i=!1)}if(i){for(;e.endsParent&&e.parent;)e=e.parent;return e}}if(e.endsWithParent)return _(e.parent,t,n)}function y(e){return A.matcher.regexIndex===0?(N+=e[0],1):(ie=!0,0)}function b(e){let t=e[0],n=e.rule,i=new r(n),a=[n.__beforeBegin,n[`on:begin`]];for(let n of a)if(n&&(n(e,i),i.isMatchIgnored))return y(t);return n.skip?N+=t:(n.excludeBegin&&(N+=t),p(),!n.returnBegin&&!n.excludeBegin&&(N=t)),g(n,e),n.returnBegin?0:t.length}function C(e){let t=e[0],r=n.substring(e.index),i=_(A,e,r);if(!i)return Ne;let a=A;A.endScope&&A.endScope._wrap?(p(),m(t,A.endScope._wrap)):A.endScope&&A.endScope._multi?(p(),h(A.endScope,e)):a.skip?N+=t:(a.returnEnd||a.excludeEnd||(N+=t),p(),a.excludeEnd&&(N=t));do A.scope&&j.closeNode(),!A.skip&&!A.subLanguage&&(te+=A.relevance),A=A.parent;while(A!==i.parent);return i.starts&&g(i.starts,e),a.returnEnd?0:t.length}function w(){let e=[];for(let t=A;t!==D;t=t.parent)t.scope&&e.unshift(t.scope);e.forEach(e=>j.openNode(e))}let T={};function E(t,r){let a=r&&r[0];if(N+=t,a==null)return p(),0;if(T.type===`begin`&&r.type===`end`&&T.index===r.index&&a===``){if(N+=n.slice(r.index,r.index+1),!o){let t=Error(`0 width match regex (${e})`);throw t.languageName=e,t.badRule=T.rule,t}return 1}if(T=r,r.type===`begin`)return b(r);if(r.type===`illegal`&&!i){let e=Error(`Illegal lexeme "`+a+`" for mode "`+(A.scope||`<unnamed>`)+`"`);throw e.mode=A,e}if(r.type===`end`){let e=C(r);if(e!==Ne)return e}if(r.type===`illegal`&&a===``)return r.index===n.length||(N+=`
|
|
71
|
+
`),1;if(re>1e5&&re>r.index*3)throw Error(`potential infinite loop, way more iterations than matches`);return N+=a,a.length}let D=M(e);if(!D)throw _e(s.replace(`{}`,e)),Error(`Unknown language: "`+e+`"`);let O=Ee(D),k=``,A=a||O,ee={},j=new l.__emitter(l);w();let N=``,te=0,ne=0,re=0,ie=!1;try{if(D.__emitTokens)D.__emitTokens(n,j);else{for(A.matcher.considerAll();;){re++,ie?ie=!1:A.matcher.considerAll(),A.matcher.lastIndex=ne;let e=A.matcher.exec(n);if(!e)break;let t=E(n.substring(ne,e.index),e);ne=e.index+t}E(n.substring(ne))}return j.finalize(),k=j.toHTML(),{language:e,value:k,relevance:te,illegal:!1,_emitter:j,_top:A}}catch(t){if(t.message&&t.message.includes(`Illegal`))return{language:e,value:je(n),illegal:!0,relevance:0,_illegalBy:{message:t.message,index:ne,context:n.slice(ne-100,ne+100),mode:t.mode,resultSoFar:k},_emitter:j};if(o)return{language:e,value:je(n),illegal:!1,relevance:0,errorRaised:t,_emitter:j,_top:A};throw t}}function b(e){let t={value:je(e),illegal:!1,relevance:0,_top:c,_emitter:new l.__emitter(l)};return t._emitter.addText(e),t}function S(e,n){n=n||l.languages||Object.keys(t);let r=b(e),i=n.filter(M).filter(te).map(t=>v(t,e,!1));i.unshift(r);let[a,o]=i.sort((e,t)=>{if(e.relevance!==t.relevance)return t.relevance-e.relevance;if(e.language&&t.language){if(M(e.language).supersetOf===t.language)return 1;if(M(t.language).supersetOf===e.language)return-1}return 0}),s=a;return s.secondBest=o,s}function C(e,t,n){let r=t&&i[t]||n;e.classList.add(`hljs`),e.classList.add(`language-${r}`)}function w(e){let t=null,n=d(e);if(u(n))return;if(ae(`before:highlightElement`,{el:e,language:n}),e.dataset.highlighted){console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e);return}if(e.children.length>0&&(l.ignoreUnescapedHTML||(console.warn(`One of your code blocks includes unescaped HTML. This is a potentially serious security risk.`),console.warn(`https://github.com/highlightjs/highlight.js/wiki/security`),console.warn(`The element with unescaped HTML:`),console.warn(e)),l.throwUnescapedHTML))throw new Ae(`One of your code blocks includes unescaped HTML.`,e.innerHTML);t=e;let r=t.textContent,i=n?p(r,{language:n,ignoreIllegals:!0}):S(r);e.innerHTML=i.value,e.dataset.highlighted=`yes`,C(e,n,i.language),e.result={language:i.language,re:i.relevance,relevance:i.relevance},i.secondBest&&(e.secondBest={language:i.secondBest.language,relevance:i.secondBest.relevance}),ae(`after:highlightElement`,{el:e,result:i,text:r})}function T(e){l=Me(l,e)}let E=()=>{k(),ye(`10.6.0`,`initHighlighting() deprecated. Use highlightAll() now.`)};function D(){k(),ye(`10.6.0`,`initHighlightingOnLoad() deprecated. Use highlightAll() now.`)}let O=!1;function k(){function e(){k()}if(document.readyState===`loading`){O||window.addEventListener(`DOMContentLoaded`,e,!1),O=!0;return}document.querySelectorAll(l.cssSelector).forEach(w)}function A(n,r){let i=null;try{i=r(e)}catch(e){if(_e(`Language definition for '{}' could not be registered.`.replace(`{}`,n)),o)_e(e);else throw e;i=c}i.name||(i.name=n),t[n]=i,i.rawDefinition=r.bind(null,e),i.aliases&&N(i.aliases,{languageName:n})}function ee(e){delete t[e];for(let t of Object.keys(i))i[t]===e&&delete i[t]}function j(){return Object.keys(t)}function M(e){return e=(e||``).toLowerCase(),t[e]||t[i[e]]}function N(e,{languageName:t}){typeof e==`string`&&(e=[e]),e.forEach(e=>{i[e.toLowerCase()]=t})}function te(e){let t=M(e);return t&&!t.disableAutodetect}function ne(e){e[`before:highlightBlock`]&&!e[`before:highlightElement`]&&(e[`before:highlightElement`]=t=>{e[`before:highlightBlock`](Object.assign({block:t.el},t))}),e[`after:highlightBlock`]&&!e[`after:highlightElement`]&&(e[`after:highlightElement`]=t=>{e[`after:highlightBlock`](Object.assign({block:t.el},t))})}function re(e){ne(e),a.push(e)}function ie(e){let t=a.indexOf(e);t!==-1&&a.splice(t,1)}function ae(e,t){let n=e;a.forEach(function(e){e[n]&&e[n](t)})}function se(e){return ye(`10.7.0`,`highlightBlock will be removed entirely in v12.0`),ye(`10.7.0`,`Please use highlightElement now.`),w(e)}Object.assign(e,{highlight:p,highlightAuto:S,highlightAll:k,highlightElement:w,highlightBlock:se,configure:T,initHighlighting:E,initHighlightingOnLoad:D,registerLanguage:A,unregisterLanguage:ee,listLanguages:j,getLanguage:M,registerAliases:N,autoDetection:te,inherit:Me,addPlugin:re,removePlugin:ie}),e.debugMode=function(){o=!1},e.safeMode=function(){o=!0},e.versionString=ke,e.regex={concat:_,lookahead:m,either:y,optional:g,anyNumberOfTimes:h};for(let e in oe)typeof oe[e]==`object`&&n(oe[e]);return Object.assign(e,oe),e},Ie=Fe({});Ie.newInstance=()=>Fe({}),t.exports=Ie,Ie.HighlightJS=Ie,Ie.default=Ie}))()).default;function Ir(e){let t=e.regex,n={},r={begin:/\$\{/,end:/\}/,contains:[`self`,{begin:/:-/,contains:[n]}]};Object.assign(n,{className:`variable`,variants:[{begin:t.concat(/\$[\w\d#@][\w\d_]*/,`(?![\\w\\d])(?![$])`)},r]});let i={className:`subst`,begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},a=e.inherit(e.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:`comment`}}),o={begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:`string`})]}},s={className:`string`,begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,n,i]};i.contains.push(s);let c={match:/\\"/},l={className:`string`,begin:/'/,end:/'/},u={match:/\\'/},d={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:`number`},e.NUMBER_MODE,n]},f=e.SHEBANG({binary:`(${[`fish`,`bash`,`zsh`,`sh`,`csh`,`ksh`,`tcsh`,`dash`,`scsh`].join(`|`)})`,relevance:10}),p={className:`function`,begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0},m=[`if`,`then`,`else`,`elif`,`fi`,`time`,`for`,`while`,`until`,`in`,`do`,`done`,`case`,`esac`,`coproc`,`function`,`select`],h=[`true`,`false`],g={match:/(\/[a-z._-]+)+/},_=[`break`,`cd`,`continue`,`eval`,`exec`,`exit`,`export`,`getopts`,`hash`,`pwd`,`readonly`,`return`,`shift`,`test`,`times`,`trap`,`umask`,`unset`],v=[`alias`,`bind`,`builtin`,`caller`,`command`,`declare`,`echo`,`enable`,`help`,`let`,`local`,`logout`,`mapfile`,`printf`,`read`,`readarray`,`source`,`sudo`,`type`,`typeset`,`ulimit`,`unalias`],y=`autoload.bg.bindkey.bye.cap.chdir.clone.comparguments.compcall.compctl.compdescribe.compfiles.compgroups.compquote.comptags.comptry.compvalues.dirs.disable.disown.echotc.echoti.emulate.fc.fg.float.functions.getcap.getln.history.integer.jobs.kill.limit.log.noglob.popd.print.pushd.pushln.rehash.sched.setcap.setopt.stat.suspend.ttyctl.unfunction.unhash.unlimit.unsetopt.vared.wait.whence.where.which.zcompile.zformat.zftp.zle.zmodload.zparseopts.zprof.zpty.zregexparse.zsocket.zstyle.ztcp`.split(`.`),b=`chcon.chgrp.chown.chmod.cp.dd.df.dir.dircolors.ln.ls.mkdir.mkfifo.mknod.mktemp.mv.realpath.rm.rmdir.shred.sync.touch.truncate.vdir.b2sum.base32.base64.cat.cksum.comm.csplit.cut.expand.fmt.fold.head.join.md5sum.nl.numfmt.od.paste.ptx.pr.sha1sum.sha224sum.sha256sum.sha384sum.sha512sum.shuf.sort.split.sum.tac.tail.tr.tsort.unexpand.uniq.wc.arch.basename.chroot.date.dirname.du.echo.env.expr.factor.groups.hostid.id.link.logname.nice.nohup.nproc.pathchk.pinky.printenv.printf.pwd.readlink.runcon.seq.sleep.stat.stdbuf.stty.tee.test.timeout.tty.uname.unlink.uptime.users.who.whoami.yes`.split(`.`);return{name:`Bash`,aliases:[`sh`,`zsh`],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:m,literal:h,built_in:[..._,...v,`set`,`shopt`,...y,...b]},contains:[f,e.SHEBANG(),p,d,a,o,g,s,c,l,u,n]}}var Lr=e=>({IMPORTANT:{scope:`meta`,begin:`!important`},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:`number`,begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},UNICODE_RANGE:{scope:`number`,begin:/\b[Uu]\+[0-9A-Fa-f][0-9A-Fa-f?]{0,5}(-[0-9A-Fa-f][0-9A-Fa-f]{0,5})?/},FUNCTION_DISPATCH:{className:`built_in`,begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:`selector-attr`,begin:/\[/,end:/\]/,illegal:`$`,contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:`number`,begin:e.NUMBER_RE+`(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?`,relevance:0},CSS_VARIABLE:{className:`attr`,begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),Rr=`a.abbr.address.article.aside.audio.b.blockquote.body.button.canvas.caption.cite.code.dd.del.details.dfn.div.dl.dt.em.fieldset.figcaption.figure.footer.form.h1.h2.h3.h4.h5.h6.header.hgroup.html.i.iframe.img.input.ins.kbd.label.legend.li.main.mark.menu.nav.object.ol.optgroup.option.p.picture.q.quote.samp.section.select.source.span.strong.summary.sup.table.tbody.td.textarea.tfoot.th.thead.time.tr.ul.var.video`.split(`.`),zr=`defs.g.marker.mask.pattern.svg.switch.symbol.feBlend.feColorMatrix.feComponentTransfer.feComposite.feConvolveMatrix.feDiffuseLighting.feDisplacementMap.feFlood.feGaussianBlur.feImage.feMerge.feMorphology.feOffset.feSpecularLighting.feTile.feTurbulence.linearGradient.radialGradient.stop.circle.ellipse.image.line.path.polygon.polyline.rect.text.use.textPath.tspan.foreignObject.clipPath`.split(`.`),Br=[...Rr,...zr],Vr=`any-hover.any-pointer.aspect-ratio.color.color-gamut.color-index.device-aspect-ratio.device-height.device-width.display-mode.forced-colors.grid.height.hover.inverted-colors.monochrome.orientation.overflow-block.overflow-inline.pointer.prefers-color-scheme.prefers-contrast.prefers-reduced-motion.prefers-reduced-transparency.resolution.scan.scripting.update.width.min-width.max-width.min-height.max-height`.split(`.`).sort().reverse(),Hr=`active.any-link.blank.checked.current.default.defined.dir.disabled.drop.empty.enabled.first.first-child.first-of-type.fullscreen.future.focus.focus-visible.focus-within.has.host.host-context.hover.indeterminate.in-range.invalid.is.lang.last-child.last-of-type.left.link.local-link.not.nth-child.nth-col.nth-last-child.nth-last-col.nth-last-of-type.nth-of-type.only-child.only-of-type.optional.out-of-range.past.placeholder-shown.read-only.read-write.required.right.root.scope.target.target-within.user-invalid.valid.visited.where`.split(`.`).sort().reverse(),Ur=[`after`,`backdrop`,`before`,`cue`,`cue-region`,`first-letter`,`first-line`,`grammar-error`,`marker`,`part`,`placeholder`,`selection`,`slotted`,`spelling-error`].sort().reverse(),Wr=`accent-color.align-content.align-items.align-self.alignment-baseline.all.anchor-name.animation.animation-composition.animation-delay.animation-direction.animation-duration.animation-fill-mode.animation-iteration-count.animation-name.animation-play-state.animation-range.animation-range-end.animation-range-start.animation-timeline.animation-timing-function.appearance.aspect-ratio.backdrop-filter.backface-visibility.background.background-attachment.background-blend-mode.background-clip.background-color.background-image.background-origin.background-position.background-position-x.background-position-y.background-repeat.background-size.baseline-shift.block-size.border.border-block.border-block-color.border-block-end.border-block-end-color.border-block-end-style.border-block-end-width.border-block-start.border-block-start-color.border-block-start-style.border-block-start-width.border-block-style.border-block-width.border-bottom.border-bottom-color.border-bottom-left-radius.border-bottom-right-radius.border-bottom-style.border-bottom-width.border-collapse.border-color.border-end-end-radius.border-end-start-radius.border-image.border-image-outset.border-image-repeat.border-image-slice.border-image-source.border-image-width.border-inline.border-inline-color.border-inline-end.border-inline-end-color.border-inline-end-style.border-inline-end-width.border-inline-start.border-inline-start-color.border-inline-start-style.border-inline-start-width.border-inline-style.border-inline-width.border-left.border-left-color.border-left-style.border-left-width.border-radius.border-right.border-right-color.border-right-style.border-right-width.border-spacing.border-start-end-radius.border-start-start-radius.border-style.border-top.border-top-color.border-top-left-radius.border-top-right-radius.border-top-style.border-top-width.border-width.bottom.box-align.box-decoration-break.box-direction.box-flex.box-flex-group.box-lines.box-ordinal-group.box-orient.box-pack.box-shadow.box-sizing.break-after.break-before.break-inside.caption-side.caret-color.clear.clip.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.color-scheme.column-count.column-fill.column-gap.column-rule.column-rule-color.column-rule-style.column-rule-width.column-span.column-width.columns.contain.contain-intrinsic-block-size.contain-intrinsic-height.contain-intrinsic-inline-size.contain-intrinsic-size.contain-intrinsic-width.container.container-name.container-type.content.content-visibility.corner-bottom-left-shape.corner-bottom-right-shape.corner-shape.corner-top-left-shape.corner-top-right-shape.counter-increment.counter-reset.counter-set.cue.cue-after.cue-before.cursor.cx.cy.direction.display.dominant-baseline.empty-cells.enable-background.field-sizing.fill.fill-opacity.fill-rule.filter.flex.flex-basis.flex-direction.flex-flow.flex-grow.flex-shrink.flex-wrap.float.flood-color.flood-opacity.flow.font.font-display.font-family.font-feature-settings.font-kerning.font-language-override.font-optical-sizing.font-palette.font-size.font-size-adjust.font-smooth.font-smoothing.font-stretch.font-style.font-synthesis.font-synthesis-position.font-synthesis-small-caps.font-synthesis-style.font-synthesis-weight.font-variant.font-variant-alternates.font-variant-caps.font-variant-east-asian.font-variant-emoji.font-variant-ligatures.font-variant-numeric.font-variant-position.font-variation-settings.font-weight.forced-color-adjust.gap.glyph-orientation-horizontal.glyph-orientation-vertical.grid.grid-area.grid-auto-columns.grid-auto-flow.grid-auto-rows.grid-column.grid-column-end.grid-column-start.grid-gap.grid-row.grid-row-end.grid-row-start.grid-template.grid-template-areas.grid-template-columns.grid-template-rows.hanging-punctuation.height.hyphenate-character.hyphenate-limit-chars.hyphens.icon.image-orientation.image-rendering.image-resolution.ime-mode.initial-letter.initial-letter-align.inline-size.inset.inset-area.inset-block.inset-block-end.inset-block-start.inset-inline.inset-inline-end.inset-inline-start.isolation.justify-content.justify-items.justify-self.kerning.left.letter-spacing.lighting-color.line-break.line-height.line-height-step.list-style.list-style-image.list-style-position.list-style-type.margin.margin-block.margin-block-end.margin-block-start.margin-bottom.margin-inline.margin-inline-end.margin-inline-start.margin-left.margin-right.margin-top.margin-trim.marker.marker-end.marker-mid.marker-start.marks.mask.mask-border.mask-border-mode.mask-border-outset.mask-border-repeat.mask-border-slice.mask-border-source.mask-border-width.mask-clip.mask-composite.mask-image.mask-mode.mask-origin.mask-position.mask-repeat.mask-size.mask-type.masonry-auto-flow.math-depth.math-shift.math-style.max-block-size.max-height.max-inline-size.max-width.min-block-size.min-height.min-inline-size.min-width.mix-blend-mode.nav-down.nav-index.nav-left.nav-right.nav-up.none.normal.object-fit.object-position.offset.offset-anchor.offset-distance.offset-path.offset-position.offset-rotate.opacity.order.orphans.outline.outline-color.outline-offset.outline-style.outline-width.overflow.overflow-anchor.overflow-block.overflow-clip-margin.overflow-inline.overflow-wrap.overflow-x.overflow-y.overlay.overscroll-behavior.overscroll-behavior-block.overscroll-behavior-inline.overscroll-behavior-x.overscroll-behavior-y.padding.padding-block.padding-block-end.padding-block-start.padding-bottom.padding-inline.padding-inline-end.padding-inline-start.padding-left.padding-right.padding-top.page.page-break-after.page-break-before.page-break-inside.paint-order.pause.pause-after.pause-before.perspective.perspective-origin.place-content.place-items.place-self.pointer-events.position.position-anchor.position-visibility.print-color-adjust.quotes.r.resize.rest.rest-after.rest-before.right.rotate.row-gap.ruby-align.ruby-position.scale.scroll-behavior.scroll-margin.scroll-margin-block.scroll-margin-block-end.scroll-margin-block-start.scroll-margin-bottom.scroll-margin-inline.scroll-margin-inline-end.scroll-margin-inline-start.scroll-margin-left.scroll-margin-right.scroll-margin-top.scroll-padding.scroll-padding-block.scroll-padding-block-end.scroll-padding-block-start.scroll-padding-bottom.scroll-padding-inline.scroll-padding-inline-end.scroll-padding-inline-start.scroll-padding-left.scroll-padding-right.scroll-padding-top.scroll-snap-align.scroll-snap-stop.scroll-snap-type.scroll-timeline.scroll-timeline-axis.scroll-timeline-name.scrollbar-color.scrollbar-gutter.scrollbar-width.shape-image-threshold.shape-margin.shape-outside.shape-rendering.speak.speak-as.src.stop-color.stop-opacity.stroke.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke-width.tab-size.table-layout.text-align.text-align-all.text-align-last.text-anchor.text-combine-upright.text-decoration.text-decoration-color.text-decoration-line.text-decoration-skip.text-decoration-skip-ink.text-decoration-style.text-decoration-thickness.text-emphasis.text-emphasis-color.text-emphasis-position.text-emphasis-style.text-indent.text-justify.text-orientation.text-overflow.text-rendering.text-shadow.text-size-adjust.text-transform.text-underline-offset.text-underline-position.text-wrap.text-wrap-mode.text-wrap-style.timeline-scope.top.touch-action.transform.transform-box.transform-origin.transform-style.transition.transition-behavior.transition-delay.transition-duration.transition-property.transition-timing-function.translate.unicode-bidi.unicode-range.user-modify.user-select.vector-effect.vertical-align.view-timeline.view-timeline-axis.view-timeline-inset.view-timeline-name.view-transition-name.visibility.voice-balance.voice-duration.voice-family.voice-pitch.voice-range.voice-rate.voice-stress.voice-volume.white-space.white-space-collapse.widows.width.will-change.word-break.word-spacing.word-wrap.writing-mode.x.y.z-index.zoom`.split(`.`).sort().reverse();function Gr(e){let t=e.regex,n=Lr(e),r={begin:/-(webkit|moz|ms|o)-(?=[a-z])/},i=/@-?\w[\w]*(-\w+)*/,a=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return{name:`CSS`,case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:`from to`},classNameAliases:{keyframePosition:`selector-tag`},contains:[n.BLOCK_COMMENT,r,n.CSS_NUMBER_MODE,{className:`selector-id`,begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:`selector-class`,begin:`\\.[a-zA-Z-][a-zA-Z0-9_-]*`,relevance:0},n.ATTRIBUTE_SELECTOR_MODE,{className:`selector-pseudo`,variants:[{begin:`:(`+Hr.join(`|`)+`)`},{begin:`:(:)?(`+Ur.join(`|`)+`)`}]},n.CSS_VARIABLE,{className:`attribute`,begin:`\\b(`+Wr.join(`|`)+`)\\b`},{begin:/:/,end:/[;}{]/,contains:[n.BLOCK_COMMENT,n.HEXCOLOR,n.IMPORTANT,n.CSS_NUMBER_MODE,n.UNICODE_RANGE,...a,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:`url data-uri`},contains:[...a,{className:`string`,begin:/[^)]/,endsWithParent:!0,excludeEnd:!0}]},n.FUNCTION_DISPATCH]},{begin:t.lookahead(/@/),end:`[{;]`,relevance:0,illegal:/:/,contains:[{className:`keyword`,begin:i},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:`and or not only`,attribute:Vr.join(` `)},contains:[{begin:/[a-z-]+(?=:)/,className:`attribute`},...a,n.CSS_NUMBER_MODE]}]},{className:`selector-tag`,begin:`\\b(`+Br.join(`|`)+`)\\b`}]}}function Kr(e){let t=e.regex;return{name:`Diff`,aliases:[`patch`],contains:[{className:`meta`,relevance:10,match:t.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^@@ +-\d+ +\+\d+,\d+ +@@/,/^@@ +-\d+,\d+ +\+\d+ +@@/,/^@@ +-\d+ +\+\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/)},{className:`comment`,variants:[{begin:t.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/),end:/$/},{match:/^\*{15}$/}]},{className:`addition`,begin:/^\+/,end:/$/},{className:`deletion`,begin:/^-/,end:/$/},{className:`addition`,begin:/^!/,end:/$/}]}}function qr(e){let t={keyword:[`break`,`case`,`chan`,`const`,`continue`,`default`,`defer`,`else`,`fallthrough`,`for`,`func`,`go`,`goto`,`if`,`import`,`interface`,`map`,`package`,`range`,`return`,`select`,`struct`,`switch`,`type`,`var`],type:[`bool`,`byte`,`complex64`,`complex128`,`error`,`float32`,`float64`,`int8`,`int16`,`int32`,`int64`,`string`,`uint8`,`uint16`,`uint32`,`uint64`,`int`,`uint`,`uintptr`,`rune`],literal:[`true`,`false`,`iota`,`nil`],built_in:[`append`,`cap`,`close`,`complex`,`copy`,`imag`,`len`,`make`,`new`,`panic`,`print`,`println`,`real`,`recover`,`delete`]};return{name:`Go`,aliases:[`golang`],keywords:t,illegal:`</`,contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:`string`,variants:[e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,{begin:"`",end:"`"}]},{className:`number`,variants:[{match:/-?\b0[xX]\.[a-fA-F0-9](_?[a-fA-F0-9])*[pP][+-]?\d(_?\d)*i?/,relevance:0},{match:/-?\b0[xX](_?[a-fA-F0-9])+((\.([a-fA-F0-9](_?[a-fA-F0-9])*)?)?[pP][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b0[oO](_?[0-7])*i?/,relevance:0},{match:/-?\b0[bB](_?[01])*i?/,relevance:0},{match:/-?\.\d(_?\d)*([eE][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b\d(_?\d)*(\.(\d(_?\d)*)?)?([eE][+-]?\d(_?\d)*)?i?/,relevance:0}]},{begin:/:=/},{className:`function`,beginKeywords:`func`,end:`\\s*(\\{|$)`,excludeEnd:!0,contains:[e.TITLE_MODE,{className:`params`,begin:/\(/,end:/\)/,endsParent:!0,keywords:t,illegal:/["']/}]}]}}var Jr=`[A-Za-z$_][0-9A-Za-z$_]*`,Yr=`as.in.of.if.for.while.finally.var.new.function.do.return.void.else.break.catch.instanceof.with.throw.case.default.try.switch.continue.typeof.delete.let.yield.const.class.debugger.async.await.static.import.from.export.extends.using`.split(`.`),Xr=[`true`,`false`,`null`,`undefined`,`NaN`,`Infinity`],Zr=`Object.Function.Boolean.Symbol.Math.Date.Number.BigInt.String.RegExp.Array.Float32Array.Float64Array.Int8Array.Uint8Array.Uint8ClampedArray.Int16Array.Int32Array.Uint16Array.Uint32Array.BigInt64Array.BigUint64Array.Set.Map.WeakSet.WeakMap.ArrayBuffer.SharedArrayBuffer.Atomics.DataView.JSON.Promise.Generator.GeneratorFunction.AsyncFunction.Reflect.Proxy.Intl.WebAssembly`.split(`.`),Qr=[`Error`,`EvalError`,`InternalError`,`RangeError`,`ReferenceError`,`SyntaxError`,`TypeError`,`URIError`],$r=[`setInterval`,`setTimeout`,`clearInterval`,`clearTimeout`,`require`,`exports`,`eval`,`isFinite`,`isNaN`,`parseFloat`,`parseInt`,`decodeURI`,`decodeURIComponent`,`encodeURI`,`encodeURIComponent`,`escape`,`unescape`],ei=[`arguments`,`this`,`super`,`console`,`window`,`document`,`localStorage`,`sessionStorage`,`module`,`self`,`global`],ti=[].concat($r,Zr,Qr);function ni(e){let t=e.regex,n=(e,{after:t})=>{let n=`</`+e[0].slice(1);return e.input.indexOf(n,t)!==-1},r=Jr,i={begin:`<>`,end:`</>`},a=/<[A-Za-z0-9\\._:-]+\s*\/>/,o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,t)=>{let r=e[0].length+e.index,i=e.input[r];if(i===`<`||i===`,`){t.ignoreMatch();return}i===`>`&&(n(e,{after:r})||t.ignoreMatch());let a,o=e.input.substring(r);if(a=o.match(/^\s*=/)){t.ignoreMatch();return}if((a=o.match(/^\s+extends\s+/))&&a.index===0){t.ignoreMatch();return}}},s={$pattern:Jr,keyword:Yr,literal:Xr,built_in:ti,"variable.language":ei},c=`[0-9](_?[0-9])*`,l=`\\.(${c})`,u=`0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`,d={className:`number`,variants:[{begin:`(\\b(${u})((${l})|\\.)?|(${l}))[eE][+-]?(${c})\\b`},{begin:`\\b(${u})\\b((${l})\\b|\\.)?|(${l})\\b`},{begin:`\\b(0|[1-9](_?[0-9])*)n\\b`},{begin:`\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b`},{begin:`\\b0[bB][0-1](_?[0-1])*n?\\b`},{begin:`\\b0[oO][0-7](_?[0-7])*n?\\b`},{begin:`\\b0[0-7]+n?\\b`}],relevance:0},f={className:`subst`,begin:`\\$\\{`,end:`\\}`,keywords:s,contains:[]},p={begin:".?html`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`xml`}},m={begin:".?css`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`css`}},h={begin:".?gql`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`graphql`}},g={className:`string`,begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,f]},_={className:`comment`,variants:[e.COMMENT(/\/\*\*(?!\/)/,`\\*/`,{relevance:0,contains:[{begin:`(?=@[A-Za-z]+)`,relevance:0,contains:[{className:`doctag`,begin:`@[A-Za-z]+`},{className:`type`,begin:`\\{`,end:`\\}`,excludeEnd:!0,excludeBegin:!0,relevance:0},{className:`variable`,begin:r+`(?=\\s*(-)|$)`,endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},v=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,m,h,g,{match:/\$\d+/},d];f.contains=v.concat({begin:/\{/,end:/\}/,keywords:s,contains:[`self`].concat(v)});let y=[].concat(_,f.contains),b=y.concat([{begin:/(\s*)\(/,end:/\)/,keywords:s,contains:[`self`].concat(y)}]),x={className:`params`,begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b},S={variants:[{match:[/class/,/\s+/,r,/\s+/,/extends/,/\s+/,t.concat(r,`(`,t.concat(/\./,r),`)*`)],scope:{1:`keyword`,3:`title.class`,5:`keyword`,7:`title.class.inherited`}},{match:[/class/,/\s+/,r],scope:{1:`keyword`,3:`title.class`}}]},C={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:`title.class`,keywords:{_:[...Zr,...Qr]}},w={label:`use_strict`,className:`meta`,relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},T={variants:[{match:[/function/,/\s+/,r,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:`keyword`,3:`title.function`},label:`func.def`,contains:[x],illegal:/%/},E={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:`variable.constant`};function D(e){return t.concat(`(?!`,e.join(`|`),`)`)}let O={match:t.concat(/\b/,D([...$r,`super`,`import`,`await`].map(e=>`${e}\\s*\\(`)),r,t.lookahead(/\s*\(/)),className:`title.function`,relevance:0},k={begin:t.concat(/\./,t.lookahead(t.concat(r,/(?![0-9A-Za-z$_(])/))),end:r,excludeBegin:!0,keywords:`prototype`,className:`property`,relevance:0},A={match:[/get|set/,/\s+/,r,/(?=\()/],className:{1:`keyword`,3:`title.function`},contains:[{begin:/\(\)/},x]},ee=`(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|`+e.UNDERSCORE_IDENT_RE+`)\\s*=>`,j={match:[/const|var|let/,/\s+/,r,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(ee)],keywords:`async`,className:{1:`keyword`,3:`title.function`},contains:[x]};return{name:`JavaScript`,aliases:[`js`,`jsx`,`mjs`,`cjs`],keywords:s,exports:{PARAMS_CONTAINS:b,CLASS_REFERENCE:C},illegal:/#(?![$_A-Za-z])/,contains:[e.SHEBANG({label:`shebang`,binary:`node`,relevance:5}),w,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,m,h,g,_,{match:/\$\d+/},d,C,{scope:`attr`,match:r+t.lookahead(`:`),relevance:0},j,{begin:`(`+e.RE_STARTERS_RE+`|\\b(case|return|throw)\\b)\\s*`,keywords:`return throw case`,relevance:0,contains:[_,e.REGEXP_MODE,{className:`function`,begin:ee,returnBegin:!0,end:`\\s*=>`,contains:[{className:`params`,variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:i.begin,end:i.end},{match:a},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:`xml`,contains:[{begin:o.begin,end:o.end,skip:!0,contains:[`self`]}]}]},T,{beginKeywords:`while if switch catch for`},{begin:`\\b(?!function)`+e.UNDERSCORE_IDENT_RE+`\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{`,returnBegin:!0,label:`func.def`,contains:[x,e.inherit(e.TITLE_MODE,{begin:r,className:`title.function`})]},{match:/\.\.\./,relevance:0},k,{match:`\\$`+r,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:`title.function`},contains:[x]},O,E,S,A,{match:/\$[(.]/}]}}var ri={scope:`number`,match:`([-+]?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)|NaN|[-+]?Infinity`,relevance:0};function ii(e){let t={className:`attr`,begin:/(("(\\.|[^\\"\r\n])*")|('(\\.|[^\\'\r\n])*'))(?=\s*:)/,relevance:1.01},n={match:/[{}[\],:]/,className:`punctuation`,relevance:0},r=[`true`,`false`,`null`],i={scope:`literal`,beginKeywords:r.join(` `)};return{name:`JSON`,aliases:[`jsonc`,`json5`],keywords:{literal:r},contains:[t,n,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,i,ri,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],illegal:`\\S`}}function ai(e){let t=e.regex,n={begin:/<\/?[A-Za-z_]/,end:`>`,subLanguage:`xml`,relevance:0},r={match:/^ {0,3}([-*_])[ \t]*(?:\1[ \t]*){2,}$/},i={className:`code`,variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{begin:`(~{3,})[^~](.|\\n)*?\\1~*[ ]*`},{begin:"```",end:"```+[ ]*$"},{begin:`~~~`,end:`~~~+[ ]*$`},{begin:"`.+?`"},{begin:`(?=^( {4}|\\t))`,contains:[{begin:`^( {4}|\\t)`,end:`(\\n)$`}],relevance:0}]},a={className:`bullet`,begin:`^[ ]*([*+-]|(\\d+\\.))(?=\\s+)`,end:`\\s+`,excludeEnd:!0},o={begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:`symbol`,begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:`link`,begin:/:\s*/,end:/$/,excludeBegin:!0}]},s={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,relevance:2},{begin:t.concat(/\[.+?\]\(/,/[A-Za-z][A-Za-z0-9+.-]*/,/:\/\/.*?\)/),relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/},{className:`string`,relevance:0,begin:`\\[`,end:`\\]`,excludeBegin:!0,returnEnd:!0},{className:`link`,relevance:0,begin:`\\]\\(`,end:`\\)`,excludeBegin:!0,excludeEnd:!0},{className:`symbol`,relevance:0,begin:`\\]\\[`,end:`\\]`,excludeBegin:!0,excludeEnd:!0}]},c={className:`strong`,contains:[],variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}]},l={className:`emphasis`,contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{begin:/_(?![_\s])/,end:/_/,relevance:0}]},u=e.inherit(c,{contains:[]}),d=e.inherit(l,{contains:[]});c.contains.push(d),l.contains.push(u);let f=[n,s];return[c,l,u,d].forEach(e=>{e.contains=e.contains.concat(f)}),f=f.concat(c,l),{name:`Markdown`,aliases:[`md`,`mkdown`,`mkd`],contains:[{className:`section`,variants:[{begin:`^#{1,6}`,end:`$`,contains:f},{begin:`(?=^.+?\\n[=-]{2,}$)`,contains:[{begin:`^[=-]*$`},{begin:`^`,end:`\\n`,contains:f}]}]},n,a,r,c,l,{className:`quote`,begin:`^>\\s+`,contains:f,end:`$`},i,s,o,{scope:`literal`,match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}}function oi(e){let t=e.regex,n=/[\p{XID_Start}_]\p{XID_Continue}*/u,r=`and.as.assert.async.await.break.case.class.continue.def.del.elif.else.except.finally.for.from.global.if.import.in.is.lambda.lazy.match.nonlocal|10.not.or.pass.raise.return.try.while.with.yield`.split(`.`),i={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:r,built_in:`__import__.abs.aiter.all.anext.any.ascii.bin.bool.breakpoint.bytearray.bytes.callable.chr.classmethod.compile.complex.delattr.dict.dir.divmod.enumerate.eval.exec.filter.float.format.frozendict.frozenset.getattr.globals.hasattr.hash.help.hex.id.input.int.isinstance.issubclass.iter.len.list.locals.map.max.memoryview.min.next.object.oct.open.ord.pow.print.property.range.repr.reversed.round.sentinel.set.setattr.slice.sorted.staticmethod.str.sum.super.tuple.type.vars.zip`.split(`.`),literal:[`__debug__`,`Ellipsis`,`False`,`None`,`NotImplemented`,`True`],type:[`Any`,`Callable`,`Coroutine`,`Dict`,`List`,`Literal`,`Generic`,`Optional`,`Sequence`,`Set`,`Tuple`,`Type`,`Union`]},a={className:`meta`,begin:/^(>>>|\.\.\.) /},o={className:`subst`,begin:/\{/,end:/\}/,keywords:i,illegal:/#/},s={begin:/\{\{/,relevance:0},c={className:`string`,contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,a],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,a],relevance:10},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,a,s,o]},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,a,s,o]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])'/,end:/'/,contains:[e.BACKSLASH_ESCAPE,s,o]},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,s,o]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},l=`[0-9](_?[0-9])*`,u=`(\\b(${l}))?\\.(${l})|\\b(${l})\\.`,d=`\\b|${r.join(`|`)}`,f={className:`number`,relevance:0,variants:[{begin:`(\\b(${l})|(${u}))[eE][+-]?(${l})[jJ]?(?=${d})`},{begin:`(${u})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${d})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${d})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${d})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${d})`},{begin:`\\b(${l})[jJ](?=${d})`}]},p={className:`comment`,begin:t.lookahead(/# type:/),end:/$/,keywords:i,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},m={className:`params`,variants:[{className:``,begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:i,contains:[`self`,a,f,c,e.HASH_COMMENT_MODE]}]};return o.contains=[c,f,a],{name:`Python`,aliases:[`py`,`gyp`,`ipython`],unicodeRegex:!0,keywords:i,illegal:/(<\/|\?)|=>/,contains:[a,f,{scope:`variable.language`,match:/\bself\b/},{beginKeywords:`if`,relevance:0},{match:/\bor\b/,scope:`keyword`},c,p,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,n],scope:{1:`keyword`,3:`title.function`},contains:[m]},{variants:[{match:[/\bclass/,/\s+/,n,/\s*/,/\(\s*/,n,/\s*\)/]},{match:[/\bclass/,/\s+/,n]}],scope:{1:`keyword`,3:`title.class`,6:`title.class.inherited`}},{className:`meta`,begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[f,m,c]}]}}function si(e){let t=e.regex,n=/(r#)?/,r=t.concat(n,e.UNDERSCORE_IDENT_RE),i=t.concat(n,e.IDENT_RE),a={scope:`title.function.invoke`,relevance:0,begin:t.concat(/\b/,/(?!(?:let|for|while|if|else|match)\b)/,i,t.lookahead(/\s*\(/))},o=`([ui](8|16|32|64|128|size)|f(16|32|64|128))?`,s=`abstract.as.async.await.become.box.break.const.continue.crate.do.dyn.else.enum.extern.false.final.fn.for.if.impl.in.let.loop.macro.match.mod.move.mut.override.priv.pub.raw.ref.return.self.Self.static.struct.super.trait.true.try.type.typeof.union.unsafe.unsized.use.virtual.where.while.yield`.split(`.`),c=[`true`,`false`,`Some`,`None`,`Ok`,`Err`],l=`drop .Copy.Send.Sized.Sync.Drop.Fn.FnMut.FnOnce.ToOwned.Clone.Debug.PartialEq.PartialOrd.Eq.Ord.AsRef.AsMut.Into.From.Default.Iterator.Extend.IntoIterator.DoubleEndedIterator.ExactSizeIterator.SliceConcatExt.ToString.assert!.assert_eq!.bitflags!.bytes!.cfg!.col!.concat!.concat_idents!.debug_assert!.debug_assert_eq!.env!.eprintln!.panic!.file!.format!.format_args!.include_bytes!.include_str!.line!.local_data_key!.module_path!.option_env!.print!.println!.select!.stringify!.try!.unimplemented!.unreachable!.vec!.write!.writeln!.macro_rules!.assert_ne!.debug_assert_ne!`.split(`.`),u=[`i8`,`i16`,`i32`,`i64`,`i128`,`isize`,`u8`,`u16`,`u32`,`u64`,`u128`,`usize`,`f16`,`f32`,`f64`,`f128`,`str`,`char`,`bool`,`Box`,`Option`,`Result`,`String`,`Vec`];return{name:`Rust`,aliases:[`rs`],keywords:{$pattern:e.IDENT_RE+`!?`,type:u,keyword:s,literal:c,built_in:l},illegal:`</`,contains:[e.C_LINE_COMMENT_MODE,e.COMMENT(`/\\*`,`\\*/`,{contains:[`self`]}),e.inherit(e.QUOTE_STRING_MODE,{begin:/b?"/,illegal:null}),{scope:`symbol`,begin:/'[a-zA-Z_][a-zA-Z0-9_]*(?!')/},{scope:`string`,variants:[{begin:/b?r(#*)"(.|\n)*?"\1(?!#)/},{begin:/b?'/,end:/'/,contains:[{scope:`char.escape`,match:/\\('|"|\\|\w|x\w{2}|u\w{4}|U\w{8})/}]}]},{scope:`number`,variants:[{begin:`\\b0b([01_]+)`+o},{begin:`\\b0o([0-7_]+)`+o},{begin:`\\b0x([A-Fa-f0-9_]+)`+o},{begin:`\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)`+o}],relevance:0},{begin:[/\bsafe/,/\s+/,/extern/],scope:{1:`keyword`,3:`keyword`}},{begin:[/fn/,/\s+/,r],scope:{1:`keyword`,3:`title.function`}},{scope:`meta`,begin:`#!?\\[`,end:`\\]`,contains:[{scope:`string`,begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE]}]},{begin:[/let/,/\s+/,/(?:mut\s+)?/,r],scope:{1:`keyword`,3:`keyword`,4:`variable`}},{begin:[/for/,/\s+/,r,/\s+/,/in/],scope:{1:`keyword`,3:`variable`,5:`keyword`}},{begin:[/type/,/\s+/,r],scope:{1:`keyword`,3:`title.class`}},{begin:[/(?:trait|enum|struct|union|impl|for)/,/\s+/,r],scope:{1:`keyword`,3:`title.class`}},{begin:e.IDENT_RE+`::`,keywords:{keyword:`Self`,built_in:l,type:u}},{scope:`punctuation`,begin:`->`},a]}}function ci(e){return{name:`Shell Session`,aliases:[`console`,`shellsession`],contains:[{className:`meta.prompt`,begin:/^\s{0,3}[./~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/,subLanguage:`bash`}}]}}function li(e){let t=e.regex,n=e.COMMENT(`--`,`$`),r={scope:`string`,variants:[{begin:/'/,end:/'/,contains:[{match:/''/}]}]},i={begin:/"/,end:/"/,contains:[{match:/""/}]},a=[`true`,`false`,`unknown`],o=[`double precision`,`large object`,`with timezone`,`without timezone`],s=`bigint.binary.blob.boolean.char.character.clob.date.dec.decfloat.decimal.float.int.integer.interval.nchar.nclob.national.numeric.real.row.smallint.time.timestamp.varchar.varying.varbinary`.split(`.`),c=[`add`,`asc`,`collation`,`desc`,`final`,`first`,`last`,`view`],l=`abs.acos.all.allocate.alter.and.any.are.array.array_agg.array_max_cardinality.as.asensitive.asin.asymmetric.at.atan.atomic.authorization.avg.begin.begin_frame.begin_partition.between.bigint.binary.blob.boolean.both.by.call.called.cardinality.cascaded.case.cast.ceil.ceiling.char.char_length.character.character_length.check.classifier.clob.close.coalesce.collate.collect.column.commit.condition.connect.constraint.contains.convert.copy.corr.corresponding.cos.cosh.count.covar_pop.covar_samp.create.cross.cube.cume_dist.current.current_catalog.current_date.current_default_transform_group.current_path.current_role.current_row.current_schema.current_time.current_timestamp.current_path.current_role.current_transform_group_for_type.current_user.cursor.cycle.date.day.deallocate.dec.decimal.decfloat.declare.default.define.delete.dense_rank.deref.describe.deterministic.disconnect.distinct.double.drop.dynamic.each.element.else.empty.end.end_frame.end_partition.end-exec.equals.escape.every.except.exec.execute.exists.exp.external.extract.false.fetch.filter.first_value.float.floor.for.foreign.frame_row.free.from.full.function.fusion.get.global.grant.group.grouping.groups.having.hold.hour.identity.in.indicator.initial.inner.inout.insensitive.insert.int.integer.intersect.intersection.interval.into.is.join.json_array.json_arrayagg.json_exists.json_object.json_objectagg.json_query.json_table.json_table_primitive.json_value.lag.language.large.last_value.lateral.lead.leading.left.like.like_regex.listagg.ln.local.localtime.localtimestamp.log.log10.lower.match.match_number.match_recognize.matches.max.member.merge.method.min.minute.mod.modifies.module.month.multiset.national.natural.nchar.nclob.new.no.none.normalize.not.nth_value.ntile.null.nullif.numeric.octet_length.occurrences_regex.of.offset.old.omit.on.one.only.open.or.order.out.outer.over.overlaps.overlay.parameter.partition.pattern.per.percent.percent_rank.percentile_cont.percentile_disc.period.portion.position.position_regex.power.precedes.precision.prepare.primary.procedure.ptf.range.rank.reads.real.recursive.ref.references.referencing.regr_avgx.regr_avgy.regr_count.regr_intercept.regr_r2.regr_slope.regr_sxx.regr_sxy.regr_syy.release.result.return.returns.revoke.right.rollback.rollup.row.row_number.rows.running.savepoint.scope.scroll.search.second.seek.select.sensitive.session_user.set.show.similar.sin.sinh.skip.smallint.some.specific.specifictype.sql.sqlexception.sqlstate.sqlwarning.sqrt.start.static.stddev_pop.stddev_samp.submultiset.subset.substring.substring_regex.succeeds.sum.symmetric.system.system_time.system_user.table.tablesample.tan.tanh.then.time.timestamp.timezone_hour.timezone_minute.to.trailing.translate.translate_regex.translation.treat.trigger.trim.trim_array.true.truncate.uescape.union.unique.unknown.unnest.update.upper.user.using.value.values.value_of.var_pop.var_samp.varbinary.varchar.varying.versioning.when.whenever.where.width_bucket.window.with.within.without.year`.split(`.`),u=`abs.acos.array_agg.asin.atan.avg.cast.ceil.ceiling.coalesce.corr.cos.cosh.count.covar_pop.covar_samp.cume_dist.dense_rank.deref.element.exp.extract.first_value.floor.json_array.json_arrayagg.json_exists.json_object.json_objectagg.json_query.json_table.json_table_primitive.json_value.lag.last_value.lead.listagg.ln.log.log10.lower.max.min.mod.nth_value.ntile.nullif.percent_rank.percentile_cont.percentile_disc.position.position_regex.power.rank.regr_avgx.regr_avgy.regr_count.regr_intercept.regr_r2.regr_slope.regr_sxx.regr_sxy.regr_syy.row_number.sin.sinh.sqrt.stddev_pop.stddev_samp.substring.substring_regex.sum.tan.tanh.translate.translate_regex.treat.trim.trim_array.unnest.upper.value_of.var_pop.var_samp.width_bucket`.split(`.`),d=[`current_catalog`,`current_date`,`current_default_transform_group`,`current_path`,`current_role`,`current_schema`,`current_transform_group_for_type`,`current_user`,`session_user`,`system_time`,`system_user`,`current_time`,`localtime`,`current_timestamp`,`localtimestamp`],f=[`create table`,`insert into`,`primary key`,`foreign key`,`not null`,`alter table`,`add constraint`,`grouping sets`,`on overflow`,`character set`,`respect nulls`,`ignore nulls`,`nulls first`,`nulls last`,`depth first`,`breadth first`],p=u,m=[...l,...c].filter(e=>!u.includes(e)),h={scope:`variable`,match:/@[a-z0-9][a-z0-9_]*/},g={scope:`operator`,match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0},_={match:t.concat(/\b/,t.either(...p),/\s*\(/),relevance:0,keywords:{built_in:p}};function v(e){return t.concat(/\b/,t.either(...e.map(e=>e.replace(/\s+/,`\\s+`))),/\b/)}let y={scope:`keyword`,match:v(f),relevance:0};function b(e,{exceptions:t,when:n}={}){let r=n;return t||=[],e.map(e=>e.match(/\|\d+$/)||t.includes(e)?e:r(e)?`${e}|0`:e)}return{name:`SQL`,case_insensitive:!0,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:b(m,{when:e=>e.length<3}),literal:a,type:s,built_in:d},contains:[{scope:`type`,match:v(o)},y,_,h,r,i,e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,n,g]}}var ui=`[A-Za-z$_][0-9A-Za-z$_]*`,di=`as.in.of.if.for.while.finally.var.new.function.do.return.void.else.break.catch.instanceof.with.throw.case.default.try.switch.continue.typeof.delete.let.yield.const.class.debugger.async.await.static.import.from.export.extends.using`.split(`.`),fi=[`true`,`false`,`null`,`undefined`,`NaN`,`Infinity`],pi=`Object.Function.Boolean.Symbol.Math.Date.Number.BigInt.String.RegExp.Array.Float32Array.Float64Array.Int8Array.Uint8Array.Uint8ClampedArray.Int16Array.Int32Array.Uint16Array.Uint32Array.BigInt64Array.BigUint64Array.Set.Map.WeakSet.WeakMap.ArrayBuffer.SharedArrayBuffer.Atomics.DataView.JSON.Promise.Generator.GeneratorFunction.AsyncFunction.Reflect.Proxy.Intl.WebAssembly`.split(`.`),mi=[`Error`,`EvalError`,`InternalError`,`RangeError`,`ReferenceError`,`SyntaxError`,`TypeError`,`URIError`],hi=[`setInterval`,`setTimeout`,`clearInterval`,`clearTimeout`,`require`,`exports`,`eval`,`isFinite`,`isNaN`,`parseFloat`,`parseInt`,`decodeURI`,`decodeURIComponent`,`encodeURI`,`encodeURIComponent`,`escape`,`unescape`],gi=[`arguments`,`this`,`super`,`console`,`window`,`document`,`localStorage`,`sessionStorage`,`module`,`self`,`global`],_i=[].concat(hi,pi,mi);function vi(e){let t=e.regex,n=(e,{after:t})=>{let n=`</`+e[0].slice(1);return e.input.indexOf(n,t)!==-1},r=ui,i={begin:`<>`,end:`</>`},a=/<[A-Za-z0-9\\._:-]+\s*\/>/,o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,t)=>{let r=e[0].length+e.index,i=e.input[r];if(i===`<`||i===`,`){t.ignoreMatch();return}i===`>`&&(n(e,{after:r})||t.ignoreMatch());let a,o=e.input.substring(r);if(a=o.match(/^\s*=/)){t.ignoreMatch();return}if((a=o.match(/^\s+extends\s+/))&&a.index===0){t.ignoreMatch();return}}},s={$pattern:ui,keyword:di,literal:fi,built_in:_i,"variable.language":gi},c=`[0-9](_?[0-9])*`,l=`\\.(${c})`,u=`0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`,d={className:`number`,variants:[{begin:`(\\b(${u})((${l})|\\.)?|(${l}))[eE][+-]?(${c})\\b`},{begin:`\\b(${u})\\b((${l})\\b|\\.)?|(${l})\\b`},{begin:`\\b(0|[1-9](_?[0-9])*)n\\b`},{begin:`\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b`},{begin:`\\b0[bB][0-1](_?[0-1])*n?\\b`},{begin:`\\b0[oO][0-7](_?[0-7])*n?\\b`},{begin:`\\b0[0-7]+n?\\b`}],relevance:0},f={className:`subst`,begin:`\\$\\{`,end:`\\}`,keywords:s,contains:[]},p={begin:".?html`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`xml`}},m={begin:".?css`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`css`}},h={begin:".?gql`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`graphql`}},g={className:`string`,begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,f]},_={className:`comment`,variants:[e.COMMENT(/\/\*\*(?!\/)/,`\\*/`,{relevance:0,contains:[{begin:`(?=@[A-Za-z]+)`,relevance:0,contains:[{className:`doctag`,begin:`@[A-Za-z]+`},{className:`type`,begin:`\\{`,end:`\\}`,excludeEnd:!0,excludeBegin:!0,relevance:0},{className:`variable`,begin:r+`(?=\\s*(-)|$)`,endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},v=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,m,h,g,{match:/\$\d+/},d];f.contains=v.concat({begin:/\{/,end:/\}/,keywords:s,contains:[`self`].concat(v)});let y=[].concat(_,f.contains),b=y.concat([{begin:/(\s*)\(/,end:/\)/,keywords:s,contains:[`self`].concat(y)}]),x={className:`params`,begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b},S={variants:[{match:[/class/,/\s+/,r,/\s+/,/extends/,/\s+/,t.concat(r,`(`,t.concat(/\./,r),`)*`)],scope:{1:`keyword`,3:`title.class`,5:`keyword`,7:`title.class.inherited`}},{match:[/class/,/\s+/,r],scope:{1:`keyword`,3:`title.class`}}]},C={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:`title.class`,keywords:{_:[...pi,...mi]}},w={label:`use_strict`,className:`meta`,relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},T={variants:[{match:[/function/,/\s+/,r,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:`keyword`,3:`title.function`},label:`func.def`,contains:[x],illegal:/%/},E={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:`variable.constant`};function D(e){return t.concat(`(?!`,e.join(`|`),`)`)}let O={match:t.concat(/\b/,D([...hi,`super`,`import`,`await`].map(e=>`${e}\\s*\\(`)),r,t.lookahead(/\s*\(/)),className:`title.function`,relevance:0},k={begin:t.concat(/\./,t.lookahead(t.concat(r,/(?![0-9A-Za-z$_(])/))),end:r,excludeBegin:!0,keywords:`prototype`,className:`property`,relevance:0},A={match:[/get|set/,/\s+/,r,/(?=\()/],className:{1:`keyword`,3:`title.function`},contains:[{begin:/\(\)/},x]},ee=`(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|`+e.UNDERSCORE_IDENT_RE+`)\\s*=>`,j={match:[/const|var|let/,/\s+/,r,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(ee)],keywords:`async`,className:{1:`keyword`,3:`title.function`},contains:[x]};return{name:`JavaScript`,aliases:[`js`,`jsx`,`mjs`,`cjs`],keywords:s,exports:{PARAMS_CONTAINS:b,CLASS_REFERENCE:C},illegal:/#(?![$_A-Za-z])/,contains:[e.SHEBANG({label:`shebang`,binary:`node`,relevance:5}),w,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,m,h,g,_,{match:/\$\d+/},d,C,{scope:`attr`,match:r+t.lookahead(`:`),relevance:0},j,{begin:`(`+e.RE_STARTERS_RE+`|\\b(case|return|throw)\\b)\\s*`,keywords:`return throw case`,relevance:0,contains:[_,e.REGEXP_MODE,{className:`function`,begin:ee,returnBegin:!0,end:`\\s*=>`,contains:[{className:`params`,variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:i.begin,end:i.end},{match:a},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:`xml`,contains:[{begin:o.begin,end:o.end,skip:!0,contains:[`self`]}]}]},T,{beginKeywords:`while if switch catch for`},{begin:`\\b(?!function)`+e.UNDERSCORE_IDENT_RE+`\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{`,returnBegin:!0,label:`func.def`,contains:[x,e.inherit(e.TITLE_MODE,{begin:r,className:`title.function`})]},{match:/\.\.\./,relevance:0},k,{match:`\\$`+r,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:`title.function`},contains:[x]},O,E,S,A,{match:/\$[(.]/}]}}function yi(e){let t=e.regex,n=vi(e),r=ui,i=[`any`,`void`,`number`,`boolean`,`string`,`object`,`never`,`symbol`,`bigint`,`unknown`],a={begin:[/namespace/,/\s+/,e.IDENT_RE],beginScope:{1:`keyword`,3:`title.class`}},o={beginKeywords:`interface`,end:/\{/,excludeEnd:!0,keywords:{keyword:`interface extends`,built_in:i},contains:[n.exports.CLASS_REFERENCE]},s={className:`meta`,relevance:10,begin:/^\s*['"]use strict['"]/},c={$pattern:ui,keyword:di.concat([`type`,`interface`,`public`,`private`,`protected`,`implements`,`declare`,`abstract`,`readonly`,`enum`,`override`,`satisfies`]),literal:fi,built_in:_i.concat(i),"variable.language":gi},l={className:`meta`,begin:`@`+r},u=(e,t,n)=>{let r=e.contains.findIndex(e=>e.label===t);if(r===-1)throw Error(`can not find mode to replace`);e.contains.splice(r,1,n)};Object.assign(n.keywords,c),n.exports.PARAMS_CONTAINS.push(l);let d=n.contains.find(e=>e.scope===`attr`),f=Object.assign({},d,{match:t.concat(r,t.lookahead(/\s*\?:/))});n.exports.PARAMS_CONTAINS.push([n.exports.CLASS_REFERENCE,d,f]),n.contains=n.contains.concat([l,a,o,f]),u(n,`shebang`,e.SHEBANG()),u(n,`use_strict`,s);let p=n.contains.find(e=>e.label===`func.def`);return p.relevance=0,Object.assign(n,{name:`TypeScript`,aliases:[`ts`,`tsx`,`mts`,`cts`]}),n}function bi(e){let t=e.regex,n=t.concat(/[\p{L}_]/u,t.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),r=/[\p{L}0-9._:-]+/u,i={className:`symbol`,begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},a={begin:/\s/,contains:[{className:`keyword`,begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},o=e.inherit(a,{begin:/\(/,end:/\)/}),s=e.inherit(e.APOS_STRING_MODE,{className:`string`}),c=e.inherit(e.QUOTE_STRING_MODE,{className:`string`}),l={endsWithParent:!0,illegal:/</,relevance:0,contains:[{className:`attr`,begin:r,relevance:0},{begin:/=\s*/,relevance:0,contains:[{className:`string`,endsParent:!0,variants:[{begin:/"/,end:/"/,contains:[i]},{begin:/'/,end:/'/,contains:[i]},{begin:/[^\s"'=<>`]+/}]}]}]};return{name:`HTML, XML`,aliases:[`html`,`xhtml`,`rss`,`atom`,`xjb`,`xsd`,`xsl`,`plist`,`wsf`,`svg`],case_insensitive:!0,unicodeRegex:!0,contains:[{className:`meta`,begin:/<![a-z]/,end:/>/,relevance:10,contains:[a,c,s,o,{begin:/\[/,end:/\]/,contains:[{className:`meta`,begin:/<![a-z]/,end:/>/,contains:[a,o,c,s]}]}]},e.COMMENT(/<!--/,/-->/,{relevance:10}),{begin:/<!\[CDATA\[/,end:/\]\]>/,relevance:10},i,{className:`meta`,end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[c]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:`tag`,begin:/<style(?=\s|>)/,end:/>/,keywords:{name:`style`},contains:[l],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:`css`}},{className:`tag`,begin:/<script(?=\s|>)/,end:/>/,keywords:{name:`script`},contains:[l],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:`javascript`}},{className:`tag`,begin:/<>|<\/>/},{className:`tag`,begin:t.concat(/</,t.lookahead(t.concat(n,t.either(/\/>/,/>/,/\s/)))),end:/\/?>/,contains:[{className:`name`,begin:n,relevance:0,starts:l}]},{className:`tag`,begin:t.concat(/<\//,t.lookahead(t.concat(n,/>/))),contains:[{className:`name`,begin:n,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}function xi(e){let t=`true false yes no null`,n=`[\\w#;/?:@&=+$,.~*'()[\\]]+`,r={className:`attr`,variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},i={className:`template-variable`,variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]},a={className:`string`,relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:`char.escape`,relevance:0}]},o={className:`string`,relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,i]},s=e.inherit(o,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),c={className:`number`,begin:`\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b`},l={end:`,`,endsWithParent:!0,excludeEnd:!0,keywords:t,relevance:0},u={begin:/\{/,end:/\}/,contains:[l],illegal:`\\n`,relevance:0},d={begin:`\\[`,end:`\\]`,contains:[l],illegal:`\\n`,relevance:0},f=[r,{className:`meta`,begin:`^---\\s*$`,relevance:10},{className:`string`,begin:`[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*`},{begin:`<%[%=-]?`,end:`[%-]?%>`,subLanguage:`ruby`,excludeBegin:!0,excludeEnd:!0,relevance:0},{className:`type`,begin:`!\\w+!`+n},{className:`type`,begin:`!<`+n+`>`},{className:`type`,begin:`!`+n},{className:`type`,begin:`!!`+n},{className:`meta`,begin:`&`+e.UNDERSCORE_IDENT_RE+`$`},{className:`meta`,begin:`\\*`+e.UNDERSCORE_IDENT_RE+`$`},{className:`bullet`,begin:`-(?=[ ]|$)`,relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:t,keywords:{literal:t}},c,{className:`number`,begin:e.C_NUMBER_RE+`\\b`,relevance:0},u,d,a,o],p=[...f];return p.pop(),p.push(s),l.contains=p,{name:`YAML`,case_insensitive:!0,aliases:[`yml`],contains:f}}for(let[e,t]of Object.entries({bash:Ir,css:Gr,diff:Kr,go:qr,javascript:ni,json:ii,markdown:ai,python:oi,rust:si,shell:ci,sql:li,typescript:yi,xml:bi,yaml:xi}))Fr.registerLanguage(e,t);function Si(e){for(let t of e.querySelectorAll(`pre code[class]`)){let e=/(?:language|lang)-(\S+)/.exec(t.className)?.[1]?.toLowerCase();!e||!Fr.getLanguage(e)||(t.innerHTML=Fr.highlight(t.textContent??``,{language:e}).value)}}var Ci={ts:`typescript`,tsx:`typescript`,mts:`typescript`,cts:`typescript`,js:`javascript`,jsx:`javascript`,mjs:`javascript`,cjs:`javascript`,py:`python`,rs:`rust`,sh:`bash`,zsh:`bash`,md:`markdown`,yml:`yaml`,html:`xml`,htm:`xml`,svg:`xml`,patch:`diff`};function wi(e){let t=e.split(`.`).pop()?.toLowerCase()??``,n=Ci[t]??t;return Fr.getLanguage(n)?n:null}function Ti(e,t){let n=document.createElement(`span`);return t&&e.length<=500?n.innerHTML=Fr.highlight(e,{language:t}).value:n.textContent=e,n}var Ei=null,Di=`cursor-pointer rounded-full border border-indigo-200 bg-indigo-50 px-2.5 py-0.5 text-[12.5px] text-indigo-700 transition-colors hover:border-indigo-300 hover:bg-indigo-100`;function Oi(){Ei=null}function ki(e,t,n){if(Ei?.remove(),Ei=null,!t.length)return;let r=G(`div`,`mt-1.5 flex flex-wrap gap-1.5`);for(let e of t){let t=G(`button`,Di,e);t.type=`button`,t.onclick=()=>{Ei===r&&(Ei=null),r.remove(),n(e)},r.append(t)}e.append(r),Ei=r}var Ai=8e3,ji=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],Mi,Ni;function Pi(e,t){Mi=e,Ni=t}var Fi={queued:`border-amber-200 bg-amber-50 text-amber-800`,running:`border-green-200 bg-green-50 text-green-800`,succeeded:`border-neutral-200 bg-neutral-50 text-neutral-600`,failed:`border-red-200 bg-red-50 text-red-700`,cancelled:`border-neutral-200 bg-neutral-50 text-neutral-500`,interrupted:`border-amber-200 bg-amber-50 text-amber-800`,skipped:`border-neutral-200 bg-neutral-50 text-neutral-500`},Ii=new Map;async function Li(e){let t=await e;t.sent&&t.error&&Ni.append(`error`,t.error)}async function Ri(e,t){try{let n=await fetch(e,{method:`POST`});n.ok||Ni.append(`error`,await u(n,t))}catch(e){Ni.append(`error`,`${t}: ${String(e)}`)}}async function zi(e){let t=Mi.sessionId();t&&await Li(d(`Reply to subagent`,`/api/task-messages/${e}/reply`,{sourceSessionId:t},`reply failed`))}function Bi(e){let t=G(`button`,`flex-none text-[11px] font-semibold normal-case text-cyan-800 hover:underline`,`Reply`);return t.onclick=()=>void zi(e),t}function Vi(e){let t=Ii.get(e.runId);t&&!t.isConnected&&(Ii.delete(e.runId),t=void 0),t||(t=G(`div`,`mx-5 my-1.5 border px-3 py-2 text-[13px]`),t.dataset.kind=`background-run`,Ni.el.append(t),Ii.set(e.runId,t)),t.className=`mx-5 my-1.5 border px-3 py-2 text-[13px] ${Fi[e.state]}`;let n=e.state===`queued`||e.state===`running`,r=`/api/task-runs/${e.runId}`,i=n?G(`span`,`spinner`):G(`span`,`w-3 flex-none text-center`,e.state===`succeeded`?`✓`:e.state===`failed`?`✕`:`·`),a=G(`button`,`min-w-0 truncate text-left font-medium hover:underline`,e.taskName);a.onclick=()=>Mi.showTasks(e.taskId);let o=G(`div`,`flex items-center gap-2`,i,G(`span`,`flex-none text-[11px] font-semibold uppercase`,e.state),a),s=G(`div`,`ml-auto flex flex-none items-center gap-2`);if(e.targetSessionId){let t=G(`button`,`font-mono text-[11px] hover:underline`,`Open`);t.title=`Open ${e.targetSessionId}`,t.onclick=()=>Mi.select(e.targetSessionId),s.append(t)}if(n){let e=G(`button`,`text-[11px] font-semibold hover:underline`,`Steer`),t={mode:`steer`,sourceSessionId:Mi.sessionId()};e.onclick=()=>void Li(d(`Steer subagent`,`${r}/steer`,t,`could not steer the run`));let n=G(`button`,`text-[11px] font-semibold hover:underline`,`Stop`);n.onclick=()=>void Ri(`${r}/cancel`,`could not stop the run`),s.append(e,n)}else if(e.targetSessionId&&e.sessionMode!==null){let e=G(`button`,`text-[11px] font-semibold hover:underline`,`Continue`),t={sourceSessionId:Mi.sessionId()};e.onclick=()=>void Li(d(`Continue subagent`,`${r}/resume`,t,`could not continue`)),s.append(e)}o.append(s);let c=Math.max(0,Math.round(((e.finishedAt??Date.now())-(e.startedAt??e.queuedAt))/1e3));t.replaceChildren(o,G(`div`,`mt-1 text-[11px] opacity-70`,`${e.sessionMode??`task`} · depth ${e.depth} · ${c}s · ${e.runId}`)),Ni.scroll()}var K=null,Hi=new WeakMap,Ui=e=>{let t=Hi.get(e)??[];return Hi.set(e,t),t};function Wi(){K&&!K.toolRows.size&&ea(`done`)}var Gi=null;function Ki(){K=null,Gi=null,Ii.clear()}function qi(){let e=Gi;return!e||K?.el===e||(Gi=null,e!==Ni.el.lastElementChild)?null:(e.remove(),e.dataset.adopted=`1`,Yi(e,e.dataset.status),e)}var Ji={running:`text-green-700 open:bg-green-50`,done:`text-neutral-400 hover:text-neutral-600 open:bg-black/[0.02] open:text-neutral-500`,failed:`text-red-600 open:bg-red-50`,interrupted:`text-amber-700 open:bg-amber-50`};function Yi(e,t){e.dataset.status=t,e.className=`${e.dataset.adopted?`float-left min-w-[6.5rem] pr-3 tabular-nums mt-[3px] open:float-none open:mt-0 open:mb-1.5 open:min-w-0 open:pr-0`:`mx-5 my-1.5`} rounded-md text-[11.5px] leading-[1.35] open:border open:border-black/[0.06] open:px-2 open:py-1.5 ${Ji[t]}`}var Xi={failed:`✕`,interrupted:`⏸`};function Zi(e){return e===`running`?G(`span`,`spinner`):e===`done`?G(`span`,`hidden`):G(`span`,`flex-none text-[12px] font-bold`,Xi[e])}function Qi(e){if(K)return K;let t=Zi(`running`),n=G(`span`,`truncate`,`working…`),{el:r}=nr(``,[t,n]);r.dataset.kind=`activity`,Yi(r,`running`);let i=G(`div`,`mt-1.5 flex max-h-64 flex-col gap-1 overflow-y-auto overscroll-contain border-t border-black/5 pt-1.5`);return r.append(i),Ni.el.append(r),Gi=r,Ni.scroll(),K={el:r,statusIcon:t,headline:n,rowsEl:i,toolRows:new Map,thinking:null,steps:0,failedSteps:0,startTs:e,sawError:!1},K}function $i(e,t,n){let r=Math.max(1,Math.round((Date.now()-e.startTs)/1e3)),i=`${e.steps} step${e.steps===1?``:`s`} · ${r}s`;e.headline.textContent=t===`running`&&n?`${i} · ${n}`:t===`done`?i:`${i} · ${t}`,Yi(e.el,t);let a=Zi(t);e.statusIcon.replaceWith(a),e.statusIcon=a}function ea(e){if(!K)return;for(let{statusEl:e}of K.toolRows.values())e.textContent===`running…`&&(e.textContent=`interrupted`);let t=K.steps>0&&K.failedSteps===K.steps;$i(K,(K.sawError||t)&&e===`done`?`failed`:e),K=null}function ta(){K&&(K.sawError=!0)}function na(e){let t=e.slice(0,400).replace(/\s+/g,` `);return t.length>100?t.slice(0,100)+`…`:t}function ra(e,t,n,r){let i=Qi(e);i.steps+=1,i.thinking=null;let a=JSON.stringify(r,null,2)??``,o=G(`span`,`ml-auto flex-none text-black/40`,`running…`),s=G(`span`,`truncate text-black/50`,na(a)),{el:c}=nr(`rounded-md px-1 py-0.5 font-mono text-[12.5px] hover:bg-black/[0.03]`,[G(`span`,`flex-none font-semibold`,n),s,o]),l=G(`pre`,`max-h-40 overflow-y-auto whitespace-pre-wrap rounded bg-black/[0.04] p-1.5 text-[12px]`,a),u=G(`pre`,`hidden max-h-56 overflow-y-auto whitespace-pre-wrap rounded bg-black/[0.04] p-1.5 text-[12px]`);c.append(G(`div`,`mt-1 flex flex-col gap-1 pl-4`,l,u)),Ui(i.el).push({tool:n,call:t,preview:s,argsPre:l,outputPre:u}),i.toolRows.set(t,{el:c,statusEl:o,outputPre:u}),i.rowsEl.append(c),Ni.bulk()||(i.rowsEl.scrollTop=i.rowsEl.scrollHeight),$i(i,`running`,n),Ni.scroll()}function ia(e,t,n){let r=K;if(!r)return;let i=r.toolRows.get(e);r.toolRows.delete(e),i&&(i.statusEl.textContent=t?`failed`:`ok`,i.statusEl.className=`ml-auto flex-none ${t?`text-red-600`:`text-green-700`}`,i.el.classList.toggle(`bg-red-50`,t),i.el.classList.toggle(`text-red-700`,t),n&&(i.outputPre.textContent=n.length>8e3?n.slice(0,Ai)+`…`:n,i.outputPre.classList.remove(`hidden`)),t&&(r.failedSteps+=1)),$i(r,`running`)}function aa(e,t){let n=Qi(e);if(!n.thinking){let{el:e,summary:t}=nr(`rounded-md px-1 py-0.5 text-[12.5px] italic text-black/50 hover:bg-black/[0.03]`,[G(`span`,`truncate`,`thinking…`)]),r=G(`div`,`mt-1 max-h-56 overflow-y-auto whitespace-pre-wrap pl-4 not-italic text-black/60`,``);e.append(r),n.rowsEl.append(e),n.thinking={pre:r,summary:t},$i(n,`running`,`thinking…`)}let r=n.thinking;r.pre.textContent=((r.pre.textContent??``)+t).slice(-4e3);let i=(r.pre.textContent??``).split(`
|
|
72
|
+
`).filter(Boolean).pop()??`thinking…`,a=r.summary.lastElementChild;a.textContent=i.length>90?`…`+i.slice(-90):i}var oa=0;function sa(e,t=0,n=!1,r){let i=Date.now()-t,a=Qi(i).el;for(let t of e){if(t.kind===`thinking`){aa(i,t.text??``);continue}let e=t.id??`replay-${++oa}`;ra(i,e,t.toolName??``,t.args),t.done&&ia(e,t.isError??!1,t.output??``)}r!==void 0&&e.some(e=>e.kind===`tool`&&e.args===void 0)&&ca(a,r),!n&&ea(e.some(e=>e.kind===`tool`&&!e.done)?`interrupted`:`done`)}function ca(e,t){let n=()=>{e.open&&(e.removeEventListener(`toggle`,n),la(e,t))};e.addEventListener(`toggle`,n)}async function la(e,t){let n=Mi.sessionId(),r=Ui(e),i=new Set(r.filter(e=>!e.argsPre.textContent)),a=e=>{for(let t of i)t.argsPre.textContent=e};if(a(`loading…`),!n)return a(`no session`);let o;try{let e=await fetch(`/api/sessions/${n}/turns/${t}/steps`);if(!e.ok)return a(await u(e,`could not load these steps`));o=(await e.json()).steps}catch(e){return a(`could not load these steps: ${String(e)}`)}let s=o.filter(e=>e.kind===`tool`);for(let[e,t]of r.entries()){if(!i.has(t))continue;let n=s[e];if(!(n&&(n.id?n.id===t.call:n.toolName===t.tool))){t.argsPre.textContent=`detail no longer available — reload the session`;continue}let r=JSON.stringify(n.args,null,2)??``;t.argsPre.textContent=r,t.preview.textContent=na(r),n.output&&(t.outputPre.textContent=n.output,t.outputPre.classList.remove(`hidden`))}}var ua,da=W(`#turns`);function fa(e){ua=e,Pi(e,{el:da,append:q,scroll:ma,bulk:()=>pa})}var pa=!1;function ma(e=!1){if(pa)return;let t=da.scrollHeight-da.scrollTop-da.clientHeight<80;(e||t)&&(da.scrollTop=da.scrollHeight)}var ha={user:{row:`border-l-indigo-500 bg-indigo-50`,body:`text-neutral-900`},assistant:{row:`border-l-transparent`,body:`text-neutral-900`},error:{row:`border-l-red-400 bg-red-50`,body:`text-red-700`},system:{row:`border-l-cyan-500 bg-cyan-50`,body:`text-neutral-800`}};function q(e,t,n=!1){Wi();let r=e===`assistant`?qi():null,i=ha[e],a=G(`div`,`group relative border-l-2 px-5 ${da.lastElementChild?.dataset.kind===e?`pt-1 pb-2.5`:`mt-1.5 py-2.5`} ${i.row}`);a.dataset.kind=e;let o=e===`user`?Pr(t):null,s=G(`div`,`whitespace-pre-wrap break-words ${i.body}`,o?.text??t);o?.paths.length&&(s.dataset.raw=t),n&&xa(s,t),r&&(a.classList.add(`flow-root`),a.append(r)),a.append(s);let c=ua.sessionId();if(o?.paths.length&&c){let e=fr(a);for(let t of o.paths)e.append(Tr(c,t))}if(e===`user`){let e=G(`button`,`absolute right-2 top-1 hidden h-6 w-6 items-center justify-center rounded text-neutral-400 hover:bg-neutral-200 hover:text-neutral-700 group-hover:flex pointer-coarse:flex`);e.title=`Edit — resends from here; this message and later turns leave the context`,e.setAttribute(`aria-label`,`Edit message`),e.innerHTML=`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="h-3.5 w-3.5"><path d="m10.7 2.3 3 3L6 13H3v-3l7.7-7.7zM9.3 3.7l3 3"/></svg>`,e.onclick=()=>_a(a,s),a.append(e)}return da.append(a),ma(),s}function ga(e,t){let n=t.kind===`task-callback`?`Task callback`:t.kind===`task-message`?t.messageKind===`decision`?`Decision needed`:`Task ${t.messageKind.replace(`_`,` `)}`:`Agent task input`;Wi();let r=G(`div`,`mt-1.5 border-l-2 border-l-cyan-500 bg-cyan-50 px-5 py-2.5`);r.dataset.kind=`system`;let i=G(`div`,`mb-1 flex items-center gap-2 text-[11px] font-semibold uppercase text-cyan-800`,G(`span`,``,n));if(t.sourceSessionId&&t.sourceSessionId!==`console`){let e=G(`button`,`truncate font-mono normal-case text-cyan-700 hover:underline`,t.sourceSessionId.slice(0,12));e.title=`Open source session`,e.onclick=()=>ua.select(t.sourceSessionId),i.append(G(`span`,`text-cyan-400`,`from`),e)}let a=G(`button`,`ml-auto flex-none font-mono normal-case text-cyan-700 hover:underline`,`run ${t.runId.slice(0,8)}`);a.onclick=()=>ua.showTasks(t.taskId),i.append(a),t.kind===`task-message`&&t.messageKind===`decision`&&i.append(Bi(t.messageId));let o=[`max-h-[min(18rem,40dvh)]`,`overflow-hidden`],s=G(`div`,`whitespace-pre-wrap break-words text-[14px] text-neutral-800 ${o.join(` `)}`,e);r.append(i,s),da.append(r);let c=e.length>800||e.split(`
|
|
73
|
+
`).length>12;if(s.clientHeight?s.scrollHeight>s.clientHeight+1:c){let e=G(`button`,`mx-auto mt-1.5 block w-fit rounded border border-cyan-200 bg-white px-2 py-1 text-[12px] font-medium text-cyan-800 shadow-sm hover:bg-cyan-100 pointer-coarse:py-3.5`,`Show full message`);e.setAttribute(`type`,`button`),e.onclick=()=>{let t=s.classList.toggle(o[0]);s.classList.toggle(o[1],t),e.textContent=t?`Show full message`:`Collapse message`,s.tabIndex=-1,s.focus({preventScroll:!0})},r.append(e)}else s.classList.remove(...o);ma()}function _a(e,t){if(ua.sessionState()!==`idle`){q(`error`,`can't edit while streaming — stop the turn first`);return}if(e.querySelector(`textarea`))return;let n=document.createElement(`textarea`);n.value=t.dataset.raw??t.textContent??``,n.className=`block w-full resize-none rounded-md border border-indigo-300 bg-white px-2 py-1 focus:outline-none`;let r=()=>{n.style.height=`auto`,n.style.height=`${Math.min(n.scrollHeight,192)}px`};n.oninput=r,t.classList.add(`hidden`),t.after(n),r(),n.focus(),n.setSelectionRange(n.value.length,n.value.length);let i=()=>{n.remove(),t.classList.remove(`hidden`)};n.onkeydown=t=>{if(!(t.isComposing||t.keyCode===229)&&(t.key===`Escape`&&i(),t.key===`Enter`&&!t.shiftKey)){t.preventDefault();let r=n.value.trim();if(!r)return i();va(e,r)}}}async function va(e,t){let n=ua.sessionId();if(!n)return;let r=[...da.querySelectorAll(`[data-kind="user"]`)].indexOf(e);for(;e.nextElementSibling;)e.nextElementSibling.remove();e.remove(),ua.ownTurn(t),q(`user`,t),ma(!0);let i=await l(`/api/sessions/${n}/turns/${r}/edit`,{text:t});if(!i.ok){let e=await u(i,`edit failed`);await ua.reload(n),q(`error`,e)}}function ya(e,t){if(!t)return;let n=new Date(t.completedAt).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,hour12:!1});(e.parentElement??e).append(G(`span`,`absolute -top-2.5 right-3 z-10 hidden rounded border border-neutral-200 bg-white px-1.5 py-0.5 text-[11.5px] text-neutral-500 shadow-sm group-hover:inline`,`${n} · ${Vn(t)}`))}function ba(e){for(let t of e.querySelectorAll(`pre`)){let e=t.querySelector(`code`);if(!e)continue;let n=G(`div`,`group/code relative`);t.replaceWith(n),n.append(t,tr(`absolute right-1.5 top-1.5 cursor-pointer rounded border border-black/[0.08] bg-white/85 px-1.5 py-0.5 text-[11px] text-neutral-500 opacity-0 transition-opacity hover:bg-white hover:text-neutral-800 focus:opacity-100 group-hover/code:opacity-100 pointer-coarse:opacity-100`,()=>e.textContent??``))}}function xa(e,t,n=!1){let r=ua.sessionId(),i=r?Cr(t,r):t;e.innerHTML=tt.sanitize(U.parse(i,{async:!1})),e.classList.remove(`whitespace-pre-wrap`),e.classList.add(`md`),Si(e),$n(e),!n&&(ba(e),jr(e))}function Sa(e,t,n,r=!1){let{text:i,suggestions:a}=qn(t);return Ln({text:i,suggestions:a})?Ca(e,Kn(t)):xa(e,i),ya(e,n),r&&ki(e.parentElement??e,a,e=>ua.send(`auto`,e)),e}function Ca(e,t){e.classList.remove(`md`,`whitespace-pre-wrap`),e.replaceChildren(G(`span`,`text-[12.5px] italic text-black/40`,t?`Stayed silent — ${t}`:`Stayed silent.`))}var wa=(e,t,n=!1)=>Sa(q(`assistant`,``),e,t,n),Ta=null,Ea=null,Da=!1,Oa=80;function ka(){if(Ea){Da=!0;return}Da=!1,Ta&&(xa(Ta,qn(Ta.dataset.raw??``).text,!0),ma()),Ea=setTimeout(()=>{Ea=null,Da&&ka()},Oa)}function Aa(){Ea&&clearTimeout(Ea),Ea=null,Da=!1}function ja(e){Ta||=q(`assistant`,``),Ta.dataset.raw=(Ta.dataset.raw??``)+e,ka()}function Ma(e=!1){if(!Ta)return;let t=Ta;Ta=null,Aa(),Sa(t,t.dataset.raw??``,void 0,e)}function Na(e,t){ea(`done`),Ta?(e&&(Ta.dataset.raw=e),ya(Ta,t)):e&&wa(e,t,!0),Ma(!0)}function Pa(){ea(`interrupted`),Ma()}function Fa(){da.replaceChildren(),Ta=null,Aa(),Ki(),Oi()}function Ia(e){if(!e){da.querySelector(`[data-kind="loading"]`)?.remove();return}let t=G(`div`,`flex flex-col gap-3 px-5 py-4`);t.dataset.kind=`loading`;for(let e of[`w-2/5`,`w-4/5`,`w-3/5`,`w-1/3`,`w-2/3`])t.append(G(`div`,`skeleton h-3.5 ${e}`));da.append(t)}function La(e,t,n){Ia(!1);let r=new Map(n.map(e=>[e.runId,e])),i=e=>[...r].filter(([,t])=>t.queuedAt<=e).map(([e])=>e),a=e=>{for(let t of e){let e=r.get(t);e&&(Vi(e),r.delete(t))}},o=e.reduce((e,t,n)=>t.role===`assistant`?n:e,-1);pa=!0;try{for(let[n,r]of e.entries()){let s=t===`streaming`&&n===e.length-1&&(!r.text||(r.steps?.some(e=>e.kind===`tool`&&!e.done)??!1)),c=r.steps;if(c?.length&&(sa(c,r.meta?.durationMs,s,n),r.meta&&a(i(r.meta.completedAt))),r.text){if(r.role===`system`&&r.origin){a(r.origin.kind===`task-message`?[r.origin.runId]:r.origin.runIds??[r.origin.runId]),ga(r.text,r.origin);continue}r.role===`assistant`?wa(r.text,r.meta,t===`idle`&&n===o):q(r.role,r.text)}}for(let e of r.values())Vi(e)}finally{pa=!1}ma(!0)}var Ra=window.fetch.bind(window),za=20,Ba=6e4,Va=[],Ha=new Map,Ua=e=>e instanceof Error?e.stack??`${e.name}: ${e.message}`:void 0;function Wa(e,t){let n=t===void 0?e:`${e}: ${String(t)}`,r=Date.now();r-(Ha.get(n)??-6e4)<Ba||(Ha.size>100&&Ha.clear(),Ha.set(n,r),Va=Va.filter(e=>r-e<6e4),!(Va.length>=za)&&(Va.push(r),Ra(`/api/client-log`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({message:n,stack:Ua(t),view:location.hash||`/`}),keepalive:!0}).catch(()=>{}),q(`error`,n)))}function Ga(){window.__pierReporting=!0,window.addEventListener(`error`,e=>{Wa(`script error: ${e.message}`,e.error)}),window.addEventListener(`unhandledrejection`,e=>{Wa(`unhandled rejection`,e.reason)})}var Ka=window.fetch.bind(window),qa=()=>{location.assign(`/login?next=${encodeURIComponent(location.pathname+location.hash)}`)};function Ja(){window.fetch=async(...e)=>{let t=await Ka(...e);return t.status===401&&qa(),t}}function Ya(e,t){if(e.readyState!==EventSource.CLOSED)return;let n=()=>Wa(`${t} stream disconnected — reload to reconnect`);Ka(`/api/projects`).then(e=>e.status===401?qa():n(),n)}var Xa=/Mac|iP(?:hone|ad|od)/.test(navigator.userAgent),Za=Xa?`⌘`:`Ctrl+`,Qa=Xa?`⇧`:`Shift+`,$a=e=>{let t=e.startsWith(`meta+`),n=e.startsWith(`ctrl+`),r=t||n?e.slice(5):e;return r.startsWith(`shift+`)?{key:r.slice(6),shift:!0,meta:t,ctrl:n}:{key:r,shift:!1,meta:t,ctrl:n}};function eo(e){let{key:t,shift:n,meta:r,ctrl:i}=$a(e);return`${r?`⌘`:i?Xa?`⌃`:`Ctrl+`:Za}${n?Qa:``}${t.toUpperCase()}`}var to=`pointer-events-none fixed z-50 flex items-center gap-2 whitespace-nowrap rounded-md bg-neutral-800 px-2 py-1 text-[11.5px] text-neutral-100 shadow-lg`;function no(e,t,n){e.removeAttribute(`title`);let r=null,i=()=>{r?.remove(),r=null};e.addEventListener(`pointerenter`,a=>{if(a.pointerType!==`mouse`)return;i(),r=G(`div`,to,t,G(`kbd`,`rounded bg-white/15 px-1 py-px font-sans text-[10.5px]`,n)),document.body.append(r);let o=e.getBoundingClientRect();r.style.top=`${Math.min(o.bottom+6,window.innerHeight-r.offsetHeight-8)}px`,r.style.left=`${Math.max(8,Math.min(o.left,window.innerWidth-r.offsetWidth-8))}px`}),e.addEventListener(`pointerleave`,i),e.addEventListener(`click`,i)}function ro(e,t,n,r,i,a=!1){no(e,n,eo(t)),so(t,r,i,a)}function io(e,t,n,r){no(e,t,`Esc`),document.addEventListener(`keydown`,e=>{e.key!==`Escape`||e.isComposing||e.defaultPrevented||document.querySelector(`dialog[open]`)||!r()||(e.preventDefault(),n())})}var ao=`input, textarea, select, [contenteditable]`;function oo(e,t,n,r,i){no(e,n,t[0].toUpperCase()),document.addEventListener(`keydown`,e=>{e.metaKey||e.ctrlKey||e.altKey||e.isComposing||e.defaultPrevented||t.includes(e.key.toLowerCase())&&(e.target?.closest?.(ao)||document.querySelector(`dialog[open]`)||!i()||(e.preventDefault(),r()))})}function so(e,t,n,r=!1){let{key:i,shift:a,meta:o,ctrl:s}=$a(e);document.addEventListener(`keydown`,e=>{e.key.toLowerCase()!==i||e.altKey||e.shiftKey!==a||(o?!e.metaKey:s?!e.ctrlKey||e.metaKey:!e.metaKey&&!e.ctrlKey)||!r&&!e.metaKey&&e.target?.closest?.(`[data-owns-keyboard]`)||n?.()||(e.preventDefault(),e.stopPropagation(),t())},!0)}var co,lo=W(`#composer`),J=W(`#input`),uo=W(`#send`),fo=W(`#send-plane`),po=W(`#send-queue`),mo=W(`#stop`),ho=W(`#queue-panel`),go=W(`#queue-rows`),_o=W(`#queue-label`),vo=W(`#image-strip`),yo=W(`#attach-input`),bo=!1,xo=[],So=[];function Co(){J.focus()}function wo(e){let t=So.indexOf(e);return t<0?!1:(So.splice(t,1),!0)}function To(e){So.push(e)}function Eo(){So=[]}function Do(){let e=co.sessionState()===`streaming`;uo.className=`flex h-7 w-7 flex-none cursor-pointer items-center justify-center rounded-lg ${e?`bg-amber-100 text-amber-700 hover:bg-amber-200 active:bg-amber-300`:`bg-indigo-600 text-white hover:bg-indigo-500 active:bg-indigo-700`}`,uo.title=e?`Queue — delivered when the turn ends`:`Send`,fo.classList.toggle(`hidden`,e),po.classList.toggle(`hidden`,!e),mo.classList.toggle(`hidden`,!e),mo.classList.toggle(`flex`,e)}function Oo(){let e=co.chatVisible()&&bo;ho.classList.toggle(`hidden`,!e),ho.classList.toggle(`flex`,e)}function ko(e,t){let n=[...e.map(e=>({mode:`steer`,text:e})),...t.map(e=>({mode:`queued`,text:e}))];bo=n.length>0,_o.textContent=n.length>1?`Queued · ${n.length}`:`Queued`,Oo(),go.replaceChildren(...n.map(e=>{let t=G(`li`,`flex items-start gap-2 text-[13px] leading-[18px]`);return e.mode===`steer`&&t.append(G(`span`,`flex-none rounded bg-indigo-100 px-1 py-0.5 text-[10.5px] font-semibold uppercase tracking-wide text-indigo-700`,e.mode)),t.append(G(`span`,`min-w-0 whitespace-pre-wrap break-words text-neutral-700`,e.text)),t}))}var Ao=8;function jo(){vo.classList.toggle(`hidden`,xo.length===0),vo.classList.toggle(`flex`,xo.length>0),vo.replaceChildren(...xo.map((e,t)=>{let n=e.mimeType.startsWith(`image/`)?Object.assign(document.createElement(`img`),{src:`data:${e.mimeType};base64,${e.data}`,className:`h-16 w-16 rounded-md border border-neutral-200 object-cover`}):G(`span`,`flex h-16 max-w-40 items-center truncate rounded-md border border-neutral-200 bg-neutral-50 px-2 text-[12px] text-neutral-700`,e.name??`file`),r=G(`button`,`absolute -right-1.5 -top-1.5 h-4 w-4 cursor-pointer rounded-full bg-neutral-700 text-[10px] leading-none text-white hover:bg-red-600`,`×`);return r.onclick=()=>{xo.splice(t,1),jo()},G(`div`,`relative`,n,r)}))}function Mo(e){if(xo.length>=Ao){q(`error`,`attachment limit is ${Ao} files per message`);return}if(e.size>33554432){q(`error`,`${e.name||`file`} is too large (32MB max)`);return}let t=new FileReader;t.onload=()=>{let n=t.result;xo.push({data:n.slice(n.indexOf(`,`)+1),mimeType:e.type||`application/octet-stream`,name:e.name||void 0}),jo()},t.readAsDataURL(e)}async function No(e){let t=[];for(let n of e){let e=await l(`/api/inbox`,n);if(!e.ok)return null;let{path:r}=await e.json();t.push(Mr(r))}return t}var Po=e=>`pier.draft.${e}`;function Fo(){let e=co.sessionId();e&&(J.value.trim()?localStorage.setItem(Po(e),J.value):localStorage.removeItem(Po(e)))}function Io(e){J.value=localStorage.getItem(Po(e))??``,Lo(),xo=[],jo()}function Lo(){J.style.height=`auto`,J.style.height=`${Math.min(J.scrollHeight,192)}px`}var Ro=!1;async function zo(e,t){let n=(t??J.value).trim(),r=t===void 0?xo:[],i=co.sessionId();if(!(!n&&r.length===0||!i)){if(t===void 0){if(Ro)return;Ro=!0,J.value=``,Lo(),Fo(),xo=[],jo()}try{let t=[];if(r.length){let e=await No(r);if(e===null){q(`error`,`attachment upload failed`),J.value=[n,J.value.trim()].filter(Boolean).join(`
|
|
74
|
+
`),Lo(),Fo(),xo=r,jo();return}t=e}let a=[n,...t].filter(Boolean).join(`
|
|
75
|
+
`),o=co.sessionState()===`idle`&&e===`auto`;o?co.setState(`streaming`):Do(),(o||e===`steer`)&&(To(a),q(`user`,a),ma(!0));let s=await l(`/api/sessions/${i}/messages`,{text:a,mode:e});if(!s.ok){let e=await u(s,`send failed`);await co.reload(i),q(`error`,e)}}finally{t===void 0&&(Ro=!1)}}}async function Bo(e){let t=co.sessionId();if(!t)return;ko([],[]);let n=await l(`/api/sessions/${t}/queue/deliver`,{mode:e});n.ok||q(`error`,`queue ${e} failed: ${n.status}`)}async function Vo(){let e=co.sessionId();if(!e)return;let t=await fetch(`/api/sessions/${e}/queue/recall`,{method:`POST`});if(!t.ok)return;let{messages:n}=await t.json();n.length&&(J.value=[J.value.trim(),...n].filter(Boolean).join(`
|
|
76
|
+
`),Lo(),Fo(),J.focus()),ko([],[])}function Ho(e){co=e;let t=()=>{let e=co.sessionId();e&&fetch(`/api/sessions/${e}/abort`,{method:`POST`})};mo.onclick=t,io(mo,`Stop the running turn`,t,()=>co.sessionState()===`streaming`&&co.chatVisible()),W(`#queue-steer`).onclick=()=>void Bo(`steer`),W(`#queue-restart`).onclick=()=>void Bo(`restart`),W(`#queue-recall`).onclick=()=>void Vo(),lo.onsubmit=e=>{e.preventDefault(),zo(`auto`)},J.oninput=()=>{Lo(),Fo()};let n=!matchMedia(`(pointer: coarse)`).matches;J.onkeydown=e=>{e.isComposing||e.keyCode===229||n&&e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),zo(`auto`))},J.onpaste=e=>{for(let t of e.clipboardData?.items??[]){let e=t.kind===`file`?t.getAsFile():null;e&&Mo(e)}let t=e.clipboardData?.getData(`text/plain`)??``,n=t.trim();!n||n===t||(e.preventDefault(),J.setRangeText(n,J.selectionStart??0,J.selectionEnd??0,`end`),Lo(),Fo())},da.ondragover=e=>e.preventDefault(),da.ondrop=e=>{e.preventDefault();for(let t of e.dataTransfer?.files??[])Mo(t)},W(`#attach`).onclick=()=>yo.click(),yo.onchange=()=>{for(let e of yo.files??[])Mo(e);yo.value=``},Do()}var Uo=null;function Wo(e){Uo&&!Uo.contains(e.target)&&Y()}function Go(e){e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),Y())}function Ko(e){Uo&&!Uo.contains(e.target)&&Y()}function Y(){Uo&&=(document.removeEventListener(`pointerdown`,Wo,!0),document.removeEventListener(`keydown`,Go,!0),window.removeEventListener(`scroll`,Ko,!0),window.removeEventListener(`resize`,Y),Uo.remove(),null)}var qo=()=>window.innerWidth<640;function Jo(e,t){Y();let n=qo();if(Uo=G(`div`,`fixed z-50 rounded-lg border border-neutral-200 bg-white py-1 shadow-lg ${n?`inset-x-2 bottom-2 max-h-[70dvh] overflow-y-auto pb-[calc(0.25rem+env(safe-area-inset-bottom))] text-[16px]`:`min-w-52 max-w-[min(42rem,calc(100vw-1rem))] text-[13px]`}`),Uo.append(t),(e.closest(`dialog[open]`)??document.body).append(Uo),!n){let t=e.getBoundingClientRect();Uo.style.top=`${Math.max(8,Math.min(t.bottom+4,window.innerHeight-Uo.offsetHeight-8))}px`,Uo.style.left=`${Math.max(8,Math.min(t.left,window.innerWidth-Uo.offsetWidth-8))}px`}document.addEventListener(`pointerdown`,Wo,!0),document.addEventListener(`keydown`,Go,!0),window.addEventListener(`scroll`,Ko,!0),window.addEventListener(`resize`,Y)}function Yo(e){let t=G(`button`,`flex w-full cursor-pointer items-center gap-2 px-3 text-left hover:bg-neutral-100 active:bg-neutral-100 ${qo()?`py-3`:`py-1.5`}`,G(`span`,`flex-none w-3 text-indigo-600`,e.checked?`✓`:``),G(`span`,`truncate`,e.label));return e.hint&&t.append(G(`span`,`ml-auto flex-none text-[11.5px] text-neutral-400`,e.hint)),t.onclick=()=>e.onSelect(),t}function Xo(e,t){Jo(e,G(`div`,``,...t.map(Yo)))}var Zo=`text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,X=(e,t=!1)=>Qo(e,`${t?`btn btn-primary`:`btn`} text-[12.5px]`),Qo=(e,t=``)=>{let n=G(`button`,t,e);return n.type=`button`,n};function $o(e,t,n){let r=X(e);return t&&r.classList.add(`bg-neutral-200`),r.onclick=n,r}function es(e,t,n){let r=Qo(e,`flex cursor-pointer items-center gap-1.5 rounded-full px-3 py-1 text-[13px] transition-colors ${t?`bg-indigo-50 font-medium text-indigo-700 ring-1 ring-indigo-200/70`:`text-neutral-600 hover:bg-neutral-100`}`);return r.onclick=n,r}function ts(e,t,...n){let r=G(`section`,`rounded-xl border border-neutral-200 bg-white shadow-xs`),i=G(`div`,`rounded-t-xl border-b border-neutral-200/70 bg-neutral-50/70 px-4 py-2.5`);return i.append(G(`h2`,`text-[13px] font-semibold text-neutral-700`,e)),t&&i.append(G(`p`,`mt-0.5 text-[11.5px] leading-snug text-neutral-500`,t)),r.append(i,G(`div`,`flex flex-col gap-4 px-4 py-3.5`,...n)),r}function Z(e,t,n={}){let r=G(`div`,`flex flex-col gap-1.5`),i=G(`div`,`flex items-center gap-1.5`,G(`span`,Zo,e));return n.help&&i.append(n.help),r.append(i,t),n.hint&&r.append(G(`span`,`text-[11.5px] leading-snug text-neutral-400`,n.hint)),r}var ns=`w-full rounded-lg border border-neutral-300 bg-white px-2.5 py-1.5 text-[12.5px] transition-colors placeholder:text-neutral-400 focus:border-indigo-400 focus:ring-2 focus:ring-indigo-100 focus:outline-none`,rs=(e,t,n,r=!1)=>{let i=document.createElement(`input`);return i.className=r?`${ns} font-mono`:ns,i.value=e,i.placeholder=t,i.oninput=()=>n(i.value),i},Q=(e=``,t=`text`)=>{let n=document.createElement(`input`);return n.type=t,n.className=ns,n.value=e,n},is=(e,t)=>{let n=document.createElement(`select`);return n.className=`${ns} select`,n.append(...e.map(([e,t])=>new Option(e,t))),n.value=t,n},as=(e=``,t=4)=>{let n=document.createElement(`textarea`);return n.className=`${ns} resize-y font-mono`,n.value=e,n.rows=t,n.spellcheck=!1,n};function os(e,t,n,r,i){let a=document.createElement(`input`);a.type=`checkbox`,a.className=`peer sr-only`,a.checked=n,a.onchange=()=>r(a.checked);let o=G(`span`,`relative h-4 w-7 flex-none rounded-full bg-neutral-300 transition-colors after:absolute after:left-0.5 after:top-0.5 after:h-3 after:w-3 after:rounded-full after:bg-white after:shadow-sm after:transition-transform peer-checked:bg-indigo-600 peer-checked:after:translate-x-3 peer-focus-visible:ring-2 peer-focus-visible:ring-indigo-200`),s=G(`label`,`flex cursor-pointer gap-2.5 ${e?`items-start`:`items-center`}`);if(s.append(a,o),e){let n=G(`span`,`flex items-center gap-1.5`,G(`span`,`text-[13px] text-neutral-700`,e));i&&n.append(i);let r=G(`span`,`flex min-w-0 flex-col`,n);t&&r.append(G(`span`,`text-[11.5px] leading-snug text-neutral-400`,t)),s.append(r)}return s}var ss={idle:`text-neutral-400`,saving:`text-neutral-400`,saved:`text-green-700`,failed:`text-red-600`};function $(e,t,n){e.className=`text-[11.5px] ${ss[t]}`,e.textContent=n}var cs=(e,t)=>G(`span`,`flex-none rounded-full px-1.5 py-px text-[10px] font-medium uppercase tracking-wide ring-1 ${t}`,e),ls=e=>G(`p`,`rounded-lg border border-dashed border-neutral-200 px-3 py-4 text-center text-[12.5px] text-neutral-400`,e);function us(e,t,n=`left`){let r=G(`span`,`group relative inline-flex`),i=Qo(`?`,`flex h-4 w-4 cursor-help items-center justify-center rounded-full border border-neutral-300 text-[9px] font-bold text-neutral-400 transition-colors group-hover:border-indigo-400 group-hover:text-indigo-500`),a=G(`span`,`absolute ${n===`right`?`right-0`:`left-0`} top-full z-20 hidden w-[min(27rem,calc(100vw-3rem))] pt-1.5 group-hover:block`),o=G(`span`,`flex flex-col gap-2 rounded-xl border border-neutral-200 bg-white p-3.5 text-[12px] font-normal normal-case leading-[1.55] tracking-normal text-neutral-600 shadow-xl`);o.append(G(`span`,`text-[12.5px] font-semibold text-neutral-800`,e));let s=G(`ol`,`flex list-decimal flex-col gap-1.5 pl-4`);for(let e of t){let t=G(`li`,`marker:text-neutral-400`);t.append(typeof e==`string`?Qn(e):e),s.append(t)}return o.append(s),a.append(o),i.onclick=()=>{let e=a.classList.contains(`hidden`);a.classList.toggle(`hidden`,!e),a.classList.toggle(`block`,e),i.classList.toggle(`border-indigo-400`,e),i.classList.toggle(`text-indigo-500`,e)},r.append(i,a),r}var ds=(e,t)=>G(`span`,`flex flex-col gap-1`,Qn(e),t),fs=e=>`${e.provider}/${e.id}`,ps=`pier.modelFavorites`,ms=e=>`${fs(e)}@${e.thinking}`,hs=null;async function gs(){let e=await fetch(`/api/settings`);if(!e.ok)throw Error(`HTTP ${e.status}`);return(await e.json()).modelMenu}function _s(){try{let e=JSON.parse(localStorage.getItem(ps)??`[]`);return Array.isArray(e)?e.filter(e=>{let t=e;return!!t&&typeof t==`object`&&typeof t.provider==`string`&&typeof t.id==`string`&&typeof t.thinking==`string`}):[]}catch{return[]}}function vs(e){let t=G(`button`,`flex min-w-0 flex-1 cursor-pointer items-center gap-2 px-3 py-1.5 text-left`,G(`span`,`w-3 flex-none text-indigo-600`,e.checked?`✓`:``),G(`span`,`truncate`,e.label));e.hint&&t.append(G(`span`,`ml-auto flex-none text-[11.5px] text-neutral-400`,e.hint)),e.title&&(t.title=e.title),t.onclick=()=>e.onSelect();let n=G(`button`,`flex-none cursor-pointer px-2 py-1.5 leading-none ${e.starred?`text-amber-500`:`text-neutral-300 opacity-0 hover:text-amber-500 group-hover/row:opacity-100`}`,e.starred?`★`:`☆`);return n.title=e.starred?`Unstar`:`Star this model + reasoning`,n.onclick=t=>{t.stopPropagation(),e.onStar()},G(`div`,`group/row flex w-full items-center hover:bg-neutral-100`,t,n)}function ys({models:e,current:t,thinkingLevel:n,thinkingLevels:r,onPick:i,onThinkingPick:a}){let o=_s(),s=n,c=G(`div`,`flex w-72 flex-col`),l=G(`div`,`flex flex-col gap-2 border-b border-neutral-200 px-2 py-2`),u=document.createElement(`input`);if(u.type=`search`,u.placeholder=`Search models`,u.setAttribute(`aria-label`,`Search models`),u.className=`w-full rounded-md border border-neutral-300 px-2 py-1.5 text-[12.5px] focus:border-indigo-400 focus:outline-none`,l.append(u),r.length){let e=G(`label`,`flex items-center gap-2 px-1 text-[12px] text-neutral-500`),t=document.createElement(`select`);t.className=`select ml-auto rounded-md border border-neutral-300 px-2 py-1 text-[12px] text-neutral-700 focus:border-indigo-400 focus:outline-none`,t.setAttribute(`aria-label`,`Reasoning level`);for(let e of r){let n=document.createElement(`option`);n.value=e,n.textContent=Rn(e),t.append(n)}t.value=n,t.onchange=()=>{s=t.value,g(u.value),a(s)},e.append(G(`span`,`font-medium`,`Reasoning`),t),l.append(e)}let d=e=>{let t=ms(e);o=o.some(e=>ms(e)===t)?o.filter(e=>ms(e)!==t):[...o,e],localStorage.setItem(ps,JSON.stringify(o)),g(u.value)},f=(e,t)=>o.some(n=>ms(n)===`${fs(e)}@${t}`),p=G(`div`,`max-h-72 overflow-y-auto py-1`),m=new Map(e.map(e=>[fs(e),e])),h=(e,n,r)=>{let a=n.map(e=>({e,model:m.get(fs(e))})).filter(e=>!!e.model&&(!r||fs(e.model).toLowerCase().includes(r)));a.length&&p.append(G(`div`,`px-3 pb-0.5 pt-1 text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,e),...a.map(({e,model:n})=>{let r=e.thinking??s;return vs({label:n.id,hint:e.thinking?Rn(e.thinking):void 0,title:e.note,checked:!!t&&fs(t)===fs(n)&&s===r,starred:f(n,r),onSelect:()=>i(n,e.thinking),onStar:()=>d({provider:n.provider,id:n.id,thinking:r})})}),G(`div`,`my-1 border-t border-neutral-100`))},g=n=>{p.replaceChildren();let r=n.trim().toLowerCase();h(`Pinned`,hs??[],r),h(`Starred`,o,r);let a=new Map;for(let t of e){if(r&&!fs(t).toLowerCase().includes(r))continue;let e=a.get(t.provider);e?e.push(t):a.set(t.provider,[t])}if(!a.size){p.append(G(`div`,`px-3 py-2 text-[12.5px] text-neutral-400`,e.length?`No matching models.`:`No models available.`));return}for(let[e,n]of a){let a=n.some(e=>!!t&&fs(t)===fs(e)),o=document.createElement(`details`);o.open=a||r.length>0;let c=G(`summary`,`flex cursor-pointer select-none items-center gap-1.5 px-3 py-1 text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400 hover:bg-neutral-100`,G(`span`,`chev`,`▶`),G(`span`,`truncate`,e),G(`span`,`ml-auto flex-none normal-case text-neutral-300`,String(n.length)));o.append(c,...n.map(e=>vs({label:e.id,checked:!!t&&fs(t)===fs(e),starred:f(e,s),onSelect:()=>i(e),onStar:()=>d({provider:e.provider,id:e.id,thinking:s})}))),p.append(o)}};return u.oninput=()=>g(u.value),g(``),gs().then(e=>{let t=JSON.stringify(e)!==JSON.stringify(hs);hs=e,t&&g(u.value)}).catch(e=>Wa(`model menu unavailable`,e)),c.append(l,p),queueMicrotask(()=>u.focus()),c}function bs(e,t,n,r){let i=Qo(t.model?`${t.model.id}${t.thinking?` · ${Rn(t.thinking)}`:``}`:t.thinking?`Pi default · ${Rn(t.thinking)}`:`Pi default`,`${ns} flex cursor-pointer items-center gap-1.5 truncate text-left hover:bg-neutral-50 ${t.model?`text-neutral-700`:`text-neutral-400`}`);return i.title=t.model?`${t.model.provider}/${t.model.id}`:`Whatever the project and Pi pick`,i.onclick=()=>{let e=ys({models:n,current:t.model,thinkingLevel:t.thinking??`medium`,thinkingLevels:[...ji],onPick:(e,n)=>{Y(),r({model:e,thinking:n??t.thinking})},onThinkingPick:e=>r({...t,thinking:e})}),a=Qo(`Pi default`,`w-full cursor-pointer px-3 py-1.5 text-left text-[12.5px] text-neutral-500 hover:bg-neutral-100`);a.onclick=()=>{Y(),r({model:null,thinking:null})};let o=G(`div`,`flex flex-col`);o.append(e,G(`div`,`border-t border-neutral-200`),a),Jo(i,o)},Z(e,i)}var xs=async e=>{let t=e?.startsWith(`/`)?`?path=${encodeURIComponent(e)}`:``,n=await fetch(`/api/fs/dirs${t}`);return n.ok?await n.json():null},Ss=(e,t,n)=>{let r=Qo(e,`flex w-full cursor-pointer items-center gap-1.5 px-3 py-1 text-left ${t}`);return r.onclick=n,r};function Cs(e,t){let n=G(`div`,`flex-none border-t border-neutral-200`),r=Ss(`+ New folder`,`text-[12px] text-neutral-500 hover:bg-neutral-100`,()=>{let r=document.createElement(`input`);r.className=`w-full border-0 bg-transparent px-3 py-1 font-mono text-[12.5px] focus:outline-none`,r.placeholder=`folder-name`;let i=G(`p`,`hidden px-3 pb-1 text-[11.5px] text-red-600`);r.onkeydown=async n=>{if(n.key!==`Enter`)return;n.preventDefault();let a=await l(`/api/fs/dirs`,{path:e,name:r.value});if(!a.ok){i.textContent=(await a.json()).error??`could not create`,i.classList.remove(`hidden`);return}t((await a.json()).path)},n.replaceChildren(r,i),r.focus()});return n.append(r),n}function ws(e,t,n){let r=e=>{n(e),Y()};async function i(t){let n=await xs(t);if(!n)return;let a=G(`div`,`flex max-h-80 w-80 flex-col`),o=Qo(`Use`,`ml-auto flex-none cursor-pointer rounded bg-indigo-600 px-2 py-0.5 text-[11.5px] text-white`);o.onclick=()=>r(n.path);let s=G(`div`,`flex flex-none items-center gap-2 border-b border-neutral-200 px-3 py-1.5`,G(`span`,`truncate font-mono text-[11.5px] text-neutral-500`,n.path),o),c=G(`div`,`min-h-0 flex-1 overflow-y-auto py-0.5 text-[12.5px]`);n.parent&&c.append(Ss(`../`,`font-mono text-neutral-500 hover:bg-neutral-100`,()=>void i(n.parent)));for(let e of n.entries)c.append(Ss(e,`truncate hover:bg-neutral-100`,()=>void i(`${n.path}/${e}`.replace(`//`,`/`))));n.entries.length||c.append(G(`p`,`px-3 py-1.5 text-[12px] text-neutral-400`,`No sub-folders.`)),a.append(s,c,Cs(n.path,e=>void i(e))),Jo(e,a)}i(t)}function Ts(e,t){let n=Qo(`Browse…`,`flex-none cursor-pointer rounded-md border border-neutral-300 px-2 py-1 text-[12px] text-neutral-600 hover:bg-neutral-100`);return n.onclick=()=>ws(n,e.value.trim()||void 0,n=>{e.value=n,e.dispatchEvent(new Event(`input`,{bubbles:!0})),t?.(n)}),n}function Es(e,t,n){let r=document.createElement(`input`);return r.className=`min-w-0 flex-1 rounded-md border border-neutral-300 bg-white px-2 py-1 font-mono text-[12.5px] focus:border-indigo-400 focus:outline-none`,r.value=e,r.placeholder=t,r.oninput=()=>n(r.value),{el:G(`div`,`flex items-center gap-1.5`,r,Ts(r,n)),input:r}}var Ds,Os=W(`#project-tree`),ks=W(`#archive-dialog`),As=W(`#archive-list`),js=W(`#archive-search`),Ms=W(`#archive-count`),Ns=W(`#new-dialog`),Ps=W(`#known-projects`),Fs=`pier.collapsedProjects`,Is=new Set(Ls());function Ls(){try{let e=JSON.parse(localStorage.getItem(Fs)??`[]`);return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}catch{return[]}}function Rs(e,t){t?Is.add(e):Is.delete(e),localStorage.setItem(Fs,JSON.stringify([...Is]))}function zs(e){let t=new Map;for(let n of e){let e=t.get(n.cwd);e?e.push(n):t.set(n.cwd,[n])}return t}var Bs=`ml-auto hidden flex-none rounded px-1 leading-none text-neutral-400 hover:bg-neutral-200 hover:text-neutral-700 group-hover:block pointer-coarse:block`;function Vs(e){let[t,n]=e.state===`streaming`?[`bg-green-500 animate-pulse`,`working…`]:e.unread?[`bg-amber-500`,`turn finished — not viewed yet`]:e.activeRuns>0?[`bg-sky-500`,`${e.activeRuns} subagent${e.activeRuns>1?`s`:``} running`]:[`bg-neutral-300`,`idle`],r=G(`span`,`h-2 w-2 flex-none rounded-full ${t}`);return r.title=n,r}async function Hs(e,t){e.pinned=t,Gs(),Ds.onPinsChanged(),(await l(`/api/sessions/${e.id}/pin`,{pinned:t,cwd:e.cwd,createdAt:e.createdAt,...e.title?{title:e.title}:{}})).ok||(e.pinned=!t,Gs(),Ds.onPinsChanged())}function Us(e){let t=G(`li`,`group flex cursor-pointer items-center gap-1.5 py-1.5 pl-6 pr-3 hover:bg-neutral-100 ${e.id===Ds.currentId()?`bg-indigo-50 hover:bg-indigo-50`:``}`),n=G(`button`,Bs,`⋯`);return n.title=`Session actions`,n.onclick=t=>{t.stopPropagation(),Ds.sessionMenu(n,e)},t.append(Vs(e),G(`span`,`truncate`,e.title??`untitled`),n),t.onclick=()=>Ds.select(e.id),t}function Ws(e,t){let n=G(`span`,`ml-auto flex-none text-[11px] text-neutral-400 group-hover:hidden`,String(t.length)),r=G(`button`,Bs,`⋯`);r.title=`Project actions`,r.onclick=t=>{t.preventDefault(),t.stopPropagation(),Xo(r,[{label:`New session here`,hint:Yn(e),onSelect:()=>{Y(),Ds.createSession(e)}},{label:`Browse files`,onSelect:()=>{Y(),Ds.openFiles(e)}},{label:`Terminal here`,onSelect:()=>{Y(),Ds.openTerminal(e)}}])};let{el:i,summary:a}=nr(`border-b border-neutral-200/70`,[G(`span`,`truncate font-mono text-[11px] font-semibold uppercase tracking-wide text-neutral-500`,Yn(e)),n,r]);a.className+=` group px-3 py-1.5 hover:bg-neutral-100`,a.title=e,i.open=!Is.has(e),i.ontoggle=()=>Rs(e,!i.open);let o=G(`ul`,`pb-1`);return o.append(...t.map(Us)),i.append(o),i}function Gs(){let e=Ds.sessions(),t=zs(e.filter(e=>e.pinned));Os.replaceChildren(...t.size?[...t].map(([e,t])=>Ws(e,t)):[G(`p`,`px-3 py-2 text-[12.5px] leading-snug text-neutral-400`,`No projects yet — create a session, or pin one from All sessions.`)]),Ps.replaceChildren(...[...zs(e).keys()].map(e=>{let t=document.createElement(`option`);return t.value=e,t})),ks.open&&tc()}var Ks=[{name:`activity`,label:`Activity`,detail:`Console — runs, scheduled tasks, dependencies`},{name:`boards`,label:`Boards`,detail:`Console — the static pages Pier publishes`},{name:`settings`,label:`Settings`,detail:`Console — providers, models, channels, agent files, password, sign out, security`}],qs=[],Js=0,Ys={ArrowDown:1,ArrowUp:-1},Xs={n:1,j:1,p:-1,k:-1};function Zs(e){qs.length&&(Js=(e+qs.length)%qs.length,qs.forEach(({el:e},t)=>e.classList.toggle(`bg-indigo-50`,t===Js)),qs[Js]?.el.scrollIntoView({block:`nearest`}))}function Qs(e){let t=G(`button`,`flex-none rounded px-1.5 py-0.5 text-[11.5px] ${e.pinned?`bg-indigo-50 text-indigo-600`:`text-neutral-400 hover:bg-neutral-200 hover:text-neutral-700`}`,e.pinned?`pinned`:`pin`);return t.title=e.pinned?`Remove from Projects`:`Pin to Projects`,t.onclick=t=>{t.stopPropagation(),Hs(e,!e.pinned)},t}function $s(e){let t=G(`li`,`flex cursor-pointer items-center gap-2 px-3 py-1.5`);return t.append(e.session?Vs(e.session):G(`span`,`h-2 w-2 flex-none`)),t.append(G(`span`,`min-w-0 flex-1 truncate`,e.label),G(`span`,`max-w-[45%] flex-none truncate text-[11.5px] text-neutral-400`,e.detail)),e.session&&t.append(G(`span`,`flex-none text-[11px] text-neutral-400`,Jn(e.session.createdAt)),Qs(e.session)),t.onmouseenter=()=>Zs(qs.findIndex(e=>e.el===t)),t.onclick=e.open,t}var ec=e=>G(`li`,`px-3 pb-0.5 pt-2 text-[11px] font-semibold uppercase tracking-wide text-neutral-400`,e);function tc(){let e=js.value.trim().toLowerCase(),t=t=>!e||t.toLowerCase().includes(e),n=e=>()=>{ks.close(),e()},r=Ds.sessions().filter(e=>t(`${e.title??``} ${e.cwd}`)),i=(e,t)=>t.createdAt-e.createdAt,a=e=>({label:e.title??`untitled`,detail:Yn(e.cwd),open:n(()=>Ds.select(e.id)),session:e}),o=r.filter(e=>e.state===`streaming`),s=r.filter(e=>e.state!==`streaming`),c=[`Console`,Ks.filter(e=>t(`${e.label} ${e.detail}`)).map(({name:e,label:t,detail:r})=>({label:t,detail:r,open:n(()=>Ds.openConsole(e))}))],l=[[`Running`,o.sort(i).map(a)],[`Projects`,s.filter(e=>e.pinned).sort(i).map(a)],[`Other sessions`,s.filter(e=>!e.pinned).sort(i).map(a)]];e?l.unshift(c):l.push(c),qs=[];let u=[];for(let[e,t]of l)if(t.length){u.push(ec(e));for(let e of t){let t=$s(e);qs.push({el:t,open:e.open}),u.push(t)}}As.replaceChildren(...u.length?u:[G(`li`,`px-3 py-3 text-[13px] text-neutral-400`,`Nothing matches.`)]),Ms.textContent=String(qs.length),Zs(Js)}function nc(){if(ks.open)return ks.close();js.value=``,Js=0,tc(),ks.showModal(),js.focus(),Ds.loadSessions().then(()=>{ks.open&&tc()})}function rc(e){Ds=e,W(`#new-cwd-row`).append(Ts(W(`#new-cwd`)));let t=W(`#new-session`),n=()=>{let e=Ds.sessions().find(e=>e.id===Ds.currentId())?.cwd??``,t=W(`#new-cwd`);t.value=e,Ns.showModal(),t.select()};t.onclick=n,ro(t,`shift+o`,`New session`,n,()=>Ns.open),W(`#new-cancel`).onclick=()=>Ns.close(),W(`#new-form`).onsubmit=()=>void Ds.createSession(W(`#new-cwd`).value.trim());let r=W(`#open-archive`);r.onclick=nc,ro(r,`k`,`Search sessions and Console`,nc,()=>ks.open),W(`#archive-close`).onclick=()=>ks.close(),js.oninput=()=>{Js=0,tc()},js.onkeydown=e=>{let t=e.altKey||e.metaKey||e.shiftKey?void 0:e.ctrlKey?Xs[e.key.toLowerCase()]:Ys[e.key];if(t!==void 0){e.preventDefault(),Zs(Js+t);return}e.key===`Enter`&&!e.ctrlKey&&(e.preventDefault(),qs[Js]?.open())}}var ic;function ac(e){ic=e,so(sc,()=>{let e=ic.currentSession();e&&(Y(),Hs(e,!e.pinned))},oc),so(cc,()=>{let e=ic.currentSession();e&&(Y(),ic.toggleFiles(e.cwd))},oc)}var oc=()=>document.querySelector(`dialog[open]`)!==null,sc=`d`,cc=`i`,lc=W(`#chat-title`),uc=W(`#chat-menu`),dc=W(`#session-meta`),fc=null,pc=null,mc=null;function hc(){fc=null,pc=null,mc=null,xc()}function gc(e,t,n){fc=e,pc=t,mc=n,vc()}function _c(e){pc&&(pc={...pc,tokens:e},xc())}function vc(){let e=ic.currentSession();lc.textContent=e?e.title??`Untitled session`:`no session`,uc.classList.toggle(`hidden`,!e),e&&(uc.onclick=()=>Dc(uc,e)),xc(),ic.syncBar()}var yc=(e,t)=>Math.min(100,Math.round(e/t.contextWindow*100)),bc=e=>e.tokens===null?`?/${zn(e.contextWindow)}`:`${zn(e.tokens)}/${zn(e.contextWindow)} · ${100-yc(e.tokens,e)}% left`;function xc(){let e=pc,t=e?.tokens??null,n=ic.currentId(),r=[];if(n){let e=(e,t)=>{let r=G(`button`,`flex-none cursor-pointer font-mono ${t}`,e);return r.title=`Change model or reasoning`,r.onclick=()=>void Cc(r,n),r};fc&&r.push(e(fc.id,`rounded bg-indigo-50 px-1.5 py-px font-medium text-indigo-700 hover:bg-indigo-100`)),mc&&r.push(e(mc,`text-neutral-500 hover:text-indigo-700`))}if(e&&t!==null){let n=yc(t,e),i=n>=90?`text-red-700`:n>=70?`text-amber-700`:`text-neutral-500`;r.push(G(`span`,`flex-none font-mono ${i}`,zn(t).toLowerCase()))}let i=r.flatMap((e,t)=>t===0?[e]:[G(`span`,`text-neutral-300`,`·`),e]);dc.replaceChildren(...i),dc.classList.toggle(`hidden`,r.length===0),dc.classList.toggle(`flex`,r.length>0)}function Sc(e,t){let n=[[`Title`,t.title??`untitled`],[`Directory`,t.cwd],[`Session`,t.id]];t.id===ic.currentId()&&(n.push([`Model`,fc?.id??`—`]),n.push([`Context`,pc?bc(pc):`—`]));let r=G(`div`,`flex max-w-80 flex-col gap-1.5 px-3 py-2`);for(let[e,t]of n){let n=G(`div`,`flex items-center gap-1.5`,G(`span`,`text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,e),tr(`cursor-pointer text-[10.5px] uppercase tracking-wide text-neutral-400 opacity-0 hover:text-neutral-700 focus:opacity-100 group-hover:opacity-100 pointer-coarse:opacity-100`,()=>t));r.append(G(`div`,`group flex flex-col`,n,G(`span`,`break-all font-mono text-[12px] text-neutral-700`,t)))}Jo(e,r)}async function Cc(e,t){try{let[n,r]=await Promise.all([fetch(`/api/sessions/${t}/models`),fetch(`/api/sessions/${t}/thinking`)]);if(!n.ok||!r.ok)throw Error(`HTTP ${n.ok?r.status:n.status}`);let i=await n.json(),a=await r.json();Jo(e,ys({models:i,current:t===ic.currentId()?fc:null,thinkingLevel:a.level,thinkingLevels:a.levels,onPick:(e,n)=>{Y(),wc(t,e,n)},onThinkingPick:e=>void Ec(t,e)}))}catch(e){q(`error`,`model options failed: ${String(e)}`)}}async function wc(e,t,n){await Tc(e,t)&&n&&await Ec(e,n)}async function Tc(e,t){let n=fc;e===ic.currentId()&&(fc=t,vc());let r=await l(`/api/sessions/${e}/model`,t);if(!r.ok){let{error:t}=await r.json().catch(()=>({}));return e===ic.currentId()&&(fc=n,vc()),q(`error`,`model change failed: ${t??r.status}`),!1}let{model:i}=await r.json();return e===ic.currentId()&&i&&(fc=i,vc()),!0}async function Ec(e,t){let n=await l(`/api/sessions/${e}/thinking`,{level:t});if(!n.ok){q(`error`,`reasoning change failed: ${n.status}`);return}let{level:r}=await n.json();e===ic.currentId()&&(mc=r,xc())}function Dc(e,t){let n=t.id===ic.currentId();Xo(e,[{label:`Session info`,onSelect:()=>Sc(e,t)},{label:t.pinned?`Remove from Projects`:`Pin to Projects`,hint:n?eo(sc):``,checked:t.pinned,onSelect:()=>{Y(),Hs(t,!t.pinned)}},{label:`Model`,hint:n?fc?.id??`…`:``,onSelect:()=>void Cc(e,t.id)},{label:`Browse files`,hint:n?eo(cc):``,onSelect:()=>{Y(),ic.openFiles(t.cwd)}}])}var Oc=W(`#sidebar`),kc=W(`#drawer-scrim`),Ac=W(`#mobile-title`),jc=W(`#mobile-menu`);function Mc(){delete Oc.dataset.open,kc.classList.add(`hidden`)}function Nc(e,t){Ac.textContent=e,jc.classList.toggle(`hidden`,!t)}var Pc=`pier.railClosed`;localStorage.getItem(Pc)===`1`&&(document.body.dataset.rail=`closed`);function Fc(e){document.body.dataset.rail=e?`closed`:``,localStorage.setItem(Pc,e?`1`:`0`)}function Ic(){if(Oc.dataset.open!==void 0)return Mc();Oc.dataset.open=``,kc.classList.remove(`hidden`)}var Lc=()=>window.innerWidth<768;function Rc(e){W(`#drawer-toggle`).onclick=Ic,kc.onclick=Mc,jc.onclick=()=>e.sessionMenu(jc);let t=W(`#rail-toggle`);t.onclick=()=>Fc(document.body.dataset.rail!==`closed`),ro(t,`meta+b`,`Toggle sidebar`,()=>Lc()?Ic():Fc(document.body.dataset.rail!==`closed`))}var zc=`https://github.com/timqi/pier`,Bc=[`text-neutral-400`,`hover:text-neutral-700`],Vc=[`rounded-full`,`bg-emerald-50`,`px-1.5`,`text-emerald-700`,`ring-1`,`ring-inset`,`ring-emerald-600/20`,`hover:bg-emerald-100`],Hc=18e5,Uc=null,Wc=W(`#version`);function Gc(e){let t=Uc?.available===!0&&Uc.latest!==null;Wc.textContent=`v${e}`,Wc.title=t?`Pier ${Uc?.latest} is out`:``,Wc.classList.remove(...t?Bc:Vc),Wc.classList.add(...t?Vc:Bc)}var Kc=e=>G(`p`,`px-3 py-1 text-[12px] leading-snug text-neutral-500`,e);function qc(){let e=G(`div`,`flex w-72 flex-col gap-1 py-1`);if(!Uc)return e.append(Kc(`Checking the registry…`)),e;let{current:t,latest:n,available:r,canApply:i,problem:a}=Uc;e.append(G(`p`,`px-3 py-1 text-[12.5px] font-medium text-neutral-700`,r?`Pier ${n} is out`:`Pier ${t}`)),e.append(Kc(r?`You are running ${t}.`:n===null?`The registry could not be reached, so this may not be the latest.`:`This is the latest release.`));let o=G(`span`,`px-3 text-[11.5px] text-neutral-400`,``),s=G(`div`,`flex items-center gap-2 px-3 py-1.5`);if(a&&e.append(G(`p`,`mx-3 my-1 rounded-md bg-red-50 px-2 py-1.5 text-[11.5px] leading-snug text-red-700`,a)),r&&i&&!a){let e=X(`Update now`,!0);e.onclick=()=>{e.disabled=!0,o.className=`px-3 text-[11.5px] text-neutral-400`,o.textContent=`starting the updater…`,(async()=>{let t=await l(`/api/update`,{});if(!t.ok){e.disabled=!1,o.className=`px-3 text-[11.5px] text-red-600`,o.textContent=await u(t,`Could not update`);return}let{draining:n}=await t.json();o.textContent=n?`Waiting for running work to finish — Pier then stops, installs and starts again.`:`Pier is stopping, installing and starting again — this page reconnects on its own.`})()},s.append(e)}let c=G(`a`,`btn text-[12.5px] no-underline`,`Source`);c.href=r?`${zc}/releases`:zc,c.target=`_blank`,c.rel=`noreferrer`,c.title=`Pier is free software (AGPL-3.0)`,s.append(c),e.append(s,o),r&&!i&&!a&&e.append(Kc(`No service manager owns this Pier, so it cannot restart itself — update it with: pier update`));let d=os(`Update automatically`,i?`Installs a new release once nothing is running — no turn in flight, no task run.`:`Needs the systemd service (pier service install); nothing here can restart Pier.`,Uc.autoUpdate,e=>{Uc&&(Uc.autoUpdate=e),(async()=>{let t=await l(`/api/settings`,{autoUpdate:e},`PUT`);if(t.ok)return;Uc&&(Uc.autoUpdate=!e);let n=d.querySelector(`input`);n&&(n.checked=!e),o.className=`px-3 text-[11.5px] text-red-600`,o.textContent=await u(t,`Could not save`)})()});if(!i){let e=d.querySelector(`input`);e&&(e.disabled=!0)}return e.append(G(`div`,`mt-1 border-t border-neutral-200 px-3 pb-1 pt-2`,d)),e}async function Jc(e){let t=await fetch(`/api/update`);t.ok&&(Uc=await t.json(),Gc(Uc.current||e))}function Yc(e){Gc(e),Wc.onclick=e=>{e.preventDefault(),Jo(Wc,qc())};let t=()=>void Jc(e).catch(()=>{});t(),setInterval(t,Hc)}var Xc=(e,t={})=>{let n=document.createElementNS(`http://www.w3.org/2000/svg`,e);for(let[e,r]of Object.entries(t))n.setAttribute(e,r);return n},Zc=e=>e===null?`-`:Xn(Date.now()-e);function Qc(e,t,n){let r=`sessions`,i=`active`,a={sessions:[],runs:[],messages:[]};async function o(){let t=await fetch(`/api/activity?scope=${i}`);if(!t.ok){e.replaceChildren(G(`p`,`p-4 text-[13px] text-red-600`,`Failed to load activity: ${t.status}`));return}a=await t.json(),s()}function s(){let t=G(`header`,`flex h-10 flex-none items-center gap-2 border-b border-neutral-200 px-4 max-md:hidden`,G(`span`,`font-medium`,`Activity`)),a=G(`div`,`tabstrip`);a.append($o(`Sessions`,r===`sessions`,()=>{r=`sessions`,s()}),$o(`Dependencies`,r===`dependencies`,()=>{r=`dependencies`,s()}),$o(`Tasks`,!1,()=>n()));let u=G(`div`,`ml-auto flex gap-1 max-md:ml-0 max-md:w-full`);u.append($o(`Active`,i===`active`,()=>{i=`active`,o()}),$o(`Last 24h`,i===`recent`,()=>{i=`recent`,o()})),a.append(u);let d=G(`div`,`min-h-0 flex-1 overflow-auto`);r===`sessions`?c(d):l(d),e.replaceChildren(t,a,d)}function c(e){let n=document.createElement(`table`);n.className=`w-full min-w-[38rem] table-fixed text-left text-[12.5px]`,n.innerHTML=`<thead class="bg-neutral-50 text-[10.5px] uppercase text-neutral-400"><tr>
|
|
77
|
+
<th class="w-[34%] px-4 py-2 font-semibold">Session</th>
|
|
78
|
+
<th class="w-[38%] px-2 py-2 font-semibold">Project</th>
|
|
79
|
+
<th class="w-[14%] px-2 py-2 font-semibold">State</th>
|
|
80
|
+
<th class="px-2 py-2 font-semibold">Duration</th></tr></thead>`;let r=document.createElement(`tbody`);for(let e of a.sessions){let n=document.createElement(`tr`);n.className=`cursor-pointer border-b border-neutral-100 hover:bg-neutral-50`,n.onclick=()=>t(e.id),n.append(G(`td`,`px-4 py-2.5`,G(`div`,`truncate font-medium`,e.title??`Untitled session`),G(`div`,`truncate font-mono text-[11px] text-neutral-400`,e.id)),G(`td`,`truncate px-2 py-2.5 font-mono text-[11.5px]`,e.cwd||`-`),G(`td`,`px-2 py-2.5`,G(`span`,`mr-2 inline-block h-2 w-2 rounded-full ${e.state===`streaming`?`animate-pulse bg-green-500`:`bg-neutral-300`}`),e.state),G(`td`,`px-2 py-2.5 text-neutral-500`,Zc(e.stateSince))),r.append(n)}n.append(r),e.append(n),a.sessions.length||e.append(G(`p`,`p-4 text-[13px] text-neutral-400`,i===`active`?`No active sessions.`:`No sessions in the last 24 hours.`))}function l(e){let r=new Map,o=[],s=(e,t,n,i)=>{r.has(e)||r.set(e,{id:e,label:t,kind:n,state:i})};for(let e of a.sessions)s(e.id,e.title??e.id.slice(0,10),`session`,e.state);for(let e of a.runs){let t=e.invokedBySessionId??`scheduler`,n=e.targetSessionId??(e.context.definition.action.type===`bash`?`process:${e.id}`:`task:${e.id}`);s(t,t===`scheduler`?`Scheduler`:t.slice(0,10),t===`scheduler`?`scheduler`:`session`),s(n,e.targetSessionId?e.targetSessionId.slice(0,10):e.context.definition.action.type===`bash`?`Bash process`:`Task`,e.targetSessionId?`session`:e.context.definition.action.type===`bash`?`process`:`task`),o.push({from:t,to:n,run:e,kind:`invocation`}),e.callbackSessionId&&(s(e.callbackSessionId,e.callbackSessionId.slice(0,10),`session`),o.push({from:n,to:e.callbackSessionId,run:e,kind:`callback`}))}for(let e of a.messages){if(!e.fromSessionId||!e.toSessionId||e.fromSessionId===e.toSessionId)continue;let t=a.runs.find(t=>t.id===e.runId);if(t){for(let t of[e.fromSessionId,e.toSessionId])s(t,t===`console`?`Console`:t.slice(0,10),t===`console`?`console`:`session`);o.push({from:e.fromSessionId,to:e.toSessionId,run:t,kind:`message`})}}if(!r.size){e.append(G(`p`,`p-4 text-[13px] text-neutral-400`,i===`active`?`No active dependencies.`:`No dependencies in the last 24 hours.`));return}let c=[...r.values()],l=new Set(o.map(e=>e.to)),u=new Map,d=c.filter(e=>!l.has(e.id)).map(e=>e.id);d.length||d.push(c[0].id);for(let e of d)u.set(e,0);for(;d.length;){let e=d.shift();for(let t of o)t.from!==e||u.has(t.to)||(u.set(t.to,u.get(e)+1),d.push(t.to))}for(let e of c)u.has(e.id)||u.set(e.id,0);let f=new Map;for(let e of c){let t=u.get(e.id);f.set(t,[...f.get(t)??[],e])}let p=Math.max(...f.keys())+1,m=Math.max(...[...f.values()].map(e=>e.length)),h=o.some(e=>e.from!==e.to&&u.get(e.from)===u.get(e.to))?40:0,g=56+p*180+(p-1)*110+h,_=56+m*46+(m-1)*30,v=new Map;for(let[e,t]of f)t.forEach((t,n)=>v.set(t.id,{x:28+e*290+90,y:28+n*76+23}));let y=Xc(`svg`,{width:String(g),height:String(_),viewBox:`0 0 ${g} ${_}`,class:`block`}),b=Xc(`defs`);for(let[e,t]of[[`activity-arrow`,`#a3a3a3`],[`activity-arrow-cb`,`#0891b2`],[`activity-arrow-msg`,`#d97706`]]){let n=Xc(`marker`,{id:e,viewBox:`0 0 10 10`,refX:`9`,refY:`5`,markerWidth:`6`,markerHeight:`6`,orient:`auto-start-reverse`});n.append(Xc(`path`,{d:`M 0 0 L 10 5 L 0 10 z`,fill:t})),b.append(n)}y.append(b);let x=new Set;for(let e of o){let t=`${e.from}→${e.to}:${e.kind}`;if(x.has(t))continue;x.add(t);let r=v.get(e.from),i=v.get(e.to),a=Xc(`path`,{d:r.x===i.x?`M ${r.x+90} ${r.y} C ${r.x+90+46} ${r.y}, ${i.x+90+46} ${i.y}, ${i.x+90} ${i.y}`:(()=>{let e=i.x>r.x,t=r.x+(e?90:-90),n=i.x+(e?-90:90),a=Math.max(36,Math.abs(n-t)*.45)*(e?1:-1);return`M ${t} ${r.y} C ${t+a} ${r.y}, ${n-a} ${i.y}, ${n} ${i.y}`})(),fill:`none`,stroke:e.kind===`callback`?`#0891b2`:e.kind===`message`?`#d97706`:`#a3a3a3`,"stroke-width":`1.5`,"marker-end":e.kind===`callback`?`url(#activity-arrow-cb)`:e.kind===`message`?`url(#activity-arrow-msg)`:`url(#activity-arrow)`});e.kind===`callback`&&a.setAttribute(`stroke-dasharray`,`6 5`),e.kind===`message`&&a.setAttribute(`stroke-dasharray`,`2 5`),a.classList.add(`cursor-pointer`),a.onclick=()=>n(e.run.taskId),y.append(a)}let S={scheduler:{fill:`#f5f3ff`,stroke:`#a78bfa`,text:`#5b21b6`},console:{fill:`#eff6ff`,stroke:`#93c5fd`,text:`#1d4ed8`},task:{fill:`#fffbeb`,stroke:`#fbbf24`,text:`#92400e`},process:{fill:`#f5f5f5`,stroke:`#a3a3a3`,text:`#525252`,dash:`4 3`}},C=/[\u1100-\u11FF\u2E80-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6]/,w=(e,t)=>{let n=0;for(let r=0;r<e.length;r++)if(n+=C.test(e[r])?2:1,n>t)return`${e.slice(0,r)}…`;return e};for(let e of c){let n=v.get(e.id),r=e.kind===`session`?e.state===`streaming`?{fill:`#ffffff`,stroke:`#10b981`,text:`#262626`}:{fill:`#fafafa`,stroke:`#d4d4d4`,text:`#737373`}:S[e.kind],i=Xc(`g`,{transform:`translate(${n.x},${n.y})`});e.kind===`session`&&i.classList.add(`cursor-pointer`),i.onclick=()=>{e.kind===`session`&&t(e.id)};let a=Xc(`rect`,{x:`-90`,y:`-23`,width:`180`,height:`46`,rx:`10`,fill:r.fill,stroke:r.stroke,"stroke-width":e.kind===`session`&&e.state===`streaming`?`1.5`:`1`});r.dash&&a.setAttribute(`stroke-dasharray`,r.dash),i.append(a);let o=-78;if(e.kind===`session`){let t=Xc(`circle`,{cx:`-75`,cy:`0`,r:`3.5`,fill:e.state===`streaming`?`#10b981`:`#d4d4d4`});if(e.state===`streaming`){let e=Xc(`animate`,{attributeName:`opacity`,values:`1;0.3;1`,dur:`1.6s`,repeatCount:`indefinite`});t.append(e)}i.append(t),o=-64}let s=Xc(`text`,{x:String(o),"text-anchor":`start`,"dominant-baseline":`middle`,"font-size":`11.5`,"font-weight":e.kind===`session`?`500`:`400`,fill:r.text});s.textContent=w(e.label,e.kind===`session`?22:25);let c=Xc(`title`);c.textContent=e.label===e.id?e.id:`${e.label}\n${e.id}`,i.append(s,c),y.append(i)}let T=e=>G(`span`,`inline-block h-2 w-2 rounded-full ${e}`);e.append(G(`div`,`w-max p-4`,y),G(`div`,`flex flex-wrap gap-x-5 gap-y-1 border-t border-neutral-200 px-4 py-2 text-[11px] text-neutral-500`,G(`span`,``,`Solid: task invocation`),G(`span`,`text-cyan-700`,`Dashed: callback`),G(`span`,`text-amber-700`,`Dotted: supervisor/control`),G(`span`,`inline-flex items-center gap-1.5`,T(`bg-emerald-500`),`streaming`),G(`span`,`inline-flex items-center gap-1.5`,T(`bg-neutral-300`),`idle`)))}let u=Zn(e,e=>{e===`dependencies`?r=`dependencies`:e===`sessions`&&(r=`sessions`),o()});return Object.assign(u,{refresh(){u.visible&&o()}})}function $c(e,t){let n=[],r=``,i=G(`header`,`sticky top-0 z-30 flex h-10 items-center gap-3 border-b border-neutral-200 bg-white px-4`,G(`span`,`font-medium max-md:hidden`,`Boards`)),a=G(`div`,`px-4 py-5`);e.append(G(`div`,`min-h-0 flex-1 overflow-y-auto`,i,a));async function o(e,t){let n=await l(`/api/boards/${e}`,{public:t},`PATCH`);n.ok||(r=`Could not change ${e}: ${n.status}`,await f())}async function s(e){let t=await fetch(`/api/boards/${e}`,{method:`DELETE`});t.ok||(r=`Could not delete ${e}: ${t.status}`),await f()}function c(e){let n=G(`div`,`group flex flex-col gap-1 border-b border-neutral-200/70 px-1 py-2.5 last:border-b-0`),r=document.createElement(`a`);r.className=`truncate font-medium text-neutral-800 hover:text-indigo-700`,r.href=`/boards/${e.slug}/`,r.target=`_blank`,r.rel=`noreferrer`,r.textContent=e.title;let i=G(`div`,`flex items-center gap-2`,r,G(`span`,`flex-none font-mono text-[11.5px] text-neutral-400`,e.slug)),a=os(``,``,e.public,t=>{e.public=t,o(e.slug,t)});a.className=`ml-auto flex flex-none cursor-pointer items-center gap-1.5 text-[11.5px] text-neutral-500`,a.append(G(`span`,``,`Public`));let c=Qo(`Delete`,`flex-none cursor-pointer text-[11.5px] text-neutral-400 opacity-0 transition-opacity hover:text-red-600 group-hover:opacity-100`);c.title=`Renames the folder on disk; nothing is erased`,c.onclick=()=>void s(e.slug),i.append(a,c),n.append(i);let l=G(`div`,`flex flex-wrap items-center gap-x-3 gap-y-1 text-[11.5px] text-neutral-500`);e.description&&l.append(G(`span`,`min-w-0 truncate`,e.description)),l.append(G(`span`,`flex-none text-neutral-400`,Jn(Date.parse(e.updatedAt))));for(let n of e.sessions){let e=Qo(n.slice(0,8),`flex-none cursor-pointer font-mono text-indigo-600 hover:underline`);e.title=`Open session ${n}`,e.onclick=()=>t(n),l.append(e)}if(e.public){let t=G(`span`,`flex-none font-mono text-neutral-400`,`/p/${e.slug}/`);t.title=`Public URL — anyone who can reach Pier can read this`,l.append(t)}return n.append(l),n}let u=[{title:`Public`,hint:`Readable at /p/<slug>/ by anyone who can reach Pier.`,wanted:!0},{title:`Private`,hint:`Reachable from the Console only.`,wanted:!1}];function d(){let e=G(`div`,`mx-auto flex max-w-3xl flex-col`);n.length===0&&e.append(G(`p`,`rounded-xl border border-dashed border-neutral-300 px-4 py-6 text-center text-[12.5px] text-neutral-500`,`No boards yet. Ask an agent to build one — it writes a folder under ~/.pier/boards.`));for(let{title:t,hint:r,wanted:i}of u){let a=n.filter(e=>e.public===i);if(a.length===0)continue;let o=G(`section`,`mb-6`);o.append(G(`h2`,`text-[13px] font-semibold text-neutral-700`,t)),o.append(G(`p`,`mb-1 text-[11.5px] leading-snug text-neutral-500`,r));let s=G(`div`,`rounded-xl border border-neutral-200 bg-white px-3`);s.append(...a.map(c)),o.append(s),e.append(o)}a.replaceChildren(...r?[G(`p`,`mb-3 text-[13px] text-red-600`,r)]:[],e)}async function f(){let e=await fetch(`/api/boards`);if(!e.ok)return r=`Could not load boards: ${e.status}`,d();n=await e.json(),d(),r=``}let p=Zn(e,()=>void f());return window.addEventListener(`focus`,()=>{p.visible&&f()}),p}var el=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`},tl=e=>[e.subject,e.body,[[e.author,e.email?`<${e.email}>`:``].filter(Boolean).join(` `),e.at?el(e.at):``].filter(Boolean).join(` · `)].filter(Boolean).join(`
|
|
81
|
+
|
|
82
|
+
`),nl=null;function rl(){nl&&(nl.remove(),nl=null,document.removeEventListener(`pointerdown`,rl,!0),window.removeEventListener(`scroll`,rl,!0))}function il(e,t){e.onmouseenter=()=>{rl();let n=t();if(!n)return;nl=G(`div`,`pointer-events-none fixed z-50 max-w-96 whitespace-pre-wrap rounded-lg bg-neutral-800/95 px-3 py-2 font-sans text-[11.5px] leading-snug text-neutral-100 shadow-lg`),nl.textContent=n,document.body.append(nl),document.addEventListener(`pointerdown`,rl,!0),window.addEventListener(`scroll`,rl,!0);let r=e.getBoundingClientRect();nl.style.left=`${Math.max(8,Math.min(r.left,window.innerWidth-nl.offsetWidth-8))}px`,nl.style.top=r.bottom+6+nl.offsetHeight>window.innerHeight?`${r.top-nl.offsetHeight-6}px`:`${r.bottom+6}px`},e.onmouseleave=rl}function al(e,t,n){let r=G(`button`,`flex w-full cursor-pointer items-center gap-1.5 px-2 py-1 text-left hover:bg-neutral-100`,G(`span`,`w-3 flex-none text-indigo-600`,e.value===t?`✓`:``),G(`span`,`flex-none font-mono text-[11.5px] text-neutral-800`,e.label??e.value));return e.subject&&r.append(G(`span`,`min-w-0 truncate text-[11px] text-neutral-400`,e.subject)),e.author&&r.append(G(`span`,`ml-auto flex-none pl-1.5 text-[10.5px] text-neutral-400`,`${e.author} · ${e.at?Jn(e.at):``}`)),il(r,()=>tl(e)),r.onclick=()=>n(e.value),r}function ol(e,t,n,r,i){let{base:a,head:o}=n,s=()=>o&&a===`${o}~1`?o:``,c=s()?`commit`:`compare`,l=t.commits[0],u=e=>[...e?[{value:``,label:`Working tree`,subject:`the files on disk, uncommitted changes included`}]:[],{...l,value:`HEAD`},...t.refs.map(e=>({value:e.name,subject:e.subject})),...t.commits.map(e=>({...e,value:e.hash}))],d=G(`div`,`flex w-[38rem] max-w-full flex-col`);function f(){let e=(e,t)=>{let n=G(`button`,`cursor-pointer rounded-full px-2.5 py-0.5 text-[11.5px] ${c===t?`bg-indigo-50 font-medium text-indigo-700`:`text-neutral-500 hover:bg-neutral-100`}`,e);return n.onclick=()=>{c=t,f()},n},n=(e,t,n,r)=>G(`div`,`flex min-w-0 flex-1 flex-col`,G(`div`,`flex-none px-2 pb-0.5 text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,e),G(`div`,`min-h-0 flex-1 overflow-y-auto`,...t.map(e=>al(e,n,r)))),l=c===`compare`?G(`div`,`flex h-72 min-h-0 divide-x divide-neutral-200 pb-1`,n(`base`,u(!1),a,e=>{a=e,f(),r(a,o)}),n(`to`,u(!0),o,e=>{o=e,f(),r(a,o)})):G(`div`,`flex h-72 min-h-0 flex-col overflow-y-auto pb-1`,...t.commits.map(e=>al({value:e.hash,...e},s(),e=>{a=`${e}~1`,o=e,Y(),r(a,o)}))),p=G(`div`,`flex-none border-t border-neutral-200`,al({value:i,label:`↺ ${i} ↔ Working tree`,subject:`back to the default: the main line's tip vs the files on disk`},a===i&&o===``?i:``,()=>{a=i,o=``,f(),r(a,o)}));d.replaceChildren(G(`div`,`flex flex-none items-center gap-1 border-b border-neutral-200 px-2 py-1.5`,e(`Compare two points`,`compare`),e(`One commit`,`commit`)),l,...c===`compare`?[p]:[])}f(),Jo(e,d)}var sl=/\.(png|jpe?g|gif|webp|avif|bmp|svg)$/i,cl={A:`text-emerald-600`,M:`text-amber-600`,D:`text-red-600`},ll=2e4,ul=30,dl=(e,t=`indigo`)=>{let n=G(`button`,`min-w-0 cursor-pointer truncate rounded-md px-2 py-0.5 text-left font-mono text-[11.5px] ${t===`indigo`?`bg-indigo-50 font-medium text-indigo-700 hover:bg-indigo-100`:`bg-neutral-100 text-neutral-600 hover:bg-neutral-200`}`,e);return n.type=`button`,n};function fl(e,t,n,r){let i=``,a={branch:null,refs:[],commits:[]},o=`HEAD`,s=``,c=new Map,l=!0,u=!1,d=[],f=new Set,p=null,m=null,h=G(`header`,`flex h-10 flex-none items-center gap-2 border-b border-neutral-200 bg-white px-3`),g=G(`div`,`flex-none border-b border-neutral-200`),_=G(`div`,`min-h-0 flex-1 overflow-y-auto py-1`),v=G(`aside`,`flex w-64 flex-none flex-col border-r border-neutral-200 text-[12.5px] max-md:h-2/5 max-md:w-full max-md:border-b max-md:border-r-0`,g,_),y=G(`div`,`h-full min-w-0 overflow-auto`),b=G(`div`,`pointer-events-none absolute inset-y-0 right-0 z-20 hidden w-2`),x=G(`section`,`relative min-w-0 flex-1`,y,b);e.append(h,G(`div`,`flex min-h-0 flex-1 max-md:flex-col`,v,x));let S=(e,t)=>`/api/explorer/${e}?${new URLSearchParams({root:i,...t})}`;async function C(e){let t=await fetch(e),n=null;try{n=await t.json()}catch{}if(!t.ok||n===null)throw Error(n?.error??`HTTP ${t.status}`);return n}let w=(e,t=`text-neutral-400`)=>G(`p`,`px-4 py-3 text-[12.5px] ${t}`,e),T=e=>{let t=0;for(let n of c.keys())n.startsWith(`${e}/`)&&t++;return t};function E(e,t){let n=new Set(t.map(e=>e.name)),r=e?`${e}/`:``;for(let[e,i]of c){if(i.status!==`D`||!e.startsWith(r))continue;let a=e.slice(r.length).split(`/`)[0];n.has(a)||(n.add(a),t.push({name:a,dir:e.slice(r.length).includes(`/`)}))}let i=t;return l&&a.branch&&(i=t.filter(e=>e.dir?T(`${r}${e.name}`)>0:c.has(`${r}${e.name}`))),i.sort((e,t)=>Number(t.dir)-Number(e.dir)||e.name.localeCompare(t.name)),i.map(e=>e.dir?O(`${r}${e.name}`,e.name):A(`${r}${e.name}`,e.name))}async function D(e,t){try{let{entries:n}=await C(S(`ls`,{path:t}));e.replaceChildren(...E(t,n)),e.childElementCount||e.append(w(l?`No changes.`:`Empty.`))}catch(n){let r=E(t,[]);r.length?e.replaceChildren(...r):e.replaceChildren(w(String(n),`text-red-600`))}}function O(e,t){let n=T(e),r=[G(`span`,`truncate`,t)];n&&r.push(G(`span`,`ml-auto flex-none rounded bg-amber-100/80 px-1 font-mono text-[10px] text-amber-700`,String(n)));let{el:i,summary:o}=nr(``,r);o.className+=` px-2 py-0.5 hover:bg-neutral-100`;let s=G(`div`,`pl-3`);i.append(s);let c=!1,d=()=>{c||(c=!0,s.append(w(`…`)),D(s,e))};return i.ontoggle=()=>{f[i.open?`add`:`delete`](e),i.open&&d()},(l&&a.branch&&!u||f.has(e))&&(i.open=!0,d()),i}function k(e){m?.classList.remove(`bg-indigo-50`,`text-indigo-700`),m=e,e.classList.add(`bg-indigo-50`,`text-indigo-700`)}function A(e,t){let n=c.get(e)?.status,r=G(`button`,`flex w-full cursor-pointer items-center gap-1.5 px-2 py-0.5 pl-6 text-left hover:bg-neutral-100`,G(`span`,`truncate`,t));return n&&r.append(G(`span`,`ml-auto flex-none font-mono text-[10.5px] font-semibold ${cl[n]??`text-neutral-500`}`,n)),r.title=e,e===p&&k(r),r.onclick=()=>{k(r),p=e,se(e)},r}let ee=()=>void D(_,``),j=(e,t)=>[...e?[G(`span`,`flex-none font-mono text-[10.5px] font-semibold text-emerald-600`,`+${e}`)]:[],...t?[G(`span`,`flex-none font-mono text-[10.5px] font-semibold text-red-600`,`−${t}`)]:[]];function M(e,t,n){let r=c.get(e),i=G(`div`,`sticky top-0 z-10 flex items-center gap-2 border-b border-neutral-200 bg-white px-4 py-1.5 font-mono text-[11.5px] text-neutral-500`,G(`span`,`truncate`,e));r&&(i.append(G(`span`,`flex-none font-semibold ${cl[r.status]??``}`,r.status)),i.append(...j(r.add,r.del)));let a=G(`div`,`ml-auto flex flex-none items-center gap-2`);if(n&&a.append(n),t){let t=document.createElement(`a`);t.className=`flex-none text-neutral-400 hover:text-indigo-700 hover:underline`,t.href=S(`file`,{path:e}),t.download=Yn(e),t.textContent=`Download`,a.append(t)}return i.append(a),i}function N(e,t){let n=e.length<=ll?t:null,r=Math.max(2,...e.map(e=>e.nums.reduce((e,t)=>Math.max(e,String(t).length),0))),i=G(`div`,`py-2 font-mono text-[12px] leading-[1.5]`);for(let t of e){let e=G(`div`,`flex pl-2 pr-4 ${t.tone===`add`?`bg-emerald-50`:t.tone===`del`?`bg-red-50`:``}`);for(let n of t.nums){let t=G(`span`,`flex-none select-none pr-1.5 text-right text-neutral-300`,n===``?``:String(n));t.style.width=`calc(${r}ch + 0.375rem)`,e.append(t)}e.append(te(t,n)),i.append(e)}return i}function te(e,t){let n=`min-w-0 flex-1 whitespace-pre-wrap [overflow-wrap:anywhere]`;if(!e.mark||e.mark[0]>=e.mark[1]){let r=Ti(e.text,t);return r.className=n,r}let[r,i]=e.mark,a=Ti(e.text.slice(r,i),t);return a.className=`rounded-xs ${e.tone===`add`?`bg-emerald-200/80`:`bg-red-200/70`}`,G(`span`,n,Ti(e.text.slice(0,r),t),a,Ti(e.text.slice(i),t))}function ne(e){let t=0;for(;t<e.length;){if(e[t].tone!==`del`){t++;continue}let n=t;for(;t<e.length&&e[t].tone===`del`;)t++;let r=t;for(;t<e.length&&e[t].tone===`add`;)t++;let i=Math.min(r-n,t-r);for(let t=0;t<i;t++){let i=e[n+t],a=e[r+t],o=Math.min(i.text.length,a.text.length),s=0;for(;s<o&&i.text[s]===a.text[s];)s++;let c=0;for(;c<o-s&&i.text[i.text.length-1-c]===a.text[a.text.length-1-c];)c++;s+c!==0&&(i.mark=[s,i.text.length-c],a.mark=[s,a.text.length-c])}}}let re=pe();function ie(){b.classList.add(`hidden`),b.replaceChildren(),re.set([],[])}let ae=0,oe=e=>e===ae;function se(e){let t=++ae;return c.has(e)?F(e,t):ce(e,t)}async function ce(e,t){if(!oe(t))return;ie();let n=S(`file`,{path:e}),r=G(`div`,`min-w-0`);if(y.classList.remove(`flex`,`flex-col`),y.replaceChildren(M(e,!0),r),sl.test(e)){let e=G(`img`,`max-w-full p-4`);e.src=n,e.onerror=()=>r.replaceChildren(w(`Could not load image.`,`text-red-600`)),r.append(e);return}if(e.toLowerCase().endsWith(`.pdf`)){let t=document.createElement(`iframe`);t.className=`h-full w-full`,t.src=n,y.replaceChildren(M(e,!0),t),y.classList.add(`flex`,`flex-col`);return}r.append(w(`…`));let i=await fetch(n);if(!oe(t))return;if(!i.ok){let{error:e}=await i.json().catch(()=>({}));r.replaceChildren(w(e??`HTTP ${i.status}`,`text-red-600`));return}if(!(i.headers.get(`content-type`)??``).startsWith(`text/plain`)){r.replaceChildren(w(`Binary file — use Download.`));return}let a=(await i.text()).split(`
|
|
83
|
+
`);oe(t)&&(a.at(-1)===``&&a.pop(),r.replaceChildren(N(a.map((e,t)=>({nums:[t+1],text:e,tone:``})),wi(e))))}function le(e){let t=[],n=0,r=0,i=!1,a=e.split(`
|
|
84
|
+
`);a.at(-1)===``&&a.pop();for(let e of a){let a=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(e);if(a){i&&t.push({nums:[``,``],text:`⋯`,tone:``}),[n,r]=[Number(a[1]),Number(a[2])],i=!0;continue}!i||e.startsWith(`\\`)||(e.startsWith(`+`)?t.push({nums:[``,r++],text:e.slice(1),tone:`add`}):e.startsWith(`-`)?t.push({nums:[n++,``],text:e.slice(1),tone:`del`}):t.push({nums:[n++,r++],text:e.slice(1),tone:``}))}return t}function ue(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n].tone;if(!r)continue;let i=t.at(-1);i&&i.end===n-1?(i.end=n,(r===`add`&&i.tone===`del`||r===`del`&&i.tone===`add`)&&(i.tone=`mixed`)):t.push({start:n,end:n,tone:r})}return t}let de={add:`bg-emerald-400`,del:`bg-red-400`,mixed:`bg-amber-400`};function fe(e,t,n){b.replaceChildren(...e.map(e=>{let r=G(`button`,`pointer-events-auto absolute w-full cursor-pointer ${de[e.tone]}`);return r.style.top=`${e.start/t*100}%`,r.style.height=`${Math.max(.4,(e.end-e.start+1)/t*100)}%`,r.title=`line ${P(n,e.start)}`,r.onclick=()=>n[e.start].scrollIntoView({block:`center`}),r})),b.classList.remove(`hidden`)}let P=(e,t)=>e[t]?.querySelector(`span`)?.textContent?.trim()||String(t+1);function pe(){let t=[],n=[],r=-1,i=G(`span`,`flex-none text-[10.5px] text-neutral-400`),a=e=>{t.length&&(r=(r+e+t.length)%t.length,n[t[r].start].scrollIntoView({block:`center`}),i.textContent=`${r+1}/${t.length}`)},o=()=>t.length>0&&!e.classList.contains(`hidden`),s=(e,t,n,r)=>{let i=G(`button`,`icon-btn flex-none`,e);return i.onclick=()=>a(t),oo(i,r,n,()=>a(t),o),i};return{el:G(`div`,`flex flex-none items-center gap-1`,i,s(`↑`,-1,`Previous change`,[`p`,`k`]),s(`↓`,1,`Next change`,[`n`,`j`])),set(e,a){t=e,n=a,r=-1,i.textContent=`${e.length} change${e.length===1?``:`s`}`}}}async function F(e,t){ie(),y.classList.remove(`flex`,`flex-col`);let n=c.get(e)?.status!==`D`;y.replaceChildren(M(e,n),w(`…`));try{let{diff:r}=await C(S(`diff`,{base:o,head:s,file:e,context:`99999`}));if(!oe(t))return;if(!r||/^Binary files /m.test(r))return ce(e,t);let i=le(r);ne(i);let a=N(i,wi(e)),c=[...a.children],l=ue(i);re.set(l,c),y.replaceChildren(M(e,n,re.el),a),fe(l,i.length,c)}catch(n){oe(t)&&y.replaceChildren(M(e,!1),w(String(n),`text-red-600`))}}let me=()=>s&&o===`${s}~1`?s:``,I=()=>a.commits.find(e=>e.hash===me())?.subject??``,he=()=>me()?`${me()} — ${I()||`commit`}`:`${o} ↔ ${s||`working tree`}`,ge=(e,t,n,r)=>{let i=G(`button`,`flex h-6 w-6 flex-none cursor-pointer items-center justify-center rounded-md ${n?`bg-indigo-50 text-indigo-700`:`text-neutral-400 hover:bg-neutral-100 hover:text-neutral-700`}`);return i.innerHTML=e,i.title=t,i.onclick=r,i};function _e(){let e=ge(`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" class="h-3.5 w-3.5"><path d="M2.5 3h11l-4.25 5v4.5l-2.5 1.25V8L2.5 3z" stroke-linejoin="round"/></svg>`,`Show only files that differ`,l,()=>{l=!l,_e(),ee()}),t=ge(`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" class="h-3.5 w-3.5"><path d="m4.5 2.5 3.5 3 3.5-3M4.5 13.5l3.5-3 3.5 3" stroke-linecap="round" stroke-linejoin="round"/></svg>`,u?`Restore folders`:`Collapse all folders`,u,()=>{if(u=!u,u)d=[...f],f.clear();else for(let e of d)f.add(e);_e(),ee()});if(!a.branch){g.replaceChildren(G(`div`,`flex items-center justify-end gap-1 p-1.5`,t));return}let n=dl(he());if(me()){let e=a.commits.find(e=>e.hash===me());il(n,()=>e?tl(e):``)}else n.title=`Choose what to diff`;n.onclick=async()=>{await xe(),ol(n,a,{base:o,head:s},(e,t)=>{o=e,s=t,ye()},Se())};let[r,i]=[0,0];for(let e of c.values())r+=e.add,i+=e.del;g.replaceChildren(G(`div`,`flex flex-col gap-1 p-2`,n,G(`div`,`flex items-center gap-1.5 pl-1`,G(`span`,`text-[11px] text-neutral-400`,`${c.size} changed file${c.size===1?``:`s`}`),...j(r,i),G(`span`,`ml-auto`),e,t)))}async function ve(){if(c=new Map,!a.branch)return;let{files:e}=await C(S(`diff`,{base:o,head:s}));for(let t of e)c.set(t.path,{status:t.status,add:t.add,del:t.del});if(c.size<=ul)for(let e of c.keys()){let t=e.split(`/`);for(let e=1;e<t.length;e++)f.add(t.slice(0,e).join(`/`))}}async function ye(){try{await ve()}catch(e){_e(),_.replaceChildren(w(String(e),`text-red-600`));return}_e(),ee(),p&&se(p)}function be(){let e=dl(i||`Choose a folder…`,`neutral`);e.className+=` max-w-72`,e.title=`Switch folder`,e.onclick=()=>Xo(e,[...t().map(e=>({label:e,checked:e===i,onSelect:()=>{Y(),n(e)}})),{label:`Browse…`,onSelect:()=>ws(e,i||void 0,n)}]);let o=G(`button`,`icon-btn ml-auto`,`✕`);o.type=`button`,o.title=`Close Files`,o.setAttribute(`aria-label`,`Close Files`),o.onclick=r,h.replaceChildren(e,G(`span`,`truncate font-mono text-[11.5px] text-neutral-400`,a.branch?`⎇ ${a.branch}`:`no git`),o)}async function xe(){if(i)try{a=await C(S(`git`,{})),be()}catch(e){y.replaceChildren(w(String(e),`text-red-600`))}}let Se=()=>a.refs.some(e=>e.name===`main`)?`main`:a.refs.some(e=>e.name===`master`)?`master`:`HEAD`;async function Ce(){if(be(),p=null,m=null,f.clear(),ie(),y.classList.remove(`flex`,`flex-col`),y.replaceChildren(w(`Select a file.`)),!i){g.replaceChildren(),_.replaceChildren(),y.replaceChildren(w(`No folder yet — pick one from the chip above.`));return}try{a=await C(S(`git`,{}))}catch(e){a={branch:null,refs:[],commits:[]},y.replaceChildren(w(String(e),`text-red-600`))}o=Se(),s=``,be(),await ye()}return Zn(e,e=>{let n=e?.startsWith(`/`)?e:i||(t()[0]??``);if(n===i&&_.childElementCount){be(),xe().then(ye);return}i=n,Ce()})}var pl={display_information:{name:`Pier`,description:`Coding agent sessions in Slack threads`,background_color:`#262626`},features:{bot_user:{display_name:`Pier`,always_online:!1},app_home:{messages_tab_enabled:!0,messages_tab_read_only_enabled:!1}},oauth_config:{scopes:{bot:[`chat:write`,`reactions:write`,`channels:history`,`channels:read`,`groups:history`,`groups:read`,`im:history`,`im:write`,`mpim:history`,`mpim:read`,`mpim:write`,`users:read`,`files:read`]}},settings:{event_subscriptions:{bot_events:[`message.channels`,`message.groups`,`message.im`,`message.mpim`]},interactivity:{is_enabled:!0},socket_mode_enabled:!0,token_rotation_enabled:!1}},ml=()=>`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(pl))}`,hl=()=>us(`Getting a bot token`,[`Open [@BotFather](https://t.me/BotFather) in Telegram.`,"Send `/newbot`, pick a display name, then a username ending in `bot`.","Copy the token it prints (`123456789:AA…`) and paste it here.","Send `/setprivacy` → `Disable` if the bot should see plain group messages. Left enabled it only ever receives mentions, replies and commands — the usual reason a bot looks dead in a group.","Send `/setjoingroups` → `Enable`, then add the bot to your group or forum."]),gl=(e=`left`)=>us(`Enabling topics on a group`,["In Telegram open the group → `Edit` → turn on `Topics`. Owner only; group size no longer matters.","The group becomes a forum supergroup and the existing chat becomes its `General` topic.","Make the bot an admin with `Manage Topics`. That is the one right topic creation needs — without it Pier logs the failure and answers in General instead.","Send one message in the group so Pier discovers it, then enable it under `Chats` below.","After that, a message in General opens its own topic with its own session. A reply, or anything starting with `/`, stays where it was sent."],e);function _l(){let e=X(`Create Slack app ↗`,!0);e.classList.add(`mt-1`,`w-fit`),e.onclick=()=>window.open(ml(),`_blank`,`noreferrer`);let t=tr(`btn w-fit text-[12.5px]`,()=>JSON.stringify(pl,null,2));return us(`Creating a Slack app`,[ds(`Opens Slack with every scope, event and Socket Mode already filled in. Pick your workspace → Create.`,e),"`Install to Workspace` → allow. Then `OAuth & Permissions` → copy the bot token (`xoxb-…`) into the field above.","`Basic Information` → `App-Level Tokens` → `Generate` with scope `connections:write`. Paste that `xapp-…` token below. The manifest cannot mint this one for you.","In Slack, invite the bot where you want it: `/invite @Pier`. It answers in threads only, so it never adds noise to the channel.",ds(`Prefer to paste it yourself? Create the app from a manifest and use this:`,t)])}var vl=()=>us(`What agent access allows`,["Gives agent sessions a `slack` tool: read a channel's history for a time range, read one thread, and post a message.",`Pier performs every call itself — the bot token is never given to the agent, and Slack's own membership rules still apply, so the bot reaches only channels it was invited to.`,`Every read fetches live from Slack — Pier keeps no message archive.`,`This includes sessions started by tasks and subagents. Switch it off if an agent should never post to your workspace on its own.`]),yl=(e=`left`)=>us(`How Slack threads work here`,[`Pier never posts in a channel's main flow. A message in the channel is answered in *its own thread*; a message in a thread is answered in that thread.`,`Each thread is its own Pi session, so one channel hosts many parallel sessions.`,`The same applies in a DM: every new message you send there starts its own thread and its own session. Reply *inside* a thread to continue that conversation.`,"Inside a thread Pier already owns, no `@mention` is needed — continuing that thread is addressing it.","Commands are bare words after a mention: `@bot settings`, `@bot stop`, `@bot bind <code>`. Slack's client swallows an unregistered `/command` before it ever reaches an app."],e),bl=()=>us(`Creating a Feishu app`,["On [open.feishu.cn](https://open.feishu.cn/app) create a 企业自建应用 (custom app). `Credentials & Basic Info` shows the App ID (`cli_…`) and App Secret — paste both here.","`Add Features` → enable **Bot** (机器人).","`Permissions` (权限管理), add: `im:message` (read messages), `im:message:send_as_bot` (send), `im:resource` (download attachments), `im:message.reactions:create` + `:read` + `:delete` (the 👀 receipt), `im:chat:readonly` (chat names for this page), `contact:user.base:readonly` (speaker names).","`Events & Callbacks` → set the mode to **长连接 (long connection)** — no public URL needed. Under Events subscribe `im.message.receive_v1` (接收消息); Callbacks gain `card.action.trigger` automatically once cards are sent, add it if listed.",`**Publish a version** (版本管理与发布 → 创建版本 → 申请发布). Nothing above takes effect until this is approved — the usual reason a configured bot stays silent.`,`Add the bot to a group (群设置 → 群机器人), or DM it directly.`]),xl=(e=`left`)=>us(`How Lark topics work here`,[`Pier never posts in a chat's main flow. A message in the chat is answered in *its own topic* (话题); a message inside a topic is answered there.`,`Each topic is its own Pi session, so one group hosts many parallel sessions.`,`The same applies in a DM: every new message starts its own topic and its own session. Reply *inside* a topic to continue that conversation.`,`Inside a topic Pier already owns, no @mention is needed — continuing that topic is addressing it.`,"Commands are slash words: `/stop`, `/settings`, `/bind <code>`. A bare @mention with nothing else also opens the settings panel."],e),Sl=[[`telegram`,`Telegram`],[`slack`,`Slack`],[`lark`,`Lark`]],Cl=(e,t)=>G(`span`,`flex items-center gap-1.5 text-[13px] text-neutral-400`,G(`span`,``,e),t),wl={dm:`bg-sky-50 text-sky-700 ring-sky-200`,group:`bg-neutral-100 text-neutral-600 ring-neutral-200`,forum:`bg-violet-50 text-violet-700 ring-violet-200`},Tl=`pier.channelsPlatform`;function El(e){let t=localStorage.getItem(Tl),n=Sl.some(([e])=>e===t)?t:`telegram`,r=null,i=[],a=G(`div`,`ml-auto flex items-center gap-1.5 text-[11.5px]`),o=G(`div`,`sticky top-0 z-30 flex items-center gap-1 border-b border-neutral-200 bg-white px-4 py-2`,a),s=G(`div`,`px-4 py-5`);e.append(G(`div`,`min-h-0 flex-1 overflow-y-auto bg-neutral-50/60`,o,s));function c(){o.replaceChildren(...Sl.map(([e,t])=>es(t,e===n,()=>{u&&_(),n=e,localStorage.setItem(Tl,e),v()})),a)}let u,d=!1,f=null;function p(e){if(a.replaceChildren(),e!==`clean`){if(a.className=`ml-auto flex items-center gap-1.5 text-[11.5px] ${ss[e]}`,e===`saving`)a.append(G(`span`,`spinner`),G(`span`,``,`Saving…`));else if(e===`saved`)a.append(G(`span`,``,`✓`),G(`span`,``,`Saved`)),setTimeout(()=>{a.textContent?.includes(`Saved`)&&p(`clean`)},2e3);else{let e=Qo(`Retry`,`cursor-pointer underline`);e.onclick=_,a.append(G(`span`,``,`⚠`),G(`span`,``,`Save failed`),e)}}}function m(){p(`saving`),clearTimeout(u),u=setTimeout(_,500)}let h=e=>t=>{e(t),m()};async function g(e){d=!0,p(`saving`);try{p((await l(`/api/channels/${e.platform}`,e.config,`PUT`)).ok?`saved`:`failed`)}catch{p(`failed`)}finally{d=!1;let e=f;f=null,e&&g(e)}}function _(){if(clearTimeout(u),u=void 0,!r)return;let e={platform:n,config:r};d?f=e:g(e)}async function v(){if(!i.length){let e=await fetch(`/api/models`);e.ok&&(i=await e.json())}let e=await fetch(`/api/channels/${n}`);if(!e.ok){r=null,c(),s.replaceChildren(ls(`Failed to load: ${e.status}`));return}r=await e.json(),p(`clean`),w()}function y(e){let t=n===`slack`,r=n===`lark`,i=rs(e.token,t?`xoxb-…`:r?`cli_…`:`123456789:AA…`,h(t=>e.token=t),!0),a=rs(e.appToken,r?``:`xapp-…`,h(t=>e.appToken=t),!0),o=Es(e.cwd,`(pier process cwd)`,h(t=>e.cwd=t));return ts(`Connection`,t?`Pier connects over Socket Mode; no public URL or webhook needed.`:r?`Pier connects over Feishu's WebSocket long connection; no public URL or webhook needed.`:`Pier polls Telegram for updates; no public URL or webhook needed.`,os(`Enabled`,`Start the adapter when Pier boots.`,e.enabled,h(t=>{e.enabled=t,c()})),Z(r?`App ID`:`Bot token`,i,{hint:`Stored locally, shown masked once saved.`,help:n===`telegram`?hl():t?_l():bl()}),...t?[Z(`App-level token`,a,{hint:`Opens the Socket Mode connection. Needs connections:write.`}),os(`Agent access`,`Let agent sessions read channel history and post through the slack tool. Off makes the tool refuse; inbound messages are unaffected.`,e.agentTool,h(t=>e.agentTool=t),vl())]:[],...r?[Z(`App Secret`,a,{hint:`From Credentials & Basic Info, beside the App ID.`})]:[],Z(`Default working directory`,o.el,{hint:`Where sessions this channel opens start.`}))}function b(e){return ts(`Defaults for new chats`,`Copied into a group the first time the bot sees it; changing them here never touches a group that already exists. DMs are always bound-users-only.`,os(`Require mention in groups`,`Ignore group messages that do not @mention or reply to the bot.`,e.requireMention,h(t=>e.requireMention=t)),os(`Require bound user`,`Only users bound with a code below can drive the agent.`,e.requireBind,h(t=>e.requireBind=t)),...n===`slack`?[Cl(`Thread mode: always on`,yl())]:n===`lark`?[Cl(`Thread mode: always on`,xl())]:[os(`Topic mode`,`In a forum group, each new request opens its own topic and its own session.`,e.topicMode,h(t=>e.topicMode=t),gl())],bs(`Model & reasoning`,e,i,h(t=>{e.model=t.model,e.thinking=t.thinking,w()})))}function x(e){let t=G(`span`,`font-mono text-[15px] font-semibold tracking-widest`),r=G(`div`,`hidden items-center gap-2 rounded-lg bg-indigo-50 px-3 py-2 text-[12.5px] text-indigo-800`,t,G(`span`,`text-[11.5px] text-indigo-500`,`DM the bot /bind <code> · expires in 10 min`)),i=X(`Generate bind code`);i.onclick=async()=>{let e=await fetch(`/api/channels/${n}/bind-code`,{method:`POST`});if(!e.ok)return;let{code:i}=await e.json();t.textContent=i,r.classList.replace(`hidden`,`flex`)};let a=G(`div`,`flex flex-col`);e.users.length||a.append(ls(`No bound users yet.`));for(let t of e.users){let e=Qo(`Remove`,`cursor-pointer text-[11.5px] text-neutral-400 opacity-0 transition-opacity hover:text-red-600 group-hover:opacity-100`);e.onclick=async()=>{await fetch(`/api/channels/${n}/users/${encodeURIComponent(t.id)}`,{method:`DELETE`}),await v()},a.append(G(`div`,`group flex items-center gap-2.5 border-b border-neutral-100 py-2 last:border-0`,G(`span`,`flex h-6 w-6 flex-none items-center justify-center rounded-full bg-neutral-100 text-[11px] font-semibold text-neutral-500`,(t.name[0]??`?`).toUpperCase()),G(`span`,`min-w-0 flex-1 truncate text-[13px] text-neutral-700`,t.name),G(`span`,`flex-none font-mono text-[11.5px] text-neutral-400`,t.id),e))}return ts(`Bound users`,`A code is single-use and expires; redeeming it in a DM binds that account.`,a,G(`div`,`flex flex-col gap-2`,i,r))}function S(e,t){let r=G(`div`,`rounded-xl border px-3.5 py-3 transition-colors ${t.enabled?`border-neutral-200 bg-white`:`border-neutral-200 bg-neutral-50/60`}`),a=G(`div`,`flex items-center gap-2`,G(`span`,`min-w-0 flex-1 truncate text-[13px] font-medium ${t.enabled?`text-neutral-800`:`text-neutral-400`}`,t.name||t.id),cs(t.kind,wl[t.kind]),G(`span`,`flex-none font-mono text-[11px] text-neutral-400`,t.id)),o=os(``,``,t.enabled,h(e=>{t.enabled=e,w()}));o.classList.add(`flex-none`,`items-center`),a.append(o);let s=G(`div`,`mt-3 flex flex-wrap items-center gap-x-6 gap-y-2`);t.kind===`dm`?s.append(G(`span`,`text-[13px] text-neutral-400`,n===`telegram`?`Direct message · bound users only, mention and topics not applicable`:`Direct message · bound users only, mention not applicable`)):s.append(os(`Require mention`,``,t.requireMention,h(e=>t.requireMention=e)),os(`Require bind`,``,t.requireBind,h(e=>t.requireBind=e)),n===`slack`?Cl(`Thread mode: always on`,yl(`right`)):n===`lark`?Cl(`Thread mode: always on`,xl(`right`)):t.kind===`forum`?os(`Topic mode`,``,t.topicMode,h(e=>t.topicMode=e),gl(`right`)):Cl(`Topic mode: forum groups only`,gl(`right`)));let c=G(`div`,`mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2`,Z(`Working directory`,Es(t.cwd,``,h(e=>t.cwd=e)).el),bs(`Model & reasoning`,t,i,h(e=>{t.model=e.model,t.thinking=e.thinking,w()})));return r.append(a,s,c),r}function C(e){let t=G(`div`,`flex flex-col gap-2.5`);return e.chats.length?t.append(...e.chats.map(t=>S(e,t))):t.append(ls(`None yet. Chats appear here after the bot sees a message in them.`)),ts(n===`slack`?`Channels`:`Chats`,`Discovered from inbound traffic — no platform reliably lists every chat a bot is in.`,t)}function w(){if(!r)return;c();let e=G(`div`,`mx-auto flex max-w-3xl flex-col gap-4`);e.append(y(r),b(r),x(r),C(r)),s.replaceChildren(e)}return Zn(e,()=>void v(),()=>{u&&_()})}function Dl(e,t){let n=`global`,r=null,i=0,a=0,o=``,s=document.createElement(`select`);s.className=`select w-full rounded-md border border-neutral-300 px-2 py-1 text-[12.5px] focus:border-indigo-400 focus:outline-none`,s.onchange=()=>{n=s.value,r=null,x.clear(),g()};let c=G(`div`,`flex flex-none flex-col gap-1 border-b border-neutral-200 px-3 pb-2.5 pt-2`);c.append(G(`span`,`text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,`Scope`),s);let d=G(`div`,`min-h-0 flex-1 overflow-y-auto py-1`),f=G(`nav`,`flex w-64 flex-none flex-col border-r border-neutral-200 text-[13px]`);f.append(c,d);let p=G(`div`,`flex min-w-0 flex-1 flex-col`),m=G(`div`,`flex min-h-0 flex-1`);m.append(f,p),e.append(m);let h=(e=``)=>`?scope=${encodeURIComponent(n)}${e}`;async function g(){let e=++i;a++;let t=await fetch(`/api/config${h()}`,{cache:`no-store`});if(e!==i)return;if(!t.ok){C(null),T(`failed to load config: ${t.status}`);return}let s=await t.json();e===i&&(n===`global`&&s.dir&&(o=s.dir,k()),C(s),r||w())}function _(e){return G(`div`,`px-3 pb-0.5 pt-2.5 text-[10.5px] font-semibold uppercase tracking-wide text-neutral-400`,e)}let v=()=>{let e=G(`span`,`flex-none rounded bg-neutral-100 px-1 text-[10px] font-semibold uppercase tracking-wide text-neutral-500`,`link`);return e.title=`Reached through a symlink`,e};function y(e,t,n,r,i=0,a=!1){let o=G(`button`,`flex w-full cursor-pointer items-center gap-1.5 py-1 pr-3 text-left hover:bg-neutral-100 ${t?`bg-indigo-50 hover:bg-indigo-50`:``} ${n?`text-neutral-400`:``}`);return o.append(G(`span`,`truncate`,e)),a&&o.append(v()),o.style.paddingLeft=`${20+i*14}px`,o.title=e,o.onclick=r,o}function b(e){let t={files:[],dirs:new Map,link:!0};for(let n of e){let e=n.name.split(`/`),r=t;for(let t of e.slice(0,-1)){let e=r.dirs.get(t);e||r.dirs.set(t,e={files:[],dirs:new Map,link:!0}),e.link&&=n.link,r=e}r.files.push({name:e[e.length-1],link:n.link})}return t}let x=new Set;function S(e,t,n,r,i,a){let o=[];for(let[s,c]of t.dirs){let t=n?`${n}/${s}`:s,l=`${e}:${t}`,u=document.createElement(`details`);u.open=x.has(l),u.ontoggle=()=>u.open?x.add(l):x.delete(l);let d=G(`summary`,`flex cursor-pointer select-none items-center gap-1 truncate py-1 pr-3 hover:bg-neutral-100`);d.style.paddingLeft=`${20+r*14}px`,d.title=t,d.append(G(`span`,`chev`,`▶`),G(`span`,`truncate text-neutral-600`,s)),c.link&&d.append(v()),u.append(d,...S(e,c,t,r+1,i,a)),o.push(u)}for(let s of t.files){let t={type:`resource`,kind:e,name:n?`${n}/${s.name}`:s.name};o.push(y(s.name,i(t),!1,()=>a(t),r,s.link))}return o}function C(e){if(!e){d.replaceChildren();return}let t=e=>JSON.stringify(e)===JSON.stringify(r),n=t=>{r=t,C(e),t.type===`file`?D(t.name):O(t.kind,t.name)},i=[];i.push(_(`Files`));for(let r of e.files){let e={type:`file`,name:r.name};i.push(y(r.name,t(e),!r.exists,()=>n(e)))}for(let r of[`extensions`,`skills`]){i.push(_(`${r} (read-only)`));let a=e.resources[r];a.length||i.push(G(`p`,`py-1 pl-5 pr-3 text-[12.5px] text-neutral-400`,`none`)),i.push(...S(r,b(a),``,0,t,n))}d.replaceChildren(...i)}function w(){p.replaceChildren(G(`p`,`px-4 py-3 text-[13px] text-neutral-400`,`Select a file to edit, or browse extensions and skills.`))}function T(e){p.replaceChildren(G(`p`,`px-4 py-3 text-[13px] text-red-600`,e))}let E=(e,...t)=>G(`div`,`flex flex-none items-center gap-3 border-b border-neutral-200 px-4 py-2`,G(`span`,`font-mono text-[12.5px] text-neutral-500`,e),...t);async function D(e){let t=++a,n=await fetch(`/api/config/files/${encodeURIComponent(e)}${h()}`,{cache:`no-store`});if(!n.ok){t===a&&T(`failed to load ${e}: ${n.status}`);return}let{content:r}=await n.json();if(t!==a)return;let i=r,o=G(`span`,`text-[11.5px] text-neutral-400`,``),s=G(`button`,`btn btn-primary ml-auto text-[12.5px]`,`Save`),c=document.createElement(`textarea`);c.className=`block min-h-0 flex-1 resize-none bg-white p-4 font-mono text-[13px] leading-relaxed focus:outline-none`,c.spellcheck=!1,c.value=r;let d=async()=>{if(s.disabled)return;let t=c.value;s.disabled=!0,$(o,`saving`,`saving…`);try{let n=await l(`/api/config/files/${encodeURIComponent(e)}${h()}`,{content:t,expected:i},`PUT`);if(!n.ok)return $(o,`failed`,await u(n,`save failed`));let r=await n.json();i=r.content,c.value===t?(c.value=r.content,$(o,`saved`,`saved — applies to new sessions`)):$(o,`idle`,`saved; newer changes are unsaved`)}catch(e){$(o,`failed`,`save failed: ${String(e)}`)}finally{s.disabled=!1}};s.onclick=()=>void d(),c.onkeydown=e=>{(e.metaKey||e.ctrlKey)&&e.key===`s`&&(e.preventDefault(),d())},c.oninput=()=>{$(o,`idle`,`unsaved changes`)},p.replaceChildren(E(e,o,s),c),c.focus()}async function O(e,t){let n=++a,r=await fetch(`/api/config/resource${h(`&kind=${e}&name=${encodeURIComponent(t)}`)}`,{cache:`no-store`});if(!r.ok){n===a&&T(`failed to load ${t}: ${r.status}`);return}let{content:i}=await r.json();n===a&&p.replaceChildren(E(t,G(`span`,`ml-auto text-[11px] uppercase tracking-wide text-neutral-400`,`read-only`)),G(`pre`,`min-h-0 flex-1 overflow-auto whitespace-pre-wrap p-4 font-mono text-[12.5px]`,i))}function k(){s.replaceChildren(new Option(o?`Global (${o})`:`Global`,`global`),...t().map(e=>new Option(`${Yn(e)} — ${e}`,e))),[...s.options].some(e=>e.value===n)||(n=`global`),s.value=n}return Zn(e,()=>{k(),g()})}var Ol=e=>`${e.provider}/${e.id}`,kl=[`hardest reasoning — architecture, gnarly debugging`,`long autonomous implementation runs`,`balanced default — implementation, review`,`cheap & fast — listings, extraction, simple checks`,`cross-vendor second opinion`];function Al(){let e=[],t=[],n=!1,r=G(`span`,`text-[11.5px]`,``),i=X(`Save menu`,!0),a=G(`div`,`flex min-w-0 flex-col gap-2`),o=G(`div`,`flex items-center gap-2`),s=G(`div`,`mx-auto flex w-full max-w-3xl min-w-0 flex-col gap-6`);function c(){n=!0,$(r,`idle`,`unsaved changes`)}function d(t){let n=Q(t.note??``);n.classList.remove(`w-full`),n.classList.add(`min-w-0`,`flex-1`),n.placeholder=`why this one — pick a preset or write your own`,n.setAttribute(`list`,`model-menu-notes`),n.oninput=()=>{t.note=n.value,c()};let r=is([[`thinking: model default`,``],...ji.map(e=>[`thinking: ${Rn(e)}`,e])],t.thinking??``);r.classList.replace(`w-full`,`w-44`),r.classList.add(`flex-none`),r.onchange=()=>{r.value?t.thinking=r.value:delete t.thinking,c()};let i=X(`Remove`);i.classList.add(`flex-none`),i.onclick=()=>{e=e.filter(e=>e!==t),c(),p()};let a=G(`span`,`w-52 flex-none truncate font-mono text-[12px] text-neutral-700`,Ol(t));return a.title=Ol(t),G(`div`,`flex min-w-0 items-center gap-2 rounded-lg border border-neutral-200 bg-white px-3 py-2 shadow-2xs max-md:flex-wrap`,a,r,n,i)}function f(){let n=t.filter(t=>!e.some(e=>Ol(e)===Ol(t))),r=is(n.map(e=>[Ol(e),Ol(e)]),n[0]?Ol(n[0]):``);r.classList.replace(`w-full`,`flex-1`),r.classList.add(`min-w-0`);let i=X(`+ Pin model`);i.classList.add(`flex-none`,`whitespace-nowrap`),i.disabled=n.length===0,i.onclick=()=>{let t=n.find(e=>Ol(e)===r.value);t&&(e.push({...t}),c(),p())},o.replaceChildren(r,i)}function p(){a.replaceChildren(...e.length?e.map(d):[ls(`Nothing pinned — every picker shows the curated catalog as is.`)]),f()}async function m(){$(r,`saving`,`saving…`);let t=await l(`/api/settings`,{modelMenu:e.map(({provider:e,id:t,thinking:n,note:r})=>({provider:e,id:t,...n?{thinking:n}:{},...r?.trim()?{note:r.trim()}:{}}))},`PUT`);if(!t.ok)return $(r,`failed`,await u(t,`Could not save`));e=(await t.json()).modelMenu,n=!1,$(r,`saved`,`Saved — agents see it on their next models call.`),p()}i.onclick=()=>void m();function h(){n||(async()=>{let[n,i]=await Promise.all([fetch(`/api/settings`),fetch(`/api/models`)]);if(!n.ok)return $(r,`failed`,await u(n,`Could not load the menu`));e=(await n.json()).modelMenu,t=i.ok?await i.json():[],r.textContent=``,p()})()}let g=G(`datalist`,``);return g.id=`model-menu-notes`,g.append(...kl.map(e=>new Option(e))),s.append(ts(`Model menu`,`Which few models this deployment favors, each with a usual reasoning level and one line of intent. Pinned entries lead every model picker, and agents delegating work match your notes against the task instead of guessing ids.`,Z(`Pinned models`,a,{hint:`The note is what an agent matches a task against — say when to reach for it, not what it is.`}),Z(`Add`,o,{hint:`The list is the live catalog — only models that exist right now can be pinned.`}),G(`div`,`flex items-center gap-3`,i,r),g)),{el:s,load:h}}var jl=(e,t)=>{let n;try{n=new URL(e)}catch{return null}if(n.protocol!==`http:`&&n.protocol!==`https:`)return null;let r=G(`a`,`text-indigo-600 hover:underline`,t);return r.href=n.href,r.target=`_blank`,r.rel=`noreferrer`,r};function Ml(e,t,n,r){let i=document.createElement(`dialog`);i.className=`m-auto w-[min(32rem,92vw)] rounded-lg border border-neutral-200 bg-white p-0 shadow-xl backdrop:bg-black/30`;let a=G(`div`,`flex flex-col gap-2`),o=G(`div`,`flex flex-col gap-2`),s=G(`p`,`text-[12.5px] text-neutral-400`,`Starting…`),c=X(`Cancel`),d=(e,t)=>{s.className=`text-[12.5px] ${ss[e]}`,s.textContent=t};i.append(G(`div`,`border-b border-neutral-200 px-4 py-2.5 text-[14px] font-semibold`,t),G(`div`,`flex max-h-[65vh] flex-col gap-3 overflow-y-auto px-4 py-3`,a,o,s),G(`div`,`flex justify-end border-t border-neutral-200 px-4 py-2.5`,c)),document.body.append(i),i.showModal();let f=e.id,p=e.state,m,h,g=new Set,_=!1,v=!1,y=async e=>{if(!v){if(e&&p===`running`){v=!0,c.disabled=!0;try{let e=await l(`/api/providers/flows/${f}/cancel`,{});if(!e.ok&&e.status!==404){d(`failed`,await u(e,`Could not cancel authentication flow`));return}}catch(e){d(`failed`,`Could not cancel authentication flow: ${String(e)}`);return}finally{v=!1,c.disabled=!1}}clearTimeout(m),i.close()}};c.onclick=()=>void y(!0),i.oncancel=e=>{e.preventDefault(),y(!0)},i.onclose=()=>{_=!0,clearTimeout(m),i.remove()};let b=e=>{if(e.type===`auth_url`){let t=G(`div`,`flex flex-col gap-1 text-[12.5px] text-neutral-600`);return e.instructions&&t.append(G(`p`,``,e.instructions)),t.append(jl(e.url,`Open authorization page`)??G(`span`,`text-red-600`,`Invalid authorization URL`)),t}if(e.type===`device_code`){let t=G(`div`,`flex flex-col gap-2 text-[12.5px] text-neutral-600`);return t.append(G(`div`,`flex items-center gap-2`,G(`code`,`font-mono text-[17px] font-semibold text-neutral-800`,e.userCode),tr(`btn text-[11px]`,()=>e.userCode))),t.append(jl(e.verificationUri,`Open verification page`)??G(`span`,`text-red-600`,`Invalid verification URL`)),t}let t=G(`div`,`text-[12.5px] text-neutral-600`,e.message);if(e.type===`info`)for(let n of e.links??[]){let e=jl(n.url,n.label??n.url);e&&t.append(` `,e)}return t},x=(e,t)=>{h=t.id;let n;if(t.type===`select`){let e=document.createElement(`select`);e.append(...t.options.map(e=>new Option(e.description?`${e.label} — ${e.description}`:e.label,e.id))),n=e}else{let e=Q(``,t.type===`secret`?`password`:`text`);e.placeholder=t.placeholder??``,e.autocomplete=`off`,n=e}n.className=`${n.tagName===`SELECT`?`select `:``}w-full rounded-lg border border-neutral-300 bg-white px-2.5 py-1.5 text-[12.5px] focus:border-indigo-400 focus:outline-none`;let r=X(`Continue`,!0);r.type=`submit`;let i=G(`form`,`flex flex-col gap-2`,G(`label`,`text-[12.5px] font-medium text-neutral-700`,t.message),n,G(`div`,`flex justify-end`,r));i.onsubmit=i=>{i.preventDefault(),r.disabled=!0,(async()=>{try{let r=await l(`/api/providers/flows/${e.id}/respond`,{promptId:t.id,value:n.value});if(_)return;if(!r.ok){d(`failed`,await u(r,`Could not submit response`));return}g.add(t.id),h=void 0,o.replaceChildren(),d(`saving`,`Waiting for provider…`)}catch(e){_||d(`failed`,`Could not submit response: ${String(e)}`)}finally{r.disabled=!1}})()},o.replaceChildren(i),n.focus()},S=e=>{p=e.state,a.replaceChildren(...e.events.map(b));let t=e.prompt&&!g.has(e.prompt.id)?e.prompt:void 0;if(t?.id!==h&&(t?x(e,t):(h=void 0,o.replaceChildren())),e.state===`running`){d(`saving`,t?`Waiting for your response.`:`Waiting for provider…`);return}clearTimeout(m),o.replaceChildren(),e.state===`succeeded`?d(`saved`,`${n} configured.`):d(`failed`,e.state===`cancelled`?`Cancelled.`:e.error??`Authentication failed.`),c.textContent=`Close`,c.onclick=()=>void y(!1),e.state===`succeeded`&&r()},C=async()=>{if(!(_||p!==`running`))try{let e=await fetch(`/api/providers/flows/${f}`,{cache:`no-store`});if(_)return;if(!e.ok){d(`failed`,await u(e,`Authentication status unavailable`)),e.status===404?p=`failed`:m=setTimeout(()=>void C(),1e3);return}S(await e.json()),p===`running`&&(m=setTimeout(()=>void C(),500))}catch(e){if(_)return;d(`failed`,`Authentication status unavailable: ${String(e)}`),m=setTimeout(()=>void C(),1e3)}};S(e),p===`running`&&(m=setTimeout(()=>void C(),500))}var Nl=[`anthropic`,`openai`,`openai-codex`,`google`,`openrouter`,`deepseek`],Pl=[[`OpenAI Chat Completions`,`openai-completions`],[`OpenAI Responses`,`openai-responses`],[`Anthropic Messages`,`anthropic-messages`],[`Google Generative AI`,`google-generative-ai`]],Fl=`__custom__`;async function Il(e){let t=X(`Add provider`,!0);t.classList.add(`ml-auto`);let n=G(`div`,`flex flex-none items-center gap-3 border-b border-neutral-200 px-4 py-2`,G(`span`,`font-mono text-[12.5px] text-neutral-500`,`Providers`),t),r=G(`div`,`min-h-0 flex-1 overflow-y-auto`);e.replaceChildren(n,r);let i=async()=>{r.replaceChildren(G(`p`,`px-4 py-3 text-[13px] text-neutral-400`,`Loading…`));try{let e=await fetch(`/api/providers`,{cache:`no-store`});if(!e.ok){r.replaceChildren(ls(await u(e,`Could not load providers`)));return}let n=await e.json();t.onclick=()=>Rl(n,void 0,i),o(n)}catch(e){r.replaceChildren(ls(`Could not load providers: ${String(e)}`))}},a=async e=>{if(window.confirm(`Remove the stored credential for ${e.name}?`))try{let t=await l(`/api/providers/${encodeURIComponent(e.id)}/logout`,{});if(!t.ok){window.alert(await u(t,`Could not remove credential`));return}await i()}catch(e){window.alert(`Could not remove credential: ${String(e)}`)}},o=e=>{let t=e.filter(e=>e.configured);if(!t.length){r.replaceChildren(ls(`No providers configured.`));return}r.replaceChildren(...t.map(t=>{let n=G(`div`,`min-w-0 flex-1`,G(`div`,`truncate text-[13px] font-medium text-neutral-700`,t.name),G(`div`,`truncate font-mono text-[11px] text-neutral-400`,t.id)),r=t.stored===`api_key`?`API key`:t.stored===`oauth`?`OAuth`:t.source??`configured`,o=t.endpoint??`Default endpoint`,s=G(`div`,`flex min-w-32 flex-col items-start gap-1`,cs(`configured`,`bg-emerald-50 text-emerald-700 ring-emerald-200`),G(`span`,`max-w-48 truncate text-[11px] text-neutral-500`,r),G(`span`,`max-w-48 truncate text-[11px] text-neutral-400`,o));s.title=o;let c=G(`div`,`flex flex-wrap justify-end gap-1.5`);if(t.builtin||t.api&&t.models){let n=X(`Edit`);n.onclick=()=>Rl(e,t,i),c.append(n)}if(t.stored){let e=X(`Remove credential`);e.onclick=()=>void a(t),c.append(e)}return G(`div`,`grid grid-cols-[minmax(8rem,1fr)_minmax(8rem,auto)_minmax(9rem,auto)] items-center gap-3 border-b border-neutral-100 px-4 py-2.5 max-sm:grid-cols-[1fr_auto]`,n,s,c)}))};await i()}function Ll(e,t){let n=t.filter(e=>!e.configured&&e.methods.length&&(e.builtin||e.api!==void 0&&e.models!==void 0)),r=(t,n)=>{if(!n.length)return;let r=document.createElement(`optgroup`);r.label=t,r.append(...n.map(e=>new Option(e.name,e.id))),e.append(r)};r(`Common`,Nl.flatMap(e=>n.filter(t=>t.id===e))),r(`More providers`,n.filter(e=>e.builtin&&!Nl.includes(e.id)).sort((e,t)=>e.name.localeCompare(t.name))),r(`Custom providers`,n.filter(e=>!e.builtin).sort((e,t)=>e.name.localeCompare(t.name))),e.append(new Option(`Custom provider…`,Fl))}function Rl(e,t,n){let r=document.createElement(`dialog`);r.className=`m-auto w-[min(32rem,92vw)] rounded-lg border border-neutral-200 bg-white p-0 shadow-xl backdrop:bg-black/30`;let i=document.createElement(`select`);i.className=`${ns} select`,t||Ll(i,e);let a=Q(),o=Q(),s=Q(),c=document.createElement(`select`);c.className=`${ns} select`,c.append(...Pl.map(([e,t])=>new Option(e,t)));let d=as(``,4);d.placeholder=`model-id
|
|
85
|
+
another-model-id`;let f=document.createElement(`input`);f.type=`checkbox`;let p=document.createElement(`select`);p.className=`${ns} select`;let m=G(`div`,`flex flex-col gap-4`),h=G(`span`,`text-[11.5px] text-red-600`,``),g=X(`Cancel`),_=X(t?`Save`:`Add`,!0);_.type=`submit`;let v=()=>t??e.find(e=>e.id===i.value),y=()=>{let e=v(),n=e?!e.builtin:i.value===Fl;a.value=e?.id??``,a.disabled=t!==void 0,o.value=e?.name??``,s.value=e?.endpoint??``,c.value=e?.api??`openai-completions`,d.value=e?.models?.map(e=>e.id).join(`
|
|
86
|
+
`)??``;let r=e?.models?.map(e=>e.reasoning)??[];f.checked=r.length?r.every(Boolean):!e,f.indeterminate=r.some(Boolean)&&!r.every(Boolean);let l=[];e?.configured&&l.push(new Option(`Keep current authentication`,``));let u=e?.methods??[{type:`api_key`,name:`API key`}];for(let t of u.filter(t=>e?.builtin!==!1||t.type===`api_key`))l.push(new Option(t.name,t.type));p.replaceChildren(...l);let h=[];t||h.push(Z(`Provider`,i)),n?h.push(Z(`Provider ID`,a),Z(`Display name`,o),Z(`Endpoint`,s),Z(`API format`,c),Z(`Models`,d),Z(`Model capabilities`,G(`label`,`flex items-center gap-2 text-[12.5px] text-neutral-600`,f,G(`span`,``,`Reasoning`)))):(s.placeholder=`Provider default`,h.push(Z(`Endpoint`,s))),h.push(Z(`Authentication`,p)),m.replaceChildren(...h)};i.onchange=y,y();let b=G(`form`,`flex flex-col gap-4 px-4 py-3`,m,G(`div`,`flex items-center justify-end gap-2`,h,g,_)),x=!1;g.onclick=()=>{x||r.close()},r.oncancel=e=>{x&&e.preventDefault()},b.onsubmit=e=>{if(e.preventDefault(),x)return;h.textContent=``;let t=v(),m=(t?!t.builtin:i.value===Fl)?{kind:`custom`,id:a.value.trim(),...o.value.trim()?{name:o.value.trim()}:{},endpoint:s.value.trim(),api:c.value,models:[...new Set(d.value.split(`
|
|
87
|
+
`).map(e=>e.trim()).filter(Boolean))].map(e=>({id:e,reasoning:f.indeterminate?t?.models?.find(t=>t.id===e)?.reasoning??f.checked:f.checked}))}:{kind:`builtin`,id:t.id,...s.value.trim()?{endpoint:s.value.trim()}:{}},y=p.value||null;x=!0,_.disabled=!0,g.disabled=!0,(async()=>{try{let e=await l(`/api/providers/setup`,{setup:m,authType:y});if(!e.ok){h.textContent=await u(e,`Could not configure provider`);return}if(r.close(),e.status===202){let t=p.selectedOptions[0]?.textContent??`Authentication`;Ml(await e.json(),m.id,t,()=>void n())}else await n()}catch(e){h.textContent=`Could not configure provider: ${String(e)}`}finally{x=!1,_.disabled=!1,g.disabled=!1}})()},r.append(G(`div`,`border-b border-neutral-200 px-4 py-2.5 text-[14px] font-semibold`,t?`Edit ${t.name}`:`Add provider`),b),r.onclose=()=>r.remove(),document.body.append(r),r.showModal(),(t?s:i).focus()}var zl=[[`providers`,`Providers`],[`models`,`Models`],[`files`,`Agent files`],[`channels`,`Channels`],[`instance`,`Instance`],[`security`,`Security`]],Bl=e=>zl.some(([t])=>t===e),Vl=`pier.settingsTopic`;function Hl(e,t,n){let r=localStorage.getItem(Vl)??void 0,i=Bl(r)?r:`providers`,a=G(`header`,`flex h-10 flex-none items-center gap-3 border-b border-neutral-200 bg-white px-4 max-md:hidden`,G(`span`,`font-medium`,`Settings`)),o=G(`div`,`tabstrip bg-white`);function s(){o.replaceChildren(...zl.map(([e,t])=>es(t,e===i,()=>n(e))))}let c=Q();c.placeholder=`https://pier.example.com`,c.autocomplete=`off`;let d=G(`span`,`text-[11.5px]`,``),f=X(`Save`,!0);async function p(){$(d,`saving`,`saving…`);let e=await l(`/api/settings`,{publicUrl:c.value},`PUT`);if(!e.ok)return $(d,`failed`,await u(e,`Could not save`));let{publicUrl:t}=await e.json();c.value=t,$(d,`saved`,t?`Saved — boards link as ${t}/p/<slug>/`:`Cleared.`)}f.onclick=()=>void p(),c.onkeydown=e=>{e.key===`Enter`&&p()};let m=ts(`Public URL`,`Where this Pier is reached from outside — the proxy's address, not the port it listens on.`,Z(`Base URL`,c,{hint:`Agents read it to hand you a clickable board link instead of a path. Nothing here changes what Pier serves; leave it empty if Pier is only reachable locally.`}),G(`div`,`flex items-center gap-3`,f,d)),h=Q(``,`password`),g=Q(``,`password`),_=Q(``,`password`);for(let e of[h,g,_])e.autocomplete=`off`;let v=G(`span`,`text-[11.5px]`,``),y=X(`Change password`,!0);async function b(){if(g.value!==_.value)return $(v,`failed`,`The two new passwords differ.`);$(v,`saving`,`changing…`);let e=await l(`/api/password`,{current:h.value,next:g.value});if(!e.ok)return $(v,`failed`,await u(e,`Could not change the password`));for(let e of[h,g,_])e.value=``;$(v,`saved`,`Changed. Sign in again with the new password.`),location.href=`/login`}y.onclick=()=>void b(),_.onkeydown=e=>{e.key===`Enter`&&b()};let x=ts(`Password`,`One shared password guards every page and API route. Changing it signs out every signed-in browser, this one included.`,Z(`Current password`,h),Z(`New password`,g,{hint:`At least 10 characters.`}),Z(`Repeat new password`,_),G(`div`,`flex items-center gap-3`,y,v)),S=X(`Reload`,!0),C=G(`span`,`text-[11.5px]`,``);S.onclick=()=>{S.disabled=!0,$(C,`saving`,`reloading…`),(async()=>{let e=await l(`/api/reload`,{});if(S.disabled=!1,!e.ok)return $(C,`failed`,await u(e,`Could not reload`));let{recycled:t,busy:n}=await e.json(),r=t?`Recycled ${t} session(s).`:`No idle session needed it.`,i=n?` ${n} still mid-turn — they take it when the turn ends.`:``;$(C,n?`idle`:`saved`,r+i)})()};let w=ts(`Reload configuration`,`Re-reads channel configuration and lets go of idle sessions, so the next message opens them with the current agent files, skills and credentials. Saving here does this on its own — use it after something outside the Console changed a file.`,G(`div`,`flex items-center gap-3`,S,C)),T=X(`Sign out`);T.onclick=()=>{l(`/logout`,{}).finally(()=>{location.href=`/login`})};let E=G(`div`,`mx-auto flex max-w-2xl flex-col gap-6`,m,w,x,ts(`Sign out`,`Ends this browser's session. Others keep theirs — change the password to sign out everywhere.`,G(`div`,`flex items-center gap-3`,T))),D=e=>G(`div`,`hidden min-h-0 flex-1 overflow-y-auto bg-neutral-50/60`,G(`div`,`px-4 py-5`,e)),O=Al(),k=G(`div`,`mx-auto flex max-w-2xl flex-col gap-6`),A=G(`section`,`hidden min-h-0 flex-1 flex-col`),ee=El(A),j=G(`section`,`hidden min-h-0 flex-1 flex-col`),M=Dl(j,t);function N(){v.textContent=``,(async()=>{let e=await fetch(`/api/settings`);if(!e.ok)return $(d,`failed`,await u(e,`Could not load settings`));c.value=(await e.json()).publicUrl,d.textContent=``})()}let te=G(`div`,`mx-auto flex max-w-2xl flex-col gap-6`);async function ne(){let e=await fetch(`/api/secrets`);if(!e.ok){te.replaceChildren(ls(await u(e,`Could not load key status`)));return}re(await e.json())}function re(e,t){let n=e.state===`locked`,r=G(`span`,`text-[11.5px]`,``);t&&$(r,`saved`,t);let i=G(`div`,`flex items-center gap-2`,cs(e.state,n?`bg-red-50 text-red-700 ring-red-200`:`bg-emerald-50 text-emerald-700 ring-emerald-200`),G(`span`,`text-[12.5px] text-neutral-600`,n?`Stored credentials cannot be read until the key is unlocked.`:e.mode===`vt`?`Key mode: vt:// — unlocking takes one vt approval per process start.`:`Key mode: file — the key sits raw in master.key; switch to vt:// to require an approval.`)),a=G(`a`,`text-indigo-600 hover:underline`,`vt`);a.href=`https://github.com/timqi/vt`,a.target=`_blank`,a.rel=`noreferrer`;let o=[i,G(`p`,`text-[12px] leading-snug text-neutral-500`,a,` is a small local KMS: it keeps the key wrapped and releases it only on an explicit approval — Touch ID on a Mac, a phone passkey on a headless host. Pier only stores the vt:// record, so master.key alone unlocks nothing.`)];if(n){o.push(G(`p`,`text-[12.5px] leading-snug text-red-600`,e.reason??`No reason reported.`));let t=X(`Unlock`,!0);t.onclick=()=>{$(r,`saving`,`unlocking… (vt mode waits on your approval)`),(async()=>{let e=await l(`/api/secrets/unlock`,{});if(!e.ok)return $(r,`failed`,await u(e,`Could not unlock`));re(await e.json(),`Unlocked — channels are starting.`)})()},o.push(G(`div`,`flex items-center gap-3`,t,r))}else{let t=async(e,t,n)=>{if(!window.confirm(t))return;$(r,`saving`,e===`vt`?`rotating… (vt asks for an approval)`:`rotating…`);let i=await l(`/api/secrets/rotate`,{mode:e});if(!i.ok)return $(r,`failed`,await u(i,`Could not rotate`));re(await i.json(),n)},n=e.mode??`file`,i=X(`Rotate key`,!0);i.onclick=()=>void t(n,`Generate a new master key? Stored credentials stay valid; the old key stops working.`,`Rotated.`);let a=n===`vt`?`file`:`vt`,s=X(a===`vt`?`Switch to vt://`:`Switch to file`);s.onclick=()=>void t(a,a===`vt`?`Move the master key into vt? Every process start will then wait on a vt approval.`:`Store the master key raw in master.key? Anyone who can read the file can read every credential.`,a===`vt`?`Switched to vt:// mode.`:`Switched to file mode.`),o.push(G(`div`,`flex items-center gap-3`,i,s,r))}te.replaceChildren(ts(`Master key`,`Seals every credential Pier stores (channel tokens, API keys). Rotating rewraps the key file; no stored data is rewritten.`,...o))}let ie=D(E),ae=D(k),oe=D(O.el),se=D(te),ce=[[`instance`,ie,N],[`providers`,ae,()=>void Il(k)],[`models`,oe,()=>O.load()],[`security`,se,()=>void ne()]];e.append(a,o,ie,ae,oe,A,j,se);function le(e){Bl(e)&&(i=e),localStorage.setItem(Vl,i),s();for(let[e,t,n]of ce){let r=e===i;t.classList.toggle(`hidden`,!r),r&&n()}i===`channels`?ee.show():ee.hide(),i===`files`?M.show():M.hide()}return Zn(e,le)}function Ul(e,t){let n=e.map(e=>[`${e.title??`Untitled`} · ${e.cwd}`,e.id]);return t&&!n.some(([,e])=>e===t)&&n.push([`Current session · ${t}`,t]),n}function Wl(e,t){let n=document.createElement(`dialog`);n.className=`m-auto w-[38.75rem] max-w-[94vw] rounded-lg border border-neutral-200 p-0 shadow-xl backdrop:bg-black/20`;let r=document.createElement(`form`);r.className=`flex max-h-[88vh] flex-col`;let i=G(`span`,`mr-auto text-[12px] text-red-600`),a=G(`header`,`flex h-11 flex-none items-center border-b border-neutral-200 px-4 font-medium`,t?`Edit task`:`New task`),o=G(`div`,`grid min-h-0 flex-1 grid-cols-2 gap-3 overflow-y-auto p-4`),s=Q(t?.name??``);s.required=!0;let c=Q(t?.description??``),l=Q(String(t?.timeoutSeconds??900),`number`);l.min=`1`,l.max=`86400`;let u=is([[`Manual`,`manual`],[`Scheduled`,`cron`],[`Watch`,`watch`]],t?.trigger.type??`manual`),d=is([[`Bash`,`bash`],[`Agent`,`agent`],[`Task`,`task`]],t?.action.type??`bash`),f=is([[`No callback`,`none`],[`Invoking session`,`origin`],[`Specific session`,`session`]],t?.callback.type??`none`),p=t?.callback.type===`session`?t.callback.sessionId:null,m=is(Ul(e.sessions(),p),p??``),h=Z(`Callback session`,m);h.classList.toggle(`hidden`,f.value!==`session`),f.onchange=()=>h.classList.toggle(`hidden`,f.value!==`session`),o.append(Z(`Name`,s),Z(`Description`,c),Z(`Trigger`,u),Z(`Action`,d),Z(`Callback`,f),h,Z(`Timeout (seconds)`,l));let g=G(`div`,`col-span-2 grid grid-cols-2 gap-3 border-t border-neutral-200 pt-3`);o.append(g);let _=()=>{g.replaceChildren();let a,o,p,h,_,v;if(u.value===`cron`)a=Q(t?.trigger.type===`cron`?t.trigger.expression:`0 9 * * *`),o=Q(t?.trigger.type===`cron`?t.trigger.timezone:Intl.DateTimeFormat().resolvedOptions().timeZone),g.append(Z(`Cron`,a),Z(`Timezone`,o));else if(u.value===`watch`){p=as(t?.trigger.type===`watch`?t.trigger.script:``,4),v=Q(t?.trigger.type===`watch`?t.trigger.cwd:e.sessions()[0]?.cwd??``),h=Q(String(t?.trigger.type===`watch`?t.trigger.intervalSeconds:60),`number`),_=is([[`Continue after matches`,`repeat`],[`Stop after first match`,`once`]],t?.trigger.type===`watch`?t.trigger.mode:`repeat`);let n=Z(`Probe script (0=match, 1=no match)`,p);n.classList.add(`col-span-2`),g.append(n,Z(`Probe directory`,v),Z(`Interval (seconds)`,h),Z(`Mode`,_))}let y,b,x,S,C,w,T,E,D,O,k;if(d.value===`bash`){b=Q(t?.action.type===`bash`?t.action.cwd:e.sessions()[0]?.cwd??``),y=as(t?.action.type===`bash`?t.action.script:``,6);let n=Z(`Bash script`,y);n.classList.add(`col-span-2`),g.append(Z(`Working directory`,b),G(`span`,``),n)}else if(d.value===`agent`){let n=e.sessions(),r=t?.action.type===`agent`?t.action:null,i=r?.session.mode===`reuse`?r.session.sessionId:``,a=Ul(n,i||null);x=is([[`Reuse session`,`reuse`],[`Fresh child per run`,`fresh`],[`Fork caller context`,`fork`]],r?.session.mode??`fresh`),S=is(a,i||a[0]?.[1]||``),C=Q((r?.session.mode===`fresh`||r?.session.mode===`fork`?r.session.cwd??``:``)||n[0]?.cwd||``),w=as(r?.prompt??``,6),T=is([[`Normal project tools`,`write`],[`Read only`,`read`]],r?.launch?.capabilities??`write`),E=is([[`Project default`,``],[`Off`,`off`],[`Low`,`low`],[`Medium`,`medium`],[`High`,`high`],[`Extra high`,`xhigh`]],r?.launch?.thinking??``),D=Q(r?.launch?.model?.provider??``),O=Q(r?.launch?.model?.id??``);let o=Z(`Session`,S),s=Z(`Child directory`,C),c=[Z(`Capabilities`,T),Z(`Thinking`,E),Z(`Model provider (optional)`,D),Z(`Model id (optional)`,O)],l=()=>{let e=x?.value===`reuse`;o.classList.toggle(`hidden`,!e),s.classList.toggle(`hidden`,e);for(let t of c)t.classList.toggle(`hidden`,e)};x.onchange=l,l();let u=Z(`Prompt`,w);u.classList.add(`col-span-2`),g.append(Z(`Session policy`,x),o,s,...c,u)}else k=is(e.tasks().filter(e=>e.id!==t?.id&&!e.archived).map(e=>[e.name,e.id]),t?.action.type===`task`?t.action.taskId:``),g.append(Z(`Target task`,k));r.onsubmit=r=>{r.preventDefault();let g=u.value===`manual`?{type:`manual`}:u.value===`cron`?{type:`cron`,expression:a.value,timezone:o.value}:{type:`watch`,script:p.value,cwd:v.value,intervalSeconds:Number(h.value),mode:_.value},A=d.value===`agent`&&x.value!==`reuse`?{capabilities:T.value,...E.value?{thinking:E.value}:{},...D.value.trim()&&O.value.trim()?{model:{provider:D.value.trim(),id:O.value.trim()}}:{}}:void 0,ee=d.value===`bash`?{type:`bash`,cwd:b.value,script:y.value}:d.value===`agent`?{type:`agent`,prompt:w.value,session:x.value===`reuse`?{mode:`reuse`,sessionId:S.value}:x.value===`fork`?{mode:`fork`,...C.value.trim()?{cwd:C.value.trim()}:{}}:{mode:`fresh`,cwd:C.value},...A?{launch:A}:{}}:{type:`task`,taskId:k.value},j=f.value===`origin`?{type:`origin`}:f.value===`session`?{type:`session`,sessionId:m.value}:{type:`none`},M={name:s.value,description:c.value,trigger:g,action:ee,callback:j,timeoutSeconds:Number(l.value)};i.textContent=``,Gl(t?.id,M,n,i,e.onSaved)}};u.onchange=_,d.onchange=_,_();let v=X(`Cancel`);v.onclick=()=>n.close();let y=X(`Save`,!0);y.type=`submit`;let b=G(`footer`,`flex flex-none justify-end gap-2 border-t border-neutral-200 px-4 py-3`);b.append(i,v,y),r.append(a,o,b),n.append(r),n.addEventListener(`close`,()=>n.remove()),document.body.append(n),n.showModal(),s.focus()}async function Gl(e,t,n,r,i){let a=await l(e?`/api/tasks/${e}`:`/api/tasks`,t,e?`PATCH`:`POST`);if(!a.ok){r.textContent=(await a.json()).error??`Task save failed`;return}let o=await a.json(),s=`task`in o?o.task:o;n.close(),i(s.id)}var Kl=e=>e===null?`-`:new Date(e).toLocaleString(),ql=e=>e.startedAt===null?`-`:Xn((e.finishedAt??Date.now())-e.startedAt);function Jl(e,t,n){let r=G(`div`,`divide-y divide-neutral-100`);for(let i of t){let t=G(`button`,`grid w-full cursor-pointer grid-cols-[7.5rem_1fr_7.5rem_6.25rem] gap-3 px-4 py-2.5 text-left text-[12.5px] hover:bg-neutral-50`);t.append(G(`span`,`font-medium`,i.state),G(`span`,`truncate text-neutral-500`,Kl(i.queuedAt)),G(`span`,`text-neutral-500`,i.triggerSource),G(`span`,`text-right text-neutral-500`,ql(i))),t.onclick=()=>void Yl(e,i.id,r,n),r.append(t)}t.length||r.append(G(`p`,`p-4 text-[13px] text-neutral-400`,`No runs yet.`)),e.replaceChildren(r)}async function Yl(e,t,n,r){let[i,a]=await Promise.all([fetch(`/api/task-runs/${t}`),fetch(`/api/task-runs/${t}/messages`)]);if(!i.ok)return;let o=await i.json(),s=a.ok?await a.json():[],c=X(`Back to runs`);c.onclick=()=>e.replaceChildren(n);let l=G(`div`,`flex items-center gap-2 border-b border-neutral-200 px-4 py-2`);if(l.append(c,G(`span`,`font-mono text-[12px] text-neutral-400`,o.id)),o.targetSessionId){let e=X(`Open session`);e.classList.add(`ml-auto`),e.onclick=()=>r.openSession(o.targetSessionId),l.append(e)}if(o.state===`queued`||o.state===`running`){let e=X(`Steer`);e.onclick=()=>void Xl(d(`Steer subagent`,`/api/task-runs/${o.id}/steer`,{mode:`steer`,sourceSessionId:r.currentSessionId()},`Run control failed`),r);let t=X(`Stop`);t.onclick=()=>void r.mutate(`/api/task-runs/${o.id}/cancel`),l.append(e,t)}else if(o.targetSessionId){let e=X(`Continue`);e.onclick=()=>void Xl(d(`Continue subagent`,`/api/task-runs/${o.id}/resume`,{sourceSessionId:r.currentSessionId()},`Run control failed`),r),l.append(e)}let u=G(`div`,`min-h-0 flex-1 overflow-auto`),f=G(`pre`,`whitespace-pre-wrap break-words p-4 font-mono text-[12px]`,JSON.stringify(o,null,2));if(u.append(f),s.length){let e=G(`div`,`border-t border-neutral-200`);e.append(G(`div`,`px-4 py-2 text-[11px] font-semibold uppercase text-neutral-400`,`Messages`));for(let t of s){let n=G(`div`,`grid grid-cols-[6.25rem_6.25rem_1fr] gap-3 border-t border-neutral-100 px-4 py-2 text-[12px]`);n.append(G(`span`,`font-medium`,t.kind),G(`span`,`text-neutral-500`,t.state),G(`span`,`whitespace-pre-wrap`,t.content)),e.append(n)}u.append(e)}e.replaceChildren(l,u)}async function Xl(e,t){let n=await e;n.sent&&(n.error?t.onError(n.error):await t.reload())}var Zl=e=>e.trigger.type===`manual`?`Manual`:e.trigger.type===`cron`?`${e.trigger.expression} (${e.trigger.timezone})`:`Every ${e.trigger.intervalSeconds}s · ${e.trigger.mode}`,Ql=e=>e.action.type===`agent`?`Agent · ${e.action.session.mode}`:e.action.type===`bash`?`Bash`:`Task`;function $l(e,t,n,r,i,a){let o=[],s=[],c=null,u=`active`;async function d(){let e=await fetch(`/api/tasks?state=${u===`archived`?`archived`:`active`}${u===`subagent`?`&kind=subagent`:``}`);if(!e.ok)return f(`Failed to load tasks: ${e.status}`);o=await e.json(),s=u===`archived`||u===`subagent`?await p():o,u!==`active`&&u!==`archived`&&u!==`subagent`&&(o=o.filter(e=>e.trigger.type===u)),c?await x(c):y()}function f(t){e.replaceChildren(G(`p`,`p-4 text-[13px] text-red-600`,t))}async function p(){let e=await fetch(`/api/tasks?state=active`);return e.ok?await e.json():s}let m={sessions:t,tasks:()=>s,onSaved:e=>{c=e,d()}},h={openSession:r,currentSessionId:i,mutate:w,onError:f,reload:d};function g(e,t){let n=G(`header`,`flex h-10 flex-none items-center gap-2 border-b border-neutral-200 px-4`);if(n.append(typeof e==`string`?G(`span`,`truncate font-medium max-md:hidden`,e):e),t.length){let e=G(`div`,`ml-auto flex items-center gap-2`);e.append(...t),n.append(e)}return n}function _(){return G(`div`,`tabstrip`,$o(`Sessions`,!1,()=>a(`sessions`)),$o(`Dependencies`,!1,()=>a(`dependencies`)),$o(`Tasks`,!0,v))}function v(){c=null,y()}function y(){let t=X(`New task`,!0);t.onclick=()=>void n().then(()=>Wl(m));let r=_(),i=G(`div`,`ml-auto flex flex-none items-center gap-1 pl-1 max-md:ml-0 max-md:w-full max-md:overflow-x-auto max-md:pl-0`);for(let[e,t]of[[`All`,`active`],[`Manual`,`manual`],[`Scheduled`,`cron`],[`Watching`,`watch`],[`Subagents`,`subagent`],[`Archived`,`archived`]])i.append($o(e,u===t,()=>{u=t,c=null,d()}));r.append(i);let a=document.createElement(`table`);a.className=`w-full min-w-[52rem] table-fixed text-left text-[12.5px]`,a.innerHTML=`<thead class="sticky top-0 bg-neutral-50 text-[10.5px] uppercase text-neutral-400"><tr>
|
|
88
|
+
<th class="w-[24%] px-4 py-2 font-semibold">Name</th><th class="w-[10%] px-2 py-2 font-semibold">Action</th>
|
|
89
|
+
<th class="w-[23%] px-2 py-2 font-semibold">Trigger</th><th class="w-[17%] px-2 py-2 font-semibold">Next</th>
|
|
90
|
+
<th class="w-[14%] px-2 py-2 font-semibold">Last result</th><th class="px-2 py-2 font-semibold"></th></tr></thead>`;let s=document.createElement(`tbody`);for(let e of o)s.append(b(e));a.append(s),e.replaceChildren(g(`Tasks`,[t]),r,G(`div`,`min-h-0 flex-1 overflow-auto`,a))}function b(e){let t=document.createElement(`tr`);t.className=`cursor-pointer border-b border-neutral-100 hover:bg-neutral-50`,t.onclick=()=>{c=e.id,x(e.id)};let n=e.archived?`Archived`:e.enabled?`Enabled`:`Paused`;t.append(G(`td`,`truncate py-2.5 pl-4 pr-2`,G(`div`,`truncate font-medium`,e.name),G(`div`,`text-[11px] text-neutral-400`,n)));for(let n of[Ql(e),Zl(e),Kl(e.nextRunAt),e.lastRun?`${e.lastRun.state} · ${ql(e.lastRun)}`:`-`])t.append(G(`td`,`truncate px-2 py-2.5`,n));let r=X(`Run`);return r.disabled=e.archived,r.onclick=t=>{t.stopPropagation(),C(e.id)},t.append(G(`td`,`px-2 py-1 text-right`,r)),t}async function x(t){let[r,i]=await Promise.all([fetch(`/api/tasks/${t}`),fetch(`/api/tasks/${t}/runs`)]);if(!r.ok||!i.ok)return f(`Failed to load task`);let a=await r.json(),o=await i.json(),s=X(`Tasks`);s.className=`cursor-pointer text-neutral-500 hover:underline`,s.onclick=v;let c=G(`span`,`flex min-w-0 items-center gap-1.5`,s,G(`span`,`text-neutral-400`,`›`),G(`span`,`truncate font-medium`,a.name)),l=X(`Run now`,!0);l.disabled=a.archived,l.onclick=()=>void C(a.id);let u=X(a.enabled?`Pause`:`Resume`);u.disabled=a.archived||a.trigger.type===`manual`,u.onclick=()=>void w(`/api/tasks/${a.id}/${a.enabled?`pause`:`resume`}`);let d=X(`Edit`);d.disabled=a.archived,d.onclick=()=>void n().then(()=>Wl(m,a));let p=X(`Archive`);p.disabled=a.archived,p.onclick=()=>void w(`/api/tasks/${a.id}/archive`);let y=G(`div`,`flex flex-none gap-1 border-b border-neutral-200 px-4 py-2`),b=X(`Definition`),x=X(`Runs (${o.length})`),T=G(`div`,`min-h-0 flex-1 overflow-auto`),E=()=>{b.classList.add(`bg-neutral-200`),x.classList.remove(`bg-neutral-200`),S(T,a)};b.onclick=E,x.onclick=()=>{x.classList.add(`bg-neutral-200`),b.classList.remove(`bg-neutral-200`),Jl(T,o,h)},y.append(b,x),e.replaceChildren(g(c,[l,u,d,p]),_(),y,T),o.length?x.click():E()}function S(e,t){let n=G(`div`,`grid max-w-4xl grid-cols-[9.375rem_minmax(0,1fr)] gap-x-5 gap-y-3 p-4 text-[13px]`),i=[[`Status`,t.archived?`Archived`:t.enabled?`Enabled`:`Paused`],[`Trigger`,Zl(t)],[`Action`,Ql(t)],[`Timeout`,`${t.timeoutSeconds}s`],[`Next run`,Kl(t.nextRunAt)],[`Revision`,String(t.revision)],[`Created by`,t.createdBySessionId??t.creator],[`Callback`,t.callback.type===`session`?t.callback.sessionId:t.callback.type],[`Description`,t.description||`-`]];t.action.type===`agent`&&(i.push([`Session policy`,t.action.session.mode]),t.action.session.mode===`reuse`&&i.push([`Session`,t.action.session.sessionId]),t.action.session.mode===`fresh`&&i.push([`Directory`,t.action.session.cwd]),t.action.session.mode===`fork`&&i.push([`Directory`,t.action.session.cwd??`Caller project`]),t.action.launch?.model&&i.push([`Model`,`${t.action.launch.model.provider}/${t.action.launch.model.id}`]),t.action.launch?.thinking&&i.push([`Thinking`,t.action.launch.thinking]),t.action.launch?.capabilities&&i.push([`Capabilities`,t.action.launch.capabilities]),i.push([`Prompt`,t.action.prompt])),t.action.type===`bash`&&i.push([`Directory`,t.action.cwd],[`Script`,t.action.script]),t.action.type===`task`&&i.push([`Target task`,t.action.taskId]),t.trigger.type===`watch`&&i.push([`Probe`,t.trigger.script]);for(let[e,t]of i)n.append(G(`span`,`text-[11px] font-semibold uppercase text-neutral-400`,e),G(`pre`,`whitespace-pre-wrap break-words font-mono text-[12.5px]`,t));if(t.action.type===`agent`&&t.action.session.mode===`reuse`){let{sessionId:e}=t.action.session,i=X(`Open session`);i.onclick=()=>r(e),n.append(G(`span`,``,``),i)}e.replaceChildren(n)}async function C(e){let t=await l(`/api/tasks/${e}/run`,{sourceSessionId:i()});if(!t.ok)return f((await t.json()).error??`Failed to run task`);c=e,await x(e)}async function w(e){let t=await fetch(e,{method:`POST`});if(!t.ok)return f((await t.json()).error??`Task update failed`);await d()}let T=Zn(e,e=>{e&&(c=e),d()});return Object.assign(T,{refresh(e){T.visible&&(!c||!e||c===e)&&d()}})}var eu=`modulepreload`,tu=function(e){return`/`+e},nu={},ru=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=tu(t,n),t=s(t),t in nu)return;nu[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:eu,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},iu=`pier.terminalPrefs`,au={fontFamily:`monospace`,fontSize:14,cursorBlink:!0},ou=()=>{try{let e=JSON.parse(localStorage.getItem(iu)??`null`),t=typeof e?.fontSize==`number`?e.fontSize:au.fontSize;return{fontFamily:typeof e?.fontFamily==`string`&&e.fontFamily.trim()?e.fontFamily.slice(0,200):au.fontFamily,fontSize:Math.round(Math.max(10,Math.min(24,t))),cursorBlink:typeof e?.cursorBlink==`boolean`?e.cursorBlink:au.cursorBlink}}catch{return{...au}}},su=e=>localStorage.setItem(iu,JSON.stringify(e)),cu=null,lu=()=>(cu||=ru(()=>import(`./ghostty-web-ODXT71Ln.js`).then(async e=>(await e.init(),e)),[]).catch(e=>{throw cu=null,e}),cu),uu={background:`#1a1b26`,foreground:`#a9b1d6`,cursor:`#c0caf5`};function du(e,t,n,r,i){let a=``,o=null,s=null,c=null,l=!1,u=0,d=ou(),f=G(`div`,`ml-auto flex min-w-0 flex-none items-center gap-2`),p=G(`header`,`flex h-10 flex-none items-center gap-2 border-b border-neutral-200 bg-white px-3`),m=G(`div`,`min-h-0 flex-1 overflow-hidden p-1`);m.style.background=uu.background,m.setAttribute(`data-owns-keyboard`,``),m.addEventListener(`keydown`,e=>{e.metaKey&&!e.defaultPrevented&&e.stopImmediatePropagation()},!0),e.append(p,m);let h=e=>{let t=G(`button`,`min-w-0 max-w-72 cursor-pointer truncate rounded-md bg-neutral-100 px-2 py-0.5 text-left font-mono text-[11.5px] text-neutral-600 hover:bg-neutral-200`,e);return t.type=`button`,t};function g(e,t){if(f.replaceChildren(),e&&f.append(G(`span`,`min-w-0 truncate text-[11.5px] text-neutral-400`,e)),t){let e=h(t.label);e.className=e.className.replace(`bg-neutral-100`,`bg-indigo-50 font-medium text-indigo-700 hover:bg-indigo-100`),e.onclick=t.run,f.append(e)}}function _(){o&&(o.options.fontFamily=d.fontFamily,o.options.fontSize=d.fontSize,o.options.cursorBlink=d.cursorBlink,requestAnimationFrame(()=>{s?.fit(),b()}))}function v(e){let t=document.createElement(`input`);t.type=`text`,t.value=d.fontFamily,t.setAttribute(`list`,`terminal-font-presets`),t.className=`w-full rounded border border-neutral-300 px-2 py-1.5 font-mono text-[12px] outline-none focus:border-indigo-400`;let n=document.createElement(`datalist`);n.id=`terminal-font-presets`;for(let e of[`monospace`,`ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace`,`JetBrains Mono, monospace`,`Cascadia Mono, monospace`,`Fira Code, monospace`]){let t=document.createElement(`option`);t.value=e,n.append(t)}let r=document.createElement(`input`);r.type=`number`,r.min=`10`,r.max=`24`,r.step=`1`,r.value=String(d.fontSize),r.className=`w-20 rounded border border-neutral-300 px-2 py-1.5 text-[12px] outline-none focus:border-indigo-400`;let i=document.createElement(`input`);i.type=`checkbox`,i.checked=d.cursorBlink,i.className=`h-4 w-4 accent-indigo-600`;let a=()=>{let e=t.value.trim(),n=Number(r.value);!e||!Number.isFinite(n)||(d={fontFamily:e.slice(0,200),fontSize:Math.round(Math.max(10,Math.min(24,n))),cursorBlink:i.checked},r.value=String(d.fontSize),su(d),_())};t.oninput=a,r.oninput=a,i.onchange=a;let o=G(`button`,`cursor-pointer text-[12px] text-neutral-500 hover:text-indigo-700`,`Reset`);o.type=`button`,o.onclick=()=>{d={...au},t.value=d.fontFamily,r.value=String(d.fontSize),i.checked=d.cursorBlink,su(d),_()},Jo(e,G(`div`,`w-72 space-y-3 px-3 py-2.5`,G(`div`,`flex items-center`,G(`span`,`text-[12px] font-semibold text-neutral-700`,`Terminal`),G(`span`,`ml-auto`,o)),G(`label`,`block space-y-1 text-[11.5px] text-neutral-500`,G(`span`,``,`Font family`),t,n),G(`label`,`flex items-center justify-between text-[11.5px] text-neutral-500`,G(`span`,``,`Font size`),r),G(`label`,`flex cursor-pointer items-center justify-between text-[11.5px] text-neutral-500`,G(`span`,``,`Blinking cursor`),i)))}function y(){let e=h(a||`Choose a folder…`);e.title=`Switch folder`,e.onclick=()=>Xo(e,[...t().map(e=>({label:e,onSelect:()=>{Y(),e!==a&&r(e)}})),{label:`Browse…`,onSelect:()=>ws(e,a||void 0,r)}]);let n=h(`Fit`);n.title=`Resize the shell to this window`,n.onclick=()=>{s?.fit(),b(),o?.focus()};let c=G(`button`,`icon-btn text-[15px]`,`⚙`);c.type=`button`,c.title=`Terminal settings`,c.setAttribute(`aria-label`,`Terminal settings`),c.onclick=()=>v(c);let l=G(`button`,`icon-btn`,`✕`);l.type=`button`,l.title=`Close Terminal`,l.setAttribute(`aria-label`,`Close Terminal`),l.onclick=i,p.replaceChildren(e,f,n,c,l)}let b=()=>{o&&c?.readyState===WebSocket.OPEN&&c.send(JSON.stringify({t:`resize`,cols:o.cols,rows:o.rows}))};function x(){c?.close(),c=null,s=null,o?.dispose(),o=null,m.replaceChildren()}async function S(){let e=++u;x(),l=!1,g(`connecting…`);let t;try{t=await lu()}catch(e){g(`could not load the terminal: ${String(e)}`,{label:`Retry`,run:()=>void S()});return}if(e!==u)return;o=new t.Terminal({fontFamily:d.fontFamily,fontSize:d.fontSize,cursorBlink:d.cursorBlink,scrollback:1e4,theme:uu}),o.open(m),s=new t.FitAddon,o.loadAddon(s),s.observeResize(),s.fit();let n=new WebSocket(`${location.protocol===`https:`?`wss`:`ws`}://${location.host}/api/terminal?cwd=${encodeURIComponent(a)}`);n.binaryType=`arraybuffer`,c=n,n.onopen=()=>{e===u&&(g(``),b(),o?.focus())},n.onmessage=t=>{if(e!==u)return;if(typeof t.data!=`string`){o?.write(new Uint8Array(t.data));return}let r;try{r=JSON.parse(t.data)}catch{l=!0,g(`invalid terminal response`,{label:`Reconnect`,run:()=>void S()}),n.close();return}r.t===`exit`?(l=!0,g(`shell exited (${r.code??`?`})`,{label:`Restart`,run:()=>void S()})):r.t===`error`&&(l=!0,g(r.message??`terminal error`,{label:`Retry`,run:()=>void S()}))},n.onclose=()=>{e!==u||l||g(`disconnected`,{label:`Reconnect`,run:()=>void S()})},o.onData(e=>{n.readyState===WebSocket.OPEN&&n.send(JSON.stringify({t:`in`,d:e}))}),o.onResize(({cols:e,rows:t})=>{n.readyState===WebSocket.OPEN&&n.send(JSON.stringify({t:`resize`,cols:e,rows:t}))})}return Zn(e,e=>{let r=e?.startsWith(`/`)?e:a||n()||t()[0]||``;if(r===a&&o){y(),!l&&c&&c.readyState>WebSocket.OPEN?S():o.focus();return}if(a=r,y(),!a){g(`No project yet — pick a folder from the chip.`);return}S()},Y)}var fu,pu=W(`#chat-header`),mu=W(`#chat-title`),hu=[pu,da,W(`#composer`)],gu=!0,_u=()=>gu,vu,yu,bu=[],xu=new Map,Su=`activity`,Cu=[`files`,`terminal`],wu=new Map,Tu={tasks:`Tasks`,activity:`Activity`,boards:`Boards`,settings:`Settings`,files:`Files`,terminal:`Terminal`},Eu=e=>vu.refresh(e),Du=()=>yu.refresh();function Ou(){let e=bu.find(e=>e.view.visible);e?Nc(Tu[e.name],!1):Nc(mu.textContent??``,fu.currentSession()!==void 0)}function ku(e,t){if((e===`tasks`||e===`activity`)&&(Su=e),Cu.includes(e)){let t=Bu();t&&(t.kind!==`console`||t.name!==e)&&wu.set(e,t)}Hu({kind:`console`,name:e,arg:t}),Mc(),gu=!1;for(let e of hu)e.classList.add(`hidden`);Oo();for(let n of bu)n.name===e?n.view.show(t):n.view.hide();for(let[t,n]of xu)n.classList.toggle(`bg-indigo-50`,t===e||t===`activity`&&e===`tasks`);Ou()}var Au=e=>ku(`tasks`,e),ju=e=>ku(`files`,e),Mu=e=>ku(`terminal`,e),Nu=(e,t)=>{bu.find(t=>t.name===e)?.view.visible?Iu(e):ku(e,t)},Pu=e=>Nu(`files`,e),Fu=e=>Nu(`terminal`,e);function Iu(e){let t=fu.currentId(),n=wu.get(e)??(t?{kind:`session`,id:t}:null);wu.delete(e),n?Hu(n):(history.replaceState(null,``,`#/`),Lu())}function Lu(){if(bu.some(({view:e})=>e.visible)){for(let{view:e}of bu)e.hide();for(let e of xu.values())e.classList.remove(`bg-indigo-50`);gu=!0;for(let e of hu)e.classList.remove(`hidden`);Oo(),Ou(),fu.maybeAckRead()}}var Ru=e=>e.kind===`session`?`#/session/${encodeURIComponent(e.id)}`:`#/${e.name}${e.arg?`/${encodeURIComponent(e.arg)}`:``}`,zu={config:`files`,channels:`channels`,providers:`providers`};function Bu(){let[e=``,t]=location.hash.replace(/^#\/?/,``).split(`/`);if(zu[e])return{kind:`console`,name:`settings`,arg:zu[e]};let n=bu.find(t=>t.name===e)?.name;return n?{kind:`console`,name:n,arg:t?decodeURIComponent(t):void 0}:e===`session`&&t?{kind:`session`,id:decodeURIComponent(t)}:null}var Vu=!1;function Hu(e,t=!1){if(Vu)return;let n=Ru(e);location.hash!==n&&(t?history.replaceState(null,``,n):location.hash=n)}var Uu=e=>Hu({kind:`session`,id:e});function Wu(){let e=Bu(),t=fu.sessions(),n=fu.currentId(),r=(e?.kind===`session`?e.id:null)??n??(t.find(e=>e.pinned)??t[0])?.id??null;Vu=!0;try{r&&r!==n&&fu.select(r),e?.kind===`console`?ku(e.name,e.arg):Lu(),r||vc()}finally{Vu=!1}e?.kind!==`console`&&r&&Hu({kind:`session`,id:r},!0)}function Gu(e){fu=e,vu=$l(W(`#tasks-view`),()=>fu.sessions().map(({id:e,cwd:t,title:n})=>({id:e,cwd:t,title:n})),e.loadSessions,e.select,()=>fu.currentId(),e=>ku(`activity`,e)),yu=Qc(W(`#activity-view`),e.select,Au),bu=[{name:`tasks`,view:vu},{name:`activity`,view:yu},{name:`boards`,view:$c(W(`#boards-view`),e.select)},{name:`files`,view:fl(W(`#files-view`),()=>[...zs(fu.sessions()).keys()],e=>ku(`files`,e),()=>Iu(`files`))},{name:`terminal`,view:du(W(`#terminal-view`),()=>[...zs(fu.sessions()).keys()],()=>fu.currentSession()?.cwd,e=>ku(`terminal`,e),()=>Iu(`terminal`))},{name:`settings`,view:Hl(W(`#settings-view`),()=>[...zs(fu.sessions()).keys()],e=>ku(`settings`,e))}];let t=W(`#open-terminal`);t.onclick=()=>Fu(),ro(t,"ctrl+`",`Terminal`,()=>Fu(),void 0,!0);for(let e of[`activity`,`boards`,`settings`]){let t=W(`#open-${e}`);xu.set(e,t),t.onclick=()=>ku(e===`activity`?Su:e)}let n=W(`#console-section`);n.open=localStorage.getItem(`pier.consoleCollapsed`)!==`1`,n.ontoggle=()=>localStorage.setItem(`pier.consoleCollapsed`,n.open?`0`:`1`),window.onhashchange=Wu}var Ku=[],qu=0,Ju=null,Yu=`idle`,Xu=null,Zu=0,Qu=!1;async function $u(e){let t=await l(`/api/sessions`,{cwd:e});if(!t.ok){q(`error`,`session create failed: ${t.status}`);return}let{id:n}=await t.json();await nd(),await dd(n),Co()}function ed(e,t){if(t)Ku=e;else{let t=new Map(e.map(e=>[e.id,e]));Ku=Ku.map(e=>t.get(e.id)??(e.pinned?{...e,pinned:!1}:e));let n=new Set(Ku.map(e=>e.id));Ku.push(...e.filter(e=>!n.has(e.id)))}Ku.sort((e,t)=>t.createdAt-e.createdAt),Gs(),id()}function td(e){let t,n=!1;return()=>(n=!0,t??=(async()=>{for(;n;)n=!1,await e()})().finally(()=>{t=void 0}))}var nd=td(async()=>{ed(await(await fetch(`/api/projects`)).json(),!1)}),rd=td(async()=>{ed(await(await fetch(`/api/sessions`)).json(),!0)});function id(){if(document.hidden||!_u())return;let e=Ku.find(e=>e.id===Ju);e?.unread&&(e.unread=!1,Gs(),fetch(`/api/sessions/${e.id}/read`,{method:`POST`}))}function ad(){return Ku.find(e=>e.id===Ju)}function od(e,t){let n=Ku.find(t=>t.id===e);!n||n.title||!t.trim()||(n.title=t.trim().slice(0,80),Gs(),vc())}function sd(e){Yu=e;let t=Ku.find(e=>e.id===Ju);t&&(t.state=e),Gs(),vc(),Do(),e===`idle`&&nd()}function cd(e){if(!(e.sessionId!==Ju||e.seq<=Zu))switch(Zu=e.seq,e.type){case`turn-start`:Qu=!0;break;case`system-input`:Ma(),ga(e.text,e.origin);break;case`task-status`:Vi(e.run);break;case`user-message`:if(od(e.sessionId,e.text),wo(e.text))break;Ma(),q(`user`,e.text),ma();break;case`text-delta`:ja(e.text);break;case`thinking-delta`:aa(e.ts,e.text);break;case`tool-start`:Ma(),ra(e.ts,e.toolCallId,e.toolName,e.args);break;case`tool-end`:ia(e.toolCallId,e.isError,e.output);break;case`turn-end`:Qu=!1,Na(e.text,e.meta),e.meta&&_c(e.meta.tokens);break;case`queue-state`:ko(e.steering,e.followUp);break;case`error`:ta(),q(`error`,e.message);break;case`state`:e.state===`idle`&&Qu&&(Qu=!1,Pa()),e.state===`idle`&&ko([],[]),sd(e.state)}}function ld(){let e=new EventSource(`/api/events`);e.onopen=()=>void nd(),e.onerror=()=>Ya(e,`Workspace`),e.onmessage=e=>{let t=JSON.parse(e.data);if(t.type===`sessions-changed`){nd();return}if(t.type===`tasks-changed`||t.type===`task-run-changed`||t.type===`task-message-changed`||t.type===`task-group-changed`){Eu(t.type===`task-run-changed`?t.taskId:void 0),Du(),t.type===`task-run-changed`&&nd();return}if(Du(),t.sessionId===Ju)return;let n=Ku.find(e=>e.id===t.sessionId);n&&(n.state=t.state,Gs())}}function ud(e,t){Xu?.close();let n=new EventSource(`/api/sessions/${e}/events?after=${t}`);n.onmessage=e=>cd(JSON.parse(e.data)),n.onerror=()=>Ya(n,`Session`),Xu=n}async function dd(e){let t=++qu,n=!1;if(!Ku.some(t=>t.id===e)){if(await rd(),t!==qu)return;n=!Ku.some(t=>t.id===e)}Lu(),Mc(),Uu(e),!(e===Ju&&!n)&&(Fo(),Ju=e,Yu=Ku.find(t=>t.id===e)?.state??`idle`,Io(e),Gs(),vc(),id(),await fd(e,n))}async function fd(e,t=!1){if(Xu?.close(),Fa(),ko([],[]),hc(),Qu=!1,Eo(),Zu=0,Ia(!0),t){Ia(!1),q(`error`,`session not found: ${e}`);return}let n=await fetch(`/api/sessions/${e}/history`),r=n.ok?await n.json():null;if(Ju===e){if(!r){Ia(!1),q(`error`,`failed to load session: ${n.status}`);return}La(r.turns,r.state,r.backgroundRuns),Zu=r.lastSeq,Qu=r.state===`streaming`,sd(r.state),ko(r.queue.steering,r.queue.followUp),gc(r.model,r.context,r.thinkingLevel),ud(e,r.lastSeq)}}Ga(),Ja();var pd=async e=>{Ju===e&&await fd(e)};fa({sessionId:()=>Ju,sessionState:()=>Yu,select:e=>void dd(e),showTasks:Au,send:(e,t)=>void zo(e,t),ownTurn:e=>{To(e),sd(`streaming`)},reload:pd}),Ho({sessionId:()=>Ju,sessionState:()=>Yu,chatVisible:_u,setState:sd,reload:pd}),Rc({sessionMenu:e=>{let t=ad();t&&Dc(e,t)}}),rc({sessions:()=>Ku,loadSessions:rd,currentId:()=>Ju,select:e=>void dd(e),sessionMenu:Dc,createSession:$u,openFiles:ju,openTerminal:Mu,openConsole:ku,onPinsChanged:vc}),ac({currentId:()=>Ju,currentSession:ad,syncBar:Ou,openFiles:ju,toggleFiles:Pu}),Gu({sessions:()=>Ku,loadSessions:rd,currentId:()=>Ju,currentSession:ad,select:e=>void dd(e),maybeAckRead:id}),Yc(`0.0.6`),document.addEventListener(`visibilitychange`,id),ld(),nd().then(Wu);export{ru as t};
|