From 316fd5b62572cdcc845528e125f0af733923e77c Mon Sep 17 00:00:00 2001 From: samzong Date: Thu, 28 May 2026 06:24:55 +0800 Subject: [PATCH] [Fix] Warm provider auth off main thread (#86281) * fix(agents): warm provider auth off main thread Signed-off-by: samzong * fix(agents): keep provider auth warm read-only * fix(ci): unblock provider auth landing * ci: serialize gateway watch artifact check * fix(ci): stabilize diffs viewer asset generation * fix(agents): avoid stale plugin auth warm results * fix(agents): keep partial auth warm cache --------- Signed-off-by: samzong Co-authored-by: Peter Steinberger --- config/knip.config.ts | 1 + extensions/diffs/assets/viewer-runtime.js | 4 +- scripts/build-diffs-viewer-runtime.mjs | 3 + scripts/release-check.ts | 1 + src/agents/auth-profiles.ts | 1 + src/agents/auth-profiles/store.ts | 21 +- src/agents/model-auth.ts | 2 + src/agents/model-provider-auth.test.ts | 263 ++++++++++ src/agents/model-provider-auth.ts | 461 +++++++++++++++++- src/agents/model-provider-auth.worker.test.ts | 83 ++++ src/agents/model-provider-auth.worker.ts | 82 ++++ src/agents/tools/image-tool.ts | 27 +- .../server-methods/models-auth-status.test.ts | 6 +- .../server-methods/models-auth-status.ts | 4 +- src/gateway/server-reload-handlers.test.ts | 12 +- src/gateway/server-reload-handlers.ts | 4 +- .../server-startup-post-attach.test.ts | 40 +- src/gateway/server-startup-post-attach.ts | 6 +- src/infra/tsdown-config.test.ts | 1 + test/release-check.test.ts | 2 + tsdown.config.ts | 1 + 21 files changed, 954 insertions(+), 71 deletions(-) create mode 100644 src/agents/model-provider-auth.worker.test.ts create mode 100644 src/agents/model-provider-auth.worker.ts diff --git a/config/knip.config.ts b/config/knip.config.ts index 5e6ae3af3f85..72c90d4126ac 100644 --- a/config/knip.config.ts +++ b/config/knip.config.ts @@ -10,6 +10,7 @@ const rootEntries = [ "src/entry.ts!", "src/cli/daemon-cli.ts!", "src/agents/code-mode.worker.ts!", + "src/agents/model-provider-auth.worker.ts!", "src/infra/kysely-node-sqlite.ts!", "src/infra/warning-filter.ts!", "src/infra/command-explainer/index.ts!", diff --git a/extensions/diffs/assets/viewer-runtime.js b/extensions/diffs/assets/viewer-runtime.js index c0f4fea8d25f..8e9506f4d0bc 100644 --- a/extensions/diffs/assets/viewer-runtime.js +++ b/extensions/diffs/assets/viewer-runtime.js @@ -6,7 +6,7 @@ var fr=Object.defineProperty;var Pp=Object.getPrototypeOf;var $p=Reflect.get;var \f\r &>`.split(""),`\0 \f\r "&'<=>\``.split("")],[`\0 \f\r "&'<=>\``.split(""),`\0 -\f\r "&'<=>\``.split("")]],single:[["&'".split(""),"\"&'`".split("")],["\0&'".split(""),"\0\"&'`".split("")]],double:[['"&'.split(""),"\"&'`".split("")],['\0"&'.split(""),"\0\"&'`".split("")]]};function Ai(e,t,n,A){let o=A.schema,a=o.space==="svg"?!1:A.settings.omitOptionalTags,r=o.space==="svg"?A.settings.closeEmptyElements:A.settings.voids.includes(e.tagName.toLowerCase()),s=[],i;o.space==="html"&&e.tagName==="svg"&&(A.schema=Un);let c=Dl(A,e.properties),d=A.all(o.space==="html"&&e.tagName==="template"?e.content:e);return A.schema=o,d&&(r=!1),(c||!a||!ni(e,t,n))&&(s.push("<",e.tagName,c?" "+c:""),r&&(o.space==="svg"||A.settings.closeSelfClosing)&&(i=c.charAt(c.length-1),(!A.settings.tightSelfClosing||i==="/"||i&&i!=='"'&&i!=="'")&&s.push(" "),s.push("/")),s.push(">")),s.push(d),!r&&(!a||!Ot(e,t,n))&&s.push(""),s.join("")}function Dl(e,t){let n=[],A=-1,o;if(t){for(o in t)if(t[o]!==null&&t[o]!==void 0){let a=Fl(e,o,t[o]);a&&n.push(a)}}for(;++ABo(n,e.alternative)&&(r=e.alternative),s=r+xe(n,Object.assign({},e.settings.characterReferences,{subset:(r==="'"?Yn.single:Yn.double)[o][a],attribute:!0}))+r),i+(s&&"="+s))}var vl=["<","&"];function Tn(e,t,n,A){return n&&n.type==="element"&&(n.tagName==="script"||n.tagName==="style")?e.value:xe(e.value,Object.assign({},A.settings.characterReferences,{subset:vl}))}function oi(e,t,n,A){return A.settings.allowDangerousHtml?e.value:Tn(e,t,n,A)}function ai(e,t,n,A){return A.all(e)}var ri=Hr("type",{invalid:xl,unknown:Ml,handlers:{comment:Jr,doctype:Wr,element:Ai,raw:oi,root:ai,text:Tn}});function xl(e){throw new Error("Expected node, not `"+e+"`")}function Ml(e){let t=e;throw new Error("Cannot compile unknown node `"+t.type+"`")}var Sl={},Ll={},Nl=[];function Ce(e,t){let n=t||Sl,A=n.quote||'"',o=A==='"'?"'":'"';if(A!=='"'&&A!=="'")throw new Error("Invalid quote `"+A+"`, expected `'` or `\"`");return{one:Rl,all:Gl,settings:{omitOptionalTags:n.omitOptionalTags||!1,allowParseErrors:n.allowParseErrors||!1,allowDangerousCharacters:n.allowDangerousCharacters||!1,quoteSmart:n.quoteSmart||!1,preferUnquoted:n.preferUnquoted||!1,tightAttributes:n.tightAttributes||!1,upperDoctype:n.upperDoctype||!1,tightDoctype:n.tightDoctype||!1,bogusComments:n.bogusComments||!1,tightCommaSeparatedLists:n.tightCommaSeparatedLists||!1,tightSelfClosing:n.tightSelfClosing||!1,collapseEmptyAttributes:n.collapseEmptyAttributes||!1,allowDangerousHtml:n.allowDangerousHtml||!1,voids:n.voids||xr,characterReferences:n.characterReferences||Ll,closeSelfClosing:n.closeSelfClosing||!1,closeEmptyElements:n.closeEmptyElements||!1},schema:n.space==="svg"?Un:Rr,quote:A,alternative:o}.one(Array.isArray(e)?{type:"root",children:e}:e,void 0,void 0)}function Rl(e,t,n){return ri(e,t,n,this)}function Gl(e){let t=[],n=e&&e.children||Nl,A=-1;for(;++A{let e=this.gutterUtilityLine??this.hoveredLine;if(e!=null){if(this.mode==="diff"&&e.type==="diff-line")return{lineNumber:e.lineNumber,side:e.annotationSide};if(this.mode==="file"&&e.type==="line")return{lineNumber:e.lineNumber}}});m(this,"handlePointerClick",e=>{let{onHunkExpand:t,onLineClick:n,onLineNumberClick:A,onTokenClick:o,onMergeConflictActionClick:a}=this.options;t==null&&n==null&&A==null&&a==null&&o==null||this.options.onGutterUtilityClick!=null&&On(e.composedPath())||(Me(this.options.__debugPointerEvents,"click","FileDiff.DEBUG.handlePointerClick:",e),this.handlePointerEvent({eventType:"click",event:e}))});m(this,"handlePointerMove",e=>{if(e.pointerType!=="mouse")return;let{lineHoverHighlight:t="disabled",onLineEnter:n,onLineLeave:A,onTokenEnter:o,onTokenLeave:a,enableGutterUtility:r=!1}=this.options;t==="disabled"&&!r&&n==null&&A==null&&o==null&&a==null||(Me(this.options.__debugPointerEvents,"move","FileDiff.DEBUG.handlePointerMove:",e),this.handlePointerEvent({eventType:"move",event:e}))});m(this,"handlePointerLeave",e=>{let{__debugPointerEvents:t}=this.options;if(Me(t,"move","FileDiff.DEBUG.handlePointerLeave: no event"),this.hoveredLine==null&&this.hoveredToken==null){Me(t,"move","FileDiff.DEBUG.handlePointerLeave: returned early, no hovered line or token");return}this.hoveredToken!=null&&(this.options.onTokenLeave?.(this.hoveredToken,e),this.clearHoveredToken()),this.hoveredLine!=null&&(this.options.onLineLeave?.({...this.hoveredLine,event:e}),this.clearHoveredLine()),this.placeUtility()});m(this,"handlePointerDown",e=>{if(e.pointerType==="mouse"&&e.button!==0||this.pre==null||this.pointerSession.mode!=="idle")return;let t=e.composedPath();On(t)&&this.options.onGutterUtilityClick!=null?this.startGutterSelectionFromPointerDown(e):(e.pointerType!=="mouse"&&this.revealUtilityFromGutterPath(t),this.startLineSelectionFromPointerDown(e))});m(this,"handleDocumentPointerMove",e=>{let{enableLineSelection:t=!1}=this.options;switch(this.pointerSession.mode){case"idle":return;case"gutterSelecting":{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let n=this.resolveSelectionPoint(e,{source:"coordinates-first"});if(n==null)return;this.pointerSession.current=n,t===!0&&this.updateSelection(n.lineNumber,n.side);return}case"selecting":{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let n=this.resolveSelectionInfo(e,{source:"coordinates-first",requireNumberColumn:!1});if(n==null||this.selectionAnchor==null)return;this.updateSelection(n.lineNumber,n.eventSide);return}case"pendingSingleLineUnselect":{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let n=this.resolveSelectionInfo(e,{source:"coordinates-first",requireNumberColumn:!1});if(n==null||this.selectionAnchor==null)return;let A={lineNumber:n.lineNumber,side:n.eventSide};if(vr(this.pointerSession.pending,A))return;this.updateSelection(n.lineNumber,n.eventSide,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.notifySelectionChangeDelta(),this.pointerSession={mode:"selecting",pointerId:e.pointerId};return}}});m(this,"handleDocumentPointerUp",e=>{let{enableLineSelection:t=!1,onGutterUtilityClick:n}=this.options;switch(this.pointerSession.mode){case"idle":return;case"gutterSelecting":{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let A=this.resolveSelectionPoint(e,{source:"coordinates-first"});A!=null&&(this.pointerSession.current=A,t&&this.updateSelection(A.lineNumber,A.side)),n?.(this.buildSelectedLineRange(this.pointerSession.anchor,this.pointerSession.current)),this.selectionAnchor=void 0,t&&(this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(),this.clearProposedSelection()),this.clearPointerSession(),this.detachDocumentPointerListeners();return}case"pendingSingleLineUnselect":if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault(),this.updateSelection(null,void 0,!1),this.selectionAnchor=void 0,this.clearPendingSingleLineState(),this.detachDocumentPointerListeners(),this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(),this.clearProposedSelection();return;case"selecting":if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault(),this.selectionAnchor=void 0,this.detachDocumentPointerListeners(),this.clearPointerSession(),this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(),this.clearProposedSelection()}});m(this,"handleDocumentPointerCancel",e=>{switch(this.pointerSession.mode){case"idle":return;case"gutterSelecting":case"selecting":case"pendingSingleLineUnselect":if("pointerId"in this.pointerSession&&e.pointerId!==this.pointerSession.pointerId)return;this.selectionAnchor=void 0,this.clearProposedSelection(),this.clearPendingSingleLineState(),this.clearPointerSession(),this.detachDocumentPointerListeners()}});m(this,"renderSelection",()=>{if(this.queuedSelectionRender!=null&&(cancelAnimationFrame(this.queuedSelectionRender),this.queuedSelectionRender=void 0),this.pre==null||this.renderedSelectionRange===this.selectedRange)return;let e=this.pre.querySelectorAll("[data-selected-line]");for(let s of e)s.removeAttribute("data-selected-line");if(this.renderedSelectionRange=this.selectedRange,this.selectedRange==null)return;let{children:t}=this.pre;if(t.length===0)return;if(t.length>2)throw console.error(t),new Error("InteractionManager.renderSelection: Somehow there are more than 2 code elements...");let n=this.pre.getAttribute("data-diff-type")==="split",A=this.getIndexesFromSelection(this.selectedRange,n);if(A==null)throw console.error({rowRange:A,selectedRange:this.selectedRange}),new Error("InteractionManager.renderSelection: No valid rowRange");let o=A.start===A.end,a=Math.min(A.start,A.end),r=Math.max(A.start,A.end);for(let s of t){let[i,c]=s.children,d=c.children.length;if(d!==i.children.length)throw new Error("InteractionManager.renderSelection: gutter and content children dont match, something is wrong");for(let u=0;ur)break;if(l==null||l{let b=[];return(t==="both"||t==="click")&&(A!=null&&b.push("onLineClick"),o!=null&&b.push("onLineNumberClick"),d!=null&&b.push("expandable hunk separators"),u!=null&&b.push("merge conflict actions")),b})()),Me(t,"move","FileDiff.DEBUG.attachEventListeners: Attaching pointer move event"),Me(t,"move","FileDiff.DEBUG.attachEventListeners: Attaching pointer leave event")):!E&&this.hasPointerListeners&&(e.removeEventListener("click",this.handlePointerClick),e.removeEventListener("pointerdown",this.handlePointerDown),e.removeEventListener("pointermove",this.handlePointerMove),e.removeEventListener("pointerleave",this.handlePointerLeave),this.hasPointerListeners=!1);let h=this.pointerSession.mode==="selecting"||this.pointerSession.mode==="pendingSingleLineUnselect",f=this.pointerSession.mode==="gutterSelecting";(!p&&h||!B&&f)&&(this.clearPointerSession(),this.detachDocumentPointerListeners(),this.selectionAnchor=void 0,this.clearPendingSingleLineState())}updateInteractiveLineAttributes(){if(this.pre==null)return;let{onLineClick:e,onLineNumberClick:t,enableLineSelection:n=!1}=this.options,A=e!=null,o=t!=null||n;A&&!this.interactiveLinesAttr?(this.pre.setAttribute("data-interactive-lines",""),this.interactiveLinesAttr=!0):!A&&this.interactiveLinesAttr&&(this.pre.removeAttribute("data-interactive-lines"),this.interactiveLinesAttr=!1),o&&!this.interactiveLineNumbersAttr?(this.pre.setAttribute("data-interactive-line-numbers",""),this.interactiveLineNumbersAttr=!0):!o&&this.interactiveLineNumbersAttr&&(this.pre.removeAttribute("data-interactive-line-numbers"),this.interactiveLineNumbersAttr=!1)}startLineSelectionFromPointerDown(e){let{enableLineSelection:t=!1}=this.options;if(!t)return;let n=this.resolveSelectionInfo(e,{source:"event-path",requireNumberColumn:!0});if(n==null)return;let{pre:A}=this;if(A==null)return;e.preventDefault();let{lineNumber:o,eventSide:a,lineIndex:r}=n;if(e.shiftKey&&this.selectedRange!=null){let s=this.getIndexesFromSelection(this.selectedRange,A.getAttribute("data-diff-type")==="split");if(s==null)return;let i=s.start<=s.end?r>=s.start:r<=s.end;this.selectionAnchor={lineNumber:i?this.selectedRange.start:this.selectedRange.end,side:i?this.selectedRange.side:this.selectedRange.endSide??this.selectedRange.side},this.updateSelection(o,a,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.pointerSession={mode:"selecting",pointerId:e.pointerId},this.attachDocumentPointerListeners();return}if(this.selectedRange?.start===o&&this.selectedRange?.end===o){let s={lineNumber:o,side:a};this.selectionAnchor=s,this.pointerSession={mode:"pendingSingleLineUnselect",pointerId:e.pointerId,anchor:s,pending:s},this.attachDocumentPointerListeners();return}this.options.controlledSelection===!0?this.proposedSelectedRange=null:this.selectedRange=null,this.placeUtility(),this.selectionAnchor={lineNumber:o,side:a},this.updateSelection(o,a,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.pointerSession={mode:"selecting",pointerId:e.pointerId},this.attachDocumentPointerListeners()}startGutterSelectionFromPointerDown(e){let{enableLineSelection:t=!1,onGutterUtilityClick:n}=this.options;if(n==null)return;let A=this.currentSelectionEnds(),o=A?.bottom??this.resolveSelectionPoint(e,{source:"event-path",excludeUtility:!1}),a=A?.top??o;o==null||a==null||(e.preventDefault(),e.stopPropagation(),this.pointerSession={mode:"gutterSelecting",pointerId:e.pointerId,anchor:a,current:o},t&&(this.selectionAnchor={lineNumber:a.lineNumber,side:a.side},this.updateSelection(o.lineNumber,o.side,!1),this.notifySelectionStart(this.getCurrentSelectionRange())),this.attachDocumentPointerListeners())}clearHoveredLine(){this.hoveredLine!=null&&(this.hoveredLine.lineElement.removeAttribute("data-hovered"),this.hoveredLine.numberElement.removeAttribute("data-hovered"),this.hoveredLine=void 0)}setHoveredLine(e){let{lineHoverHighlight:t="disabled"}=this.options;this.hoveredLine!=null&&this.clearHoveredLine(),this.hoveredLine=e,t!=="disabled"&&((t==="both"||t==="line")&&this.hoveredLine.lineElement.setAttribute("data-hovered",""),(t==="both"||t==="number")&&this.hoveredLine.numberElement.setAttribute("data-hovered",""))}clearHoveredToken(){this.hoveredToken!=null&&(this.hoveredToken=void 0)}setHoveredToken(e){this.hoveredToken!=null&&this.clearHoveredToken(),this.hoveredToken=e}ensureGutterUtilityNode(e){if(this.gutterUtilityContainer==null&&(this.gutterUtilityContainer=document.createElement("div"),this.gutterUtilityContainer.setAttribute("data-gutter-utility-slot","")),e)this.gutterUtilityButton!=null&&(this.gutterUtilityButton.remove(),this.gutterUtilityButton=void 0),this.gutterUtilitySlot==null&&(this.gutterUtilitySlot=document.createElement("slot"),this.gutterUtilitySlot.name="gutter-utility-slot"),this.gutterUtilitySlot.parentNode!==this.gutterUtilityContainer&&this.gutterUtilityContainer.replaceChildren(this.gutterUtilitySlot);else{if(this.gutterUtilitySlot?.remove(),this.gutterUtilitySlot=void 0,this.gutterUtilityButton==null){let t=document.createElement("div");t.innerHTML=Ce(Fr());let n=t.firstElementChild;if(!(n instanceof HTMLButtonElement))throw new Error("InteractionManager.ensureGutterUtilityNode: Node element should be a button");n.remove(),this.gutterUtilityButton=n}this.gutterUtilityButton.parentNode!==this.gutterUtilityContainer&&this.gutterUtilityContainer.replaceChildren(this.gutterUtilityButton)}}revealUtilityFromGutterPath(e){if(this.placeUtilityFromSelection())return;let t=this.resolvePointerTarget(e);Jt(t)&&t.numberColumn&&this.showUtilityOnLine(this.toEventBaseProps(t))}placeUtility(){if(!this.placeUtilityFromSelection()){if(this.hoveredLine!=null){this.showUtilityOnLine(this.hoveredLine);return}this.hideUtility()}}placeUtilityFromSelection(){let e=this.currentSelectionEnds();if(e==null)return!1;let t=this.targetForSelectionPoint(e.bottom);return t==null?this.hideUtility():this.showUtilityOnLine(this.toEventBaseProps(t)),!0}showUtilityOnLine(e){this.gutterUtilityContainer!=null&&(this.gutterUtilityLine=e,e.numberElement.appendChild(this.gutterUtilityContainer))}hideUtility(){this.gutterUtilityContainer?.remove(),this.gutterUtilityLine=void 0}currentSelectionEnds(){let e=this.getCurrentSelectionRange();return e==null?void 0:this.selectionEnds(e)}selectionEnds(e){let t={lineNumber:e.start,side:e.side},n={lineNumber:e.end,side:e.endSide??e.side},A=this.selectionPointRowIndex(t),o=this.selectionPointRowIndex(n);if(!(A==null||o==null))return A>o?{top:n,bottom:t}:{top:t,bottom:n}}selectionPointRowIndex(e){let t=this.getLineIndex(e.lineNumber,e.side);if(t!=null)return this.isSplitDiff()?t[1]:t[0]}targetForSelectionPoint(e){if(this.pre==null)return;let t=this.getLineIndex(e.lineNumber,e.side);if(t==null)return;let n=this.mode==="diff"?`${t[0]},${t[1]}`:`${t[0]}`,A=this.pre.querySelectorAll(`[data-column-number="${e.lineNumber}"][data-line-index="${n}"]`);for(let o of A){if(!(o instanceof HTMLElement))continue;let a=this.resolvePointerTarget(Kn(o));if(Jt(a)&&!(this.mode==="diff"&&e.side!=null&&a.side!==e.side))return a}}attachDocumentPointerListeners(){this.hasDocumentPointerListeners||(document.addEventListener("pointermove",this.handleDocumentPointerMove),document.addEventListener("pointerup",this.handleDocumentPointerUp),document.addEventListener("pointercancel",this.handleDocumentPointerCancel),this.hasDocumentPointerListeners=!0)}detachDocumentPointerListeners(){this.hasDocumentPointerListeners&&(document.removeEventListener("pointermove",this.handleDocumentPointerMove),document.removeEventListener("pointerup",this.handleDocumentPointerUp),document.removeEventListener("pointercancel",this.handleDocumentPointerCancel),this.hasDocumentPointerListeners=!1)}clearPointerSession(){this.pointerSession={mode:"idle"}}clearPendingSingleLineState(){this.pointerSession.mode==="pendingSingleLineUnselect"&&(this.pointerSession={mode:"idle"})}selectionInfoFromPath(e,t){let n=this.resolvePointerTarget(e);if(Jt(n)&&!(t&&!n.numberColumn)&&n.splitLineIndex!=null)return{lineIndex:n.splitLineIndex,lineNumber:n.lineNumber,eventSide:this.mode==="diff"?n.side:void 0}}resolveSelectionInfo(e,t){let n=this.resolveSelectionPath(e,t);return n!=null?this.selectionInfoFromPath(n,t.requireNumberColumn):void 0}selectionPointFromPath(e){let t=this.resolvePointerTarget(e);if(Jt(t))return{lineNumber:t.lineNumber,side:this.mode==="diff"?t.side:void 0}}resolveSelectionPoint(e,t){let n=this.resolveSelectionPath(e,t);return n!=null?this.selectionPointFromPath(n):void 0}resolveSelectionPath(e,t){let n=t.excludeUtility!==!1;switch(t.source){case"event-path":return this.pathFromEventPath(e.composedPath(),n);case"coordinates-first":{let A=this.pathFromCoordinates(e,n);return A!==void 0?A??void 0:this.pathFromEventPath(e.composedPath(),n)}}}pathFromCoordinates(e,t){let n=this.hitTest(e);if(n!==void 0)return n===null?null:this.pathFromElement(n,t)??null}pathFromEventPath(e,t){if(!(t&&On(e))){for(let n of e)if(n instanceof Element)return this.pathFromElement(n,t)}}pathFromElement(e,t){let n=Kn(e);if(t&&On(n))return;let A=$l(e);return A!=null?Kn(A):this.pathFromAnnotationSlot(e)}pathFromAnnotationSlot(e){let t=Yl(ql(e));if(t==null)return;let n=this.targetForSelectionPoint(t);return n!=null?Kn(n.lineElement):void 0}hitTest(e){if(!Number.isFinite(e.clientX)||!Number.isFinite(e.clientY))return;let t=this.pre?.getRootNode(),n=si(t)?t:si(document)?document:void 0;if(n!=null)return n.elementFromPoint(e.clientX,e.clientY)}getLineIndex(e,t){let{getLineIndex:n}=this.options;return n!=null?n(e,t):[e-1,e-1]}getCurrentSelectionRange(){return this.proposedSelectedRange!==void 0?this.proposedSelectedRange:this.selectedRange}clearProposedSelection(){this.proposedSelectedRange=void 0}updateSelection(e,t,n=!0){let A=this.getCurrentSelectionRange(),o;if(e==null)o=null;else{let a=this.selectionAnchor?.side??t,r=this.selectionAnchor?.lineNumber??e;o=this.buildSelectionRange(r,e,a,t)}so(A??void 0,o??void 0)||(this.options.controlledSelection===!0?this.proposedSelectedRange=o:(this.selectedRange=o,this.queuedSelectionRender??(this.queuedSelectionRender=requestAnimationFrame(this.renderSelection))),this.placeUtility(),n&&this.notifySelectionChangeDelta())}getIndexesFromSelection(e,t){if(this.pre==null)return;let n=this.getLineIndex(e.start,e.side),A=this.getLineIndex(e.end,e.endSide??e.side);return n!=null&&A!=null?{start:t?n[1]:n[0],end:t?A[1]:A[0]}:void 0}notifySelectionCommitted(){this.options.onLineSelected?.(this.getCurrentSelectionRange()??null)}notifySelectionChangeDelta(){this.options.onLineSelectionChange?.(this.getCurrentSelectionRange()??null)}notifySelectionStart(e){this.options.onLineSelectionStart?.(e)}notifySelectionEnd(e){this.options.onLineSelectionEnd?.(e)}toEventBaseProps(e){return this.mode==="file"?{type:"line",lineElement:e.lineElement,lineNumber:e.lineNumber,numberColumn:e.numberColumn,numberElement:e.numberElement}:{type:"diff-line",annotationSide:e.side,lineType:e.lineType,lineElement:e.lineElement,numberElement:e.numberElement,lineNumber:e.lineNumber,numberColumn:e.numberColumn}}toTokenEventBaseProps({lineCharEnd:e,lineCharStart:t,lineNumber:n,side:A,tokenElement:o,tokenText:a}){return this.mode==="file"?{type:"token",lineCharEnd:e,lineCharStart:t,lineNumber:n,tokenElement:o,tokenText:a}:{type:"token",lineCharEnd:e,lineCharStart:t,lineNumber:n,side:A,tokenElement:o,tokenText:a}}buildSelectedLineRange(e,t){return this.buildSelectionRange(e.lineNumber,t.lineNumber,e.side,t.side)}buildSelectionRange(e,t,n,A){return{start:e,end:t,...n!=null?{side:n}:{},...n!==A&&A!=null?{endSide:A}:{}}}resolvePointerTarget(e){let t=!1,n,A,o,a,r,s,i,c,d,u;for(let p of e){if(!(p instanceof HTMLElement))continue;if(u==null&&p.hasAttribute("data-merge-conflict-action")){let h=p.getAttribute("data-merge-conflict-action")??void 0,f=p.getAttribute("data-merge-conflict-conflict-index")??void 0,b=f!=null?Number.parseInt(f,10):NaN;Pl(h)&&Number.isFinite(b)&&(u={kind:"merge-conflict-action",resolution:h,conflictIndex:b})}if(s==null&&p.hasAttribute("data-char")){s=p;let h=p.getAttribute("data-char");if(h!=null){let f=Number.parseInt(h,10);if(!Number.isNaN(f)){let b=p.textContent??"",C=f+b.length;(b.trim()!==""||this.options.enableTokenInteractionsOnWhitespace===!0)&&(i={tokenElement:s,lineCharStart:f,lineCharEnd:C,tokenText:b});continue}}}let l=r==null?p.getAttribute("data-column-number")??void 0:void 0;if(l!=null){r=p,d=Number.parseInt(l,10),t=!0,n=di(p),a=p.getAttribute("data-line-index")??void 0;continue}let B=o==null?p.getAttribute("data-line")??void 0:void 0;if(B!=null){o=p,d=Number.parseInt(B,10),n=di(p),a=p.getAttribute("data-line-index")??void 0;continue}if(c==null&&(p.hasAttribute("data-expand-button")||p.hasAttribute("data-unmodified-lines"))){c={hunkIndex:void 0,direction:p.hasAttribute("data-expand-up")?"up":p.hasAttribute("data-expand-down")?"down":"both",all:p.hasAttribute("data-expand-all-button")};continue}let E=c!=null?p.getAttribute("data-expand-index")??void 0:void 0;if(c!=null&&E!=null){let h=Number.parseInt(E,10);Number.isNaN(h)||(c.hunkIndex=h);continue}if(A==null&&p.hasAttribute("data-code")){A=p;break}}if(u!=null)return u;if(c?.hunkIndex!=null)return{type:"line-info",hunkIndex:c.hunkIndex,direction:c.direction,all:c.all};if(o??(o=a!=null?ii(A,`[data-line][data-line-index="${a}"]`):void 0),r??(r=a!=null?ii(A,`[data-column-number][data-line-index="${a}"]`):void 0),A==null||o==null||r==null||n==null||d==null||Number.isNaN(d))return;let g=this.parseLineIndex(o,this.isSplitDiff());return i!=null?this.mode==="file"?{kind:"token",lineType:n,lineElement:o,lineNumber:d,numberColumn:t,numberElement:r,side:void 0,splitLineIndex:g,...i}:{kind:"token",lineType:n,lineElement:o,lineNumber:d,numberColumn:t,numberElement:r,side:ci(n,A),splitLineIndex:g,...i}:this.mode==="file"?{kind:"line",lineType:n,lineElement:o,lineNumber:d,numberColumn:t,numberElement:r,side:void 0,splitLineIndex:g}:{kind:"line",lineType:n,lineElement:o,lineNumber:d,numberColumn:t,numberElement:r,side:ci(n,A),splitLineIndex:g}}isSplitDiff(){return this.pre?.getAttribute("data-diff-type")==="split"}parseLineIndex(e,t){let n=(e.getAttribute("data-line-index")??"").split(",").map(A=>Number.parseInt(A,10)).filter(A=>!Number.isNaN(A));if(t&&n.length===2)return n[1];if(!t)return n[0]}};function wo({enableTokenInteractionsOnWhitespace:e,enableGutterUtility:t,lineHoverHighlight:n,onGutterUtilityClick:A,onLineClick:o,onLineEnter:a,onLineLeave:r,onLineNumberClick:s,onTokenClick:i,onTokenEnter:c,onTokenLeave:d,renderGutterUtility:u,__debugPointerEvents:g,enableLineSelection:p,controlledSelection:l,onLineSelected:B,onLineSelectionStart:E,onLineSelectionChange:h,onLineSelectionEnd:f},b,C,Q){return{enableTokenInteractionsOnWhitespace:e,enableGutterUtility:Hl({enableGutterUtility:t,renderGutterUtility:u,onGutterUtilityClick:A}),usesCustomGutterUtility:u!=null,lineHoverHighlight:n,onGutterUtilityClick:A,onHunkExpand:b,onMergeConflictActionClick:Q,onLineClick:o,onLineEnter:a,onLineLeave:r,onLineNumberClick:s,onTokenClick:i,onTokenEnter:c,onTokenLeave:d,__debugPointerEvents:g,enableLineSelection:p,controlledSelection:l,onLineSelected:B,onLineSelectionStart:E,onLineSelectionChange:h,onLineSelectionEnd:f,getLineIndex:C}}function Hl({enableGutterUtility:e,renderGutterUtility:t,onGutterUtilityClick:n}){if(n!=null&&t!=null)throw new Error("Cannot use both 'onGutterUtilityClick' and 'renderGutterUtility'. Use only one gutter utility API.");return e??!1}function Jt(e){return e!=null&&"kind"in e&&e.kind==="line"}function Jn(e){return e!=null&&"kind"in e&&e.kind==="token"}function Eo(e){return Jt(e)||Jn(e)}function jl(e){return"type"in e&&e.type==="line-info"}function Ul(e){return"kind"in e&&e.kind==="merge-conflict-action"}function Pl(e){return e==="current"||e==="incoming"||e==="both"}function ii(e,t){let n=e?.querySelector(t);return n instanceof HTMLElement?n:void 0}function Kn(e){let t=[],n=e;for(;n!=null;)t.push(n),n=n.parentNode;return t}function $l(e){let t=e.closest("[data-line], [data-column-number]");if(t instanceof HTMLElement)return t;let n=e.closest('[data-line-annotation], [data-gutter-buffer="annotation"]');if(!(n instanceof HTMLElement))return;let A=n.previousElementSibling;return A instanceof HTMLElement&&(A.hasAttribute("data-line")||A.hasAttribute("data-column-number"))?A:void 0}function ql(e){let t=e.closest('[slot^="annotation-"]');if(t instanceof HTMLElement)return t.getAttribute("slot")??void 0;if(e instanceof HTMLElement){let n=e.getAttribute("name")??void 0;return n!=null&&n.startsWith("annotation-")?n:void 0}}function Yl(e){if(e==null)return;let t=/^annotation-(?:(additions|deletions)-)?(\d+)$/.exec(e);if(t==null)return;let n=Number.parseInt(t[2],10);if(Number.isFinite(n))return{lineNumber:n,side:t[1]}}function si(e){return e!=null&&typeof e.elementFromPoint=="function"}function ci(e,t){switch(e){case"change-deletion":return"deletions";case"change-addition":return"additions";default:return t.hasAttribute("data-deletions")?"deletions":"additions"}}function di(e){let t=e.getAttribute("data-line-type");if(t!=null)switch(t){case"change-deletion":case"change-addition":case"context":case"context-expanded":return t;default:return}}function On(e){for(let t of e)if(t instanceof HTMLElement&&(t.hasAttribute("data-utility-button")||t.hasAttribute("data-gutter-utility-slot")||t.getAttribute("slot")==="gutter-utility-slot"||t.getAttribute("name")==="gutter-utility-slot"))return!0;return!1}function Me(e="none",t,...n){switch(e){case"none":return;case"both":break;case"click":if(t!=="click")return;break;case"move":if(t!=="move")return;break}console.log(...n)}var ae,gi=(ae=class{constructor(){m(this,"observedNodes",new Map);m(this,"applyColumnUpdates",t=>{for(let[n,A]of t){let o=A.codeInlineSize!=null?Tl(A.codeInlineSize):n.codeWidth,a=A.numberInlineSize!=null?Kl(A.numberInlineSize):n.numberWidth,r=o!==n.codeWidth,s=a!==n.numberWidth;if(!(!r&&!s)&&(n.codeWidth=o,n.numberWidth=a,r&&n.codeElement.style.setProperty("--diffs-column-width",`${typeof o=="number"?`${o}px`:"auto"}`),s&&n.codeElement.style.setProperty("--diffs-column-number-width",`${a===0?"auto":`${a}px`}`),r||s&&o!=="auto")){let i=typeof o=="number"?Math.max(o-a,0):0;n.codeElement.style.setProperty("--diffs-column-content-width",`${i>0?`${i}px`:"auto"}`)}}})}static getResizeObserver(){let t=ae.resizeObserver??new ResizeObserver(ae.handleSharedResizeEntries);return ae.resizeObserver=t,t}static handleSharedResizeEntries(t){let n=new Map;for(let A of t){let o=ae.managersByElement.get(A.target);if(o==null)continue;let a=n.get(o);a==null?n.set(o,[A]):a.push(A)}for(let[A,o]of n)A.handleResizeEntries(o)}setup(t,n){let A=new Set,o=0,a=new Map(this.observedNodes);this.observedNodes.clear();for(let r of t.children){if(o===2)break;let s=(()=>{if(r instanceof HTMLElement&&r.tagName==="CODE")return r})();if(s==null)continue;o++;let i=a.get(s);if(i!=null&&i.type!=="code")throw new Error("ResizeManager.setup: somehow a code node is being used for an annotation, should be impossible");let c=s.firstElementChild;c instanceof HTMLElement||(c=null),i!=null?(this.observedNodes.set(s,i),a.delete(s),i.numberElement!==c?(i.numberElement!=null&&(this.unobserve(i.numberElement),a.delete(i.numberElement)),c!=null&&(this.observe(c),a.delete(c),this.observedNodes.set(c,i)),i.numberElement=c,i.numberWidth=0):i.numberElement!=null?(a.delete(i.numberElement),this.observedNodes.set(i.numberElement,i)):i.numberWidth=0):(i={type:"code",codeElement:s,numberElement:c,codeWidth:"auto",numberWidth:0},this.observedNodes.set(s,i),this.observe(s),c!=null&&(this.observedNodes.set(c,i),this.observe(c)))}if(o>1&&!n){let r=t.querySelectorAll('[data-line-annotation*=","]'),s=new Map;for(let i of r){if(!(i instanceof HTMLElement))continue;let c=i.getAttribute("data-line-annotation")??"";if(!/^\d+,\d+$/.test(c)){console.error("DiffFileRenderer.setupResizeObserver: Invalid element or annotation",{lineAnnotation:c,element:i});continue}let d=s.get(c);d==null&&(d=[],s.set(c,d)),d.push(i)}for(let[i,c]of s){if(c.length!==2){console.error("DiffFileRenderer.setupResizeObserver: Bad Pair",i,c);continue}let[d,u]=c,g=d.firstElementChild,p=u.firstElementChild;if(!(d instanceof HTMLElement)||!(u instanceof HTMLElement)||!(g instanceof HTMLElement)||!(p instanceof HTMLElement))continue;let l=a.get(g);if(l!=null){this.observedNodes.set(g,l),this.observedNodes.set(p,l),a.delete(g),a.delete(p);continue}let B=g.getBoundingClientRect().height,E=p.getBoundingClientRect().height;l={type:"annotations",column1:{container:d,child:g,childHeight:B},column2:{container:u,child:p,childHeight:E},currentHeight:"auto"},A.add({child1:g,child2:p,item:l,newHeight:Math.max(B,E)})}for(let i of A)this.applyNewHeight(i.item,i.newHeight),this.observedNodes.set(i.child1,i.item),this.observedNodes.set(i.child2,i.item),this.observe(i.child1),this.observe(i.child2);A.clear()}for(let[r,s]of a)this.unobserve(r),s.type==="code"?Ol(s):Jl(s);a.clear()}cleanUp(){for(let t of this.observedNodes.keys())this.unobserve(t);this.observedNodes.clear()}observe(t){let{managersByElement:n}=ae,A=n.get(t);if(A!==this){if(A!=null&&A!==this)throw new Error("ResizeManager.observe: element is already owned by another ResizeManager");n.set(t,this),ae.getResizeObserver().observe(t)}}unobserve(t){let{managersByElement:n,resizeObserver:A}=ae,o=n.get(t);if(o!=null){if(o!==this)throw new Error("ResizeManager.unobserve: element is owned by another ResizeManager");n.delete(t),A?.unobserve(t),A!=null&&n.size===0&&(A.disconnect(),ae.resizeObserver=void 0)}}handleResizeEntries(t){let n=new Map,A=new Set;for(let o of t){let{target:a,borderBoxSize:r,contentBoxSize:s}=o;if(!(a instanceof HTMLElement)){console.error("ResizeManager.handleResizeEntries: Invalid element for ResizeObserver",o);continue}let i=this.observedNodes.get(a);if(i==null){console.error("ResizeManager.handleResizeEntries: Not a valid observed node",o);continue}if(i.type==="annotations"){let c=(()=>{if(a===i.column1.child)return i.column1;if(a===i.column2.child)return i.column2})();if(c==null){console.error("ResizeManager.handleResizeEntries: Couldn't find a column for",{item:i,target:a});continue}c.childHeight=r[0].blockSize,A.add(i)}else if(i.type==="code"){let c=n.get(i)??{},d=s[0].inlineSize;a===i.codeElement?c.codeInlineSize=d:a===i.numberElement&&(c.numberInlineSize=d),n.set(i,c)}}this.applyAnnotationUpdates(A),A.clear(),this.applyColumnUpdates(n),n.clear()}applyAnnotationUpdates(t){for(let n of t)this.applyNewHeight(n,Math.max(n.column1.childHeight,n.column2.childHeight))}applyNewHeight(t,n){n!==t.currentHeight&&(t.currentHeight=Math.max(n,0),t.column1.container.style.setProperty("--diffs-annotation-min-height",`${t.currentHeight}px`),t.column2.container.style.setProperty("--diffs-annotation-min-height",`${t.currentHeight}px`))}},m(ae,"resizeObserver"),m(ae,"managersByElement",new Map),ae);function Tl(e){let t=Math.max(Math.floor(e),0);return t===0?"auto":t}function Kl(e){return Math.max(Math.ceil(e),0)}function Ol(e){e.codeElement.isConnected&&(e.codeElement.style.removeProperty("--diffs-column-content-width"),e.codeElement.style.removeProperty("--diffs-column-number-width"),e.codeElement.style.removeProperty("--diffs-column-width"))}function Jl(e){e.column1.container.isConnected&&e.column1.container.style.removeProperty("--diffs-annotation-min-height"),e.column2.container.isConnected&&e.column2.container.style.removeProperty("--diffs-annotation-min-height")}var Ke=new Map,Wn=new Map,pi=new Map,Wt=new Set;function Qo(e){for(let t of Array.isArray(e)?e:[e])if(!(t==="text"||t==="ansi")&&!Wt.has(t))return!1;return!0}function yo(e,t){e=Array.isArray(e)?e:[e];for(let n of e){if(Wt.has(n.name))continue;let A=Ke.get(n.name);A==null&&(A=n,Ke.set(n.name,A)),Wt.add(A.name),t.loadLanguageSync(A.data)}}function zn(){return typeof WorkerGlobalScope<"u"&&typeof self<"u"&&self instanceof WorkerGlobalScope}var $=class extends Error{constructor(t){super(t),this.name="ShikiError"}};function Wl(e){return So(e)}function So(e){return Array.isArray(e)?zl(e):e instanceof RegExp?e:typeof e=="object"?Zl(e):e}function zl(e){let t=[];for(let n=0,A=e.length;n{for(let A in n)e[A]=n[A]}),e}function Qi(e){let t=~e.lastIndexOf("/")||~e.lastIndexOf("\\");return t===0?e:~t===e.length-1?Qi(e.substring(0,e.length-1)):e.substr(~t+1)}var ko=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,Zn=class{static hasCaptures(e){return e===null?!1:(ko.lastIndex=0,ko.test(e))}static replaceCaptures(e,t,n){return e.replace(ko,(A,o,a,r)=>{let s=n[parseInt(o||a,10)];if(s){let i=t.substring(s.start,s.end);for(;i[0]===".";)i=i.substring(1);switch(r){case"downcase":return i.toLowerCase();case"upcase":return i.toUpperCase();default:return i}}else return A})}};function yi(e,t){return et?1:0}function ki(e,t){if(e===null&&t===null)return 0;if(!e)return-1;if(!t)return 1;let n=e.length,A=t.length;if(n===A){for(let o=0;othis._root.match(e)));this._colorMap=e,this._defaults=t,this._root=n}static createFromRawTheme(e,t){return this.createFromParsedTheme(em(e),t)}static createFromParsedTheme(e,t){return nm(e,t)}getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(e===null)return this._defaults;let t=e.scopeName,A=this._cachedMatchRoot.get(t).find(o=>Vl(e.parent,o.parentScopes));return A?new Di(A.fontStyle,A.foreground,A.background):null}},Io=class Vn{constructor(t,n){this.parent=t,this.scopeName=n}static push(t,n){for(let A of n)t=new Vn(t,A);return t}static from(...t){let n=null;for(let A=0;A"){if(n===t.length-1)return!1;A=t[++n],o=!0}for(;e&&!Xl(e.scopeName,A);){if(o)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function Xl(e,t){return t===e||e.startsWith(t)&&e[t.length]==="."}var Di=class{constructor(e,t,n){this.fontStyle=e,this.foregroundId=t,this.backgroundId=n}};function em(e){if(!e)return[];if(!e.settings||!Array.isArray(e.settings))return[];let t=e.settings,n=[],A=0;for(let o=0,a=t.length;o1&&(E=l.slice(0,l.length-1),E.reverse()),n[A++]=new tm(B,E,o,i,c,d)}}return n}var tm=class{constructor(e,t,n,A,o,a){this.scope=e,this.parentScopes=t,this.index=n,this.fontStyle=A,this.foreground=o,this.background=a}},te=(e=>(e[e.NotSet=-1]="NotSet",e[e.None=0]="None",e[e.Italic=1]="Italic",e[e.Bold=2]="Bold",e[e.Underline=4]="Underline",e[e.Strikethrough=8]="Strikethrough",e))(te||{});function nm(e,t){e.sort((i,c)=>{let d=yi(i.scope,c.scope);return d!==0||(d=ki(i.parentScopes,c.parentScopes),d!==0)?d:i.index-c.index});let n=0,A="#000000",o="#ffffff";for(;e.length>=1&&e[0].scope==="";){let i=e.shift();i.fontStyle!==-1&&(n=i.fontStyle),i.foreground!==null&&(A=i.foreground),i.background!==null&&(o=i.background)}let a=new Am(t),r=new Di(n,a.getId(A),a.getId(o)),s=new am(new Do(0,null,-1,0,0),[]);for(let i=0,c=e.length;it?console.log("how did this happen?"):this.scopeDepth=t,n!==-1&&(this.fontStyle=n),A!==0&&(this.foreground=A),o!==0&&(this.background=o)}},am=class Fo{constructor(t,n=[],A={}){m(this,"_rulesWithParentScopes");this._mainRule=t,this._children=A,this._rulesWithParentScopes=n}static _cmpBySpecificity(t,n){if(t.scopeDepth!==n.scopeDepth)return n.scopeDepth-t.scopeDepth;let A=0,o=0;for(;t.parentScopes[A]===">"&&A++,n.parentScopes[o]===">"&&o++,!(A>=t.parentScopes.length||o>=n.parentScopes.length);){let a=n.parentScopes[o].length-t.parentScopes[A].length;if(a!==0)return a;A++,o++}return n.parentScopes.length-t.parentScopes.length}match(t){if(t!==""){let A=t.indexOf("."),o,a;if(A===-1?(o=t,a=""):(o=t.substring(0,A),a=t.substring(A+1)),this._children.hasOwnProperty(o))return this._children[o].match(a)}let n=this._rulesWithParentScopes.concat(this._mainRule);return n.sort(Fo._cmpBySpecificity),n}insert(t,n,A,o,a,r){if(n===""){this._doInsertHere(t,A,o,a,r);return}let s=n.indexOf("."),i,c;s===-1?(i=n,c=""):(i=n.substring(0,s),c=n.substring(s+1));let d;this._children.hasOwnProperty(i)?d=this._children[i]:(d=new Fo(this._mainRule.clone(),Do.cloneArr(this._rulesWithParentScopes)),this._children[i]=d),d.insert(t+1,c,A,o,a,r)}_doInsertHere(t,n,A,o,a){if(n===null){this._mainRule.acceptOverwrite(t,A,o,a);return}for(let r=0,s=this._rulesWithParentScopes.length;r>>0}static getTokenType(t){return(t&768)>>>8}static containsBalancedBrackets(t){return(t&1024)!==0}static getFontStyle(t){return(t&30720)>>>11}static getForeground(t){return(t&16744448)>>>15}static getBackground(t){return(t&4278190080)>>>24}static set(t,n,A,o,a,r,s){let i=le.getLanguageId(t),c=le.getTokenType(t),d=le.containsBalancedBrackets(t)?1:0,u=le.getFontStyle(t),g=le.getForeground(t),p=le.getBackground(t);return n!==0&&(i=n),A!==8&&(c=A),o!==null&&(d=o?1:0),a!==-1&&(u=a),r!==0&&(g=r),s!==0&&(p=s),(i<<0|c<<8|d<<10|u<<11|g<<15|p<<24)>>>0}};function eA(e,t){let n=[],A=rm(e),o=A.next();for(;o!==null;){let i=0;if(o.length===2&&o.charAt(1)===":"){switch(o.charAt(0)){case"R":i=1;break;case"L":i=-1;break;default:console.log(`Unknown priority ${o} in scope selector`)}o=A.next()}let c=r();if(n.push({matcher:c,priority:i}),o!==",")break;o=A.next()}return n;function a(){if(o==="-"){o=A.next();let i=a();return c=>!!i&&!i(c)}if(o==="("){o=A.next();let i=s();return o===")"&&(o=A.next()),i}if(mi(o)){let i=[];do i.push(o),o=A.next();while(mi(o));return c=>t(i,c)}return null}function r(){let i=[],c=a();for(;c;)i.push(c),c=a();return d=>i.every(u=>u(d))}function s(){let i=[],c=r();for(;c&&(i.push(c),o==="|"||o===",");){do o=A.next();while(o==="|"||o===",");c=r()}return d=>i.some(u=>u(d))}}function mi(e){return!!e&&!!e.match(/[\w\.:]+/)}function rm(e){let t=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,n=t.exec(e);return{next:()=>{if(!n)return null;let A=n[0];return n=t.exec(e),A}}}function vi(e){typeof e.dispose=="function"&&e.dispose()}var Xt=class{constructor(e){this.scopeName=e}toKey(){return this.scopeName}},im=class{constructor(e,t){this.scopeName=e,this.ruleName=t}toKey(){return`${this.scopeName}#${this.ruleName}`}},sm=class{constructor(){m(this,"_references",[]);m(this,"_seenReferenceKeys",new Set);m(this,"visitedRule",new Set)}get references(){return this._references}add(e){let t=e.toKey();this._seenReferenceKeys.has(t)||(this._seenReferenceKeys.add(t),this._references.push(e))}},cm=class{constructor(e,t){m(this,"seenFullScopeRequests",new Set);m(this,"seenPartialScopeRequests",new Set);m(this,"Q");this.repo=e,this.initialScopeName=t,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new Xt(this.initialScopeName)]}processQueue(){let e=this.Q;this.Q=[];let t=new sm;for(let n of e)dm(n,this.initialScopeName,this.repo,t);for(let n of t.references)if(n instanceof Xt){if(this.seenFullScopeRequests.has(n.scopeName))continue;this.seenFullScopeRequests.add(n.scopeName),this.Q.push(n)}else{if(this.seenFullScopeRequests.has(n.scopeName)||this.seenPartialScopeRequests.has(n.toKey()))continue;this.seenPartialScopeRequests.add(n.toKey()),this.Q.push(n)}}};function dm(e,t,n,A){let o=n.lookup(e.scopeName);if(!o){if(e.scopeName===t)throw new Error(`No grammar provided for <${t}>`);return}let a=n.lookup(t);e instanceof Xt?Xn({baseGrammar:a,selfGrammar:o},A):vo(e.ruleName,{baseGrammar:a,selfGrammar:o,repository:o.repository},A);let r=n.injections(e.scopeName);if(r)for(let s of r)A.add(new Xt(s))}function vo(e,t,n){if(t.repository&&t.repository[e]){let A=t.repository[e];tA([A],t,n)}}function Xn(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&tA(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&tA(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function tA(e,t,n){for(let A of e){if(n.visitedRule.has(A))continue;n.visitedRule.add(A);let o=A.repository?wi({},t.repository,A.repository):t.repository;Array.isArray(A.patterns)&&tA(A.patterns,{...t,repository:o},n);let a=A.include;if(!a)continue;let r=xi(a);switch(r.kind){case 0:Xn({...t,selfGrammar:t.baseGrammar},n);break;case 1:Xn(t,n);break;case 2:vo(r.ruleName,{...t,repository:o},n);break;case 3:case 4:let s=r.scopeName===t.selfGrammar.scopeName?t.selfGrammar:r.scopeName===t.baseGrammar.scopeName?t.baseGrammar:void 0;if(s){let i={baseGrammar:t.baseGrammar,selfGrammar:s,repository:o};r.kind===4?vo(r.ruleName,i,n):Xn(i,n)}else r.kind===4?n.add(new im(r.scopeName,r.ruleName)):n.add(new Xt(r.scopeName));break}}}var um=class{constructor(){m(this,"kind",0)}},gm=class{constructor(){m(this,"kind",1)}},pm=class{constructor(e){m(this,"kind",2);this.ruleName=e}},lm=class{constructor(e){m(this,"kind",3);this.scopeName=e}},mm=class{constructor(e,t){m(this,"kind",4);this.scopeName=e,this.ruleName=t}};function xi(e){if(e==="$base")return new um;if(e==="$self")return new gm;let t=e.indexOf("#");if(t===-1)return new lm(e);if(t===0)return new pm(e.substring(1));{let n=e.substring(0,t),A=e.substring(t+1);return new mm(n,A)}}var fm=/\\(\d+)/,fi=/\\(\d+)/g;var bm=-1,Mi=-2;var nn=class{constructor(e,t,n,A){m(this,"$location");m(this,"id");m(this,"_nameIsCapturing");m(this,"_name");m(this,"_contentNameIsCapturing");m(this,"_contentName");this.$location=e,this.id=t,this._name=n||null,this._nameIsCapturing=Zn.hasCaptures(this._name),this._contentName=A||null,this._contentNameIsCapturing=Zn.hasCaptures(this._contentName)}get debugName(){let e=this.$location?`${Qi(this.$location.filename)}:${this.$location.line}`:"unknown";return`${this.constructor.name}#${this.id} @ ${e}`}getName(e,t){return!this._nameIsCapturing||this._name===null||e===null||t===null?this._name:Zn.replaceCaptures(this._name,e,t)}getContentName(e,t){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:Zn.replaceCaptures(this._contentName,e,t)}},Bm=class extends nn{constructor(t,n,A,o,a){super(t,n,A,o);m(this,"retokenizeCapturedWithRuleId");this.retokenizeCapturedWithRuleId=a}dispose(){}collectPatterns(t,n){throw new Error("Not supported!")}compile(t,n){throw new Error("Not supported!")}compileAG(t,n,A,o){throw new Error("Not supported!")}},hm=class extends nn{constructor(t,n,A,o,a){super(t,n,A,null);m(this,"_match");m(this,"captures");m(this,"_cachedCompiledPatterns");this._match=new en(o,this.id),this.captures=a,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(t,n){n.push(this._match)}compile(t,n){return this._getCachedCompiledPatterns(t).compile(t)}compileAG(t,n,A,o){return this._getCachedCompiledPatterns(t).compileAG(t,A,o)}_getCachedCompiledPatterns(t){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new tn,this.collectPatterns(t,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},bi=class extends nn{constructor(t,n,A,o,a){super(t,n,A,o);m(this,"hasMissingPatterns");m(this,"patterns");m(this,"_cachedCompiledPatterns");this.patterns=a.patterns,this.hasMissingPatterns=a.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}collectPatterns(t,n){for(let A of this.patterns)t.getRule(A).collectPatterns(t,n)}compile(t,n){return this._getCachedCompiledPatterns(t).compile(t)}compileAG(t,n,A,o){return this._getCachedCompiledPatterns(t).compileAG(t,A,o)}_getCachedCompiledPatterns(t){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new tn,this.collectPatterns(t,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},xo=class extends nn{constructor(t,n,A,o,a,r,s,i,c,d){super(t,n,A,o);m(this,"_begin");m(this,"beginCaptures");m(this,"_end");m(this,"endHasBackReferences");m(this,"endCaptures");m(this,"applyEndPatternLast");m(this,"hasMissingPatterns");m(this,"patterns");m(this,"_cachedCompiledPatterns");this._begin=new en(a,this.id),this.beginCaptures=r,this._end=new en(s||"\uFFFF",-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=i,this.applyEndPatternLast=c||!1,this.patterns=d.patterns,this.hasMissingPatterns=d.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(t,n){return this._end.resolveBackReferences(t,n)}collectPatterns(t,n){n.push(this._begin)}compile(t,n){return this._getCachedCompiledPatterns(t,n).compile(t)}compileAG(t,n,A,o){return this._getCachedCompiledPatterns(t,n).compileAG(t,A,o)}_getCachedCompiledPatterns(t,n){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new tn;for(let A of this.patterns)t.getRule(A).collectPatterns(t,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,n):this._cachedCompiledPatterns.setSource(0,n)),this._cachedCompiledPatterns}},nA=class extends nn{constructor(t,n,A,o,a,r,s,i,c){super(t,n,A,o);m(this,"_begin");m(this,"beginCaptures");m(this,"whileCaptures");m(this,"_while");m(this,"whileHasBackReferences");m(this,"hasMissingPatterns");m(this,"patterns");m(this,"_cachedCompiledPatterns");m(this,"_cachedCompiledWhilePatterns");this._begin=new en(a,this.id),this.beginCaptures=r,this.whileCaptures=i,this._while=new en(s,Mi),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=c.patterns,this.hasMissingPatterns=c.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null),this._cachedCompiledWhilePatterns&&(this._cachedCompiledWhilePatterns.dispose(),this._cachedCompiledWhilePatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(t,n){return this._while.resolveBackReferences(t,n)}collectPatterns(t,n){n.push(this._begin)}compile(t,n){return this._getCachedCompiledPatterns(t).compile(t)}compileAG(t,n,A,o){return this._getCachedCompiledPatterns(t).compileAG(t,A,o)}_getCachedCompiledPatterns(t){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new tn;for(let n of this.patterns)t.getRule(n).collectPatterns(t,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(t,n){return this._getCachedCompiledWhilePatterns(t,n).compile(t)}compileWhileAG(t,n,A,o){return this._getCachedCompiledWhilePatterns(t,n).compileAG(t,A,o)}_getCachedCompiledWhilePatterns(t,n){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new tn,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,n||"\uFFFF"),this._cachedCompiledWhilePatterns}},Si=class ne{static createCaptureRule(t,n,A,o,a){return t.registerRule(r=>new Bm(n,r,A,o,a))}static getCompiledRuleId(t,n,A){return t.id||n.registerRule(o=>{if(t.id=o,t.match)return new hm(t.$vscodeTextmateLocation,t.id,t.name,t.match,ne._compileCaptures(t.captures,n,A));if(typeof t.begin>"u"){t.repository&&(A=wi({},A,t.repository));let a=t.patterns;return typeof a>"u"&&t.include&&(a=[{include:t.include}]),new bi(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,ne._compilePatterns(a,n,A))}return t.while?new nA(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,ne._compileCaptures(t.beginCaptures||t.captures,n,A),t.while,ne._compileCaptures(t.whileCaptures||t.captures,n,A),ne._compilePatterns(t.patterns,n,A)):new xo(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,ne._compileCaptures(t.beginCaptures||t.captures,n,A),t.end,ne._compileCaptures(t.endCaptures||t.captures,n,A),t.applyEndPatternLast,ne._compilePatterns(t.patterns,n,A))}),t.id}static _compileCaptures(t,n,A){let o=[];if(t){let a=0;for(let r in t){if(r==="$vscodeTextmateLocation")continue;let s=parseInt(r,10);s>a&&(a=s)}for(let r=0;r<=a;r++)o[r]=null;for(let r in t){if(r==="$vscodeTextmateLocation")continue;let s=parseInt(r,10),i=0;t[r].patterns&&(i=ne.getCompiledRuleId(t[r],n,A)),o[s]=ne.createCaptureRule(n,t[r].$vscodeTextmateLocation,t[r].name,t[r].contentName,i)}}return o}static _compilePatterns(t,n,A){let o=[];if(t)for(let a=0,r=t.length;at.substring(o.start,o.end));return fi.lastIndex=0,this.source.replace(fi,(o,a)=>Ii(A[parseInt(a,10)]||""))}_buildAnchorCache(){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let t=[],n=[],A=[],o=[],a,r,s,i;for(a=0,r=this.source.length;an.source);this._cached=new Bi(e,t,this._items.map(n=>n.ruleId))}return this._cached}compileAG(e,t,n){return this._hasAnchors?t?n?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G0):n?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G0):this.compile(e)}_resolveAnchors(e,t,n){let A=this._items.map(o=>o.resolveAnchors(t,n));return new Bi(e,A,this._items.map(o=>o.ruleId))}},Bi=class{constructor(e,t,n){m(this,"scanner");this.regExps=t,this.rules=n,this.scanner=e.createOnigScanner(t)}dispose(){typeof this.scanner.dispose=="function"&&this.scanner.dispose()}toString(){let e=[];for(let t=0,n=this.rules.length;t\``.split("")]],single:[["&'".split(""),"\"&'`".split("")],["\0&'".split(""),"\0\"&'`".split("")]],double:[['"&'.split(""),"\"&'`".split("")],['\0"&'.split(""),"\0\"&'`".split("")]]};function Ai(e,t,n,A){let o=A.schema,a=o.space==="svg"?!1:A.settings.omitOptionalTags,r=o.space==="svg"?A.settings.closeEmptyElements:A.settings.voids.includes(e.tagName.toLowerCase()),s=[],i;o.space==="html"&&e.tagName==="svg"&&(A.schema=Un);let c=Dl(A,e.properties),d=A.all(o.space==="html"&&e.tagName==="template"?e.content:e);return A.schema=o,d&&(r=!1),(c||!a||!ni(e,t,n))&&(s.push("<",e.tagName,c?" "+c:""),r&&(o.space==="svg"||A.settings.closeSelfClosing)&&(i=c.charAt(c.length-1),(!A.settings.tightSelfClosing||i==="/"||i&&i!=='"'&&i!=="'")&&s.push(" "),s.push("/")),s.push(">")),s.push(d),!r&&(!a||!Ot(e,t,n))&&s.push(""),s.join("")}function Dl(e,t){let n=[],A=-1,o;if(t){for(o in t)if(t[o]!==null&&t[o]!==void 0){let a=Fl(e,o,t[o]);a&&n.push(a)}}for(;++ABo(n,e.alternative)&&(r=e.alternative),s=r+xe(n,Object.assign({},e.settings.characterReferences,{subset:(r==="'"?Yn.single:Yn.double)[o][a],attribute:!0}))+r),i+(s&&"="+s))}var vl=["<","&"];function Tn(e,t,n,A){return n&&n.type==="element"&&(n.tagName==="script"||n.tagName==="style")?e.value:xe(e.value,Object.assign({},A.settings.characterReferences,{subset:vl}))}function oi(e,t,n,A){return A.settings.allowDangerousHtml?e.value:Tn(e,t,n,A)}function ai(e,t,n,A){return A.all(e)}var ri=Hr("type",{invalid:xl,unknown:Ml,handlers:{comment:Jr,doctype:Wr,element:Ai,raw:oi,root:ai,text:Tn}});function xl(e){throw new Error("Expected node, not `"+e+"`")}function Ml(e){let t=e;throw new Error("Cannot compile unknown node `"+t.type+"`")}var Sl={},Ll={},Nl=[];function Ce(e,t){let n=t||Sl,A=n.quote||'"',o=A==='"'?"'":'"';if(A!=='"'&&A!=="'")throw new Error("Invalid quote `"+A+"`, expected `'` or `\"`");return{one:Rl,all:Gl,settings:{omitOptionalTags:n.omitOptionalTags||!1,allowParseErrors:n.allowParseErrors||!1,allowDangerousCharacters:n.allowDangerousCharacters||!1,quoteSmart:n.quoteSmart||!1,preferUnquoted:n.preferUnquoted||!1,tightAttributes:n.tightAttributes||!1,upperDoctype:n.upperDoctype||!1,tightDoctype:n.tightDoctype||!1,bogusComments:n.bogusComments||!1,tightCommaSeparatedLists:n.tightCommaSeparatedLists||!1,tightSelfClosing:n.tightSelfClosing||!1,collapseEmptyAttributes:n.collapseEmptyAttributes||!1,allowDangerousHtml:n.allowDangerousHtml||!1,voids:n.voids||xr,characterReferences:n.characterReferences||Ll,closeSelfClosing:n.closeSelfClosing||!1,closeEmptyElements:n.closeEmptyElements||!1},schema:n.space==="svg"?Un:Rr,quote:A,alternative:o}.one(Array.isArray(e)?{type:"root",children:e}:e,void 0,void 0)}function Rl(e,t,n){return ri(e,t,n,this)}function Gl(e){let t=[],n=e&&e.children||Nl,A=-1;for(;++A{let e=this.gutterUtilityLine??this.hoveredLine;if(e!=null){if(this.mode==="diff"&&e.type==="diff-line")return{lineNumber:e.lineNumber,side:e.annotationSide};if(this.mode==="file"&&e.type==="line")return{lineNumber:e.lineNumber}}});m(this,"handlePointerClick",e=>{let{onHunkExpand:t,onLineClick:n,onLineNumberClick:A,onTokenClick:o,onMergeConflictActionClick:a}=this.options;t==null&&n==null&&A==null&&a==null&&o==null||this.options.onGutterUtilityClick!=null&&On(e.composedPath())||(Me(this.options.__debugPointerEvents,"click","FileDiff.DEBUG.handlePointerClick:",e),this.handlePointerEvent({eventType:"click",event:e}))});m(this,"handlePointerMove",e=>{if(e.pointerType!=="mouse")return;let{lineHoverHighlight:t="disabled",onLineEnter:n,onLineLeave:A,onTokenEnter:o,onTokenLeave:a,enableGutterUtility:r=!1}=this.options;t==="disabled"&&!r&&n==null&&A==null&&o==null&&a==null||(Me(this.options.__debugPointerEvents,"move","FileDiff.DEBUG.handlePointerMove:",e),this.handlePointerEvent({eventType:"move",event:e}))});m(this,"handlePointerLeave",e=>{let{__debugPointerEvents:t}=this.options;if(Me(t,"move","FileDiff.DEBUG.handlePointerLeave: no event"),this.hoveredLine==null&&this.hoveredToken==null){Me(t,"move","FileDiff.DEBUG.handlePointerLeave: returned early, no hovered line or token");return}this.hoveredToken!=null&&(this.options.onTokenLeave?.(this.hoveredToken,e),this.clearHoveredToken()),this.hoveredLine!=null&&(this.options.onLineLeave?.({...this.hoveredLine,event:e}),this.clearHoveredLine()),this.placeUtility()});m(this,"handlePointerDown",e=>{if(e.pointerType==="mouse"&&e.button!==0||this.pre==null||this.pointerSession.mode!=="idle")return;let t=e.composedPath();On(t)&&this.options.onGutterUtilityClick!=null?this.startGutterSelectionFromPointerDown(e):(e.pointerType!=="mouse"&&this.revealUtilityFromGutterPath(t),this.startLineSelectionFromPointerDown(e))});m(this,"handleDocumentPointerMove",e=>{let{enableLineSelection:t=!1}=this.options;switch(this.pointerSession.mode){case"idle":return;case"gutterSelecting":{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let n=this.resolveSelectionPoint(e,{source:"coordinates-first"});if(n==null)return;this.pointerSession.current=n,t===!0&&this.updateSelection(n.lineNumber,n.side);return}case"selecting":{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let n=this.resolveSelectionInfo(e,{source:"coordinates-first",requireNumberColumn:!1});if(n==null||this.selectionAnchor==null)return;this.updateSelection(n.lineNumber,n.eventSide);return}case"pendingSingleLineUnselect":{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let n=this.resolveSelectionInfo(e,{source:"coordinates-first",requireNumberColumn:!1});if(n==null||this.selectionAnchor==null)return;let A={lineNumber:n.lineNumber,side:n.eventSide};if(vr(this.pointerSession.pending,A))return;this.updateSelection(n.lineNumber,n.eventSide,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.notifySelectionChangeDelta(),this.pointerSession={mode:"selecting",pointerId:e.pointerId};return}}});m(this,"handleDocumentPointerUp",e=>{let{enableLineSelection:t=!1,onGutterUtilityClick:n}=this.options;switch(this.pointerSession.mode){case"idle":return;case"gutterSelecting":{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();let A=this.resolveSelectionPoint(e,{source:"coordinates-first"});A!=null&&(this.pointerSession.current=A,t&&this.updateSelection(A.lineNumber,A.side)),n?.(this.buildSelectedLineRange(this.pointerSession.anchor,this.pointerSession.current)),this.selectionAnchor=void 0,t&&(this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(),this.clearProposedSelection()),this.clearPointerSession(),this.detachDocumentPointerListeners();return}case"pendingSingleLineUnselect":if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault(),this.updateSelection(null,void 0,!1),this.selectionAnchor=void 0,this.clearPendingSingleLineState(),this.detachDocumentPointerListeners(),this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(),this.clearProposedSelection();return;case"selecting":if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault(),this.selectionAnchor=void 0,this.detachDocumentPointerListeners(),this.clearPointerSession(),this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(),this.clearProposedSelection()}});m(this,"handleDocumentPointerCancel",e=>{switch(this.pointerSession.mode){case"idle":return;case"gutterSelecting":case"selecting":case"pendingSingleLineUnselect":if("pointerId"in this.pointerSession&&e.pointerId!==this.pointerSession.pointerId)return;this.selectionAnchor=void 0,this.clearProposedSelection(),this.clearPendingSingleLineState(),this.clearPointerSession(),this.detachDocumentPointerListeners()}});m(this,"renderSelection",()=>{if(this.queuedSelectionRender!=null&&(cancelAnimationFrame(this.queuedSelectionRender),this.queuedSelectionRender=void 0),this.pre==null||this.renderedSelectionRange===this.selectedRange)return;let e=this.pre.querySelectorAll("[data-selected-line]");for(let s of e)s.removeAttribute("data-selected-line");if(this.renderedSelectionRange=this.selectedRange,this.selectedRange==null)return;let{children:t}=this.pre;if(t.length===0)return;if(t.length>2)throw console.error(t),new Error("InteractionManager.renderSelection: Somehow there are more than 2 code elements...");let n=this.pre.getAttribute("data-diff-type")==="split",A=this.getIndexesFromSelection(this.selectedRange,n);if(A==null)throw console.error({rowRange:A,selectedRange:this.selectedRange}),new Error("InteractionManager.renderSelection: No valid rowRange");let o=A.start===A.end,a=Math.min(A.start,A.end),r=Math.max(A.start,A.end);for(let s of t){let[i,c]=s.children,d=c.children.length;if(d!==i.children.length)throw new Error("InteractionManager.renderSelection: gutter and content children dont match, something is wrong");for(let u=0;ur)break;if(l==null||l{let b=[];return(t==="both"||t==="click")&&(A!=null&&b.push("onLineClick"),o!=null&&b.push("onLineNumberClick"),d!=null&&b.push("expandable hunk separators"),u!=null&&b.push("merge conflict actions")),b})()),Me(t,"move","FileDiff.DEBUG.attachEventListeners: Attaching pointer move event"),Me(t,"move","FileDiff.DEBUG.attachEventListeners: Attaching pointer leave event")):!E&&this.hasPointerListeners&&(e.removeEventListener("click",this.handlePointerClick),e.removeEventListener("pointerdown",this.handlePointerDown),e.removeEventListener("pointermove",this.handlePointerMove),e.removeEventListener("pointerleave",this.handlePointerLeave),this.hasPointerListeners=!1);let h=this.pointerSession.mode==="selecting"||this.pointerSession.mode==="pendingSingleLineUnselect",f=this.pointerSession.mode==="gutterSelecting";(!p&&h||!B&&f)&&(this.clearPointerSession(),this.detachDocumentPointerListeners(),this.selectionAnchor=void 0,this.clearPendingSingleLineState())}updateInteractiveLineAttributes(){if(this.pre==null)return;let{onLineClick:e,onLineNumberClick:t,enableLineSelection:n=!1}=this.options,A=e!=null,o=t!=null||n;A&&!this.interactiveLinesAttr?(this.pre.setAttribute("data-interactive-lines",""),this.interactiveLinesAttr=!0):!A&&this.interactiveLinesAttr&&(this.pre.removeAttribute("data-interactive-lines"),this.interactiveLinesAttr=!1),o&&!this.interactiveLineNumbersAttr?(this.pre.setAttribute("data-interactive-line-numbers",""),this.interactiveLineNumbersAttr=!0):!o&&this.interactiveLineNumbersAttr&&(this.pre.removeAttribute("data-interactive-line-numbers"),this.interactiveLineNumbersAttr=!1)}startLineSelectionFromPointerDown(e){let{enableLineSelection:t=!1}=this.options;if(!t)return;let n=this.resolveSelectionInfo(e,{source:"event-path",requireNumberColumn:!0});if(n==null)return;let{pre:A}=this;if(A==null)return;e.preventDefault();let{lineNumber:o,eventSide:a,lineIndex:r}=n;if(e.shiftKey&&this.selectedRange!=null){let s=this.getIndexesFromSelection(this.selectedRange,A.getAttribute("data-diff-type")==="split");if(s==null)return;let i=s.start<=s.end?r>=s.start:r<=s.end;this.selectionAnchor={lineNumber:i?this.selectedRange.start:this.selectedRange.end,side:i?this.selectedRange.side:this.selectedRange.endSide??this.selectedRange.side},this.updateSelection(o,a,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.pointerSession={mode:"selecting",pointerId:e.pointerId},this.attachDocumentPointerListeners();return}if(this.selectedRange?.start===o&&this.selectedRange?.end===o){let s={lineNumber:o,side:a};this.selectionAnchor=s,this.pointerSession={mode:"pendingSingleLineUnselect",pointerId:e.pointerId,anchor:s,pending:s},this.attachDocumentPointerListeners();return}this.options.controlledSelection===!0?this.proposedSelectedRange=null:this.selectedRange=null,this.placeUtility(),this.selectionAnchor={lineNumber:o,side:a},this.updateSelection(o,a,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.pointerSession={mode:"selecting",pointerId:e.pointerId},this.attachDocumentPointerListeners()}startGutterSelectionFromPointerDown(e){let{enableLineSelection:t=!1,onGutterUtilityClick:n}=this.options;if(n==null)return;let A=this.currentSelectionEnds(),o=A?.bottom??this.resolveSelectionPoint(e,{source:"event-path",excludeUtility:!1}),a=A?.top??o;o==null||a==null||(e.preventDefault(),e.stopPropagation(),this.pointerSession={mode:"gutterSelecting",pointerId:e.pointerId,anchor:a,current:o},t&&(this.selectionAnchor={lineNumber:a.lineNumber,side:a.side},this.updateSelection(o.lineNumber,o.side,!1),this.notifySelectionStart(this.getCurrentSelectionRange())),this.attachDocumentPointerListeners())}clearHoveredLine(){this.hoveredLine!=null&&(this.hoveredLine.lineElement.removeAttribute("data-hovered"),this.hoveredLine.numberElement.removeAttribute("data-hovered"),this.hoveredLine=void 0)}setHoveredLine(e){let{lineHoverHighlight:t="disabled"}=this.options;this.hoveredLine!=null&&this.clearHoveredLine(),this.hoveredLine=e,t!=="disabled"&&((t==="both"||t==="line")&&this.hoveredLine.lineElement.setAttribute("data-hovered",""),(t==="both"||t==="number")&&this.hoveredLine.numberElement.setAttribute("data-hovered",""))}clearHoveredToken(){this.hoveredToken!=null&&(this.hoveredToken=void 0)}setHoveredToken(e){this.hoveredToken!=null&&this.clearHoveredToken(),this.hoveredToken=e}ensureGutterUtilityNode(e){if(this.gutterUtilityContainer==null&&(this.gutterUtilityContainer=document.createElement("div"),this.gutterUtilityContainer.setAttribute("data-gutter-utility-slot","")),e)this.gutterUtilityButton!=null&&(this.gutterUtilityButton.remove(),this.gutterUtilityButton=void 0),this.gutterUtilitySlot==null&&(this.gutterUtilitySlot=document.createElement("slot"),this.gutterUtilitySlot.name="gutter-utility-slot"),this.gutterUtilitySlot.parentNode!==this.gutterUtilityContainer&&this.gutterUtilityContainer.replaceChildren(this.gutterUtilitySlot);else{if(this.gutterUtilitySlot?.remove(),this.gutterUtilitySlot=void 0,this.gutterUtilityButton==null){let t=document.createElement("div");t.innerHTML=Ce(Fr());let n=t.firstElementChild;if(!(n instanceof HTMLButtonElement))throw new Error("InteractionManager.ensureGutterUtilityNode: Node element should be a button");n.remove(),this.gutterUtilityButton=n}this.gutterUtilityButton.parentNode!==this.gutterUtilityContainer&&this.gutterUtilityContainer.replaceChildren(this.gutterUtilityButton)}}revealUtilityFromGutterPath(e){if(this.placeUtilityFromSelection())return;let t=this.resolvePointerTarget(e);Jt(t)&&t.numberColumn&&this.showUtilityOnLine(this.toEventBaseProps(t))}placeUtility(){if(!this.placeUtilityFromSelection()){if(this.hoveredLine!=null){this.showUtilityOnLine(this.hoveredLine);return}this.hideUtility()}}placeUtilityFromSelection(){let e=this.currentSelectionEnds();if(e==null)return!1;let t=this.targetForSelectionPoint(e.bottom);return t==null?this.hideUtility():this.showUtilityOnLine(this.toEventBaseProps(t)),!0}showUtilityOnLine(e){this.gutterUtilityContainer!=null&&(this.gutterUtilityLine=e,e.numberElement.appendChild(this.gutterUtilityContainer))}hideUtility(){this.gutterUtilityContainer?.remove(),this.gutterUtilityLine=void 0}currentSelectionEnds(){let e=this.getCurrentSelectionRange();return e==null?void 0:this.selectionEnds(e)}selectionEnds(e){let t={lineNumber:e.start,side:e.side},n={lineNumber:e.end,side:e.endSide??e.side},A=this.selectionPointRowIndex(t),o=this.selectionPointRowIndex(n);if(!(A==null||o==null))return A>o?{top:n,bottom:t}:{top:t,bottom:n}}selectionPointRowIndex(e){let t=this.getLineIndex(e.lineNumber,e.side);if(t!=null)return this.isSplitDiff()?t[1]:t[0]}targetForSelectionPoint(e){if(this.pre==null)return;let t=this.getLineIndex(e.lineNumber,e.side);if(t==null)return;let n=this.mode==="diff"?`${t[0]},${t[1]}`:`${t[0]}`,A=this.pre.querySelectorAll(`[data-column-number="${e.lineNumber}"][data-line-index="${n}"]`);for(let o of A){if(!(o instanceof HTMLElement))continue;let a=this.resolvePointerTarget(Kn(o));if(Jt(a)&&!(this.mode==="diff"&&e.side!=null&&a.side!==e.side))return a}}attachDocumentPointerListeners(){this.hasDocumentPointerListeners||(document.addEventListener("pointermove",this.handleDocumentPointerMove),document.addEventListener("pointerup",this.handleDocumentPointerUp),document.addEventListener("pointercancel",this.handleDocumentPointerCancel),this.hasDocumentPointerListeners=!0)}detachDocumentPointerListeners(){this.hasDocumentPointerListeners&&(document.removeEventListener("pointermove",this.handleDocumentPointerMove),document.removeEventListener("pointerup",this.handleDocumentPointerUp),document.removeEventListener("pointercancel",this.handleDocumentPointerCancel),this.hasDocumentPointerListeners=!1)}clearPointerSession(){this.pointerSession={mode:"idle"}}clearPendingSingleLineState(){this.pointerSession.mode==="pendingSingleLineUnselect"&&(this.pointerSession={mode:"idle"})}selectionInfoFromPath(e,t){let n=this.resolvePointerTarget(e);if(Jt(n)&&!(t&&!n.numberColumn)&&n.splitLineIndex!=null)return{lineIndex:n.splitLineIndex,lineNumber:n.lineNumber,eventSide:this.mode==="diff"?n.side:void 0}}resolveSelectionInfo(e,t){let n=this.resolveSelectionPath(e,t);return n!=null?this.selectionInfoFromPath(n,t.requireNumberColumn):void 0}selectionPointFromPath(e){let t=this.resolvePointerTarget(e);if(Jt(t))return{lineNumber:t.lineNumber,side:this.mode==="diff"?t.side:void 0}}resolveSelectionPoint(e,t){let n=this.resolveSelectionPath(e,t);return n!=null?this.selectionPointFromPath(n):void 0}resolveSelectionPath(e,t){let n=t.excludeUtility!==!1;switch(t.source){case"event-path":return this.pathFromEventPath(e.composedPath(),n);case"coordinates-first":{let A=this.pathFromCoordinates(e,n);return A!==void 0?A??void 0:this.pathFromEventPath(e.composedPath(),n)}}}pathFromCoordinates(e,t){let n=this.hitTest(e);if(n!==void 0)return n===null?null:this.pathFromElement(n,t)??null}pathFromEventPath(e,t){if(!(t&&On(e))){for(let n of e)if(n instanceof Element)return this.pathFromElement(n,t)}}pathFromElement(e,t){let n=Kn(e);if(t&&On(n))return;let A=$l(e);return A!=null?Kn(A):this.pathFromAnnotationSlot(e)}pathFromAnnotationSlot(e){let t=Yl(ql(e));if(t==null)return;let n=this.targetForSelectionPoint(t);return n!=null?Kn(n.lineElement):void 0}hitTest(e){if(!Number.isFinite(e.clientX)||!Number.isFinite(e.clientY))return;let t=this.pre?.getRootNode(),n=si(t)?t:si(document)?document:void 0;if(n!=null)return n.elementFromPoint(e.clientX,e.clientY)}getLineIndex(e,t){let{getLineIndex:n}=this.options;return n!=null?n(e,t):[e-1,e-1]}getCurrentSelectionRange(){return this.proposedSelectedRange!==void 0?this.proposedSelectedRange:this.selectedRange}clearProposedSelection(){this.proposedSelectedRange=void 0}updateSelection(e,t,n=!0){let A=this.getCurrentSelectionRange(),o;if(e==null)o=null;else{let a=this.selectionAnchor?.side??t,r=this.selectionAnchor?.lineNumber??e;o=this.buildSelectionRange(r,e,a,t)}so(A??void 0,o??void 0)||(this.options.controlledSelection===!0?this.proposedSelectedRange=o:(this.selectedRange=o,this.queuedSelectionRender??(this.queuedSelectionRender=requestAnimationFrame(this.renderSelection))),this.placeUtility(),n&&this.notifySelectionChangeDelta())}getIndexesFromSelection(e,t){if(this.pre==null)return;let n=this.getLineIndex(e.start,e.side),A=this.getLineIndex(e.end,e.endSide??e.side);return n!=null&&A!=null?{start:t?n[1]:n[0],end:t?A[1]:A[0]}:void 0}notifySelectionCommitted(){this.options.onLineSelected?.(this.getCurrentSelectionRange()??null)}notifySelectionChangeDelta(){this.options.onLineSelectionChange?.(this.getCurrentSelectionRange()??null)}notifySelectionStart(e){this.options.onLineSelectionStart?.(e)}notifySelectionEnd(e){this.options.onLineSelectionEnd?.(e)}toEventBaseProps(e){return this.mode==="file"?{type:"line",lineElement:e.lineElement,lineNumber:e.lineNumber,numberColumn:e.numberColumn,numberElement:e.numberElement}:{type:"diff-line",annotationSide:e.side,lineType:e.lineType,lineElement:e.lineElement,numberElement:e.numberElement,lineNumber:e.lineNumber,numberColumn:e.numberColumn}}toTokenEventBaseProps({lineCharEnd:e,lineCharStart:t,lineNumber:n,side:A,tokenElement:o,tokenText:a}){return this.mode==="file"?{type:"token",lineCharEnd:e,lineCharStart:t,lineNumber:n,tokenElement:o,tokenText:a}:{type:"token",lineCharEnd:e,lineCharStart:t,lineNumber:n,side:A,tokenElement:o,tokenText:a}}buildSelectedLineRange(e,t){return this.buildSelectionRange(e.lineNumber,t.lineNumber,e.side,t.side)}buildSelectionRange(e,t,n,A){return{start:e,end:t,...n!=null?{side:n}:{},...n!==A&&A!=null?{endSide:A}:{}}}resolvePointerTarget(e){let t=!1,n,A,o,a,r,s,i,c,d,u;for(let p of e){if(!(p instanceof HTMLElement))continue;if(u==null&&p.hasAttribute("data-merge-conflict-action")){let h=p.getAttribute("data-merge-conflict-action")??void 0,f=p.getAttribute("data-merge-conflict-conflict-index")??void 0,b=f!=null?Number.parseInt(f,10):Number.NaN;Pl(h)&&Number.isFinite(b)&&(u={kind:"merge-conflict-action",resolution:h,conflictIndex:b})}if(s==null&&p.hasAttribute("data-char")){s=p;let h=p.getAttribute("data-char");if(h!=null){let f=Number.parseInt(h,10);if(!Number.isNaN(f)){let b=p.textContent??"",C=f+b.length;(b.trim()!==""||this.options.enableTokenInteractionsOnWhitespace===!0)&&(i={tokenElement:s,lineCharStart:f,lineCharEnd:C,tokenText:b});continue}}}let l=r==null?p.getAttribute("data-column-number")??void 0:void 0;if(l!=null){r=p,d=Number.parseInt(l,10),t=!0,n=di(p),a=p.getAttribute("data-line-index")??void 0;continue}let B=o==null?p.getAttribute("data-line")??void 0:void 0;if(B!=null){o=p,d=Number.parseInt(B,10),n=di(p),a=p.getAttribute("data-line-index")??void 0;continue}if(c==null&&(p.hasAttribute("data-expand-button")||p.hasAttribute("data-unmodified-lines"))){c={hunkIndex:void 0,direction:p.hasAttribute("data-expand-up")?"up":p.hasAttribute("data-expand-down")?"down":"both",all:p.hasAttribute("data-expand-all-button")};continue}let E=c!=null?p.getAttribute("data-expand-index")??void 0:void 0;if(c!=null&&E!=null){let h=Number.parseInt(E,10);Number.isNaN(h)||(c.hunkIndex=h);continue}if(A==null&&p.hasAttribute("data-code")){A=p;break}}if(u!=null)return u;if(c?.hunkIndex!=null)return{type:"line-info",hunkIndex:c.hunkIndex,direction:c.direction,all:c.all};if(o??(o=a!=null?ii(A,`[data-line][data-line-index="${a}"]`):void 0),r??(r=a!=null?ii(A,`[data-column-number][data-line-index="${a}"]`):void 0),A==null||o==null||r==null||n==null||d==null||Number.isNaN(d))return;let g=this.parseLineIndex(o,this.isSplitDiff());return i!=null?this.mode==="file"?{kind:"token",lineType:n,lineElement:o,lineNumber:d,numberColumn:t,numberElement:r,side:void 0,splitLineIndex:g,...i}:{kind:"token",lineType:n,lineElement:o,lineNumber:d,numberColumn:t,numberElement:r,side:ci(n,A),splitLineIndex:g,...i}:this.mode==="file"?{kind:"line",lineType:n,lineElement:o,lineNumber:d,numberColumn:t,numberElement:r,side:void 0,splitLineIndex:g}:{kind:"line",lineType:n,lineElement:o,lineNumber:d,numberColumn:t,numberElement:r,side:ci(n,A),splitLineIndex:g}}isSplitDiff(){return this.pre?.getAttribute("data-diff-type")==="split"}parseLineIndex(e,t){let n=(e.getAttribute("data-line-index")??"").split(",").map(A=>Number.parseInt(A,10)).filter(A=>!Number.isNaN(A));if(t&&n.length===2)return n[1];if(!t)return n[0]}};function wo({enableTokenInteractionsOnWhitespace:e,enableGutterUtility:t,lineHoverHighlight:n,onGutterUtilityClick:A,onLineClick:o,onLineEnter:a,onLineLeave:r,onLineNumberClick:s,onTokenClick:i,onTokenEnter:c,onTokenLeave:d,renderGutterUtility:u,__debugPointerEvents:g,enableLineSelection:p,controlledSelection:l,onLineSelected:B,onLineSelectionStart:E,onLineSelectionChange:h,onLineSelectionEnd:f},b,C,Q){return{enableTokenInteractionsOnWhitespace:e,enableGutterUtility:Hl({enableGutterUtility:t,renderGutterUtility:u,onGutterUtilityClick:A}),usesCustomGutterUtility:u!=null,lineHoverHighlight:n,onGutterUtilityClick:A,onHunkExpand:b,onMergeConflictActionClick:Q,onLineClick:o,onLineEnter:a,onLineLeave:r,onLineNumberClick:s,onTokenClick:i,onTokenEnter:c,onTokenLeave:d,__debugPointerEvents:g,enableLineSelection:p,controlledSelection:l,onLineSelected:B,onLineSelectionStart:E,onLineSelectionChange:h,onLineSelectionEnd:f,getLineIndex:C}}function Hl({enableGutterUtility:e,renderGutterUtility:t,onGutterUtilityClick:n}){if(n!=null&&t!=null)throw new Error("Cannot use both 'onGutterUtilityClick' and 'renderGutterUtility'. Use only one gutter utility API.");return e??!1}function Jt(e){return e!=null&&"kind"in e&&e.kind==="line"}function Jn(e){return e!=null&&"kind"in e&&e.kind==="token"}function Eo(e){return Jt(e)||Jn(e)}function jl(e){return"type"in e&&e.type==="line-info"}function Ul(e){return"kind"in e&&e.kind==="merge-conflict-action"}function Pl(e){return e==="current"||e==="incoming"||e==="both"}function ii(e,t){let n=e?.querySelector(t);return n instanceof HTMLElement?n:void 0}function Kn(e){let t=[],n=e;for(;n!=null;)t.push(n),n=n.parentNode;return t}function $l(e){let t=e.closest("[data-line], [data-column-number]");if(t instanceof HTMLElement)return t;let n=e.closest('[data-line-annotation], [data-gutter-buffer="annotation"]');if(!(n instanceof HTMLElement))return;let A=n.previousElementSibling;return A instanceof HTMLElement&&(A.hasAttribute("data-line")||A.hasAttribute("data-column-number"))?A:void 0}function ql(e){let t=e.closest('[slot^="annotation-"]');if(t instanceof HTMLElement)return t.getAttribute("slot")??void 0;if(e instanceof HTMLElement){let n=e.getAttribute("name")??void 0;return n!=null&&n.startsWith("annotation-")?n:void 0}}function Yl(e){if(e==null)return;let t=/^annotation-(?:(additions|deletions)-)?(\d+)$/.exec(e);if(t==null)return;let n=Number.parseInt(t[2],10);if(Number.isFinite(n))return{lineNumber:n,side:t[1]}}function si(e){return e!=null&&typeof e.elementFromPoint=="function"}function ci(e,t){switch(e){case"change-deletion":return"deletions";case"change-addition":return"additions";default:return t.hasAttribute("data-deletions")?"deletions":"additions"}}function di(e){let t=e.getAttribute("data-line-type");if(t!=null)switch(t){case"change-deletion":case"change-addition":case"context":case"context-expanded":return t;default:return}}function On(e){for(let t of e)if(t instanceof HTMLElement&&(t.hasAttribute("data-utility-button")||t.hasAttribute("data-gutter-utility-slot")||t.getAttribute("slot")==="gutter-utility-slot"||t.getAttribute("name")==="gutter-utility-slot"))return!0;return!1}function Me(e="none",t,...n){switch(e){case"none":return;case"both":break;case"click":if(t!=="click")return;break;case"move":if(t!=="move")return;break}console.log(...n)}var ae,gi=(ae=class{constructor(){m(this,"observedNodes",new Map);m(this,"applyColumnUpdates",t=>{for(let[n,A]of t){let o=A.codeInlineSize!=null?Tl(A.codeInlineSize):n.codeWidth,a=A.numberInlineSize!=null?Kl(A.numberInlineSize):n.numberWidth,r=o!==n.codeWidth,s=a!==n.numberWidth;if(!(!r&&!s)&&(n.codeWidth=o,n.numberWidth=a,r&&n.codeElement.style.setProperty("--diffs-column-width",`${typeof o=="number"?`${o}px`:"auto"}`),s&&n.codeElement.style.setProperty("--diffs-column-number-width",`${a===0?"auto":`${a}px`}`),r||s&&o!=="auto")){let i=typeof o=="number"?Math.max(o-a,0):0;n.codeElement.style.setProperty("--diffs-column-content-width",`${i>0?`${i}px`:"auto"}`)}}})}static getResizeObserver(){let t=ae.resizeObserver??new ResizeObserver(ae.handleSharedResizeEntries);return ae.resizeObserver=t,t}static handleSharedResizeEntries(t){let n=new Map;for(let A of t){let o=ae.managersByElement.get(A.target);if(o==null)continue;let a=n.get(o);a==null?n.set(o,[A]):a.push(A)}for(let[A,o]of n)A.handleResizeEntries(o)}setup(t,n){let A=new Set,o=0,a=new Map(this.observedNodes);this.observedNodes.clear();for(let r of t.children){if(o===2)break;let s=(()=>{if(r instanceof HTMLElement&&r.tagName==="CODE")return r})();if(s==null)continue;o++;let i=a.get(s);if(i!=null&&i.type!=="code")throw new Error("ResizeManager.setup: somehow a code node is being used for an annotation, should be impossible");let c=s.firstElementChild;c instanceof HTMLElement||(c=null),i!=null?(this.observedNodes.set(s,i),a.delete(s),i.numberElement!==c?(i.numberElement!=null&&(this.unobserve(i.numberElement),a.delete(i.numberElement)),c!=null&&(this.observe(c),a.delete(c),this.observedNodes.set(c,i)),i.numberElement=c,i.numberWidth=0):i.numberElement!=null?(a.delete(i.numberElement),this.observedNodes.set(i.numberElement,i)):i.numberWidth=0):(i={type:"code",codeElement:s,numberElement:c,codeWidth:"auto",numberWidth:0},this.observedNodes.set(s,i),this.observe(s),c!=null&&(this.observedNodes.set(c,i),this.observe(c)))}if(o>1&&!n){let r=t.querySelectorAll('[data-line-annotation*=","]'),s=new Map;for(let i of r){if(!(i instanceof HTMLElement))continue;let c=i.getAttribute("data-line-annotation")??"";if(!/^\d+,\d+$/.test(c)){console.error("DiffFileRenderer.setupResizeObserver: Invalid element or annotation",{lineAnnotation:c,element:i});continue}let d=s.get(c);d==null&&(d=[],s.set(c,d)),d.push(i)}for(let[i,c]of s){if(c.length!==2){console.error("DiffFileRenderer.setupResizeObserver: Bad Pair",i,c);continue}let[d,u]=c,g=d.firstElementChild,p=u.firstElementChild;if(!(d instanceof HTMLElement)||!(u instanceof HTMLElement)||!(g instanceof HTMLElement)||!(p instanceof HTMLElement))continue;let l=a.get(g);if(l!=null){this.observedNodes.set(g,l),this.observedNodes.set(p,l),a.delete(g),a.delete(p);continue}let B=g.getBoundingClientRect().height,E=p.getBoundingClientRect().height;l={type:"annotations",column1:{container:d,child:g,childHeight:B},column2:{container:u,child:p,childHeight:E},currentHeight:"auto"},A.add({child1:g,child2:p,item:l,newHeight:Math.max(B,E)})}for(let i of A)this.applyNewHeight(i.item,i.newHeight),this.observedNodes.set(i.child1,i.item),this.observedNodes.set(i.child2,i.item),this.observe(i.child1),this.observe(i.child2);A.clear()}for(let[r,s]of a)this.unobserve(r),s.type==="code"?Ol(s):Jl(s);a.clear()}cleanUp(){for(let t of this.observedNodes.keys())this.unobserve(t);this.observedNodes.clear()}observe(t){let{managersByElement:n}=ae,A=n.get(t);if(A!==this){if(A!=null&&A!==this)throw new Error("ResizeManager.observe: element is already owned by another ResizeManager");n.set(t,this),ae.getResizeObserver().observe(t)}}unobserve(t){let{managersByElement:n,resizeObserver:A}=ae,o=n.get(t);if(o!=null){if(o!==this)throw new Error("ResizeManager.unobserve: element is owned by another ResizeManager");n.delete(t),A?.unobserve(t),A!=null&&n.size===0&&(A.disconnect(),ae.resizeObserver=void 0)}}handleResizeEntries(t){let n=new Map,A=new Set;for(let o of t){let{target:a,borderBoxSize:r,contentBoxSize:s}=o;if(!(a instanceof HTMLElement)){console.error("ResizeManager.handleResizeEntries: Invalid element for ResizeObserver",o);continue}let i=this.observedNodes.get(a);if(i==null){console.error("ResizeManager.handleResizeEntries: Not a valid observed node",o);continue}if(i.type==="annotations"){let c=(()=>{if(a===i.column1.child)return i.column1;if(a===i.column2.child)return i.column2})();if(c==null){console.error("ResizeManager.handleResizeEntries: Couldn't find a column for",{item:i,target:a});continue}c.childHeight=r[0].blockSize,A.add(i)}else if(i.type==="code"){let c=n.get(i)??{},d=s[0].inlineSize;a===i.codeElement?c.codeInlineSize=d:a===i.numberElement&&(c.numberInlineSize=d),n.set(i,c)}}this.applyAnnotationUpdates(A),A.clear(),this.applyColumnUpdates(n),n.clear()}applyAnnotationUpdates(t){for(let n of t)this.applyNewHeight(n,Math.max(n.column1.childHeight,n.column2.childHeight))}applyNewHeight(t,n){n!==t.currentHeight&&(t.currentHeight=Math.max(n,0),t.column1.container.style.setProperty("--diffs-annotation-min-height",`${t.currentHeight}px`),t.column2.container.style.setProperty("--diffs-annotation-min-height",`${t.currentHeight}px`))}},m(ae,"resizeObserver"),m(ae,"managersByElement",new Map),ae);function Tl(e){let t=Math.max(Math.floor(e),0);return t===0?"auto":t}function Kl(e){return Math.max(Math.ceil(e),0)}function Ol(e){e.codeElement.isConnected&&(e.codeElement.style.removeProperty("--diffs-column-content-width"),e.codeElement.style.removeProperty("--diffs-column-number-width"),e.codeElement.style.removeProperty("--diffs-column-width"))}function Jl(e){e.column1.container.isConnected&&e.column1.container.style.removeProperty("--diffs-annotation-min-height"),e.column2.container.isConnected&&e.column2.container.style.removeProperty("--diffs-annotation-min-height")}var Ke=new Map,Wn=new Map,pi=new Map,Wt=new Set;function Qo(e){for(let t of Array.isArray(e)?e:[e])if(!(t==="text"||t==="ansi")&&!Wt.has(t))return!1;return!0}function yo(e,t){e=Array.isArray(e)?e:[e];for(let n of e){if(Wt.has(n.name))continue;let A=Ke.get(n.name);A==null&&(A=n,Ke.set(n.name,A)),Wt.add(A.name),t.loadLanguageSync(A.data)}}function zn(){return typeof WorkerGlobalScope<"u"&&typeof self<"u"&&self instanceof WorkerGlobalScope}var $=class extends Error{constructor(t){super(t),this.name="ShikiError"}};function Wl(e){return So(e)}function So(e){return Array.isArray(e)?zl(e):e instanceof RegExp?e:typeof e=="object"?Zl(e):e}function zl(e){let t=[];for(let n=0,A=e.length;n{for(let A in n)e[A]=n[A]}),e}function Qi(e){let t=~e.lastIndexOf("/")||~e.lastIndexOf("\\");return t===0?e:~t===e.length-1?Qi(e.substring(0,e.length-1)):e.substr(~t+1)}var ko=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,Zn=class{static hasCaptures(e){return e===null?!1:(ko.lastIndex=0,ko.test(e))}static replaceCaptures(e,t,n){return e.replace(ko,(A,o,a,r)=>{let s=n[parseInt(o||a,10)];if(s){let i=t.substring(s.start,s.end);for(;i[0]===".";)i=i.substring(1);switch(r){case"downcase":return i.toLowerCase();case"upcase":return i.toUpperCase();default:return i}}else return A})}};function yi(e,t){return et?1:0}function ki(e,t){if(e===null&&t===null)return 0;if(!e)return-1;if(!t)return 1;let n=e.length,A=t.length;if(n===A){for(let o=0;othis._root.match(e)));this._colorMap=e,this._defaults=t,this._root=n}static createFromRawTheme(e,t){return this.createFromParsedTheme(em(e),t)}static createFromParsedTheme(e,t){return nm(e,t)}getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(e===null)return this._defaults;let t=e.scopeName,A=this._cachedMatchRoot.get(t).find(o=>Vl(e.parent,o.parentScopes));return A?new Di(A.fontStyle,A.foreground,A.background):null}},Io=class Vn{constructor(t,n){this.parent=t,this.scopeName=n}static push(t,n){for(let A of n)t=new Vn(t,A);return t}static from(...t){let n=null;for(let A=0;A"){if(n===t.length-1)return!1;A=t[++n],o=!0}for(;e&&!Xl(e.scopeName,A);){if(o)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function Xl(e,t){return t===e||e.startsWith(t)&&e[t.length]==="."}var Di=class{constructor(e,t,n){this.fontStyle=e,this.foregroundId=t,this.backgroundId=n}};function em(e){if(!e)return[];if(!e.settings||!Array.isArray(e.settings))return[];let t=e.settings,n=[],A=0;for(let o=0,a=t.length;o1&&(E=l.slice(0,l.length-1),E.reverse()),n[A++]=new tm(B,E,o,i,c,d)}}return n}var tm=class{constructor(e,t,n,A,o,a){this.scope=e,this.parentScopes=t,this.index=n,this.fontStyle=A,this.foreground=o,this.background=a}},te=(e=>(e[e.NotSet=-1]="NotSet",e[e.None=0]="None",e[e.Italic=1]="Italic",e[e.Bold=2]="Bold",e[e.Underline=4]="Underline",e[e.Strikethrough=8]="Strikethrough",e))(te||{});function nm(e,t){e.sort((i,c)=>{let d=yi(i.scope,c.scope);return d!==0||(d=ki(i.parentScopes,c.parentScopes),d!==0)?d:i.index-c.index});let n=0,A="#000000",o="#ffffff";for(;e.length>=1&&e[0].scope==="";){let i=e.shift();i.fontStyle!==-1&&(n=i.fontStyle),i.foreground!==null&&(A=i.foreground),i.background!==null&&(o=i.background)}let a=new Am(t),r=new Di(n,a.getId(A),a.getId(o)),s=new am(new Do(0,null,-1,0,0),[]);for(let i=0,c=e.length;it?console.log("how did this happen?"):this.scopeDepth=t,n!==-1&&(this.fontStyle=n),A!==0&&(this.foreground=A),o!==0&&(this.background=o)}},am=class Fo{constructor(t,n=[],A={}){m(this,"_rulesWithParentScopes");this._mainRule=t,this._children=A,this._rulesWithParentScopes=n}static _cmpBySpecificity(t,n){if(t.scopeDepth!==n.scopeDepth)return n.scopeDepth-t.scopeDepth;let A=0,o=0;for(;t.parentScopes[A]===">"&&A++,n.parentScopes[o]===">"&&o++,!(A>=t.parentScopes.length||o>=n.parentScopes.length);){let a=n.parentScopes[o].length-t.parentScopes[A].length;if(a!==0)return a;A++,o++}return n.parentScopes.length-t.parentScopes.length}match(t){if(t!==""){let A=t.indexOf("."),o,a;if(A===-1?(o=t,a=""):(o=t.substring(0,A),a=t.substring(A+1)),this._children.hasOwnProperty(o))return this._children[o].match(a)}let n=this._rulesWithParentScopes.concat(this._mainRule);return n.sort(Fo._cmpBySpecificity),n}insert(t,n,A,o,a,r){if(n===""){this._doInsertHere(t,A,o,a,r);return}let s=n.indexOf("."),i,c;s===-1?(i=n,c=""):(i=n.substring(0,s),c=n.substring(s+1));let d;this._children.hasOwnProperty(i)?d=this._children[i]:(d=new Fo(this._mainRule.clone(),Do.cloneArr(this._rulesWithParentScopes)),this._children[i]=d),d.insert(t+1,c,A,o,a,r)}_doInsertHere(t,n,A,o,a){if(n===null){this._mainRule.acceptOverwrite(t,A,o,a);return}for(let r=0,s=this._rulesWithParentScopes.length;r>>0}static getTokenType(t){return(t&768)>>>8}static containsBalancedBrackets(t){return(t&1024)!==0}static getFontStyle(t){return(t&30720)>>>11}static getForeground(t){return(t&16744448)>>>15}static getBackground(t){return(t&4278190080)>>>24}static set(t,n,A,o,a,r,s){let i=le.getLanguageId(t),c=le.getTokenType(t),d=le.containsBalancedBrackets(t)?1:0,u=le.getFontStyle(t),g=le.getForeground(t),p=le.getBackground(t);return n!==0&&(i=n),A!==8&&(c=A),o!==null&&(d=o?1:0),a!==-1&&(u=a),r!==0&&(g=r),s!==0&&(p=s),(i<<0|c<<8|d<<10|u<<11|g<<15|p<<24)>>>0}};function eA(e,t){let n=[],A=rm(e),o=A.next();for(;o!==null;){let i=0;if(o.length===2&&o.charAt(1)===":"){switch(o.charAt(0)){case"R":i=1;break;case"L":i=-1;break;default:console.log(`Unknown priority ${o} in scope selector`)}o=A.next()}let c=r();if(n.push({matcher:c,priority:i}),o!==",")break;o=A.next()}return n;function a(){if(o==="-"){o=A.next();let i=a();return c=>!!i&&!i(c)}if(o==="("){o=A.next();let i=s();return o===")"&&(o=A.next()),i}if(mi(o)){let i=[];do i.push(o),o=A.next();while(mi(o));return c=>t(i,c)}return null}function r(){let i=[],c=a();for(;c;)i.push(c),c=a();return d=>i.every(u=>u(d))}function s(){let i=[],c=r();for(;c&&(i.push(c),o==="|"||o===",");){do o=A.next();while(o==="|"||o===",");c=r()}return d=>i.some(u=>u(d))}}function mi(e){return!!e&&!!e.match(/[\w\.:]+/)}function rm(e){let t=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,n=t.exec(e);return{next:()=>{if(!n)return null;let A=n[0];return n=t.exec(e),A}}}function vi(e){typeof e.dispose=="function"&&e.dispose()}var Xt=class{constructor(e){this.scopeName=e}toKey(){return this.scopeName}},im=class{constructor(e,t){this.scopeName=e,this.ruleName=t}toKey(){return`${this.scopeName}#${this.ruleName}`}},sm=class{constructor(){m(this,"_references",[]);m(this,"_seenReferenceKeys",new Set);m(this,"visitedRule",new Set)}get references(){return this._references}add(e){let t=e.toKey();this._seenReferenceKeys.has(t)||(this._seenReferenceKeys.add(t),this._references.push(e))}},cm=class{constructor(e,t){m(this,"seenFullScopeRequests",new Set);m(this,"seenPartialScopeRequests",new Set);m(this,"Q");this.repo=e,this.initialScopeName=t,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new Xt(this.initialScopeName)]}processQueue(){let e=this.Q;this.Q=[];let t=new sm;for(let n of e)dm(n,this.initialScopeName,this.repo,t);for(let n of t.references)if(n instanceof Xt){if(this.seenFullScopeRequests.has(n.scopeName))continue;this.seenFullScopeRequests.add(n.scopeName),this.Q.push(n)}else{if(this.seenFullScopeRequests.has(n.scopeName)||this.seenPartialScopeRequests.has(n.toKey()))continue;this.seenPartialScopeRequests.add(n.toKey()),this.Q.push(n)}}};function dm(e,t,n,A){let o=n.lookup(e.scopeName);if(!o){if(e.scopeName===t)throw new Error(`No grammar provided for <${t}>`);return}let a=n.lookup(t);e instanceof Xt?Xn({baseGrammar:a,selfGrammar:o},A):vo(e.ruleName,{baseGrammar:a,selfGrammar:o,repository:o.repository},A);let r=n.injections(e.scopeName);if(r)for(let s of r)A.add(new Xt(s))}function vo(e,t,n){if(t.repository&&t.repository[e]){let A=t.repository[e];tA([A],t,n)}}function Xn(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&tA(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&tA(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function tA(e,t,n){for(let A of e){if(n.visitedRule.has(A))continue;n.visitedRule.add(A);let o=A.repository?wi({},t.repository,A.repository):t.repository;Array.isArray(A.patterns)&&tA(A.patterns,{...t,repository:o},n);let a=A.include;if(!a)continue;let r=xi(a);switch(r.kind){case 0:Xn({...t,selfGrammar:t.baseGrammar},n);break;case 1:Xn(t,n);break;case 2:vo(r.ruleName,{...t,repository:o},n);break;case 3:case 4:let s=r.scopeName===t.selfGrammar.scopeName?t.selfGrammar:r.scopeName===t.baseGrammar.scopeName?t.baseGrammar:void 0;if(s){let i={baseGrammar:t.baseGrammar,selfGrammar:s,repository:o};r.kind===4?vo(r.ruleName,i,n):Xn(i,n)}else r.kind===4?n.add(new im(r.scopeName,r.ruleName)):n.add(new Xt(r.scopeName));break}}}var um=class{constructor(){m(this,"kind",0)}},gm=class{constructor(){m(this,"kind",1)}},pm=class{constructor(e){m(this,"kind",2);this.ruleName=e}},lm=class{constructor(e){m(this,"kind",3);this.scopeName=e}},mm=class{constructor(e,t){m(this,"kind",4);this.scopeName=e,this.ruleName=t}};function xi(e){if(e==="$base")return new um;if(e==="$self")return new gm;let t=e.indexOf("#");if(t===-1)return new lm(e);if(t===0)return new pm(e.substring(1));{let n=e.substring(0,t),A=e.substring(t+1);return new mm(n,A)}}var fm=/\\(\d+)/,fi=/\\(\d+)/g;var bm=-1,Mi=-2;var nn=class{constructor(e,t,n,A){m(this,"$location");m(this,"id");m(this,"_nameIsCapturing");m(this,"_name");m(this,"_contentNameIsCapturing");m(this,"_contentName");this.$location=e,this.id=t,this._name=n||null,this._nameIsCapturing=Zn.hasCaptures(this._name),this._contentName=A||null,this._contentNameIsCapturing=Zn.hasCaptures(this._contentName)}get debugName(){let e=this.$location?`${Qi(this.$location.filename)}:${this.$location.line}`:"unknown";return`${this.constructor.name}#${this.id} @ ${e}`}getName(e,t){return!this._nameIsCapturing||this._name===null||e===null||t===null?this._name:Zn.replaceCaptures(this._name,e,t)}getContentName(e,t){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:Zn.replaceCaptures(this._contentName,e,t)}},Bm=class extends nn{constructor(t,n,A,o,a){super(t,n,A,o);m(this,"retokenizeCapturedWithRuleId");this.retokenizeCapturedWithRuleId=a}dispose(){}collectPatterns(t,n){throw new Error("Not supported!")}compile(t,n){throw new Error("Not supported!")}compileAG(t,n,A,o){throw new Error("Not supported!")}},hm=class extends nn{constructor(t,n,A,o,a){super(t,n,A,null);m(this,"_match");m(this,"captures");m(this,"_cachedCompiledPatterns");this._match=new en(o,this.id),this.captures=a,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(t,n){n.push(this._match)}compile(t,n){return this._getCachedCompiledPatterns(t).compile(t)}compileAG(t,n,A,o){return this._getCachedCompiledPatterns(t).compileAG(t,A,o)}_getCachedCompiledPatterns(t){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new tn,this.collectPatterns(t,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},bi=class extends nn{constructor(t,n,A,o,a){super(t,n,A,o);m(this,"hasMissingPatterns");m(this,"patterns");m(this,"_cachedCompiledPatterns");this.patterns=a.patterns,this.hasMissingPatterns=a.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}collectPatterns(t,n){for(let A of this.patterns)t.getRule(A).collectPatterns(t,n)}compile(t,n){return this._getCachedCompiledPatterns(t).compile(t)}compileAG(t,n,A,o){return this._getCachedCompiledPatterns(t).compileAG(t,A,o)}_getCachedCompiledPatterns(t){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new tn,this.collectPatterns(t,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},xo=class extends nn{constructor(t,n,A,o,a,r,s,i,c,d){super(t,n,A,o);m(this,"_begin");m(this,"beginCaptures");m(this,"_end");m(this,"endHasBackReferences");m(this,"endCaptures");m(this,"applyEndPatternLast");m(this,"hasMissingPatterns");m(this,"patterns");m(this,"_cachedCompiledPatterns");this._begin=new en(a,this.id),this.beginCaptures=r,this._end=new en(s||"\uFFFF",-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=i,this.applyEndPatternLast=c||!1,this.patterns=d.patterns,this.hasMissingPatterns=d.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(t,n){return this._end.resolveBackReferences(t,n)}collectPatterns(t,n){n.push(this._begin)}compile(t,n){return this._getCachedCompiledPatterns(t,n).compile(t)}compileAG(t,n,A,o){return this._getCachedCompiledPatterns(t,n).compileAG(t,A,o)}_getCachedCompiledPatterns(t,n){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new tn;for(let A of this.patterns)t.getRule(A).collectPatterns(t,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,n):this._cachedCompiledPatterns.setSource(0,n)),this._cachedCompiledPatterns}},nA=class extends nn{constructor(t,n,A,o,a,r,s,i,c){super(t,n,A,o);m(this,"_begin");m(this,"beginCaptures");m(this,"whileCaptures");m(this,"_while");m(this,"whileHasBackReferences");m(this,"hasMissingPatterns");m(this,"patterns");m(this,"_cachedCompiledPatterns");m(this,"_cachedCompiledWhilePatterns");this._begin=new en(a,this.id),this.beginCaptures=r,this.whileCaptures=i,this._while=new en(s,Mi),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=c.patterns,this.hasMissingPatterns=c.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null),this._cachedCompiledWhilePatterns&&(this._cachedCompiledWhilePatterns.dispose(),this._cachedCompiledWhilePatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(t,n){return this._while.resolveBackReferences(t,n)}collectPatterns(t,n){n.push(this._begin)}compile(t,n){return this._getCachedCompiledPatterns(t).compile(t)}compileAG(t,n,A,o){return this._getCachedCompiledPatterns(t).compileAG(t,A,o)}_getCachedCompiledPatterns(t){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new tn;for(let n of this.patterns)t.getRule(n).collectPatterns(t,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(t,n){return this._getCachedCompiledWhilePatterns(t,n).compile(t)}compileWhileAG(t,n,A,o){return this._getCachedCompiledWhilePatterns(t,n).compileAG(t,A,o)}_getCachedCompiledWhilePatterns(t,n){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new tn,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,n||"\uFFFF"),this._cachedCompiledWhilePatterns}},Si=class ne{static createCaptureRule(t,n,A,o,a){return t.registerRule(r=>new Bm(n,r,A,o,a))}static getCompiledRuleId(t,n,A){return t.id||n.registerRule(o=>{if(t.id=o,t.match)return new hm(t.$vscodeTextmateLocation,t.id,t.name,t.match,ne._compileCaptures(t.captures,n,A));if(typeof t.begin>"u"){t.repository&&(A=wi({},A,t.repository));let a=t.patterns;return typeof a>"u"&&t.include&&(a=[{include:t.include}]),new bi(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,ne._compilePatterns(a,n,A))}return t.while?new nA(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,ne._compileCaptures(t.beginCaptures||t.captures,n,A),t.while,ne._compileCaptures(t.whileCaptures||t.captures,n,A),ne._compilePatterns(t.patterns,n,A)):new xo(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,ne._compileCaptures(t.beginCaptures||t.captures,n,A),t.end,ne._compileCaptures(t.endCaptures||t.captures,n,A),t.applyEndPatternLast,ne._compilePatterns(t.patterns,n,A))}),t.id}static _compileCaptures(t,n,A){let o=[];if(t){let a=0;for(let r in t){if(r==="$vscodeTextmateLocation")continue;let s=parseInt(r,10);s>a&&(a=s)}for(let r=0;r<=a;r++)o[r]=null;for(let r in t){if(r==="$vscodeTextmateLocation")continue;let s=parseInt(r,10),i=0;t[r].patterns&&(i=ne.getCompiledRuleId(t[r],n,A)),o[s]=ne.createCaptureRule(n,t[r].$vscodeTextmateLocation,t[r].name,t[r].contentName,i)}}return o}static _compilePatterns(t,n,A){let o=[];if(t)for(let a=0,r=t.length;at.substring(o.start,o.end));return fi.lastIndex=0,this.source.replace(fi,(o,a)=>Ii(A[parseInt(a,10)]||""))}_buildAnchorCache(){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let t=[],n=[],A=[],o=[],a,r,s,i;for(a=0,r=this.source.length;an.source);this._cached=new Bi(e,t,this._items.map(n=>n.ruleId))}return this._cached}compileAG(e,t,n){return this._hasAnchors?t?n?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G0):n?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G0):this.compile(e)}_resolveAnchors(e,t,n){let A=this._items.map(o=>o.resolveAnchors(t,n));return new Bi(e,A,this._items.map(o=>o.ruleId))}},Bi=class{constructor(e,t,n){m(this,"scanner");this.regExps=t,this.rules=n,this.scanner=e.createOnigScanner(t)}dispose(){typeof this.scanner.dispose=="function"&&this.scanner.dispose()}toString(){let e=[];for(let t=0,n=this.rules.length;t{let n=this._scopeToLanguage(t),A=this._toStandardTokenType(t);return new _o(n,A)}));this._defaultAttributes=new _o(t,8),this._embeddedLanguagesMatcher=new Em(Object.entries(n||{}))}getDefaultAttributes(){return this._defaultAttributes}getBasicScopeAttributes(t){return t===null?Se._NULL_SCOPE_METADATA:this._getBasicScopeAttributes.get(t)}_scopeToLanguage(t){return this._embeddedLanguagesMatcher.match(t)||0}_toStandardTokenType(t){let n=t.match(Se.STANDARD_TOKEN_TYPE_REGEXP);if(!n)return 8;switch(n[1]){case"comment":return 1;case"string":return 2;case"regex":return 3;case"meta.embedded":return 0}throw new Error("Unexpected match for standard token type!")}},m(Se,"_NULL_SCOPE_METADATA",new _o(0,0)),m(Se,"STANDARD_TOKEN_TYPE_REGEXP",/\b(comment|string|regex|meta\.embedded)\b/),Se),Em=class{constructor(e){m(this,"values");m(this,"scopesRegExp");if(e.length===0)this.values=null,this.scopesRegExp=null;else{this.values=new Map(e);let t=e.map(([n,A])=>Ii(n));t.sort(),t.reverse(),this.scopesRegExp=new RegExp(`^((${t.join(")|(")}))($|\\.)`,"")}}match(e){if(!this.scopesRegExp)return;let t=e.match(this.scopesRegExp);if(t)return this.values.get(t[1])}},xy={InDebugMode:typeof process<"u"&&!!process.env.VSCODE_TEXTMATE_DEBUG},Ni=!1,hi=class{constructor(e,t){this.stack=e,this.stoppedEarly=t}};function Ri(e,t,n,A,o,a,r,s){let i=t.content.length,c=!1,d=-1;if(r){let p=wm(e,t,n,A,o,a);o=p.stack,A=p.linePos,n=p.isFirstLine,d=p.anchorPosition}let u=Date.now();for(;!c;){if(s!==0&&Date.now()-u>s)return new hi(o,!0);g()}return new hi(o,!1);function g(){let p=Qm(e,t,n,A,o,d);if(!p){a.produce(o,i),c=!0;return}let l=p.captureIndices,B=p.matchedRuleId,E=l&&l.length>0?l[0].end>A:!1;if(B===bm){let h=o.getRule(e);a.produce(o,l[0].start),o=o.withContentNameScopesList(o.nameScopesList),zt(e,t,n,o,a,h.endCaptures,l),a.produce(o,l[0].end);let f=o;if(o=o.parent,d=f.getAnchorPos(),!E&&f.getEnterPos()===A){o=f,a.produce(o,i),c=!0;return}}else{let h=e.getRule(B);a.produce(o,l[0].start);let f=o,b=h.getName(t.content,l),C=o.contentNameScopesList.pushAttributed(b,e);if(o=o.push(B,A,d,l[0].end===i,null,C,C),h instanceof xo){let Q=h;zt(e,t,n,o,a,Q.beginCaptures,l),a.produce(o,l[0].end),d=l[0].end;let _=Q.getContentName(t.content,l),y=C.pushAttributed(_,e);if(o=o.withContentNameScopesList(y),Q.endHasBackReferences&&(o=o.withEndRule(Q.getEndWithResolvedBackReferences(t.content,l))),!E&&f.hasSameRuleAs(o)){o=o.pop(),a.produce(o,i),c=!0;return}}else if(h instanceof nA){let Q=h;zt(e,t,n,o,a,Q.beginCaptures,l),a.produce(o,l[0].end),d=l[0].end;let _=Q.getContentName(t.content,l),y=C.pushAttributed(_,e);if(o=o.withContentNameScopesList(y),Q.whileHasBackReferences&&(o=o.withEndRule(Q.getWhileWithResolvedBackReferences(t.content,l))),!E&&f.hasSameRuleAs(o)){o=o.pop(),a.produce(o,i),c=!0;return}}else if(zt(e,t,n,o,a,h.captures,l),a.produce(o,l[0].end),o=o.pop(),!E){o=o.safePop(),a.produce(o,i),c=!0;return}}l[0].end>A&&(A=l[0].end,n=!1)}}function wm(e,t,n,A,o,a){let r=o.beginRuleCapturedEOL?0:-1,s=[];for(let i=o;i;i=i.pop()){let c=i.getRule(e);c instanceof nA&&s.push({rule:c,stack:i})}for(let i=s.pop();i;i=s.pop()){let{ruleScanner:c,findOptions:d}=Im(i.rule,e,i.stack.endRule,n,A===r),u=c.findNextMatchSync(t,A,d);if(u){if(u.ruleId!==Mi){o=i.stack.pop();break}u.captureIndices&&u.captureIndices.length&&(a.produce(i.stack,u.captureIndices[0].start),zt(e,t,n,i.stack,a,i.rule.whileCaptures,u.captureIndices),a.produce(i.stack,u.captureIndices[0].end),r=u.captureIndices[0].end,u.captureIndices[0].end>A&&(A=u.captureIndices[0].end,n=!1))}else{o=i.stack.pop();break}}return{stack:o,linePos:A,anchorPosition:r,isFirstLine:n}}function Qm(e,t,n,A,o,a){let r=ym(e,t,n,A,o,a),s=e.getInjections();if(s.length===0)return r;let i=km(s,e,t,n,A,o,a);if(!i)return r;if(!r)return i;let c=r.captureIndices[0].start,d=i.captureIndices[0].start;return d=s)&&(s=b,i=f.captureIndices,c=f.ruleId,d=l.priority,s===o))break}return i?{priorityMatch:d===-1,captureIndices:i,matchedRuleId:c}:null}function Gi(e,t,n,A,o){if(Ni){let r=e.compile(t,n),s=Hi(A,o);return{ruleScanner:r,findOptions:s}}return{ruleScanner:e.compileAG(t,n,A,o),findOptions:0}}function Im(e,t,n,A,o){if(Ni){let r=e.compileWhile(t,n),s=Hi(A,o);return{ruleScanner:r,findOptions:s}}return{ruleScanner:e.compileWhileAG(t,n,A,o),findOptions:0}}function Hi(e,t){let n=0;return e||(n|=1),t||(n|=4),n}function zt(e,t,n,A,o,a,r){if(a.length===0)return;let s=t.content,i=Math.min(a.length,r.length),c=[],d=r[0].end;for(let u=0;ud)break;for(;c.length>0&&c[c.length-1].endPos<=p.start;)o.produceFromScopes(c[c.length-1].scopes,c[c.length-1].endPos),c.pop();if(c.length>0?o.produceFromScopes(c[c.length-1].scopes,p.start):o.produce(A,p.start),g.retokenizeCapturedWithRuleId){let B=g.getName(s,r),E=A.contentNameScopesList.pushAttributed(B,e),h=g.getContentName(s,r),f=E.pushAttributed(h,e),b=A.push(g.retokenizeCapturedWithRuleId,p.start,-1,!1,null,E,f),C=e.createOnigString(s.substring(0,p.end));Ri(e,C,n&&p.start===0,p.start,b,o,!1,0),vi(C);continue}let l=g.getName(s,r);if(l!==null){let E=(c.length>0?c[c.length-1].scopes:A.contentNameScopesList).pushAttributed(l,e);c.push(new _m(E,p.end))}}for(;c.length>0;)o.produceFromScopes(c[c.length-1].scopes,c[c.length-1].endPos),c.pop()}var _m=class{constructor(e,t){m(this,"scopes");m(this,"endPos");this.scopes=e,this.endPos=t}};function Dm(e,t,n,A,o,a,r,s){return new vm(e,t,n,A,o,a,r,s)}function Ci(e,t,n,A,o){let a=eA(t,AA),r=Si.getCompiledRuleId(n,A,o.repository);for(let s of a)e.push({debugSelector:t,matcher:s.matcher,ruleId:r,grammar:o,priority:s.priority})}function AA(e,t){if(t.length{for(let o=n;on&&e.substr(0,n)===t&&e[n]==="."}var vm=class{constructor(e,t,n,A,o,a,r,s){m(this,"_rootId");m(this,"_lastRuleId");m(this,"_ruleId2desc");m(this,"_includedGrammars");m(this,"_grammarRepository");m(this,"_grammar");m(this,"_injections");m(this,"_basicScopeAttributesProvider");m(this,"_tokenTypeMatchers");if(this._rootScopeName=e,this.balancedBracketSelectors=a,this._onigLib=s,this._basicScopeAttributesProvider=new Cm(n,A),this._rootId=-1,this._lastRuleId=0,this._ruleId2desc=[null],this._includedGrammars={},this._grammarRepository=r,this._grammar=Ei(t,null),this._injections=null,this._tokenTypeMatchers=[],o)for(let i of Object.keys(o)){let c=eA(i,AA);for(let d of c)this._tokenTypeMatchers.push({matcher:d.matcher,type:o[i]})}}get themeProvider(){return this._grammarRepository}dispose(){for(let e of this._ruleId2desc)e&&e.dispose()}createOnigScanner(e){return this._onigLib.createOnigScanner(e)}createOnigString(e){return this._onigLib.createOnigString(e)}getMetadataForScope(e){return this._basicScopeAttributesProvider.getBasicScopeAttributes(e)}_collectInjections(){let e={lookup:o=>o===this._rootScopeName?this._grammar:this.getExternalGrammar(o),injections:o=>this._grammarRepository.injections(o)},t=[],n=this._rootScopeName,A=e.lookup(n);if(A){let o=A.injections;if(o)for(let r in o)Ci(t,r,o[r],this,A);let a=this._grammarRepository.injections(n);a&&a.forEach(r=>{let s=this.getExternalGrammar(r);if(s){let i=s.injectionSelector;i&&Ci(t,i,s,this,s)}})}return t.sort((o,a)=>o.priority-a.priority),t}getInjections(){return this._injections===null&&(this._injections=this._collectInjections()),this._injections}registerRule(e){let t=++this._lastRuleId,n=e(t);return this._ruleId2desc[t]=n,n}getRule(e){return this._ruleId2desc[e]}getExternalGrammar(e,t){if(this._includedGrammars[e])return this._includedGrammars[e];if(this._grammarRepository){let n=this._grammarRepository.lookup(e);if(n)return this._includedGrammars[e]=Ei(n,t&&t.$base),this._includedGrammars[e]}}tokenizeLine(e,t,n=0){let A=this._tokenize(e,t,!1,n);return{tokens:A.lineTokens.getResult(A.ruleStack,A.lineLength),ruleStack:A.ruleStack,stoppedEarly:A.stoppedEarly}}tokenizeLine2(e,t,n=0){let A=this._tokenize(e,t,!0,n);return{tokens:A.lineTokens.getBinaryResult(A.ruleStack,A.lineLength),ruleStack:A.ruleStack,stoppedEarly:A.stoppedEarly}}_tokenize(e,t,n,A){this._rootId===-1&&(this._rootId=Si.getCompiledRuleId(this._grammar.repository.$self,this,this._grammar.repository),this.getInjections());let o;if(!t||t===Mo.NULL){o=!0;let c=this._basicScopeAttributesProvider.getDefaultAttributes(),d=this.themeProvider.getDefaults(),u=st.set(0,c.languageId,c.tokenType,null,d.fontStyle,d.foregroundId,d.backgroundId),g=this.getRule(this._rootId).getName(null,null),p;g?p=Zt.createRootAndLookUpScopeName(g,u,this):p=Zt.createRoot("unknown",u),t=new Mo(null,this._rootId,-1,-1,!1,null,p,p)}else o=!1,t.reset();e=e+` `;let a=this.createOnigString(e),r=a.content.length,s=new Mm(n,e,this._tokenTypeMatchers,this.balancedBracketSelectors),i=Ri(this,a,o,0,t,s,!0,A);return vi(a),{lineLength:r,lineTokens:s,ruleStack:i.stack,stoppedEarly:i.stoppedEarly}}};function Ei(e,t){return e=Wl(e),e.repository=e.repository||{},e.repository.$self={$vscodeTextmateLocation:e.$vscodeTextmateLocation,patterns:e.patterns,name:e.scopeName},e.repository.$base=t||e.repository.$self,e}var Zt=class ye{constructor(t,n,A){this.parent=t,this.scopePath=n,this.tokenAttributes=A}static fromExtension(t,n){let A=t,o=t?.scopePath??null;for(let a of n)o=Io.push(o,a.scopeNames),A=new ye(A,o,a.encodedTokenAttributes);return A}static createRoot(t,n){return new ye(null,new Io(null,t),n)}static createRootAndLookUpScopeName(t,n,A){let o=A.getMetadataForScope(t),a=new Io(null,t),r=A.themeProvider.themeMatch(a),s=ye.mergeAttributes(n,o,r);return new ye(null,a,s)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(" ")}equals(t){return ye.equals(this,t)}static equals(t,n){do{if(t===n||!t&&!n)return!0;if(!t||!n||t.scopeName!==n.scopeName||t.tokenAttributes!==n.tokenAttributes)return!1;t=t.parent,n=n.parent}while(!0)}static mergeAttributes(t,n,A){let o=-1,a=0,r=0;return A!==null&&(o=A.fontStyle,a=A.foregroundId,r=A.backgroundId),st.set(t,n.languageId,n.tokenType,null,o,a,r)}pushAttributed(t,n){if(t===null)return this;if(t.indexOf(" ")===-1)return ye._pushAttributed(this,t,n);let A=t.split(/ /g),o=this;for(let a of A)o=ye._pushAttributed(o,a,n);return o}static _pushAttributed(t,n,A){let o=A.getMetadataForScope(n),a=t.scopePath.push(n),r=A.themeProvider.themeMatch(a),s=ye.mergeAttributes(t.tokenAttributes,o,r);return new ye(t,a,s)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(t){let n=[],A=this;for(;A&&A!==t;)n.push({encodedTokenAttributes:A.tokenAttributes,scopeNames:A.scopePath.getExtensionIfDefined(A.parent?.scopePath??null)}),A=A.parent;return A===t?n.reverse():void 0}},me,Mo=(me=class{constructor(t,n,A,o,a,r,s,i){m(this,"_stackElementBrand");m(this,"_enterPos");m(this,"_anchorPos");m(this,"depth");this.parent=t,this.ruleId=n,this.beginRuleCapturedEOL=a,this.endRule=r,this.nameScopesList=s,this.contentNameScopesList=i,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=A,this._anchorPos=o}equals(t){return t===null?!1:me._equals(this,t)}static _equals(t,n){return t===n?!0:this._structuralEquals(t,n)?Zt.equals(t.contentNameScopesList,n.contentNameScopesList):!1}static _structuralEquals(t,n){do{if(t===n||!t&&!n)return!0;if(!t||!n||t.depth!==n.depth||t.ruleId!==n.ruleId||t.endRule!==n.endRule)return!1;t=t.parent,n=n.parent}while(!0)}clone(){return this}static _reset(t){for(;t;)t._enterPos=-1,t._anchorPos=-1,t=t.parent}reset(){me._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(t,n,A,o,a,r,s){return new me(this,t,n,A,o,a,r,s)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(t){return t.getRule(this.ruleId)}toString(){let t=[];return this._writeString(t,0),"["+t.join(",")+"]"}_writeString(t,n){return this.parent&&(n=this.parent._writeString(t,n)),t[n++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,n}withContentNameScopesList(t){return this.contentNameScopesList===t?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,t)}withEndRule(t){return this.endRule===t?this:new me(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,t,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(t){let n=this;for(;n&&n._enterPos===t._enterPos;){if(n.ruleId===t.ruleId)return!0;n=n.parent}return!1}toStateStackFrame(){return{ruleId:this.ruleId,beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(t,n){let A=Zt.fromExtension(t?.nameScopesList??null,n.nameScopesList);return new me(t,n.ruleId,n.enterPos??-1,n.anchorPos??-1,n.beginRuleCapturedEOL,n.endRule,A,Zt.fromExtension(A,n.contentNameScopesList))}},m(me,"NULL",new me(null,0,0,0,!1,null,null,null)),me),xm=class{constructor(e,t){m(this,"balancedBracketScopes");m(this,"unbalancedBracketScopes");m(this,"allowAny",!1);this.balancedBracketScopes=e.flatMap(n=>n==="*"?(this.allowAny=!0,[]):eA(n,AA).map(A=>A.matcher)),this.unbalancedBracketScopes=t.flatMap(n=>eA(n,AA).map(A=>A.matcher))}get matchesAlways(){return this.allowAny&&this.unbalancedBracketScopes.length===0}get matchesNever(){return this.balancedBracketScopes.length===0&&!this.allowAny}match(e){for(let t of this.unbalancedBracketScopes)if(t(e))return!1;for(let t of this.balancedBracketScopes)if(t(e))return!0;return this.allowAny}},Mm=class{constructor(e,t,n,A){m(this,"_emitBinaryTokens");m(this,"_lineText");m(this,"_tokens");m(this,"_binaryTokens");m(this,"_lastTokenEndIndex");m(this,"_tokenTypeOverrides");this.balancedBracketSelectors=A,this._emitBinaryTokens=e,this._tokenTypeOverrides=n,this._lineText=null,this._tokens=[],this._binaryTokens=[],this._lastTokenEndIndex=0}produce(e,t){this.produceFromScopes(e.contentNameScopesList,t)}produceFromScopes(e,t){if(this._lastTokenEndIndex>=t)return;if(this._emitBinaryTokens){let A=e?.tokenAttributes??0,o=!1;if(this.balancedBracketSelectors?.matchesAlways&&(o=!0),this._tokenTypeOverrides.length>0||this.balancedBracketSelectors&&!this.balancedBracketSelectors.matchesAlways&&!this.balancedBracketSelectors.matchesNever){let a=e?.getScopeNames()??[];for(let r of this._tokenTypeOverrides)r.matcher(a)&&(A=st.set(A,0,r.type,null,-1,0,0));this.balancedBracketSelectors&&(o=this.balancedBracketSelectors.match(a))}if(o&&(A=st.set(A,0,8,o,-1,0,0)),this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-1]===A){this._lastTokenEndIndex=t;return}this._binaryTokens.push(this._lastTokenEndIndex),this._binaryTokens.push(A),this._lastTokenEndIndex=t;return}let n=e?.getScopeNames()??[];this._tokens.push({startIndex:this._lastTokenEndIndex,endIndex:t,scopes:n}),this._lastTokenEndIndex=t}getResult(e,t){return this._tokens.length>0&&this._tokens[this._tokens.length-1].startIndex===t-1&&this._tokens.pop(),this._tokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._tokens[this._tokens.length-1].startIndex=0),this._tokens}getBinaryResult(e,t){this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-2]===t-1&&(this._binaryTokens.pop(),this._binaryTokens.pop()),this._binaryTokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._binaryTokens[this._binaryTokens.length-2]=0);let n=new Uint32Array(this._binaryTokens.length);for(let A=0,o=this._binaryTokens.length;A0;)a.Q.map(r=>this._loadSingleGrammar(r.scopeName)),a.processQueue();return this._grammarForScopeName(e,t,n,A,o)}_loadSingleGrammar(e){this._ensureGrammarCache.has(e)||(this._doLoadSingleGrammar(e),this._ensureGrammarCache.set(e,!0))}_doLoadSingleGrammar(e){let t=this._options.loadGrammar(e);if(t){let n=typeof this._options.getInjections=="function"?this._options.getInjections(e):void 0;this._syncRegistry.addGrammar(t,n)}}addGrammar(e,t=[],n=0,A=null){return this._syncRegistry.addGrammar(e,t),this._grammarForScopeName(e.scopeName,n,A)}_grammarForScopeName(e,t=0,n=null,A=null,o=null){return this._syncRegistry.grammarForScopeName(e,t,n,A,o)}},oA=Mo.NULL;function aA(e,t){let n=typeof e=="string"?{}:{...e.colorReplacements},A=typeof e=="string"?e:e.name;for(let[o,a]of Object.entries(t?.colorReplacements||{}))typeof a=="string"?n[o]=a:o===A&&Object.assign(n,a);return n}function Je(e,t){return e&&(t?.[e?.toLowerCase()]||e)}function Lm(e){return Array.isArray(e)?e:[e]}async function Ki(e){return Promise.resolve(typeof e=="function"?e():e).then(t=>t.default||t)}function Ho(e){return!e||["plaintext","txt","text","plain"].includes(e)}function Oi(e){return e==="ansi"||Ho(e)}function jo(e){return e==="none"}function Ji(e){return jo(e)}function Wi(e,t){var A;if(!t)return e;e.properties||(e.properties={}),(A=e.properties).class||(A.class=[]),typeof e.properties.class=="string"&&(e.properties.class=e.properties.class.split(/\s+/g)),Array.isArray(e.properties.class)||(e.properties.class=[]);let n=Array.isArray(t)?t:t.split(/\s+/g);for(let o of n)o&&!e.properties.class.includes(o)&&e.properties.class.push(o);return e}function dA(e,t=!1){if(e.length===0)return[["",0]];let n=e.split(/(\r?\n)/g),A=0,o=[];for(let a=0;ao);function n(o){if(o===e.length)return{line:t.length-1,character:t[t.length-1].length};let a=o,r=0;for(let s of t){if(aa&&o[a])}var Uo="light-dark()",Rm=["color","background-color"];function Gm(e,t){let n=0,A=[];for(let o of t)o>n&&A.push({...e,content:e.content.slice(n,o),offset:e.offset+n}),n=o;return nA-o);return n.length?e.map(A=>A.flatMap(o=>{let a=n.filter(r=>o.offsetr-o.offset).sort((r,s)=>r-s);return a.length?Gm(o,a):o})):e}function jm(e,t,n,A,o="css-vars"){let a={content:e.content,explanation:e.explanation,offset:e.offset},r=t.map(d=>on(e.variants[d])),s=new Set(r.flatMap(d=>Object.keys(d))),i={},c=(d,u)=>{let g=u==="color"?"":u==="background-color"?"-bg":`-${u}`;return n+t[d]+(u==="color"?"":g)};return r.forEach((d,u)=>{for(let g of s){let p=d[g]||"inherit";if(u===0&&A&&Rm.includes(g))if(A===Uo&&r.length>1){let l=t.findIndex(f=>f==="light"),B=t.findIndex(f=>f==="dark");if(l===-1||B===-1)throw new $('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');let E=r[l][g]||"inherit",h=r[B][g]||"inherit";i[g]=`light-dark(${E}, ${h})`,o==="css-vars"&&(i[c(u,g)]=p)}else i[g]=p;else o==="css-vars"&&(i[c(u,g)]=p)}}),a.htmlStyle=i,a}function on(e){let t={};if(e.color&&(t.color=e.color),e.bgColor&&(t["background-color"]=e.bgColor),e.fontStyle){e.fontStyle&te.Italic&&(t["font-style"]="italic"),e.fontStyle&te.Bold&&(t["font-weight"]="bold");let n=[];e.fontStyle&te.Underline&&n.push("underline"),e.fontStyle&te.Strikethrough&&n.push("line-through"),n.length&&(t["text-decoration"]=n.join(" "))}return t}function rA(e){return typeof e=="string"?e:Object.entries(e).map(([t,n])=>`${t}:${n}`).join(";")}var Zi=new WeakMap;function uA(e,t){Zi.set(e,t)}function an(e){return Zi.get(e)}var Et=class e{constructor(...t){m(this,"_stacks",{});m(this,"lang");if(t.length===2){let[n,A]=t;this.lang=A,this._stacks=n}else{let[n,A,o]=t;this.lang=A,this._stacks={[o]:n}}}get themes(){return Object.keys(this._stacks)}get theme(){return this.themes[0]}get _stack(){return this._stacks[this.theme]}static initial(t,n){return new e(Object.fromEntries(Lm(n).map(A=>[A,oA])),t)}getInternalStack(t=this.theme){return this._stacks[t]}getScopes(t=this.theme){return Um(this._stacks[t])}toJSON(){return{lang:this.lang,theme:this.theme,themes:this.themes,scopes:this.getScopes()}}};function Um(e){let t=[],n=new Set;function A(o){if(n.has(o))return;n.add(o);let a=o?.nameScopesList?.scopeName;a&&t.push(a),o.parent&&A(o.parent)}return A(e),t}function Pm(e,t){if(!(e instanceof Et))throw new $("Invalid grammar state");return e.getInternalStack(t)}function $m(){let e=new WeakMap;function t(n){if(!e.has(n.meta)){let A=function(r){if(typeof r=="number"){if(r<0||r>n.source.length)throw new $(`Invalid decoration offset: ${r}. Code length: ${n.source.length}`);return{...o.indexToPos(r),offset:r}}else{let s=o.lines[r.line];if(s===void 0)throw new $(`Invalid decoration position ${JSON.stringify(r)}. Lines length: ${o.lines.length}`);let i=r.character;if(i<0&&(i=s.length+i),i<0||i>s.length)throw new $(`Invalid decoration position ${JSON.stringify(r)}. Line ${r.line} length: ${s.length}`);return{...r,character:i,offset:o.posToIndex(r.line,i)}}},o=Nm(n.source),a=(n.options.decorations||[]).map(r=>({...r,start:A(r.start),end:A(r.end)}));qm(a),e.set(n.meta,{decorations:a,converter:o,source:n.source})}return e.get(n.meta)}return{name:"shiki:decorations",tokens(n){if(!this.options.decorations?.length)return;let o=t(this).decorations.flatMap(r=>[r.start.offset,r.end.offset]);return Hm(n,o)},code(n){if(!this.options.decorations?.length)return;let A=t(this),o=Array.from(n.children).filter(d=>d.type==="element"&&d.tagName==="span");if(o.length!==A.converter.lines.length)throw new $(`Number of lines in code element (${o.length}) does not match the number of lines in the source (${A.converter.lines.length}). Failed to apply decorations.`);function a(d,u,g,p){let l=o[d],B="",E=-1,h=-1;if(u===0&&(E=0),g===0&&(h=0),g===Number.POSITIVE_INFINITY&&(h=l.children.length),E===-1||h===-1)for(let b=0;bB);return d.tagName=u.tagName||"span",d.properties={...d.properties,...p,class:d.properties.class},u.properties?.class&&Wi(d,u.properties.class),d=l(d,g)||d,d}let i=[],c=A.decorations.sort((d,u)=>u.start.offset-d.start.offset||d.end.offset-u.end.offset);for(let d of c){let{start:u,end:g}=d;if(u.line===g.line)a(u.line,u.character,g.character,d);else if(u.liner(p,d));a(g.line,0,g.character,d)}}i.forEach(d=>d())}}}function qm(e){for(let t=0;tn.end.offset)throw new $(`Invalid decoration range: ${JSON.stringify(n.start)} - ${JSON.stringify(n.end)}`);for(let A=t+1;ANumber.parseInt(A));return n.length!==3||n.some(A=>Number.isNaN(A))?void 0:{type:"rgb",rgb:n}}else if(t==="5"){let n=e.shift();if(n)return{type:"table",index:Number(n)}}}function Om(e){let t=[];for(;e.length>0;){let n=e.shift();if(!n)continue;let A=Number.parseInt(n);if(!Number.isNaN(A))if(A===0)t.push({type:"resetAll"});else if(A<=9)Lo[A]&&t.push({type:"setDecoration",value:Lo[A]});else if(A<=29){let o=Lo[A-20];o&&(t.push({type:"resetDecoration",value:o}),o==="dim"&&t.push({type:"resetDecoration",value:"bold"}))}else if(A<=37)t.push({type:"setForegroundColor",value:{type:"named",name:ct[A-30]}});else if(A===38){let o=Ui(e);o&&t.push({type:"setForegroundColor",value:o})}else if(A===39)t.push({type:"resetForegroundColor"});else if(A<=47)t.push({type:"setBackgroundColor",value:{type:"named",name:ct[A-40]}});else if(A===48){let o=Ui(e);o&&t.push({type:"setBackgroundColor",value:o})}else A===49?t.push({type:"resetBackgroundColor"}):A===53?t.push({type:"setDecoration",value:"overline"}):A===55?t.push({type:"resetDecoration",value:"overline"}):A>=90&&A<=97?t.push({type:"setForegroundColor",value:{type:"named",name:ct[A-90+8]}}):A>=100&&A<=107&&t.push({type:"setBackgroundColor",value:{type:"named",name:ct[A-100+8]}})}return t}function Jm(){let e=null,t=null,n=new Set;return{parse(A){let o=[],a=0;do{let r=Km(A,a),s=r.sequence?A.substring(a,r.startPosition):A.substring(a);if(s.length>0&&o.push({value:s,foreground:e,background:t,decorations:new Set(n)}),r.sequence){let i=Om(r.sequence);for(let c of i)c.type==="resetAll"?(e=null,t=null,n.clear()):c.type==="resetForegroundColor"?e=null:c.type==="resetBackgroundColor"?t=null:c.type==="resetDecoration"&&n.delete(c.value);for(let c of i)c.type==="setForegroundColor"?e=c.value:c.type==="setBackgroundColor"?t=c.value:c.type==="setDecoration"&&n.add(c.value)}a=r.position}while(aMath.max(0,Math.min(i,255)).toString(16).padStart(2,"0")).join("")}`}let A;function o(){if(A)return A;A=[];for(let c=0;c{let c=`terminal.ansi${i[0].toUpperCase()}${i.substring(1)}`,d=e.colors?.[c];return[i,d||Zm[i]]})),r=zm(a),s=Jm();return o.map(i=>s.parse(i[0]).map(c=>{let d,u;c.decorations.has("reverse")?(d=c.background?r.value(c.background):e.bg,u=c.foreground?r.value(c.foreground):e.fg):(d=c.foreground?r.value(c.foreground):e.fg,u=c.background?r.value(c.background):void 0),d=Je(d,A),u=Je(u,A),c.decorations.has("dim")&&(d=Xm(d));let g=te.None;return c.decorations.has("bold")&&(g|=te.Bold),c.decorations.has("italic")&&(g|=te.Italic),c.decorations.has("underline")&&(g|=te.Underline),c.decorations.has("strikethrough")&&(g|=te.Strikethrough),{content:c.value,offset:i[1],color:d,bgColor:u,fontStyle:g}}))}function Xm(e){let t=e.match(/#([0-9a-f]{3,8})/i);if(t){let A=t[1];if(A.length===8){let o=Math.round(Number.parseInt(A.slice(6,8),16)/2).toString(16).padStart(2,"0");return`#${A.slice(0,6)}${o}`}else{if(A.length===6)return`#${A}80`;if(A.length===4){let o=A[0],a=A[1],r=A[2],s=A[3],i=Math.round(Number.parseInt(`${s}${s}`,16)/2).toString(16).padStart(2,"0");return`#${o}${o}${a}${a}${r}${r}${i}`}else if(A.length===3){let o=A[0],a=A[1],r=A[2];return`#${o}${o}${a}${a}${r}${r}80`}}}let n=e.match(/var\((--[\w-]+-ansi-[\w-]+)\)/);return n?`var(${n[1]}-dim)`:e}function Po(e,t,n={}){let{theme:A=e.getLoadedThemes()[0]}=n,o=e.resolveLangAlias(n.lang||"text");if(Ho(o)||jo(A))return dA(t).map(i=>[{content:i[0],offset:i[1]}]);let{theme:a,colorMap:r}=e.setTheme(A);if(o==="ansi")return Vm(a,t,n);let s=e.getLanguage(n.lang||"text");if(n.grammarState){if(n.grammarState.lang!==s.name)throw new $(`Grammar state language "${n.grammarState.lang}" does not match highlight language "${s.name}"`);if(!n.grammarState.themes.includes(a.name))throw new $(`Grammar state themes "${n.grammarState.themes}" do not contain highlight theme "${a.name}"`)}return tf(t,s,a,r,n)}function ef(...e){if(e.length===2)return an(e[1]);let[t,n,A={}]=e,{lang:o="text",theme:a=t.getLoadedThemes()[0]}=A;if(Ho(o)||jo(a))throw new $("Plain language does not have grammar state");if(o==="ansi")throw new $("ANSI language does not have grammar state");let{theme:r,colorMap:s}=t.setTheme(a),i=t.getLanguage(o);return new Et($o(n,i,r,s,A).stateStack,i.name,r.name)}function tf(e,t,n,A,o){let a=$o(e,t,n,A,o),r=new Et(a.stateStack,t.name,n.name);return uA(a.tokens,r),a.tokens}function $o(e,t,n,A,o){let a=aA(n,o),{tokenizeMaxLineLength:r=0,tokenizeTimeLimit:s=500}=o,i=dA(e),c=o.grammarState?Pm(o.grammarState,n.name)??oA:o.grammarContextCode!=null?$o(o.grammarContextCode,t,n,A,{...o,grammarState:void 0,grammarContextCode:void 0}).stateStack:oA,d=[],u=[];for(let g=0,p=i.length;g0&&l.length>=r){d=[],u.push([{content:l,offset:B,color:"",fontStyle:0}]);continue}let E,h,f;o.includeExplanation&&(E=t.tokenizeLine(l,c,s),h=E.tokens,f=0);let b=t.tokenizeLine2(l,c,s),C=b.tokens.length/2;for(let Q=0;Qce.trim());break;case"object":N=H.scope;break;default:continue}G.push({settings:H,selectors:N.map(ce=>ce.split(/ /))})}v.explanation=[];let F=0;for(;_+F({scopeName:t}))}function Af(e,t){let n=[];for(let A=0,o=t.length;A=0&&o>=0;)Pi(e[A],n[o])&&(A-=1),o-=1;return A===-1}function af(e,t,n){let A=[];for(let{selectors:o,settings:a}of e)for(let r of o)if(of(r,t,n)){A.push(a);break}return A}function Xi(e,t,n){let A=Object.entries(n.themes).filter(i=>i[1]).map(i=>({color:i[0],theme:i[1]})),o=A.map(i=>{let c=Po(e,t,{...n,theme:i.theme}),d=an(c),u=typeof i.theme=="string"?i.theme:i.theme.name;return{tokens:c,state:d,theme:u}}),a=rf(...o.map(i=>i.tokens)),r=a[0].map((i,c)=>i.map((d,u)=>{let g={content:d.content,variants:{},offset:d.offset};return"includeExplanation"in n&&n.includeExplanation&&(g.explanation=d.explanation),a.forEach((p,l)=>{let{content:B,explanation:E,offset:h,...f}=p[c][u];g.variants[A[l].color]=f}),g})),s=o[0].state?new Et(Object.fromEntries(o.map(i=>[i.theme,i.state?.getInternalStack(i.theme)])),o[0].state.lang):void 0;return s&&uA(r,s),r}function rf(...e){let t=e.map(()=>[]),n=e.length;for(let A=0;Ai[A]),a=t.map(()=>[]);t.forEach((i,c)=>i.push(a[c]));let r=o.map(()=>0),s=o.map(i=>i[0]);for(;s.every(i=>i);){let i=Math.min(...s.map(c=>c.content.length));for(let c=0;ch[1]).map(h=>({color:h[0],theme:h[1]})).sort((h,f)=>h.color===c?-1:f.color===c?1:0);if(g.length===0)throw new $("`themes` option must not be empty");let p=Xi(e,t,n);if(i=an(p),c&&Uo!==c&&!g.find(h=>h.color===c))throw new $(`\`themes\` option must contain the defaultColor key \`${c}\``);let l=g.map(h=>e.getTheme(h.theme)),B=g.map(h=>h.color);a=p.map(h=>h.map(f=>jm(f,B,d,c,u))),i&&uA(a,i);let E=g.map(h=>aA(h.theme,n));o=$i(g,l,E,d,c,"fg",u),A=$i(g,l,E,d,c,"bg",u),r=`shiki-themes ${l.map(h=>h.name).join(" ")}`,s=c?void 0:[o,A].join(";")}else if("theme"in n){let c=aA(n.theme,n);a=Po(e,t,n);let d=e.getTheme(n.theme);A=Je(d.bg,c),o=Je(d.fg,c),r=d.name,i=an(a)}else throw new $("Invalid options, either `theme` or `themes` must be provided");return{tokens:a,fg:o,bg:A,themeName:r,rootStyle:s,grammarState:i}}function $i(e,t,n,A,o,a,r){return e.map((s,i)=>{let c=Je(t[i][a],n[i])||"inherit",d=`${A+s.color}${a==="bg"?"-bg":""}:${c}`;if(i===0&&o){if(o===Uo&&e.length>1){let u=e.findIndex(B=>B.color==="light"),g=e.findIndex(B=>B.color==="dark");if(u===-1||g===-1)throw new $('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');let p=Je(t[u][a],n[u])||"inherit",l=Je(t[g][a],n[g])||"inherit";return`light-dark(${p}, ${l});${d}`}return c}return r==="css-vars"?d:null}).filter(s=>!!s).join(";")}function cA(e,t,n,A={meta:{},options:n,codeToHast:(o,a)=>cA(e,o,a),codeToTokens:(o,a)=>sA(e,o,a)}){let o=t;for(let l of iA(n))o=l.preprocess?.call(A,o,n)||o;let{tokens:a,fg:r,bg:s,themeName:i,rootStyle:c,grammarState:d}=sA(e,o,n),{mergeWhitespaces:u=!0,mergeSameStyleTokens:g=!1}=n;u===!0?a=cf(a):u==="never"&&(a=df(a)),g&&(a=uf(a));let p={...A,get source(){return o}};for(let l of iA(n))a=l.tokens?.call(p,a)||a;return sf(a,{...n,fg:r,bg:s,themeName:i,rootStyle:n.rootStyle===!1?!1:n.rootStyle??c},p,d)}function sf(e,t,n,A=an(e)){let o=iA(t),a=[],r={type:"root",children:[]},{structure:s="classic",tabindex:i="0"}=t,c={class:`shiki ${t.themeName||""}`};t.rootStyle!==!1&&(t.rootStyle!=null?c.style=t.rootStyle:c.style=`background-color:${t.bg};color:${t.fg}`),i!==!1&&i!=null&&(c.tabindex=i.toString());for(let[B,E]of Object.entries(t.meta||{}))B.startsWith("_")||(c[B]=E);let d={type:"element",tagName:"pre",properties:c,children:[],data:t.data},u={type:"element",tagName:"code",properties:{},children:a},g=[],p={...n,structure:s,addClassToHast:Wi,get source(){return n.source},get tokens(){return e},get options(){return t},get root(){return r},get pre(){return d},get code(){return u},get lines(){return g}};if(e.forEach((B,E)=>{E&&(s==="inline"?r.children.push({type:"element",tagName:"br",properties:{},children:[]}):s==="classic"&&a.push({type:"text",value:` `}));let h={type:"element",tagName:"span",properties:{class:"line"},children:[]},f=0;for(let b of B){let C={type:"element",tagName:"span",properties:{...b.htmlAttrs},children:[{type:"text",value:b.content}]},Q=rA(b.htmlStyle||on(b));Q&&(C.properties.style=Q);for(let _ of o)C=_?.span?.call(p,C,E+1,f,h,b)||C;s==="inline"?r.children.push(C):s==="classic"&&h.children.push(C),f+=b.content.length}if(s==="classic"){for(let b of o)h=b?.line?.call(p,h,E+1)||h;g.push(h),a.push(h)}else s==="inline"&&g.push(h)}),s==="classic"){for(let B of o)u=B?.code?.call(p,u)||u;d.children.push(u);for(let B of o)d=B?.pre?.call(p,d)||d;r.children.push(d)}else if(s==="inline"){let B=[],E={type:"element",tagName:"span",properties:{class:"line"},children:[]};for(let b of r.children)b.type==="element"&&b.tagName==="br"?(B.push(E),E={type:"element",tagName:"span",properties:{class:"line"},children:[]}):(b.type==="element"||b.type==="text")&&E.children.push(b);B.push(E);let f={type:"element",tagName:"code",properties:{},children:B};for(let b of o)f=b?.code?.call(p,f)||f;r.children=[];for(let b=0;b0&&r.children.push({type:"element",tagName:"br",properties:{},children:[]});let C=f.children[b];C.type==="element"&&r.children.push(...C.children)}}let l=r;for(let B of o)l=B?.root?.call(p,l)||l;return A&&uA(l,A),l}function cf(e){return e.map(t=>{let n=[],A="",o;return t.forEach((a,r)=>{let i=!(a.fontStyle&&(a.fontStyle&te.Underline||a.fontStyle&te.Strikethrough));i&&a.content.match(/^\s+$/)&&t[r+1]?(o===void 0&&(o=a.offset),A+=a.content):A?(i?n.push({...a,offset:o,content:A+a.content}):n.push({content:A,offset:o},a),o=void 0,A=""):n.push(a)}),n})}function df(e){return e.map(t=>t.flatMap(n=>{if(n.content.match(/^\s+$/))return n;let A=n.content.match(/^(\s*)(.*?)(\s*)$/);if(!A)return n;let[,o,a,r]=A;if(!o&&!r)return n;let s=[{...n,offset:n.offset+o.length,content:a}];return o&&s.unshift({content:o,offset:n.offset}),r&&s.push({content:r,offset:n.offset+o.length+a.length}),s}))}function uf(e){return e.map(t=>{let n=[];for(let A of t){if(n.length===0){n.push({...A});continue}let o=n[n.length-1],a=rA(o.htmlStyle||on(o)),r=rA(A.htmlStyle||on(A)),s=o.fontStyle&&(o.fontStyle&te.Underline||o.fontStyle&te.Strikethrough),i=A.fontStyle&&(A.fontStyle&te.Underline||A.fontStyle&te.Strikethrough);!s&&!i&&a===r?o.content+=A.content:n.push({...A})}return n})}var gf=Ce;function pf(e,t,n){let A={meta:{},options:n,codeToHast:(a,r)=>cA(e,a,r),codeToTokens:(a,r)=>sA(e,a,r)},o=gf(cA(e,t,n,A));for(let a of iA(n))o=a.postprocess?.call(A,o,n)||o;return o}var qi={light:"#333333",dark:"#bbbbbb"},Yi={light:"#fffffe",dark:"#1e1e1e"},Ti="__shiki_resolved";function wt(e){if(e?.[Ti])return e;let t={...e};t.tokenColors&&!t.settings&&(t.settings=t.tokenColors,delete t.tokenColors),t.type||(t.type="dark"),t.colorReplacements={...t.colorReplacements},t.settings||(t.settings=[]);let{bg:n,fg:A}=t;if(!n||!A){let s=t.settings?t.settings.find(i=>!i.name&&!i.scope):void 0;s?.settings?.foreground&&(A=s.settings.foreground),s?.settings?.background&&(n=s.settings.background),!A&&t?.colors?.["editor.foreground"]&&(A=t.colors["editor.foreground"]),!n&&t?.colors?.["editor.background"]&&(n=t.colors["editor.background"]),A||(A=t.type==="light"?qi.light:qi.dark),n||(n=t.type==="light"?Yi.light:Yi.dark),t.fg=A,t.bg=n}t.settings[0]&&t.settings[0].settings&&!t.settings[0].scope||t.settings.unshift({settings:{foreground:t.fg,background:t.bg}});let o=0,a=new Map;function r(s){if(a.has(s))return a.get(s);o+=1;let i=`#${o.toString(16).padStart(8,"0").toLowerCase()}`;return t.colorReplacements?.[`#${i}`]?r(s):(a.set(s,i),i)}t.settings=t.settings.map(s=>{let i=s.settings?.foreground&&!s.settings.foreground.startsWith("#"),c=s.settings?.background&&!s.settings.background.startsWith("#");if(!i&&!c)return s;let d={...s,settings:{...s.settings}};if(i){let u=r(s.settings.foreground);t.colorReplacements[u]=s.settings.foreground,d.settings.foreground=u}if(c){let u=r(s.settings.background);t.colorReplacements[u]=s.settings.background,d.settings.background=u}return d});for(let s of Object.keys(t.colors||{}))if((s==="editor.foreground"||s==="editor.background"||s.startsWith("terminal.ansi"))&&!t.colors[s]?.startsWith("#")){let i=r(t.colors[s]);t.colorReplacements[i]=t.colors[s],t.colors[s]=i}return Object.defineProperty(t,Ti,{enumerable:!1,writable:!1,value:!0}),t}async function es(e){return Array.from(new Set((await Promise.all(e.filter(t=>!Oi(t)).map(async t=>await Ki(t).then(n=>Array.isArray(n)?n:[n])))).flat()))}async function ts(e){return(await Promise.all(e.map(async n=>Ji(n)?null:wt(await Ki(n))))).filter(n=>!!n)}var No=3,lf=!1;function mf(e,t=3){if(No&&!(typeof No=="number"&&t>No)){if(lf)throw new Error(`[SHIKI DEPRECATE]: ${e}`);console.trace(`[SHIKI DEPRECATE]: ${e}`)}}var Oe=class extends Error{constructor(t){super(t),this.name="ShikiError"}};function ns(e,t){if(!t)return e;if(t[e]){let n=new Set([e]);for(;t[e];){if(e=t[e],n.has(e))throw new Oe(`Circular alias \`${Array.from(n).join(" -> ")} -> ${e}\``);n.add(e)}}return e}var Ro=class extends ji{constructor(n,A,o,a={}){super(n);m(this,"_resolvedThemes",new Map);m(this,"_resolvedGrammars",new Map);m(this,"_langMap",new Map);m(this,"_langGraph",new Map);m(this,"_textmateThemeCache",new WeakMap);m(this,"_loadedThemesCache",null);m(this,"_loadedLanguagesCache",null);this._resolver=n,this._themes=A,this._langs=o,this._alias=a,this._themes.map(r=>this.loadTheme(r)),this.loadLanguages(this._langs)}getTheme(n){return typeof n=="string"?this._resolvedThemes.get(n):this.loadTheme(n)}loadTheme(n){let A=wt(n);return A.name&&(this._resolvedThemes.set(A.name,A),this._loadedThemesCache=null),A}getLoadedThemes(){return this._loadedThemesCache||(this._loadedThemesCache=[...this._resolvedThemes.keys()]),this._loadedThemesCache}setTheme(n){let A=this._textmateThemeCache.get(n);A||(A=Vt.createFromRawTheme(n),this._textmateThemeCache.set(n,A)),this._syncRegistry.setTheme(A)}getGrammar(n){return n=ns(n,this._alias),this._resolvedGrammars.get(n)}loadLanguage(n){if(this.getGrammar(n.name))return;let A=new Set([...this._langMap.values()].filter(r=>r.embeddedLangsLazy?.includes(n.name)));this._resolver.addLanguage(n);let o={balancedBracketSelectors:n.balancedBracketSelectors||["*"],unbalancedBracketSelectors:n.unbalancedBracketSelectors||[]};this._syncRegistry._rawGrammars.set(n.scopeName,n);let a=this.loadGrammarWithConfiguration(n.scopeName,1,o);if(a.name=n.name,this._resolvedGrammars.set(n.name,a),n.aliases&&n.aliases.forEach(r=>{this._alias[r]=n.name}),this._loadedLanguagesCache=null,A.size)for(let r of A)this._resolvedGrammars.delete(r.name),this._loadedLanguagesCache=null,this._syncRegistry?._injectionGrammars?.delete(r.scopeName),this._syncRegistry?._grammars?.delete(r.scopeName),this.loadLanguage(this._langMap.get(r.name))}dispose(){super.dispose(),this._resolvedThemes.clear(),this._resolvedGrammars.clear(),this._langMap.clear(),this._langGraph.clear(),this._loadedThemesCache=null}loadLanguages(n){for(let a of n)this.resolveEmbeddedLanguages(a);let A=Array.from(this._langGraph.entries()),o=A.filter(([a,r])=>!r);if(o.length){let a=A.filter(([r,s])=>s?(s.embeddedLanguages||s.embeddedLangs)?.some(c=>o.map(([d])=>d).includes(c)):!1).filter(r=>!o.includes(r));throw new Oe(`Missing languages ${o.map(([r])=>`\`${r}\``).join(", ")}, required by ${a.map(([r])=>`\`${r}\``).join(", ")}`)}for(let[a,r]of A)this._resolver.addLanguage(r);for(let[a,r]of A)this.loadLanguage(r)}getLoadedLanguages(){return this._loadedLanguagesCache||(this._loadedLanguagesCache=[...new Set([...this._resolvedGrammars.keys(),...Object.keys(this._alias)])]),this._loadedLanguagesCache}resolveEmbeddedLanguages(n){this._langMap.set(n.name,n),this._langGraph.set(n.name,n);let A=n.embeddedLanguages??n.embeddedLangs;if(A)for(let o of A)this._langGraph.set(o,this._langMap.get(o))}},Go=class{constructor(t,n){m(this,"_langs",new Map);m(this,"_scopeToLang",new Map);m(this,"_injections",new Map);m(this,"_onigLib");this._onigLib={createOnigScanner:A=>t.createScanner(A),createOnigString:A=>t.createString(A)},n.forEach(A=>this.addLanguage(A))}get onigLib(){return this._onigLib}getLangRegistration(t){return this._langs.get(t)}loadGrammar(t){return this._scopeToLang.get(t)}addLanguage(t){this._langs.set(t.name,t),t.aliases&&t.aliases.forEach(n=>{this._langs.set(n,t)}),this._scopeToLang.set(t.scopeName,t),t.injectTo&&t.injectTo.forEach(n=>{this._injections.get(n)||this._injections.set(n,[]),this._injections.get(n).push(t.scopeName)})}getInjections(t){let n=t.split("."),A=[];for(let o=1;o<=n.length;o++){let a=n.slice(0,o).join(".");A=[...A,...this._injections.get(a)||[]]}return A}},An=0;function ff(e){An+=1,e.warnings!==!1&&An>=10&&An%10===0&&console.warn(`[Shiki] ${An} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \`highlighter.dispose()\` to release unused instances.`);let t=!1;if(!e.engine)throw new Oe("`engine` option is required for synchronous mode");let n=(e.langs||[]).flat(1),A=(e.themes||[]).flat(1).map(wt),o=new Go(e.engine,n),a=new Ro(o,A,n,e.langAlias),r;function s(b){return ns(b,e.langAlias)}function i(b){h();let C=a.getGrammar(typeof b=="string"?b:b.name);if(!C)throw new Oe(`Language \`${b}\` not found, you may need to load it first`);return C}function c(b){if(b==="none")return{bg:"",fg:"",name:"none",settings:[],type:"dark"};h();let C=a.getTheme(b);if(!C)throw new Oe(`Theme \`${b}\` not found, you may need to load it first`);return C}function d(b){h();let C=c(b);r!==b&&(a.setTheme(C),r=b);let Q=a.getColorMap();return{theme:C,colorMap:Q}}function u(){return h(),a.getLoadedThemes()}function g(){return h(),a.getLoadedLanguages()}function p(...b){h(),a.loadLanguages(b.flat(1))}async function l(...b){return p(await es(b))}function B(...b){h();for(let C of b.flat(1))a.loadTheme(C)}async function E(...b){return h(),B(await ts(b))}function h(){if(t)throw new Oe("Shiki instance has been disposed")}function f(){t||(t=!0,a.dispose(),An-=1)}return{setTheme:d,getTheme:c,getLanguage:i,getLoadedThemes:u,getLoadedLanguages:g,resolveLangAlias:s,loadLanguage:l,loadLanguageSync:p,loadTheme:E,loadThemeSync:B,dispose:f,[Symbol.dispose]:f}}async function bf(e){e.engine||mf("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");let[t,n,A]=await Promise.all([ts(e.themes||[]),es(e.langs||[]),e.engine]);return ff({...e,themes:t,langs:n,engine:A})}async function Bf(e){let t=await bf(e);return{getLastGrammarState:(...n)=>ef(t,...n),codeToTokensBase:(n,A)=>Po(t,n,A),codeToTokensWithThemes:(n,A)=>Xi(t,n,A),codeToTokens:(n,A)=>sA(t,n,A),codeToHast:(n,A)=>cA(t,n,A),codeToHtml:(n,A)=>pf(t,n,A),getBundledLanguages:()=>({}),getBundledThemes:()=>({}),...t,getInternalContext:()=>t}}function As(e){let t=e.langs,n=e.themes,A=e.engine;async function o(a){function r(u){if(typeof u=="string"){if(u=a.langAlias?.[u]||u,Oi(u))return[];let g=t[u];if(!g)throw new $(`Language \`${u}\` is not included in this bundle. You may want to load it from external source.`);return g}return u}function s(u){if(Ji(u))return"none";if(typeof u=="string"){let g=n[u];if(!g)throw new $(`Theme \`${u}\` is not included in this bundle. You may want to load it from external source.`);return g}return u}let i=(a.themes??[]).map(u=>s(u)),c=(a.langs??[]).map(u=>r(u)),d=await Bf({engine:a.engine??A(),...a,themes:i,langs:c});return{...d,loadLanguage(...u){return d.loadLanguage(...u.map(r))},loadTheme(...u){return d.loadTheme(...u.map(s))},getBundledLanguages(){return t},getBundledThemes(){return n}}}return o}function hf(e){let t;async function n(A={}){if(t){let o=await t;return await Promise.all([o.loadTheme(...A.themes||[]),o.loadLanguage(...A.langs||[])]),o}else{t=e({...A,themes:[],langs:[]});let o=await t;return await Promise.all([o.loadTheme(...A.themes||[]),o.loadLanguage(...A.langs||[])]),o}}return n}function os(e,t){let n=hf(e);async function A(o,a){let r=await n({langs:[a.lang],themes:"theme"in a?[a.theme]:Object.values(a.themes)}),s=await t?.guessEmbeddedLanguages?.(o,a.lang,r);return s&&await r.loadLanguage(...s),r}return{getSingletonHighlighter(o){return n(o)},async codeToHtml(o,a){return(await A(o,a)).codeToHtml(o,a)},async codeToHast(o,a){return(await A(o,a)).codeToHast(o,a)},async codeToTokens(o,a){return(await A(o,a)).codeToTokens(o,a)},async codeToTokensBase(o,a){return(await A(o,a)).codeToTokensBase(o,a)},async codeToTokensWithThemes(o,a){return(await A(o,a)).codeToTokensWithThemes(o,a)},async getLastGrammarState(o,a){return(await n({langs:[a.lang],themes:[a.theme]})).getLastGrammarState(o,a)}}}function We(e){if([...e].length!==1)throw new Error(`Expected "${e}" to be a single code point`);return e.codePointAt(0)}function as(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}var rn=new Set(["alnum","alpha","ascii","blank","cntrl","digit","graph","lower","print","punct","space","upper","word","xdigit"]),K=String.raw;function Le(e,t){if(e==null)throw new Error(t??"Value expected");return e}var us=K`\[\^?`,gs=`c.? | C(?:-.?)?|${K`[pP]\{(?:\^?[-\x20_]*[A-Za-z][-\x20\w]*\})?`}|${K`x[89A-Fa-f]\p{AHex}(?:\\x[89A-Fa-f]\p{AHex})*`}|${K`u(?:\p{AHex}{4})? | x\{[^\}]*\}? | x\p{AHex}{0,2}`}|${K`o\{[^\}]*\}?`}|${K`\d{1,3}`}`,Yo=/[?*+][?+]?|\{(?:\d+(?:,\d*)?|,\d+)\}\??/,gA=new RegExp(K` @@ -41,7 +41,7 @@ var fr=Object.defineProperty;var Pp=Object.getPrototypeOf;var $p=Reflect.get;var | && | . `.replace(/\s+/g,""),"gsu");function ps(e,t={}){let n={flags:"",...t,rules:{captureGroup:!1,singleline:!1,...t.rules}};if(typeof e!="string")throw new Error("String expected as pattern");let A=Hf(n.flags),o=[A.extended],a={captureGroup:n.rules.captureGroup,getCurrentModX(){return o.at(-1)},numOpenGroups:0,popModX(){o.pop()},pushModX(u){o.push(u)},replaceCurrentModX(u){o[o.length-1]=u},singleline:n.rules.singleline},r=[],s;for(gA.lastIndex=0;s=gA.exec(e);){let u=Cf(a,e,s[0],gA.lastIndex);u.tokens?r.push(...u.tokens):u.token&&r.push(u.token),u.lastIndex!==void 0&&(gA.lastIndex=u.lastIndex)}let i=[],c=0;r.filter(u=>u.type==="GroupOpen").forEach(u=>{u.kind==="capturing"?u.number=++c:u.raw==="("&&i.push(u)}),c||i.forEach((u,g)=>{u.kind="capturing",u.number=g+1});let d=c||i.length;return{tokens:r.map(u=>u.type==="EscapedNumber"?Uf(u,d):u).flat(),flags:A}}function Cf(e,t,n,A){let[o,a]=n;if(n==="["||n==="[^"){let r=Ef(t,n,A);return{tokens:r.tokens,lastIndex:r.lastIndex}}if(o==="\\"){if("AbBGyYzZ".includes(a))return{token:rs(n,n)};if(/^\\g[<']/.test(n)){if(!/^\\g(?:<[^>]+>|'[^']+')$/.test(n))throw new Error(`Invalid group name "${n}"`);return{token:xf(n)}}if(/^\\k[<']/.test(n)){if(!/^\\k(?:<[^>]+>|'[^']+')$/.test(n))throw new Error(`Invalid group name "${n}"`);return{token:ms(n)}}if(a==="K")return{token:fs("keep",n)};if(a==="N"||a==="R")return{token:dt("newline",n,{negate:a==="N"})};if(a==="O")return{token:dt("any",n)};if(a==="X")return{token:dt("text_segment",n)};let r=ls(n,{inCharClass:!1});return Array.isArray(r)?{tokens:r}:{token:r}}if(o==="("){if(a==="*")return{token:Nf(n)};if(n==="(?{")throw new Error(`Unsupported callout "${n}"`);if(n.startsWith("(?#")){if(t[A]!==")")throw new Error('Unclosed comment group "(?#"');return{lastIndex:A+1}}if(/^\(\?[-imx]+[:)]$/.test(n))return{token:Lf(n,e)};if(e.pushModX(e.getCurrentModX()),e.numOpenGroups++,n==="("&&!e.captureGroup||n==="(?:")return{token:Qt("group",n)};if(n==="(?>")return{token:Qt("atomic",n)};if(n==="(?="||n==="(?!"||n==="(?<="||n==="(?")||n.startsWith("(?'")&&n.endsWith("'"))return{token:Qt("capturing",n,{...n!=="("&&{name:n.slice(3,-1)}})};if(n.startsWith("(?~")){if(n==="(?~|")throw new Error(`Unsupported absence function kind "${n}"`);return{token:Qt("absence_repeater",n)}}throw n==="(?("?new Error(`Unsupported conditional "${n}"`):new Error(`Invalid or unsupported group option "${n}"`)}if(n===")"){if(e.popModX(),e.numOpenGroups--,e.numOpenGroups<0)throw new Error('Unmatched ")"');return{token:Df(n)}}if(e.getCurrentModX()){if(n==="#"){let r=t.indexOf(` -`,A);return{lastIndex:r===-1?t.length:r}}if(/^\s$/.test(n)){let r=/\s+/y;return r.lastIndex=A,{lastIndex:r.exec(t)?r.lastIndex:A}}}if(n===".")return{token:dt("dot",n)};if(n==="^"||n==="$"){let r=e.singleline?{"^":K`\A`,$:K`\Z`}[n]:n;return{token:rs(r,n)}}return n==="|"?{token:Qf(n)}:Yo.test(n)?{tokens:Pf(n)}:{token:Ne(We(n),n)}}function Ef(e,t,n){let A=[is(t[1]==="^",t)],o=1,a;for(qo.lastIndex=n;a=qo.exec(e);){let r=a[0];if(r[0]==="["&&r[1]!==":")o++,A.push(is(r[1]==="^",r));else if(r==="]"){if(A.at(-1).type==="CharacterClassOpen")A.push(Ne(93,r));else if(o--,A.push(yf(r)),!o)break}else{let s=wf(r);Array.isArray(s)?A.push(...s):A.push(s)}}return{tokens:A,lastIndex:qo.lastIndex||e.length}}function wf(e){if(e[0]==="\\")return ls(e,{inCharClass:!0});if(e[0]==="["){let t=/\[:(?\^?)(?[a-z]+):\]/.exec(e);if(!t||!rn.has(t.groups.name))throw new Error(`Invalid POSIX class "${e}"`);return dt("posix",e,{value:t.groups.name,negate:!!t.groups.negate})}return e==="-"?kf(e):e==="&&"?If(e):Ne(We(e),e)}function ls(e,{inCharClass:t}){let n=e[1];if(n==="c"||n==="C")return Sf(e);if("dDhHsSwW".includes(n))return Rf(e);if(e.startsWith(K`\o{`))throw new Error(`Incomplete, invalid, or unsupported octal code point "${e}"`);if(/^\\[pP]\{/.test(e)){if(e.length===3)throw new Error(`Incomplete or invalid Unicode property "${e}"`);return Gf(e)}if(/^\\x[89A-Fa-f]\p{AHex}/u.test(e))try{let A=e.split(/\\x/).slice(1).map(r=>parseInt(r,16)),o=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}).decode(new Uint8Array(A)),a=new TextEncoder;return[...o].map(r=>{let s=[...a.encode(r)].map(i=>`\\x${i.toString(16)}`).join("");return Ne(We(r),s)})}catch{throw new Error(`Multibyte code "${e}" incomplete or invalid in Oniguruma`)}if(n==="u"||n==="x")return Ne(jf(e),e);if(ss.has(n))return Ne(ss.get(n),e);if(/\d/.test(n))return _f(t,e);if(e==="\\")throw new Error(K`Incomplete escape "\"`);if(n==="M")throw new Error(`Unsupported meta "${e}"`);if([...e].length===2)return Ne(e.codePointAt(1),e);throw new Error(`Unexpected escape "${e}"`)}function Qf(e){return{type:"Alternator",raw:e}}function rs(e,t){return{type:"Assertion",kind:e,raw:t}}function ms(e){return{type:"Backreference",raw:e}}function Ne(e,t){return{type:"Character",value:e,raw:t}}function yf(e){return{type:"CharacterClassClose",raw:e}}function kf(e){return{type:"CharacterClassHyphen",raw:e}}function If(e){return{type:"CharacterClassIntersector",raw:e}}function is(e,t){return{type:"CharacterClassOpen",negate:e,raw:t}}function dt(e,t,n={}){return{type:"CharacterSet",kind:e,...n,raw:t}}function fs(e,t,n={}){return e==="keep"?{type:"Directive",kind:e,raw:t}:{type:"Directive",kind:e,flags:Le(n.flags),raw:t}}function _f(e,t){return{type:"EscapedNumber",inCharClass:e,raw:t}}function Df(e){return{type:"GroupClose",raw:e}}function Qt(e,t,n={}){return{type:"GroupOpen",kind:e,...n,raw:t}}function Ff(e,t,n,A){return{type:"NamedCallout",kind:e,tag:t,arguments:n,raw:A}}function vf(e,t,n,A){return{type:"Quantifier",kind:e,min:t,max:n,raw:A}}function xf(e){return{type:"Subroutine",raw:e}}var Mf=new Set(["COUNT","CMP","ERROR","FAIL","MAX","MISMATCH","SKIP","TOTAL_COUNT"]),ss=new Map([["a",7],["b",8],["e",27],["f",12],["n",10],["r",13],["t",9],["v",11]]);function Sf(e){let t=e[1]==="c"?e[2]:e[3];if(!t||!/[A-Za-z]/.test(t))throw new Error(`Unsupported control character "${e}"`);return Ne(We(t.toUpperCase())-64,e)}function Lf(e,t){let{on:n,off:A}=/^\(\?(?[imx]*)(?:-(?[-imx]*))?/.exec(e).groups;A??(A="");let o=(t.getCurrentModX()||n.includes("x"))&&!A.includes("x"),a=ds(n),r=ds(A),s={};if(a&&(s.enable=a),r&&(s.disable=r),e.endsWith(")"))return t.replaceCurrentModX(o),fs("flags",e,{flags:s});if(e.endsWith(":"))return t.pushModX(o),t.numOpenGroups++,Qt("group",e,{...(a||r)&&{flags:s}});throw new Error(`Unexpected flag modifier "${e}"`)}function Nf(e){let t=/\(\*(?[A-Za-z_]\w*)?(?:\[(?(?:[A-Za-z_]\w*)?)\])?(?:\{(?[^}]*)\})?\)/.exec(e);if(!t)throw new Error(`Incomplete or invalid named callout "${e}"`);let{name:n,tag:A,args:o}=t.groups;if(!n)throw new Error(`Invalid named callout "${e}"`);if(A==="")throw new Error(`Named callout tag with empty value not allowed "${e}"`);let a=o?o.split(",").filter(d=>d!=="").map(d=>/^[+-]?\d+$/.test(d)?+d:d):[],[r,s,i]=a,c=Mf.has(n)?n.toLowerCase():"custom";switch(c){case"fail":case"mismatch":case"skip":if(a.length>0)throw new Error(`Named callout arguments not allowed "${a}"`);break;case"error":if(a.length>1)throw new Error(`Named callout allows only one argument "${a}"`);if(typeof r=="string")throw new Error(`Named callout argument must be a number "${r}"`);break;case"max":if(!a.length||a.length>2)throw new Error(`Named callout must have one or two arguments "${a}"`);if(typeof r=="string"&&!/^[A-Za-z_]\w*$/.test(r))throw new Error(`Named callout argument one must be a tag or number "${r}"`);if(a.length===2&&(typeof s=="number"||!/^[<>X]$/.test(s)))throw new Error(`Named callout optional argument two must be '<', '>', or 'X' "${s}"`);break;case"count":case"total_count":if(a.length>1)throw new Error(`Named callout allows only one argument "${a}"`);if(a.length===1&&(typeof r=="number"||!/^[<>X]$/.test(r)))throw new Error(`Named callout optional argument must be '<', '>', or 'X' "${r}"`);break;case"cmp":if(a.length!==3)throw new Error(`Named callout must have three arguments "${a}"`);if(typeof r=="string"&&!/^[A-Za-z_]\w*$/.test(r))throw new Error(`Named callout argument one must be a tag or number "${r}"`);if(typeof s=="number"||!/^(?:[<>!=]=|[<>])$/.test(s))throw new Error(`Named callout argument two must be '==', '!=', '>', '<', '>=', or '<=' "${s}"`);if(typeof i=="string"&&!/^[A-Za-z_]\w*$/.test(i))throw new Error(`Named callout argument three must be a tag or number "${i}"`);break;case"custom":throw new Error(`Undefined callout name "${n}"`);default:throw new Error(`Unexpected named callout kind "${c}"`)}return Ff(c,A??null,o?.split(",")??null,e)}function cs(e){let t=null,n,A;if(e[0]==="{"){let{minStr:o,maxStr:a}=/^\{(?\d*)(?:,(?\d*))?/.exec(e).groups,r=1e5;if(+o>r||a&&+a>r)throw new Error("Quantifier value unsupported in Oniguruma");if(n=+o,A=a===void 0?+o:a===""?1/0:+a,n>A&&(t="possessive",[n,A]=[A,n]),e.endsWith("?")){if(t==="possessive")throw new Error('Unsupported possessive interval quantifier chain with "?"');t="lazy"}else t||(t="greedy")}else n=e[0]==="+"?1:0,A=e[0]==="?"?1:1/0,t=e[1]==="+"?"possessive":e[1]==="?"?"lazy":"greedy";return vf(t,n,A,e)}function Rf(e){let t=e[1].toLowerCase();return dt({d:"digit",h:"hex",s:"space",w:"word"}[t],e,{negate:e[1]!==t})}function Gf(e){let{p:t,neg:n,value:A}=/^\\(?

[pP])\{(?\^?)(?[^}]+)/.exec(e).groups;return dt("property",e,{value:A,negate:t==="P"&&!n||t==="p"&&!!n})}function ds(e){let t={};return e.includes("i")&&(t.ignoreCase=!0),e.includes("m")&&(t.dotAll=!0),e.includes("x")&&(t.extended=!0),Object.keys(t).length?t:null}function Hf(e){let t={ignoreCase:!1,dotAll:!1,extended:!1,digitIsAscii:!1,posixIsAscii:!1,spaceIsAscii:!1,wordIsAscii:!1,textSegmentMode:null};for(let n=0;n\p{AHex}+)/u.exec(e).groups.hex:e.slice(2);return parseInt(t,16)}function Uf(e,t){let{raw:n,inCharClass:A}=e,o=n.slice(1);if(!A&&(o!=="0"&&o.length===1||o[0]!=="0"&&+o<=t))return[ms(n)];let a=[],r=o.match(/^[0-7]+|\d/g);for(let s=0;s127)throw new Error(K`Octal encoded byte above 177 unsupported "${n}"`)}else c=We(i);a.push(Ne(c,(s===0?"\\":"")+i))}return a}function Pf(e){let t=[],n=new RegExp(Yo,"gy"),A;for(;A=n.exec(e);){let o=A[0];if(o[0]==="{"){let a=/^\{(?\d+),(?\d+)\}\??$/.exec(o);if(a){let{min:r,max:s}=a.groups;if(+r>+s&&o.endsWith("?")){n.lastIndex--,t.push(cs(o.slice(0,-1)));continue}}}t.push(cs(o))}return t}function pA(e,t){if(!Array.isArray(e.body))throw new Error("Expected node with body array");if(e.body.length!==1)return!1;let n=e.body[0];return!t||Object.keys(t).every(A=>t[A]===n[A])}function bs(e){return $f.has(e.type)}var $f=new Set(["AbsenceFunction","Backreference","CapturingGroup","Character","CharacterClass","CharacterSet","Group","Quantifier","Subroutine"]);function mA(e,t={}){let n={flags:"",normalizeUnknownPropertyNames:!1,skipBackrefValidation:!1,skipLookbehindValidation:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}},A=ps(e,{flags:n.flags,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline}}),o=(g,p)=>{let l=A.tokens[a.nextIndex];switch(a.parent=g,a.nextIndex++,l.type){case"Alternator":return Re();case"Assertion":return qf(l);case"Backreference":return Yf(l,a);case"Character":return yt(l.value,{useLastValid:!!p.isCheckingRangeEnd});case"CharacterClassHyphen":return Tf(l,a,p);case"CharacterClassOpen":return Kf(l,a,p);case"CharacterSet":return Of(l,a);case"Directive":return Xf(l.kind,{flags:l.flags});case"GroupOpen":return Jf(l,a,p);case"NamedCallout":return tb(l.kind,l.tag,l.arguments);case"Quantifier":return Wf(l,a);case"Subroutine":return zf(l,a);default:throw new Error(`Unexpected token type "${l.type}"`)}},a={capturingGroups:[],hasNumberedRef:!1,namedGroupsByName:new Map,nextIndex:0,normalizeUnknownPropertyNames:n.normalizeUnknownPropertyNames,parent:null,skipBackrefValidation:n.skipBackrefValidation,skipLookbehindValidation:n.skipLookbehindValidation,skipPropertyNameValidation:n.skipPropertyNameValidation,subroutines:[],tokens:A.tokens,unicodePropertyMap:n.unicodePropertyMap,walk:o},r=Ab(eb(A.flags)),s=r.body[0];for(;a.nextIndexi.length)throw new Error("Subroutine uses a group number that's not defined");g&&(i[g-1].isSubroutined=!0)}else if(d.has(g)){if(d.get(g).length>1)throw new Error(K`Subroutine uses a duplicate group name "\g<${g}>"`);d.get(g)[0].isSubroutined=!0}else throw new Error(K`Subroutine uses a group name that's not defined "\g<${g}>"`);return r}function qf({kind:e}){return fA(Le({"^":"line_start",$:"line_end","\\A":"string_start","\\b":"word_boundary","\\B":"word_boundary","\\G":"search_start","\\y":"text_segment_boundary","\\Y":"text_segment_boundary","\\z":"string_end","\\Z":"string_end_newline"}[e],`Unexpected assertion kind "${e}"`),{negate:e===K`\B`||e===K`\Y`})}function Yf({raw:e},t){let n=/^\\k[<']/.test(e),A=n?e.slice(3,-1):e.slice(1),o=(a,r=!1)=>{let s=t.capturingGroups.length,i=!1;if(a>s)if(t.skipBackrefValidation)i=!0;else throw new Error(`Not enough capturing groups defined to the left "${e}"`);return t.hasNumberedRef=!0,lA(r?s+1-a:a,{orphan:i})};if(n){let a=/^(?-?)0*(?[1-9]\d*)$/.exec(A);if(a)return o(+a.groups.num,!!a.groups.sign);if(/[-+]/.test(A))throw new Error(`Invalid backref name "${e}"`);if(!t.namedGroupsByName.has(A))throw new Error(`Group name not defined to the left "${e}"`);return lA(A)}return o(+A)}function Tf(e,t,n){let{tokens:A,walk:o}=t,a=t.parent,r=a.body.at(-1),s=A[t.nextIndex];if(!n.isCheckingRangeEnd&&r&&r.type!=="CharacterClass"&&r.type!=="CharacterClassRange"&&s&&s.type!=="CharacterClassOpen"&&s.type!=="CharacterClassClose"&&s.type!=="CharacterClassIntersector"){let i=o(a,{...n,isCheckingRangeEnd:!0});if(r.type==="Character"&&i.type==="Character")return a.body.pop(),Vf(r,i);throw new Error("Invalid character class range")}return yt(We("-"))}function Kf({negate:e},t,n){let{tokens:A,walk:o}=t,a=[sn()],r=A[t.nextIndex],s=Cs(r);for(;s.type!=="CharacterClassClose";){if(s.type==="CharacterClassIntersector")a.push(sn()),t.nextIndex++;else{let c=a.at(-1);c.body.push(o(c,n))}s=Cs(A[t.nextIndex],r)}let i=sn({negate:e});return a.length===1?i.body=a[0].body:(i.kind="intersection",i.body=a.map(c=>c.body.length===1?c.body[0]:c)),t.nextIndex++,i}function Of({kind:e,negate:t,value:n},A){let{normalizeUnknownPropertyNames:o,skipPropertyNameValidation:a,unicodePropertyMap:r}=A;if(e==="property"){let s=kt(n);if(rn.has(s)&&!r?.has(s))e="posix",n=s;else return ut(n,{negate:t,normalizeUnknownPropertyNames:o,skipPropertyNameValidation:a,unicodePropertyMap:r})}return e==="posix"?nb(n,{negate:t}):bA(e,{negate:t})}function Jf(e,t,n){let{tokens:A,capturingGroups:o,namedGroupsByName:a,skipLookbehindValidation:r,walk:s}=t,i=ob(e),c=i.type==="AbsenceFunction",d=hs(i),u=d&&i.negate;if(i.type==="CapturingGroup"&&(o.push(i),i.name&&as(a,i.name,[]).push(i)),c&&n.isInAbsenceFunction)throw new Error("Nested absence function not supported by Oniguruma");let g=Es(A[t.nextIndex]);for(;g.type!=="GroupClose";){if(g.type==="Alternator")i.body.push(Re()),t.nextIndex++;else{let p=i.body.at(-1),l=s(p,{...n,isInAbsenceFunction:n.isInAbsenceFunction||c,isInLookbehind:n.isInLookbehind||d,isInNegLookbehind:n.isInNegLookbehind||u});if(p.body.push(l),(d||n.isInLookbehind)&&!r){let B="Lookbehind includes a pattern not allowed by Oniguruma";if(u||n.isInNegLookbehind){if(Bs(l)||l.type==="CapturingGroup")throw new Error(B)}else if(Bs(l)||hs(l)&&l.negate)throw new Error(B)}}g=Es(A[t.nextIndex])}return t.nextIndex++,i}function Wf({kind:e,min:t,max:n},A){let o=A.parent,a=o.body.at(-1);if(!a||!bs(a))throw new Error("Quantifier requires a repeatable token");let r=Ko(e,t,n,a);return o.body.pop(),r}function zf({raw:e},t){let{capturingGroups:n,subroutines:A}=t,o=e.slice(3,-1),a=/^(?[-+]?)0*(?[1-9]\d*)$/.exec(o);if(a){let s=+a.groups.num,i=n.length;if(t.hasNumberedRef=!0,o={"":s,"+":i+s,"-":i+1-s}[a.groups.sign],o<1)throw new Error("Invalid subroutine number")}else o==="0"&&(o=0);let r=Oo(o);return A.push(r),r}function Zf(e,t){if(e!=="repeater")throw new Error(`Unexpected absence function kind "${e}"`);return{type:"AbsenceFunction",kind:e,body:cn(t?.body)}}function Re(e){return{type:"Alternative",body:ws(e?.body)}}function fA(e,t){let n={type:"Assertion",kind:e};return(e==="word_boundary"||e==="text_segment_boundary")&&(n.negate=!!t?.negate),n}function lA(e,t){let n=!!t?.orphan;return{type:"Backreference",ref:e,...n&&{orphan:n}}}function To(e,t){let n={name:void 0,isSubroutined:!1,...t};if(n.name!==void 0&&!ab(n.name))throw new Error(`Group name "${n.name}" invalid in Oniguruma`);return{type:"CapturingGroup",number:e,...n.name&&{name:n.name},...n.isSubroutined&&{isSubroutined:n.isSubroutined},body:cn(t?.body)}}function yt(e,t){let n={useLastValid:!1,...t};if(e>1114111){let A=e.toString(16);if(n.useLastValid)e=1114111;else throw e>1310719?new Error(`Invalid code point out of range "\\x{${A}}"`):new Error(`Invalid code point out of range in JS "\\x{${A}}"`)}return{type:"Character",value:e}}function sn(e){let t={kind:"union",negate:!1,...e};return{type:"CharacterClass",kind:t.kind,negate:t.negate,body:ws(e?.body)}}function Vf(e,t){if(t.valuen)throw new Error("Invalid reversed quantifier range");return{type:"Quantifier",kind:e,min:t,max:n,body:A}}function Ab(e,t){return{type:"Regex",body:cn(t?.body),flags:e}}function Oo(e){return{type:"Subroutine",ref:e}}function ut(e,t){let n={negate:!1,normalizeUnknownPropertyNames:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t},A=n.unicodePropertyMap?.get(kt(e));if(!A){if(n.normalizeUnknownPropertyNames)A=rb(e);else if(n.unicodePropertyMap&&!n.skipPropertyNameValidation)throw new Error(K`Invalid Unicode property "\p{${e}}"`)}return{type:"CharacterSet",kind:"property",value:A??e,negate:n.negate}}function ob({flags:e,kind:t,name:n,negate:A,number:o}){switch(t){case"absence_repeater":return Zf("repeater");case"atomic":return de({atomic:!0});case"capturing":return To(o,{name:n});case"group":return de({flags:e});case"lookahead":case"lookbehind":return ze({behind:t==="lookbehind",negate:A});default:throw new Error(`Unexpected group kind "${t}"`)}}function cn(e){if(e===void 0)e=[Re()];else if(!Array.isArray(e)||!e.length||!e.every(t=>t.type==="Alternative"))throw new Error("Invalid body; expected array of one or more Alternative nodes");return e}function ws(e){if(e===void 0)e=[];else if(!Array.isArray(e)||!e.every(t=>!!t.type))throw new Error("Invalid body; expected array of nodes");return e}function Bs(e){return e.type==="LookaroundAssertion"&&e.kind==="lookahead"}function hs(e){return e.type==="LookaroundAssertion"&&e.kind==="lookbehind"}function ab(e){return/^[\p{Alpha}\p{Pc}][^)]*$/u.test(e)}function rb(e){return e.trim().replace(/[- _]+/g,"_").replace(/[A-Z][a-z]+(?=[A-Z])/g,"$&_").replace(/[A-Za-z]+/g,t=>t[0].toUpperCase()+t.slice(1).toLowerCase())}function kt(e){return e.replace(/[- _]+/g,"").toLowerCase()}function Cs(e,t){let n=t;return Le(e,`Unclosed character class${n?.type==="Character"&&n.value===93&&n.raw==="]"?' (started with "]")':""}`)}function Es(e){return Le(e,"Unclosed group")}function gt(e,t,n=null){function A(a,r){for(let s=0;sA-Za-z\-]|<[=!]|\(DEFINE\))`;function ys(e,t){for(let n=0;n=t&&e[n]++}function ks(e,t,n,A){return e.slice(0,t)+A+e.slice(t+n.length)}var se=Object.freeze({DEFAULT:"DEFAULT",CHAR_CLASS:"CHAR_CLASS"});function dn(e,t,n,A){let o=new RegExp(String.raw`${t}|(?<$skip>\[\^?|\\?.)`,"gsu"),a=[!1],r=0,s="";for(let i of e.matchAll(o)){let{0:c,groups:{$skip:d}}=i;if(!d&&(!A||A===se.DEFAULT==!r)){n instanceof Function?s+=n(i,{context:r?se.CHAR_CLASS:se.DEFAULT,negated:a[a.length-1]}):s+=n;continue}c[0]==="["?(r++,a.push(c[1]==="^")):c==="]"&&r&&(r--,a.pop()),s+=c}return s}function Jo(e,t,n,A){dn(e,t,n,A)}function ib(e,t,n=0,A){if(!new RegExp(t,"su").test(e))return null;let o=new RegExp(`${t}|(?<$skip>\\\\?.)`,"gsu");o.lastIndex=n;let a=0,r;for(;r=o.exec(e);){let{0:s,groups:{$skip:i}}=r;if(!i&&(!A||A===se.DEFAULT==!a))return r;s==="["?a++:s==="]"&&a&&a--,o.lastIndex==r.index&&o.lastIndex++}return null}function un(e,t,n){return!!ib(e,t,0,n)}function Is(e,t){let n=/\\?./gsu;n.lastIndex=t;let A=e.length,o=0,a=1,r;for(;r=n.exec(e);){let[s]=r;if(s==="[")o++;else if(o)s==="]"&&o--;else if(s==="(")a++;else if(s===")"&&(a--,!a)){A=r.index;break}}return e.slice(t,A)}var _s=new RegExp(String.raw`(?${Qs})|(?\((?:\?<[^>]+>)?)|\\?.`,"gsu");function zo(e,t){let n=t?.hiddenCaptures??[],A=t?.captureTransfers??new Map;if(!/\(\?>/.test(e))return{pattern:e,captureTransfers:A,hiddenCaptures:n};let o="(?>",a="(?:(?=(",r=[0],s=[],i=0,c=0,d=NaN,u;do{u=!1;let g=0,p=0,l=!1,B;for(_s.lastIndex=Number.isNaN(d)?0:d+a.length;B=_s.exec(e);){let{0:E,index:h,groups:{capturingStart:f,noncapturingStart:b}}=B;if(E==="[")g++;else if(g)E==="]"&&g--;else if(E===o&&!l)d=h,l=!0;else if(l&&b)p++;else if(f)l?p++:(i++,r.push(i+c));else if(E===")"&&l){if(!p){c++;let C=i+c;if(e=`${e.slice(0,d)}${a}${e.slice(d+o.length,h)}))<$$${C}>)${e.slice(h+1)}`,u=!0,s.push(C),ys(n,C),A.size){let Q=new Map;A.forEach((_,y)=>{Q.set(y>=C?y+1:y,_.map(M=>M>=C?M+1:M))}),A=Q}break}p--}}}while(u);return n.push(...s),e=dn(e,String.raw`\\(?[1-9]\d*)|<\$\$(?\d+)>`,({0:g,groups:{backrefNum:p,wrappedBackrefNum:l}})=>{if(p){let B=+p;if(B>r.length-1)throw new Error(`Backref "${g}" greater than number of captures`);return`\\${r[B]}`}return`\\${l}`},se.DEFAULT),{pattern:e,captureTransfers:A,hiddenCaptures:n}}var Ds=String.raw`(?:[?*+]|\{\d+(?:,\d*)?\})`,Wo=new RegExp(String.raw` +`,A);return{lastIndex:r===-1?t.length:r}}if(/^\s$/.test(n)){let r=/\s+/y;return r.lastIndex=A,{lastIndex:r.exec(t)?r.lastIndex:A}}}if(n===".")return{token:dt("dot",n)};if(n==="^"||n==="$"){let r=e.singleline?{"^":K`\A`,$:K`\Z`}[n]:n;return{token:rs(r,n)}}return n==="|"?{token:Qf(n)}:Yo.test(n)?{tokens:Pf(n)}:{token:Ne(We(n),n)}}function Ef(e,t,n){let A=[is(t[1]==="^",t)],o=1,a;for(qo.lastIndex=n;a=qo.exec(e);){let r=a[0];if(r[0]==="["&&r[1]!==":")o++,A.push(is(r[1]==="^",r));else if(r==="]"){if(A.at(-1).type==="CharacterClassOpen")A.push(Ne(93,r));else if(o--,A.push(yf(r)),!o)break}else{let s=wf(r);Array.isArray(s)?A.push(...s):A.push(s)}}return{tokens:A,lastIndex:qo.lastIndex||e.length}}function wf(e){if(e[0]==="\\")return ls(e,{inCharClass:!0});if(e[0]==="["){let t=/\[:(?\^?)(?[a-z]+):\]/.exec(e);if(!t||!rn.has(t.groups.name))throw new Error(`Invalid POSIX class "${e}"`);return dt("posix",e,{value:t.groups.name,negate:!!t.groups.negate})}return e==="-"?kf(e):e==="&&"?If(e):Ne(We(e),e)}function ls(e,{inCharClass:t}){let n=e[1];if(n==="c"||n==="C")return Sf(e);if("dDhHsSwW".includes(n))return Rf(e);if(e.startsWith(K`\o{`))throw new Error(`Incomplete, invalid, or unsupported octal code point "${e}"`);if(/^\\[pP]\{/.test(e)){if(e.length===3)throw new Error(`Incomplete or invalid Unicode property "${e}"`);return Gf(e)}if(/^\\x[89A-Fa-f]\p{AHex}/u.test(e))try{let A=e.split(/\\x/).slice(1).map(r=>parseInt(r,16)),o=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}).decode(new Uint8Array(A)),a=new TextEncoder;return[...o].map(r=>{let s=[...a.encode(r)].map(i=>`\\x${i.toString(16)}`).join("");return Ne(We(r),s)})}catch{throw new Error(`Multibyte code "${e}" incomplete or invalid in Oniguruma`)}if(n==="u"||n==="x")return Ne(jf(e),e);if(ss.has(n))return Ne(ss.get(n),e);if(/\d/.test(n))return _f(t,e);if(e==="\\")throw new Error(K`Incomplete escape "\"`);if(n==="M")throw new Error(`Unsupported meta "${e}"`);if([...e].length===2)return Ne(e.codePointAt(1),e);throw new Error(`Unexpected escape "${e}"`)}function Qf(e){return{type:"Alternator",raw:e}}function rs(e,t){return{type:"Assertion",kind:e,raw:t}}function ms(e){return{type:"Backreference",raw:e}}function Ne(e,t){return{type:"Character",value:e,raw:t}}function yf(e){return{type:"CharacterClassClose",raw:e}}function kf(e){return{type:"CharacterClassHyphen",raw:e}}function If(e){return{type:"CharacterClassIntersector",raw:e}}function is(e,t){return{type:"CharacterClassOpen",negate:e,raw:t}}function dt(e,t,n={}){return{type:"CharacterSet",kind:e,...n,raw:t}}function fs(e,t,n={}){return e==="keep"?{type:"Directive",kind:e,raw:t}:{type:"Directive",kind:e,flags:Le(n.flags),raw:t}}function _f(e,t){return{type:"EscapedNumber",inCharClass:e,raw:t}}function Df(e){return{type:"GroupClose",raw:e}}function Qt(e,t,n={}){return{type:"GroupOpen",kind:e,...n,raw:t}}function Ff(e,t,n,A){return{type:"NamedCallout",kind:e,tag:t,arguments:n,raw:A}}function vf(e,t,n,A){return{type:"Quantifier",kind:e,min:t,max:n,raw:A}}function xf(e){return{type:"Subroutine",raw:e}}var Mf=new Set(["COUNT","CMP","ERROR","FAIL","MAX","MISMATCH","SKIP","TOTAL_COUNT"]),ss=new Map([["a",7],["b",8],["e",27],["f",12],["n",10],["r",13],["t",9],["v",11]]);function Sf(e){let t=e[1]==="c"?e[2]:e[3];if(!t||!/[A-Za-z]/.test(t))throw new Error(`Unsupported control character "${e}"`);return Ne(We(t.toUpperCase())-64,e)}function Lf(e,t){let{on:n,off:A}=/^\(\?(?[imx]*)(?:-(?[-imx]*))?/.exec(e).groups;A??(A="");let o=(t.getCurrentModX()||n.includes("x"))&&!A.includes("x"),a=ds(n),r=ds(A),s={};if(a&&(s.enable=a),r&&(s.disable=r),e.endsWith(")"))return t.replaceCurrentModX(o),fs("flags",e,{flags:s});if(e.endsWith(":"))return t.pushModX(o),t.numOpenGroups++,Qt("group",e,{...(a||r)&&{flags:s}});throw new Error(`Unexpected flag modifier "${e}"`)}function Nf(e){let t=/\(\*(?[A-Za-z_]\w*)?(?:\[(?(?:[A-Za-z_]\w*)?)\])?(?:\{(?[^}]*)\})?\)/.exec(e);if(!t)throw new Error(`Incomplete or invalid named callout "${e}"`);let{name:n,tag:A,args:o}=t.groups;if(!n)throw new Error(`Invalid named callout "${e}"`);if(A==="")throw new Error(`Named callout tag with empty value not allowed "${e}"`);let a=o?o.split(",").filter(d=>d!=="").map(d=>/^[+-]?\d+$/.test(d)?+d:d):[],[r,s,i]=a,c=Mf.has(n)?n.toLowerCase():"custom";switch(c){case"fail":case"mismatch":case"skip":if(a.length>0)throw new Error(`Named callout arguments not allowed "${a}"`);break;case"error":if(a.length>1)throw new Error(`Named callout allows only one argument "${a}"`);if(typeof r=="string")throw new Error(`Named callout argument must be a number "${r}"`);break;case"max":if(!a.length||a.length>2)throw new Error(`Named callout must have one or two arguments "${a}"`);if(typeof r=="string"&&!/^[A-Za-z_]\w*$/.test(r))throw new Error(`Named callout argument one must be a tag or number "${r}"`);if(a.length===2&&(typeof s=="number"||!/^[<>X]$/.test(s)))throw new Error(`Named callout optional argument two must be '<', '>', or 'X' "${s}"`);break;case"count":case"total_count":if(a.length>1)throw new Error(`Named callout allows only one argument "${a}"`);if(a.length===1&&(typeof r=="number"||!/^[<>X]$/.test(r)))throw new Error(`Named callout optional argument must be '<', '>', or 'X' "${r}"`);break;case"cmp":if(a.length!==3)throw new Error(`Named callout must have three arguments "${a}"`);if(typeof r=="string"&&!/^[A-Za-z_]\w*$/.test(r))throw new Error(`Named callout argument one must be a tag or number "${r}"`);if(typeof s=="number"||!/^(?:[<>!=]=|[<>])$/.test(s))throw new Error(`Named callout argument two must be '==', '!=', '>', '<', '>=', or '<=' "${s}"`);if(typeof i=="string"&&!/^[A-Za-z_]\w*$/.test(i))throw new Error(`Named callout argument three must be a tag or number "${i}"`);break;case"custom":throw new Error(`Undefined callout name "${n}"`);default:throw new Error(`Unexpected named callout kind "${c}"`)}return Ff(c,A??null,o?.split(",")??null,e)}function cs(e){let t=null,n,A;if(e[0]==="{"){let{minStr:o,maxStr:a}=/^\{(?\d*)(?:,(?\d*))?/.exec(e).groups,r=1e5;if(+o>r||a&&+a>r)throw new Error("Quantifier value unsupported in Oniguruma");if(n=+o,A=a===void 0?+o:a===""?1/0:+a,n>A&&(t="possessive",[n,A]=[A,n]),e.endsWith("?")){if(t==="possessive")throw new Error('Unsupported possessive interval quantifier chain with "?"');t="lazy"}else t||(t="greedy")}else n=e[0]==="+"?1:0,A=e[0]==="?"?1:1/0,t=e[1]==="+"?"possessive":e[1]==="?"?"lazy":"greedy";return vf(t,n,A,e)}function Rf(e){let t=e[1].toLowerCase();return dt({d:"digit",h:"hex",s:"space",w:"word"}[t],e,{negate:e[1]!==t})}function Gf(e){let{p:t,neg:n,value:A}=/^\\(?

[pP])\{(?\^?)(?[^}]+)/.exec(e).groups;return dt("property",e,{value:A,negate:t==="P"&&!n||t==="p"&&!!n})}function ds(e){let t={};return e.includes("i")&&(t.ignoreCase=!0),e.includes("m")&&(t.dotAll=!0),e.includes("x")&&(t.extended=!0),Object.keys(t).length?t:null}function Hf(e){let t={ignoreCase:!1,dotAll:!1,extended:!1,digitIsAscii:!1,posixIsAscii:!1,spaceIsAscii:!1,wordIsAscii:!1,textSegmentMode:null};for(let n=0;n\p{AHex}+)/u.exec(e).groups.hex:e.slice(2);return parseInt(t,16)}function Uf(e,t){let{raw:n,inCharClass:A}=e,o=n.slice(1);if(!A&&(o!=="0"&&o.length===1||o[0]!=="0"&&+o<=t))return[ms(n)];let a=[],r=o.match(/^[0-7]+|\d/g);for(let s=0;s127)throw new Error(K`Octal encoded byte above 177 unsupported "${n}"`)}else c=We(i);a.push(Ne(c,(s===0?"\\":"")+i))}return a}function Pf(e){let t=[],n=new RegExp(Yo,"gy"),A;for(;A=n.exec(e);){let o=A[0];if(o[0]==="{"){let a=/^\{(?\d+),(?\d+)\}\??$/.exec(o);if(a){let{min:r,max:s}=a.groups;if(+r>+s&&o.endsWith("?")){n.lastIndex--,t.push(cs(o.slice(0,-1)));continue}}}t.push(cs(o))}return t}function pA(e,t){if(!Array.isArray(e.body))throw new Error("Expected node with body array");if(e.body.length!==1)return!1;let n=e.body[0];return!t||Object.keys(t).every(A=>t[A]===n[A])}function bs(e){return $f.has(e.type)}var $f=new Set(["AbsenceFunction","Backreference","CapturingGroup","Character","CharacterClass","CharacterSet","Group","Quantifier","Subroutine"]);function mA(e,t={}){let n={flags:"",normalizeUnknownPropertyNames:!1,skipBackrefValidation:!1,skipLookbehindValidation:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}},A=ps(e,{flags:n.flags,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline}}),o=(g,p)=>{let l=A.tokens[a.nextIndex];switch(a.parent=g,a.nextIndex++,l.type){case"Alternator":return Re();case"Assertion":return qf(l);case"Backreference":return Yf(l,a);case"Character":return yt(l.value,{useLastValid:!!p.isCheckingRangeEnd});case"CharacterClassHyphen":return Tf(l,a,p);case"CharacterClassOpen":return Kf(l,a,p);case"CharacterSet":return Of(l,a);case"Directive":return Xf(l.kind,{flags:l.flags});case"GroupOpen":return Jf(l,a,p);case"NamedCallout":return tb(l.kind,l.tag,l.arguments);case"Quantifier":return Wf(l,a);case"Subroutine":return zf(l,a);default:throw new Error(`Unexpected token type "${l.type}"`)}},a={capturingGroups:[],hasNumberedRef:!1,namedGroupsByName:new Map,nextIndex:0,normalizeUnknownPropertyNames:n.normalizeUnknownPropertyNames,parent:null,skipBackrefValidation:n.skipBackrefValidation,skipLookbehindValidation:n.skipLookbehindValidation,skipPropertyNameValidation:n.skipPropertyNameValidation,subroutines:[],tokens:A.tokens,unicodePropertyMap:n.unicodePropertyMap,walk:o},r=Ab(eb(A.flags)),s=r.body[0];for(;a.nextIndexi.length)throw new Error("Subroutine uses a group number that's not defined");g&&(i[g-1].isSubroutined=!0)}else if(d.has(g)){if(d.get(g).length>1)throw new Error(K`Subroutine uses a duplicate group name "\g<${g}>"`);d.get(g)[0].isSubroutined=!0}else throw new Error(K`Subroutine uses a group name that's not defined "\g<${g}>"`);return r}function qf({kind:e}){return fA(Le({"^":"line_start",$:"line_end","\\A":"string_start","\\b":"word_boundary","\\B":"word_boundary","\\G":"search_start","\\y":"text_segment_boundary","\\Y":"text_segment_boundary","\\z":"string_end","\\Z":"string_end_newline"}[e],`Unexpected assertion kind "${e}"`),{negate:e===K`\B`||e===K`\Y`})}function Yf({raw:e},t){let n=/^\\k[<']/.test(e),A=n?e.slice(3,-1):e.slice(1),o=(a,r=!1)=>{let s=t.capturingGroups.length,i=!1;if(a>s)if(t.skipBackrefValidation)i=!0;else throw new Error(`Not enough capturing groups defined to the left "${e}"`);return t.hasNumberedRef=!0,lA(r?s+1-a:a,{orphan:i})};if(n){let a=/^(?-?)0*(?[1-9]\d*)$/.exec(A);if(a)return o(+a.groups.num,!!a.groups.sign);if(/[-+]/.test(A))throw new Error(`Invalid backref name "${e}"`);if(!t.namedGroupsByName.has(A))throw new Error(`Group name not defined to the left "${e}"`);return lA(A)}return o(+A)}function Tf(e,t,n){let{tokens:A,walk:o}=t,a=t.parent,r=a.body.at(-1),s=A[t.nextIndex];if(!n.isCheckingRangeEnd&&r&&r.type!=="CharacterClass"&&r.type!=="CharacterClassRange"&&s&&s.type!=="CharacterClassOpen"&&s.type!=="CharacterClassClose"&&s.type!=="CharacterClassIntersector"){let i=o(a,{...n,isCheckingRangeEnd:!0});if(r.type==="Character"&&i.type==="Character")return a.body.pop(),Vf(r,i);throw new Error("Invalid character class range")}return yt(We("-"))}function Kf({negate:e},t,n){let{tokens:A,walk:o}=t,a=[sn()],r=A[t.nextIndex],s=Cs(r);for(;s.type!=="CharacterClassClose";){if(s.type==="CharacterClassIntersector")a.push(sn()),t.nextIndex++;else{let c=a.at(-1);c.body.push(o(c,n))}s=Cs(A[t.nextIndex],r)}let i=sn({negate:e});return a.length===1?i.body=a[0].body:(i.kind="intersection",i.body=a.map(c=>c.body.length===1?c.body[0]:c)),t.nextIndex++,i}function Of({kind:e,negate:t,value:n},A){let{normalizeUnknownPropertyNames:o,skipPropertyNameValidation:a,unicodePropertyMap:r}=A;if(e==="property"){let s=kt(n);if(rn.has(s)&&!r?.has(s))e="posix",n=s;else return ut(n,{negate:t,normalizeUnknownPropertyNames:o,skipPropertyNameValidation:a,unicodePropertyMap:r})}return e==="posix"?nb(n,{negate:t}):bA(e,{negate:t})}function Jf(e,t,n){let{tokens:A,capturingGroups:o,namedGroupsByName:a,skipLookbehindValidation:r,walk:s}=t,i=ob(e),c=i.type==="AbsenceFunction",d=hs(i),u=d&&i.negate;if(i.type==="CapturingGroup"&&(o.push(i),i.name&&as(a,i.name,[]).push(i)),c&&n.isInAbsenceFunction)throw new Error("Nested absence function not supported by Oniguruma");let g=Es(A[t.nextIndex]);for(;g.type!=="GroupClose";){if(g.type==="Alternator")i.body.push(Re()),t.nextIndex++;else{let p=i.body.at(-1),l=s(p,{...n,isInAbsenceFunction:n.isInAbsenceFunction||c,isInLookbehind:n.isInLookbehind||d,isInNegLookbehind:n.isInNegLookbehind||u});if(p.body.push(l),(d||n.isInLookbehind)&&!r){let B="Lookbehind includes a pattern not allowed by Oniguruma";if(u||n.isInNegLookbehind){if(Bs(l)||l.type==="CapturingGroup")throw new Error(B)}else if(Bs(l)||hs(l)&&l.negate)throw new Error(B)}}g=Es(A[t.nextIndex])}return t.nextIndex++,i}function Wf({kind:e,min:t,max:n},A){let o=A.parent,a=o.body.at(-1);if(!a||!bs(a))throw new Error("Quantifier requires a repeatable token");let r=Ko(e,t,n,a);return o.body.pop(),r}function zf({raw:e},t){let{capturingGroups:n,subroutines:A}=t,o=e.slice(3,-1),a=/^(?[-+]?)0*(?[1-9]\d*)$/.exec(o);if(a){let s=+a.groups.num,i=n.length;if(t.hasNumberedRef=!0,o={"":s,"+":i+s,"-":i+1-s}[a.groups.sign],o<1)throw new Error("Invalid subroutine number")}else o==="0"&&(o=0);let r=Oo(o);return A.push(r),r}function Zf(e,t){if(e!=="repeater")throw new Error(`Unexpected absence function kind "${e}"`);return{type:"AbsenceFunction",kind:e,body:cn(t?.body)}}function Re(e){return{type:"Alternative",body:ws(e?.body)}}function fA(e,t){let n={type:"Assertion",kind:e};return(e==="word_boundary"||e==="text_segment_boundary")&&(n.negate=!!t?.negate),n}function lA(e,t){let n=!!t?.orphan;return{type:"Backreference",ref:e,...n&&{orphan:n}}}function To(e,t){let n={name:void 0,isSubroutined:!1,...t};if(n.name!==void 0&&!ab(n.name))throw new Error(`Group name "${n.name}" invalid in Oniguruma`);return{type:"CapturingGroup",number:e,...n.name&&{name:n.name},...n.isSubroutined&&{isSubroutined:n.isSubroutined},body:cn(t?.body)}}function yt(e,t){let n={useLastValid:!1,...t};if(e>1114111){let A=e.toString(16);if(n.useLastValid)e=1114111;else throw e>1310719?new Error(`Invalid code point out of range "\\x{${A}}"`):new Error(`Invalid code point out of range in JS "\\x{${A}}"`)}return{type:"Character",value:e}}function sn(e){let t={kind:"union",negate:!1,...e};return{type:"CharacterClass",kind:t.kind,negate:t.negate,body:ws(e?.body)}}function Vf(e,t){if(t.valuen)throw new Error("Invalid reversed quantifier range");return{type:"Quantifier",kind:e,min:t,max:n,body:A}}function Ab(e,t){return{type:"Regex",body:cn(t?.body),flags:e}}function Oo(e){return{type:"Subroutine",ref:e}}function ut(e,t){let n={negate:!1,normalizeUnknownPropertyNames:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t},A=n.unicodePropertyMap?.get(kt(e));if(!A){if(n.normalizeUnknownPropertyNames)A=rb(e);else if(n.unicodePropertyMap&&!n.skipPropertyNameValidation)throw new Error(K`Invalid Unicode property "\p{${e}}"`)}return{type:"CharacterSet",kind:"property",value:A??e,negate:n.negate}}function ob({flags:e,kind:t,name:n,negate:A,number:o}){switch(t){case"absence_repeater":return Zf("repeater");case"atomic":return de({atomic:!0});case"capturing":return To(o,{name:n});case"group":return de({flags:e});case"lookahead":case"lookbehind":return ze({behind:t==="lookbehind",negate:A});default:throw new Error(`Unexpected group kind "${t}"`)}}function cn(e){if(e===void 0)e=[Re()];else if(!Array.isArray(e)||!e.length||!e.every(t=>t.type==="Alternative"))throw new Error("Invalid body; expected array of one or more Alternative nodes");return e}function ws(e){if(e===void 0)e=[];else if(!Array.isArray(e)||!e.every(t=>!!t.type))throw new Error("Invalid body; expected array of nodes");return e}function Bs(e){return e.type==="LookaroundAssertion"&&e.kind==="lookahead"}function hs(e){return e.type==="LookaroundAssertion"&&e.kind==="lookbehind"}function ab(e){return/^[\p{Alpha}\p{Pc}][^)]*$/u.test(e)}function rb(e){return e.trim().replace(/[- _]+/g,"_").replace(/[A-Z][a-z]+(?=[A-Z])/g,"$&_").replace(/[A-Za-z]+/g,t=>t[0].toUpperCase()+t.slice(1).toLowerCase())}function kt(e){return e.replace(/[- _]+/g,"").toLowerCase()}function Cs(e,t){let n=t;return Le(e,`Unclosed character class${n?.type==="Character"&&n.value===93&&n.raw==="]"?' (started with "]")':""}`)}function Es(e){return Le(e,"Unclosed group")}function gt(e,t,n=null){function A(a,r){for(let s=0;sA-Za-z\-]|<[=!]|\(DEFINE\))`;function ys(e,t){for(let n=0;n=t&&e[n]++}function ks(e,t,n,A){return e.slice(0,t)+A+e.slice(t+n.length)}var se=Object.freeze({DEFAULT:"DEFAULT",CHAR_CLASS:"CHAR_CLASS"});function dn(e,t,n,A){let o=new RegExp(String.raw`${t}|(?<$skip>\[\^?|\\?.)`,"gsu"),a=[!1],r=0,s="";for(let i of e.matchAll(o)){let{0:c,groups:{$skip:d}}=i;if(!d&&(!A||A===se.DEFAULT==!r)){n instanceof Function?s+=n(i,{context:r?se.CHAR_CLASS:se.DEFAULT,negated:a[a.length-1]}):s+=n;continue}c[0]==="["?(r++,a.push(c[1]==="^")):c==="]"&&r&&(r--,a.pop()),s+=c}return s}function Jo(e,t,n,A){dn(e,t,n,A)}function ib(e,t,n=0,A){if(!new RegExp(t,"su").test(e))return null;let o=new RegExp(`${t}|(?<$skip>\\\\?.)`,"gsu");o.lastIndex=n;let a=0,r;for(;r=o.exec(e);){let{0:s,groups:{$skip:i}}=r;if(!i&&(!A||A===se.DEFAULT==!a))return r;s==="["?a++:s==="]"&&a&&a--,o.lastIndex==r.index&&o.lastIndex++}return null}function un(e,t,n){return!!ib(e,t,0,n)}function Is(e,t){let n=/\\?./gsu;n.lastIndex=t;let A=e.length,o=0,a=1,r;for(;r=n.exec(e);){let[s]=r;if(s==="[")o++;else if(o)s==="]"&&o--;else if(s==="(")a++;else if(s===")"&&(a--,!a)){A=r.index;break}}return e.slice(t,A)}var _s=new RegExp(String.raw`(?${Qs})|(?\((?:\?<[^>]+>)?)|\\?.`,"gsu");function zo(e,t){let n=t?.hiddenCaptures??[],A=t?.captureTransfers??new Map;if(!/\(\?>/.test(e))return{pattern:e,captureTransfers:A,hiddenCaptures:n};let o="(?>",a="(?:(?=(",r=[0],s=[],i=0,c=0,d=Number.NaN,u;do{u=!1;let g=0,p=0,l=!1,B;for(_s.lastIndex=Number.isNaN(d)?0:d+a.length;B=_s.exec(e);){let{0:E,index:h,groups:{capturingStart:f,noncapturingStart:b}}=B;if(E==="[")g++;else if(g)E==="]"&&g--;else if(E===o&&!l)d=h,l=!0;else if(l&&b)p++;else if(f)l?p++:(i++,r.push(i+c));else if(E===")"&&l){if(!p){c++;let C=i+c;if(e=`${e.slice(0,d)}${a}${e.slice(d+o.length,h)}))<$$${C}>)${e.slice(h+1)}`,u=!0,s.push(C),ys(n,C),A.size){let Q=new Map;A.forEach((_,y)=>{Q.set(y>=C?y+1:y,_.map(M=>M>=C?M+1:M))}),A=Q}break}p--}}}while(u);return n.push(...s),e=dn(e,String.raw`\\(?[1-9]\d*)|<\$\$(?\d+)>`,({0:g,groups:{backrefNum:p,wrappedBackrefNum:l}})=>{if(p){let B=+p;if(B>r.length-1)throw new Error(`Backref "${g}" greater than number of captures`);return`\\${r[B]}`}return`\\${l}`},se.DEFAULT),{pattern:e,captureTransfers:A,hiddenCaptures:n}}var Ds=String.raw`(?:[?*+]|\{\d+(?:,\d*)?\})`,Wo=new RegExp(String.raw` \\(?: \d+ | c[A-Za-z] | [gk]<[^>]+> diff --git a/scripts/build-diffs-viewer-runtime.mjs b/scripts/build-diffs-viewer-runtime.mjs index fd0145be251f..5d4f739f1faa 100644 --- a/scripts/build-diffs-viewer-runtime.mjs +++ b/scripts/build-diffs-viewer-runtime.mjs @@ -38,6 +38,9 @@ export async function buildDiffsViewerRuntime(targetName) { target: "es2020", format: "esm", minify: true, + define: { + NaN: "Number.NaN", + }, legalComments: "none", outfile: outputPath, write: false, diff --git a/scripts/release-check.ts b/scripts/release-check.ts index 74770937d68d..d4a149ecc339 100755 --- a/scripts/release-check.ts +++ b/scripts/release-check.ts @@ -80,6 +80,7 @@ const requiredPathGroups = [ "scripts/postinstall-bundled-plugins.mjs", "dist/plugin-sdk/compat.js", "dist/plugin-sdk/root-alias.cjs", + "dist/agents/model-provider-auth.worker.js", "dist/task-registry-control.runtime.js", "dist/telegram-ingress-worker.runtime.js", "dist/build-info.json", diff --git a/src/agents/auth-profiles.ts b/src/agents/auth-profiles.ts index bcfdc2886a41..201da7c081e5 100644 --- a/src/agents/auth-profiles.ts +++ b/src/agents/auth-profiles.ts @@ -52,6 +52,7 @@ export { clearRuntimeAuthProfileStoreSnapshots, ensureAuthProfileStore, ensureAuthProfileStoreWithoutExternalProfiles, + getRuntimeAuthProfileStoreSnapshot, hasAnyAuthProfileStoreSource, loadAuthProfileStoreForSecretsRuntime, loadAuthProfileStoreWithoutExternalProfiles, diff --git a/src/agents/auth-profiles/store.ts b/src/agents/auth-profiles/store.ts index c638d108cc3c..c55408c72d56 100644 --- a/src/agents/auth-profiles/store.ts +++ b/src/agents/auth-profiles/store.ts @@ -35,7 +35,7 @@ import { } from "./persisted.js"; import { clearRuntimeAuthProfileStoreSnapshots as clearRuntimeAuthProfileStoreSnapshotsImpl, - getRuntimeAuthProfileStoreSnapshot, + getRuntimeAuthProfileStoreSnapshot as getRuntimeAuthProfileStoreSnapshotImpl, hasRuntimeAuthProfileStoreSnapshot, replaceRuntimeAuthProfileStoreSnapshots as replaceRuntimeAuthProfileStoreSnapshotsImpl, setRuntimeAuthProfileStoreSnapshot, @@ -150,8 +150,8 @@ function resolveRuntimeAuthProfileStore( ): AuthProfileStore | null { const mainKey = resolveAuthStorePath(undefined); const requestedKey = resolveAuthStorePath(agentDir); - const mainStore = getRuntimeAuthProfileStoreSnapshot(undefined); - const requestedStore = getRuntimeAuthProfileStoreSnapshot(agentDir); + const mainStore = getRuntimeAuthProfileStoreSnapshotImpl(undefined); + const requestedStore = getRuntimeAuthProfileStoreSnapshotImpl(agentDir); if (!agentDir || requestedKey === mainKey) { if (!mainStore) { @@ -899,6 +899,8 @@ export function ensureAuthProfileStore( externalCli?: ExternalCliAuthDiscovery; externalCliProviderIds?: Iterable; externalCliProfileIds?: Iterable; + readOnly?: boolean; + syncExternalCli?: boolean; }, ): AuthProfileStore { const externalCli = resolveExternalCliOverlayOptions(options); @@ -921,7 +923,12 @@ export function ensureAuthProfileStore( export function ensureAuthProfileStoreWithoutExternalProfiles( agentDir?: string, - options?: { allowKeychainPrompt?: boolean; resolveLegacyOAuthSidecars?: boolean }, + options?: { + allowKeychainPrompt?: boolean; + readOnly?: boolean; + resolveLegacyOAuthSidecars?: boolean; + syncExternalCli?: boolean; + }, ): AuthProfileStore { const effectiveOptions: LoadAuthProfileStoreOptions = { ...options, @@ -1015,6 +1022,12 @@ export function ensureAuthProfileStoreForLocalUpdate(agentDir?: string): AuthPro export { hasAnyAuthProfileStoreSource } from "./source-check.js"; +export function getRuntimeAuthProfileStoreSnapshot( + agentDir?: string, +): AuthProfileStore | undefined { + return getRuntimeAuthProfileStoreSnapshotImpl(agentDir); +} + export function replaceRuntimeAuthProfileStoreSnapshots( entries: Array<{ agentDir?: string; store: AuthProfileStore }>, ): void { diff --git a/src/agents/model-auth.ts b/src/agents/model-auth.ts index 1803a3ee4537..1f2ac941a5ff 100644 --- a/src/agents/model-auth.ts +++ b/src/agents/model-auth.ts @@ -65,6 +65,7 @@ export type ProviderCredentialPrecedence = "profile-first" | "env-first"; export type RuntimeProviderAuthLookup = { envApiKey: Pick; syntheticAuthProviderRefs?: readonly string[]; + syntheticAuthProviderRefsComplete?: boolean; }; const log = createSubsystemLogger("model-auth"); @@ -125,6 +126,7 @@ export function createRuntimeProviderAuthLookup(params: { syntheticAuthProviderRefs: syntheticAuthProviderRefs?.complete ? syntheticAuthProviderRefs.refs : undefined, + syntheticAuthProviderRefsComplete: syntheticAuthProviderRefs?.complete, }; } diff --git a/src/agents/model-provider-auth.test.ts b/src/agents/model-provider-auth.test.ts index 5d9a5e651631..3f2c9cea63db 100644 --- a/src/agents/model-provider-auth.test.ts +++ b/src/agents/model-provider-auth.test.ts @@ -1,5 +1,10 @@ +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; import { afterEach, describe, expect, it, vi } from "vitest"; import type { OpenClawConfig } from "../config/types.openclaw.js"; +import type { AuthProfileStore } from "./auth-profiles.js"; import type { ModelCatalogEntry } from "./model-catalog.types.js"; const modelCatalogMocks = vi.hoisted(() => ({ @@ -14,6 +19,7 @@ const modelAuthMocks = vi.hoisted(() => ({ authEvidenceMap: {}, }, syntheticAuthProviderRefs: [], + syntheticAuthProviderRefsComplete: true, })), hasRuntimeAvailableProviderAuth: vi.fn< @@ -31,6 +37,9 @@ const authProfilesMocks = vi.hoisted(() => ({ ensureAuthProfileStoreWithoutExternalProfiles: vi.fn(() => ({ profiles: {} })), externalCliDiscoveryForProviders: vi.fn(() => ({}) as never), externalCliDiscoveryForProviderAuth: vi.fn(() => ({}) as never), + getRuntimeAuthProfileStoreSnapshot: vi.fn<(agentDir?: string) => AuthProfileStore | undefined>( + () => undefined, + ), listProfilesForProvider: vi.fn(() => []), })); @@ -49,6 +58,7 @@ vi.mock("./auth-profiles.js", () => ({ authProfilesMocks.ensureAuthProfileStoreWithoutExternalProfiles, externalCliDiscoveryForProviders: authProfilesMocks.externalCliDiscoveryForProviders, externalCliDiscoveryForProviderAuth: authProfilesMocks.externalCliDiscoveryForProviderAuth, + getRuntimeAuthProfileStoreSnapshot: authProfilesMocks.getRuntimeAuthProfileStoreSnapshot, listProfilesForProvider: authProfilesMocks.listProfilesForProvider, })); @@ -59,15 +69,18 @@ vi.mock("./workspace.js", () => ({ vi.mock("./agent-scope-config.js", () => ({ listAgentIds: () => ["default"], resolveAgentDir: () => "/warm/default-agent", + resolveDefaultAgentDir: () => "/warm/default-agent", resolveAgentWorkspaceDir: () => "/warm/default-workspace", resolveDefaultAgentId: () => "default", })); const { clearCurrentProviderAuthState, + buildCurrentProviderAuthStateSnapshot, createProviderAuthChecker, hasAuthForModelProvider, warmCurrentProviderAuthState, + warmCurrentProviderAuthStateOffMainThread, } = await import("./model-provider-auth.js"); describe("prepared provider auth state", () => { @@ -109,6 +122,62 @@ describe("prepared provider auth state", () => { }); }); + it("disables persisted auth-store sync for read-only warm snapshots", async () => { + const cfg = {} as OpenClawConfig; + const externalCli = { mode: "scoped" }; + modelCatalogMocks.loadModelCatalog.mockResolvedValue([ + { id: "gpt", name: "gpt", provider: "openai" }, + ]); + authProfilesMocks.externalCliDiscoveryForProviders.mockReturnValue(externalCli as never); + modelAuthMocks.hasRuntimeAvailableProviderAuth.mockReturnValue(false); + + await buildCurrentProviderAuthStateSnapshot(cfg, { readOnlyAuthStore: true }); + + expect(authProfilesMocks.ensureAuthProfileStore).toHaveBeenCalledWith("/warm/default-agent", { + config: cfg, + externalCli, + readOnly: true, + syncExternalCli: false, + }); + }); + + it("does not cache false worker answers for process-local plugin synthetic auth", async () => { + const cfg = { + models: { + providers: { + "plugin-provider": { + api: "plugin-api", + baseUrl: "https://example.com/v1", + models: [{ id: "plugin-model", name: "Plugin Model" }], + }, + }, + }, + } as unknown as OpenClawConfig; + modelCatalogMocks.loadModelCatalog.mockResolvedValue([ + { id: "plugin-model", name: "Plugin Model", provider: "plugin-provider" }, + ]); + modelAuthMocks.hasRuntimeAvailableProviderAuth.mockReturnValue(false); + + const snapshot = await buildCurrentProviderAuthStateSnapshot(cfg, { + runtimeAuthLookups: new Map([ + [ + "default", + { + envApiKey: { + aliasMap: {}, + candidateMap: {}, + authEvidenceMap: {}, + }, + syntheticAuthProviderRefs: ["plugin-api"], + syntheticAuthProviderRefsComplete: true, + }, + ], + ]), + }); + + expect(snapshot.agents[0]?.providers).toEqual([]); + }); + it("hasAuthForModelProvider returns the prepared answer after warm and falls through to compute after clear", async () => { const cfg = {} as OpenClawConfig; modelCatalogMocks.loadModelCatalog.mockResolvedValue([ @@ -326,4 +395,198 @@ describe("prepared provider auth state", () => { await expect(hasAuthForModelProvider({ provider: "openai", cfg })).resolves.toBe(true); expect(modelAuthMocks.hasRuntimeAvailableProviderAuth).toHaveBeenCalledTimes(1); }); + + it("publishes provider auth state produced by the off-main-thread warm runner", async () => { + const cfg = { gateway: { port: 18789 } } as OpenClawConfig; + modelCatalogMocks.loadModelCatalog.mockResolvedValue([ + { id: "gpt", name: "gpt", provider: "openai" }, + ]); + modelAuthMocks.hasRuntimeAvailableProviderAuth.mockReturnValue(true); + const snapshot = await buildCurrentProviderAuthStateSnapshot(cfg); + expect(modelAuthMocks.hasRuntimeAvailableProviderAuth).toHaveBeenCalledTimes(1); + + clearCurrentProviderAuthState(); + modelAuthMocks.hasRuntimeAvailableProviderAuth.mockClear(); + const runWorker = vi.fn(async () => snapshot); + await warmCurrentProviderAuthStateOffMainThread(cfg, { runWorker }); + + modelAuthMocks.hasRuntimeAvailableProviderAuth.mockReturnValue(false); + await expect(hasAuthForModelProvider({ provider: "openai", cfg })).resolves.toBe(true); + const runtimeAuthLookup = + modelAuthMocks.createRuntimeProviderAuthLookup.mock.results.at(-1)?.value; + expect(runWorker).toHaveBeenCalledWith({ + cfg, + runtimeAuthLookups: [{ agentId: "default", lookup: runtimeAuthLookup }], + timeoutMs: 120_000, + isCancelled: expect.any(Function), + workerUrl: undefined, + }); + expect(modelAuthMocks.hasRuntimeAvailableProviderAuth).not.toHaveBeenCalled(); + }); + + it("passes runtime auth profile snapshots to the off-main-thread warm runner", async () => { + const cfg = {} as OpenClawConfig; + const store = { + version: 1, + profiles: { + runtime: { + type: "api_key" as const, + provider: "openai", + key: "test-key", + }, + }, + }; + authProfilesMocks.getRuntimeAuthProfileStoreSnapshot.mockImplementation((agentDir) => + agentDir === "/warm/default-agent" ? store : undefined, + ); + const snapshot = { + agents: [ + { + agentId: "default", + configFingerprint: "fingerprint", + providers: [["openai", true] as [string, boolean]], + }, + ], + }; + const runWorker = vi.fn(async () => snapshot); + + await warmCurrentProviderAuthStateOffMainThread(cfg, { runWorker }); + + const runtimeAuthLookup = + modelAuthMocks.createRuntimeProviderAuthLookup.mock.results.at(-1)?.value; + expect(runWorker).toHaveBeenCalledWith({ + cfg, + runtimeAuthStores: [ + { + agentDir: "/warm/default-agent", + store: { + version: 1, + profiles: { + runtime: { + type: "api_key", + provider: "openai", + }, + }, + }, + }, + ], + runtimeAuthLookups: [{ agentId: "default", lookup: runtimeAuthLookup }], + timeoutMs: 120_000, + isCancelled: expect.any(Function), + workerUrl: undefined, + }); + }); + + it("keeps off-main-thread warm partial when plugin synthetic auth lookup is incomplete", async () => { + const cfg = {} as OpenClawConfig; + authProfilesMocks.getRuntimeAuthProfileStoreSnapshot.mockReturnValue(undefined); + modelAuthMocks.createRuntimeProviderAuthLookup.mockReturnValueOnce({ + envApiKey: { + aliasMap: {}, + candidateMap: {}, + authEvidenceMap: {}, + }, + syntheticAuthProviderRefs: [], + syntheticAuthProviderRefsComplete: false, + }); + const runWorker = vi.fn(async () => ({ agents: [] })); + + await warmCurrentProviderAuthStateOffMainThread(cfg, { runWorker }); + + expect(runWorker).toHaveBeenCalledWith({ + cfg, + runtimeAuthLookups: [ + { + agentId: "default", + lookup: { + envApiKey: { + aliasMap: {}, + candidateMap: {}, + authEvidenceMap: {}, + }, + syntheticAuthProviderRefs: [], + syntheticAuthProviderRefsComplete: false, + }, + }, + ], + omitFalseProviderAuth: true, + timeoutMs: 120_000, + isCancelled: expect.any(Function), + workerUrl: undefined, + }); + }); + + it("terminates the off-main-thread warm worker when cancellation fires", async () => { + const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-provider-auth-worker-")); + const workerPath = path.join(tempDir, "slow-worker.mjs"); + const markerPath = path.join(tempDir, "worker-finished"); + await fs.writeFile( + workerPath, + ` + import fs from "node:fs"; + import { parentPort, workerData } from "node:worker_threads"; + setTimeout(() => { + fs.writeFileSync(workerData.cfg.markerPath, "finished"); + parentPort.postMessage({ + status: "ok", + snapshot: { + agents: [{ + agentId: "default", + configFingerprint: "fingerprint", + providers: [["openai", true]] + }] + } + }); + }, 200); + `, + ); + let cancelled = false; + + try { + const warmPromise = warmCurrentProviderAuthStateOffMainThread( + { markerPath } as unknown as OpenClawConfig, + { + isCancelled: () => cancelled, + timeoutMs: 5_000, + workerUrl: pathToFileURL(workerPath), + }, + ); + await Promise.resolve(); + cancelled = true; + await warmPromise; + await new Promise((resolve) => setTimeout(resolve, 250)); + + await expect(fs.access(markerPath)).rejects.toMatchObject({ code: "ENOENT" }); + } finally { + await fs.rm(tempDir, { recursive: true, force: true }); + } + }); + + it("does not publish an off-main-thread warm after the prepared auth state is cleared", async () => { + const cfg = { gateway: { port: 18789 } } as OpenClawConfig; + modelCatalogMocks.loadModelCatalog.mockResolvedValue([ + { id: "gpt", name: "gpt", provider: "openai" }, + ]); + modelAuthMocks.hasRuntimeAvailableProviderAuth.mockReturnValue(true); + const snapshot = await buildCurrentProviderAuthStateSnapshot(cfg); + expect(modelAuthMocks.hasRuntimeAvailableProviderAuth).toHaveBeenCalledTimes(1); + + clearCurrentProviderAuthState(); + modelAuthMocks.hasRuntimeAvailableProviderAuth.mockClear(); + let resolveWorker: ((value: typeof snapshot) => void) | undefined; + const warmPromise = warmCurrentProviderAuthStateOffMainThread(cfg, { + runWorker: () => + new Promise((resolve) => { + resolveWorker = resolve; + }), + }); + await Promise.resolve(); + clearCurrentProviderAuthState(); + resolveWorker?.(snapshot); + await warmPromise; + + modelAuthMocks.hasRuntimeAvailableProviderAuth.mockReturnValue(false); + await expect(hasAuthForModelProvider({ provider: "openai", cfg })).resolves.toBe(false); + expect(modelAuthMocks.hasRuntimeAvailableProviderAuth).toHaveBeenCalledTimes(1); + }); }); diff --git a/src/agents/model-provider-auth.ts b/src/agents/model-provider-auth.ts index 396532bf34e5..6af676a27cdd 100644 --- a/src/agents/model-provider-auth.ts +++ b/src/agents/model-provider-auth.ts @@ -1,3 +1,6 @@ +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { Worker } from "node:worker_threads"; import { hashRuntimeConfigValue } from "../config/runtime-snapshot.js"; import type { OpenClawConfig } from "../config/types.openclaw.js"; import { @@ -11,6 +14,7 @@ import { externalCliDiscoveryForProviders, ensureAuthProfileStore, ensureAuthProfileStoreWithoutExternalProfiles, + getRuntimeAuthProfileStoreSnapshot, listProfilesForProvider, type AuthProfileStore, } from "./auth-profiles.js"; @@ -35,18 +39,75 @@ type PreparedProviderAuthState = { providers: ReadonlyMap; }; -// One entry per configured agent, keyed by agentId. Populated by -// warmCurrentProviderAuthState at gateway startup / on reload; consulted by -// hasAuthForModelProvider on every model-listing call. +export type ProviderAuthWarmSnapshot = { + agents: Array<{ + agentId: string; + configFingerprint: string; + providers: Array<[string, boolean]>; + }>; +}; + +type ProviderAuthWarmWorkerResult = + | { + status: "ok"; + snapshot: ProviderAuthWarmSnapshot; + } + | { + status: "failed"; + error: string; + }; + +type ProviderAuthWarmRuntimeAuthStore = { + agentDir?: string; + store: AuthProfileStore; +}; + +type ProviderAuthWarmRuntimeAuthLookup = { + agentId: string; + lookup: RuntimeProviderAuthLookup; +}; + +type ProviderAuthWarmWorkerRunner = (params: { + cfg: OpenClawConfig; + runtimeAuthStores?: ProviderAuthWarmRuntimeAuthStore[]; + runtimeAuthLookups?: ProviderAuthWarmRuntimeAuthLookup[]; + omitFalseProviderAuth?: boolean; + timeoutMs: number; + isCancelled: () => boolean; + workerUrl?: URL; +}) => Promise; + +const PROVIDER_AUTH_WARM_WORKER_TIMEOUT_MS = 120_000; +const PROVIDER_AUTH_WARM_CANCEL_POLL_MS = 25; + +// One entry per configured agent, keyed by agentId. Populated by the provider +// auth warm path; consulted by hasAuthForModelProvider on every model-listing call. let currentProviderAuthStates: ReadonlyMap | null = null; const configFingerprintCache = new WeakMap(); // Generation counter guards against an in-flight warm publishing stale // state after a subsequent warm or clear has invalidated it. let currentProviderAuthStateGeneration = 0; +let currentProviderAuthWarmWorker: + | { + worker: Worker; + cancelled: boolean; + } + | undefined; + +function cancelCurrentProviderAuthWarmWorker(): void { + const current = currentProviderAuthWarmWorker; + if (!current) { + return; + } + current.cancelled = true; + currentProviderAuthWarmWorker = undefined; + void current.worker.terminate(); +} export function clearCurrentProviderAuthState(): void { currentProviderAuthStates = null; currentProviderAuthStateGeneration += 1; + cancelCurrentProviderAuthWarmWorker(); } function resolvePreparedStateForCaller(params: { @@ -93,7 +154,7 @@ export async function hasAuthForModelProvider(params: { resolveRuntimeAuthLookup?: () => RuntimeProviderAuthLookup; }): Promise { const provider = normalizeProviderId(params.provider); - // The prepared map is built by warmCurrentProviderAuthState — one entry per + // The prepared map is built by the provider auth warm path — one entry per // configured agent, keyed by agentId. Only consult it when the caller's // full auth context matches the warmed scope; otherwise fall through to // compute so callers that narrow the scope — e.g. gateway `models.list` @@ -196,19 +257,76 @@ export function createProviderAuthChecker(params: { }; } -export async function warmCurrentProviderAuthState( +function serializeProviderAuthStates( + states: ReadonlyMap, +): ProviderAuthWarmSnapshot { + return { + agents: [...states.values()].map((state) => ({ + agentId: state.agentId, + configFingerprint: state.configFingerprint, + providers: [...state.providers.entries()], + })), + }; +} + +function publishProviderAuthWarmSnapshot(snapshot: ProviderAuthWarmSnapshot): void { + currentProviderAuthStates = new Map( + snapshot.agents.map((state) => [ + state.agentId, + { + agentId: state.agentId, + configFingerprint: state.configFingerprint, + providers: new Map(state.providers), + }, + ]), + ); +} + +function resolveProviderConfigApi( + cfg: OpenClawConfig | undefined, + provider: string, +): string | undefined { + const providers = cfg?.models?.providers ?? {}; + const direct = providers[provider]; + if (direct?.api) { + return direct.api; + } + const normalized = normalizeProviderId(provider); + const matched = Object.entries(providers).find( + ([key]) => normalizeProviderId(key) === normalized, + )?.[1]; + return matched?.api; +} + +function shouldOmitFalsePreparedAuthForProcessSyntheticProvider(params: { + cfg: OpenClawConfig; + provider: string; + runtimeAuthLookup: RuntimeProviderAuthLookup; +}): boolean { + const syntheticRefs = params.runtimeAuthLookup.syntheticAuthProviderRefs; + if (!syntheticRefs?.length) { + return false; + } + const eligibleRefs = new Set(syntheticRefs.map((ref) => normalizeProviderId(ref))); + const providerApi = resolveProviderConfigApi(params.cfg, params.provider); + return [params.provider, providerApi] + .filter((ref): ref is string => typeof ref === "string" && ref.trim().length > 0) + .some((ref) => eligibleRefs.has(normalizeProviderId(ref))); +} + +export async function buildCurrentProviderAuthStateSnapshot( cfg: OpenClawConfig, - options: { isCancelled?: () => boolean } = {}, -): Promise { - // Claim a fresh generation; any concurrent warm or clear bumps this and - // turns our published state stale. - currentProviderAuthStateGeneration += 1; - const ownGeneration = currentProviderAuthStateGeneration; - const isWarmStale = () => - options.isCancelled?.() === true || ownGeneration !== currentProviderAuthStateGeneration; + options: { + isCancelled?: () => boolean; + readOnlyAuthStore?: boolean; + runtimeAuthLookups?: ReadonlyMap; + omitFalseProviderAuth?: boolean; + } = {}, +): Promise { + const isWarmStale = () => options.isCancelled?.() === true; const catalog = await loadModelCatalog({ config: cfg, readOnly: true }); if (isWarmStale()) { - return; + return { agents: [] }; } const providers = new Set(); for (const entry of catalog) { @@ -222,27 +340,37 @@ export async function warmCurrentProviderAuthState( // work is the auth-discovery sweep against that agent's store. for (const agentId of listAgentIds(cfg)) { if (isWarmStale()) { - return; + return { agents: [] }; } const workspaceDir = resolveAgentWorkspaceDir(cfg, agentId); const agentDir = resolveAgentDir(cfg, agentId); - const runtimeAuthLookup = createRuntimeProviderAuthLookup({ - cfg, - workspaceDir, - }); + const runtimeAuthLookup = + options.runtimeAuthLookups?.get(agentId) ?? + createRuntimeProviderAuthLookup({ + cfg, + workspaceDir, + }); // One AuthProfileStore scoped to every candidate provider; without this // the per-provider externalCli discovery rebuilds the store ~N times. - const store = ensureAuthProfileStore(agentDir, { - config: cfg, - externalCli: externalCliDiscoveryForProviders({ - cfg, - providers: providerList, - }), + const externalCli = externalCliDiscoveryForProviders({ + cfg, + providers: providerList, }); + const store = options.readOnlyAuthStore + ? ensureAuthProfileStore(agentDir, { + config: cfg, + externalCli, + readOnly: true, + syncExternalCli: false, + }) + : ensureAuthProfileStore(agentDir, { + config: cfg, + externalCli, + }); const state = new Map(); for (const provider of providers) { if (isWarmStale()) { - return; + return { agents: [] }; } const value = await hasAuthForModelProvider({ provider, @@ -252,6 +380,17 @@ export async function warmCurrentProviderAuthState( store, runtimeAuthLookup, }); + if ( + !value && + (options.omitFalseProviderAuth || + shouldOmitFalsePreparedAuthForProcessSyntheticProvider({ + cfg, + provider, + runtimeAuthLookup, + })) + ) { + continue; + } state.set(provider, value); } states.set(agentId, { @@ -260,10 +399,278 @@ export async function warmCurrentProviderAuthState( providers: state, }); } + return serializeProviderAuthStates(states); +} + +export async function warmCurrentProviderAuthState( + cfg: OpenClawConfig, + options: { isCancelled?: () => boolean } = {}, +): Promise { + // Claim a fresh generation; any concurrent warm or clear bumps this and + // turns our published state stale. + currentProviderAuthStateGeneration += 1; + const ownGeneration = currentProviderAuthStateGeneration; + const isWarmStale = () => + options.isCancelled?.() === true || ownGeneration !== currentProviderAuthStateGeneration; + const snapshot = await buildCurrentProviderAuthStateSnapshot(cfg, { + isCancelled: isWarmStale, + }); + if (isWarmStale()) { + return; + } if (options.isCancelled?.() || ownGeneration !== currentProviderAuthStateGeneration) { // A newer warm or clear ran while we were building; skip publication so // the newer answer wins. return; } - currentProviderAuthStates = states; + publishProviderAuthWarmSnapshot(snapshot); +} + +function resolveProviderAuthWarmWorkerUrl(currentModuleUrl: string): URL { + const currentPath = fileURLToPath(currentModuleUrl); + const distMarker = `${path.sep}dist${path.sep}`; + const distIndex = currentPath.lastIndexOf(distMarker); + if (distIndex >= 0) { + const distRoot = currentPath.slice(0, distIndex + distMarker.length - 1); + return pathToFileURL(path.join(distRoot, "agents", "model-provider-auth.worker.js")); + } + const extension = path.extname(currentPath) || ".js"; + return new URL(`./model-provider-auth.worker${extension}`, currentModuleUrl); +} + +function isProviderAuthWarmSnapshot(value: unknown): value is ProviderAuthWarmSnapshot { + if ( + !value || + typeof value !== "object" || + !Array.isArray((value as { agents?: unknown }).agents) + ) { + return false; + } + return (value as ProviderAuthWarmSnapshot).agents.every( + (agent) => + typeof agent.agentId === "string" && + typeof agent.configFingerprint === "string" && + Array.isArray(agent.providers) && + agent.providers.every( + (entry) => + Array.isArray(entry) && + entry.length === 2 && + typeof entry[0] === "string" && + typeof entry[1] === "boolean", + ), + ); +} + +function isProviderAuthWarmWorkerResult(value: unknown): value is ProviderAuthWarmWorkerResult { + if (!value || typeof value !== "object") { + return false; + } + const result = value as ProviderAuthWarmWorkerResult; + if (result.status === "failed") { + return typeof result.error === "string"; + } + return result.status === "ok" && isProviderAuthWarmSnapshot(result.snapshot); +} + +function createProviderAuthWarmPresenceStore(store: AuthProfileStore): AuthProfileStore { + const profiles: AuthProfileStore["profiles"] = {}; + for (const [profileId, credential] of Object.entries(store.profiles)) { + profiles[profileId] = { + type: "api_key", + provider: credential.provider, + }; + } + return { + version: store.version, + profiles, + }; +} + +function collectProviderAuthWarmRuntimeAuthStores( + cfg: OpenClawConfig, +): ProviderAuthWarmRuntimeAuthStore[] { + const entries: ProviderAuthWarmRuntimeAuthStore[] = []; + const seen = new Set(); + const addStore = (agentDir?: string) => { + if (seen.has(agentDir)) { + return; + } + seen.add(agentDir); + const store = getRuntimeAuthProfileStoreSnapshot(agentDir); + if (!store) { + return; + } + entries.push({ + ...(agentDir === undefined ? {} : { agentDir }), + store: createProviderAuthWarmPresenceStore(store), + }); + }; + + addStore(); + for (const agentId of listAgentIds(cfg)) { + addStore(resolveAgentDir(cfg, agentId)); + } + return entries; +} + +function collectProviderAuthWarmRuntimeAuthLookups(cfg: OpenClawConfig): { + entries: ProviderAuthWarmRuntimeAuthLookup[]; + omitFalseProviderAuth: boolean; +} { + const entries: ProviderAuthWarmRuntimeAuthLookup[] = []; + let omitFalseProviderAuth = false; + for (const agentId of listAgentIds(cfg)) { + const lookup = createRuntimeProviderAuthLookup({ + cfg, + workspaceDir: resolveAgentWorkspaceDir(cfg, agentId), + }); + if (lookup.syntheticAuthProviderRefsComplete === false) { + omitFalseProviderAuth = true; + } + entries.push({ agentId, lookup }); + } + return { entries, omitFalseProviderAuth }; +} + +function runProviderAuthWarmWorker(params: { + cfg: OpenClawConfig; + runtimeAuthStores?: ProviderAuthWarmRuntimeAuthStore[]; + runtimeAuthLookups?: ProviderAuthWarmRuntimeAuthLookup[]; + omitFalseProviderAuth?: boolean; + timeoutMs: number; + isCancelled: () => boolean; + workerUrl?: URL; +}): Promise { + const worker = new Worker(params.workerUrl ?? resolveProviderAuthWarmWorkerUrl(import.meta.url), { + workerData: { + cfg: params.cfg, + ...(params.runtimeAuthStores?.length ? { runtimeAuthStores: params.runtimeAuthStores } : {}), + ...(params.runtimeAuthLookups?.length + ? { runtimeAuthLookups: params.runtimeAuthLookups } + : {}), + ...(params.omitFalseProviderAuth ? { omitFalseProviderAuth: true } : {}), + }, + }); + worker.unref?.(); + const handle = { + worker, + cancelled: false, + }; + currentProviderAuthWarmWorker = handle; + return new Promise((resolve, reject) => { + let settled = false; + let timer: ReturnType | undefined; + let cancelTimer: ReturnType | undefined; + const finish = (complete: () => void) => { + if (settled) { + return; + } + settled = true; + if (currentProviderAuthWarmWorker === handle) { + currentProviderAuthWarmWorker = undefined; + } + if (timer) { + clearTimeout(timer); + } + if (cancelTimer) { + clearInterval(cancelTimer); + } + complete(); + }; + const cancelWorker = () => { + handle.cancelled = true; + void worker.terminate(); + finish(() => resolve({ agents: [] })); + }; + timer = setTimeout(() => { + handle.cancelled = true; + void worker.terminate(); + finish(() => reject(new Error("provider auth warm worker timed out"))); + }, params.timeoutMs); + timer.unref?.(); + cancelTimer = setInterval(() => { + if (params.isCancelled()) { + cancelWorker(); + } + }, PROVIDER_AUTH_WARM_CANCEL_POLL_MS); + cancelTimer.unref?.(); + worker.once("message", (message: unknown) => { + void worker.terminate(); + finish(() => { + if (handle.cancelled) { + resolve({ agents: [] }); + return; + } + if (!isProviderAuthWarmWorkerResult(message)) { + reject(new Error("invalid provider auth warm worker response")); + return; + } + if (message.status === "failed") { + reject(new Error(message.error)); + return; + } + resolve(message.snapshot); + }); + }); + worker.once("error", (error) => { + finish(() => { + if (handle.cancelled) { + resolve({ agents: [] }); + return; + } + reject(error); + }); + }); + worker.once("exit", (code) => { + if (settled || code === 0) { + return; + } + finish(() => { + if (handle.cancelled) { + resolve({ agents: [] }); + return; + } + reject(new Error(`provider auth warm worker exited with code ${code}`)); + }); + }); + if (params.isCancelled()) { + cancelWorker(); + } + }); +} + +export async function warmCurrentProviderAuthStateOffMainThread( + cfg: OpenClawConfig, + options: { + isCancelled?: () => boolean; + timeoutMs?: number; + workerUrl?: URL; + runWorker?: ProviderAuthWarmWorkerRunner; + } = {}, +): Promise { + currentProviderAuthStateGeneration += 1; + const ownGeneration = currentProviderAuthStateGeneration; + cancelCurrentProviderAuthWarmWorker(); + const isWarmStale = () => + options.isCancelled?.() === true || ownGeneration !== currentProviderAuthStateGeneration; + if (isWarmStale()) { + return; + } + const runtimeAuthStores = collectProviderAuthWarmRuntimeAuthStores(cfg); + const runtimeAuthLookups = collectProviderAuthWarmRuntimeAuthLookups(cfg); + const snapshot = await (options.runWorker ?? runProviderAuthWarmWorker)({ + cfg, + ...(runtimeAuthStores.length ? { runtimeAuthStores } : {}), + ...(runtimeAuthLookups.entries.length + ? { runtimeAuthLookups: runtimeAuthLookups.entries } + : {}), + ...(runtimeAuthLookups.omitFalseProviderAuth ? { omitFalseProviderAuth: true } : {}), + timeoutMs: options.timeoutMs ?? PROVIDER_AUTH_WARM_WORKER_TIMEOUT_MS, + isCancelled: isWarmStale, + workerUrl: options.workerUrl, + }); + if (isWarmStale()) { + return; + } + publishProviderAuthWarmSnapshot(snapshot); } diff --git a/src/agents/model-provider-auth.worker.test.ts b/src/agents/model-provider-auth.worker.test.ts new file mode 100644 index 000000000000..6f2d5335e049 --- /dev/null +++ b/src/agents/model-provider-auth.worker.test.ts @@ -0,0 +1,83 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import type { OpenClawConfig } from "../config/types.openclaw.js"; +import { clearRuntimeAuthProfileStoreSnapshots } from "./auth-profiles.js"; +import { clearCurrentProviderAuthState } from "./model-provider-auth.js"; +import { runProviderAuthWarmWorkerInput } from "./model-provider-auth.worker.js"; + +const tempDirs: string[] = []; +const envKeys = ["OPENCLAW_DISABLE_PERSISTED_PLUGIN_REGISTRY", "OPENCLAW_STATE_DIR"] as const; + +function restoreEnv(previous: Record<(typeof envKeys)[number], string | undefined>): void { + for (const key of envKeys) { + if (previous[key] === undefined) { + delete process.env[key]; + continue; + } + process.env[key] = previous[key]; + } +} + +describe("provider auth warm worker", () => { + afterEach(() => { + clearCurrentProviderAuthState(); + clearRuntimeAuthProfileStoreSnapshots(); + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("preserves runtime-only auth profile snapshots in the worker warm input", async () => { + const root = mkdtempSync(path.join(tmpdir(), "openclaw-provider-auth-worker-")); + tempDirs.push(root); + const previousEnv = Object.fromEntries(envKeys.map((key) => [key, process.env[key]])) as Record< + (typeof envKeys)[number], + string | undefined + >; + process.env.OPENCLAW_DISABLE_PERSISTED_PLUGIN_REGISTRY = "1"; + process.env.OPENCLAW_STATE_DIR = path.join(root, "state"); + + try { + const agentDir = path.join(root, "agent"); + const cfg = { + agents: { list: [{ id: "main", agentDir }] }, + models: { + providers: { + "runtime-only": { + baseUrl: "https://example.com/v1", + api: "openai", + models: [{ id: "runtime-model", name: "Runtime Model" }], + }, + }, + }, + } as unknown as OpenClawConfig; + const result = await runProviderAuthWarmWorkerInput({ + cfg, + runtimeAuthStores: [ + { + agentDir, + store: { + version: 1, + profiles: { + "runtime-only:default": { + type: "api_key", + provider: "runtime-only", + }, + }, + }, + }, + ], + }); + + expect(result.status).toBe("ok"); + if (result.status !== "ok") { + return; + } + expect(result.snapshot.agents[0]?.providers).toContainEqual(["runtime-only", true]); + } finally { + restoreEnv(previousEnv); + } + }, 30_000); +}); diff --git a/src/agents/model-provider-auth.worker.ts b/src/agents/model-provider-auth.worker.ts new file mode 100644 index 000000000000..d2255f651c41 --- /dev/null +++ b/src/agents/model-provider-auth.worker.ts @@ -0,0 +1,82 @@ +import { parentPort, workerData } from "node:worker_threads"; +import type { OpenClawConfig } from "../config/types.openclaw.js"; +import { replaceRuntimeAuthProfileStoreSnapshots, type AuthProfileStore } from "./auth-profiles.js"; +import type { RuntimeProviderAuthLookup } from "./model-auth.js"; +import { buildCurrentProviderAuthStateSnapshot } from "./model-provider-auth.js"; + +type ProviderAuthWarmRuntimeAuthStore = { + agentDir?: string; + store: AuthProfileStore; +}; + +type ProviderAuthWarmWorkerInput = { + cfg: OpenClawConfig; + runtimeAuthStores?: ProviderAuthWarmRuntimeAuthStore[]; + runtimeAuthLookups?: Array<{ + agentId: string; + lookup: RuntimeProviderAuthLookup; + }>; + omitFalseProviderAuth?: boolean; +}; + +type ProviderAuthWarmWorkerResult = + | { + status: "ok"; + snapshot: Awaited>; + } + | { + status: "failed"; + error: string; + }; + +function isWorkerInput(value: unknown): value is ProviderAuthWarmWorkerInput { + return ( + !!value && + typeof value === "object" && + "cfg" in value && + (!("runtimeAuthStores" in value) || + Array.isArray((value as { runtimeAuthStores?: unknown }).runtimeAuthStores)) && + (!("runtimeAuthLookups" in value) || + Array.isArray((value as { runtimeAuthLookups?: unknown }).runtimeAuthLookups)) && + (!("omitFalseProviderAuth" in value) || + typeof (value as { omitFalseProviderAuth?: unknown }).omitFalseProviderAuth === "boolean") + ); +} + +export async function runProviderAuthWarmWorkerInput( + input: unknown, +): Promise { + if (!isWorkerInput(input)) { + return { + status: "failed", + error: "invalid provider auth warm worker input", + }; + } + try { + if (input.runtimeAuthStores?.length) { + replaceRuntimeAuthProfileStoreSnapshots(input.runtimeAuthStores); + } + const snapshot = await buildCurrentProviderAuthStateSnapshot(input.cfg, { + readOnlyAuthStore: true, + runtimeAuthLookups: new Map( + input.runtimeAuthLookups?.map(({ agentId, lookup }) => [agentId, lookup]), + ), + omitFalseProviderAuth: input.omitFalseProviderAuth, + }); + return { + status: "ok", + snapshot, + }; + } catch (error) { + return { + status: "failed", + error: String(error), + }; + } +} + +if (parentPort) { + const sendToParent: (message: ProviderAuthWarmWorkerResult) => void = + parentPort.postMessage.bind(parentPort); + sendToParent(await runProviderAuthWarmWorkerInput(workerData)); +} diff --git a/src/agents/tools/image-tool.ts b/src/agents/tools/image-tool.ts index 8163db035311..faa4bfec7e9b 100644 --- a/src/agents/tools/image-tool.ts +++ b/src/agents/tools/image-tool.ts @@ -18,7 +18,11 @@ import { classifyMediaReferenceSource, normalizeMediaReferenceSource, } from "../../media/media-reference.js"; -import type { ImageCompressionModelPolicy, ImageCompressionPolicy } from "../../media/web-media.js"; +import type { + ImageCompressionModelPolicy, + ImageCompressionPolicy, + WebMediaResult, +} from "../../media/web-media.js"; import { describeImageWithModel, describeImagesWithModel, @@ -76,10 +80,23 @@ import { const DEFAULT_PROMPT = "Describe the image."; const DEFAULT_MAX_IMAGES = 20; -type ImageWebMediaRuntime = Pick< - typeof import("../../media/web-media.js"), - "loadWebMedia" | "optimizeImageBufferForWebMedia" ->; +type ImageToolLoadWebMediaOptions = { + maxBytes?: number; + sandboxValidated?: boolean; + readFile?: (filePath: string) => Promise; + imageCompression?: ImageCompressionPolicy; + localRoots?: readonly string[] | "any"; + inboundRoots?: readonly string[]; + ssrfPolicy?: ReturnType; +}; + +type ImageWebMediaRuntime = { + loadWebMedia: ( + mediaUrl: string, + options?: ImageToolLoadWebMediaOptions, + ) => Promise; + optimizeImageBufferForWebMedia: (typeof import("../../media/web-media.js"))["optimizeImageBufferForWebMedia"]; +}; async function loadImageWebMediaRuntime(): Promise { return await import("../../media/web-media.js"); diff --git a/src/gateway/server-methods/models-auth-status.test.ts b/src/gateway/server-methods/models-auth-status.test.ts index eb658576b516..750761086c0e 100644 --- a/src/gateway/server-methods/models-auth-status.test.ts +++ b/src/gateway/server-methods/models-auth-status.test.ts @@ -24,7 +24,7 @@ const mocks = vi.hoisted(() => ({ ), refreshActiveSecretsRuntimeSnapshot: vi.fn(async () => false), clearCurrentProviderAuthState: vi.fn(), - warmCurrentProviderAuthState: vi.fn(async (_cfg: unknown) => {}), + warmCurrentProviderAuthStateOffMainThread: vi.fn(async (_cfg: unknown) => {}), buildAuthHealthSummary: vi.fn( (): AuthHealthSummary => ({ now: 0, warnAfterMs: 0, profiles: [], providers: [] }), ), @@ -74,7 +74,7 @@ vi.mock("../../secrets/runtime.js", () => ({ vi.mock("../../agents/model-provider-auth.js", () => ({ clearCurrentProviderAuthState: mocks.clearCurrentProviderAuthState, - warmCurrentProviderAuthState: mocks.warmCurrentProviderAuthState, + warmCurrentProviderAuthStateOffMainThread: mocks.warmCurrentProviderAuthStateOffMainThread, })); import { @@ -618,7 +618,7 @@ describe("models.authLogout", () => { }); expect(mocks.refreshActiveSecretsRuntimeSnapshot).toHaveBeenCalledTimes(1); expect(mocks.clearCurrentProviderAuthState).toHaveBeenCalled(); - expect(mocks.warmCurrentProviderAuthState).toHaveBeenCalledWith({}); + expect(mocks.warmCurrentProviderAuthStateOffMainThread).toHaveBeenCalledWith({}); const [ok, payload] = firstRespondCall(opts) ?? []; expect(ok).toBe(true); expect((payload as ModelAuthLogoutResult).removedProfiles).toEqual(["openrouter:default"]); diff --git a/src/gateway/server-methods/models-auth-status.ts b/src/gateway/server-methods/models-auth-status.ts index 2978d2a40e6a..dd84e5dd9be7 100644 --- a/src/gateway/server-methods/models-auth-status.ts +++ b/src/gateway/server-methods/models-auth-status.ts @@ -17,7 +17,7 @@ import { } from "../../agents/auth-profiles.js"; import { clearCurrentProviderAuthState, - warmCurrentProviderAuthState, + warmCurrentProviderAuthStateOffMainThread, } from "../../agents/model-provider-auth.js"; import { resolveProviderIdForAuth } from "../../agents/provider-auth-aliases.js"; import { normalizeProviderId } from "../../agents/provider-id.js"; @@ -391,7 +391,7 @@ export const modelsAuthStatusHandlers: GatewayRequestHandlers = { await refreshActiveSecretsRuntimeSnapshot(); invalidateModelAuthStatusCache(); clearCurrentProviderAuthState(); - void warmCurrentProviderAuthState(context.getRuntimeConfig()).catch((err) => { + void warmCurrentProviderAuthStateOffMainThread(context.getRuntimeConfig()).catch((err) => { log.warn(`provider auth state rewarm after logout failed: ${formatForLog(err)}`); }); const { runIds: abortedRunIds } = abortChatRunsForProvider( diff --git a/src/gateway/server-reload-handlers.test.ts b/src/gateway/server-reload-handlers.test.ts index bf2944bc6dc5..fb93d804d6a2 100644 --- a/src/gateway/server-reload-handlers.test.ts +++ b/src/gateway/server-reload-handlers.test.ts @@ -44,7 +44,7 @@ const hoisted = vi.hoisted(() => ({ reloadEvents: [] as string[], resetModelCatalogCache: vi.fn(() => {}), clearCurrentProviderAuthState: vi.fn(() => {}), - warmCurrentProviderAuthState: vi.fn(async (_cfg: OpenClawConfig) => {}), + warmCurrentProviderAuthStateOffMainThread: vi.fn(async (_cfg: OpenClawConfig) => {}), disposeAllSessionMcpRuntimes: vi.fn(async () => {}), })); @@ -113,9 +113,9 @@ vi.mock("../agents/model-provider-auth.js", () => ({ hoisted.reloadEvents.push("clear-provider-auth"); hoisted.clearCurrentProviderAuthState(); }, - warmCurrentProviderAuthState: async (cfg: OpenClawConfig) => { + warmCurrentProviderAuthStateOffMainThread: async (cfg: OpenClawConfig) => { hoisted.reloadEvents.push("warm-provider-auth"); - await hoisted.warmCurrentProviderAuthState(cfg); + await hoisted.warmCurrentProviderAuthStateOffMainThread(cfg); }, })); @@ -171,7 +171,7 @@ afterEach(() => { hoisted.reloadEvents.length = 0; hoisted.resetModelCatalogCache.mockClear(); hoisted.clearCurrentProviderAuthState.mockClear(); - hoisted.warmCurrentProviderAuthState.mockClear(); + hoisted.warmCurrentProviderAuthStateOffMainThread.mockClear(); hoisted.disposeAllSessionMcpRuntimes.mockClear(); hoisted.disposeAllSessionMcpRuntimes.mockResolvedValue(undefined); }); @@ -240,7 +240,7 @@ describe("gateway hot reload model state", () => { "clear-provider-auth", "warm-provider-auth", ]); - expect(hoisted.warmCurrentProviderAuthState).toHaveBeenCalledWith(nextConfig); + expect(hoisted.warmCurrentProviderAuthStateOffMainThread).toHaveBeenCalledWith(nextConfig); }); it("disposes cached MCP runtimes on MCP config hot reloads", async () => { @@ -267,7 +267,7 @@ describe("gateway hot reload model state", () => { ); expect(hoisted.disposeAllSessionMcpRuntimes).toHaveBeenCalledTimes(1); - expect(hoisted.warmCurrentProviderAuthState).toHaveBeenCalledWith(nextConfig); + expect(hoisted.warmCurrentProviderAuthStateOffMainThread).toHaveBeenCalledWith(nextConfig); }); }); diff --git a/src/gateway/server-reload-handlers.ts b/src/gateway/server-reload-handlers.ts index 9ea9122b6490..3bdb395917b5 100644 --- a/src/gateway/server-reload-handlers.ts +++ b/src/gateway/server-reload-handlers.ts @@ -7,7 +7,7 @@ import { import { resetModelCatalogCache } from "../agents/model-catalog.js"; import { clearCurrentProviderAuthState, - warmCurrentProviderAuthState, + warmCurrentProviderAuthStateOffMainThread, } from "../agents/model-provider-auth.js"; import { getTotalPendingReplies } from "../auto-reply/reply/dispatcher-registry.js"; import type { CliDeps } from "../cli/deps.types.js"; @@ -500,7 +500,7 @@ export function createGatewayReloadHandlers(params: GatewayReloadHandlerParams) applyGatewayLaneConcurrency(nextConfig); - void warmCurrentProviderAuthState(nextConfig).catch((err) => { + void warmCurrentProviderAuthStateOffMainThread(nextConfig).catch((err) => { params.logReload.warn(`provider auth state rewarm failed: ${String(err)}`); }); diff --git a/src/gateway/server-startup-post-attach.test.ts b/src/gateway/server-startup-post-attach.test.ts index dac01ab5e69c..ac3a9224937e 100644 --- a/src/gateway/server-startup-post-attach.test.ts +++ b/src/gateway/server-startup-post-attach.test.ts @@ -48,7 +48,9 @@ const hoisted = vi.hoisted(() => { })); const ensureOpenClawModelsJson = vi.fn(async () => {}); const clearCurrentProviderAuthState = vi.fn(); - const warmCurrentProviderAuthState = vi.fn(async (_cfg?: unknown, _options?: unknown) => {}); + const warmCurrentProviderAuthStateOffMainThread = vi.fn( + async (_cfg?: unknown, _options?: unknown) => {}, + ); const setAuthProfileFailureHook = vi.fn(); const transcriptsAutoStartService = { start: vi.fn(), @@ -81,7 +83,7 @@ const hoisted = vi.hoisted(() => { getModelRefStatus, ensureOpenClawModelsJson, clearCurrentProviderAuthState, - warmCurrentProviderAuthState, + warmCurrentProviderAuthStateOffMainThread, setAuthProfileFailureHook, transcriptsAutoStartService, createTranscriptsAutoStartService, @@ -179,7 +181,7 @@ vi.mock("../agents/models-config.js", () => ({ vi.mock("../agents/model-provider-auth.js", () => ({ clearCurrentProviderAuthState: hoisted.clearCurrentProviderAuthState, - warmCurrentProviderAuthState: hoisted.warmCurrentProviderAuthState, + warmCurrentProviderAuthStateOffMainThread: hoisted.warmCurrentProviderAuthStateOffMainThread, })); vi.mock("../agents/auth-profiles.js", async () => { @@ -293,8 +295,8 @@ describe("startGatewayPostAttachRuntime", () => { hoisted.ensureOpenClawModelsJson.mockReset(); hoisted.ensureOpenClawModelsJson.mockResolvedValue(undefined); hoisted.clearCurrentProviderAuthState.mockClear(); - hoisted.warmCurrentProviderAuthState.mockReset(); - hoisted.warmCurrentProviderAuthState.mockResolvedValue(undefined); + hoisted.warmCurrentProviderAuthStateOffMainThread.mockReset(); + hoisted.warmCurrentProviderAuthStateOffMainThread.mockResolvedValue(undefined); hoisted.setAuthProfileFailureHook.mockClear(); hoisted.transcriptsAutoStartService.start.mockClear(); hoisted.transcriptsAutoStartService.stop.mockClear(); @@ -832,11 +834,11 @@ describe("startGatewayPostAttachRuntime", () => { await vi.waitFor(() => { expect(hoisted.setAuthProfileFailureHook).toHaveBeenCalledTimes(1); }); - expect(hoisted.warmCurrentProviderAuthState).not.toHaveBeenCalled(); + expect(hoisted.warmCurrentProviderAuthStateOffMainThread).not.toHaveBeenCalled(); await vi.advanceTimersByTimeAsync(1_000); await vi.waitFor(() => { - expect(hoisted.warmCurrentProviderAuthState).toHaveBeenCalledTimes(1); + expect(hoisted.warmCurrentProviderAuthStateOffMainThread).toHaveBeenCalledTimes(1); }); } finally { vi.useRealTimers(); @@ -898,17 +900,17 @@ describe("startGatewayPostAttachRuntime", () => { await vi.advanceTimersByTimeAsync(1_000); await vi.waitFor(() => { - expect(hoisted.warmCurrentProviderAuthState).toHaveBeenCalledTimes(1); + expect(hoisted.warmCurrentProviderAuthStateOffMainThread).toHaveBeenCalledTimes(1); }); const hook = hoisted.setAuthProfileFailureHook.mock.calls[0]?.[0] as (() => void) | undefined; hook?.(); expect(hoisted.clearCurrentProviderAuthState).toHaveBeenCalledTimes(1); - expect(hoisted.warmCurrentProviderAuthState).toHaveBeenCalledTimes(1); + expect(hoisted.warmCurrentProviderAuthStateOffMainThread).toHaveBeenCalledTimes(1); await vi.advanceTimersByTimeAsync(1_000); await vi.waitFor(() => { - expect(hoisted.warmCurrentProviderAuthState).toHaveBeenCalledTimes(2); + expect(hoisted.warmCurrentProviderAuthStateOffMainThread).toHaveBeenCalledTimes(2); }); } finally { vi.useRealTimers(); @@ -978,12 +980,12 @@ describe("startGatewayPostAttachRuntime", () => { await sidecar.stop(); await vi.advanceTimersByTimeAsync(1_000); - expect(hoisted.warmCurrentProviderAuthState).not.toHaveBeenCalled(); + expect(hoisted.warmCurrentProviderAuthStateOffMainThread).not.toHaveBeenCalled(); const hook = hoisted.setAuthProfileFailureHook.mock.calls[0]?.[0] as (() => void) | undefined; hook?.(); expect(hoisted.clearCurrentProviderAuthState).not.toHaveBeenCalled(); - expect(hoisted.warmCurrentProviderAuthState).not.toHaveBeenCalled(); + expect(hoisted.warmCurrentProviderAuthStateOffMainThread).not.toHaveBeenCalled(); } finally { vi.useRealTimers(); } @@ -1010,7 +1012,7 @@ describe("startGatewayPostAttachRuntime", () => { }); await vi.advanceTimersByTimeAsync(0); await vi.waitFor(() => { - expect(hoisted.warmCurrentProviderAuthState).toHaveBeenCalledTimes(1); + expect(hoisted.warmCurrentProviderAuthStateOffMainThread).toHaveBeenCalledTimes(1); }); const hook = hoisted.setAuthProfileFailureHook.mock.calls[0]?.[0] as (() => void) | undefined; @@ -1021,15 +1023,19 @@ describe("startGatewayPostAttachRuntime", () => { hook(); currentCfg = afterFailureCfg; hook(); - expect(hoisted.warmCurrentProviderAuthState).toHaveBeenCalledTimes(1); + expect(hoisted.warmCurrentProviderAuthStateOffMainThread).toHaveBeenCalledTimes(1); expect(hoisted.clearCurrentProviderAuthState).toHaveBeenCalledTimes(2); await vi.advanceTimersByTimeAsync(1_000); await vi.waitFor(() => { - expect(hoisted.warmCurrentProviderAuthState).toHaveBeenCalledTimes(2); + expect(hoisted.warmCurrentProviderAuthStateOffMainThread).toHaveBeenCalledTimes(2); }); - expect(hoisted.warmCurrentProviderAuthState.mock.calls[0]?.[0]).toBe(reloadedCfg); - expect(hoisted.warmCurrentProviderAuthState.mock.calls[1]?.[0]).toBe(afterFailureCfg); + expect(hoisted.warmCurrentProviderAuthStateOffMainThread.mock.calls[0]?.[0]).toBe( + reloadedCfg, + ); + expect(hoisted.warmCurrentProviderAuthStateOffMainThread.mock.calls[1]?.[0]).toBe( + afterFailureCfg, + ); } finally { vi.useRealTimers(); } diff --git a/src/gateway/server-startup-post-attach.ts b/src/gateway/server-startup-post-attach.ts index 2bc9ec47d1ce..5c21be3d726a 100644 --- a/src/gateway/server-startup-post-attach.ts +++ b/src/gateway/server-startup-post-attach.ts @@ -191,7 +191,7 @@ function scheduleProviderAuthStatePrewarm(params: { const isStopped = () => stopped; const delayMs = params.delayMs ?? PROVIDER_AUTH_PREWARM_START_DELAY_MS; void (async () => { - const { clearCurrentProviderAuthState, warmCurrentProviderAuthState } = + const { clearCurrentProviderAuthState, warmCurrentProviderAuthStateOffMainThread } = await import("../agents/model-provider-auth.js"); const { setAuthProfileFailureHook } = await import("../agents/auth-profiles.js"); const runRewarm = async (reason: string) => { @@ -202,7 +202,7 @@ function scheduleProviderAuthStatePrewarm(params: { rewarmInFlight = true; try { const metrics = await measureProviderAuthWarm(() => - warmCurrentProviderAuthState(cfg, { isCancelled: isStopped }), + warmCurrentProviderAuthStateOffMainThread(cfg, { isCancelled: isStopped }), ); if (isStopped()) { return; @@ -255,7 +255,7 @@ function scheduleProviderAuthStatePrewarm(params: { } const cfg = params.getConfig(); const metrics = await measureProviderAuthWarm(() => - warmCurrentProviderAuthState(cfg, { isCancelled: isStopped }), + warmCurrentProviderAuthStateOffMainThread(cfg, { isCancelled: isStopped }), ); if (isStopped()) { return; diff --git a/src/infra/tsdown-config.test.ts b/src/infra/tsdown-config.test.ts index c939f7bd8646..9263d1f26b6d 100644 --- a/src/infra/tsdown-config.test.ts +++ b/src/infra/tsdown-config.test.ts @@ -99,6 +99,7 @@ describe("tsdown config", () => { "agents/model-catalog.runtime", "agents/models-config.runtime", "cli/gateway-lifecycle.runtime", + "agents/model-provider-auth.worker", "plugins/memory-state", "subagent-registry.runtime", "task-registry-control.runtime", diff --git a/test/release-check.test.ts b/test/release-check.test.ts index 5a56fb89aede..5b16143517e4 100644 --- a/test/release-check.test.ts +++ b/test/release-check.test.ts @@ -565,6 +565,7 @@ describe("collectMissingPackPaths", () => { "scripts/lib/official-external-provider-catalog.json", "scripts/lib/package-dist-imports.mjs", "scripts/postinstall-bundled-plugins.mjs", + "dist/agents/model-provider-auth.worker.js", "dist/task-registry-control.runtime.js", "dist/telegram-ingress-worker.runtime.js", bundledDistPluginFile("telegram", "runtime-api.js"), @@ -597,6 +598,7 @@ describe("collectMissingPackPaths", () => { "scripts/lib/package-dist-imports.mjs", "scripts/postinstall-bundled-plugins.mjs", "dist/plugin-sdk/root-alias.cjs", + "dist/agents/model-provider-auth.worker.js", "dist/task-registry-control.runtime.js", "dist/telegram-ingress-worker.runtime.js", "dist/build-info.json", diff --git a/tsdown.config.ts b/tsdown.config.ts index e8a0f0628d65..978ecfd6a0b6 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -233,6 +233,7 @@ function buildCoreDistEntries(): Record { "agents/model-catalog.runtime": "src/agents/model-catalog.runtime.ts", "agents/models-config.runtime": "src/agents/models-config.runtime.ts", "agents/code-mode.worker": "src/agents/code-mode.worker.ts", + "agents/model-provider-auth.worker": "src/agents/model-provider-auth.worker.ts", "acp/control-plane/manager": "src/acp/control-plane/manager.ts", "cli/gateway-lifecycle.runtime": "src/cli/gateway-cli/lifecycle.runtime.ts", "provider-dispatcher.runtime": "src/auto-reply/reply/provider-dispatcher.runtime.ts",