diff --git a/app/web/components/CutListPanel.test.tsx b/app/web/components/CutListPanel.test.tsx index 1ceadbc..3e942b0 100644 --- a/app/web/components/CutListPanel.test.tsx +++ b/app/web/components/CutListPanel.test.tsx @@ -2352,6 +2352,12 @@ describe("CutListPanel asset diagnostics + Refresh assets (#427)", () => { expect( await screen.findByTestId("lettering-review-state-1"), ).toHaveTextContent("Draft ready"); + expect( + await screen.findByTestId("cut-preview-1-overlay-layer"), + ).toBeInTheDocument(); + expect( + await screen.findByTestId("cut-preview-2-overlay-layer"), + ).toBeInTheDocument(); expect(screen.getByTestId("cut-card-status-2")).toHaveTextContent( "Needs review", ); @@ -2361,6 +2367,205 @@ describe("CutListPanel asset diagnostics + Refresh assets (#427)", () => { expect(screen.getByTestId("add-bubbles-2")).toHaveTextContent( "Review lettering", ); + + fireEvent.click(screen.getByTestId("cut-preview-1-open")); + expect( + await screen.findByTestId("focused-lettering-editor"), + ).toBeInTheDocument(); + }); + + it("renders drafted overlays across multiple cut previews after AI draft all unlettered (#503)", async () => { + let cuts = [ + makeCut({ + id: 1, + cleanImagePath: "assets/plot-01/cut-01-clean.webp", + dialogue: [{ speaker: "Mira", text: "We move now." }], + }), + makeCut({ + id: 2, + cleanImagePath: "assets/plot-01/cut-02-clean.webp", + narration: "The city held its breath.", + }), + ]; + const fn = vi.fn((url: string, opts?: RequestInit) => { + if (url.includes("/asset/")) { + return Promise.resolve({ + ok: true, + status: 200, + blob: () => + Promise.resolve(new Blob(["img"], { type: "image/webp" })), + }); + } + if (url.includes("/asset-diagnostics")) { + return Promise.resolve({ + ok: true, + status: 200, + json: () => + Promise.resolve({ + diagnostics: [ + { + cutId: 1, + kind: "image", + state: "clean-ready", + issue: null, + convertiblePng: null, + }, + { + cutId: 2, + kind: "image", + state: "clean-ready", + issue: null, + convertiblePng: null, + }, + ], + summary: { + planned: 0, + needsConversion: 0, + missing: 0, + cleanReady: 2, + finalReady: 0, + uploaded: 0, + }, + }), + }); + } + if (url.includes("/detect-clean-images")) { + return Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ detected: [], stale: [] }), + }); + } + if (url.endsWith("/cuts/plot-01") && opts?.method === "PUT") { + cuts = JSON.parse(String(opts.body)).cuts; + return Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ ok: true }), + }); + } + if (url.includes("/cuts/plot-01")) { + return Promise.resolve({ + ok: true, + status: 200, + json: () => + Promise.resolve({ version: 1, plotFile: "plot-01", cuts }), + }); + } + return Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({}), + }); + }); + + render( + , + ); + + await screen.findByTestId("cut-list-panel"); + fireEvent.click(screen.getByTestId("ai-draft-all-btn")); + + await waitFor(() => + expect(screen.getByTestId("lettering-review-state-1")).toHaveTextContent( + "Draft ready", + ), + ); + expect(screen.getByTestId("lettering-review-state-2")).toHaveTextContent( + "Draft ready", + ); + expect( + await screen.findByTestId("cut-preview-1-overlay-layer"), + ).toBeInTheDocument(); + expect( + await screen.findByTestId("cut-preview-2-overlay-layer"), + ).toBeInTheDocument(); + expect(cuts[0].overlays.length).toBeGreaterThan(0); + expect(cuts[1].overlays.length).toBeGreaterThan(0); + }); + + it("renders drafted overlays for text panels without a clean image path (#503)", async () => { + const cuts = [ + makeCut({ + id: 1, + kind: "text", + background: "#101820", + aspectRatio: "4:5", + overlays: [ + { + id: "title-1", + type: "narration", + x: 0.12, + y: 0.18, + width: 0.68, + height: 0.24, + text: "Three days later.", + }, + ], + }), + ]; + const fn = vi.fn((url: string) => { + if (url.includes("/asset-diagnostics")) { + return Promise.resolve({ + ok: true, + status: 200, + json: () => + Promise.resolve({ + diagnostics: [ + { + cutId: 1, + kind: "text", + state: "planned", + issue: null, + convertiblePng: null, + }, + ], + summary: { + planned: 1, + needsConversion: 0, + missing: 0, + cleanReady: 0, + finalReady: 0, + uploaded: 0, + }, + }), + }); + } + if (url.includes("/detect-clean-images")) { + return Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({ detected: [], stale: [] }), + }); + } + if (url.includes("/cuts/plot-01")) { + return Promise.resolve({ + ok: true, + status: 200, + json: () => + Promise.resolve({ version: 1, plotFile: "plot-01", cuts }), + }); + } + return Promise.resolve({ + ok: true, + status: 200, + json: () => Promise.resolve({}), + }); + }); + + render( + , + ); + + await screen.findByTestId("cut-list-panel"); + expect(screen.queryByTestId("cut-card-noart-1")).not.toBeInTheDocument(); + expect( + await screen.findByTestId("cut-preview-1-overlay-layer"), + ).toBeInTheDocument(); + fireEvent.click(screen.getByTestId("cut-preview-1-open")); + expect( + await screen.findByTestId("focused-lettering-editor"), + ).toBeInTheDocument(); }); it("does not overwrite existing overlays with AI draft without explicit confirmation (#494)", async () => { diff --git a/app/web/components/CutListPanel.tsx b/app/web/components/CutListPanel.tsx index 9408ac6..b7203cf 100644 --- a/app/web/components/CutListPanel.tsx +++ b/app/web/components/CutListPanel.tsx @@ -1,6 +1,7 @@ import { Fragment, useState, useEffect, useCallback, useRef } from "react"; import { LetteringEditor } from "./LetteringEditor"; -import { AssetImage, assetUrl } from "./asset-image"; +import { assetUrl } from "./asset-image"; +import { CutOverlayPreview } from "./CutOverlayPreview"; import { buildCodexTaskPrompt } from "@app-lib/cartoon-prompt"; import type { Cut as LibCut } from "@app-lib/cuts"; import { isTextPanel, isStaleTailedExport } from "@app-lib/cuts"; @@ -265,6 +266,7 @@ function CutRow({ cut, storyName, plotFile, + language, expanded, onToggle, authFetch, @@ -286,6 +288,7 @@ function CutRow({ cut: Cut; storyName: string; plotFile: string; + language?: string; expanded: boolean; onToggle: () => void; authFetch: (url: string, opts?: RequestInit) => Promise; @@ -436,6 +439,11 @@ function CutRow({ } : null; // exported / uploaded — the next action is the episode-level upload/publish const reviewState = letteringReviewState(cut); + const canOpenPreviewEditor = + !!cut.cleanImagePath || + !!cut.narration || + cut.dialogue.length > 0 || + isTextPanel(cut); return (
- {thumbPath ? ( - ) : (
setExpandedCut(expandedCut === cut.id ? null : cut.id) diff --git a/app/web/components/CutOverlayPreview.tsx b/app/web/components/CutOverlayPreview.tsx new file mode 100644 index 0000000..4215a4e --- /dev/null +++ b/app/web/components/CutOverlayPreview.tsx @@ -0,0 +1,306 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { + getDefaultFont, + getDisplayFont, + getFontCdnUrl, + getFontFamily, + type FontEntry, +} from "@app-lib/fonts"; +import { + speechTailPoints, + balloonPathD, + bubbleLayoutOptionsForOverlay, + balloonRadiusForOverlay, + type Overlay, +} from "@app-lib/overlays"; +import { layoutBubbleText } from "@app-lib/bubble-text"; +import { textPanelDimensions } from "@app-lib/cuts"; +import { useAuthedAsset } from "./asset-image"; + +type AuthFetch = (url: string, opts?: RequestInit) => Promise; + +function loadFont(font: FontEntry) { + const id = `gfont-${font.googleFontsId}`; + if (document.getElementById(id)) return; + const link = document.createElement("link"); + link.id = id; + link.rel = "stylesheet"; + link.href = getFontCdnUrl(font); + document.head.appendChild(link); +} + +interface CutOverlayPreviewProps { + storyName: string; + assetPath?: string | null; + authFetch: AuthFetch; + alt: string; + overlays: Overlay[]; + language?: string; + background?: string; + aspectRatio?: string; + className?: string; + onClick?: () => void; + testId?: string; +} + +export function CutOverlayPreview({ + storyName, + assetPath, + authFetch, + alt, + overlays, + language = "English", + background, + aspectRatio, + className, + onClick, + testId, +}: CutOverlayPreviewProps) { + const bodyFont = getDefaultFont(language); + const displayFont = getDisplayFont(); + const bodyFontFamily = getFontFamily(bodyFont); + const displayFontFamily = getFontFamily(displayFont); + const asset = useAuthedAsset(storyName, assetPath, authFetch); + const stageRef = useRef(null); + const measureContext = useMemo( + () => + typeof document !== "undefined" + ? document.createElement("canvas").getContext("2d") + : null, + [], + ); + const [fontsReady, setFontsReady] = useState(false); + const [naturalSize, setNaturalSize] = useState<{ width: number; height: number }>( + () => textPanelDimensions(aspectRatio) ?? { width: 800, height: 600 }, + ); + const [stageSize, setStageSize] = useState({ width: 0, height: 0 }); + + useEffect(() => { + loadFont(bodyFont); + loadFont(displayFont); + }, [bodyFont, displayFont]); + + useEffect(() => { + let cancelled = false; + (async () => { + try { + if (document.fonts?.load) { + await Promise.all([ + document.fonts.load(`16px "${bodyFont.family}"`), + document.fonts.load(`16px "${displayFont.family}"`), + ]); + } + } catch { + /* best effort */ + } + if (!cancelled) setFontsReady(true); + })(); + return () => { + cancelled = true; + }; + }, [bodyFont.family, displayFont.family]); + + useEffect(() => { + const el = stageRef.current; + if (!el) return; + const observer = new ResizeObserver(() => { + setStageSize({ + width: el.clientWidth, + height: el.clientHeight, + }); + }); + observer.observe(el); + return () => observer.disconnect(); + }, []); + + const measureWidth = useCallback( + (fontFamily: string) => + (text: string, fontSize: number, fontWeight: 400 | 700 = 400): number => { + if (!measureContext) return text.length * fontSize * 0.5; + measureContext.font = `${fontWeight} ${fontSize}px ${fontFamily}`; + return measureContext.measureText(text).width; + }, + [measureContext], + ); + + const stage = ( +
+
+ {assetPath ? ( + asset.error || (!asset.loading && !asset.url) ? ( +
+ Image not available +
+ ) : asset.url ? ( + {alt} { + const width = e.currentTarget.naturalWidth || naturalSize.width; + const height = e.currentTarget.naturalHeight || naturalSize.height; + if (width > 0 && height > 0) setNaturalSize({ width, height }); + }} + /> + ) : ( +
+ Loading image… +
+ ) + ) : ( +
+ )} + + {stageSize.width > 0 && stageSize.height > 0 && overlays.length > 0 && ( + <> + + {overlays.map((overlay) => { + if (overlay.type !== "speech") return null; + const ox = overlay.x * stageSize.width; + const oy = overlay.y * stageSize.height; + const ow = overlay.width * stageSize.width; + const oh = overlay.height * stageSize.height; + const radius = balloonRadiusForOverlay(overlay, ow, oh); + const tail = overlay.tailAnchor + ? speechTailPoints(ox, oy, ow, oh, overlay.tailAnchor, radius) + : null; + const strokeW = Math.max(1.25, stageSize.height * 0.004); + return ( + + ); + })} + + {overlays.map((overlay) => { + const left = overlay.x * stageSize.width; + const top = overlay.y * stageSize.height; + const width = overlay.width * stageSize.width; + const height = overlay.height * stageSize.height; + const fontFamily = + overlay.type === "sfx" ? displayFontFamily : bodyFontFamily; + const isSpeech = overlay.type === "speech"; + const isNarration = overlay.type === "narration"; + const hasSpeaker = overlay.type !== "sfx" && !!overlay.speaker; + return ( +
+ {!overlay.text ? ( + + {overlay.type} + + ) : !fontsReady ? ( +
+ {hasSpeaker ? `${overlay.speaker}: ${overlay.text}` : overlay.text} +
+ ) : ( + (() => { + const layout = layoutBubbleText( + measureWidth(fontFamily), + overlay.text, + width, + height, + bubbleLayoutOptionsForOverlay( + overlay, + stageSize.height, + width, + height, + ), + ); + return ( +
+ {hasSpeaker && ( + + {overlay.speaker} + + )} + + {layout.lines.map((line, i) => ( + + {line} + + ))} + +
+ ); + })() + )} +
+ ); + })} + + )} +
+
+ ); + + if (!onClick) return stage; + + return ( + + ); +} diff --git a/app/web/dist/assets/export-cut-CDJl8Zjg.js b/app/web/dist/assets/export-cut-HPHvubLr.js similarity index 98% rename from app/web/dist/assets/export-cut-CDJl8Zjg.js rename to app/web/dist/assets/export-cut-HPHvubLr.js index e2b0206..75f0d73 100644 --- a/app/web/dist/assets/export-cut-CDJl8Zjg.js +++ b/app/web/dist/assets/export-cut-HPHvubLr.js @@ -1 +1 @@ -import{M as w,v as O,t as A,c as M,b as R,s as H,l as I,a as B,d as F}from"./index-CP7cx6Zm.js";const z=w;async function G(e){if(typeof document>"u"||!document.fonts||typeof document.fonts.load!="function")return{ready:!0,missing:[]};const n=[];for(const s of e)try{const t=await document.fonts.load(`16px "${s}"`);!t||t.length===0?n.push(s):document.fonts.check(`16px "${s}"`)||n.push(s)}catch{n.push(s)}return{ready:n.length===0,missing:n}}function C(e){return new Promise((n,s)=>{const t=new Image;t.crossOrigin="anonymous",t.onload=()=>n(t),t.onerror=()=>s(new Error("Failed to load image")),t.src=e})}const W="rgba(255, 255, 255, 0.95)",_="#1a1a1a",L="rgba(244, 239, 230, 0.94)",N="rgba(26, 26, 26, 0.55)";function Y(e){return Math.max(2,e*.004)}function K(e,n,s,t,c,d,f){e.beginPath();for(const o of F(n,s,t,c,d,f))o.k==="M"?e.moveTo(o.x,o.y):o.k==="L"?e.lineTo(o.x,o.y):e.arcTo(o.cornerX,o.cornerY,o.x,o.y,o.r);e.closePath()}function P(e,n,s,t,c,d){var f;for(const o of n){const l=o.x*s,i=o.y*t,r=o.width*s,a=o.height*t,y=Y(t);if(o.type==="speech"){const u=R(o,r,a),k=o.tailAnchor?H(l,i,r,a,o.tailAnchor,u):null;K(e,l,i,r,a,k,u),e.fillStyle=W,e.fill(),e.strokeStyle=_,e.lineWidth=y,e.lineJoin="round",e.stroke()}else if(o.type==="narration"){const u=Math.min(r,a)*.12;e.beginPath(),e.roundRect(l,i,r,a,u),e.fillStyle=L,e.fill(),e.strokeStyle=N,e.lineWidth=Math.max(1.5,y*.75),e.lineJoin="round",e.stroke()}const g=o.type==="sfx"?d:c,T=o.type!=="sfx"&&!!o.speaker,h=I((u,k,E=400)=>(e.font=`${E} ${k}px ${g}`,e.measureText(u).width),o.text,r,a,B(o,t,r,a));e.textAlign="center",e.textBaseline="middle";const p=l+r/2,S=T?h.speakerFontSize*1.2:0;T&&(e.fillStyle="#3a3a3a",e.font=`700 ${h.speakerFontSize}px ${g}`,e.fillText(o.speaker,p,i+S/2+a*.04,r-6));const v=i+S,b=a-S,$=h.lines.length*h.lineHeight;let m=v+b/2-$/2+h.lineHeight/2;e.font=`${((f=o.textStyle)==null?void 0:f.fontWeight)??400} ${h.fontSize}px ${g}`;for(const u of h.lines)o.type==="sfx"?(e.fillStyle="#000",e.strokeStyle="#fff",e.lineWidth=3,e.strokeText(u,p,m),e.fillText(u,p,m)):(e.fillStyle="#1a1a1a",e.fillText(u,p,m)),m+=h.lineHeight}}function X(e,n,s,t,c){const d=Math.max(14,Math.min(t*.05,28));e.font=`${d}px ${c}`,e.fillStyle="#1a1a1a",e.textAlign="center",e.textBaseline="middle";const f=[];if(n.dialogue)for(const i of n.dialogue)f.push(`${i.speaker}: ${i.text}`);n.narration&&f.push(n.narration);const o=d*1.6,l=t/2-(f.length-1)*o/2;for(let i=0;iz?{valid:!1,error:`Image is ${(e.size/1024).toFixed(0)}KB, exceeds 1MB limit`}:{valid:!0}}export{z as MAX_SIZE,G as ensureFontsReady,Z as exportCut,P as renderOverlays,A as textPanelDimensions,j as validateExportSize}; +import{M as w,v as O,t as A,c as M,b as R,s as H,l as I,a as B,d as F}from"./index-BGjpCebA.js";const z=w;async function G(e){if(typeof document>"u"||!document.fonts||typeof document.fonts.load!="function")return{ready:!0,missing:[]};const n=[];for(const s of e)try{const t=await document.fonts.load(`16px "${s}"`);!t||t.length===0?n.push(s):document.fonts.check(`16px "${s}"`)||n.push(s)}catch{n.push(s)}return{ready:n.length===0,missing:n}}function C(e){return new Promise((n,s)=>{const t=new Image;t.crossOrigin="anonymous",t.onload=()=>n(t),t.onerror=()=>s(new Error("Failed to load image")),t.src=e})}const W="rgba(255, 255, 255, 0.95)",_="#1a1a1a",L="rgba(244, 239, 230, 0.94)",N="rgba(26, 26, 26, 0.55)";function Y(e){return Math.max(2,e*.004)}function K(e,n,s,t,c,d,f){e.beginPath();for(const o of F(n,s,t,c,d,f))o.k==="M"?e.moveTo(o.x,o.y):o.k==="L"?e.lineTo(o.x,o.y):e.arcTo(o.cornerX,o.cornerY,o.x,o.y,o.r);e.closePath()}function P(e,n,s,t,c,d){var f;for(const o of n){const l=o.x*s,i=o.y*t,r=o.width*s,a=o.height*t,y=Y(t);if(o.type==="speech"){const u=R(o,r,a),k=o.tailAnchor?H(l,i,r,a,o.tailAnchor,u):null;K(e,l,i,r,a,k,u),e.fillStyle=W,e.fill(),e.strokeStyle=_,e.lineWidth=y,e.lineJoin="round",e.stroke()}else if(o.type==="narration"){const u=Math.min(r,a)*.12;e.beginPath(),e.roundRect(l,i,r,a,u),e.fillStyle=L,e.fill(),e.strokeStyle=N,e.lineWidth=Math.max(1.5,y*.75),e.lineJoin="round",e.stroke()}const g=o.type==="sfx"?d:c,T=o.type!=="sfx"&&!!o.speaker,h=I((u,k,E=400)=>(e.font=`${E} ${k}px ${g}`,e.measureText(u).width),o.text,r,a,B(o,t,r,a));e.textAlign="center",e.textBaseline="middle";const p=l+r/2,S=T?h.speakerFontSize*1.2:0;T&&(e.fillStyle="#3a3a3a",e.font=`700 ${h.speakerFontSize}px ${g}`,e.fillText(o.speaker,p,i+S/2+a*.04,r-6));const v=i+S,b=a-S,$=h.lines.length*h.lineHeight;let m=v+b/2-$/2+h.lineHeight/2;e.font=`${((f=o.textStyle)==null?void 0:f.fontWeight)??400} ${h.fontSize}px ${g}`;for(const u of h.lines)o.type==="sfx"?(e.fillStyle="#000",e.strokeStyle="#fff",e.lineWidth=3,e.strokeText(u,p,m),e.fillText(u,p,m)):(e.fillStyle="#1a1a1a",e.fillText(u,p,m)),m+=h.lineHeight}}function X(e,n,s,t,c){const d=Math.max(14,Math.min(t*.05,28));e.font=`${d}px ${c}`,e.fillStyle="#1a1a1a",e.textAlign="center",e.textBaseline="middle";const f=[];if(n.dialogue)for(const i of n.dialogue)f.push(`${i.speaker}: ${i.text}`);n.narration&&f.push(n.narration);const o=d*1.6,l=t/2-(f.length-1)*o/2;for(let i=0;iz?{valid:!1,error:`Image is ${(e.size/1024).toFixed(0)}KB, exceeds 1MB limit`}:{valid:!0}}export{z as MAX_SIZE,G as ensureFontsReady,Z as exportCut,P as renderOverlays,A as textPanelDimensions,j as validateExportSize}; diff --git a/app/web/dist/assets/index-CP7cx6Zm.js b/app/web/dist/assets/index-BGjpCebA.js similarity index 63% rename from app/web/dist/assets/index-CP7cx6Zm.js rename to app/web/dist/assets/index-BGjpCebA.js index f165fdd..164a116 100644 --- a/app/web/dist/assets/index-CP7cx6Zm.js +++ b/app/web/dist/assets/index-BGjpCebA.js @@ -1,4 +1,4 @@ -(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))s(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&s(c)}).observe(document,{childList:!0,subtree:!0});function i(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(a){if(a.ep)return;a.ep=!0;const o=i(a);fetch(a.href,o)}})();function zu(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Yd={exports:{}},lo={};/** +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))s(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&s(c)}).observe(document,{childList:!0,subtree:!0});function i(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(a){if(a.ep)return;a.ep=!0;const o=i(a);fetch(a.href,o)}})();function Pu(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Kd={exports:{}},lo={};/** * @license React * react-jsx-runtime.production.js * @@ -6,7 +6,7 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var J_;function aC(){if(J_)return lo;J_=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function i(s,a,o){var c=null;if(o!==void 0&&(c=""+o),a.key!==void 0&&(c=""+a.key),"key"in a){o={};for(var h in a)h!=="key"&&(o[h]=a[h])}else o=a;return a=o.ref,{$$typeof:e,type:s,key:c,ref:a!==void 0?a:null,props:o}}return lo.Fragment=t,lo.jsx=i,lo.jsxs=i,lo}var eb;function lC(){return eb||(eb=1,Yd.exports=aC()),Yd.exports}var d=lC(),Kd={exports:{}},et={};/** + */var tb;function fC(){if(tb)return lo;tb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function i(s,a,o){var c=null;if(o!==void 0&&(c=""+o),a.key!==void 0&&(c=""+a.key),"key"in a){o={};for(var h in a)h!=="key"&&(o[h]=a[h])}else o=a;return a=o.ref,{$$typeof:e,type:s,key:c,ref:a!==void 0?a:null,props:o}}return lo.Fragment=t,lo.jsx=i,lo.jsxs=i,lo}var ib;function pC(){return ib||(ib=1,Kd.exports=fC()),Kd.exports}var d=pC(),Vd={exports:{}},it={};/** * @license React * react.production.js * @@ -14,7 +14,7 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var tb;function oC(){if(tb)return et;tb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),c=Symbol.for("react.context"),h=Symbol.for("react.forward_ref"),p=Symbol.for("react.suspense"),f=Symbol.for("react.memo"),_=Symbol.for("react.lazy"),x=Symbol.for("react.activity"),b=Symbol.iterator;function v(M){return M===null||typeof M!="object"?null:(M=b&&M[b]||M["@@iterator"],typeof M=="function"?M:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},j=Object.assign,R={};function E(M,G,C){this.props=M,this.context=G,this.refs=R,this.updater=C||S}E.prototype.isReactComponent={},E.prototype.setState=function(M,G){if(typeof M!="object"&&typeof M!="function"&&M!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,M,G,"setState")},E.prototype.forceUpdate=function(M){this.updater.enqueueForceUpdate(this,M,"forceUpdate")};function N(){}N.prototype=E.prototype;function I(M,G,C){this.props=M,this.context=G,this.refs=R,this.updater=C||S}var te=I.prototype=new N;te.constructor=I,j(te,E.prototype),te.isPureReactComponent=!0;var F=Array.isArray;function D(){}var ie={H:null,A:null,T:null,S:null},fe=Object.prototype.hasOwnProperty;function Se(M,G,C){var V=C.ref;return{$$typeof:e,type:M,key:G,ref:V!==void 0?V:null,props:C}}function H(M,G){return Se(M.type,G,M.props)}function ce(M){return typeof M=="object"&&M!==null&&M.$$typeof===e}function W(M){var G={"=":"=0",":":"=2"};return"$"+M.replace(/[=:]/g,function(C){return G[C]})}var K=/\/+/g;function X(M,G){return typeof M=="object"&&M!==null&&M.key!=null?W(""+M.key):G.toString(36)}function U(M){switch(M.status){case"fulfilled":return M.value;case"rejected":throw M.reason;default:switch(typeof M.status=="string"?M.then(D,D):(M.status="pending",M.then(function(G){M.status==="pending"&&(M.status="fulfilled",M.value=G)},function(G){M.status==="pending"&&(M.status="rejected",M.reason=G)})),M.status){case"fulfilled":return M.value;case"rejected":throw M.reason}}throw M}function A(M,G,C,V,ne){var ae=typeof M;(ae==="undefined"||ae==="boolean")&&(M=null);var Y=!1;if(M===null)Y=!0;else switch(ae){case"bigint":case"string":case"number":Y=!0;break;case"object":switch(M.$$typeof){case e:case t:Y=!0;break;case _:return Y=M._init,A(Y(M._payload),G,C,V,ne)}}if(Y)return ne=ne(M),Y=V===""?"."+X(M,0):V,F(ne)?(C="",Y!=null&&(C=Y.replace(K,"$&/")+"/"),A(ne,G,C,"",function(Be){return Be})):ne!=null&&(ce(ne)&&(ne=H(ne,C+(ne.key==null||M&&M.key===ne.key?"":(""+ne.key).replace(K,"$&/")+"/")+Y)),G.push(ne)),1;Y=0;var he=V===""?".":V+":";if(F(M))for(var _e=0;_e>>1,T=A[xe];if(0>>1;xea(C,$))Va(ne,C)?(A[xe]=ne,A[V]=$,xe=V):(A[xe]=C,A[G]=$,xe=G);else if(Va(ne,$))A[xe]=ne,A[V]=$,xe=V;else break e}}return O}function a(A,O){var $=A.sortIndex-O.sortIndex;return $!==0?$:A.id-O.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var c=Date,h=c.now();e.unstable_now=function(){return c.now()-h}}var p=[],f=[],_=1,x=null,b=3,v=!1,S=!1,j=!1,R=!1,E=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,I=typeof setImmediate<"u"?setImmediate:null;function te(A){for(var O=i(f);O!==null;){if(O.callback===null)s(f);else if(O.startTime<=A)s(f),O.sortIndex=O.expirationTime,t(p,O);else break;O=i(f)}}function F(A){if(j=!1,te(A),!S)if(i(p)!==null)S=!0,D||(D=!0,W());else{var O=i(f);O!==null&&U(F,O.startTime-A)}}var D=!1,ie=-1,fe=5,Se=-1;function H(){return R?!0:!(e.unstable_now()-SeA&&H());){var xe=x.callback;if(typeof xe=="function"){x.callback=null,b=x.priorityLevel;var T=xe(x.expirationTime<=A);if(A=e.unstable_now(),typeof T=="function"){x.callback=T,te(A),O=!0;break t}x===i(p)&&s(p),te(A)}else s(p);x=i(p)}if(x!==null)O=!0;else{var M=i(f);M!==null&&U(F,M.startTime-A),O=!1}}break e}finally{x=null,b=$,v=!1}O=void 0}}finally{O?W():D=!1}}}var W;if(typeof I=="function")W=function(){I(ce)};else if(typeof MessageChannel<"u"){var K=new MessageChannel,X=K.port2;K.port1.onmessage=ce,W=function(){X.postMessage(null)}}else W=function(){E(ce,0)};function U(A,O){ie=E(function(){A(e.unstable_now())},O)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(A){A.callback=null},e.unstable_forceFrameRate=function(A){0>A||125xe?(A.sortIndex=$,t(f,A),i(p)===null&&A===i(f)&&(j?(N(ie),ie=-1):j=!0,U(F,$-xe))):(A.sortIndex=T,t(p,A),S||v||(S=!0,D||(D=!0,W()))),A},e.unstable_shouldYield=H,e.unstable_wrapCallback=function(A){var O=b;return function(){var $=b;b=O;try{return A.apply(this,arguments)}finally{b=$}}}})(Zd)),Zd}var rb;function hC(){return rb||(rb=1,Xd.exports=uC()),Xd.exports}var Qd={exports:{}},tn={};/** + */var sb;function xC(){return sb||(sb=1,(function(e){function t(A,z){var $=A.length;A.push(z);e:for(;0<$;){var ge=$-1>>>1,T=A[ge];if(0>>1;gea(C,$))Xa(se,C)?(A[ge]=se,A[X]=$,ge=X):(A[ge]=C,A[V]=$,ge=V);else if(Xa(se,$))A[ge]=se,A[X]=$,ge=X;else break e}}return z}function a(A,z){var $=A.sortIndex-z.sortIndex;return $!==0?$:A.id-z.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var c=Date,h=c.now();e.unstable_now=function(){return c.now()-h}}var p=[],f=[],_=1,x=null,b=3,v=!1,S=!1,j=!1,D=!1,E=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,I=typeof setImmediate<"u"?setImmediate:null;function te(A){for(var z=i(f);z!==null;){if(z.callback===null)s(f);else if(z.startTime<=A)s(f),z.sortIndex=z.expirationTime,t(p,z);else break;z=i(f)}}function q(A){if(j=!1,te(A),!S)if(i(p)!==null)S=!0,R||(R=!0,F());else{var z=i(f);z!==null&&U(q,z.startTime-A)}}var R=!1,ie=-1,fe=5,be=-1;function B(){return D?!0:!(e.unstable_now()-beA&&B());){var ge=x.callback;if(typeof ge=="function"){x.callback=null,b=x.priorityLevel;var T=ge(x.expirationTime<=A);if(A=e.unstable_now(),typeof T=="function"){x.callback=T,te(A),z=!0;break t}x===i(p)&&s(p),te(A)}else s(p);x=i(p)}if(x!==null)z=!0;else{var M=i(f);M!==null&&U(q,M.startTime-A),z=!1}}break e}finally{x=null,b=$,v=!1}z=void 0}}finally{z?F():R=!1}}}var F;if(typeof I=="function")F=function(){I(ne)};else if(typeof MessageChannel<"u"){var G=new MessageChannel,Y=G.port2;G.port1.onmessage=ne,F=function(){Y.postMessage(null)}}else F=function(){E(ne,0)};function U(A,z){ie=E(function(){A(e.unstable_now())},z)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(A){A.callback=null},e.unstable_forceFrameRate=function(A){0>A||125ge?(A.sortIndex=$,t(f,A),i(p)===null&&A===i(f)&&(j?(N(ie),ie=-1):j=!0,U(q,$-ge))):(A.sortIndex=T,t(p,A),S||v||(S=!0,R||(R=!0,F()))),A},e.unstable_shouldYield=B,e.unstable_wrapCallback=function(A){var z=b;return function(){var $=b;b=z;try{return A.apply(this,arguments)}finally{b=$}}}})(Qd)),Qd}var ab;function _C(){return ab||(ab=1,Zd.exports=xC()),Zd.exports}var Jd={exports:{}},tn={};/** * @license React * react-dom.production.js * @@ -30,7 +30,7 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var sb;function dC(){if(sb)return tn;sb=1;var e=Hp();function t(p){var f="https://react.dev/errors/"+p;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Qd.exports=dC(),Qd.exports}/** + */var lb;function bC(){if(lb)return tn;lb=1;var e=Hp();function t(p){var f="https://react.dev/errors/"+p;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Jd.exports=bC(),Jd.exports}/** * @license React * react-dom-client.production.js * @@ -38,15 +38,15 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var lb;function pC(){if(lb)return oo;lb=1;var e=hC(),t=Hp(),i=fC();function s(n){var r="https://react.dev/errors/"+n;if(1T||(n.current=xe[T],xe[T]=null,T--)}function C(n,r){T++,xe[T]=n.current,n.current=r}var V=M(null),ne=M(null),ae=M(null),Y=M(null);function he(n,r){switch(C(ae,r),C(ne,n),C(V,null),r.nodeType){case 9:case 11:n=(n=r.documentElement)&&(n=n.namespaceURI)?S_(n):0;break;default:if(n=r.tagName,r=r.namespaceURI)r=S_(r),n=w_(r,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}G(V),C(V,n)}function _e(){G(V),G(ne),G(ae)}function Be(n){n.memoizedState!==null&&C(Y,n);var r=V.current,l=w_(r,n.type);r!==l&&(C(ne,n),C(V,l))}function Le(n){ne.current===n&&(G(V),G(ne)),Y.current===n&&(G(Y),no._currentValue=$)}var je,be;function tt(n){if(je===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);je=r&&r[1]||"",be=-1T||(n.current=ge[T],ge[T]=null,T--)}function C(n,r){T++,ge[T]=n.current,n.current=r}var X=M(null),se=M(null),le=M(null),K=M(null);function he(n,r){switch(C(le,r),C(se,n),C(X,null),r.nodeType){case 9:case 11:n=(n=r.documentElement)&&(n=n.namespaceURI)?C_(n):0;break;default:if(n=r.tagName,r=r.namespaceURI)r=C_(r),n=k_(r,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}V(X),C(X,n)}function _e(){V(X),V(se),V(le)}function Me(n){n.memoizedState!==null&&C(K,n);var r=X.current,l=k_(r,n.type);r!==l&&(C(se,n),C(X,l))}function Le(n){se.current===n&&(V(X),V(se)),K.current===n&&(V(K),no._currentValue=$)}var He,ke;function Ue(n){if(He===void 0)try{throw Error()}catch(l){var r=l.stack.trim().match(/\n( *(at )?)/);He=r&&r[1]||"",ke=-1)":-1m||B[u]!==J[m]){var ue=` -`+B[u].replace(" at new "," at ");return n.displayName&&ue.includes("")&&(ue=ue.replace("",n.displayName)),ue}while(1<=u&&0<=m);break}}}finally{St=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?tt(l):""}function We(n,r){switch(n.tag){case 26:case 27:case 5:return tt(n.type);case 16:return tt("Lazy");case 13:return n.child!==r&&r!==null?tt("Suspense Fallback"):tt("Suspense");case 19:return tt("SuspenseList");case 0:case 15:return ot(n.type,!1);case 11:return ot(n.type.render,!1);case 1:return ot(n.type,!0);case 31:return tt("Activity");default:return""}}function Mt(n){try{var r="",l=null;do r+=We(n,l),l=n,n=n.return;while(n);return r}catch(u){return` +`);for(m=u=0;um||L[u]!==J[m]){var ue=` +`+L[u].replace(" at new "," at ");return n.displayName&&ue.includes("")&&(ue=ue.replace("",n.displayName)),ue}while(1<=u&&0<=m);break}}}finally{Je=!1,Error.prepareStackTrace=l}return(l=n?n.displayName||n.name:"")?Ue(l):""}function Ve(n,r){switch(n.tag){case 26:case 27:case 5:return Ue(n.type);case 16:return Ue("Lazy");case 13:return n.child!==r&&r!==null?Ue("Suspense Fallback"):Ue("Suspense");case 19:return Ue("SuspenseList");case 0:case 15:return at(n.type,!1);case 11:return at(n.type.render,!1);case 1:return at(n.type,!0);case 31:return Ue("Activity");default:return""}}function Et(n){try{var r="",l=null;do r+=Ve(n,l),l=n,n=n.return;while(n);return r}catch(u){return` Error generating stack: `+u.message+` -`+u.stack}}var He=Object.prototype.hasOwnProperty,xt=e.unstable_scheduleCallback,Ae=e.unstable_cancelCallback,Kt=e.unstable_shouldYield,mi=e.unstable_requestPaint,wt=e.unstable_now,Qe=e.unstable_getCurrentPriorityLevel,Q=e.unstable_ImmediatePriority,ge=e.unstable_UserBlockingPriority,Te=e.unstable_NormalPriority,Ue=e.unstable_LowPriority,it=e.unstable_IdlePriority,Wt=e.log,ui=e.unstable_setDisableYieldValue,Bt=null,vt=null;function At(n){if(typeof Wt=="function"&&ui(n),vt&&typeof vt.setStrictMode=="function")try{vt.setStrictMode(Bt,n)}catch{}}var Ze=Math.clz32?Math.clz32:we,hi=Math.log,P=Math.LN2;function we(n){return n>>>=0,n===0?32:31-(hi(n)/P|0)|0}var ze=256,Re=262144,Ge=4194304;function $e(n){var r=n&42;if(r!==0)return r;switch(n&-n){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return n&261888;case 262144:case 524288:case 1048576:case 2097152:return n&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return n&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return n}}function ht(n,r,l){var u=n.pendingLanes;if(u===0)return 0;var m=0,g=n.suspendedLanes,y=n.pingedLanes;n=n.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?m=$e(u):(y&=k,y!==0?m=$e(y):l||(l=k&~n,l!==0&&(m=$e(l))))):(k=u&~g,k!==0?m=$e(k):y!==0?m=$e(y):l||(l=u&~n,l!==0&&(m=$e(l)))),m===0?0:r!==0&&r!==m&&(r&g)===0&&(g=m&-m,l=r&-r,g>=l||g===32&&(l&4194048)!==0)?r:m}function dt(n,r){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&r)===0}function lt(n,r){switch(n){case 1:case 2:case 4:case 8:case 64:return r+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return r+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Vt(){var n=Ge;return Ge<<=1,(Ge&62914560)===0&&(Ge=4194304),n}function Ci(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function ft(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function Fi(n,r,l,u,m,g){var y=n.pendingLanes;n.pendingLanes=l,n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0,n.expiredLanes&=l,n.entangledLanes&=l,n.errorRecoveryDisabledLanes&=l,n.shellSuspendCounter=0;var k=n.entanglements,B=n.expirationTimes,J=n.hiddenUpdates;for(l=y&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var Ei=/[\n"\\]/g;function gi(n){return n.replace(Ei,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function Gi(n,r,l,u,m,g,y,k){n.name="",y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"?n.type=y:n.removeAttribute("type"),r!=null?y==="number"?(r===0&&n.value===""||n.value!=r)&&(n.value=""+Ct(r)):n.value!==""+Ct(r)&&(n.value=""+Ct(r)):y!=="submit"&&y!=="reset"||n.removeAttribute("value"),r!=null?Or(n,y,Ct(r)):l!=null?Or(n,y,Ct(l)):u!=null&&n.removeAttribute("value"),m==null&&g!=null&&(n.defaultChecked=!!g),m!=null&&(n.checked=m&&typeof m!="function"&&typeof m!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?n.name=""+Ct(k):n.removeAttribute("name")}function Nn(n,r,l,u,m,g,y,k){if(g!=null&&typeof g!="function"&&typeof g!="symbol"&&typeof g!="boolean"&&(n.type=g),r!=null||l!=null){if(!(g!=="submit"&&g!=="reset"||r!=null)){Lr(n);return}l=l!=null?""+Ct(l):"",r=r!=null?""+Ct(r):l,k||r===n.value||(n.value=r),n.defaultValue=r}u=u??m,u=typeof u!="function"&&typeof u!="symbol"&&!!u,n.checked=k?n.checked:!!u,n.defaultChecked=!!u,y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(n.name=y),Lr(n)}function Or(n,r,l){r==="number"&&xr(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function jn(n,r,l,u){if(n=n.options,r){r={};for(var m=0;m"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),re=!1;if(Wn)try{var ye={};Object.defineProperty(ye,"passive",{get:function(){re=!0}}),window.addEventListener("test",ye,ye),window.removeEventListener("test",ye,ye)}catch{re=!1}var ke=null,Je=null,Pt=null;function Ni(){if(Pt)return Pt;var n,r=Je,l=r.length,u,m="value"in ke?ke.value:ke.textContent,g=m.length;for(n=0;n=Cl),Tm=" ",Am=!1;function Rm(n,r){switch(n){case"keyup":return j1.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Dm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Na=!1;function A1(n,r){switch(n){case"compositionend":return Dm(r);case"keypress":return r.which!==32?null:(Am=!0,Tm);case"textInput":return n=r.data,n===Tm&&Am?null:n;default:return null}}function R1(n,r){if(Na)return n==="compositionend"||!Ju&&Rm(n,r)?(n=Ni(),Pt=Je=ke=null,Na=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(r.ctrlKey||r.altKey||r.metaKey)||r.ctrlKey&&r.altKey){if(r.char&&1=r)return{node:l,offset:r-n};n=u}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=Hm(l)}}function $m(n,r){return n&&r?n===r?!0:n&&n.nodeType===3?!1:r&&r.nodeType===3?$m(n,r.parentNode):"contains"in n?n.contains(r):n.compareDocumentPosition?!!(n.compareDocumentPosition(r)&16):!1:!1}function Fm(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var r=xr(n.document);r instanceof n.HTMLIFrameElement;){try{var l=typeof r.contentWindow.location.href=="string"}catch{l=!1}if(l)n=r.contentWindow;else break;r=xr(n.document)}return r}function ih(n){var r=n&&n.nodeName&&n.nodeName.toLowerCase();return r&&(r==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||r==="textarea"||n.contentEditable==="true")}var I1=Wn&&"documentMode"in document&&11>=document.documentMode,ja=null,nh=null,jl=null,rh=!1;function qm(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;rh||ja==null||ja!==xr(u)||(u=ja,"selectionStart"in u&&ih(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),jl&&Nl(jl,u)||(jl=u,u=Ic(nh,"onSelect"),0>=y,m-=y,yr=1<<32-Ze(r)+m|l<st?(bt=Ie,Ie=null):bt=Ie.sibling;var Tt=ee(q,Ie,Z[st],de);if(Tt===null){Ie===null&&(Ie=bt);break}n&&Ie&&Tt.alternate===null&&r(q,Ie),z=g(Tt,z,st),jt===null?Fe=Tt:jt.sibling=Tt,jt=Tt,Ie=bt}if(st===Z.length)return l(q,Ie),yt&&Pr(q,st),Fe;if(Ie===null){for(;stst?(bt=Ie,Ie=null):bt=Ie.sibling;var Ds=ee(q,Ie,Tt.value,de);if(Ds===null){Ie===null&&(Ie=bt);break}n&&Ie&&Ds.alternate===null&&r(q,Ie),z=g(Ds,z,st),jt===null?Fe=Ds:jt.sibling=Ds,jt=Ds,Ie=bt}if(Tt.done)return l(q,Ie),yt&&Pr(q,st),Fe;if(Ie===null){for(;!Tt.done;st++,Tt=Z.next())Tt=pe(q,Tt.value,de),Tt!==null&&(z=g(Tt,z,st),jt===null?Fe=Tt:jt.sibling=Tt,jt=Tt);return yt&&Pr(q,st),Fe}for(Ie=u(Ie);!Tt.done;st++,Tt=Z.next())Tt=se(Ie,q,st,Tt.value,de),Tt!==null&&(n&&Tt.alternate!==null&&Ie.delete(Tt.key===null?st:Tt.key),z=g(Tt,z,st),jt===null?Fe=Tt:jt.sibling=Tt,jt=Tt);return n&&Ie.forEach(function(sC){return r(q,sC)}),yt&&Pr(q,st),Fe}function Ut(q,z,Z,de){if(typeof Z=="object"&&Z!==null&&Z.type===j&&Z.key===null&&(Z=Z.props.children),typeof Z=="object"&&Z!==null){switch(Z.$$typeof){case v:e:{for(var Fe=Z.key;z!==null;){if(z.key===Fe){if(Fe=Z.type,Fe===j){if(z.tag===7){l(q,z.sibling),de=m(z,Z.props.children),de.return=q,q=de;break e}}else if(z.elementType===Fe||typeof Fe=="object"&&Fe!==null&&Fe.$$typeof===fe&&ta(Fe)===z.type){l(q,z.sibling),de=m(z,Z.props),Bl(de,Z),de.return=q,q=de;break e}l(q,z);break}else r(q,z);z=z.sibling}Z.type===j?(de=Xs(Z.props.children,q.mode,de,Z.key),de.return=q,q=de):(de=ic(Z.type,Z.key,Z.props,null,q.mode,de),Bl(de,Z),de.return=q,q=de)}return y(q);case S:e:{for(Fe=Z.key;z!==null;){if(z.key===Fe)if(z.tag===4&&z.stateNode.containerInfo===Z.containerInfo&&z.stateNode.implementation===Z.implementation){l(q,z.sibling),de=m(z,Z.children||[]),de.return=q,q=de;break e}else{l(q,z);break}else r(q,z);z=z.sibling}de=hh(Z,q.mode,de),de.return=q,q=de}return y(q);case fe:return Z=ta(Z),Ut(q,z,Z,de)}if(U(Z))return Oe(q,z,Z,de);if(W(Z)){if(Fe=W(Z),typeof Fe!="function")throw Error(s(150));return Z=Fe.call(Z),Ke(q,z,Z,de)}if(typeof Z.then=="function")return Ut(q,z,cc(Z),de);if(Z.$$typeof===I)return Ut(q,z,sc(q,Z),de);uc(q,Z)}return typeof Z=="string"&&Z!==""||typeof Z=="number"||typeof Z=="bigint"?(Z=""+Z,z!==null&&z.tag===6?(l(q,z.sibling),de=m(z,Z),de.return=q,q=de):(l(q,z),de=uh(Z,q.mode,de),de.return=q,q=de),y(q)):l(q,z)}return function(q,z,Z,de){try{Ml=0;var Fe=Ut(q,z,Z,de);return Ia=null,Fe}catch(Ie){if(Ie===Pa||Ie===lc)throw Ie;var jt=An(29,Ie,null,q.mode);return jt.lanes=de,jt.return=q,jt}finally{}}}var na=fg(!0),pg=fg(!1),ms=!1;function wh(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ch(n,r){n=n.updateQueue,r.updateQueue===n&&(r.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function gs(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function xs(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(Dt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=tc(n),Zm(n,null,l),r}return ec(n,u,r,l),tc(n)}function Ll(n,r,l){if(r=r.updateQueue,r!==null&&(r=r.shared,(l&4194048)!==0)){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,ln(n,l)}}function kh(n,r){var l=n.updateQueue,u=n.alternate;if(u!==null&&(u=u.updateQueue,l===u)){var m=null,g=null;if(l=l.firstBaseUpdate,l!==null){do{var y={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=y:g=g.next=y,l=l.next}while(l!==null);g===null?m=g=r:g=g.next=r}else m=g=r;l={baseState:u.baseState,firstBaseUpdate:m,lastBaseUpdate:g,shared:u.shared,callbacks:u.callbacks},n.updateQueue=l;return}n=l.lastBaseUpdate,n===null?l.firstBaseUpdate=r:n.next=r,l.lastBaseUpdate=r}var Eh=!1;function Ol(){if(Eh){var n=za;if(n!==null)throw n}}function zl(n,r,l,u){Eh=!1;var m=n.updateQueue;ms=!1;var g=m.firstBaseUpdate,y=m.lastBaseUpdate,k=m.shared.pending;if(k!==null){m.shared.pending=null;var B=k,J=B.next;B.next=null,y===null?g=J:y.next=J,y=B;var ue=n.alternate;ue!==null&&(ue=ue.updateQueue,k=ue.lastBaseUpdate,k!==y&&(k===null?ue.firstBaseUpdate=J:k.next=J,ue.lastBaseUpdate=B))}if(g!==null){var pe=m.baseState;y=0,ue=J=B=null,k=g;do{var ee=k.lane&-536870913,se=ee!==k.lane;if(se?(_t&ee)===ee:(u&ee)===ee){ee!==0&&ee===Oa&&(Eh=!0),ue!==null&&(ue=ue.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Oe=n,Ke=k;ee=r;var Ut=l;switch(Ke.tag){case 1:if(Oe=Ke.payload,typeof Oe=="function"){pe=Oe.call(Ut,pe,ee);break e}pe=Oe;break e;case 3:Oe.flags=Oe.flags&-65537|128;case 0:if(Oe=Ke.payload,ee=typeof Oe=="function"?Oe.call(Ut,pe,ee):Oe,ee==null)break e;pe=x({},pe,ee);break e;case 2:ms=!0}}ee=k.callback,ee!==null&&(n.flags|=64,se&&(n.flags|=8192),se=m.callbacks,se===null?m.callbacks=[ee]:se.push(ee))}else se={lane:ee,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ue===null?(J=ue=se,B=pe):ue=ue.next=se,y|=ee;if(k=k.next,k===null){if(k=m.shared.pending,k===null)break;se=k,k=se.next,se.next=null,m.lastBaseUpdate=se,m.shared.pending=null}}while(!0);ue===null&&(B=pe),m.baseState=B,m.firstBaseUpdate=J,m.lastBaseUpdate=ue,g===null&&(m.shared.lanes=0),Ss|=y,n.lanes=y,n.memoizedState=pe}}function mg(n,r){if(typeof n!="function")throw Error(s(191,n));n.call(r)}function gg(n,r){var l=n.callbacks;if(l!==null)for(n.callbacks=null,n=0;ng?g:8;var y=A.T,k={};A.T=k,Wh(n,!1,r,l);try{var B=m(),J=A.S;if(J!==null&&J(k,B),B!==null&&typeof B=="object"&&typeof B.then=="function"){var ue=K1(B,u);Hl(n,r,ue,Ln(n))}else Hl(n,r,u,Ln(n))}catch(pe){Hl(n,r,{then:function(){},status:"rejected",reason:pe},Ln())}finally{O.p=g,y!==null&&k.types!==null&&(y.types=k.types),A.T=y}}function ew(){}function Fh(n,r,l,u){if(n.tag!==5)throw Error(s(476));var m=Kg(n).queue;Yg(n,m,r,$,l===null?ew:function(){return Vg(n),l(u)})}function Kg(n){var r=n.memoizedState;if(r!==null)return r;r={memoizedState:$,baseState:$,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:$r,lastRenderedState:$},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:$r,lastRenderedState:l},next:null},n.memoizedState=r,n=n.alternate,n!==null&&(n.memoizedState=r),r}function Vg(n){var r=Kg(n);r.next===null&&(r=n.alternate.memoizedState),Hl(n,r.next.queue,{},Ln())}function qh(){return Vi(no)}function Xg(){return fi().memoizedState}function Zg(){return fi().memoizedState}function tw(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=Ln();n=gs(l);var u=xs(r,n,l);u!==null&&(yn(u,r,l),Ll(u,r,l)),r={cache:bh()},n.payload=r;return}r=r.return}}function iw(n,r,l){var u=Ln();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},vc(n)?Jg(r,l):(l=oh(n,r,l,u),l!==null&&(yn(l,n,u),ex(l,r,u)))}function Qg(n,r,l){var u=Ln();Hl(n,r,l,u)}function Hl(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(vc(n))Jg(r,m);else{var g=n.alternate;if(n.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var y=r.lastRenderedState,k=g(y,l);if(m.hasEagerState=!0,m.eagerState=k,Tn(k,y))return ec(n,r,m,0),Ft===null&&Jo(),!1}catch{}finally{}if(l=oh(n,r,m,u),l!==null)return yn(l,n,u),ex(l,r,u),!0}return!1}function Wh(n,r,l,u){if(u={lane:2,revertLane:wd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},vc(n)){if(r)throw Error(s(479))}else r=oh(n,l,u,2),r!==null&&yn(r,n,2)}function vc(n){var r=n.alternate;return n===rt||r!==null&&r===rt}function Jg(n,r){Ua=fc=!0;var l=n.pending;l===null?r.next=r:(r.next=l.next,l.next=r),n.pending=r}function ex(n,r,l){if((l&4194048)!==0){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,ln(n,l)}}var Ul={readContext:Vi,use:gc,useCallback:si,useContext:si,useEffect:si,useImperativeHandle:si,useLayoutEffect:si,useInsertionEffect:si,useMemo:si,useReducer:si,useRef:si,useState:si,useDebugValue:si,useDeferredValue:si,useTransition:si,useSyncExternalStore:si,useId:si,useHostTransitionStatus:si,useFormState:si,useActionState:si,useOptimistic:si,useMemoCache:si,useCacheRefresh:si};Ul.useEffectEvent=si;var tx={readContext:Vi,use:gc,useCallback:function(n,r){return un().memoizedState=[n,r===void 0?null:r],n},useContext:Vi,useEffect:Pg,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,_c(4194308,4,$g.bind(null,r,n),l)},useLayoutEffect:function(n,r){return _c(4194308,4,n,r)},useInsertionEffect:function(n,r){_c(4,2,n,r)},useMemo:function(n,r){var l=un();r=r===void 0?null:r;var u=n();if(ra){At(!0);try{n()}finally{At(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=un();if(l!==void 0){var m=l(r);if(ra){At(!0);try{l(r)}finally{At(!1)}}}else m=r;return u.memoizedState=u.baseState=m,n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:m},u.queue=n,n=n.dispatch=iw.bind(null,rt,n),[u.memoizedState,n]},useRef:function(n){var r=un();return n={current:n},r.memoizedState=n},useState:function(n){n=Ph(n);var r=n.queue,l=Qg.bind(null,rt,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:Uh,useDeferredValue:function(n,r){var l=un();return $h(l,n,r)},useTransition:function(){var n=Ph(!1);return n=Yg.bind(null,rt,n.queue,!0,!1),un().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=rt,m=un();if(yt){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),Ft===null)throw Error(s(349));(_t&127)!==0||Sg(u,r,l)}m.memoizedState=l;var g={value:l,getSnapshot:r};return m.queue=g,Pg(Cg.bind(null,u,g,n),[n]),u.flags|=2048,Fa(9,{destroy:void 0},wg.bind(null,u,g,l,r),null),l},useId:function(){var n=un(),r=Ft.identifierPrefix;if(yt){var l=Sr,u=yr;l=(u&~(1<<32-Ze(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=pc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?y.createElement("select",{is:u.is}):y.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?y.createElement(m,{is:u.is}):y.createElement(m)}}g[le]=r,g[L]=u;e:for(y=r.child;y!==null;){if(y.tag===5||y.tag===6)g.appendChild(y.stateNode);else if(y.tag!==4&&y.tag!==27&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===r)break e;for(;y.sibling===null;){if(y.return===null||y.return===r)break e;y=y.return}y.sibling.return=y.return,y=y.sibling}r.stateNode=g;e:switch(Zi(g,m,u),m){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&qr(r)}}return Zt(r),sd(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&qr(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=ae.current,Ba(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Ki,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[le]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||v_(n.nodeValue,l)),n||fs(r,!0)}else n=Hc(n).createTextNode(u),n[le]=r,r.stateNode=n}return Zt(r),null;case 31:if(l=r.memoizedState,n===null||n.memoizedState!==null){if(u=Ba(r),l!==null){if(n===null){if(!u)throw Error(s(318));if(n=r.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(s(557));n[le]=r}else Zs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Zt(r),n=!1}else l=mh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=l),n=!0;if(!n)return r.flags&256?(Dn(r),r):(Dn(r),null);if((r.flags&128)!==0)throw Error(s(558))}return Zt(r),null;case 13:if(u=r.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Ba(r),u!==null&&u.dehydrated!==null){if(n===null){if(!m)throw Error(s(318));if(m=r.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(s(317));m[le]=r}else Zs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Zt(r),m=!1}else m=mh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return r.flags&256?(Dn(r),r):(Dn(r),null)}return Dn(r),(r.flags&128)!==0?(r.lanes=l,r):(l=u!==null,n=n!==null&&n.memoizedState!==null,l&&(u=r.child,m=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(m=u.alternate.memoizedState.cachePool.pool),g=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(g=u.memoizedState.cachePool.pool),g!==m&&(u.flags|=2048)),l!==n&&l&&(r.child.flags|=8192),kc(r,r.updateQueue),Zt(r),null);case 4:return _e(),n===null&&Nd(r.stateNode.containerInfo),Zt(r),null;case 10:return Hr(r.type),Zt(r),null;case 19:if(G(di),u=r.memoizedState,u===null)return Zt(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)Fl(u,!1);else{if(ai!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=dc(n),g!==null){for(r.flags|=128,Fl(u,!1),n=g.updateQueue,r.updateQueue=n,kc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)Qm(l,n),l=l.sibling;return C(di,di.current&1|2),yt&&Pr(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&wt()>Ac&&(r.flags|=128,m=!0,Fl(u,!1),r.lanes=4194304)}else{if(!m)if(n=dc(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,kc(r,n),Fl(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!yt)return Zt(r),null}else 2*wt()-u.renderingStartTime>Ac&&l!==536870912&&(r.flags|=128,m=!0,Fl(u,!1),r.lanes=4194304);u.isBackwards?(g.sibling=r.child,r.child=g):(n=u.last,n!==null?n.sibling=g:r.child=g,u.last=g)}return u.tail!==null?(n=u.tail,u.rendering=n,u.tail=n.sibling,u.renderingStartTime=wt(),n.sibling=null,l=di.current,C(di,m?l&1|2:l&1),yt&&Pr(r,u.treeForkCount),n):(Zt(r),null);case 22:case 23:return Dn(r),jh(),u=r.memoizedState!==null,n!==null?n.memoizedState!==null!==u&&(r.flags|=8192):u&&(r.flags|=8192),u?(l&536870912)!==0&&(r.flags&128)===0&&(Zt(r),r.subtreeFlags&6&&(r.flags|=8192)):Zt(r),l=r.updateQueue,l!==null&&kc(r,l.retryQueue),l=null,n!==null&&n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(l=n.memoizedState.cachePool.pool),u=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(u=r.memoizedState.cachePool.pool),u!==l&&(r.flags|=2048),n!==null&&G(ea),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),Hr(xi),Zt(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function lw(n,r){switch(fh(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return Hr(xi),_e(),n=r.flags,(n&65536)!==0&&(n&128)===0?(r.flags=n&-65537|128,r):null;case 26:case 27:case 5:return Le(r),null;case 31:if(r.memoizedState!==null){if(Dn(r),r.alternate===null)throw Error(s(340));Zs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 13:if(Dn(r),n=r.memoizedState,n!==null&&n.dehydrated!==null){if(r.alternate===null)throw Error(s(340));Zs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return G(di),null;case 4:return _e(),null;case 10:return Hr(r.type),null;case 22:case 23:return Dn(r),jh(),n!==null&&G(ea),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return Hr(xi),null;case 25:return null;default:return null}}function kx(n,r){switch(fh(r),r.tag){case 3:Hr(xi),_e();break;case 26:case 27:case 5:Le(r);break;case 4:_e();break;case 31:r.memoizedState!==null&&Dn(r);break;case 13:Dn(r);break;case 19:G(di);break;case 10:Hr(r.type);break;case 22:case 23:Dn(r),jh(),n!==null&&G(ea);break;case 24:Hr(xi)}}function ql(n,r){try{var l=r.updateQueue,u=l!==null?l.lastEffect:null;if(u!==null){var m=u.next;l=m;do{if((l.tag&n)===n){u=void 0;var g=l.create,y=l.inst;u=g(),y.destroy=u}l=l.next}while(l!==m)}}catch(k){zt(r,r.return,k)}}function vs(n,r,l){try{var u=r.updateQueue,m=u!==null?u.lastEffect:null;if(m!==null){var g=m.next;u=g;do{if((u.tag&n)===n){var y=u.inst,k=y.destroy;if(k!==void 0){y.destroy=void 0,m=r;var B=l,J=k;try{J()}catch(ue){zt(m,B,ue)}}}u=u.next}while(u!==g)}}catch(ue){zt(r,r.return,ue)}}function Ex(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{gg(r,l)}catch(u){zt(n,n.return,u)}}}function Nx(n,r,l){l.props=sa(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){zt(n,r,u)}}function Wl(n,r){try{var l=n.ref;if(l!==null){switch(n.tag){case 26:case 27:case 5:var u=n.stateNode;break;case 30:u=n.stateNode;break;default:u=n.stateNode}typeof l=="function"?n.refCleanup=l(u):l.current=u}}catch(m){zt(n,r,m)}}function wr(n,r){var l=n.ref,u=n.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){zt(n,r,m)}finally{n.refCleanup=null,n=n.alternate,n!=null&&(n.refCleanup=null)}else if(typeof l=="function")try{l(null)}catch(m){zt(n,r,m)}else l.current=null}function jx(n){var r=n.type,l=n.memoizedProps,u=n.stateNode;try{e:switch(r){case"button":case"input":case"select":case"textarea":l.autoFocus&&u.focus();break e;case"img":l.src?u.src=l.src:l.srcSet&&(u.srcset=l.srcSet)}}catch(m){zt(n,n.return,m)}}function ad(n,r,l){try{var u=n.stateNode;Tw(u,n.type,l,r),u[L]=r}catch(m){zt(n,n.return,m)}}function Tx(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&Ns(n.type)||n.tag===4}function ld(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||Tx(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;n.tag!==5&&n.tag!==6&&n.tag!==18;){if(n.tag===27&&Ns(n.type)||n.flags&2||n.child===null||n.tag===4)continue e;n.child.return=n,n=n.child}if(!(n.flags&2))return n.stateNode}}function od(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(n,r):(r=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,r.appendChild(n),l=l._reactRootContainer,l!=null||r.onclick!==null||(r.onclick=lr));else if(u!==4&&(u===27&&Ns(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(od(n,r,l),n=n.sibling;n!==null;)od(n,r,l),n=n.sibling}function Ec(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?l.insertBefore(n,r):l.appendChild(n);else if(u!==4&&(u===27&&Ns(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(Ec(n,r,l),n=n.sibling;n!==null;)Ec(n,r,l),n=n.sibling}function Ax(n){var r=n.stateNode,l=n.memoizedProps;try{for(var u=n.type,m=r.attributes;m.length;)r.removeAttributeNode(m[0]);Zi(r,u,l),r[le]=n,r[L]=l}catch(g){zt(n,n.return,g)}}var Wr=!1,vi=!1,cd=!1,Rx=typeof WeakSet=="function"?WeakSet:Set,Mi=null;function ow(n,r){if(n=n.containerInfo,Ad=Yc,n=Fm(n),ih(n)){if("selectionStart"in n)var l={start:n.selectionStart,end:n.selectionEnd};else e:{l=(l=n.ownerDocument)&&l.defaultView||window;var u=l.getSelection&&l.getSelection();if(u&&u.rangeCount!==0){l=u.anchorNode;var m=u.anchorOffset,g=u.focusNode;u=u.focusOffset;try{l.nodeType,g.nodeType}catch{l=null;break e}var y=0,k=-1,B=-1,J=0,ue=0,pe=n,ee=null;t:for(;;){for(var se;pe!==l||m!==0&&pe.nodeType!==3||(k=y+m),pe!==g||u!==0&&pe.nodeType!==3||(B=y+u),pe.nodeType===3&&(y+=pe.nodeValue.length),(se=pe.firstChild)!==null;)ee=pe,pe=se;for(;;){if(pe===n)break t;if(ee===l&&++J===m&&(k=y),ee===g&&++ue===u&&(B=y),(se=pe.nextSibling)!==null)break;pe=ee,ee=pe.parentNode}pe=se}l=k===-1||B===-1?null:{start:k,end:B}}else l=null}l=l||{start:0,end:0}}else l=null;for(Rd={focusedElem:n,selectionRange:l},Yc=!1,Mi=r;Mi!==null;)if(r=Mi,n=r.child,(r.subtreeFlags&1028)!==0&&n!==null)n.return=r,Mi=n;else for(;Mi!==null;){switch(r=Mi,g=r.alternate,n=r.flags,r.tag){case 0:if((n&4)!==0&&(n=r.updateQueue,n=n!==null?n.events:null,n!==null))for(l=0;l title"))),Zi(g,u,l),g[le]=n,Rt(g),u=g;break e;case"link":var y=z_("link","href",m).get(u+(l.href||""));if(y){for(var k=0;kUt&&(y=Ut,Ut=Ke,Ke=y);var q=Um(k,Ke),z=Um(k,Ut);if(q&&z&&(se.rangeCount!==1||se.anchorNode!==q.node||se.anchorOffset!==q.offset||se.focusNode!==z.node||se.focusOffset!==z.offset)){var Z=pe.createRange();Z.setStart(q.node,q.offset),se.removeAllRanges(),Ke>Ut?(se.addRange(Z),se.extend(z.node,z.offset)):(Z.setEnd(z.node,z.offset),se.addRange(Z))}}}}for(pe=[],se=k;se=se.parentNode;)se.nodeType===1&&pe.push({element:se,left:se.scrollLeft,top:se.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kl?32:l,A.T=null,l=gd,gd=null;var g=Cs,y=Xr;if(ji=0,Ka=Cs=null,Xr=0,(Dt&6)!==0)throw Error(s(331));var k=Dt;if(Dt|=4,$x(g.current),Ix(g,g.current,y,l),Dt=k,Zl(0,!1),vt&&typeof vt.onPostCommitFiberRoot=="function")try{vt.onPostCommitFiberRoot(Bt,g)}catch{}return!0}finally{O.p=m,A.T=u,a_(n,r)}}function o_(n,r,l){r=Kn(l,r),r=Vh(n.stateNode,r,2),n=xs(n,r,2),n!==null&&(ft(n,2),Cr(n))}function zt(n,r,l){if(n.tag===3)o_(n,n,l);else for(;r!==null;){if(r.tag===3){o_(r,n,l);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ws===null||!ws.has(u))){n=Kn(l,n),l=cx(2),u=xs(r,l,2),u!==null&&(ux(l,u,r,n),ft(u,2),Cr(u));break}}r=r.return}}function vd(n,r,l){var u=n.pingCache;if(u===null){u=n.pingCache=new hw;var m=new Set;u.set(r,m)}else m=u.get(r),m===void 0&&(m=new Set,u.set(r,m));m.has(l)||(dd=!0,m.add(l),n=gw.bind(null,n,r,l),r.then(n,n))}function gw(n,r,l){var u=n.pingCache;u!==null&&u.delete(r),n.pingedLanes|=n.suspendedLanes&l,n.warmLanes&=~l,Ft===n&&(_t&l)===l&&(ai===4||ai===3&&(_t&62914560)===_t&&300>wt()-Tc?(Dt&2)===0&&Va(n,0):fd|=l,Ya===_t&&(Ya=0)),Cr(n)}function c_(n,r){r===0&&(r=Vt()),n=Vs(n,r),n!==null&&(ft(n,r),Cr(n))}function xw(n){var r=n.memoizedState,l=0;r!==null&&(l=r.retryLane),c_(n,l)}function _w(n,r){var l=0;switch(n.tag){case 31:case 13:var u=n.stateNode,m=n.memoizedState;m!==null&&(l=m.retryLane);break;case 19:u=n.stateNode;break;case 22:u=n.stateNode._retryCache;break;default:throw Error(s(314))}u!==null&&u.delete(r),c_(n,l)}function bw(n,r){return xt(n,r)}var Oc=null,Za=null,yd=!1,zc=!1,Sd=!1,Es=0;function Cr(n){n!==Za&&n.next===null&&(Za===null?Oc=Za=n:Za=Za.next=n),zc=!0,yd||(yd=!0,yw())}function Zl(n,r){if(!Sd&&zc){Sd=!0;do for(var l=!1,u=Oc;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var y=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-Ze(42|n)+1)-1,g&=m&~(y&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,f_(u,g))}else g=_t,g=ht(u,u===Ft?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||dt(u,g)||(l=!0,f_(u,g));u=u.next}while(l);Sd=!1}}function vw(){u_()}function u_(){zc=yd=!1;var n=0;Es!==0&&Rw()&&(n=Es);for(var r=wt(),l=null,u=Oc;u!==null;){var m=u.next,g=h_(u,r);g===0?(u.next=null,l===null?Oc=m:l.next=m,m===null&&(Za=l)):(l=u,(n!==0||(g&3)!==0)&&(zc=!0)),u=m}ji!==0&&ji!==5||Zl(n),Es!==0&&(Es=0)}function h_(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0k)break;var ue=B.transferSize,pe=B.initiatorType;ue&&y_(pe)&&(B=B.responseEnd,y+=ue*(B"u"?null:document;function M_(n,r,l){var u=Qa;if(u&&typeof r=="string"&&r){var m=gi(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),D_.has(m)||(D_.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),Zi(r,"link",n),Rt(r),u.head.appendChild(r)))}}function Hw(n){Zr.D(n),M_("dns-prefetch",n,null)}function Uw(n,r){Zr.C(n,r),M_("preconnect",n,r)}function $w(n,r,l){Zr.L(n,r,l);var u=Qa;if(u&&n&&r){var m='link[rel="preload"][as="'+gi(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+gi(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+gi(l.imageSizes)+'"]')):m+='[href="'+gi(n)+'"]';var g=m;switch(r){case"style":g=Ja(n);break;case"script":g=el(n)}er.has(g)||(n=x({rel:"preload",href:r==="image"&&l&&l.imageSrcSet?void 0:n,as:r},l),er.set(g,n),u.querySelector(m)!==null||r==="style"&&u.querySelector(to(g))||r==="script"&&u.querySelector(io(g))||(r=u.createElement("link"),Zi(r,"link",n),Rt(r),u.head.appendChild(r)))}}function Fw(n,r){Zr.m(n,r);var l=Qa;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+gi(u)+'"][href="'+gi(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=el(n)}if(!er.has(g)&&(n=x({rel:"modulepreload",href:n},r),er.set(g,n),l.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(io(g)))return}u=l.createElement("link"),Zi(u,"link",n),Rt(u),l.head.appendChild(u)}}}function qw(n,r,l){Zr.S(n,r,l);var u=Qa;if(u&&n){var m=Gt(u).hoistableStyles,g=Ja(n);r=r||"default";var y=m.get(g);if(!y){var k={loading:0,preload:null};if(y=u.querySelector(to(g)))k.loading=5;else{n=x({rel:"stylesheet",href:n,"data-precedence":r},l),(l=er.get(g))&&Pd(n,l);var B=y=u.createElement("link");Rt(B),Zi(B,"link",n),B._p=new Promise(function(J,ue){B.onload=J,B.onerror=ue}),B.addEventListener("load",function(){k.loading|=1}),B.addEventListener("error",function(){k.loading|=2}),k.loading|=4,$c(y,r,u)}y={type:"stylesheet",instance:y,count:1,state:k},m.set(g,y)}}}function Ww(n,r){Zr.X(n,r);var l=Qa;if(l&&n){var u=Gt(l).hoistableScripts,m=el(n),g=u.get(m);g||(g=l.querySelector(io(m)),g||(n=x({src:n,async:!0},r),(r=er.get(m))&&Id(n,r),g=l.createElement("script"),Rt(g),Zi(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function Gw(n,r){Zr.M(n,r);var l=Qa;if(l&&n){var u=Gt(l).hoistableScripts,m=el(n),g=u.get(m);g||(g=l.querySelector(io(m)),g||(n=x({src:n,async:!0,type:"module"},r),(r=er.get(m))&&Id(n,r),g=l.createElement("script"),Rt(g),Zi(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function B_(n,r,l,u){var m=(m=ae.current)?Uc(m):null;if(!m)throw Error(s(446));switch(n){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(r=Ja(l.href),l=Gt(m).hoistableStyles,u=l.get(r),u||(u={type:"style",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){n=Ja(l.href);var g=Gt(m).hoistableStyles,y=g.get(n);if(y||(m=m.ownerDocument||m,y={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,y),(g=m.querySelector(to(n)))&&!g._p&&(y.instance=g,y.state.loading=5),er.has(n)||(l={rel:"preload",as:"style",href:l.href,crossOrigin:l.crossOrigin,integrity:l.integrity,media:l.media,hrefLang:l.hrefLang,referrerPolicy:l.referrerPolicy},er.set(n,l),g||Yw(m,n,l,y.state))),r&&u===null)throw Error(s(528,""));return y}if(r&&u!==null)throw Error(s(529,""));return null;case"script":return r=l.async,l=l.src,typeof l=="string"&&r&&typeof r!="function"&&typeof r!="symbol"?(r=el(l),l=Gt(m).hoistableScripts,u=l.get(r),u||(u={type:"script",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,n))}}function Ja(n){return'href="'+gi(n)+'"'}function to(n){return'link[rel="stylesheet"]['+n+"]"}function L_(n){return x({},n,{"data-precedence":n.precedence,precedence:null})}function Yw(n,r,l,u){n.querySelector('link[rel="preload"][as="style"]['+r+"]")?u.loading=1:(r=n.createElement("link"),u.preload=r,r.addEventListener("load",function(){return u.loading|=1}),r.addEventListener("error",function(){return u.loading|=2}),Zi(r,"link",l),Rt(r),n.head.appendChild(r))}function el(n){return'[src="'+gi(n)+'"]'}function io(n){return"script[async]"+n}function O_(n,r,l){if(r.count++,r.instance===null)switch(r.type){case"style":var u=n.querySelector('style[data-href~="'+gi(l.href)+'"]');if(u)return r.instance=u,Rt(u),u;var m=x({},l,{"data-href":l.href,"data-precedence":l.precedence,href:null,precedence:null});return u=(n.ownerDocument||n).createElement("style"),Rt(u),Zi(u,"style",m),$c(u,l.precedence,n),r.instance=u;case"stylesheet":m=Ja(l.href);var g=n.querySelector(to(m));if(g)return r.state.loading|=4,r.instance=g,Rt(g),g;u=L_(l),(m=er.get(m))&&Pd(u,m),g=(n.ownerDocument||n).createElement("link"),Rt(g);var y=g;return y._p=new Promise(function(k,B){y.onload=k,y.onerror=B}),Zi(g,"link",u),r.state.loading|=4,$c(g,l.precedence,n),r.instance=g;case"script":return g=el(l.src),(m=n.querySelector(io(g)))?(r.instance=m,Rt(m),m):(u=l,(m=er.get(g))&&(u=x({},l),Id(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),Rt(m),Zi(m,"link",u),n.head.appendChild(m),r.instance=m);case"void":return null;default:throw Error(s(443,r.type))}else r.type==="stylesheet"&&(r.state.loading&4)===0&&(u=r.instance,r.state.loading|=4,$c(u,l.precedence,n));return r.instance}function $c(n,r,l){for(var u=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=u.length?u[u.length-1]:null,g=m,y=0;y title"):null)}function Kw(n,r,l){if(l===1||r.itemProp!=null)return!1;switch(n){case"meta":case"title":return!0;case"style":if(typeof r.precedence!="string"||typeof r.href!="string"||r.href==="")break;return!0;case"link":if(typeof r.rel!="string"||typeof r.href!="string"||r.href===""||r.onLoad||r.onError)break;switch(r.rel){case"stylesheet":return n=r.disabled,typeof r.precedence=="string"&&n==null;default:return!0}case"script":if(r.async&&typeof r.async!="function"&&typeof r.async!="symbol"&&!r.onLoad&&!r.onError&&r.src&&typeof r.src=="string")return!0}return!1}function I_(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function Vw(n,r,l,u){if(l.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var m=Ja(u.href),g=r.querySelector(to(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=qc.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,Rt(g);return}g=r.ownerDocument||r,u=L_(u),(m=er.get(m))&&Pd(u,m),g=g.createElement("link"),Rt(g);var y=g;y._p=new Promise(function(k,B){y.onload=k,y.onerror=B}),Zi(g,"link",u),l.instance=g}n.stylesheets===null&&(n.stylesheets=new Map),n.stylesheets.set(l,r),(r=l.state.preload)&&(l.state.loading&3)===0&&(n.count++,l=qc.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var Hd=0;function Xw(n,r){return n.stylesheets&&n.count===0&&Gc(n,n.stylesheets),0Hd?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function qc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Gc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Wc=null;function Gc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Wc=new Map,r.forEach(Zw,n),Wc=null,qc.call(n))}function Zw(n,r){if(!(r.state.loading&4)){var l=Wc.get(n);if(l)var u=l.get(null);else{l=new Map,Wc.set(n,l);for(var m=n.querySelectorAll("link[data-precedence],style[data-precedence]"),g=0;g"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Vd.exports=pC(),Vd.exports}var gC=mC();const xC=zu(gC);function _C({onLogin:e}){const[t,i]=w.useState(""),[s,a]=w.useState(null),[o,c]=w.useState(!1),h=async p=>{if(p.preventDefault(),!t.trim())return;c(!0),a(null);const f=await e(t);f&&a(f),c(!1)};return d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsxs("div",{className:"w-full max-w-sm",children:[d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"local writer agent"})]}),d.jsxs("form",{onSubmit:h,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.jsx("input",{type:"password",value:t,onChange:p=>i(p.target.value),placeholder:"enter your passphrase",autoFocus:!0,className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),s&&d.jsx("p",{className:"text-error text-xs",children:s}),d.jsx("button",{type:"submit",disabled:o||!t.trim(),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:o?"authenticating...":"unlock"})]})]}),d.jsx("p",{className:"text-muted mt-4 text-center text-[10px]",children:"enter your passphrase to unlock"})]})})}function bC({onSetup:e}){const[t,i]=w.useState(""),[s,a]=w.useState(""),[o,c]=w.useState(null),[h,p]=w.useState(!1),f=async _=>{if(_.preventDefault(),!t.trim()||t.length<4){c("Passphrase must be at least 4 characters");return}if(t!==s){c("Passphrases do not match");return}p(!0),c(null);const x=await e(t);x&&c(x),p(!1)};return d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsx("div",{className:"w-full max-w-sm",children:d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"first-time setup"})]}),d.jsx("p",{className:"text-muted mb-4 text-xs leading-relaxed",children:"Choose a passphrase to protect your local writer agent. This will be used to unlock the app and secure your OWS wallet."}),d.jsxs("form",{onSubmit:f,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.jsx("input",{type:"password",value:t,onChange:_=>i(_.target.value),placeholder:"choose a passphrase",autoFocus:!0,className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Confirm"}),d.jsx("input",{type:"password",value:s,onChange:_=>a(_.target.value),placeholder:"repeat passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),o&&d.jsx("p",{className:"text-error text-xs",children:o}),d.jsx("button",{type:"submit",disabled:h||!t.trim()||!s.trim(),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:h?"setting up...":"create passphrase"})]})]})})})}const Jd="http://localhost:7777";function jy({token:e}){const[t,i]=w.useState(null),[s,a]=w.useState(!1),[o,c]=w.useState(null),[h,p]=w.useState(!1),[f,_]=w.useState(null),x=w.useCallback((E,N)=>fetch(E,{...N,headers:{...N==null?void 0:N.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{x(`${Jd}/api/wallet`).then(E=>E.json()).then(E=>i(E)).catch(()=>i({exists:!1,error:"Failed to load wallet"}))},[x]);w.useEffect(()=>{b()},[b]);const v=async()=>{a(!0),_(null);try{const E=await x(`${Jd}/api/wallet/create`,{method:"POST"}),N=await E.json();if(!E.ok)throw new Error(N.error||"Creation failed");b()}catch(E){_(E instanceof Error?E.message:"Failed to create wallet")}a(!1)},S=async E=>{c(E.walletId||E.name),_(null);try{const N=await x(`${Jd}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:E.walletId,name:E.name,address:E.normalizedAddress||E.address})}),I=await N.json();if(!N.ok)throw new Error(I.error||"Wallet switch failed");b()}catch(N){_(N instanceof Error?N.message:"Failed to switch wallet")}c(null)},j=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},R=E=>`${E.slice(0,6)}...${E.slice(-4)}`;return d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"OWS Wallet"}),!t&&d.jsx("p",{className:"text-muted text-xs",children:"loading..."}),t&&!t.exists&&d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:t.error||"No wallet created yet. Create one to enable autonomous transactions."}),f&&d.jsx("p",{className:"text-error text-xs",children:f}),d.jsx("button",{onClick:v,disabled:s,className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 rounded border px-4 py-2 text-xs font-medium transition-colors",children:s?"creating...":"create wallet"})]}),(t==null?void 0:t.selectionRequired)&&t.wallets&&t.wallets.length>0&&d.jsxs("div",{className:"mb-4 space-y-3 rounded border border-amber-600/30 bg-amber-950/10 p-3",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Multiple OWS wallets found. Select the wallet OWS should use for publishing and signing."}),t.wallets.map(E=>d.jsxs("div",{className:"border-border flex items-center justify-between gap-3 rounded border p-2",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsx("p",{className:"text-foreground truncate text-xs font-medium",children:E.name}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),d.jsx("button",{onClick:()=>S(E),disabled:!E.address||o===(E.walletId||E.name),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 rounded border px-2 py-1 text-[10px] font-medium transition-colors",children:o===(E.walletId||E.name)?"switching...":"use"})]},E.walletId||E.name)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),t&&t.exists&&t.address&&d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:"Active Wallet (Base)"}),d.jsx("span",{className:`rounded border px-1.5 py-0.5 text-[9px] ${t.ethBalance&&parseFloat(t.ethBalance)>0?"border-accent/30 text-accent":"border-accent-dim/30 text-accent-dim"}`,children:t.ethBalance&&parseFloat(t.ethBalance)>0?"active":"no balance"})]}),t.name&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Name"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.name})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("code",{className:"text-foreground bg-surface rounded px-2 py-1 text-xs font-mono",children:R(t.address)}),d.jsx("button",{onClick:j,className:"text-muted hover:text-accent text-xs transition-colors",children:h?"copied":"copy"})]}),d.jsxs("div",{className:"border-border space-y-1 border-t pt-3",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.ethBalance||"0.000000"," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC"}),d.jsxs("span",{className:"text-foreground font-medium",children:["$",t.usdcBalance||"0.00"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"PLOT"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.plotBalance||"0.0000"," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Network"}),d.jsx("span",{className:"text-foreground",children:"Base"})]})]}),t.wallets&&t.wallets.length>1&&d.jsxs("div",{className:"border-border space-y-2 border-t pt-3",children:[d.jsx("p",{className:"text-muted text-[10px] font-medium uppercase tracking-wider",children:"Switch Wallet"}),t.wallets.map(E=>d.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("p",{className:E.active?"text-accent truncate font-medium":"text-foreground truncate",children:[E.name,E.active?" (active)":""]}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),!E.active&&d.jsx("button",{onClick:()=>S(E),disabled:!E.address||o===(E.walletId||E.name),className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 rounded border px-2 py-1 text-[10px] transition-colors",children:o===(E.walletId||E.name)?"...":"use"})]},E.walletId||E.name)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),d.jsxs("div",{className:"border-border border-t pt-3",children:[d.jsx("p",{className:"text-muted mb-2 text-[10px] font-medium uppercase tracking-wider",children:"Fund Wallet"}),d.jsx("p",{className:"text-muted text-[10px]",children:"Send ETH on Base for gas (~$0.01 per publish):"}),d.jsx("code",{className:"text-foreground bg-surface mt-1 block break-all rounded px-2 py-1.5 text-[10px] font-mono",children:t.address})]})]}),(t==null?void 0:t.exists)&&d.jsx("button",{onClick:v,disabled:s,className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 mt-4 rounded border px-3 py-1.5 text-[10px] font-medium transition-colors",children:s?"creating...":"create another wallet"})]})}function Eu(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const Up="Codex is installed but its capabilities couldn't be read — you may need to log in to Codex (resolve outside OWS), then re-check.";function vC({token:e,onLogout:t}){const[i,s]=w.useState(""),[a,o]=w.useState(""),[c,h]=w.useState(null),[p,f]=w.useState(!1),[_,x]=w.useState(!1),[b,v]=w.useState(null),[S,j]=w.useState("AI Writer"),[R,E]=w.useState(""),[N,I]=w.useState(""),[te,F]=w.useState(!1),[D,ie]=w.useState(null),[fe,Se]=w.useState(""),[H,ce]=w.useState(null),[W,K]=w.useState(!1),[X,U]=w.useState(null),[A,O]=w.useState(null),[$,xe]=w.useState(null),T=w.useCallback((ne,ae)=>fetch(ne,{...ae,headers:{...ae==null?void 0:ae.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]);w.useEffect(()=>{T("/api/settings/link-status").then(ne=>ne.json()).then(ne=>v(ne)).catch(()=>v({linked:!1}))},[]),w.useEffect(()=>{T("/api/agent/readiness").then(ne=>ne.ok?ne.json():null).then(ne=>{ne&&xe(ne)}).catch(()=>{})},[]);const M=async()=>{if(!S.trim()){ie("Agent name is required");return}if(!R.trim()){ie("Description is required");return}F(!0),ie(null);try{const ne=await T("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:S,description:R,...N.trim()&&{genre:N}})}),ae=await ne.json();if(!ne.ok)throw new Error(ae.error||"Registration failed");v({linked:!0,agentId:ae.agentId,owsWallet:ae.owsWallet,txHash:ae.txHash})}catch(ne){ie(ne instanceof Error?ne.message:"Registration failed")}F(!1)},G=async()=>{if(!fe.trim()||!/^0x[a-fA-F0-9]{40}$/.test(fe)){U("Enter a valid wallet address (0x...)");return}K(!0),U(null),ce(null);try{const ne=await T("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:fe})}),ae=await ne.json();if(!ne.ok)throw new Error(ae.error||"Failed to generate binding code");ce(ae)}catch(ne){U(ne instanceof Error?ne.message:"Failed to generate binding code")}K(!1)},C=async(ne,ae)=>{await navigator.clipboard.writeText(ne),O(ae),setTimeout(()=>O(null),2e3)},V=async()=>{if(h(null),f(!1),!i||i.length<4){h("Passphrase must be at least 4 characters");return}if(i!==a){h("Passphrases do not match");return}x(!0);try{const ne=await T("/api/auth/reset-passphrase",{method:"POST",body:JSON.stringify({passphrase:i})});if(!ne.ok){const ae=await ne.json();throw new Error(ae.error||"Reset failed")}f(!0),s(""),o(""),setTimeout(()=>f(!1),3e3)}catch(ne){h(ne instanceof Error?ne.message:"Reset failed")}x(!1)};return d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Settings"}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Identity"}),b!=null&&b.linked?d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-sm font-medium text-accent",children:"Registered"}),d.jsxs("span",{className:"text-muted text-xs",children:["Agent #",b.agentId]})]}),b.owsWallet&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Wallet: ",b.owsWallet.slice(0,6),"...",b.owsWallet.slice(-4)]}),b.owner&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Owner: ",b.owner.slice(0,6),"...",b.owner.slice(-4)]}),b.txHash&&d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://basescan.org/tx/${b.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View transaction on BaseScan"})}),d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://plotlink.xyz/profile/${b.owsWallet}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View agent profile on plotlink.xyz"})})]}):d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:"Register this AI writer on-chain via ERC-8004. Uses your OWS wallet's existing ETH balance for gas."}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Name"}),d.jsx("input",{value:S,onChange:ne=>j(ne.target.value),placeholder:"AI Writer",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Description"}),d.jsx("input",{value:R,onChange:ne=>E(ne.target.value),placeholder:"An AI writing assistant for fiction stories",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Genre (optional)"}),d.jsx("input",{value:N,onChange:ne=>I(ne.target.value),placeholder:"e.g. Fiction, Sci-Fi, Fantasy",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),D&&d.jsx("p",{className:"text-error text-xs",children:D}),d.jsx("button",{onClick:M,disabled:te||!S.trim()||!R.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:te?"Registering...":"Register Agent Identity"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4","data-testid":"provider-readiness",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Providers"}),d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Claude"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.claude.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.codex.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex version"}),d.jsx("span",{className:"text-muted text-xs font-mono",children:($==null?void 0:$.codex.version)??"—"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Image generation"}),d.jsx("span",{className:"text-muted text-xs",children:($==null?void 0:$.codex.imageGeneration)??"unknown"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex auth"}),d.jsx("span",{className:"text-muted text-xs","data-testid":"codex-auth-status",children:$!=null&&$.codex.installed?$.codex.auth==="ok"?"ok":"unclear":"—"})]}),Eu($)&&d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:Up}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Last checked"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.checkedAt?new Date($.checkedAt).toLocaleString():"—"})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Link to PlotLink"}),b!=null&&b.owner?d.jsxs("p",{className:"text-muted text-xs",children:["Linked to owner ",d.jsxs("span",{className:"font-mono",children:[b.owner.slice(0,6),"...",b.owner.slice(-4)]})]}):d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:"Link this OWS wallet to your PlotLink account so your stories appear under your profile on plotlink.xyz."}),d.jsxs("div",{className:"text-muted text-xs space-y-1 pl-3",children:[d.jsx("p",{children:"1. Enter your PlotLink wallet address below"}),d.jsx("p",{children:'2. Click "Generate Binding Code"'}),d.jsx("p",{children:"3. Copy the code and paste it on plotlink.xyz → Agents → Link AI Writer"})]}),d.jsx("input",{value:fe,onChange:ne=>Se(ne.target.value),placeholder:"Your PlotLink wallet address (0x...)",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent font-mono"}),X&&d.jsx("p",{className:"text-error text-xs",children:X}),d.jsx("button",{onClick:G,disabled:W||!fe.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:W?"Generating...":"Generate Binding Code"}),H&&d.jsxs("div",{className:"space-y-3 mt-3",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Binding Code (signature)"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:H.signature}),d.jsx("button",{onClick:()=>C(H.signature,"signature"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:A==="signature"?"Copied!":"Copy"})]})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"OWS Wallet Address"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:H.owsWallet}),d.jsx("button",{onClick:()=>C(H.owsWallet,"wallet"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:A==="wallet"?"Copied!":"Copy"})]})]}),H.agentId&&d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Agent ID"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono text-foreground pr-16",children:H.agentId}),d.jsx("button",{onClick:()=>C(String(H.agentId),"agentId"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:A==="agentId"?"Copied!":"Copy"})]})]}),d.jsx("p",{className:"text-xs text-accent",children:'Now go to plotlink.xyz/agents and paste the values in the "Link AI Writer" section.'})]})]})]}),d.jsx(jy,{token:e}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Reset Passphrase"}),d.jsxs("div",{className:"space-y-3",children:[d.jsx("input",{type:"password",value:i,onChange:ne=>s(ne.target.value),placeholder:"new passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"}),d.jsx("input",{type:"password",value:a,onChange:ne=>o(ne.target.value),placeholder:"confirm passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"}),c&&d.jsx("p",{className:"text-error text-xs",children:c}),p&&d.jsx("p",{className:"text-xs text-accent",children:"passphrase updated"}),d.jsx("button",{onClick:V,disabled:_||!i.trim(),className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 w-full rounded border px-4 py-2 text-xs font-medium transition-colors",children:_?"updating...":"update passphrase"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Session"}),d.jsx("button",{onClick:t,className:"border-border text-muted hover:border-error hover:text-error rounded border px-4 py-2 text-xs font-medium transition-colors",children:"logout"})]})]})}const yC="http://localhost:7777";function SC({token:e}){const[t,i]=w.useState(null),s=w.useCallback((h,p)=>fetch(h,{...p,headers:{...p==null?void 0:p.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),a=w.useCallback(()=>{s(`${yC}/api/dashboard`).then(h=>h.json()).then(i)},[s]);w.useEffect(()=>{a()},[a]);const o=h=>`${h.slice(0,6)}...${h.slice(-4)}`,c=h=>{if(!h)return"Unknown date";const p=new Date(h);return isNaN(p.getTime())?"Unknown date":p.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})};return t?d.jsxs("div",{className:"mx-auto max-w-2xl space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Writer Dashboard"}),d.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-accent text-lg font-bold",children:t.stories.totalPublished}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"published"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.pendingFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"pending"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalStories}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"stories"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"files"})]})]}),t.wallet&&d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Wallet"}),d.jsxs("div",{className:"space-y-1.5",children:[t.wallet.name&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Active wallet"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.wallet.name})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Address"}),d.jsx("code",{className:"text-foreground font-mono text-[10px]",children:o(t.wallet.address)})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH Balance"}),d.jsxs("span",{className:"text-foreground",children:[t.wallet.ethFormatted," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC Balance"}),d.jsxs("span",{className:"text-foreground",children:["$",t.wallet.usdcBalance]})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Profit & Loss"}),d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Total costs (gas)"}),d.jsxs("span",{className:"text-error",children:["-",t.pnl.totalCostsEth," ETH (~$",t.pnl.totalCostsUsd,")"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Royalties earned"}),d.jsxs("span",{className:"text-accent",children:["+",t.pnl.totalRoyaltiesPlot," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Unclaimed royalties"}),d.jsxs("span",{className:"text-foreground",children:[t.royalties.unclaimed," PLOT"]})]}),d.jsxs("div",{className:"border-border flex justify-between border-t pt-1.5 text-xs font-medium",children:[d.jsx("span",{className:"text-muted",children:"Net P&L (USD)"}),d.jsxs("span",{className:parseFloat(t.pnl.netPnlUsd)>=0?"text-accent":"text-error",children:[parseFloat(t.pnl.netPnlUsd)>=0?"+":"","$",t.pnl.netPnlUsd]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Stories published"}),d.jsx("span",{className:"text-foreground",children:t.costs.storiesPublished})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Published Stories"}),t.stories.published.length===0?d.jsx("p",{className:"text-muted text-xs",children:"no published stories yet"}):d.jsx("div",{className:"space-y-3",children:t.stories.published.map(h=>d.jsxs("div",{className:"bg-surface rounded border border-border p-4",children:[d.jsxs("div",{className:"flex items-start justify-between",children:[d.jsxs("div",{children:[h.genre&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-2 py-0.5 text-[10px] font-medium",children:h.genre}),d.jsx("h4",{className:"text-foreground mt-1 text-sm font-serif font-medium",children:h.title}),d.jsx("p",{className:"text-muted mt-0.5 text-[10px] font-mono",children:h.storyName})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[h.hasNotIndexed&&d.jsx("span",{className:"rounded border border-amber-600/30 px-1.5 py-0.5 text-[9px] text-amber-700",children:"not indexed"}),d.jsxs("span",{className:"rounded border border-green-700/30 px-1.5 py-0.5 text-[9px] text-green-700",children:[h.publishedFiles," published"]})]})]}),d.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-center",children:[d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.plotCount}),d.jsx("div",{className:"text-muted text-[9px]",children:"Plots"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium font-mono",children:h.storylineId?`#${h.storylineId}`:"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Storyline"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.totalGasCostEth??"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Gas (ETH)"})]})]}),d.jsx("div",{className:"mt-2 space-y-1",children:h.files.map(p=>d.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:p.status==="published-not-indexed"?"text-amber-700":"text-green-700",children:p.status==="published-not-indexed"?"⚠":"✓"}),d.jsx("span",{className:"text-muted font-mono",children:p.file})]}),p.txHash&&d.jsxs("a",{href:`https://basescan.org/tx/${p.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted hover:text-accent font-mono",children:["tx:",p.txHash.slice(0,8),"..."]})]},p.file))}),d.jsxs("div",{className:"mt-2 flex items-center justify-between text-[10px]",children:[d.jsx("span",{className:"text-muted",children:c(h.latestPublishedAt)}),h.storylineId&&d.jsx("a",{href:`https://plotlink.xyz/story/${h.storylineId}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"})]})]},h.id))})]}),t.stories.pendingFiles>0&&d.jsx("div",{className:"border-border rounded border p-4",children:d.jsxs("p",{className:"text-muted text-xs",children:[t.stories.pendingFiles," file(s) pending publish — go to Stories to publish them."]})})]}):d.jsx("div",{className:"flex h-full items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"loading dashboard..."})})}const wC={published:"✓","published-not-indexed":"⚠",pending:"⏳",draft:"📝"},CC={published:"text-green-700","published-not-indexed":"text-amber-700",pending:"text-amber-700",draft:"text-muted"};function kC({authFetch:e,selectedStory:t,selectedFile:i,onSelectFile:s,onNewStory:a,untitledSessions:o=[]}){const[c,h]=w.useState([]),[p,f]=w.useState([]),[_,x]=w.useState(new Set),[b,v]=w.useState(!1),S=w.useCallback(async()=>{try{const F=await e("/api/stories");if(F.ok){const D=await F.json();h(D.stories)}}catch{}},[e]),j=w.useCallback(async()=>{try{const F=await e("/api/stories/archived");if(F.ok){const D=await F.json();f(D.stories)}}catch{}},[e]),R=w.useCallback(async F=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:F})})).ok&&(j(),S())}catch{}},[e,j,S]);w.useEffect(()=>{S();const F=setInterval(S,5e3);return()=>clearInterval(F)},[S]),w.useEffect(()=>{b&&j()},[b,j]),w.useEffect(()=>{t&&x(F=>new Set(F).add(t))},[t]);const E=F=>{x(D=>{const ie=new Set(D);return ie.has(F)?ie.delete(F):ie.add(F),ie})},N=F=>{var ie;const D=F.map(fe=>{var Se;return{file:fe.file,num:(Se=fe.file.match(/^plot-(\d+)\.md$/))==null?void 0:Se[1]}}).filter(fe=>fe.num!=null).sort((fe,Se)=>parseInt(Se.num)-parseInt(fe.num));return D.length>0?D[0].file:F.some(fe=>fe.file==="genesis.md")?"genesis.md":F.some(fe=>fe.file==="structure.md")?"structure.md":((ie=F[0])==null?void 0:ie.file)??null},I=F=>{if(E(F.name),F.contentType==="cartoon")s(F.name,"");else{const D=N(F.files);D&&s(F.name,D)}},te=F=>{const D=ie=>{if(ie==="structure.md")return 0;if(ie==="genesis.md")return 1;const fe=ie.match(/^plot-(\d+)\.md$/);return fe?2+parseInt(fe[1]):100};return[...F].sort((ie,fe)=>D(ie.file)-D(fe.file))};return b?d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Archives"}),d.jsx("span",{className:"text-xs text-muted",children:p.length})]}),d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.jsxs("button",{onClick:()=>v(!1),className:"w-full px-3 py-1.5 text-sm text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1.5",children:[d.jsx("span",{children:"←"}),d.jsx("span",{children:"Back"})]})}),d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:p.length===0?d.jsx("div",{className:"p-3 text-sm text-muted",children:d.jsx("p",{children:"No archived stories."})}):p.map(F=>d.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-surface",children:[d.jsx("span",{className:"text-sm font-medium truncate",title:F.name,children:F.title||F.name}),d.jsx("button",{onClick:()=>R(F.name),className:"text-xs text-accent hover:text-accent-dim flex-shrink-0 ml-2",children:"Restore"})]},F.name))})]}):d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Stories"}),d.jsx("span",{className:"text-xs text-muted",children:c.length})]}),a&&d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.jsxs("button",{onClick:a,className:"w-full px-3 py-1.5 text-sm bg-accent text-white rounded hover:bg-accent-dim flex items-center justify-center gap-1.5",children:[d.jsx("span",{children:"+"}),d.jsx("span",{children:"New Story"})]})}),d.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[o.map(F=>d.jsx("div",{children:d.jsxs("button",{onClick:()=>s(F,""),className:`w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm ${t===F?"bg-surface":""}`,children:[d.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-600 flex-shrink-0"}),d.jsx("span",{className:"font-medium italic text-muted",children:"Untitled"})]})},F)),c.length===0&&o.length===0?d.jsxs("div",{className:"p-3 text-sm text-muted",children:[d.jsx("p",{children:"No stories yet."}),d.jsx("p",{className:"mt-1 text-xs",children:'Click "+ New Story" above to start writing.'})]}):c.filter(F=>F.name!=="_example").map(F=>d.jsxs("div",{children:[d.jsxs("button",{onClick:()=>I(F),className:"w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm",children:[d.jsx("span",{className:"text-xs text-muted",children:_.has(F.name)?"▼":"▶"}),d.jsx("span",{className:"font-medium truncate",title:F.name,children:F.title||F.name}),F.contentType==="cartoon"&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-1.5 py-0.5 text-[10px] font-medium flex-shrink-0",children:"Cartoon"}),d.jsxs("span",{className:"ml-auto flex-shrink-0 text-xs text-muted",children:[F.publishedCount,"/",F.files.length]})]}),_.has(F.name)&&d.jsx("div",{className:"pl-4",children:te(F.files).map(D=>{const ie=t===F.name&&i===D.file;return d.jsxs("button",{onClick:()=>s(F.name,D.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${ie?"bg-surface font-medium":""}`,children:[d.jsx("span",{className:CC[D.status],children:wC[D.status]}),d.jsx("span",{className:"truncate font-mono",children:D.file})]},D.file)})})]},F.name))]}),d.jsx("div",{className:"px-3 py-2 border-t border-border",children:d.jsx("button",{onClick:()=>v(!0),className:"w-full px-3 py-1.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded flex items-center justify-center gap-1.5",children:d.jsx("span",{children:"Archives"})})})]})}/** +`+u.stack}}var ze=Object.prototype.hasOwnProperty,_t=e.unstable_scheduleCallback,Te=e.unstable_cancelCallback,Kt=e.unstable_shouldYield,mi=e.unstable_requestPaint,wt=e.unstable_now,et=e.unstable_getCurrentPriorityLevel,Q=e.unstable_ImmediatePriority,xe=e.unstable_UserBlockingPriority,je=e.unstable_NormalPriority,$e=e.unstable_LowPriority,nt=e.unstable_IdlePriority,Wt=e.log,ui=e.unstable_setDisableYieldValue,Bt=null,yt=null;function Rt(n){if(typeof Wt=="function"&&ui(n),yt&&typeof yt.setStrictMode=="function")try{yt.setStrictMode(Bt,n)}catch{}}var Qe=Math.clz32?Math.clz32:Se,hi=Math.log,H=Math.LN2;function Se(n){return n>>>=0,n===0?32:31-(hi(n)/H|0)|0}var Oe=256,Ae=262144,Ge=4194304;function Fe(n){var r=n&42;if(r!==0)return r;switch(n&-n){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return n&261888;case 262144:case 524288:case 1048576:case 2097152:return n&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return n&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return n}}function dt(n,r,l){var u=n.pendingLanes;if(u===0)return 0;var m=0,g=n.suspendedLanes,y=n.pingedLanes;n=n.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?m=Fe(u):(y&=k,y!==0?m=Fe(y):l||(l=k&~n,l!==0&&(m=Fe(l))))):(k=u&~g,k!==0?m=Fe(k):y!==0?m=Fe(y):l||(l=u&~n,l!==0&&(m=Fe(l)))),m===0?0:r!==0&&r!==m&&(r&g)===0&&(g=m&-m,l=r&-r,g>=l||g===32&&(l&4194048)!==0)?r:m}function ft(n,r){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&r)===0}function ct(n,r){switch(n){case 1:case 2:case 4:case 8:case 64:return r+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return r+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Vt(){var n=Ge;return Ge<<=1,(Ge&62914560)===0&&(Ge=4194304),n}function Ci(n){for(var r=[],l=0;31>l;l++)r.push(n);return r}function pt(n,r){n.pendingLanes|=r,r!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function Fi(n,r,l,u,m,g){var y=n.pendingLanes;n.pendingLanes=l,n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0,n.expiredLanes&=l,n.entangledLanes&=l,n.errorRecoveryDisabledLanes&=l,n.shellSuspendCounter=0;var k=n.entanglements,L=n.expirationTimes,J=n.hiddenUpdates;for(l=y&~l;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var Ei=/[\n"\\]/g;function gi(n){return n.replace(Ei,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function Gi(n,r,l,u,m,g,y,k){n.name="",y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"?n.type=y:n.removeAttribute("type"),r!=null?y==="number"?(r===0&&n.value===""||n.value!=r)&&(n.value=""+Ct(r)):n.value!==""+Ct(r)&&(n.value=""+Ct(r)):y!=="submit"&&y!=="reset"||n.removeAttribute("value"),r!=null?Or(n,y,Ct(r)):l!=null?Or(n,y,Ct(l)):u!=null&&n.removeAttribute("value"),m==null&&g!=null&&(n.defaultChecked=!!g),m!=null&&(n.checked=m&&typeof m!="function"&&typeof m!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?n.name=""+Ct(k):n.removeAttribute("name")}function jn(n,r,l,u,m,g,y,k){if(g!=null&&typeof g!="function"&&typeof g!="symbol"&&typeof g!="boolean"&&(n.type=g),r!=null||l!=null){if(!(g!=="submit"&&g!=="reset"||r!=null)){Lr(n);return}l=l!=null?""+Ct(l):"",r=r!=null?""+Ct(r):l,k||r===n.value||(n.value=r),n.defaultValue=r}u=u??m,u=typeof u!="function"&&typeof u!="symbol"&&!!u,n.checked=k?n.checked:!!u,n.defaultChecked=!!u,y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(n.name=y),Lr(n)}function Or(n,r,l){r==="number"&&xr(n.ownerDocument)===n||n.defaultValue===""+l||(n.defaultValue=""+l)}function Tn(n,r,l,u){if(n=n.options,r){r={};for(var m=0;m"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),re=!1;if(Wn)try{var ye={};Object.defineProperty(ye,"passive",{get:function(){re=!0}}),window.addEventListener("test",ye,ye),window.removeEventListener("test",ye,ye)}catch{re=!1}var Ce=null,tt=null,Pt=null;function Ni(){if(Pt)return Pt;var n,r=tt,l=r.length,u,m="value"in Ce?Ce.value:Ce.textContent,g=m.length;for(n=0;n=Cl),Rm=" ",Dm=!1;function Mm(n,r){switch(n){case"keyup":return L1.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Bm(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Na=!1;function z1(n,r){switch(n){case"compositionend":return Bm(r);case"keypress":return r.which!==32?null:(Dm=!0,Rm);case"textInput":return n=r.data,n===Rm&&Dm?null:n;default:return null}}function P1(n,r){if(Na)return n==="compositionend"||!eh&&Mm(n,r)?(n=Ni(),Pt=tt=Ce=null,Na=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(r.ctrlKey||r.altKey||r.metaKey)||r.ctrlKey&&r.altKey){if(r.char&&1=r)return{node:l,offset:r-n};n=u}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=$m(l)}}function qm(n,r){return n&&r?n===r?!0:n&&n.nodeType===3?!1:r&&r.nodeType===3?qm(n,r.parentNode):"contains"in n?n.contains(r):n.compareDocumentPosition?!!(n.compareDocumentPosition(r)&16):!1:!1}function Wm(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var r=xr(n.document);r instanceof n.HTMLIFrameElement;){try{var l=typeof r.contentWindow.location.href=="string"}catch{l=!1}if(l)n=r.contentWindow;else break;r=xr(n.document)}return r}function nh(n){var r=n&&n.nodeName&&n.nodeName.toLowerCase();return r&&(r==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||r==="textarea"||n.contentEditable==="true")}var G1=Wn&&"documentMode"in document&&11>=document.documentMode,ja=null,rh=null,jl=null,sh=!1;function Gm(n,r,l){var u=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;sh||ja==null||ja!==xr(u)||(u=ja,"selectionStart"in u&&nh(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),jl&&Nl(jl,u)||(jl=u,u=Uc(rh,"onSelect"),0>=y,m-=y,yr=1<<32-Qe(r)+m|l<lt?(vt=Ie,Ie=null):vt=Ie.sibling;var At=ee(W,Ie,Z[lt],de);if(At===null){Ie===null&&(Ie=vt);break}n&&Ie&&At.alternate===null&&r(W,Ie),P=g(At,P,lt),Tt===null?qe=At:Tt.sibling=At,Tt=At,Ie=vt}if(lt===Z.length)return l(W,Ie),St&&Pr(W,lt),qe;if(Ie===null){for(;ltlt?(vt=Ie,Ie=null):vt=Ie.sibling;var Ds=ee(W,Ie,At.value,de);if(Ds===null){Ie===null&&(Ie=vt);break}n&&Ie&&Ds.alternate===null&&r(W,Ie),P=g(Ds,P,lt),Tt===null?qe=Ds:Tt.sibling=Ds,Tt=Ds,Ie=vt}if(At.done)return l(W,Ie),St&&Pr(W,lt),qe;if(Ie===null){for(;!At.done;lt++,At=Z.next())At=pe(W,At.value,de),At!==null&&(P=g(At,P,lt),Tt===null?qe=At:Tt.sibling=At,Tt=At);return St&&Pr(W,lt),qe}for(Ie=u(Ie);!At.done;lt++,At=Z.next())At=ae(Ie,W,lt,At.value,de),At!==null&&(n&&At.alternate!==null&&Ie.delete(At.key===null?lt:At.key),P=g(At,P,lt),Tt===null?qe=At:Tt.sibling=At,Tt=At);return n&&Ie.forEach(function(dC){return r(W,dC)}),St&&Pr(W,lt),qe}function Ut(W,P,Z,de){if(typeof Z=="object"&&Z!==null&&Z.type===j&&Z.key===null&&(Z=Z.props.children),typeof Z=="object"&&Z!==null){switch(Z.$$typeof){case v:e:{for(var qe=Z.key;P!==null;){if(P.key===qe){if(qe=Z.type,qe===j){if(P.tag===7){l(W,P.sibling),de=m(P,Z.props.children),de.return=W,W=de;break e}}else if(P.elementType===qe||typeof qe=="object"&&qe!==null&&qe.$$typeof===fe&&ta(qe)===P.type){l(W,P.sibling),de=m(P,Z.props),Bl(de,Z),de.return=W,W=de;break e}l(W,P);break}else r(W,P);P=P.sibling}Z.type===j?(de=Xs(Z.props.children,W.mode,de,Z.key),de.return=W,W=de):(de=rc(Z.type,Z.key,Z.props,null,W.mode,de),Bl(de,Z),de.return=W,W=de)}return y(W);case S:e:{for(qe=Z.key;P!==null;){if(P.key===qe)if(P.tag===4&&P.stateNode.containerInfo===Z.containerInfo&&P.stateNode.implementation===Z.implementation){l(W,P.sibling),de=m(P,Z.children||[]),de.return=W,W=de;break e}else{l(W,P);break}else r(W,P);P=P.sibling}de=dh(Z,W.mode,de),de.return=W,W=de}return y(W);case fe:return Z=ta(Z),Ut(W,P,Z,de)}if(U(Z))return Be(W,P,Z,de);if(F(Z)){if(qe=F(Z),typeof qe!="function")throw Error(s(150));return Z=qe.call(Z),Ke(W,P,Z,de)}if(typeof Z.then=="function")return Ut(W,P,hc(Z),de);if(Z.$$typeof===I)return Ut(W,P,lc(W,Z),de);dc(W,Z)}return typeof Z=="string"&&Z!==""||typeof Z=="number"||typeof Z=="bigint"?(Z=""+Z,P!==null&&P.tag===6?(l(W,P.sibling),de=m(P,Z),de.return=W,W=de):(l(W,P),de=hh(Z,W.mode,de),de.return=W,W=de),y(W)):l(W,P)}return function(W,P,Z,de){try{Ml=0;var qe=Ut(W,P,Z,de);return Ia=null,qe}catch(Ie){if(Ie===Pa||Ie===cc)throw Ie;var Tt=Rn(29,Ie,null,W.mode);return Tt.lanes=de,Tt.return=W,Tt}finally{}}}var na=mg(!0),gg=mg(!1),ms=!1;function Ch(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function kh(n,r){n=n.updateQueue,r.updateQueue===n&&(r.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function gs(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function xs(n,r,l){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(Mt&2)!==0){var m=u.pending;return m===null?r.next=r:(r.next=m.next,m.next=r),u.pending=r,r=nc(n),Jm(n,null,l),r}return ic(n,u,r,l),nc(n)}function Ll(n,r,l){if(r=r.updateQueue,r!==null&&(r=r.shared,(l&4194048)!==0)){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,ln(n,l)}}function Eh(n,r){var l=n.updateQueue,u=n.alternate;if(u!==null&&(u=u.updateQueue,l===u)){var m=null,g=null;if(l=l.firstBaseUpdate,l!==null){do{var y={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};g===null?m=g=y:g=g.next=y,l=l.next}while(l!==null);g===null?m=g=r:g=g.next=r}else m=g=r;l={baseState:u.baseState,firstBaseUpdate:m,lastBaseUpdate:g,shared:u.shared,callbacks:u.callbacks},n.updateQueue=l;return}n=l.lastBaseUpdate,n===null?l.firstBaseUpdate=r:n.next=r,l.lastBaseUpdate=r}var Nh=!1;function Ol(){if(Nh){var n=za;if(n!==null)throw n}}function zl(n,r,l,u){Nh=!1;var m=n.updateQueue;ms=!1;var g=m.firstBaseUpdate,y=m.lastBaseUpdate,k=m.shared.pending;if(k!==null){m.shared.pending=null;var L=k,J=L.next;L.next=null,y===null?g=J:y.next=J,y=L;var ue=n.alternate;ue!==null&&(ue=ue.updateQueue,k=ue.lastBaseUpdate,k!==y&&(k===null?ue.firstBaseUpdate=J:k.next=J,ue.lastBaseUpdate=L))}if(g!==null){var pe=m.baseState;y=0,ue=J=L=null,k=g;do{var ee=k.lane&-536870913,ae=ee!==k.lane;if(ae?(bt&ee)===ee:(u&ee)===ee){ee!==0&&ee===Oa&&(Nh=!0),ue!==null&&(ue=ue.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Be=n,Ke=k;ee=r;var Ut=l;switch(Ke.tag){case 1:if(Be=Ke.payload,typeof Be=="function"){pe=Be.call(Ut,pe,ee);break e}pe=Be;break e;case 3:Be.flags=Be.flags&-65537|128;case 0:if(Be=Ke.payload,ee=typeof Be=="function"?Be.call(Ut,pe,ee):Be,ee==null)break e;pe=x({},pe,ee);break e;case 2:ms=!0}}ee=k.callback,ee!==null&&(n.flags|=64,ae&&(n.flags|=8192),ae=m.callbacks,ae===null?m.callbacks=[ee]:ae.push(ee))}else ae={lane:ee,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ue===null?(J=ue=ae,L=pe):ue=ue.next=ae,y|=ee;if(k=k.next,k===null){if(k=m.shared.pending,k===null)break;ae=k,k=ae.next,ae.next=null,m.lastBaseUpdate=ae,m.shared.pending=null}}while(!0);ue===null&&(L=pe),m.baseState=L,m.firstBaseUpdate=J,m.lastBaseUpdate=ue,g===null&&(m.shared.lanes=0),Ss|=y,n.lanes=y,n.memoizedState=pe}}function xg(n,r){if(typeof n!="function")throw Error(s(191,n));n.call(r)}function _g(n,r){var l=n.callbacks;if(l!==null)for(n.callbacks=null,n=0;ng?g:8;var y=A.T,k={};A.T=k,Gh(n,!1,r,l);try{var L=m(),J=A.S;if(J!==null&&J(k,L),L!==null&&typeof L=="object"&&typeof L.then=="function"){var ue=tw(L,u);Hl(n,r,ue,On(n))}else Hl(n,r,u,On(n))}catch(pe){Hl(n,r,{then:function(){},status:"rejected",reason:pe},On())}finally{z.p=g,y!==null&&k.types!==null&&(y.types=k.types),A.T=y}}function lw(){}function qh(n,r,l,u){if(n.tag!==5)throw Error(s(476));var m=Xg(n).queue;Vg(n,m,r,$,l===null?lw:function(){return Zg(n),l(u)})}function Xg(n){var r=n.memoizedState;if(r!==null)return r;r={memoizedState:$,baseState:$,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:$r,lastRenderedState:$},next:null};var l={};return r.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:$r,lastRenderedState:l},next:null},n.memoizedState=r,n=n.alternate,n!==null&&(n.memoizedState=r),r}function Zg(n){var r=Xg(n);r.next===null&&(r=n.alternate.memoizedState),Hl(n,r.next.queue,{},On())}function Wh(){return Vi(no)}function Qg(){return fi().memoizedState}function Jg(){return fi().memoizedState}function ow(n){for(var r=n.return;r!==null;){switch(r.tag){case 24:case 3:var l=On();n=gs(l);var u=xs(r,n,l);u!==null&&(Sn(u,r,l),Ll(u,r,l)),r={cache:vh()},n.payload=r;return}r=r.return}}function cw(n,r,l){var u=On();l={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Sc(n)?tx(r,l):(l=ch(n,r,l,u),l!==null&&(Sn(l,n,u),ix(l,r,u)))}function ex(n,r,l){var u=On();Hl(n,r,l,u)}function Hl(n,r,l,u){var m={lane:u,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(Sc(n))tx(r,m);else{var g=n.alternate;if(n.lanes===0&&(g===null||g.lanes===0)&&(g=r.lastRenderedReducer,g!==null))try{var y=r.lastRenderedState,k=g(y,l);if(m.hasEagerState=!0,m.eagerState=k,An(k,y))return ic(n,r,m,0),Ft===null&&tc(),!1}catch{}finally{}if(l=ch(n,r,m,u),l!==null)return Sn(l,n,u),ix(l,r,u),!0}return!1}function Gh(n,r,l,u){if(u={lane:2,revertLane:Cd(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Sc(n)){if(r)throw Error(s(479))}else r=ch(n,l,u,2),r!==null&&Sn(r,n,2)}function Sc(n){var r=n.alternate;return n===st||r!==null&&r===st}function tx(n,r){Ua=mc=!0;var l=n.pending;l===null?r.next=r:(r.next=l.next,l.next=r),n.pending=r}function ix(n,r,l){if((l&4194048)!==0){var u=r.lanes;u&=n.pendingLanes,l|=u,r.lanes=l,ln(n,l)}}var Ul={readContext:Vi,use:_c,useCallback:si,useContext:si,useEffect:si,useImperativeHandle:si,useLayoutEffect:si,useInsertionEffect:si,useMemo:si,useReducer:si,useRef:si,useState:si,useDebugValue:si,useDeferredValue:si,useTransition:si,useSyncExternalStore:si,useId:si,useHostTransitionStatus:si,useFormState:si,useActionState:si,useOptimistic:si,useMemoCache:si,useCacheRefresh:si};Ul.useEffectEvent=si;var nx={readContext:Vi,use:_c,useCallback:function(n,r){return un().memoizedState=[n,r===void 0?null:r],n},useContext:Vi,useEffect:Hg,useImperativeHandle:function(n,r,l){l=l!=null?l.concat([n]):null,vc(4194308,4,qg.bind(null,r,n),l)},useLayoutEffect:function(n,r){return vc(4194308,4,n,r)},useInsertionEffect:function(n,r){vc(4,2,n,r)},useMemo:function(n,r){var l=un();r=r===void 0?null:r;var u=n();if(ra){Rt(!0);try{n()}finally{Rt(!1)}}return l.memoizedState=[u,r],u},useReducer:function(n,r,l){var u=un();if(l!==void 0){var m=l(r);if(ra){Rt(!0);try{l(r)}finally{Rt(!1)}}}else m=r;return u.memoizedState=u.baseState=m,n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:m},u.queue=n,n=n.dispatch=cw.bind(null,st,n),[u.memoizedState,n]},useRef:function(n){var r=un();return n={current:n},r.memoizedState=n},useState:function(n){n=Ih(n);var r=n.queue,l=ex.bind(null,st,r);return r.dispatch=l,[n.memoizedState,l]},useDebugValue:$h,useDeferredValue:function(n,r){var l=un();return Fh(l,n,r)},useTransition:function(){var n=Ih(!1);return n=Vg.bind(null,st,n.queue,!0,!1),un().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,r,l){var u=st,m=un();if(St){if(l===void 0)throw Error(s(407));l=l()}else{if(l=r(),Ft===null)throw Error(s(349));(bt&127)!==0||Cg(u,r,l)}m.memoizedState=l;var g={value:l,getSnapshot:r};return m.queue=g,Hg(Eg.bind(null,u,g,n),[n]),u.flags|=2048,Fa(9,{destroy:void 0},kg.bind(null,u,g,l,r),null),l},useId:function(){var n=un(),r=Ft.identifierPrefix;if(St){var l=Sr,u=yr;l=(u&~(1<<32-Qe(u)-1)).toString(32)+l,r="_"+r+"R_"+l,l=gc++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?y.createElement("select",{is:u.is}):y.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?y.createElement(m,{is:u.is}):y.createElement(m)}}g[oe]=r,g[O]=u;e:for(y=r.child;y!==null;){if(y.tag===5||y.tag===6)g.appendChild(y.stateNode);else if(y.tag!==4&&y.tag!==27&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===r)break e;for(;y.sibling===null;){if(y.return===null||y.return===r)break e;y=y.return}y.sibling.return=y.return,y=y.sibling}r.stateNode=g;e:switch(Zi(g,m,u),m){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&qr(r)}}return Zt(r),ad(r,r.type,n===null?null:n.memoizedProps,r.pendingProps,l),null;case 6:if(n&&r.stateNode!=null)n.memoizedProps!==u&&qr(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(s(166));if(n=le.current,Ba(r)){if(n=r.stateNode,l=r.memoizedProps,u=null,m=Ki,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[oe]=r,n=!!(n.nodeValue===l||u!==null&&u.suppressHydrationWarning===!0||S_(n.nodeValue,l)),n||fs(r,!0)}else n=$c(n).createTextNode(u),n[oe]=r,r.stateNode=n}return Zt(r),null;case 31:if(l=r.memoizedState,n===null||n.memoizedState!==null){if(u=Ba(r),l!==null){if(n===null){if(!u)throw Error(s(318));if(n=r.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(s(557));n[oe]=r}else Zs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Zt(r),n=!1}else l=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=l),n=!0;if(!n)return r.flags&256?(Mn(r),r):(Mn(r),null);if((r.flags&128)!==0)throw Error(s(558))}return Zt(r),null;case 13:if(u=r.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=Ba(r),u!==null&&u.dehydrated!==null){if(n===null){if(!m)throw Error(s(318));if(m=r.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(s(317));m[oe]=r}else Zs(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Zt(r),m=!1}else m=gh(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return r.flags&256?(Mn(r),r):(Mn(r),null)}return Mn(r),(r.flags&128)!==0?(r.lanes=l,r):(l=u!==null,n=n!==null&&n.memoizedState!==null,l&&(u=r.child,m=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(m=u.alternate.memoizedState.cachePool.pool),g=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(g=u.memoizedState.cachePool.pool),g!==m&&(u.flags|=2048)),l!==n&&l&&(r.child.flags|=8192),Nc(r,r.updateQueue),Zt(r),null);case 4:return _e(),n===null&&jd(r.stateNode.containerInfo),Zt(r),null;case 10:return Hr(r.type),Zt(r),null;case 19:if(V(di),u=r.memoizedState,u===null)return Zt(r),null;if(m=(r.flags&128)!==0,g=u.rendering,g===null)if(m)Fl(u,!1);else{if(ai!==0||n!==null&&(n.flags&128)!==0)for(n=r.child;n!==null;){if(g=pc(n),g!==null){for(r.flags|=128,Fl(u,!1),n=g.updateQueue,r.updateQueue=n,Nc(r,n),r.subtreeFlags=0,n=l,l=r.child;l!==null;)eg(l,n),l=l.sibling;return C(di,di.current&1|2),St&&Pr(r,u.treeForkCount),r.child}n=n.sibling}u.tail!==null&&wt()>Dc&&(r.flags|=128,m=!0,Fl(u,!1),r.lanes=4194304)}else{if(!m)if(n=pc(g),n!==null){if(r.flags|=128,m=!0,n=n.updateQueue,r.updateQueue=n,Nc(r,n),Fl(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!St)return Zt(r),null}else 2*wt()-u.renderingStartTime>Dc&&l!==536870912&&(r.flags|=128,m=!0,Fl(u,!1),r.lanes=4194304);u.isBackwards?(g.sibling=r.child,r.child=g):(n=u.last,n!==null?n.sibling=g:r.child=g,u.last=g)}return u.tail!==null?(n=u.tail,u.rendering=n,u.tail=n.sibling,u.renderingStartTime=wt(),n.sibling=null,l=di.current,C(di,m?l&1|2:l&1),St&&Pr(r,u.treeForkCount),n):(Zt(r),null);case 22:case 23:return Mn(r),Th(),u=r.memoizedState!==null,n!==null?n.memoizedState!==null!==u&&(r.flags|=8192):u&&(r.flags|=8192),u?(l&536870912)!==0&&(r.flags&128)===0&&(Zt(r),r.subtreeFlags&6&&(r.flags|=8192)):Zt(r),l=r.updateQueue,l!==null&&Nc(r,l.retryQueue),l=null,n!==null&&n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(l=n.memoizedState.cachePool.pool),u=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(u=r.memoizedState.cachePool.pool),u!==l&&(r.flags|=2048),n!==null&&V(ea),null;case 24:return l=null,n!==null&&(l=n.memoizedState.cache),r.memoizedState.cache!==l&&(r.flags|=2048),Hr(xi),Zt(r),null;case 25:return null;case 30:return null}throw Error(s(156,r.tag))}function pw(n,r){switch(ph(r),r.tag){case 1:return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 3:return Hr(xi),_e(),n=r.flags,(n&65536)!==0&&(n&128)===0?(r.flags=n&-65537|128,r):null;case 26:case 27:case 5:return Le(r),null;case 31:if(r.memoizedState!==null){if(Mn(r),r.alternate===null)throw Error(s(340));Zs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 13:if(Mn(r),n=r.memoizedState,n!==null&&n.dehydrated!==null){if(r.alternate===null)throw Error(s(340));Zs()}return n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 19:return V(di),null;case 4:return _e(),null;case 10:return Hr(r.type),null;case 22:case 23:return Mn(r),Th(),n!==null&&V(ea),n=r.flags,n&65536?(r.flags=n&-65537|128,r):null;case 24:return Hr(xi),null;case 25:return null;default:return null}}function Nx(n,r){switch(ph(r),r.tag){case 3:Hr(xi),_e();break;case 26:case 27:case 5:Le(r);break;case 4:_e();break;case 31:r.memoizedState!==null&&Mn(r);break;case 13:Mn(r);break;case 19:V(di);break;case 10:Hr(r.type);break;case 22:case 23:Mn(r),Th(),n!==null&&V(ea);break;case 24:Hr(xi)}}function ql(n,r){try{var l=r.updateQueue,u=l!==null?l.lastEffect:null;if(u!==null){var m=u.next;l=m;do{if((l.tag&n)===n){u=void 0;var g=l.create,y=l.inst;u=g(),y.destroy=u}l=l.next}while(l!==m)}}catch(k){zt(r,r.return,k)}}function vs(n,r,l){try{var u=r.updateQueue,m=u!==null?u.lastEffect:null;if(m!==null){var g=m.next;u=g;do{if((u.tag&n)===n){var y=u.inst,k=y.destroy;if(k!==void 0){y.destroy=void 0,m=r;var L=l,J=k;try{J()}catch(ue){zt(m,L,ue)}}}u=u.next}while(u!==g)}}catch(ue){zt(r,r.return,ue)}}function jx(n){var r=n.updateQueue;if(r!==null){var l=n.stateNode;try{_g(r,l)}catch(u){zt(n,n.return,u)}}}function Tx(n,r,l){l.props=sa(n.type,n.memoizedProps),l.state=n.memoizedState;try{l.componentWillUnmount()}catch(u){zt(n,r,u)}}function Wl(n,r){try{var l=n.ref;if(l!==null){switch(n.tag){case 26:case 27:case 5:var u=n.stateNode;break;case 30:u=n.stateNode;break;default:u=n.stateNode}typeof l=="function"?n.refCleanup=l(u):l.current=u}}catch(m){zt(n,r,m)}}function wr(n,r){var l=n.ref,u=n.refCleanup;if(l!==null)if(typeof u=="function")try{u()}catch(m){zt(n,r,m)}finally{n.refCleanup=null,n=n.alternate,n!=null&&(n.refCleanup=null)}else if(typeof l=="function")try{l(null)}catch(m){zt(n,r,m)}else l.current=null}function Ax(n){var r=n.type,l=n.memoizedProps,u=n.stateNode;try{e:switch(r){case"button":case"input":case"select":case"textarea":l.autoFocus&&u.focus();break e;case"img":l.src?u.src=l.src:l.srcSet&&(u.srcset=l.srcSet)}}catch(m){zt(n,n.return,m)}}function ld(n,r,l){try{var u=n.stateNode;Ow(u,n.type,l,r),u[O]=r}catch(m){zt(n,n.return,m)}}function Rx(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&Ns(n.type)||n.tag===4}function od(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||Rx(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;n.tag!==5&&n.tag!==6&&n.tag!==18;){if(n.tag===27&&Ns(n.type)||n.flags&2||n.child===null||n.tag===4)continue e;n.child.return=n,n=n.child}if(!(n.flags&2))return n.stateNode}}function cd(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(n,r):(r=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,r.appendChild(n),l=l._reactRootContainer,l!=null||r.onclick!==null||(r.onclick=lr));else if(u!==4&&(u===27&&Ns(n.type)&&(l=n.stateNode,r=null),n=n.child,n!==null))for(cd(n,r,l),n=n.sibling;n!==null;)cd(n,r,l),n=n.sibling}function jc(n,r,l){var u=n.tag;if(u===5||u===6)n=n.stateNode,r?l.insertBefore(n,r):l.appendChild(n);else if(u!==4&&(u===27&&Ns(n.type)&&(l=n.stateNode),n=n.child,n!==null))for(jc(n,r,l),n=n.sibling;n!==null;)jc(n,r,l),n=n.sibling}function Dx(n){var r=n.stateNode,l=n.memoizedProps;try{for(var u=n.type,m=r.attributes;m.length;)r.removeAttributeNode(m[0]);Zi(r,u,l),r[oe]=n,r[O]=l}catch(g){zt(n,n.return,g)}}var Wr=!1,vi=!1,ud=!1,Mx=typeof WeakSet=="function"?WeakSet:Set,Mi=null;function mw(n,r){if(n=n.containerInfo,Rd=Vc,n=Wm(n),nh(n)){if("selectionStart"in n)var l={start:n.selectionStart,end:n.selectionEnd};else e:{l=(l=n.ownerDocument)&&l.defaultView||window;var u=l.getSelection&&l.getSelection();if(u&&u.rangeCount!==0){l=u.anchorNode;var m=u.anchorOffset,g=u.focusNode;u=u.focusOffset;try{l.nodeType,g.nodeType}catch{l=null;break e}var y=0,k=-1,L=-1,J=0,ue=0,pe=n,ee=null;t:for(;;){for(var ae;pe!==l||m!==0&&pe.nodeType!==3||(k=y+m),pe!==g||u!==0&&pe.nodeType!==3||(L=y+u),pe.nodeType===3&&(y+=pe.nodeValue.length),(ae=pe.firstChild)!==null;)ee=pe,pe=ae;for(;;){if(pe===n)break t;if(ee===l&&++J===m&&(k=y),ee===g&&++ue===u&&(L=y),(ae=pe.nextSibling)!==null)break;pe=ee,ee=pe.parentNode}pe=ae}l=k===-1||L===-1?null:{start:k,end:L}}else l=null}l=l||{start:0,end:0}}else l=null;for(Dd={focusedElem:n,selectionRange:l},Vc=!1,Mi=r;Mi!==null;)if(r=Mi,n=r.child,(r.subtreeFlags&1028)!==0&&n!==null)n.return=r,Mi=n;else for(;Mi!==null;){switch(r=Mi,g=r.alternate,n=r.flags,r.tag){case 0:if((n&4)!==0&&(n=r.updateQueue,n=n!==null?n.events:null,n!==null))for(l=0;l title"))),Zi(g,u,l),g[oe]=n,Dt(g),u=g;break e;case"link":var y=I_("link","href",m).get(u+(l.href||""));if(y){for(var k=0;kUt&&(y=Ut,Ut=Ke,Ke=y);var W=Fm(k,Ke),P=Fm(k,Ut);if(W&&P&&(ae.rangeCount!==1||ae.anchorNode!==W.node||ae.anchorOffset!==W.offset||ae.focusNode!==P.node||ae.focusOffset!==P.offset)){var Z=pe.createRange();Z.setStart(W.node,W.offset),ae.removeAllRanges(),Ke>Ut?(ae.addRange(Z),ae.extend(P.node,P.offset)):(Z.setEnd(P.node,P.offset),ae.addRange(Z))}}}}for(pe=[],ae=k;ae=ae.parentNode;)ae.nodeType===1&&pe.push({element:ae,left:ae.scrollLeft,top:ae.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;kl?32:l,A.T=null,l=xd,xd=null;var g=Cs,y=Xr;if(ji=0,Ka=Cs=null,Xr=0,(Mt&6)!==0)throw Error(s(331));var k=Mt;if(Mt|=4,qx(g.current),Ux(g,g.current,y,l),Mt=k,Zl(0,!1),yt&&typeof yt.onPostCommitFiberRoot=="function")try{yt.onPostCommitFiberRoot(Bt,g)}catch{}return!0}finally{z.p=m,A.T=u,o_(n,r)}}function u_(n,r,l){r=Kn(l,r),r=Xh(n.stateNode,r,2),n=xs(n,r,2),n!==null&&(pt(n,2),Cr(n))}function zt(n,r,l){if(n.tag===3)u_(n,n,l);else for(;r!==null;){if(r.tag===3){u_(r,n,l);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ws===null||!ws.has(u))){n=Kn(l,n),l=hx(2),u=xs(r,l,2),u!==null&&(dx(l,u,r,n),pt(u,2),Cr(u));break}}r=r.return}}function yd(n,r,l){var u=n.pingCache;if(u===null){u=n.pingCache=new _w;var m=new Set;u.set(r,m)}else m=u.get(r),m===void 0&&(m=new Set,u.set(r,m));m.has(l)||(fd=!0,m.add(l),n=ww.bind(null,n,r,l),r.then(n,n))}function ww(n,r,l){var u=n.pingCache;u!==null&&u.delete(r),n.pingedLanes|=n.suspendedLanes&l,n.warmLanes&=~l,Ft===n&&(bt&l)===l&&(ai===4||ai===3&&(bt&62914560)===bt&&300>wt()-Rc?(Mt&2)===0&&Va(n,0):pd|=l,Ya===bt&&(Ya=0)),Cr(n)}function h_(n,r){r===0&&(r=Vt()),n=Vs(n,r),n!==null&&(pt(n,r),Cr(n))}function Cw(n){var r=n.memoizedState,l=0;r!==null&&(l=r.retryLane),h_(n,l)}function kw(n,r){var l=0;switch(n.tag){case 31:case 13:var u=n.stateNode,m=n.memoizedState;m!==null&&(l=m.retryLane);break;case 19:u=n.stateNode;break;case 22:u=n.stateNode._retryCache;break;default:throw Error(s(314))}u!==null&&u.delete(r),h_(n,l)}function Ew(n,r){return _t(n,r)}var Pc=null,Za=null,Sd=!1,Ic=!1,wd=!1,Es=0;function Cr(n){n!==Za&&n.next===null&&(Za===null?Pc=Za=n:Za=Za.next=n),Ic=!0,Sd||(Sd=!0,jw())}function Zl(n,r){if(!wd&&Ic){wd=!0;do for(var l=!1,u=Pc;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var g=0;else{var y=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-Qe(42|n)+1)-1,g&=m&~(y&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(l=!0,m_(u,g))}else g=bt,g=dt(u,u===Ft?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||ft(u,g)||(l=!0,m_(u,g));u=u.next}while(l);wd=!1}}function Nw(){d_()}function d_(){Ic=Sd=!1;var n=0;Es!==0&&Pw()&&(n=Es);for(var r=wt(),l=null,u=Pc;u!==null;){var m=u.next,g=f_(u,r);g===0?(u.next=null,l===null?Pc=m:l.next=m,m===null&&(Za=l)):(l=u,(n!==0||(g&3)!==0)&&(Ic=!0)),u=m}ji!==0&&ji!==5||Zl(n),Es!==0&&(Es=0)}function f_(n,r){for(var l=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,g=n.pendingLanes&-62914561;0k)break;var ue=L.transferSize,pe=L.initiatorType;ue&&w_(pe)&&(L=L.responseEnd,y+=ue*(L"u"?null:document;function L_(n,r,l){var u=Qa;if(u&&typeof r=="string"&&r){var m=gi(r);m='link[rel="'+n+'"][href="'+m+'"]',typeof l=="string"&&(m+='[crossorigin="'+l+'"]'),B_.has(m)||(B_.add(m),n={rel:n,crossOrigin:l,href:r},u.querySelector(m)===null&&(r=u.createElement("link"),Zi(r,"link",n),Dt(r),u.head.appendChild(r)))}}function Yw(n){Zr.D(n),L_("dns-prefetch",n,null)}function Kw(n,r){Zr.C(n,r),L_("preconnect",n,r)}function Vw(n,r,l){Zr.L(n,r,l);var u=Qa;if(u&&n&&r){var m='link[rel="preload"][as="'+gi(r)+'"]';r==="image"&&l&&l.imageSrcSet?(m+='[imagesrcset="'+gi(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(m+='[imagesizes="'+gi(l.imageSizes)+'"]')):m+='[href="'+gi(n)+'"]';var g=m;switch(r){case"style":g=Ja(n);break;case"script":g=el(n)}er.has(g)||(n=x({rel:"preload",href:r==="image"&&l&&l.imageSrcSet?void 0:n,as:r},l),er.set(g,n),u.querySelector(m)!==null||r==="style"&&u.querySelector(to(g))||r==="script"&&u.querySelector(io(g))||(r=u.createElement("link"),Zi(r,"link",n),Dt(r),u.head.appendChild(r)))}}function Xw(n,r){Zr.m(n,r);var l=Qa;if(l&&n){var u=r&&typeof r.as=="string"?r.as:"script",m='link[rel="modulepreload"][as="'+gi(u)+'"][href="'+gi(n)+'"]',g=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=el(n)}if(!er.has(g)&&(n=x({rel:"modulepreload",href:n},r),er.set(g,n),l.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(io(g)))return}u=l.createElement("link"),Zi(u,"link",n),Dt(u),l.head.appendChild(u)}}}function Zw(n,r,l){Zr.S(n,r,l);var u=Qa;if(u&&n){var m=Gt(u).hoistableStyles,g=Ja(n);r=r||"default";var y=m.get(g);if(!y){var k={loading:0,preload:null};if(y=u.querySelector(to(g)))k.loading=5;else{n=x({rel:"stylesheet",href:n,"data-precedence":r},l),(l=er.get(g))&&Id(n,l);var L=y=u.createElement("link");Dt(L),Zi(L,"link",n),L._p=new Promise(function(J,ue){L.onload=J,L.onerror=ue}),L.addEventListener("load",function(){k.loading|=1}),L.addEventListener("error",function(){k.loading|=2}),k.loading|=4,qc(y,r,u)}y={type:"stylesheet",instance:y,count:1,state:k},m.set(g,y)}}}function Qw(n,r){Zr.X(n,r);var l=Qa;if(l&&n){var u=Gt(l).hoistableScripts,m=el(n),g=u.get(m);g||(g=l.querySelector(io(m)),g||(n=x({src:n,async:!0},r),(r=er.get(m))&&Hd(n,r),g=l.createElement("script"),Dt(g),Zi(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function Jw(n,r){Zr.M(n,r);var l=Qa;if(l&&n){var u=Gt(l).hoistableScripts,m=el(n),g=u.get(m);g||(g=l.querySelector(io(m)),g||(n=x({src:n,async:!0,type:"module"},r),(r=er.get(m))&&Hd(n,r),g=l.createElement("script"),Dt(g),Zi(g,"link",n),l.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(m,g))}}function O_(n,r,l,u){var m=(m=le.current)?Fc(m):null;if(!m)throw Error(s(446));switch(n){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(r=Ja(l.href),l=Gt(m).hoistableStyles,u=l.get(r),u||(u={type:"style",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){n=Ja(l.href);var g=Gt(m).hoistableStyles,y=g.get(n);if(y||(m=m.ownerDocument||m,y={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(n,y),(g=m.querySelector(to(n)))&&!g._p&&(y.instance=g,y.state.loading=5),er.has(n)||(l={rel:"preload",as:"style",href:l.href,crossOrigin:l.crossOrigin,integrity:l.integrity,media:l.media,hrefLang:l.hrefLang,referrerPolicy:l.referrerPolicy},er.set(n,l),g||eC(m,n,l,y.state))),r&&u===null)throw Error(s(528,""));return y}if(r&&u!==null)throw Error(s(529,""));return null;case"script":return r=l.async,l=l.src,typeof l=="string"&&r&&typeof r!="function"&&typeof r!="symbol"?(r=el(l),l=Gt(m).hoistableScripts,u=l.get(r),u||(u={type:"script",instance:null,count:0,state:null},l.set(r,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,n))}}function Ja(n){return'href="'+gi(n)+'"'}function to(n){return'link[rel="stylesheet"]['+n+"]"}function z_(n){return x({},n,{"data-precedence":n.precedence,precedence:null})}function eC(n,r,l,u){n.querySelector('link[rel="preload"][as="style"]['+r+"]")?u.loading=1:(r=n.createElement("link"),u.preload=r,r.addEventListener("load",function(){return u.loading|=1}),r.addEventListener("error",function(){return u.loading|=2}),Zi(r,"link",l),Dt(r),n.head.appendChild(r))}function el(n){return'[src="'+gi(n)+'"]'}function io(n){return"script[async]"+n}function P_(n,r,l){if(r.count++,r.instance===null)switch(r.type){case"style":var u=n.querySelector('style[data-href~="'+gi(l.href)+'"]');if(u)return r.instance=u,Dt(u),u;var m=x({},l,{"data-href":l.href,"data-precedence":l.precedence,href:null,precedence:null});return u=(n.ownerDocument||n).createElement("style"),Dt(u),Zi(u,"style",m),qc(u,l.precedence,n),r.instance=u;case"stylesheet":m=Ja(l.href);var g=n.querySelector(to(m));if(g)return r.state.loading|=4,r.instance=g,Dt(g),g;u=z_(l),(m=er.get(m))&&Id(u,m),g=(n.ownerDocument||n).createElement("link"),Dt(g);var y=g;return y._p=new Promise(function(k,L){y.onload=k,y.onerror=L}),Zi(g,"link",u),r.state.loading|=4,qc(g,l.precedence,n),r.instance=g;case"script":return g=el(l.src),(m=n.querySelector(io(g)))?(r.instance=m,Dt(m),m):(u=l,(m=er.get(g))&&(u=x({},l),Hd(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),Dt(m),Zi(m,"link",u),n.head.appendChild(m),r.instance=m);case"void":return null;default:throw Error(s(443,r.type))}else r.type==="stylesheet"&&(r.state.loading&4)===0&&(u=r.instance,r.state.loading|=4,qc(u,l.precedence,n));return r.instance}function qc(n,r,l){for(var u=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=u.length?u[u.length-1]:null,g=m,y=0;y title"):null)}function tC(n,r,l){if(l===1||r.itemProp!=null)return!1;switch(n){case"meta":case"title":return!0;case"style":if(typeof r.precedence!="string"||typeof r.href!="string"||r.href==="")break;return!0;case"link":if(typeof r.rel!="string"||typeof r.href!="string"||r.href===""||r.onLoad||r.onError)break;switch(r.rel){case"stylesheet":return n=r.disabled,typeof r.precedence=="string"&&n==null;default:return!0}case"script":if(r.async&&typeof r.async!="function"&&typeof r.async!="symbol"&&!r.onLoad&&!r.onError&&r.src&&typeof r.src=="string")return!0}return!1}function U_(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function iC(n,r,l,u){if(l.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var m=Ja(u.href),g=r.querySelector(to(m));if(g){r=g._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(n.count++,n=Gc.bind(n),r.then(n,n)),l.state.loading|=4,l.instance=g,Dt(g);return}g=r.ownerDocument||r,u=z_(u),(m=er.get(m))&&Id(u,m),g=g.createElement("link"),Dt(g);var y=g;y._p=new Promise(function(k,L){y.onload=k,y.onerror=L}),Zi(g,"link",u),l.instance=g}n.stylesheets===null&&(n.stylesheets=new Map),n.stylesheets.set(l,r),(r=l.state.preload)&&(l.state.loading&3)===0&&(n.count++,l=Gc.bind(n),r.addEventListener("load",l),r.addEventListener("error",l))}}var Ud=0;function nC(n,r){return n.stylesheets&&n.count===0&&Kc(n,n.stylesheets),0Ud?50:800)+r);return n.unsuspend=l,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function Gc(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Kc(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var Yc=null;function Kc(n,r){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Yc=new Map,r.forEach(rC,n),Yc=null,Gc.call(n))}function rC(n,r){if(!(r.state.loading&4)){var l=Yc.get(n);if(l)var u=l.get(null);else{l=new Map,Yc.set(n,l);for(var m=n.querySelectorAll("link[data-precedence],style[data-precedence]"),g=0;g"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Xd.exports=yC(),Xd.exports}var wC=SC();const CC=Pu(wC);function kC({onLogin:e}){const[t,i]=w.useState(""),[s,a]=w.useState(null),[o,c]=w.useState(!1),h=async p=>{if(p.preventDefault(),!t.trim())return;c(!0),a(null);const f=await e(t);f&&a(f),c(!1)};return d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsxs("div",{className:"w-full max-w-sm",children:[d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"local writer agent"})]}),d.jsxs("form",{onSubmit:h,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.jsx("input",{type:"password",value:t,onChange:p=>i(p.target.value),placeholder:"enter your passphrase",autoFocus:!0,className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),s&&d.jsx("p",{className:"text-error text-xs",children:s}),d.jsx("button",{type:"submit",disabled:o||!t.trim(),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:o?"authenticating...":"unlock"})]})]}),d.jsx("p",{className:"text-muted mt-4 text-center text-[10px]",children:"enter your passphrase to unlock"})]})})}function EC({onSetup:e}){const[t,i]=w.useState(""),[s,a]=w.useState(""),[o,c]=w.useState(null),[h,p]=w.useState(!1),f=async _=>{if(_.preventDefault(),!t.trim()||t.length<4){c("Passphrase must be at least 4 characters");return}if(t!==s){c("Passphrases do not match");return}p(!0),c(null);const x=await e(t);x&&c(x),p(!1)};return d.jsx("div",{className:"flex h-screen items-center justify-center p-4",children:d.jsx("div",{className:"w-full max-w-sm",children:d.jsxs("div",{className:"border-border rounded border p-6",children:[d.jsxs("div",{className:"mb-6 text-center",children:[d.jsx("h1",{className:"text-accent text-lg font-bold tracking-tight",children:"PlotLink OWS"}),d.jsx("p",{className:"text-muted mt-1 text-xs",children:"first-time setup"})]}),d.jsx("p",{className:"text-muted mb-4 text-xs leading-relaxed",children:"Choose a passphrase to protect your local writer agent. This will be used to unlock the app and secure your OWS wallet."}),d.jsxs("form",{onSubmit:f,className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Passphrase"}),d.jsx("input",{type:"password",value:t,onChange:_=>i(_.target.value),placeholder:"choose a passphrase",autoFocus:!0,className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted mb-1.5 block text-xs uppercase tracking-wider",children:"Confirm"}),d.jsx("input",{type:"password",value:s,onChange:_=>a(_.target.value),placeholder:"repeat passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),o&&d.jsx("p",{className:"text-error text-xs",children:o}),d.jsx("button",{type:"submit",disabled:h||!t.trim()||!s.trim(),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:h?"setting up...":"create passphrase"})]})]})})})}const ef="http://localhost:7777";function Ry({token:e}){const[t,i]=w.useState(null),[s,a]=w.useState(!1),[o,c]=w.useState(null),[h,p]=w.useState(!1),[f,_]=w.useState(null),x=w.useCallback((E,N)=>fetch(E,{...N,headers:{...N==null?void 0:N.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),b=w.useCallback(()=>{x(`${ef}/api/wallet`).then(E=>E.json()).then(E=>i(E)).catch(()=>i({exists:!1,error:"Failed to load wallet"}))},[x]);w.useEffect(()=>{b()},[b]);const v=async()=>{a(!0),_(null);try{const E=await x(`${ef}/api/wallet/create`,{method:"POST"}),N=await E.json();if(!E.ok)throw new Error(N.error||"Creation failed");b()}catch(E){_(E instanceof Error?E.message:"Failed to create wallet")}a(!1)},S=async E=>{c(E.walletId||E.name),_(null);try{const N=await x(`${ef}/api/wallet/active`,{method:"POST",body:JSON.stringify({walletId:E.walletId,name:E.name,address:E.normalizedAddress||E.address})}),I=await N.json();if(!N.ok)throw new Error(I.error||"Wallet switch failed");b()}catch(N){_(N instanceof Error?N.message:"Failed to switch wallet")}c(null)},j=()=>{t!=null&&t.address&&(navigator.clipboard.writeText(t.address),p(!0),setTimeout(()=>p(!1),2e3))},D=E=>`${E.slice(0,6)}...${E.slice(-4)}`;return d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"OWS Wallet"}),!t&&d.jsx("p",{className:"text-muted text-xs",children:"loading..."}),t&&!t.exists&&d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:t.error||"No wallet created yet. Create one to enable autonomous transactions."}),f&&d.jsx("p",{className:"text-error text-xs",children:f}),d.jsx("button",{onClick:v,disabled:s,className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 rounded border px-4 py-2 text-xs font-medium transition-colors",children:s?"creating...":"create wallet"})]}),(t==null?void 0:t.selectionRequired)&&t.wallets&&t.wallets.length>0&&d.jsxs("div",{className:"mb-4 space-y-3 rounded border border-amber-600/30 bg-amber-950/10 p-3",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Multiple OWS wallets found. Select the wallet OWS should use for publishing and signing."}),t.wallets.map(E=>d.jsxs("div",{className:"border-border flex items-center justify-between gap-3 rounded border p-2",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsx("p",{className:"text-foreground truncate text-xs font-medium",children:E.name}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),d.jsx("button",{onClick:()=>S(E),disabled:!E.address||o===(E.walletId||E.name),className:"border-accent text-accent hover:bg-accent/10 disabled:opacity-40 rounded border px-2 py-1 text-[10px] font-medium transition-colors",children:o===(E.walletId||E.name)?"switching...":"use"})]},E.walletId||E.name)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),t&&t.exists&&t.address&&d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:"Active Wallet (Base)"}),d.jsx("span",{className:`rounded border px-1.5 py-0.5 text-[9px] ${t.ethBalance&&parseFloat(t.ethBalance)>0?"border-accent/30 text-accent":"border-accent-dim/30 text-accent-dim"}`,children:t.ethBalance&&parseFloat(t.ethBalance)>0?"active":"no balance"})]}),t.name&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Name"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.name})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("code",{className:"text-foreground bg-surface rounded px-2 py-1 text-xs font-mono",children:D(t.address)}),d.jsx("button",{onClick:j,className:"text-muted hover:text-accent text-xs transition-colors",children:h?"copied":"copy"})]}),d.jsxs("div",{className:"border-border space-y-1 border-t pt-3",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.ethBalance||"0.000000"," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC"}),d.jsxs("span",{className:"text-foreground font-medium",children:["$",t.usdcBalance||"0.00"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"PLOT"}),d.jsxs("span",{className:"text-foreground font-medium",children:[t.plotBalance||"0.0000"," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Network"}),d.jsx("span",{className:"text-foreground",children:"Base"})]})]}),t.wallets&&t.wallets.length>1&&d.jsxs("div",{className:"border-border space-y-2 border-t pt-3",children:[d.jsx("p",{className:"text-muted text-[10px] font-medium uppercase tracking-wider",children:"Switch Wallet"}),t.wallets.map(E=>d.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("p",{className:E.active?"text-accent truncate font-medium":"text-foreground truncate",children:[E.name,E.active?" (active)":""]}),d.jsx("p",{className:"text-muted truncate text-[10px] font-mono",children:E.address||"No EVM address"})]}),!E.active&&d.jsx("button",{onClick:()=>S(E),disabled:!E.address||o===(E.walletId||E.name),className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 rounded border px-2 py-1 text-[10px] transition-colors",children:o===(E.walletId||E.name)?"...":"use"})]},E.walletId||E.name)),f&&d.jsx("p",{className:"text-error text-xs",children:f})]}),d.jsxs("div",{className:"border-border border-t pt-3",children:[d.jsx("p",{className:"text-muted mb-2 text-[10px] font-medium uppercase tracking-wider",children:"Fund Wallet"}),d.jsx("p",{className:"text-muted text-[10px]",children:"Send ETH on Base for gas (~$0.01 per publish):"}),d.jsx("code",{className:"text-foreground bg-surface mt-1 block break-all rounded px-2 py-1.5 text-[10px] font-mono",children:t.address})]})]}),(t==null?void 0:t.exists)&&d.jsx("button",{onClick:v,disabled:s,className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 mt-4 rounded border px-3 py-1.5 text-[10px] font-medium transition-colors",children:s?"creating...":"create another wallet"})]})}function Eu(e){return!!e&&e.codex.installed&&e.codex.auth==="unknown"}const Up="Codex is installed but its capabilities couldn't be read — you may need to log in to Codex (resolve outside OWS), then re-check.";function NC({token:e,onLogout:t}){const[i,s]=w.useState(""),[a,o]=w.useState(""),[c,h]=w.useState(null),[p,f]=w.useState(!1),[_,x]=w.useState(!1),[b,v]=w.useState(null),[S,j]=w.useState("AI Writer"),[D,E]=w.useState(""),[N,I]=w.useState(""),[te,q]=w.useState(!1),[R,ie]=w.useState(null),[fe,be]=w.useState(""),[B,ne]=w.useState(null),[F,G]=w.useState(!1),[Y,U]=w.useState(null),[A,z]=w.useState(null),[$,ge]=w.useState(null),T=w.useCallback((se,le)=>fetch(se,{...le,headers:{...le==null?void 0:le.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]);w.useEffect(()=>{T("/api/settings/link-status").then(se=>se.json()).then(se=>v(se)).catch(()=>v({linked:!1}))},[]),w.useEffect(()=>{T("/api/agent/readiness").then(se=>se.ok?se.json():null).then(se=>{se&&ge(se)}).catch(()=>{})},[]);const M=async()=>{if(!S.trim()){ie("Agent name is required");return}if(!D.trim()){ie("Description is required");return}q(!0),ie(null);try{const se=await T("/api/settings/register-agent",{method:"POST",body:JSON.stringify({name:S,description:D,...N.trim()&&{genre:N}})}),le=await se.json();if(!se.ok)throw new Error(le.error||"Registration failed");v({linked:!0,agentId:le.agentId,owsWallet:le.owsWallet,txHash:le.txHash})}catch(se){ie(se instanceof Error?se.message:"Registration failed")}q(!1)},V=async()=>{if(!fe.trim()||!/^0x[a-fA-F0-9]{40}$/.test(fe)){U("Enter a valid wallet address (0x...)");return}G(!0),U(null),ne(null);try{const se=await T("/api/settings/generate-binding",{method:"POST",body:JSON.stringify({humanWallet:fe})}),le=await se.json();if(!se.ok)throw new Error(le.error||"Failed to generate binding code");ne(le)}catch(se){U(se instanceof Error?se.message:"Failed to generate binding code")}G(!1)},C=async(se,le)=>{await navigator.clipboard.writeText(se),z(le),setTimeout(()=>z(null),2e3)},X=async()=>{if(h(null),f(!1),!i||i.length<4){h("Passphrase must be at least 4 characters");return}if(i!==a){h("Passphrases do not match");return}x(!0);try{const se=await T("/api/auth/reset-passphrase",{method:"POST",body:JSON.stringify({passphrase:i})});if(!se.ok){const le=await se.json();throw new Error(le.error||"Reset failed")}f(!0),s(""),o(""),setTimeout(()=>f(!1),3e3)}catch(se){h(se instanceof Error?se.message:"Reset failed")}x(!1)};return d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Settings"}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Identity"}),b!=null&&b.linked?d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-sm font-medium text-accent",children:"Registered"}),d.jsxs("span",{className:"text-muted text-xs",children:["Agent #",b.agentId]})]}),b.owsWallet&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Wallet: ",b.owsWallet.slice(0,6),"...",b.owsWallet.slice(-4)]}),b.owner&&d.jsxs("p",{className:"text-muted text-xs font-mono",children:["Owner: ",b.owner.slice(0,6),"...",b.owner.slice(-4)]}),b.txHash&&d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://basescan.org/tx/${b.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View transaction on BaseScan"})}),d.jsx("p",{className:"text-muted text-xs",children:d.jsx("a",{href:`https://plotlink.xyz/profile/${b.owsWallet}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View agent profile on plotlink.xyz"})})]}):d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:"Register this AI writer on-chain via ERC-8004. Uses your OWS wallet's existing ETH balance for gas."}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Name"}),d.jsx("input",{value:S,onChange:se=>j(se.target.value),placeholder:"AI Writer",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Description"}),d.jsx("input",{value:D,onChange:se=>E(se.target.value),placeholder:"An AI writing assistant for fiction stories",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Genre (optional)"}),d.jsx("input",{value:N,onChange:se=>I(se.target.value),placeholder:"e.g. Fiction, Sci-Fi, Fantasy",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"})]}),R&&d.jsx("p",{className:"text-error text-xs",children:R}),d.jsx("button",{onClick:M,disabled:te||!S.trim()||!D.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:te?"Registering...":"Register Agent Identity"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4","data-testid":"provider-readiness",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Agent Providers"}),d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Claude"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.claude.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.codex.installed?"Installed":"Not detected"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex version"}),d.jsx("span",{className:"text-muted text-xs font-mono",children:($==null?void 0:$.codex.version)??"—"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Image generation"}),d.jsx("span",{className:"text-muted text-xs",children:($==null?void 0:$.codex.imageGeneration)??"unknown"})]}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Codex auth"}),d.jsx("span",{className:"text-muted text-xs","data-testid":"codex-auth-status",children:$!=null&&$.codex.installed?$.codex.auth==="ok"?"ok":"unclear":"—"})]}),Eu($)&&d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"codex-auth-unknown-settings",children:Up}),d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("span",{className:"text-foreground text-sm",children:"Last checked"}),d.jsx("span",{className:"text-muted text-xs",children:$!=null&&$.checkedAt?new Date($.checkedAt).toLocaleString():"—"})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Link to PlotLink"}),b!=null&&b.owner?d.jsxs("p",{className:"text-muted text-xs",children:["Linked to owner ",d.jsxs("span",{className:"font-mono",children:[b.owner.slice(0,6),"...",b.owner.slice(-4)]})]}):d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-muted text-xs",children:"Link this OWS wallet to your PlotLink account so your stories appear under your profile on plotlink.xyz."}),d.jsxs("div",{className:"text-muted text-xs space-y-1 pl-3",children:[d.jsx("p",{children:"1. Enter your PlotLink wallet address below"}),d.jsx("p",{children:'2. Click "Generate Binding Code"'}),d.jsx("p",{children:"3. Copy the code and paste it on plotlink.xyz → Agents → Link AI Writer"})]}),d.jsx("input",{value:fe,onChange:se=>be(se.target.value),placeholder:"Your PlotLink wallet address (0x...)",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent font-mono"}),Y&&d.jsx("p",{className:"text-error text-xs",children:Y}),d.jsx("button",{onClick:V,disabled:F||!fe.trim(),className:"bg-accent text-white hover:bg-accent-dim disabled:opacity-50 w-full rounded px-4 py-2 text-sm font-medium transition-colors",children:F?"Generating...":"Generate Binding Code"}),B&&d.jsxs("div",{className:"space-y-3 mt-3",children:[d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Binding Code (signature)"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.signature}),d.jsx("button",{onClick:()=>C(B.signature,"signature"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:A==="signature"?"Copied!":"Copy"})]})]}),d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"OWS Wallet Address"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono break-all text-foreground pr-16",children:B.owsWallet}),d.jsx("button",{onClick:()=>C(B.owsWallet,"wallet"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:A==="wallet"?"Copied!":"Copy"})]})]}),B.agentId&&d.jsxs("div",{children:[d.jsx("label",{className:"text-muted text-xs block mb-1",children:"Agent ID"}),d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:"bg-surface border-border rounded border p-2 text-xs font-mono text-foreground pr-16",children:B.agentId}),d.jsx("button",{onClick:()=>C(String(B.agentId),"agentId"),className:"absolute top-1 right-1 text-xs px-2 py-1 rounded border border-border text-muted hover:text-accent hover:border-accent transition-colors",children:A==="agentId"?"Copied!":"Copy"})]})]}),d.jsx("p",{className:"text-xs text-accent",children:'Now go to plotlink.xyz/agents and paste the values in the "Link AI Writer" section.'})]})]})]}),d.jsx(Ry,{token:e}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Reset Passphrase"}),d.jsxs("div",{className:"space-y-3",children:[d.jsx("input",{type:"password",value:i,onChange:se=>s(se.target.value),placeholder:"new passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"}),d.jsx("input",{type:"password",value:a,onChange:se=>o(se.target.value),placeholder:"confirm passphrase",className:"bg-surface border-border text-foreground placeholder:text-muted/50 w-full rounded border px-3 py-2 text-sm outline-none focus:border-accent"}),c&&d.jsx("p",{className:"text-error text-xs",children:c}),p&&d.jsx("p",{className:"text-xs text-accent",children:"passphrase updated"}),d.jsx("button",{onClick:X,disabled:_||!i.trim(),className:"border-border text-muted hover:border-accent hover:text-accent disabled:opacity-40 w-full rounded border px-4 py-2 text-xs font-medium transition-colors",children:_?"updating...":"update passphrase"})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Session"}),d.jsx("button",{onClick:t,className:"border-border text-muted hover:border-error hover:text-error rounded border px-4 py-2 text-xs font-medium transition-colors",children:"logout"})]})]})}const jC="http://localhost:7777";function TC({token:e}){const[t,i]=w.useState(null),s=w.useCallback((h,p)=>fetch(h,{...p,headers:{...p==null?void 0:p.headers,Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),[e]),a=w.useCallback(()=>{s(`${jC}/api/dashboard`).then(h=>h.json()).then(i)},[s]);w.useEffect(()=>{a()},[a]);const o=h=>`${h.slice(0,6)}...${h.slice(-4)}`,c=h=>{if(!h)return"Unknown date";const p=new Date(h);return isNaN(p.getTime())?"Unknown date":p.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})};return t?d.jsxs("div",{className:"mx-auto max-w-2xl space-y-6 p-6",children:[d.jsx("h2",{className:"text-accent text-lg font-bold",children:"Writer Dashboard"}),d.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-accent text-lg font-bold",children:t.stories.totalPublished}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"published"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.pendingFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"pending"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalStories}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"stories"})]}),d.jsxs("div",{className:"border-border rounded border p-3 text-center",children:[d.jsx("div",{className:"text-foreground text-lg font-bold",children:t.stories.totalFiles}),d.jsx("div",{className:"text-muted text-[10px] uppercase tracking-wider",children:"files"})]})]}),t.wallet&&d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Wallet"}),d.jsxs("div",{className:"space-y-1.5",children:[t.wallet.name&&d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Active wallet"}),d.jsx("span",{className:"text-foreground truncate pl-3 font-mono text-[10px]",children:t.wallet.name})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Address"}),d.jsx("code",{className:"text-foreground font-mono text-[10px]",children:o(t.wallet.address)})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"ETH Balance"}),d.jsxs("span",{className:"text-foreground",children:[t.wallet.ethFormatted," ETH"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"USDC Balance"}),d.jsxs("span",{className:"text-foreground",children:["$",t.wallet.usdcBalance]})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Profit & Loss"}),d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Total costs (gas)"}),d.jsxs("span",{className:"text-error",children:["-",t.pnl.totalCostsEth," ETH (~$",t.pnl.totalCostsUsd,")"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Royalties earned"}),d.jsxs("span",{className:"text-accent",children:["+",t.pnl.totalRoyaltiesPlot," PLOT"]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Unclaimed royalties"}),d.jsxs("span",{className:"text-foreground",children:[t.royalties.unclaimed," PLOT"]})]}),d.jsxs("div",{className:"border-border flex justify-between border-t pt-1.5 text-xs font-medium",children:[d.jsx("span",{className:"text-muted",children:"Net P&L (USD)"}),d.jsxs("span",{className:parseFloat(t.pnl.netPnlUsd)>=0?"text-accent":"text-error",children:[parseFloat(t.pnl.netPnlUsd)>=0?"+":"","$",t.pnl.netPnlUsd]})]}),d.jsxs("div",{className:"flex justify-between text-xs",children:[d.jsx("span",{className:"text-muted",children:"Stories published"}),d.jsx("span",{className:"text-foreground",children:t.costs.storiesPublished})]})]})]}),d.jsxs("div",{className:"border-border rounded border p-4",children:[d.jsx("h3",{className:"text-accent mb-3 text-xs font-bold uppercase tracking-wider",children:"Published Stories"}),t.stories.published.length===0?d.jsx("p",{className:"text-muted text-xs",children:"no published stories yet"}):d.jsx("div",{className:"space-y-3",children:t.stories.published.map(h=>d.jsxs("div",{className:"bg-surface rounded border border-border p-4",children:[d.jsxs("div",{className:"flex items-start justify-between",children:[d.jsxs("div",{children:[h.genre&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-2 py-0.5 text-[10px] font-medium",children:h.genre}),d.jsx("h4",{className:"text-foreground mt-1 text-sm font-serif font-medium",children:h.title}),d.jsx("p",{className:"text-muted mt-0.5 text-[10px] font-mono",children:h.storyName})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[h.hasNotIndexed&&d.jsx("span",{className:"rounded border border-amber-600/30 px-1.5 py-0.5 text-[9px] text-amber-700",children:"not indexed"}),d.jsxs("span",{className:"rounded border border-green-700/30 px-1.5 py-0.5 text-[9px] text-green-700",children:[h.publishedFiles," published"]})]})]}),d.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-center",children:[d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.plotCount}),d.jsx("div",{className:"text-muted text-[9px]",children:"Plots"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium font-mono",children:h.storylineId?`#${h.storylineId}`:"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Storyline"})]}),d.jsxs("div",{className:"rounded bg-background p-1.5",children:[d.jsx("div",{className:"text-foreground text-sm font-medium",children:h.totalGasCostEth??"—"}),d.jsx("div",{className:"text-muted text-[9px]",children:"Gas (ETH)"})]})]}),d.jsx("div",{className:"mt-2 space-y-1",children:h.files.map(p=>d.jsxs("div",{className:"flex items-center justify-between text-[10px]",children:[d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:p.status==="published-not-indexed"?"text-amber-700":"text-green-700",children:p.status==="published-not-indexed"?"⚠":"✓"}),d.jsx("span",{className:"text-muted font-mono",children:p.file})]}),p.txHash&&d.jsxs("a",{href:`https://basescan.org/tx/${p.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted hover:text-accent font-mono",children:["tx:",p.txHash.slice(0,8),"..."]})]},p.file))}),d.jsxs("div",{className:"mt-2 flex items-center justify-between text-[10px]",children:[d.jsx("span",{className:"text-muted",children:c(h.latestPublishedAt)}),h.storylineId&&d.jsx("a",{href:`https://plotlink.xyz/story/${h.storylineId}`,target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"})]})]},h.id))})]}),t.stories.pendingFiles>0&&d.jsx("div",{className:"border-border rounded border p-4",children:d.jsxs("p",{className:"text-muted text-xs",children:[t.stories.pendingFiles," file(s) pending publish — go to Stories to publish them."]})})]}):d.jsx("div",{className:"flex h-full items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"loading dashboard..."})})}const AC={published:"✓","published-not-indexed":"⚠",pending:"⏳",draft:"📝"},RC={published:"text-green-700","published-not-indexed":"text-amber-700",pending:"text-amber-700",draft:"text-muted"};function DC({authFetch:e,selectedStory:t,selectedFile:i,onSelectFile:s,onNewStory:a,untitledSessions:o=[]}){const[c,h]=w.useState([]),[p,f]=w.useState([]),[_,x]=w.useState(new Set),[b,v]=w.useState(!1),S=w.useCallback(async()=>{try{const q=await e("/api/stories");if(q.ok){const R=await q.json();h(R.stories)}}catch{}},[e]),j=w.useCallback(async()=>{try{const q=await e("/api/stories/archived");if(q.ok){const R=await q.json();f(R.stories)}}catch{}},[e]),D=w.useCallback(async q=>{try{(await e("/api/stories/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:q})})).ok&&(j(),S())}catch{}},[e,j,S]);w.useEffect(()=>{S();const q=setInterval(S,5e3);return()=>clearInterval(q)},[S]),w.useEffect(()=>{b&&j()},[b,j]),w.useEffect(()=>{t&&x(q=>new Set(q).add(t))},[t]);const E=q=>{x(R=>{const ie=new Set(R);return ie.has(q)?ie.delete(q):ie.add(q),ie})},N=q=>{var ie;const R=q.map(fe=>{var be;return{file:fe.file,num:(be=fe.file.match(/^plot-(\d+)\.md$/))==null?void 0:be[1]}}).filter(fe=>fe.num!=null).sort((fe,be)=>parseInt(be.num)-parseInt(fe.num));return R.length>0?R[0].file:q.some(fe=>fe.file==="genesis.md")?"genesis.md":q.some(fe=>fe.file==="structure.md")?"structure.md":((ie=q[0])==null?void 0:ie.file)??null},I=q=>{if(E(q.name),q.contentType==="cartoon")s(q.name,"");else{const R=N(q.files);R&&s(q.name,R)}},te=q=>{const R=ie=>{if(ie==="structure.md")return 0;if(ie==="genesis.md")return 1;const fe=ie.match(/^plot-(\d+)\.md$/);return fe?2+parseInt(fe[1]):100};return[...q].sort((ie,fe)=>R(ie.file)-R(fe.file))};return b?d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Archives"}),d.jsx("span",{className:"text-xs text-muted",children:p.length})]}),d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.jsxs("button",{onClick:()=>v(!1),className:"w-full px-3 py-1.5 text-sm text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1.5",children:[d.jsx("span",{children:"←"}),d.jsx("span",{children:"Back"})]})}),d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:p.length===0?d.jsx("div",{className:"p-3 text-sm text-muted",children:d.jsx("p",{children:"No archived stories."})}):p.map(q=>d.jsxs("div",{className:"px-3 py-2 flex items-center justify-between hover:bg-surface",children:[d.jsx("span",{className:"text-sm font-medium truncate",title:q.name,children:q.title||q.name}),d.jsx("button",{onClick:()=>D(q.name),className:"text-xs text-accent hover:text-accent-dim flex-shrink-0 ml-2",children:"Restore"})]},q.name))})]}):d.jsxs("div",{className:"h-full flex flex-col",children:[d.jsxs("div",{className:"px-3 py-1.5 border-b border-border flex items-center justify-between",children:[d.jsx("span",{className:"text-xs font-mono text-muted",children:"Stories"}),d.jsx("span",{className:"text-xs text-muted",children:c.length})]}),a&&d.jsx("div",{className:"px-3 py-2 border-b border-border",children:d.jsxs("button",{onClick:a,className:"w-full px-3 py-1.5 text-sm bg-accent text-white rounded hover:bg-accent-dim flex items-center justify-center gap-1.5",children:[d.jsx("span",{children:"+"}),d.jsx("span",{children:"New Story"})]})}),d.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[o.map(q=>d.jsx("div",{children:d.jsxs("button",{onClick:()=>s(q,""),className:`w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm ${t===q?"bg-surface":""}`,children:[d.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-600 flex-shrink-0"}),d.jsx("span",{className:"font-medium italic text-muted",children:"Untitled"})]})},q)),c.length===0&&o.length===0?d.jsxs("div",{className:"p-3 text-sm text-muted",children:[d.jsx("p",{children:"No stories yet."}),d.jsx("p",{className:"mt-1 text-xs",children:'Click "+ New Story" above to start writing.'})]}):c.filter(q=>q.name!=="_example").map(q=>d.jsxs("div",{children:[d.jsxs("button",{onClick:()=>I(q),className:"w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-surface text-sm",children:[d.jsx("span",{className:"text-xs text-muted",children:_.has(q.name)?"▼":"▶"}),d.jsx("span",{className:"font-medium truncate",title:q.name,children:q.title||q.name}),q.contentType==="cartoon"&&d.jsx("span",{className:"bg-accent/10 text-accent rounded px-1.5 py-0.5 text-[10px] font-medium flex-shrink-0",children:"Cartoon"}),d.jsxs("span",{className:"ml-auto flex-shrink-0 text-xs text-muted",children:[q.publishedCount,"/",q.files.length]})]}),_.has(q.name)&&d.jsx("div",{className:"pl-4",children:te(q.files).map(R=>{const ie=t===q.name&&i===R.file;return d.jsxs("button",{onClick:()=>s(q.name,R.file),className:`w-full px-3 py-1.5 text-left flex items-center gap-2 text-xs hover:bg-surface ${ie?"bg-surface font-medium":""}`,children:[d.jsx("span",{className:RC[R.status],children:AC[R.status]}),d.jsx("span",{className:"truncate font-mono",children:R.file})]},R.file)})})]},q.name))]}),d.jsx("div",{className:"px-3 py-2 border-t border-border",children:d.jsx("button",{onClick:()=>v(!0),className:"w-full px-3 py-1.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded flex items-center justify-center gap-1.5",children:d.jsx("span",{children:"Archives"})})})]})}/** * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. * @license MIT * @@ -57,22 +57,22 @@ Error generating stack: `+u.message+` * Fabrice Bellard's javascript vt100 for jslinux: * http://bellard.org/jslinux/ * Copyright (c) 2011 Fabrice Bellard - */var Ty=Object.defineProperty,EC=Object.getOwnPropertyDescriptor,NC=(e,t)=>{for(var i in t)Ty(e,i,{get:t[i],enumerable:!0})},ci=(e,t,i,s)=>{for(var a=s>1?void 0:s?EC(t,i):t,o=e.length-1,c;o>=0;o--)(c=e[o])&&(a=(s?c(t,i,a):c(a))||a);return s&&a&&Ty(t,i,a),a},De=(e,t)=>(i,s)=>t(i,s,e),cb="Terminal input",Hf={get:()=>cb,set:e=>cb=e},ub="Too much output to announce, navigate to rows manually to read",Uf={get:()=>ub,set:e=>ub=e};function jC(e){return e.replace(/\r?\n/g,"\r")}function TC(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function AC(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function RC(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");Ay(a,t,i,s)}}function Ay(e,t,i,s){e=jC(e),e=TC(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function Ry(e,t,i){let s=i.getBoundingClientRect(),a=e.clientX-s.left-10,o=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${a}px`,t.style.top=`${o}px`,t.style.zIndex="1000",t.focus()}function hb(e,t,i,s,a){Ry(e,t,i),a&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function zs(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Pu(e,t=0,i=e.length){let s="";for(let a=t;a65535?(o-=65536,s+=String.fromCharCode((o>>10)+55296)+String.fromCharCode(o%1024+56320)):s+=String.fromCharCode(o)}return s}var DC=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let s=0,a=0;if(this._interim){let o=e.charCodeAt(a++);56320<=o&&o<=57343?t[s++]=(this._interim-55296)*1024+o-56320+65536:(t[s++]=this._interim,t[s++]=o),this._interim=0}for(let o=a;o=i)return this._interim=c,s;let h=e.charCodeAt(o);56320<=h&&h<=57343?t[s++]=(c-55296)*1024+h-56320+65536:(t[s++]=c,t[s++]=h);continue}c!==65279&&(t[s++]=c)}return s}},MC=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let s=0,a,o,c,h,p=0,f=0;if(this.interim[0]){let b=!1,v=this.interim[0];v&=(v&224)===192?31:(v&240)===224?15:7;let S=0,j;for(;(j=this.interim[++S]&63)&&S<4;)v<<=6,v|=j;let R=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=R-S;for(;f=i)return 0;if(j=e[f++],(j&192)!==128){f--,b=!0;break}else this.interim[S++]=j,v<<=6,v|=j&63}b||(R===2?v<128?f--:t[s++]=v:R===3?v<2048||v>=55296&&v<=57343||v===65279||(t[s++]=v):v<65536||v>1114111||(t[s++]=v)),this.interim.fill(0)}let _=i-4,x=f;for(;x=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(p=(a&31)<<6|o&63,p<128){x--;continue}t[s++]=p}else if((a&240)===224){if(x>=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,s;if(c=e[x++],(c&192)!==128){x--;continue}if(p=(a&15)<<12|(o&63)<<6|c&63,p<2048||p>=55296&&p<=57343||p===65279)continue;t[s++]=p}else if((a&248)===240){if(x>=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,s;if(c=e[x++],(c&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,this.interim[2]=c,s;if(h=e[x++],(h&192)!==128){x--;continue}if(p=(a&7)<<18|(o&63)<<12|(c&63)<<6|h&63,p<65536||p>1114111)continue;t[s++]=p}}return s}},Dy="",Is=" ",Po=class My{constructor(){this.fg=0,this.bg=0,this.extended=new Nu}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new My;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Nu=class By{constructor(t=0,i=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=i}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new By(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},sr=class Ly extends Po{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Nu,this.combinedData=""}static fromCharData(t){let i=new Ly;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?zs(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let a=t[1].charCodeAt(1);56320<=a&&a<=57343?this.content=(s-55296)*1024+a-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},db="di$target",$f="di$dependencies",ef=new Map;function BC(e){return e[$f]||[]}function $i(e){if(ef.has(e))return ef.get(e);let t=function(i,s,a){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");LC(t,i,a)};return t._id=e,ef.set(e,t),t}function LC(e,t,i){t[db]===t?t[$f].push({id:e,index:i}):(t[$f]=[{id:e,index:i}],t[db]=t)}var pn=$i("BufferService"),Oy=$i("CoreMouseService"),ba=$i("CoreService"),OC=$i("CharsetService"),$p=$i("InstantiationService"),zy=$i("LogService"),mn=$i("OptionsService"),Py=$i("OscLinkService"),zC=$i("UnicodeService"),Io=$i("DecorationService"),Ff=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){var _;let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let s=[],a=this._optionsService.rawOptions.linkHandler,o=new sr,c=i.getTrimmedLength(),h=-1,p=-1,f=!1;for(let x=0;xa?a.activate(j,R,v):PC(j,R),hover:(j,R)=>{var E;return(E=a==null?void 0:a.hover)==null?void 0:E.call(a,j,R,v)},leave:(j,R)=>{var E;return(E=a==null?void 0:a.leave)==null?void 0:E.call(a,j,R,v)}})}f=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=x,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};Ff=ci([De(0,pn),De(1,mn),De(2,Py)],Ff);function PC(e,t){if(confirm(`Do you want to navigate to ${t}? + */var Dy=Object.defineProperty,MC=Object.getOwnPropertyDescriptor,BC=(e,t)=>{for(var i in t)Dy(e,i,{get:t[i],enumerable:!0})},ci=(e,t,i,s)=>{for(var a=s>1?void 0:s?MC(t,i):t,o=e.length-1,c;o>=0;o--)(c=e[o])&&(a=(s?c(t,i,a):c(a))||a);return s&&a&&Dy(t,i,a),a},Re=(e,t)=>(i,s)=>t(i,s,e),hb="Terminal input",Uf={get:()=>hb,set:e=>hb=e},db="Too much output to announce, navigate to rows manually to read",$f={get:()=>db,set:e=>db=e};function LC(e){return e.replace(/\r?\n/g,"\r")}function OC(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function zC(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function PC(e,t,i,s){if(e.stopPropagation(),e.clipboardData){let a=e.clipboardData.getData("text/plain");My(a,t,i,s)}}function My(e,t,i,s){e=LC(e),e=OC(e,i.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function By(e,t,i){let s=i.getBoundingClientRect(),a=e.clientX-s.left-10,o=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${a}px`,t.style.top=`${o}px`,t.style.zIndex="1000",t.focus()}function fb(e,t,i,s,a){By(e,t,i),a&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}function zs(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Iu(e,t=0,i=e.length){let s="";for(let a=t;a65535?(o-=65536,s+=String.fromCharCode((o>>10)+55296)+String.fromCharCode(o%1024+56320)):s+=String.fromCharCode(o)}return s}var IC=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let s=0,a=0;if(this._interim){let o=e.charCodeAt(a++);56320<=o&&o<=57343?t[s++]=(this._interim-55296)*1024+o-56320+65536:(t[s++]=this._interim,t[s++]=o),this._interim=0}for(let o=a;o=i)return this._interim=c,s;let h=e.charCodeAt(o);56320<=h&&h<=57343?t[s++]=(c-55296)*1024+h-56320+65536:(t[s++]=c,t[s++]=h);continue}c!==65279&&(t[s++]=c)}return s}},HC=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let s=0,a,o,c,h,p=0,f=0;if(this.interim[0]){let b=!1,v=this.interim[0];v&=(v&224)===192?31:(v&240)===224?15:7;let S=0,j;for(;(j=this.interim[++S]&63)&&S<4;)v<<=6,v|=j;let D=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,E=D-S;for(;f=i)return 0;if(j=e[f++],(j&192)!==128){f--,b=!0;break}else this.interim[S++]=j,v<<=6,v|=j&63}b||(D===2?v<128?f--:t[s++]=v:D===3?v<2048||v>=55296&&v<=57343||v===65279||(t[s++]=v):v<65536||v>1114111||(t[s++]=v)),this.interim.fill(0)}let _=i-4,x=f;for(;x=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(p=(a&31)<<6|o&63,p<128){x--;continue}t[s++]=p}else if((a&240)===224){if(x>=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,s;if(c=e[x++],(c&192)!==128){x--;continue}if(p=(a&15)<<12|(o&63)<<6|c&63,p<2048||p>=55296&&p<=57343||p===65279)continue;t[s++]=p}else if((a&248)===240){if(x>=i)return this.interim[0]=a,s;if(o=e[x++],(o&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,s;if(c=e[x++],(c&192)!==128){x--;continue}if(x>=i)return this.interim[0]=a,this.interim[1]=o,this.interim[2]=c,s;if(h=e[x++],(h&192)!==128){x--;continue}if(p=(a&7)<<18|(o&63)<<12|(c&63)<<6|h&63,p<65536||p>1114111)continue;t[s++]=p}}return s}},Ly="",Is=" ",Ho=class Oy{constructor(){this.fg=0,this.bg=0,this.extended=new Nu}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new Oy;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Nu=class zy{constructor(t=0,i=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=i}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new zy(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},sr=class Py extends Ho{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Nu,this.combinedData=""}static fromCharData(t){let i=new Py;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?zs(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let s=t[1].charCodeAt(0);if(55296<=s&&s<=56319){let a=t[1].charCodeAt(1);56320<=a&&a<=57343?this.content=(s-55296)*1024+a-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},pb="di$target",Ff="di$dependencies",tf=new Map;function UC(e){return e[Ff]||[]}function $i(e){if(tf.has(e))return tf.get(e);let t=function(i,s,a){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");$C(t,i,a)};return t._id=e,tf.set(e,t),t}function $C(e,t,i){t[pb]===t?t[Ff].push({id:e,index:i}):(t[Ff]=[{id:e,index:i}],t[pb]=t)}var mn=$i("BufferService"),Iy=$i("CoreMouseService"),ba=$i("CoreService"),FC=$i("CharsetService"),$p=$i("InstantiationService"),Hy=$i("LogService"),gn=$i("OptionsService"),Uy=$i("OscLinkService"),qC=$i("UnicodeService"),Uo=$i("DecorationService"),qf=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){var _;let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let s=[],a=this._optionsService.rawOptions.linkHandler,o=new sr,c=i.getTrimmedLength(),h=-1,p=-1,f=!1;for(let x=0;xa?a.activate(j,D,v):WC(j,D),hover:(j,D)=>{var E;return(E=a==null?void 0:a.hover)==null?void 0:E.call(a,j,D,v)},leave:(j,D)=>{var E;return(E=a==null?void 0:a.leave)==null?void 0:E.call(a,j,D,v)}})}f=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=x,h=o.extended.urlId):(p=-1,h=-1)}}t(s)}};qf=ci([Re(0,mn),Re(1,gn),Re(2,Uy)],qf);function WC(e,t){if(confirm(`Do you want to navigate to ${t}? -WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var Iu=$i("CharSizeService"),ns=$i("CoreBrowserService"),Fp=$i("MouseService"),rs=$i("RenderService"),IC=$i("SelectionService"),Iy=$i("CharacterJoinerService"),xl=$i("ThemeService"),Hy=$i("LinkProviderService"),HC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?fb.isErrorNoTelemetry(e)?new fb(e.message+` +WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}var Hu=$i("CharSizeService"),ns=$i("CoreBrowserService"),Fp=$i("MouseService"),rs=$i("RenderService"),GC=$i("SelectionService"),$y=$i("CharacterJoinerService"),xl=$i("ThemeService"),Fy=$i("LinkProviderService"),YC=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?mb.isErrorNoTelemetry(e)?new mb(e.message+` `+e.stack):new Error(e.message+` -`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},UC=new HC;function gu(e){$C(e)||UC.onUnexpectedError(e)}var qf="Canceled";function $C(e){return e instanceof FC?!0:e instanceof Error&&e.name===qf&&e.message===qf}var FC=class extends Error{constructor(){super(qf),this.name=this.message}};function qC(e){return new Error(`Illegal argument: ${e}`)}var fb=class Wf extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Wf)return t;let i=new Wf;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Gf=class Uy extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,Uy.prototype)}};function On(e,t=0){return e[e.length-(1+t)]}var WC;(e=>{function t(o){return o<0}e.isLessThan=t;function i(o){return o<=0}e.isLessThanOrEqual=i;function s(o){return o>0}e.isGreaterThan=s;function a(o){return o===0}e.isNeitherLessOrGreaterThan=a,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(WC||(WC={}));function GC(e,t){let i=this,s=!1,a;return function(){return s||(s=!0,t||(a=e.apply(i,arguments))),a}}var $y;(e=>{function t(te){return te&&typeof te=="object"&&typeof te[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*a(te){yield te}e.single=a;function o(te){return t(te)?te:a(te)}e.wrap=o;function c(te){return te||i}e.from=c;function*h(te){for(let F=te.length-1;F>=0;F--)yield te[F]}e.reverse=h;function p(te){return!te||te[Symbol.iterator]().next().done===!0}e.isEmpty=p;function f(te){return te[Symbol.iterator]().next().value}e.first=f;function _(te,F){let D=0;for(let ie of te)if(F(ie,D++))return!0;return!1}e.some=_;function x(te,F){for(let D of te)if(F(D))return D}e.find=x;function*b(te,F){for(let D of te)F(D)&&(yield D)}e.filter=b;function*v(te,F){let D=0;for(let ie of te)yield F(ie,D++)}e.map=v;function*S(te,F){let D=0;for(let ie of te)yield*F(ie,D++)}e.flatMap=S;function*j(...te){for(let F of te)yield*F}e.concat=j;function R(te,F,D){let ie=D;for(let fe of te)ie=F(ie,fe);return ie}e.reduce=R;function*E(te,F,D=te.length){for(F<0&&(F+=te.length),D<0?D+=te.length:D>te.length&&(D=te.length);F1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function YC(...e){return ii(()=>ga(e))}function ii(e){return{dispose:GC(()=>{e()})}}var Fy=class qy{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{ga(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?qy.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),void 0)}};Fy.DISABLE_DISPOSED_WARNING=!1;var Hs=Fy,ut=class{constructor(){this._store=new Hs,this._store}dispose(){this._store.dispose()}_register(t){if(t===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(t)}};ut.None=Object.freeze({dispose(){}});var pl=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,(e=this._value)==null||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},is=typeof window=="object"?window:globalThis,Yf=class Kf{constructor(t){this.element=t,this.next=Kf.Undefined,this.prev=Kf.Undefined}};Yf.Undefined=new Yf(void 0);var ni=Yf,pb=class{constructor(){this._first=ni.Undefined,this._last=ni.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===ni.Undefined}clear(){let e=this._first;for(;e!==ni.Undefined;){let t=e.next;e.prev=ni.Undefined,e.next=ni.Undefined,e=t}this._first=ni.Undefined,this._last=ni.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new ni(e);if(this._first===ni.Undefined)this._first=i,this._last=i;else if(t){let a=this._last;this._last=i,i.prev=a,a.next=i}else{let a=this._first;this._first=i,i.next=a,a.prev=i}this._size+=1;let s=!1;return()=>{s||(s=!0,this._remove(i))}}shift(){if(this._first!==ni.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==ni.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==ni.Undefined&&e.next!==ni.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===ni.Undefined&&e.next===ni.Undefined?(this._first=ni.Undefined,this._last=ni.Undefined):e.next===ni.Undefined?(this._last=this._last.prev,this._last.next=ni.Undefined):e.prev===ni.Undefined&&(this._first=this._first.next,this._first.prev=ni.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==ni.Undefined;)yield e.element,e=e.next}},KC=globalThis.performance&&typeof globalThis.performance.now=="function",VC=class Wy{static create(t){return new Wy(t)}constructor(t){this._now=KC&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},en;(e=>{e.None=()=>ut.None;function t(W,K){return x(W,()=>{},0,void 0,!0,void 0,K)}e.defer=t;function i(W){return(K,X=null,U)=>{let A=!1,O;return O=W($=>{if(!A)return O?O.dispose():A=!0,K.call(X,$)},null,U),A&&O.dispose(),O}}e.once=i;function s(W,K,X){return f((U,A=null,O)=>W($=>U.call(A,K($)),null,O),X)}e.map=s;function a(W,K,X){return f((U,A=null,O)=>W($=>{K($),U.call(A,$)},null,O),X)}e.forEach=a;function o(W,K,X){return f((U,A=null,O)=>W($=>K($)&&U.call(A,$),null,O),X)}e.filter=o;function c(W){return W}e.signal=c;function h(...W){return(K,X=null,U)=>{let A=YC(...W.map(O=>O($=>K.call(X,$))));return _(A,U)}}e.any=h;function p(W,K,X,U){let A=X;return s(W,O=>(A=K(A,O),A),U)}e.reduce=p;function f(W,K){let X,U={onWillAddFirstListener(){X=W(A.fire,A)},onDidRemoveLastListener(){X==null||X.dispose()}},A=new Ce(U);return K==null||K.add(A),A.event}function _(W,K){return K instanceof Array?K.push(W):K&&K.add(W),W}function x(W,K,X=100,U=!1,A=!1,O,$){let xe,T,M,G=0,C,V={leakWarningThreshold:O,onWillAddFirstListener(){xe=W(ae=>{G++,T=K(T,ae),U&&!M&&(ne.fire(T),T=void 0),C=()=>{let Y=T;T=void 0,M=void 0,(!U||G>1)&&ne.fire(Y),G=0},typeof X=="number"?(clearTimeout(M),M=setTimeout(C,X)):M===void 0&&(M=0,queueMicrotask(C))})},onWillRemoveListener(){A&&G>0&&(C==null||C())},onDidRemoveLastListener(){C=void 0,xe.dispose()}},ne=new Ce(V);return $==null||$.add(ne),ne.event}e.debounce=x;function b(W,K=0,X){return e.debounce(W,(U,A)=>U?(U.push(A),U):[A],K,void 0,!0,void 0,X)}e.accumulate=b;function v(W,K=(U,A)=>U===A,X){let U=!0,A;return o(W,O=>{let $=U||!K(O,A);return U=!1,A=O,$},X)}e.latch=v;function S(W,K,X){return[e.filter(W,K,X),e.filter(W,U=>!K(U),X)]}e.split=S;function j(W,K=!1,X=[],U){let A=X.slice(),O=W(T=>{A?A.push(T):xe.fire(T)});U&&U.add(O);let $=()=>{A==null||A.forEach(T=>xe.fire(T)),A=null},xe=new Ce({onWillAddFirstListener(){O||(O=W(T=>xe.fire(T)),U&&U.add(O))},onDidAddFirstListener(){A&&(K?setTimeout($):$())},onDidRemoveLastListener(){O&&O.dispose(),O=null}});return U&&U.add(xe),xe.event}e.buffer=j;function R(W,K){return(X,U,A)=>{let O=K(new N);return W(function($){let xe=O.evaluate($);xe!==E&&X.call(U,xe)},void 0,A)}}e.chain=R;let E=Symbol("HaltChainable");class N{constructor(){this.steps=[]}map(K){return this.steps.push(K),this}forEach(K){return this.steps.push(X=>(K(X),X)),this}filter(K){return this.steps.push(X=>K(X)?X:E),this}reduce(K,X){let U=X;return this.steps.push(A=>(U=K(U,A),U)),this}latch(K=(X,U)=>X===U){let X=!0,U;return this.steps.push(A=>{let O=X||!K(A,U);return X=!1,U=A,O?A:E}),this}evaluate(K){for(let X of this.steps)if(K=X(K),K===E)break;return K}}function I(W,K,X=U=>U){let U=(...xe)=>$.fire(X(...xe)),A=()=>W.on(K,U),O=()=>W.removeListener(K,U),$=new Ce({onWillAddFirstListener:A,onDidRemoveLastListener:O});return $.event}e.fromNodeEventEmitter=I;function te(W,K,X=U=>U){let U=(...xe)=>$.fire(X(...xe)),A=()=>W.addEventListener(K,U),O=()=>W.removeEventListener(K,U),$=new Ce({onWillAddFirstListener:A,onDidRemoveLastListener:O});return $.event}e.fromDOMEventEmitter=te;function F(W){return new Promise(K=>i(W)(K))}e.toPromise=F;function D(W){let K=new Ce;return W.then(X=>{K.fire(X)},()=>{K.fire(void 0)}).finally(()=>{K.dispose()}),K.event}e.fromPromise=D;function ie(W,K){return W(X=>K.fire(X))}e.forward=ie;function fe(W,K,X){return K(X),W(U=>K(U))}e.runAndSubscribe=fe;class Se{constructor(K,X){this._observable=K,this._counter=0,this._hasChanged=!1;let U={onWillAddFirstListener:()=>{K.addObserver(this)},onDidRemoveLastListener:()=>{K.removeObserver(this)}};this.emitter=new Ce(U),X&&X.add(this.emitter)}beginUpdate(K){this._counter++}handlePossibleChange(K){}handleChange(K,X){this._hasChanged=!0}endUpdate(K){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function H(W,K){return new Se(W,K).emitter.event}e.fromObservable=H;function ce(W){return(K,X,U)=>{let A=0,O=!1,$={beginUpdate(){A++},endUpdate(){A--,A===0&&(W.reportChanges(),O&&(O=!1,K.call(X)))},handlePossibleChange(){},handleChange(){O=!0}};W.addObserver($),W.reportChanges();let xe={dispose(){W.removeObserver($)}};return U instanceof Hs?U.add(xe):Array.isArray(U)&&U.push(xe),xe}}e.fromObservableLight=ce})(en||(en={}));var Vf=class Xf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Xf._idPool++}`,Xf.all.add(this)}start(t){this._stopWatch=new VC,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Vf.all=new Set,Vf._idPool=0;var XC=Vf,ZC=-1,Gy=class Yy{constructor(t,i,s=(Yy._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=s,this._warnCountdown=0}dispose(){var t;(t=this._stacks)==null||t.clear()}check(t,i){let s=this.threshold;if(s<=0||i{let o=this._stacks.get(t.value)||0;this._stacks.set(t.value,o-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,i=0;for(let[s,a]of this._stacks)(!t||i{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},KC=new YC;function gu(e){VC(e)||KC.onUnexpectedError(e)}var Wf="Canceled";function VC(e){return e instanceof XC?!0:e instanceof Error&&e.name===Wf&&e.message===Wf}var XC=class extends Error{constructor(){super(Wf),this.name=this.message}};function ZC(e){return new Error(`Illegal argument: ${e}`)}var mb=class Gf extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Gf)return t;let i=new Gf;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Yf=class qy extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,qy.prototype)}};function zn(e,t=0){return e[e.length-(1+t)]}var QC;(e=>{function t(o){return o<0}e.isLessThan=t;function i(o){return o<=0}e.isLessThanOrEqual=i;function s(o){return o>0}e.isGreaterThan=s;function a(o){return o===0}e.isNeitherLessOrGreaterThan=a,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(QC||(QC={}));function JC(e,t){let i=this,s=!1,a;return function(){return s||(s=!0,t||(a=e.apply(i,arguments))),a}}var Wy;(e=>{function t(te){return te&&typeof te=="object"&&typeof te[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function s(){return i}e.empty=s;function*a(te){yield te}e.single=a;function o(te){return t(te)?te:a(te)}e.wrap=o;function c(te){return te||i}e.from=c;function*h(te){for(let q=te.length-1;q>=0;q--)yield te[q]}e.reverse=h;function p(te){return!te||te[Symbol.iterator]().next().done===!0}e.isEmpty=p;function f(te){return te[Symbol.iterator]().next().value}e.first=f;function _(te,q){let R=0;for(let ie of te)if(q(ie,R++))return!0;return!1}e.some=_;function x(te,q){for(let R of te)if(q(R))return R}e.find=x;function*b(te,q){for(let R of te)q(R)&&(yield R)}e.filter=b;function*v(te,q){let R=0;for(let ie of te)yield q(ie,R++)}e.map=v;function*S(te,q){let R=0;for(let ie of te)yield*q(ie,R++)}e.flatMap=S;function*j(...te){for(let q of te)yield*q}e.concat=j;function D(te,q,R){let ie=R;for(let fe of te)ie=q(ie,fe);return ie}e.reduce=D;function*E(te,q,R=te.length){for(q<0&&(q+=te.length),R<0?R+=te.length:R>te.length&&(R=te.length);q1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function ek(...e){return ii(()=>ga(e))}function ii(e){return{dispose:JC(()=>{e()})}}var Gy=class Yy{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{ga(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?Yy.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),void 0)}};Gy.DISABLE_DISPOSED_WARNING=!1;var Hs=Gy,ht=class{constructor(){this._store=new Hs,this._store}dispose(){this._store.dispose()}_register(t){if(t===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(t)}};ht.None=Object.freeze({dispose(){}});var pl=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,(e=this._value)==null||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},is=typeof window=="object"?window:globalThis,Kf=class Vf{constructor(t){this.element=t,this.next=Vf.Undefined,this.prev=Vf.Undefined}};Kf.Undefined=new Kf(void 0);var ni=Kf,gb=class{constructor(){this._first=ni.Undefined,this._last=ni.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===ni.Undefined}clear(){let e=this._first;for(;e!==ni.Undefined;){let t=e.next;e.prev=ni.Undefined,e.next=ni.Undefined,e=t}this._first=ni.Undefined,this._last=ni.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new ni(e);if(this._first===ni.Undefined)this._first=i,this._last=i;else if(t){let a=this._last;this._last=i,i.prev=a,a.next=i}else{let a=this._first;this._first=i,i.next=a,a.prev=i}this._size+=1;let s=!1;return()=>{s||(s=!0,this._remove(i))}}shift(){if(this._first!==ni.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==ni.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==ni.Undefined&&e.next!==ni.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===ni.Undefined&&e.next===ni.Undefined?(this._first=ni.Undefined,this._last=ni.Undefined):e.next===ni.Undefined?(this._last=this._last.prev,this._last.next=ni.Undefined):e.prev===ni.Undefined&&(this._first=this._first.next,this._first.prev=ni.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==ni.Undefined;)yield e.element,e=e.next}},tk=globalThis.performance&&typeof globalThis.performance.now=="function",ik=class Ky{static create(t){return new Ky(t)}constructor(t){this._now=tk&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},en;(e=>{e.None=()=>ht.None;function t(F,G){return x(F,()=>{},0,void 0,!0,void 0,G)}e.defer=t;function i(F){return(G,Y=null,U)=>{let A=!1,z;return z=F($=>{if(!A)return z?z.dispose():A=!0,G.call(Y,$)},null,U),A&&z.dispose(),z}}e.once=i;function s(F,G,Y){return f((U,A=null,z)=>F($=>U.call(A,G($)),null,z),Y)}e.map=s;function a(F,G,Y){return f((U,A=null,z)=>F($=>{G($),U.call(A,$)},null,z),Y)}e.forEach=a;function o(F,G,Y){return f((U,A=null,z)=>F($=>G($)&&U.call(A,$),null,z),Y)}e.filter=o;function c(F){return F}e.signal=c;function h(...F){return(G,Y=null,U)=>{let A=ek(...F.map(z=>z($=>G.call(Y,$))));return _(A,U)}}e.any=h;function p(F,G,Y,U){let A=Y;return s(F,z=>(A=G(A,z),A),U)}e.reduce=p;function f(F,G){let Y,U={onWillAddFirstListener(){Y=F(A.fire,A)},onDidRemoveLastListener(){Y==null||Y.dispose()}},A=new we(U);return G==null||G.add(A),A.event}function _(F,G){return G instanceof Array?G.push(F):G&&G.add(F),F}function x(F,G,Y=100,U=!1,A=!1,z,$){let ge,T,M,V=0,C,X={leakWarningThreshold:z,onWillAddFirstListener(){ge=F(le=>{V++,T=G(T,le),U&&!M&&(se.fire(T),T=void 0),C=()=>{let K=T;T=void 0,M=void 0,(!U||V>1)&&se.fire(K),V=0},typeof Y=="number"?(clearTimeout(M),M=setTimeout(C,Y)):M===void 0&&(M=0,queueMicrotask(C))})},onWillRemoveListener(){A&&V>0&&(C==null||C())},onDidRemoveLastListener(){C=void 0,ge.dispose()}},se=new we(X);return $==null||$.add(se),se.event}e.debounce=x;function b(F,G=0,Y){return e.debounce(F,(U,A)=>U?(U.push(A),U):[A],G,void 0,!0,void 0,Y)}e.accumulate=b;function v(F,G=(U,A)=>U===A,Y){let U=!0,A;return o(F,z=>{let $=U||!G(z,A);return U=!1,A=z,$},Y)}e.latch=v;function S(F,G,Y){return[e.filter(F,G,Y),e.filter(F,U=>!G(U),Y)]}e.split=S;function j(F,G=!1,Y=[],U){let A=Y.slice(),z=F(T=>{A?A.push(T):ge.fire(T)});U&&U.add(z);let $=()=>{A==null||A.forEach(T=>ge.fire(T)),A=null},ge=new we({onWillAddFirstListener(){z||(z=F(T=>ge.fire(T)),U&&U.add(z))},onDidAddFirstListener(){A&&(G?setTimeout($):$())},onDidRemoveLastListener(){z&&z.dispose(),z=null}});return U&&U.add(ge),ge.event}e.buffer=j;function D(F,G){return(Y,U,A)=>{let z=G(new N);return F(function($){let ge=z.evaluate($);ge!==E&&Y.call(U,ge)},void 0,A)}}e.chain=D;let E=Symbol("HaltChainable");class N{constructor(){this.steps=[]}map(G){return this.steps.push(G),this}forEach(G){return this.steps.push(Y=>(G(Y),Y)),this}filter(G){return this.steps.push(Y=>G(Y)?Y:E),this}reduce(G,Y){let U=Y;return this.steps.push(A=>(U=G(U,A),U)),this}latch(G=(Y,U)=>Y===U){let Y=!0,U;return this.steps.push(A=>{let z=Y||!G(A,U);return Y=!1,U=A,z?A:E}),this}evaluate(G){for(let Y of this.steps)if(G=Y(G),G===E)break;return G}}function I(F,G,Y=U=>U){let U=(...ge)=>$.fire(Y(...ge)),A=()=>F.on(G,U),z=()=>F.removeListener(G,U),$=new we({onWillAddFirstListener:A,onDidRemoveLastListener:z});return $.event}e.fromNodeEventEmitter=I;function te(F,G,Y=U=>U){let U=(...ge)=>$.fire(Y(...ge)),A=()=>F.addEventListener(G,U),z=()=>F.removeEventListener(G,U),$=new we({onWillAddFirstListener:A,onDidRemoveLastListener:z});return $.event}e.fromDOMEventEmitter=te;function q(F){return new Promise(G=>i(F)(G))}e.toPromise=q;function R(F){let G=new we;return F.then(Y=>{G.fire(Y)},()=>{G.fire(void 0)}).finally(()=>{G.dispose()}),G.event}e.fromPromise=R;function ie(F,G){return F(Y=>G.fire(Y))}e.forward=ie;function fe(F,G,Y){return G(Y),F(U=>G(U))}e.runAndSubscribe=fe;class be{constructor(G,Y){this._observable=G,this._counter=0,this._hasChanged=!1;let U={onWillAddFirstListener:()=>{G.addObserver(this)},onDidRemoveLastListener:()=>{G.removeObserver(this)}};this.emitter=new we(U),Y&&Y.add(this.emitter)}beginUpdate(G){this._counter++}handlePossibleChange(G){}handleChange(G,Y){this._hasChanged=!0}endUpdate(G){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function B(F,G){return new be(F,G).emitter.event}e.fromObservable=B;function ne(F){return(G,Y,U)=>{let A=0,z=!1,$={beginUpdate(){A++},endUpdate(){A--,A===0&&(F.reportChanges(),z&&(z=!1,G.call(Y)))},handlePossibleChange(){},handleChange(){z=!0}};F.addObserver($),F.reportChanges();let ge={dispose(){F.removeObserver($)}};return U instanceof Hs?U.add(ge):Array.isArray(U)&&U.push(ge),ge}}e.fromObservableLight=ne})(en||(en={}));var Xf=class Zf{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Zf._idPool++}`,Zf.all.add(this)}start(t){this._stopWatch=new ik,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Xf.all=new Set,Xf._idPool=0;var nk=Xf,rk=-1,Vy=class Xy{constructor(t,i,s=(Xy._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=s,this._warnCountdown=0}dispose(){var t;(t=this._stacks)==null||t.clear()}check(t,i){let s=this.threshold;if(s<=0||i{let o=this._stacks.get(t.value)||0;this._stacks.set(t.value,o-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,i=0;for(let[s,a]of this._stacks)(!t||i{var h,p,f,_,x;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let b=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(b);let v=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],S=new tk(`${b}. HINT: Stack shows most frequent listener (${v[1]}-times)`,v[0]);return(((h=this._options)==null?void 0:h.onListenerError)||gu)(S),ut.None}if(this._disposed)return ut.None;i&&(t=t.bind(i));let a=new tf(t),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(a.stack=JC.create(),o=this._leakageMon.check(a.stack,this._size+1)),this._listeners?this._listeners instanceof tf?(this._deliveryQueue??(this._deliveryQueue=new sk),this._listeners=[this._listeners,a]):this._listeners.push(a):((f=(p=this._options)==null?void 0:p.onWillAddFirstListener)==null||f.call(p,this),this._listeners=a,(x=(_=this._options)==null?void 0:_.onDidAddFirstListener)==null||x.call(_,this)),this._size++;let c=ii(()=>{o==null||o(),this._removeListener(a)});return s instanceof Hs?s.add(c):Array.isArray(s)&&s.push(c),c}),this._event}_removeListener(t){var o,c,h,p;if((c=(o=this._options)==null?void 0:o.onWillRemoveListener)==null||c.call(o,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(p=(h=this._options)==null?void 0:h.onDidRemoveLastListener)==null||p.call(h,this),this._size=0;return}let i=this._listeners,s=i.indexOf(t);if(s===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,i[s]=void 0;let a=this._deliveryQueue.current===this;if(this._size*nk<=i.length){let f=0;for(let _=0;_0}},sk=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Zf=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new Ce,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new Ce,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,i){if(this.getZoomLevel(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToZoomLevel.set(s,t),this._onDidChangeZoomLevel.fire(s)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,i){this.mapWindowIdToZoomFactor.set(this.getWindowId(i),t)}setFullscreen(t,i){if(this.isFullscreen(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToFullScreen.set(s,t),this._onDidChangeFullscreen.fire(s)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};Zf.INSTANCE=new Zf;var qp=Zf;function ak(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}qp.INSTANCE.onDidChangeZoomLevel;function lk(e){return qp.INSTANCE.getZoomFactor(e)}qp.INSTANCE.onDidChangeFullscreen;var _l=typeof navigator=="object"?navigator.userAgent:"",Qf=_l.indexOf("Firefox")>=0,ok=_l.indexOf("AppleWebKit")>=0,Wp=_l.indexOf("Chrome")>=0,ck=!Wp&&_l.indexOf("Safari")>=0;_l.indexOf("Electron/")>=0;_l.indexOf("Android")>=0;var nf=!1;if(typeof is.matchMedia=="function"){let e=is.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=is.matchMedia("(display-mode: fullscreen)");nf=e.matches,ak(is,e,({matches:i})=>{nf&&t.matches||(nf=i)})}var cl="en",Jf=!1,ep=!1,xu=!1,Vy=!1,eu,_u=cl,mb=cl,uk,dr,ma=globalThis,Ji,ky;typeof ma.vscode<"u"&&typeof ma.vscode.process<"u"?Ji=ma.vscode.process:typeof process<"u"&&typeof((ky=process==null?void 0:process.versions)==null?void 0:ky.node)=="string"&&(Ji=process);var Ey,hk=typeof((Ey=Ji==null?void 0:Ji.versions)==null?void 0:Ey.electron)=="string",dk=hk&&(Ji==null?void 0:Ji.type)==="renderer",Ny;if(typeof Ji=="object"){Jf=Ji.platform==="win32",ep=Ji.platform==="darwin",xu=Ji.platform==="linux",xu&&Ji.env.SNAP&&Ji.env.SNAP_REVISION,Ji.env.CI||Ji.env.BUILD_ARTIFACTSTAGINGDIRECTORY,eu=cl,_u=cl;let e=Ji.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);eu=t.userLocale,mb=t.osLocale,_u=t.resolvedLanguage||cl,uk=(Ny=t.languagePack)==null?void 0:Ny.translationsConfigFile}catch{}Vy=!0}else typeof navigator=="object"&&!dk?(dr=navigator.userAgent,Jf=dr.indexOf("Windows")>=0,ep=dr.indexOf("Macintosh")>=0,(dr.indexOf("Macintosh")>=0||dr.indexOf("iPad")>=0||dr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,xu=dr.indexOf("Linux")>=0,(dr==null?void 0:dr.indexOf("Mobi"))>=0,_u=globalThis._VSCODE_NLS_LANGUAGE||cl,eu=navigator.language.toLowerCase(),mb=eu):console.error("Unable to resolve platform.");var Xy=Jf,Rr=ep,fk=xu,gb=Vy,Dr=dr,Ms=_u,pk;(e=>{function t(){return Ms}e.value=t;function i(){return Ms.length===2?Ms==="en":Ms.length>=3?Ms[0]==="e"&&Ms[1]==="n"&&Ms[2]==="-":!1}e.isDefaultVariant=i;function s(){return Ms==="en"}e.isDefault=s})(pk||(pk={}));var mk=typeof ma.postMessage=="function"&&!ma.importScripts;(()=>{if(mk){let e=[];ma.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let s=0,a=e.length;s{let s=++t;e.push({id:s,callback:i}),ma.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var gk=!!(Dr&&Dr.indexOf("Chrome")>=0);Dr&&Dr.indexOf("Firefox")>=0;!gk&&Dr&&Dr.indexOf("Safari")>=0;Dr&&Dr.indexOf("Edg/")>=0;Dr&&Dr.indexOf("Android")>=0;var il=typeof navigator=="object"?navigator:{};gb||document.queryCommandSupported&&document.queryCommandSupported("copy")||il&&il.clipboard&&il.clipboard.writeText,gb||il&&il.clipboard&&il.clipboard.readText;var Gp=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},rf=new Gp,xb=new Gp,_b=new Gp,xk=new Array(230),Zy;(e=>{function t(h){return rf.keyCodeToStr(h)}e.toString=t;function i(h){return rf.strToKeyCode(h)}e.fromString=i;function s(h){return xb.keyCodeToStr(h)}e.toUserSettingsUS=s;function a(h){return _b.keyCodeToStr(h)}e.toUserSettingsGeneral=a;function o(h){return xb.strToKeyCode(h)||_b.strToKeyCode(h)}e.fromUserSettings=o;function c(h){if(h>=98&&h<=113)return null;switch(h){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return rf.keyCodeToStr(h)}e.toElectronAccelerator=c})(Zy||(Zy={}));var _k=class Qy{constructor(t,i,s,a,o){this.ctrlKey=t,this.shiftKey=i,this.altKey=s,this.metaKey=a,this.keyCode=o}equals(t){return t instanceof Qy&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",i=this.shiftKey?"1":"0",s=this.altKey?"1":"0",a=this.metaKey?"1":"0";return`K${t}${i}${s}${a}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new bk([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},bk=class{constructor(e){if(e.length===0)throw qC("chords");this.chords=e}getHashCode(){let e="";for(let t=0,i=this.chords.length;t{function t(i){return i===e.None||i===e.Cancelled||i instanceof jk?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:en.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Jy})})(Nk||(Nk={}));var jk=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Jy:(this._emitter||(this._emitter=new Ce),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Yp=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new Gf("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Gf("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},Tk=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){var e;(e=this.disposable)==null||e.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new Gf("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=ii(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},Ak;(e=>{async function t(s){let a,o=await Promise.all(s.map(c=>c.then(h=>h,h=>{a||(a=h)})));if(typeof a<"u")throw a;return o}e.settled=t;function i(s){return new Promise(async(a,o)=>{try{await s(a,o)}catch(c){o(c)}})}e.withAsyncBody=i})(Ak||(Ak={}));var Sb=class ir{static fromArray(t){return new ir(i=>{i.emitMany(t)})}static fromPromise(t){return new ir(async i=>{i.emitMany(await t)})}static fromPromises(t){return new ir(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new ir(async i=>{await Promise.all(t.map(async s=>{for await(let a of s)i.emitOne(a)}))})}constructor(t,i){this._state=0,this._results=[],this._error=null,this._onReturn=i,this._onStateChanged=new Ce,queueMicrotask(async()=>{let s={emitOne:a=>this.emitOne(a),emitMany:a=>this.emitMany(a),reject:a=>this.reject(a)};try{await Promise.resolve(t(s)),this.resolve()}catch(a){this.reject(a)}finally{s.emitOne=void 0,s.emitMany=void 0,s.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t{var i;return(i=this._onReturn)==null||i.call(this),{done:!0,value:void 0}}}}static map(t,i){return new ir(async s=>{for await(let a of t)s.emitOne(i(a))})}map(t){return ir.map(this,t)}static filter(t,i){return new ir(async s=>{for await(let a of t)i(a)&&s.emitOne(a)})}filter(t){return ir.filter(this,t)}static coalesce(t){return ir.filter(t,i=>!!i)}coalesce(){return ir.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return ir.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};Sb.EMPTY=Sb.fromArray([]);var{getWindow:Tr,getWindowId:Rk,onDidRegisterWindow:Dk}=(function(){let e=new Map,t={window:is,disposables:new Hs};e.set(is.vscodeWindowId,t);let i=new Ce,s=new Ce,a=new Ce;function o(c,h){return(typeof c=="number"?e.get(c):void 0)??(h?t:void 0)}return{onDidRegisterWindow:i.event,onWillUnregisterWindow:a.event,onDidUnregisterWindow:s.event,registerWindow(c){if(e.has(c.vscodeWindowId))return ut.None;let h=new Hs,p={window:c,disposables:h.add(new Hs)};return e.set(c.vscodeWindowId,p),h.add(ii(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Xe(c,Bi.BEFORE_UNLOAD,()=>{a.fire(c)})),i.fire(p),h},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(c){return c.vscodeWindowId},hasWindow(c){return e.has(c)},getWindowById:o,getWindow(c){var f;let h=c;if((f=h==null?void 0:h.ownerDocument)!=null&&f.defaultView)return h.ownerDocument.defaultView.window;let p=c;return p!=null&&p.view?p.view.window:is},getDocument(c){return Tr(c).document}}})(),Mk=class{constructor(e,t,i,s){this._node=e,this._type=t,this._handler=i,this._options=s||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function Xe(e,t,i,s){return new Mk(e,t,i,s)}var wb=function(e,t,i,s){return Xe(e,t,i,s)},Kp,Bk=class extends Tk{constructor(e){super(),this.defaultTarget=e&&Tr(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Cb=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){gu(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,s=new Map,a=o=>{i.set(o,!1);let c=e.get(o)??[];for(t.set(o,c),e.set(o,[]),s.set(o,!0);c.length>0;)c.sort(Cb.sort),c.shift().execute();s.set(o,!1)};Kp=(o,c,h=0)=>{let p=Rk(o),f=new Cb(c,h),_=e.get(p);return _||(_=[],e.set(p,_)),_.push(f),i.get(p)||(i.set(p,!0),o.requestAnimationFrame(()=>a(p))),f}})();function Lk(e){let t=e.getBoundingClientRect(),i=Tr(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var Bi={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},Ok=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=Sn(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Sn(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Sn(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Sn(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Sn(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Sn(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Sn(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Sn(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Sn(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Sn(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Sn(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Sn(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Sn(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Sn(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Sn(e){return typeof e=="number"?`${e}px`:e}function Eo(e){return new Ok(e)}var e0=class{constructor(){this._hooks=new Hs,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,s,a){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=a;let o=e;try{e.setPointerCapture(t),this._hooks.add(ii(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=Tr(e)}this._hooks.add(Xe(o,Bi.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Xe(o,Bi.POINTER_UP,c=>this.stopMonitoring(!0)))}};function zk(e,t,i){let s=null,a=null;if(typeof i.value=="function"?(s="value",a=i.value,a.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof i.get=="function"&&(s="get",a=i.get),!a)throw new Error("not supported");let o=`$memoize$${t}`;i[s]=function(...c){return this.hasOwnProperty(o)||Object.defineProperty(this,o,{configurable:!1,enumerable:!1,writable:!1,value:a.apply(this,c)}),this[o]}}var Nr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Nr||(Nr={}));var yo=class nn extends ut{constructor(){super(),this.dispatched=!1,this.targets=new pb,this.ignoreTargets=new pb,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(en.runAndSubscribe(Dk,({window:t,disposables:i})=>{i.add(Xe(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(Xe(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(Xe(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:is,disposables:this._store}))}static addTarget(t){if(!nn.isTouchDevice())return ut.None;nn.INSTANCE||(nn.INSTANCE=new nn);let i=nn.INSTANCE.targets.push(t);return ii(i)}static ignoreTarget(t){if(!nn.isTouchDevice())return ut.None;nn.INSTANCE||(nn.INSTANCE=new nn);let i=nn.INSTANCE.ignoreTargets.push(t);return ii(i)}static isTouchDevice(){return"ontouchstart"in is||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let s=0,a=t.targetTouches.length;s=nn.HOLD_DELAY&&Math.abs(p.initialPageX-On(p.rollingPageX))<30&&Math.abs(p.initialPageY-On(p.rollingPageY))<30){let _=this.newGestureEvent(Nr.Contextmenu,p.initialTarget);_.pageX=On(p.rollingPageX),_.pageY=On(p.rollingPageY),this.dispatchEvent(_)}else if(a===1){let _=On(p.rollingPageX),x=On(p.rollingPageY),b=On(p.rollingTimestamps)-p.rollingTimestamps[0],v=_-p.rollingPageX[0],S=x-p.rollingPageY[0],j=[...this.targets].filter(R=>p.initialTarget instanceof Node&&R.contains(p.initialTarget));this.inertia(t,j,s,Math.abs(v)/b,v>0?1:-1,_,Math.abs(S)/b,S>0?1:-1,x)}this.dispatchEvent(this.newGestureEvent(Nr.End,p.initialTarget)),delete this.activeTouches[h.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,i){let s=document.createEvent("CustomEvent");return s.initEvent(t,!1,!0),s.initialTarget=i,s.tapCount=0,s}dispatchEvent(t){if(t.type===Nr.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>nn.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===Nr.Change||t.type===Nr.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let s of this.ignoreTargets)if(s.contains(t.initialTarget))return;let i=[];for(let s of this.targets)if(s.contains(t.initialTarget)){let a=0,o=t.initialTarget;for(;o&&o!==s;)a++,o=o.parentElement;i.push([a,s])}i.sort((s,a)=>s[0]-a[0]);for(let[s,a]of i)a.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,s,a,o,c,h,p,f){this.handle=Kp(t,()=>{let _=Date.now(),x=_-s,b=0,v=0,S=!0;a+=nn.SCROLL_FRICTION*x,h+=nn.SCROLL_FRICTION*x,a>0&&(S=!1,b=o*a*x),h>0&&(S=!1,v=p*h*x);let j=this.newGestureEvent(Nr.Change);j.translationX=b,j.translationY=v,i.forEach(R=>R.dispatchEvent(j)),S||this.inertia(t,i,_,a,o,c+b,h,p,f+v)})}onTouchMove(t){let i=Date.now();for(let s=0,a=t.changedTouches.length;s3&&(c.rollingPageX.shift(),c.rollingPageY.shift(),c.rollingTimestamps.shift()),c.rollingPageX.push(o.pageX),c.rollingPageY.push(o.pageY),c.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};yo.SCROLL_FRICTION=-.005,yo.HOLD_DELAY=700,yo.CLEAR_TAP_COUNT_TIME=400,ci([zk],yo,"isTouchDevice",1);var Pk=yo,Vp=class extends ut{onclick(e,t){this._register(Xe(e,Bi.CLICK,i=>t(new tu(Tr(e),i))))}onmousedown(e,t){this._register(Xe(e,Bi.MOUSE_DOWN,i=>t(new tu(Tr(e),i))))}onmouseover(e,t){this._register(Xe(e,Bi.MOUSE_OVER,i=>t(new tu(Tr(e),i))))}onmouseleave(e,t){this._register(Xe(e,Bi.MOUSE_LEAVE,i=>t(new tu(Tr(e),i))))}onkeydown(e,t){this._register(Xe(e,Bi.KEY_DOWN,i=>t(new bb(i))))}onkeyup(e,t){this._register(Xe(e,Bi.KEY_UP,i=>t(new bb(i))))}oninput(e,t){this._register(Xe(e,Bi.INPUT,t))}onblur(e,t){this._register(Xe(e,Bi.BLUR,t))}onfocus(e,t){this._register(Xe(e,Bi.FOCUS,t))}onchange(e,t){this._register(Xe(e,Bi.CHANGE,t))}ignoreGesture(e){return Pk.ignoreTarget(e)}},kb=11,Ik=class extends Vp{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=kb+"px",this.domNode.style.height=kb+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new e0),this._register(wb(this.bgDomNode,Bi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(wb(this.domNode,Bi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new Bk),this._pointerdownScheduleRepeatTimer=this._register(new Yp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Tr(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},Hk=class tp{constructor(t,i,s,a,o,c,h){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,s=s|0,a=a|0,o=o|0,c=c|0,h=h|0),this.rawScrollLeft=a,this.rawScrollTop=h,i<0&&(i=0),a+i>s&&(a=s-i),a<0&&(a=0),o<0&&(o=0),h+o>c&&(h=c-o),h<0&&(h=0),this.width=i,this.scrollWidth=s,this.scrollLeft=a,this.height=o,this.scrollHeight=c,this.scrollTop=h}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,i){return new tp(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new tp(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,i){let s=this.width!==t.width,a=this.scrollWidth!==t.scrollWidth,o=this.scrollLeft!==t.scrollLeft,c=this.height!==t.height,h=this.scrollHeight!==t.scrollHeight,p=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:s,scrollWidthChanged:a,scrollLeftChanged:o,heightChanged:c,scrollHeightChanged:h,scrollTopChanged:p}}},Uk=class extends ut{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Hk(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){var s;let i=this._state.withScrollDimensions(e,t);this._setState(i,!!this._smoothScrolling),(s=this._smoothScrolling)==null||s.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let s;t?s=new Nb(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):s=this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=s}else{let i=this._state.withScrollPosition(e);this._smoothScrolling=Nb.start(this._state,i,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},Eb=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function sf(e,t){let i=t-e;return function(s){return e+i*qk(s)}}function $k(e,t,i){return function(s){return s2.5*s){let a,o;return t{var e;(e=this._domNode)==null||e.setClassName(this._visibleClassName)},0))}_hide(e){var t;this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,(t=this._domNode)==null||t.setClassName(this._invisibleClassName+(e?" fade":"")))}},Gk=140,t0=class extends Vp{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new Wk(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new e0),this._shouldRender=!0,this.domNode=Eo(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(Xe(this.domNode.domNode,Bi.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Ik(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=Eo(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof s=="number"&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Xe(this.slider.domNode,Bi.POINTER_DOWN,a=>{a.button===0&&(a.preventDefault(),this._sliderPointerDown(a))})),this.onclick(this.slider.domNode,a=>{a.leftButton&&a.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,i=t+this._scrollbarState.getSliderPosition(),s=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),a=this._sliderPointerPosition(e);i<=a&&a<=s?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,i=e.offsetY;else{let a=Lk(this.domNode.domNode);t=e.pageX-a.left,i=e.pageY-a.top}let s=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(s):this._scrollbarState.getDesiredScrollPositionFromOffset(s)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),s=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,a=>{let o=this._sliderOrthogonalPointerPosition(a),c=Math.abs(o-i);if(Xy&&c>Gk){this._setDesiredScrollPositionNow(s.getScrollPosition());return}let h=this._sliderPointerPosition(a)-t;this._setDesiredScrollPositionNow(s.getDesiredScrollPositionFromDelta(h))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},i0=class np{constructor(t,i,s,a,o,c){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(s),this._arrowSize=Math.round(t),this._visibleSize=a,this._scrollSize=o,this._scrollPosition=c,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new np(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,s,a,o){let c=Math.max(0,s-t),h=Math.max(0,c-2*i),p=a>0&&a>s;if(!p)return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(h),computedSliderRatio:0,computedSliderPosition:0};let f=Math.round(Math.max(20,Math.floor(s*h/a))),_=(h-f)/(a-s),x=o*_;return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(f),computedSliderRatio:_,computedSliderPosition:Math.round(x)}}_refreshComputedValues(){let t=np._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,s=this._scrollPosition;return i0&&Math.abs(t.deltaY)>0)return 1;let s=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(s+=.25),i){let a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),c=Math.abs(i.deltaX),h=Math.abs(i.deltaY),p=Math.max(Math.min(a,c),1),f=Math.max(Math.min(o,h),1),_=Math.max(a,c),x=Math.max(o,h);_%p===0&&x%f===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};rp.INSTANCE=new rp;var Zk=rp,Qk=class extends Vp{constructor(e,t,i){super(),this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new Ce),this.onWillScroll=this._onWillScroll.event,this._options=e2(t),this._scrollable=i,this._register(this._scrollable.onScroll(a=>{this._onWillScroll.fire(a),this._onDidScroll(a),this._onScroll.fire(a)}));let s={onMouseWheel:a=>this._onMouseWheel(a),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new Kk(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new Yk(this._scrollable,this._options,s)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=Eo(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Eo(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Eo(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,a=>this._onMouseOver(a)),this.onmouseleave(this._listenOnDomNode,a=>this._onMouseLeave(a)),this._hideTimeout=this._register(new Yp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=ga(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Rr&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new yb(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=ga(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new yb(i))};this._mouseWheelToDispose.push(Xe(this._listenOnDomNode,Bi.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=Zk.INSTANCE;t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let o=e.deltaY*this._options.mouseWheelScrollSensitivity,c=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&c+o===0?c=o=0:Math.abs(o)>=Math.abs(c)?c=0:o=0),this._options.flipAxes&&([o,c]=[c,o]);let h=!Rr&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||h)&&!c&&(c=o,o=0),e.browserEvent&&e.browserEvent.altKey&&(c=c*this._options.fastScrollSensitivity,o=o*this._options.fastScrollSensitivity);let p=this._scrollable.getFutureScrollPosition(),f={};if(o){let _=jb*o,x=p.scrollTop-(_<0?Math.floor(_):Math.ceil(_));this._verticalScrollbar.writeScrollPosition(f,x)}if(c){let _=jb*c,x=p.scrollLeft-(_<0?Math.floor(_):Math.ceil(_));this._horizontalScrollbar.writeScrollPosition(f,x)}f=this._scrollable.validateScrollPosition(f),(p.scrollLeft!==f.scrollLeft||p.scrollTop!==f.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(f):this._scrollable.setScrollPositionNow(f),i=!0)}let s=i;!s&&this._options.alwaysConsumeMouseWheel&&(s=!0),!s&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(s=!0),s&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,i=e.scrollLeft>0,s=i?" left":"",a=t?" top":"",o=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${s}`),this._topShadowDomNode.setClassName(`shadow${a}`),this._topLeftShadowDomNode.setClassName(`shadow${o}${a}${s}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),Vk)}},Jk=class extends Qk{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function e2(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Rr&&(t.className+=" mac"),t}var sp=class extends ut{constructor(e,t,i,s,a,o,c,h){super(),this._bufferService=i,this._optionsService=c,this._renderService=h,this._onRequestScrollLines=this._register(new Ce),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let p=this._register(new Uk({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:f=>Kp(s.window,f)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new Jk(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},p)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(a.onProtocolChange(f=>{this._scrollableElement.updateOptions({handleMouseWheel:!(f&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(en.runAndSubscribe(o.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=o.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(ii(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(ii(()=>this._styleElement.remove())),this._register(en.runAndSubscribe(o.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${o.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${o.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${o.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` -`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(f=>this._handleScroll(f)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){var e;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:((e=this._optionsService.rawOptions.overviewRuler)==null?void 0:e.width)||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};sp=ci([De(2,pn),De(3,ns),De(4,Oy),De(5,xl),De(6,mn),De(7,rs)],sp);var ap=class extends ut{constructor(e,t,i,s,a){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=a,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(o=>this._removeDecoration(o))),this._register(ii(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){var s;let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",((s=e==null?void 0:e.options)==null?void 0:s.layer)==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=i?`${i*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){var t;(t=this._decorationElements.get(e))==null||t.remove(),this._decorationElements.delete(e),e.dispose()}};ap=ci([De(1,pn),De(2,ns),De(3,Io),De(4,rs)],ap);var t2=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},kr={full:0,left:0,center:0,right:0},Bs={full:0,left:0,center:0,right:0},co={full:0,left:0,center:0,right:0},ju=class extends ut{constructor(e,t,i,s,a,o,c,h){var f;super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=s,this._renderService=a,this._optionsService=o,this._themeService=c,this._coreBrowserService=h,this._colorZoneStore=new t2,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),(f=this._viewportElement.parentElement)==null||f.insertBefore(this._canvas,this._viewportElement),this._register(ii(()=>{var _;return(_=this._canvas)==null?void 0:_.remove()}));let p=this._canvas.getContext("2d");if(p)this._ctx=p;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){var e;return((e=this._optionsService.options.overviewRuler)==null?void 0:e.width)||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);Bs.full=this._canvas.width,Bs.left=e,Bs.center=t,Bs.right=e,this._refreshDrawHeightConstants(),co.full=1,co.left=1,co.center=1+Bs.left,co.right=1+Bs.left+Bs.center}_refreshDrawHeightConstants(){kr.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);kr.left=t,kr.center=t,kr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(co[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-kr[e.position||"full"]/2),Bs[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+kr[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};ju=ci([De(2,pn),De(3,Io),De(4,rs),De(5,mn),De(6,xl),De(7,ns)],ju);var me;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=` -`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(me||(me={}));var bu;(e=>(e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"))(bu||(bu={}));var n0;(e=>e.ST=`${me.ESC}\\`)(n0||(n0={}));var lp=class{constructor(e,t,i,s,a,o){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=a,this._renderService=o,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.lengththis.updateCompositionElements(!0),0)}}};lp=ci([De(2,pn),De(3,mn),De(4,ba),De(5,rs)],lp);var Li=0,Oi=0,zi=0,li=0,Tb={css:"#00000000",rgba:0},wi;(e=>{function t(a,o,c,h){return h!==void 0?`#${oa(a)}${oa(o)}${oa(c)}${oa(h)}`:`#${oa(a)}${oa(o)}${oa(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(wi||(wi={}));var Qt;(e=>{function t(p,f){if(li=(f.rgba&255)/255,li===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,j=p.rgba>>8&255;Li=v+Math.round((_-v)*li),Oi=S+Math.round((x-S)*li),zi=j+Math.round((b-j)*li);let R=wi.toCss(Li,Oi,zi),E=wi.toRgba(Li,Oi,zi);return{css:R,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=vu.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return wi.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Li,Oi,zi]=vu.toChannels(f),{css:wi.toCss(Li,Oi,zi),rgba:f}}e.opaque=a;function o(p,f){return li=Math.round(f*255),[Li,Oi,zi]=vu.toChannels(p.rgba),{css:wi.toCss(Li,Oi,zi,li),rgba:wi.toRgba(Li,Oi,zi,li)}}e.opacity=o;function c(p,f){return li=p.rgba&255,o(p,li*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(Qt||(Qt={}));var ri;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d",{willReadFrequently:!0});o&&(t=o,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return Li=parseInt(a.slice(1,2).repeat(2),16),Oi=parseInt(a.slice(2,3).repeat(2),16),zi=parseInt(a.slice(3,4).repeat(2),16),wi.toColor(Li,Oi,zi);case 5:return Li=parseInt(a.slice(1,2).repeat(2),16),Oi=parseInt(a.slice(2,3).repeat(2),16),zi=parseInt(a.slice(3,4).repeat(2),16),li=parseInt(a.slice(4,5).repeat(2),16),wi.toColor(Li,Oi,zi,li);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let o=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(o)return Li=parseInt(o[1]),Oi=parseInt(o[2]),zi=parseInt(o[3]),li=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),wi.toColor(Li,Oi,zi,li);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Li,Oi,zi,li]=t.getImageData(0,0,1,1).data,li!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:wi.toRgba(Li,Oi,zi,li),css:a}}e.toColor=s})(ri||(ri={}));var hn;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,a,o){let c=s/255,h=a/255,p=o/255,f=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4),_=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4),x=p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4);return f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(hn||(hn={}));var vu;(e=>{function t(c,h){if(li=(h&255)/255,li===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Li=x+Math.round((p-x)*li),Oi=b+Math.round((f-b)*li),zi=v+Math.round((_-v)*li),wi.toRgba(Li,Oi,zi)}e.blend=t;function i(c,h,p){let f=hn.relativeLuminance(c>>8),_=hn.relativeLuminance(h>>8);if(Qr(f,_)>8));if(S>8));return S>R?v:j}return v}let x=a(c,h,p),b=Qr(f,hn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Qr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,x));for(;j0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),j=Qr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Qr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,x));for(;j>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(vu||(vu={}));function oa(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Qr(e,t){return e1){let _=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x<_.length;x++)i.push(_[x])}a=f,c=o,h=this._workCell.fg,p=this._workCell.bg}o+=this._workCell.getChars().length||Is.length}if(this._bufferService.cols-a>1){let f=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_=H,O=K,$=this._workCell;if(b.length>0&&K===b[0][0]&&A){let be=b.shift(),tt=this._isCellInSelection(be[0],t);for(N=be[0]+1;N=be[1]),A?(U=!0,$=new i2(this._workCell,e.translateToString(!0,be[0],be[1]),be[1]-be[0]),O=be[1]-1,X=$.getWidth()):H=be[1]}let xe=this._isCellInSelection(K,t),T=i&&K===o,M=W&&K>=f&&K<=_,G=!1;this._decorationService.forEachDecorationAtCell(K,t,void 0,be=>{G=!0});let C=$.getChars()||Is;if(C===" "&&($.isUnderline()||$.isOverline())&&(C=" "),Se=X*h-p.get(C,$.isBold(),$.isItalic()),!j)j=this._document.createElement("span");else if(R&&(xe&&fe||!xe&&!fe&&$.bg===I)&&(xe&&fe&&v.selectionForeground||$.fg===te)&&$.extended.ext===F&&M===D&&Se===ie&&!T&&!U&&!G&&A){$.isInvisible()?E+=Is:E+=C,R++;continue}else R&&(j.textContent=E),j=this._document.createElement("span"),R=0,E="";if(I=$.bg,te=$.fg,F=$.extended.ext,D=M,ie=Se,fe=xe,U&&o>=K&&o<=O&&(o=K),!this._coreService.isCursorHidden&&T&&this._coreService.isCursorInitialized){if(ce.push("xterm-cursor"),this._coreBrowserService.isFocused)c&&ce.push("xterm-cursor-blink"),ce.push(s==="bar"?"xterm-cursor-bar":s==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(a)switch(a){case"outline":ce.push("xterm-cursor-outline");break;case"block":ce.push("xterm-cursor-block");break;case"bar":ce.push("xterm-cursor-bar");break;case"underline":ce.push("xterm-cursor-underline");break}}if($.isBold()&&ce.push("xterm-bold"),$.isItalic()&&ce.push("xterm-italic"),$.isDim()&&ce.push("xterm-dim"),$.isInvisible()?E=Is:E=$.getChars()||Is,$.isUnderline()&&(ce.push(`xterm-underline-${$.extended.underlineStyle}`),E===" "&&(E=" "),!$.isUnderlineColorDefault()))if($.isUnderlineColorRGB())j.style.textDecorationColor=`rgb(${Po.toColorRGB($.getUnderlineColor()).join(",")})`;else{let be=$.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&$.isBold()&&be<8&&(be+=8),j.style.textDecorationColor=v.ansi[be].css}$.isOverline()&&(ce.push("xterm-overline"),E===" "&&(E=" ")),$.isStrikethrough()&&ce.push("xterm-strikethrough"),M&&(j.style.textDecoration="underline");let V=$.getFgColor(),ne=$.getFgColorMode(),ae=$.getBgColor(),Y=$.getBgColorMode(),he=!!$.isInverse();if(he){let be=V;V=ae,ae=be;let tt=ne;ne=Y,Y=tt}let _e,Be,Le=!1;this._decorationService.forEachDecorationAtCell(K,t,void 0,be=>{be.options.layer!=="top"&&Le||(be.backgroundColorRGB&&(Y=50331648,ae=be.backgroundColorRGB.rgba>>8&16777215,_e=be.backgroundColorRGB),be.foregroundColorRGB&&(ne=50331648,V=be.foregroundColorRGB.rgba>>8&16777215,Be=be.foregroundColorRGB),Le=be.options.layer==="top")}),!Le&&xe&&(_e=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,ae=_e.rgba>>8&16777215,Y=50331648,Le=!0,v.selectionForeground&&(ne=50331648,V=v.selectionForeground.rgba>>8&16777215,Be=v.selectionForeground)),Le&&ce.push("xterm-decoration-top");let je;switch(Y){case 16777216:case 33554432:je=v.ansi[ae],ce.push(`xterm-bg-${ae}`);break;case 50331648:je=wi.toColor(ae>>16,ae>>8&255,ae&255),this._addStyle(j,`background-color:#${Ab((ae>>>0).toString(16),"0",6)}`);break;case 0:default:he?(je=v.foreground,ce.push("xterm-bg-257")):je=v.background}switch(_e||$.isDim()&&(_e=Qt.multiplyOpacity(je,.5)),ne){case 16777216:case 33554432:$.isBold()&&V<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(V+=8),this._applyMinimumContrast(j,je,v.ansi[V],$,_e,void 0)||ce.push(`xterm-fg-${V}`);break;case 50331648:let be=wi.toColor(V>>16&255,V>>8&255,V&255);this._applyMinimumContrast(j,je,be,$,_e,Be)||this._addStyle(j,`color:#${Ab(V.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(j,je,v.foreground,$,_e,Be)||he&&ce.push("xterm-fg-257")}ce.length&&(j.className=ce.join(" "),ce.length=0),!T&&!U&&!G&&A?R++:j.textContent=E,Se!==this.defaultSpacing&&(j.style.letterSpacing=`${Se}px`),x.push(j),K=O}return j&&R&&(j.textContent=E),x}_applyMinimumContrast(e,t,i,s,a,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||s2(s.getCode()))return!1;let c=this._getContrastCache(s),h;if(!a&&!o&&(h=c.getColor(t.rgba,i.rgba)),h===void 0){let p=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);h=Qt.ensureContrastRatio(a||t,o||i,p),c.setColor((a||t).rgba,(o||i).rgba,h??null)}return h?(this._addStyle(e,`color:${h.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,s=this._selectionEnd;return!i||!s?!1:this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t=i[0]&&e=i[0]}};op=ci([De(1,Iy),De(2,mn),De(3,ns),De(4,ba),De(5,Io),De(6,xl)],op);function Ab(e,t,i){for(;e.length0&&(this._flat[s]=c),c}let a=e;t&&(a+="B"),i&&(a+="I");let o=this._holey.get(a);if(o===void 0){let c=0;t&&(c|=1),i&&(c|=2),o=this._measure(e,c),o>0&&this._holey.set(a,o)}return o}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},o2=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,i,s=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1]){this.clear();return}let a=e.buffers.active.ydisp,o=t[1]-a,c=i[1]-a,h=Math.max(o,0),p=Math.min(c,e.rows-1);if(h>=e.rows||p<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=o,this.viewportEndRow=c,this.viewportCappedStartRow=h,this.viewportCappedEndRow=p,this.startCol=t[0],this.endCol=i[0]}isCellSelected(e,t,i){return this.hasSelection?(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i=this.startCol&&t=this.startCol):!1}};function c2(){return new o2}var af="xterm-dom-renderer-owner-",tr="xterm-rows",nu="xterm-fg-",Rb="xterm-bg-",uo="xterm-focus",ru="xterm-selection",u2=1,cp=class extends ut{constructor(e,t,i,s,a,o,c,h,p,f,_,x,b,v){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=s,this._viewportElement=a,this._helperContainer=o,this._linkifier2=c,this._charSizeService=p,this._optionsService=f,this._bufferService=_,this._coreService=x,this._coreBrowserService=b,this._themeService=v,this._terminalClass=u2++,this._rowElements=[],this._selectionRenderModel=c2(),this.onRequestRedraw=this._register(new Ce).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(tr),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(ru),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=a2(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(S=>this._injectCss(S))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(op,document),this._element.classList.add(af+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(S=>this._handleLinkHover(S))),this._register(this._linkifier2.onHideLinkUnderline(S=>this._handleLinkLeave(S))),this._register(ii(()=>{this._element.classList.remove(af+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new l2(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${tr} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${tr} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${tr} .xterm-dim { color: ${Qt.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let i=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,a=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% { box-shadow: none; }}`,t+=`@keyframes ${a} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${tr}.${uo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${tr}.${uo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${tr}.${uo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${a} 1s step-end infinite;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${ru} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${ru} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${ru} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${nu}${o} { color: ${c.css}; }${this._terminalSelector} .${nu}${o}.xterm-dim { color: ${Qt.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${Rb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${nu}257 { color: ${Qt.opaque(e.background).css}; }${this._terminalSelector} .${nu}257.xterm-dim { color: ${Qt.multiplyOpacity(Qt.opaque(e.background),.5).css}; }${this._terminalSelector} .${Rb}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let s=this._document.createElement("div");this._rowContainer.appendChild(s),this._rowElements.push(s)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(uo),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(uo),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let s=this._selectionRenderModel.viewportStartRow,a=this._selectionRenderModel.viewportEndRow,o=this._selectionRenderModel.viewportCappedStartRow,c=this._selectionRenderModel.viewportCappedEndRow,h=this._document.createDocumentFragment();if(i){let p=e[0]>t[0];h.appendChild(this._createSelectionElement(o,p?t[0]:e[0],p?e[0]:t[0],c-o+1))}else{let p=s===o?e[0]:0,f=o===a?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(o,p,f));let _=c-o-1;if(h.appendChild(this._createSelectionElement(o+1,0,this._bufferService.cols,_)),o!==c){let x=a===c?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(c,0,x))}}this._selectionContainer.appendChild(h)}_createSelectionElement(e,t,i,s=1){let a=this._document.createElement("div"),o=t*this.dimensions.css.cell.width,c=this.dimensions.css.cell.width*(i-t);return o+c>this.dimensions.css.canvas.width&&(c=this.dimensions.css.canvas.width-o),a.style.height=`${s*this.dimensions.css.cell.height}px`,a.style.top=`${e*this.dimensions.css.cell.height}px`,a.style.left=`${o}px`,a.style.width=`${c}px`,a}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let i=this._bufferService.buffer,s=i.ybase+i.y,a=Math.min(i.x,this._bufferService.cols-1),o=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,c=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,h=this._optionsService.rawOptions.cursorInactiveStyle;for(let p=e;p<=t;p++){let f=p+i.ydisp,_=this._rowElements[p],x=i.lines.get(f);if(!_||!x)break;_.replaceChildren(...this._rowFactory.createRow(x,f,f===s,c,h,a,o,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${af}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,a,o){i<0&&(e=0),s<0&&(t=0);let c=this._bufferService.rows-1;i=Math.max(Math.min(i,c),0),s=Math.max(Math.min(s,c),0),a=Math.min(a,this._bufferService.cols);let h=this._bufferService.buffer,p=h.ybase+h.y,f=Math.min(h.x,a-1),_=this._optionsService.rawOptions.cursorBlink,x=this._optionsService.rawOptions.cursorStyle,b=this._optionsService.rawOptions.cursorInactiveStyle;for(let v=i;v<=s;++v){let S=v+h.ydisp,j=this._rowElements[v],R=h.lines.get(S);if(!j||!R)break;j.replaceChildren(...this._rowFactory.createRow(R,S,S===p,x,b,f,_,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};cp=ci([De(7,$p),De(8,Iu),De(9,mn),De(10,pn),De(11,ba),De(12,ns),De(13,xl)],cp);var up=class extends ut{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new Ce),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new d2(this._optionsService))}catch{this._measureStrategy=this._register(new h2(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};up=ci([De(2,mn)],up);var r0=class extends ut{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},h2=class extends r0{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},d2=class extends r0{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},f2=class extends ut{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new p2(this._window)),this._onDprChange=this._register(new Ce),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new Ce),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(en.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Xe(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Xe(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},p2=class extends ut{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new pl),this._onDprChange=this._register(new Ce),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(ii(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Xe(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){var e;this._outerListener&&((e=this._resolutionMediaMatchList)==null||e.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},m2=class extends ut{constructor(){super(),this.linkProviders=[],this._register(ii(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function Xp(e,t,i){let s=i.getBoundingClientRect(),a=e.getComputedStyle(i),o=parseInt(a.getPropertyValue("padding-left")),c=parseInt(a.getPropertyValue("padding-top"));return[t.clientX-s.left-o,t.clientY-s.top-c]}function g2(e,t,i,s,a,o,c,h,p){if(!o)return;let f=Xp(e,t,i);if(f)return f[0]=Math.ceil((f[0]+(p?c/2:0))/c),f[1]=Math.ceil(f[1]/h),f[0]=Math.min(Math.max(f[0],1),s+(p?1:0)),f[1]=Math.min(Math.max(f[1],1),a),f}var hp=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,a){return g2(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,a)}getMouseReportCoords(e,t){let i=Xp(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};hp=ci([De(0,rs),De(1,Iu)],hp);var x2=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},s0={};NC(s0,{getSafariVersion:()=>b2,isChromeOS:()=>c0,isFirefox:()=>a0,isIpad:()=>v2,isIphone:()=>y2,isLegacyEdge:()=>_2,isLinux:()=>Zp,isMac:()=>Au,isNode:()=>Hu,isSafari:()=>l0,isWindows:()=>o0});var Hu=typeof process<"u"&&"title"in process,Ho=Hu?"node":navigator.userAgent,Uo=Hu?"node":navigator.platform,a0=Ho.includes("Firefox"),_2=Ho.includes("Edge"),l0=/^((?!chrome|android).)*safari/i.test(Ho);function b2(){if(!l0)return 0;let e=Ho.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Au=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Uo),v2=Uo==="iPad",y2=Uo==="iPhone",o0=["Windows","Win16","Win32","WinCE"].includes(Uo),Zp=Uo.indexOf("Linux")>=0,c0=/\bCrOS\b/.test(Ho),u0=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ia){s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),this._start();return}s=a}this.clear()}},S2=class extends u0{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},w2=class extends u0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Ru=!Hu&&"requestIdleCallback"in window?w2:S2,C2=class{constructor(){this._queue=new Ru}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},dp=class extends ut{constructor(e,t,i,s,a,o,c,h,p){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=s,this._coreService=a,this._coreBrowserService=h,this._renderer=this._register(new pl),this._pausedResizeTask=new C2,this._observerDisposable=this._register(new pl),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new Ce),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new Ce),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new Ce),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new Ce),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new x2((f,_)=>this._renderRows(f,_),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new k2(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(ii(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(c.onResize(()=>this._fullRefresh())),this._register(c.buffers.onBufferActivate(()=>{var f;return(f=this._renderer.value)==null?void 0:f.clear()})),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(o.onDecorationRegistered(()=>this._fullRefresh())),this._register(o.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(c.cols,c.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(c.buffer.y,c.buffer.y,!0))),this._register(p.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(f=>this._registerIntersectionObserver(f,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(s=>this._handleIntersectionChange(s[s.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=ii(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let s=this._syncOutputHandler.flush();s&&(e=Math.min(e,s.start),t=Math.max(t,s.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var e,t;this._renderer.value&&((t=(e=this._renderer.value).clearTextureAtlas)==null||t.call(e),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>{var i;return(i=this._renderer.value)==null?void 0:i.handleResize(e,t)}):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){var e;(e=this._renderer.value)==null||e.handleCharSizeChanged()}handleBlur(){var e;(e=this._renderer.value)==null||e.handleBlur()}handleFocus(){var e;(e=this._renderer.value)==null||e.handleFocus()}handleSelectionChanged(e,t,i){var s;this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,(s=this._renderer.value)==null||s.handleSelectionChanged(e,t,i)}handleCursorMove(){var e;(e=this._renderer.value)==null||e.handleCursorMove()}clear(){var e;(e=this._renderer.value)==null||e.clear()}};dp=ci([De(2,mn),De(3,Iu),De(4,ba),De(5,Io),De(6,pn),De(7,ns),De(8,xl)],dp);var k2=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function E2(e,t,i,s){let a=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return T2(a,o,e,t,i,s)+Uu(o,t,i,s)+A2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Do(Math.abs(a-e),Ro(c,s));c=o>t?"D":"C";let h=Math.abs(o-t),p=j2(o>t?e:a,i)+(h-1)*i.cols+1+N2(o>t?a:e);return Do(p,Ro(c,s))}function N2(e,t){return e-1}function j2(e,t){return t.cols-e}function T2(e,t,i,s,a,o){return Uu(t,s,a,o).length===0?"":Do(d0(e,t,e,t-xa(t,a),!1,a).length,Ro("D",o))}function Uu(e,t,i,s){let a=e-xa(e,i),o=t-xa(t,i),c=Math.abs(a-o)-R2(e,t,i);return Do(c,Ro(h0(e,t),s))}function A2(e,t,i,s,a,o){let c;Uu(t,s,a,o).length>0?c=s-xa(s,a):c=t;let h=s,p=D2(e,t,i,s,a,o);return Do(d0(e,c,i,h,p==="C",a).length,Ro(p,o))}function R2(e,t,i){var c;let s=0,a=e-xa(e,i),o=t-xa(t,i);for(let h=0;h=0&&e0?c=s-xa(s,a):c=t,e=i&&ct?"A":"B"}function d0(e,t,i,s,a,o){let c=e,h=t,p="";for(;(c!==i||h!==s)&&h>=0&&ho.cols-1?(p+=o.buffer.translateBufferLineToString(h,!1,e,c),c=0,e=0,h++):!a&&c<0&&(p+=o.buffer.translateBufferLineToString(h,!1,0,e+1),c=o.cols-1,e=c,h--);return p+o.buffer.translateBufferLineToString(h,!1,e,c)}function Ro(e,t){let i=t?"O":"[";return me.ESC+i+e}function Do(e,t){e=Math.floor(e);let i="";for(let s=0;sthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function Db(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var lf=50,B2=15,L2=50,O2=500,z2=" ",P2=new RegExp(z2,"g"),fp=class extends ut{constructor(e,t,i,s,a,o,c,h,p){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=a,this._mouseService=o,this._optionsService=c,this._renderService=h,this._coreBrowserService=p,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new sr,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new Ce),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new Ce),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new Ce),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new Ce),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=f=>this._handleMouseMove(f),this._mouseUpListener=f=>this._handleMouseUp(f),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(f=>this._handleTrim(f)),this._register(this._bufferService.buffers.onBufferActivate(f=>this._handleBufferActivate(f))),this.enable(),this._model=new M2(this._bufferService),this._activeSelectionMode=0,this._register(ii(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(f=>{f.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let i=this._bufferService.buffer,s=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let a=e[0]a.replace(P2," ")).join(o0?`\r +`))}},lk=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},ok=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},ck=0,nf=class{constructor(e){this.value=e,this.id=ck++}},uk=2,hk,we=class{constructor(t){var i,s,a,o;this._size=0,this._options=t,this._leakageMon=(i=this._options)!=null&&i.leakWarningThreshold?new sk((t==null?void 0:t.onListenerError)??gu,((s=this._options)==null?void 0:s.leakWarningThreshold)??rk):void 0,this._perfMon=(a=this._options)!=null&&a._profName?new nk(this._options._profName):void 0,this._deliveryQueue=(o=this._options)==null?void 0:o.deliveryQueue}dispose(){var t,i,s,a;this._disposed||(this._disposed=!0,((t=this._deliveryQueue)==null?void 0:t.current)===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),(s=(i=this._options)==null?void 0:i.onDidRemoveLastListener)==null||s.call(i),(a=this._leakageMon)==null||a.dispose())}get event(){return this._event??(this._event=(t,i,s)=>{var h,p,f,_,x;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let b=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(b);let v=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],S=new ok(`${b}. HINT: Stack shows most frequent listener (${v[1]}-times)`,v[0]);return(((h=this._options)==null?void 0:h.onListenerError)||gu)(S),ht.None}if(this._disposed)return ht.None;i&&(t=t.bind(i));let a=new nf(t),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(a.stack=ak.create(),o=this._leakageMon.check(a.stack,this._size+1)),this._listeners?this._listeners instanceof nf?(this._deliveryQueue??(this._deliveryQueue=new dk),this._listeners=[this._listeners,a]):this._listeners.push(a):((f=(p=this._options)==null?void 0:p.onWillAddFirstListener)==null||f.call(p,this),this._listeners=a,(x=(_=this._options)==null?void 0:_.onDidAddFirstListener)==null||x.call(_,this)),this._size++;let c=ii(()=>{o==null||o(),this._removeListener(a)});return s instanceof Hs?s.add(c):Array.isArray(s)&&s.push(c),c}),this._event}_removeListener(t){var o,c,h,p;if((c=(o=this._options)==null?void 0:o.onWillRemoveListener)==null||c.call(o,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(p=(h=this._options)==null?void 0:h.onDidRemoveLastListener)==null||p.call(h,this),this._size=0;return}let i=this._listeners,s=i.indexOf(t);if(s===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,i[s]=void 0;let a=this._deliveryQueue.current===this;if(this._size*uk<=i.length){let f=0;for(let _=0;_0}},dk=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Qf=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new we,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new we,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,i){if(this.getZoomLevel(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToZoomLevel.set(s,t),this._onDidChangeZoomLevel.fire(s)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,i){this.mapWindowIdToZoomFactor.set(this.getWindowId(i),t)}setFullscreen(t,i){if(this.isFullscreen(i)===t)return;let s=this.getWindowId(i);this.mapWindowIdToFullScreen.set(s,t),this._onDidChangeFullscreen.fire(s)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};Qf.INSTANCE=new Qf;var qp=Qf;function fk(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}qp.INSTANCE.onDidChangeZoomLevel;function pk(e){return qp.INSTANCE.getZoomFactor(e)}qp.INSTANCE.onDidChangeFullscreen;var _l=typeof navigator=="object"?navigator.userAgent:"",Jf=_l.indexOf("Firefox")>=0,mk=_l.indexOf("AppleWebKit")>=0,Wp=_l.indexOf("Chrome")>=0,gk=!Wp&&_l.indexOf("Safari")>=0;_l.indexOf("Electron/")>=0;_l.indexOf("Android")>=0;var rf=!1;if(typeof is.matchMedia=="function"){let e=is.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=is.matchMedia("(display-mode: fullscreen)");rf=e.matches,fk(is,e,({matches:i})=>{rf&&t.matches||(rf=i)})}var cl="en",ep=!1,tp=!1,xu=!1,Qy=!1,iu,_u=cl,xb=cl,xk,dr,ma=globalThis,Ji,jy;typeof ma.vscode<"u"&&typeof ma.vscode.process<"u"?Ji=ma.vscode.process:typeof process<"u"&&typeof((jy=process==null?void 0:process.versions)==null?void 0:jy.node)=="string"&&(Ji=process);var Ty,_k=typeof((Ty=Ji==null?void 0:Ji.versions)==null?void 0:Ty.electron)=="string",bk=_k&&(Ji==null?void 0:Ji.type)==="renderer",Ay;if(typeof Ji=="object"){ep=Ji.platform==="win32",tp=Ji.platform==="darwin",xu=Ji.platform==="linux",xu&&Ji.env.SNAP&&Ji.env.SNAP_REVISION,Ji.env.CI||Ji.env.BUILD_ARTIFACTSTAGINGDIRECTORY,iu=cl,_u=cl;let e=Ji.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);iu=t.userLocale,xb=t.osLocale,_u=t.resolvedLanguage||cl,xk=(Ay=t.languagePack)==null?void 0:Ay.translationsConfigFile}catch{}Qy=!0}else typeof navigator=="object"&&!bk?(dr=navigator.userAgent,ep=dr.indexOf("Windows")>=0,tp=dr.indexOf("Macintosh")>=0,(dr.indexOf("Macintosh")>=0||dr.indexOf("iPad")>=0||dr.indexOf("iPhone")>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0,xu=dr.indexOf("Linux")>=0,(dr==null?void 0:dr.indexOf("Mobi"))>=0,_u=globalThis._VSCODE_NLS_LANGUAGE||cl,iu=navigator.language.toLowerCase(),xb=iu):console.error("Unable to resolve platform.");var Jy=ep,Rr=tp,vk=xu,_b=Qy,Dr=dr,Ms=_u,yk;(e=>{function t(){return Ms}e.value=t;function i(){return Ms.length===2?Ms==="en":Ms.length>=3?Ms[0]==="e"&&Ms[1]==="n"&&Ms[2]==="-":!1}e.isDefaultVariant=i;function s(){return Ms==="en"}e.isDefault=s})(yk||(yk={}));var Sk=typeof ma.postMessage=="function"&&!ma.importScripts;(()=>{if(Sk){let e=[];ma.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let s=0,a=e.length;s{let s=++t;e.push({id:s,callback:i}),ma.postMessage({vscodeScheduleAsyncWork:s},"*")}}return e=>setTimeout(e)})();var wk=!!(Dr&&Dr.indexOf("Chrome")>=0);Dr&&Dr.indexOf("Firefox")>=0;!wk&&Dr&&Dr.indexOf("Safari")>=0;Dr&&Dr.indexOf("Edg/")>=0;Dr&&Dr.indexOf("Android")>=0;var il=typeof navigator=="object"?navigator:{};_b||document.queryCommandSupported&&document.queryCommandSupported("copy")||il&&il.clipboard&&il.clipboard.writeText,_b||il&&il.clipboard&&il.clipboard.readText;var Gp=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},sf=new Gp,bb=new Gp,vb=new Gp,Ck=new Array(230),e0;(e=>{function t(h){return sf.keyCodeToStr(h)}e.toString=t;function i(h){return sf.strToKeyCode(h)}e.fromString=i;function s(h){return bb.keyCodeToStr(h)}e.toUserSettingsUS=s;function a(h){return vb.keyCodeToStr(h)}e.toUserSettingsGeneral=a;function o(h){return bb.strToKeyCode(h)||vb.strToKeyCode(h)}e.fromUserSettings=o;function c(h){if(h>=98&&h<=113)return null;switch(h){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return sf.keyCodeToStr(h)}e.toElectronAccelerator=c})(e0||(e0={}));var kk=class t0{constructor(t,i,s,a,o){this.ctrlKey=t,this.shiftKey=i,this.altKey=s,this.metaKey=a,this.keyCode=o}equals(t){return t instanceof t0&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",i=this.shiftKey?"1":"0",s=this.altKey?"1":"0",a=this.metaKey?"1":"0";return`K${t}${i}${s}${a}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new Ek([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Ek=class{constructor(e){if(e.length===0)throw ZC("chords");this.chords=e}getHashCode(){let e="";for(let t=0,i=this.chords.length;t{function t(i){return i===e.None||i===e.Cancelled||i instanceof Lk?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:en.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:i0})})(Bk||(Bk={}));var Lk=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?i0:(this._emitter||(this._emitter=new we),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Yp=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new Yf("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Yf("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},Ok=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){var e;(e=this.disposable)==null||e.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new Yf("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let s=i.setInterval(()=>{e()},t);this.disposable=ii(()=>{i.clearInterval(s),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}},zk;(e=>{async function t(s){let a,o=await Promise.all(s.map(c=>c.then(h=>h,h=>{a||(a=h)})));if(typeof a<"u")throw a;return o}e.settled=t;function i(s){return new Promise(async(a,o)=>{try{await s(a,o)}catch(c){o(c)}})}e.withAsyncBody=i})(zk||(zk={}));var Cb=class ir{static fromArray(t){return new ir(i=>{i.emitMany(t)})}static fromPromise(t){return new ir(async i=>{i.emitMany(await t)})}static fromPromises(t){return new ir(async i=>{await Promise.all(t.map(async s=>i.emitOne(await s)))})}static merge(t){return new ir(async i=>{await Promise.all(t.map(async s=>{for await(let a of s)i.emitOne(a)}))})}constructor(t,i){this._state=0,this._results=[],this._error=null,this._onReturn=i,this._onStateChanged=new we,queueMicrotask(async()=>{let s={emitOne:a=>this.emitOne(a),emitMany:a=>this.emitMany(a),reject:a=>this.reject(a)};try{await Promise.resolve(t(s)),this.resolve()}catch(a){this.reject(a)}finally{s.emitOne=void 0,s.emitMany=void 0,s.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t{var i;return(i=this._onReturn)==null||i.call(this),{done:!0,value:void 0}}}}static map(t,i){return new ir(async s=>{for await(let a of t)s.emitOne(i(a))})}map(t){return ir.map(this,t)}static filter(t,i){return new ir(async s=>{for await(let a of t)i(a)&&s.emitOne(a)})}filter(t){return ir.filter(this,t)}static coalesce(t){return ir.filter(t,i=>!!i)}coalesce(){return ir.coalesce(this)}static async toPromise(t){let i=[];for await(let s of t)i.push(s);return i}toPromise(){return ir.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};Cb.EMPTY=Cb.fromArray([]);var{getWindow:Tr,getWindowId:Pk,onDidRegisterWindow:Ik}=(function(){let e=new Map,t={window:is,disposables:new Hs};e.set(is.vscodeWindowId,t);let i=new we,s=new we,a=new we;function o(c,h){return(typeof c=="number"?e.get(c):void 0)??(h?t:void 0)}return{onDidRegisterWindow:i.event,onWillUnregisterWindow:a.event,onDidUnregisterWindow:s.event,registerWindow(c){if(e.has(c.vscodeWindowId))return ht.None;let h=new Hs,p={window:c,disposables:h.add(new Hs)};return e.set(c.vscodeWindowId,p),h.add(ii(()=>{e.delete(c.vscodeWindowId),s.fire(c)})),h.add(Ze(c,Bi.BEFORE_UNLOAD,()=>{a.fire(c)})),i.fire(p),h},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(c){return c.vscodeWindowId},hasWindow(c){return e.has(c)},getWindowById:o,getWindow(c){var f;let h=c;if((f=h==null?void 0:h.ownerDocument)!=null&&f.defaultView)return h.ownerDocument.defaultView.window;let p=c;return p!=null&&p.view?p.view.window:is},getDocument(c){return Tr(c).document}}})(),Hk=class{constructor(e,t,i,s){this._node=e,this._type=t,this._handler=i,this._options=s||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};function Ze(e,t,i,s){return new Hk(e,t,i,s)}var kb=function(e,t,i,s){return Ze(e,t,i,s)},Kp,Uk=class extends Ok{constructor(e){super(),this.defaultTarget=e&&Tr(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Eb=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){gu(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,s=new Map,a=o=>{i.set(o,!1);let c=e.get(o)??[];for(t.set(o,c),e.set(o,[]),s.set(o,!0);c.length>0;)c.sort(Eb.sort),c.shift().execute();s.set(o,!1)};Kp=(o,c,h=0)=>{let p=Pk(o),f=new Eb(c,h),_=e.get(p);return _||(_=[],e.set(p,_)),_.push(f),i.get(p)||(i.set(p,!0),o.requestAnimationFrame(()=>a(p))),f}})();function $k(e){let t=e.getBoundingClientRect(),i=Tr(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}var Bi={CLICK:"click",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",KEY_DOWN:"keydown",KEY_UP:"keyup",BEFORE_UNLOAD:"beforeunload",CHANGE:"change",FOCUS:"focus",BLUR:"blur",INPUT:"input"},Fk=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=wn(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=wn(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=wn(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=wn(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=wn(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=wn(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=wn(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=wn(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=wn(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=wn(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=wn(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=wn(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=wn(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=wn(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function wn(e){return typeof e=="number"?`${e}px`:e}function jo(e){return new Fk(e)}var n0=class{constructor(){this._hooks=new Hs,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,s,a){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=s,this._onStopCallback=a;let o=e;try{e.setPointerCapture(t),this._hooks.add(ii(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{o=Tr(e)}this._hooks.add(Ze(o,Bi.POINTER_MOVE,c=>{if(c.buttons!==i){this.stopMonitoring(!0);return}c.preventDefault(),this._pointerMoveCallback(c)})),this._hooks.add(Ze(o,Bi.POINTER_UP,c=>this.stopMonitoring(!0)))}};function qk(e,t,i){let s=null,a=null;if(typeof i.value=="function"?(s="value",a=i.value,a.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof i.get=="function"&&(s="get",a=i.get),!a)throw new Error("not supported");let o=`$memoize$${t}`;i[s]=function(...c){return this.hasOwnProperty(o)||Object.defineProperty(this,o,{configurable:!1,enumerable:!1,writable:!1,value:a.apply(this,c)}),this[o]}}var Nr;(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Nr||(Nr={}));var yo=class nn extends ht{constructor(){super(),this.dispatched=!1,this.targets=new gb,this.ignoreTargets=new gb,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(en.runAndSubscribe(Ik,({window:t,disposables:i})=>{i.add(Ze(t.document,"touchstart",s=>this.onTouchStart(s),{passive:!1})),i.add(Ze(t.document,"touchend",s=>this.onTouchEnd(t,s))),i.add(Ze(t.document,"touchmove",s=>this.onTouchMove(s),{passive:!1}))},{window:is,disposables:this._store}))}static addTarget(t){if(!nn.isTouchDevice())return ht.None;nn.INSTANCE||(nn.INSTANCE=new nn);let i=nn.INSTANCE.targets.push(t);return ii(i)}static ignoreTarget(t){if(!nn.isTouchDevice())return ht.None;nn.INSTANCE||(nn.INSTANCE=new nn);let i=nn.INSTANCE.ignoreTargets.push(t);return ii(i)}static isTouchDevice(){return"ontouchstart"in is||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let s=0,a=t.targetTouches.length;s=nn.HOLD_DELAY&&Math.abs(p.initialPageX-zn(p.rollingPageX))<30&&Math.abs(p.initialPageY-zn(p.rollingPageY))<30){let _=this.newGestureEvent(Nr.Contextmenu,p.initialTarget);_.pageX=zn(p.rollingPageX),_.pageY=zn(p.rollingPageY),this.dispatchEvent(_)}else if(a===1){let _=zn(p.rollingPageX),x=zn(p.rollingPageY),b=zn(p.rollingTimestamps)-p.rollingTimestamps[0],v=_-p.rollingPageX[0],S=x-p.rollingPageY[0],j=[...this.targets].filter(D=>p.initialTarget instanceof Node&&D.contains(p.initialTarget));this.inertia(t,j,s,Math.abs(v)/b,v>0?1:-1,_,Math.abs(S)/b,S>0?1:-1,x)}this.dispatchEvent(this.newGestureEvent(Nr.End,p.initialTarget)),delete this.activeTouches[h.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,i){let s=document.createEvent("CustomEvent");return s.initEvent(t,!1,!0),s.initialTarget=i,s.tapCount=0,s}dispatchEvent(t){if(t.type===Nr.Tap){let i=new Date().getTime(),s=0;i-this._lastSetTapCountTime>nn.CLEAR_TAP_COUNT_TIME?s=1:s=2,this._lastSetTapCountTime=i,t.tapCount=s}else(t.type===Nr.Change||t.type===Nr.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let s of this.ignoreTargets)if(s.contains(t.initialTarget))return;let i=[];for(let s of this.targets)if(s.contains(t.initialTarget)){let a=0,o=t.initialTarget;for(;o&&o!==s;)a++,o=o.parentElement;i.push([a,s])}i.sort((s,a)=>s[0]-a[0]);for(let[s,a]of i)a.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,s,a,o,c,h,p,f){this.handle=Kp(t,()=>{let _=Date.now(),x=_-s,b=0,v=0,S=!0;a+=nn.SCROLL_FRICTION*x,h+=nn.SCROLL_FRICTION*x,a>0&&(S=!1,b=o*a*x),h>0&&(S=!1,v=p*h*x);let j=this.newGestureEvent(Nr.Change);j.translationX=b,j.translationY=v,i.forEach(D=>D.dispatchEvent(j)),S||this.inertia(t,i,_,a,o,c+b,h,p,f+v)})}onTouchMove(t){let i=Date.now();for(let s=0,a=t.changedTouches.length;s3&&(c.rollingPageX.shift(),c.rollingPageY.shift(),c.rollingTimestamps.shift()),c.rollingPageX.push(o.pageX),c.rollingPageY.push(o.pageY),c.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};yo.SCROLL_FRICTION=-.005,yo.HOLD_DELAY=700,yo.CLEAR_TAP_COUNT_TIME=400,ci([qk],yo,"isTouchDevice",1);var Wk=yo,Vp=class extends ht{onclick(e,t){this._register(Ze(e,Bi.CLICK,i=>t(new nu(Tr(e),i))))}onmousedown(e,t){this._register(Ze(e,Bi.MOUSE_DOWN,i=>t(new nu(Tr(e),i))))}onmouseover(e,t){this._register(Ze(e,Bi.MOUSE_OVER,i=>t(new nu(Tr(e),i))))}onmouseleave(e,t){this._register(Ze(e,Bi.MOUSE_LEAVE,i=>t(new nu(Tr(e),i))))}onkeydown(e,t){this._register(Ze(e,Bi.KEY_DOWN,i=>t(new yb(i))))}onkeyup(e,t){this._register(Ze(e,Bi.KEY_UP,i=>t(new yb(i))))}oninput(e,t){this._register(Ze(e,Bi.INPUT,t))}onblur(e,t){this._register(Ze(e,Bi.BLUR,t))}onfocus(e,t){this._register(Ze(e,Bi.FOCUS,t))}onchange(e,t){this._register(Ze(e,Bi.CHANGE,t))}ignoreGesture(e){return Wk.ignoreTarget(e)}},Nb=11,Gk=class extends Vp{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=Nb+"px",this.domNode.style.height=Nb+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new n0),this._register(kb(this.bgDomNode,Bi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(kb(this.domNode,Bi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new Uk),this._pointerdownScheduleRepeatTimer=this._register(new Yp)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Tr(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},Yk=class ip{constructor(t,i,s,a,o,c,h){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,s=s|0,a=a|0,o=o|0,c=c|0,h=h|0),this.rawScrollLeft=a,this.rawScrollTop=h,i<0&&(i=0),a+i>s&&(a=s-i),a<0&&(a=0),o<0&&(o=0),h+o>c&&(h=c-o),h<0&&(h=0),this.width=i,this.scrollWidth=s,this.scrollLeft=a,this.height=o,this.scrollHeight=c,this.scrollTop=h}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,i){return new ip(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new ip(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,i){let s=this.width!==t.width,a=this.scrollWidth!==t.scrollWidth,o=this.scrollLeft!==t.scrollLeft,c=this.height!==t.height,h=this.scrollHeight!==t.scrollHeight,p=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:s,scrollWidthChanged:a,scrollLeftChanged:o,heightChanged:c,scrollHeightChanged:h,scrollTopChanged:p}}},Kk=class extends ht{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new we),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Yk(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){var s;let i=this._state.withScrollDimensions(e,t);this._setState(i,!!this._smoothScrolling),(s=this._smoothScrolling)==null||s.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let s;t?s=new Tb(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):s=this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=s}else{let i=this._state.withScrollPosition(e);this._smoothScrolling=Tb.start(this._state,i,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},jb=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};function af(e,t){let i=t-e;return function(s){return e+i*Zk(s)}}function Vk(e,t,i){return function(s){return s2.5*s){let a,o;return t{var e;(e=this._domNode)==null||e.setClassName(this._visibleClassName)},0))}_hide(e){var t;this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,(t=this._domNode)==null||t.setClassName(this._invisibleClassName+(e?" fade":"")))}},Jk=140,r0=class extends Vp{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new Qk(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new n0),this._shouldRender=!0,this.domNode=jo(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(Ze(this.domNode.domNode,Bi.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new Gk(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,s){this.slider=jo(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof s=="number"&&this.slider.setHeight(s),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Ze(this.slider.domNode,Bi.POINTER_DOWN,a=>{a.button===0&&(a.preventDefault(),this._sliderPointerDown(a))})),this.onclick(this.slider.domNode,a=>{a.leftButton&&a.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,i=t+this._scrollbarState.getSliderPosition(),s=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),a=this._sliderPointerPosition(e);i<=a&&a<=s?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,i=e.offsetY;else{let a=$k(this.domNode.domNode);t=e.pageX-a.left,i=e.pageY-a.top}let s=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(s):this._scrollbarState.getDesiredScrollPositionFromOffset(s)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),s=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,a=>{let o=this._sliderOrthogonalPointerPosition(a),c=Math.abs(o-i);if(Jy&&c>Jk){this._setDesiredScrollPositionNow(s.getScrollPosition());return}let h=this._sliderPointerPosition(a)-t;this._setDesiredScrollPositionNow(s.getDesiredScrollPositionFromDelta(h))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},s0=class rp{constructor(t,i,s,a,o,c){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(s),this._arrowSize=Math.round(t),this._visibleSize=a,this._scrollSize=o,this._scrollPosition=c,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new rp(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,s,a,o){let c=Math.max(0,s-t),h=Math.max(0,c-2*i),p=a>0&&a>s;if(!p)return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(h),computedSliderRatio:0,computedSliderPosition:0};let f=Math.round(Math.max(20,Math.floor(s*h/a))),_=(h-f)/(a-s),x=o*_;return{computedAvailableSize:Math.round(c),computedIsNeeded:p,computedSliderSize:Math.round(f),computedSliderRatio:_,computedSliderPosition:Math.round(x)}}_refreshComputedValues(){let t=rp._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,s=this._scrollPosition;return i0&&Math.abs(t.deltaY)>0)return 1;let s=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(s+=.25),i){let a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),c=Math.abs(i.deltaX),h=Math.abs(i.deltaY),p=Math.max(Math.min(a,c),1),f=Math.max(Math.min(o,h),1),_=Math.max(a,c),x=Math.max(o,h);_%p===0&&x%f===0&&(s-=.5)}return Math.min(Math.max(s,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};sp.INSTANCE=new sp;var r2=sp,s2=class extends Vp{constructor(e,t,i){super(),this._onScroll=this._register(new we),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new we),this.onWillScroll=this._onWillScroll.event,this._options=l2(t),this._scrollable=i,this._register(this._scrollable.onScroll(a=>{this._onWillScroll.fire(a),this._onDidScroll(a),this._onScroll.fire(a)}));let s={onMouseWheel:a=>this._onMouseWheel(a),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new t2(this._scrollable,this._options,s)),this._horizontalScrollbar=this._register(new e2(this._scrollable,this._options,s)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=jo(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=jo(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=jo(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,a=>this._onMouseOver(a)),this.onmouseleave(this._listenOnDomNode,a=>this._onMouseLeave(a)),this._hideTimeout=this._register(new Yp),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=ga(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Rr&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new wb(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=ga(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new wb(i))};this._mouseWheelToDispose.push(Ze(this._listenOnDomNode,Bi.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){var a;if((a=e.browserEvent)!=null&&a.defaultPrevented)return;let t=r2.INSTANCE;t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let o=e.deltaY*this._options.mouseWheelScrollSensitivity,c=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&c+o===0?c=o=0:Math.abs(o)>=Math.abs(c)?c=0:o=0),this._options.flipAxes&&([o,c]=[c,o]);let h=!Rr&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||h)&&!c&&(c=o,o=0),e.browserEvent&&e.browserEvent.altKey&&(c=c*this._options.fastScrollSensitivity,o=o*this._options.fastScrollSensitivity);let p=this._scrollable.getFutureScrollPosition(),f={};if(o){let _=Ab*o,x=p.scrollTop-(_<0?Math.floor(_):Math.ceil(_));this._verticalScrollbar.writeScrollPosition(f,x)}if(c){let _=Ab*c,x=p.scrollLeft-(_<0?Math.floor(_):Math.ceil(_));this._horizontalScrollbar.writeScrollPosition(f,x)}f=this._scrollable.validateScrollPosition(f),(p.scrollLeft!==f.scrollLeft||p.scrollTop!==f.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(f):this._scrollable.setScrollPositionNow(f),i=!0)}let s=i;!s&&this._options.alwaysConsumeMouseWheel&&(s=!0),!s&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(s=!0),s&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,i=e.scrollLeft>0,s=i?" left":"",a=t?" top":"",o=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${s}`),this._topShadowDomNode.setClassName(`shadow${a}`),this._topLeftShadowDomNode.setClassName(`shadow${o}${a}${s}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),i2)}},a2=class extends s2{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function l2(e){let t={lazyRender:typeof e.lazyRender<"u"?e.lazyRender:!1,className:typeof e.className<"u"?e.className:"",useShadows:typeof e.useShadows<"u"?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<"u"?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<"u"?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<"u"?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<"u"?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<"u"?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<"u"?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<"u"?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<"u"?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<"u"?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<"u"?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<"u"?e.listenOnDomNode:null,horizontal:typeof e.horizontal<"u"?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<"u"?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<"u"?e.horizontalHasArrows:!1,vertical:typeof e.vertical<"u"?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<"u"?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<"u"?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<"u"?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<"u"?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<"u"?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<"u"?e.verticalSliderSize:t.verticalScrollbarSize,Rr&&(t.className+=" mac"),t}var ap=class extends ht{constructor(e,t,i,s,a,o,c,h){super(),this._bufferService=i,this._optionsService=c,this._renderService=h,this._onRequestScrollLines=this._register(new we),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let p=this._register(new Kk({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:f=>Kp(s.window,f)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new a2(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},p)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(a.onProtocolChange(f=>{this._scrollableElement.updateOptions({handleMouseWheel:!(f&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(en.runAndSubscribe(o.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=o.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(ii(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=s.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(ii(()=>this._styleElement.remove())),this._register(en.runAndSubscribe(o.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${o.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${o.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${o.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` +`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(f=>this._handleScroll(f)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){var e;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:((e=this._optionsService.rawOptions.overviewRuler)==null?void 0:e.width)||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};ap=ci([Re(2,mn),Re(3,ns),Re(4,Iy),Re(5,xl),Re(6,gn),Re(7,rs)],ap);var lp=class extends ht{constructor(e,t,i,s,a){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=a,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(o=>this._removeDecoration(o))),this._register(ii(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){var s;let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",((s=e==null?void 0:e.options)==null?void 0:s.layer)==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=i?`${i*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){var t;(t=this._decorationElements.get(e))==null||t.remove(),this._decorationElements.delete(e),e.dispose()}};lp=ci([Re(1,mn),Re(2,ns),Re(3,Uo),Re(4,rs)],lp);var o2=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},kr={full:0,left:0,center:0,right:0},Bs={full:0,left:0,center:0,right:0},co={full:0,left:0,center:0,right:0},ju=class extends ht{constructor(e,t,i,s,a,o,c,h){var f;super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=s,this._renderService=a,this._optionsService=o,this._themeService=c,this._coreBrowserService=h,this._colorZoneStore=new o2,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),(f=this._viewportElement.parentElement)==null||f.insertBefore(this._canvas,this._viewportElement),this._register(ii(()=>{var _;return(_=this._canvas)==null?void 0:_.remove()}));let p=this._canvas.getContext("2d");if(p)this._ctx=p;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){var e;return((e=this._optionsService.options.overviewRuler)==null?void 0:e.width)||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);Bs.full=this._canvas.width,Bs.left=e,Bs.center=t,Bs.right=e,this._refreshDrawHeightConstants(),co.full=1,co.left=1,co.center=1+Bs.left,co.right=1+Bs.left+Bs.center}_refreshDrawHeightConstants(){kr.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);kr.left=t,kr.center=t,kr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*kr.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(co[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-kr[e.position||"full"]/2),Bs[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+kr[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};ju=ci([Re(2,mn),Re(3,Uo),Re(4,rs),Re(5,gn),Re(6,xl),Re(7,ns)],ju);var me;(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=` +`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""))(me||(me={}));var bu;(e=>(e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"))(bu||(bu={}));var a0;(e=>e.ST=`${me.ESC}\\`)(a0||(a0={}));var op=class{constructor(e,t,i,s,a,o){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=a,this._renderService=o,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.lengththis.updateCompositionElements(!0),0)}}};op=ci([Re(2,mn),Re(3,gn),Re(4,ba),Re(5,rs)],op);var Li=0,Oi=0,zi=0,li=0,Rb={css:"#00000000",rgba:0},wi;(e=>{function t(a,o,c,h){return h!==void 0?`#${oa(a)}${oa(o)}${oa(c)}${oa(h)}`:`#${oa(a)}${oa(o)}${oa(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(wi||(wi={}));var Qt;(e=>{function t(p,f){if(li=(f.rgba&255)/255,li===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,j=p.rgba>>8&255;Li=v+Math.round((_-v)*li),Oi=S+Math.round((x-S)*li),zi=j+Math.round((b-j)*li);let D=wi.toCss(Li,Oi,zi),E=wi.toRgba(Li,Oi,zi);return{css:D,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=vu.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return wi.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Li,Oi,zi]=vu.toChannels(f),{css:wi.toCss(Li,Oi,zi),rgba:f}}e.opaque=a;function o(p,f){return li=Math.round(f*255),[Li,Oi,zi]=vu.toChannels(p.rgba),{css:wi.toCss(Li,Oi,zi,li),rgba:wi.toRgba(Li,Oi,zi,li)}}e.opacity=o;function c(p,f){return li=p.rgba&255,o(p,li*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(Qt||(Qt={}));var ri;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d",{willReadFrequently:!0});o&&(t=o,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return Li=parseInt(a.slice(1,2).repeat(2),16),Oi=parseInt(a.slice(2,3).repeat(2),16),zi=parseInt(a.slice(3,4).repeat(2),16),wi.toColor(Li,Oi,zi);case 5:return Li=parseInt(a.slice(1,2).repeat(2),16),Oi=parseInt(a.slice(2,3).repeat(2),16),zi=parseInt(a.slice(3,4).repeat(2),16),li=parseInt(a.slice(4,5).repeat(2),16),wi.toColor(Li,Oi,zi,li);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let o=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(o)return Li=parseInt(o[1]),Oi=parseInt(o[2]),zi=parseInt(o[3]),li=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),wi.toColor(Li,Oi,zi,li);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Li,Oi,zi,li]=t.getImageData(0,0,1,1).data,li!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:wi.toRgba(Li,Oi,zi,li),css:a}}e.toColor=s})(ri||(ri={}));var hn;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,a,o){let c=s/255,h=a/255,p=o/255,f=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4),_=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4),x=p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4);return f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(hn||(hn={}));var vu;(e=>{function t(c,h){if(li=(h&255)/255,li===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Li=x+Math.round((p-x)*li),Oi=b+Math.round((f-b)*li),zi=v+Math.round((_-v)*li),wi.toRgba(Li,Oi,zi)}e.blend=t;function i(c,h,p){let f=hn.relativeLuminance(c>>8),_=hn.relativeLuminance(h>>8);if(Qr(f,_)>8));if(S>8));return S>D?v:j}return v}let x=a(c,h,p),b=Qr(f,hn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Qr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,x));for(;j0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),j=Qr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Qr(hn.relativeLuminance2(b,v,S),hn.relativeLuminance2(f,_,x));for(;j>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(vu||(vu={}));function oa(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Qr(e,t){return e1){let _=this._getJoinedRanges(s,c,o,t,a);for(let x=0;x<_.length;x++)i.push(_[x])}a=f,c=o,h=this._workCell.fg,p=this._workCell.bg}o+=this._workCell.getChars().length||Is.length}if(this._bufferService.cols-a>1){let f=this._getJoinedRanges(s,c,o,t,a);for(let _=0;_=B,z=G,$=this._workCell;if(b.length>0&&G===b[0][0]&&A){let ke=b.shift(),Ue=this._isCellInSelection(ke[0],t);for(N=ke[0]+1;N=ke[1]),A?(U=!0,$=new c2(this._workCell,e.translateToString(!0,ke[0],ke[1]),ke[1]-ke[0]),z=ke[1]-1,Y=$.getWidth()):B=ke[1]}let ge=this._isCellInSelection(G,t),T=i&&G===o,M=F&&G>=f&&G<=_,V=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,ke=>{V=!0});let C=$.getChars()||Is;if(C===" "&&($.isUnderline()||$.isOverline())&&(C=" "),be=Y*h-p.get(C,$.isBold(),$.isItalic()),!j)j=this._document.createElement("span");else if(D&&(ge&&fe||!ge&&!fe&&$.bg===I)&&(ge&&fe&&v.selectionForeground||$.fg===te)&&$.extended.ext===q&&M===R&&be===ie&&!T&&!U&&!V&&A){$.isInvisible()?E+=Is:E+=C,D++;continue}else D&&(j.textContent=E),j=this._document.createElement("span"),D=0,E="";if(I=$.bg,te=$.fg,q=$.extended.ext,R=M,ie=be,fe=ge,U&&o>=G&&o<=z&&(o=G),!this._coreService.isCursorHidden&&T&&this._coreService.isCursorInitialized){if(ne.push("xterm-cursor"),this._coreBrowserService.isFocused)c&&ne.push("xterm-cursor-blink"),ne.push(s==="bar"?"xterm-cursor-bar":s==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(a)switch(a){case"outline":ne.push("xterm-cursor-outline");break;case"block":ne.push("xterm-cursor-block");break;case"bar":ne.push("xterm-cursor-bar");break;case"underline":ne.push("xterm-cursor-underline");break}}if($.isBold()&&ne.push("xterm-bold"),$.isItalic()&&ne.push("xterm-italic"),$.isDim()&&ne.push("xterm-dim"),$.isInvisible()?E=Is:E=$.getChars()||Is,$.isUnderline()&&(ne.push(`xterm-underline-${$.extended.underlineStyle}`),E===" "&&(E=" "),!$.isUnderlineColorDefault()))if($.isUnderlineColorRGB())j.style.textDecorationColor=`rgb(${Ho.toColorRGB($.getUnderlineColor()).join(",")})`;else{let ke=$.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&$.isBold()&&ke<8&&(ke+=8),j.style.textDecorationColor=v.ansi[ke].css}$.isOverline()&&(ne.push("xterm-overline"),E===" "&&(E=" ")),$.isStrikethrough()&&ne.push("xterm-strikethrough"),M&&(j.style.textDecoration="underline");let X=$.getFgColor(),se=$.getFgColorMode(),le=$.getBgColor(),K=$.getBgColorMode(),he=!!$.isInverse();if(he){let ke=X;X=le,le=ke;let Ue=se;se=K,K=Ue}let _e,Me,Le=!1;this._decorationService.forEachDecorationAtCell(G,t,void 0,ke=>{ke.options.layer!=="top"&&Le||(ke.backgroundColorRGB&&(K=50331648,le=ke.backgroundColorRGB.rgba>>8&16777215,_e=ke.backgroundColorRGB),ke.foregroundColorRGB&&(se=50331648,X=ke.foregroundColorRGB.rgba>>8&16777215,Me=ke.foregroundColorRGB),Le=ke.options.layer==="top")}),!Le&&ge&&(_e=this._coreBrowserService.isFocused?v.selectionBackgroundOpaque:v.selectionInactiveBackgroundOpaque,le=_e.rgba>>8&16777215,K=50331648,Le=!0,v.selectionForeground&&(se=50331648,X=v.selectionForeground.rgba>>8&16777215,Me=v.selectionForeground)),Le&&ne.push("xterm-decoration-top");let He;switch(K){case 16777216:case 33554432:He=v.ansi[le],ne.push(`xterm-bg-${le}`);break;case 50331648:He=wi.toColor(le>>16,le>>8&255,le&255),this._addStyle(j,`background-color:#${Db((le>>>0).toString(16),"0",6)}`);break;case 0:default:he?(He=v.foreground,ne.push("xterm-bg-257")):He=v.background}switch(_e||$.isDim()&&(_e=Qt.multiplyOpacity(He,.5)),se){case 16777216:case 33554432:$.isBold()&&X<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(X+=8),this._applyMinimumContrast(j,He,v.ansi[X],$,_e,void 0)||ne.push(`xterm-fg-${X}`);break;case 50331648:let ke=wi.toColor(X>>16&255,X>>8&255,X&255);this._applyMinimumContrast(j,He,ke,$,_e,Me)||this._addStyle(j,`color:#${Db(X.toString(16),"0",6)}`);break;case 0:default:this._applyMinimumContrast(j,He,v.foreground,$,_e,Me)||he&&ne.push("xterm-fg-257")}ne.length&&(j.className=ne.join(" "),ne.length=0),!T&&!U&&!V&&A?D++:j.textContent=E,be!==this.defaultSpacing&&(j.style.letterSpacing=`${be}px`),x.push(j),G=z}return j&&D&&(j.textContent=E),x}_applyMinimumContrast(e,t,i,s,a,o){if(this._optionsService.rawOptions.minimumContrastRatio===1||d2(s.getCode()))return!1;let c=this._getContrastCache(s),h;if(!a&&!o&&(h=c.getColor(t.rgba,i.rgba)),h===void 0){let p=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);h=Qt.ensureContrastRatio(a||t,o||i,p),c.setColor((a||t).rgba,(o||i).rgba,h??null)}return h?(this._addStyle(e,`color:${h.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,s=this._selectionEnd;return!i||!s?!1:this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t=i[0]&&e=i[0]}};cp=ci([Re(1,$y),Re(2,gn),Re(3,ns),Re(4,ba),Re(5,Uo),Re(6,xl)],cp);function Db(e,t,i){for(;e.length0&&(this._flat[s]=c),c}let a=e;t&&(a+="B"),i&&(a+="I");let o=this._holey.get(a);if(o===void 0){let c=0;t&&(c|=1),i&&(c|=2),o=this._measure(e,c),o>0&&this._holey.set(a,o)}return o}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},m2=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,i,s=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1]){this.clear();return}let a=e.buffers.active.ydisp,o=t[1]-a,c=i[1]-a,h=Math.max(o,0),p=Math.min(c,e.rows-1);if(h>=e.rows||p<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=o,this.viewportEndRow=c,this.viewportCappedStartRow=h,this.viewportCappedEndRow=p,this.startCol=t[0],this.endCol=i[0]}isCellSelected(e,t,i){return this.hasSelection?(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i=this.startCol&&t=this.startCol):!1}};function g2(){return new m2}var lf="xterm-dom-renderer-owner-",tr="xterm-rows",su="xterm-fg-",Mb="xterm-bg-",uo="xterm-focus",au="xterm-selection",x2=1,up=class extends ht{constructor(e,t,i,s,a,o,c,h,p,f,_,x,b,v){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=s,this._viewportElement=a,this._helperContainer=o,this._linkifier2=c,this._charSizeService=p,this._optionsService=f,this._bufferService=_,this._coreService=x,this._coreBrowserService=b,this._themeService=v,this._terminalClass=x2++,this._rowElements=[],this._selectionRenderModel=g2(),this.onRequestRedraw=this._register(new we).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(tr),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(au),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=f2(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(S=>this._injectCss(S))),this._injectCss(this._themeService.colors),this._rowFactory=h.createInstance(cp,document),this._element.classList.add(lf+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(S=>this._handleLinkHover(S))),this._register(this._linkifier2.onHideLinkUnderline(S=>this._handleLinkLeave(S))),this._register(ii(()=>{this._element.classList.remove(lf+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new p2(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${tr} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${tr} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${tr} .xterm-dim { color: ${Qt.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let i=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,a=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% { box-shadow: none; }}`,t+=`@keyframes ${a} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${tr}.${uo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${tr}.${uo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${tr}.${uo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${a} 1s step-end infinite;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${tr} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${au} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${au} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${au} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[o,c]of e.ansi.entries())t+=`${this._terminalSelector} .${su}${o} { color: ${c.css}; }${this._terminalSelector} .${su}${o}.xterm-dim { color: ${Qt.multiplyOpacity(c,.5).css}; }${this._terminalSelector} .${Mb}${o} { background-color: ${c.css}; }`;t+=`${this._terminalSelector} .${su}257 { color: ${Qt.opaque(e.background).css}; }${this._terminalSelector} .${su}257.xterm-dim { color: ${Qt.multiplyOpacity(Qt.opaque(e.background),.5).css}; }${this._terminalSelector} .${Mb}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let s=this._document.createElement("div");this._rowContainer.appendChild(s),this._rowElements.push(s)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(uo),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(uo),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let s=this._selectionRenderModel.viewportStartRow,a=this._selectionRenderModel.viewportEndRow,o=this._selectionRenderModel.viewportCappedStartRow,c=this._selectionRenderModel.viewportCappedEndRow,h=this._document.createDocumentFragment();if(i){let p=e[0]>t[0];h.appendChild(this._createSelectionElement(o,p?t[0]:e[0],p?e[0]:t[0],c-o+1))}else{let p=s===o?e[0]:0,f=o===a?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(o,p,f));let _=c-o-1;if(h.appendChild(this._createSelectionElement(o+1,0,this._bufferService.cols,_)),o!==c){let x=a===c?t[0]:this._bufferService.cols;h.appendChild(this._createSelectionElement(c,0,x))}}this._selectionContainer.appendChild(h)}_createSelectionElement(e,t,i,s=1){let a=this._document.createElement("div"),o=t*this.dimensions.css.cell.width,c=this.dimensions.css.cell.width*(i-t);return o+c>this.dimensions.css.canvas.width&&(c=this.dimensions.css.canvas.width-o),a.style.height=`${s*this.dimensions.css.cell.height}px`,a.style.top=`${e*this.dimensions.css.cell.height}px`,a.style.left=`${o}px`,a.style.width=`${c}px`,a}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let i=this._bufferService.buffer,s=i.ybase+i.y,a=Math.min(i.x,this._bufferService.cols-1),o=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,c=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,h=this._optionsService.rawOptions.cursorInactiveStyle;for(let p=e;p<=t;p++){let f=p+i.ydisp,_=this._rowElements[p],x=i.lines.get(f);if(!_||!x)break;_.replaceChildren(...this._rowFactory.createRow(x,f,f===s,c,h,a,o,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${lf}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,a,o){i<0&&(e=0),s<0&&(t=0);let c=this._bufferService.rows-1;i=Math.max(Math.min(i,c),0),s=Math.max(Math.min(s,c),0),a=Math.min(a,this._bufferService.cols);let h=this._bufferService.buffer,p=h.ybase+h.y,f=Math.min(h.x,a-1),_=this._optionsService.rawOptions.cursorBlink,x=this._optionsService.rawOptions.cursorStyle,b=this._optionsService.rawOptions.cursorInactiveStyle;for(let v=i;v<=s;++v){let S=v+h.ydisp,j=this._rowElements[v],D=h.lines.get(S);if(!j||!D)break;j.replaceChildren(...this._rowFactory.createRow(D,S,S===p,x,b,f,_,this.dimensions.css.cell.width,this._widthCache,o?v===i?e:0:-1,o?(v===s?t:a)-1:-1))}}};up=ci([Re(7,$p),Re(8,Hu),Re(9,gn),Re(10,mn),Re(11,ba),Re(12,ns),Re(13,xl)],up);var hp=class extends ht{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new we),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new b2(this._optionsService))}catch{this._measureStrategy=this._register(new _2(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};hp=ci([Re(2,gn)],hp);var l0=class extends ht{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},_2=class extends l0{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},b2=class extends l0{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},v2=class extends ht{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new y2(this._window)),this._onDprChange=this._register(new we),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new we),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(s=>this._screenDprMonitor.setWindow(s))),this._register(en.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Ze(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Ze(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},y2=class extends ht{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new pl),this._onDprChange=this._register(new we),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(ii(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Ze(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){var e;this._outerListener&&((e=this._resolutionMediaMatchList)==null||e.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},S2=class extends ht{constructor(){super(),this.linkProviders=[],this._register(ii(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function Xp(e,t,i){let s=i.getBoundingClientRect(),a=e.getComputedStyle(i),o=parseInt(a.getPropertyValue("padding-left")),c=parseInt(a.getPropertyValue("padding-top"));return[t.clientX-s.left-o,t.clientY-s.top-c]}function w2(e,t,i,s,a,o,c,h,p){if(!o)return;let f=Xp(e,t,i);if(f)return f[0]=Math.ceil((f[0]+(p?c/2:0))/c),f[1]=Math.ceil(f[1]/h),f[0]=Math.min(Math.max(f[0],1),s+(p?1:0)),f[1]=Math.min(Math.max(f[1],1),a),f}var dp=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,a){return w2(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,a)}getMouseReportCoords(e,t){let i=Xp(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};dp=ci([Re(0,rs),Re(1,Hu)],dp);var C2=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},o0={};BC(o0,{getSafariVersion:()=>E2,isChromeOS:()=>d0,isFirefox:()=>c0,isIpad:()=>N2,isIphone:()=>j2,isLegacyEdge:()=>k2,isLinux:()=>Zp,isMac:()=>Au,isNode:()=>Uu,isSafari:()=>u0,isWindows:()=>h0});var Uu=typeof process<"u"&&"title"in process,$o=Uu?"node":navigator.userAgent,Fo=Uu?"node":navigator.platform,c0=$o.includes("Firefox"),k2=$o.includes("Edge"),u0=/^((?!chrome|android).)*safari/i.test($o);function E2(){if(!u0)return 0;let e=$o.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var Au=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Fo),N2=Fo==="iPad",j2=Fo==="iPhone",h0=["Windows","Win16","Win32","WinCE"].includes(Fo),Zp=Fo.indexOf("Linux")>=0,d0=/\bCrOS\b/.test($o),f0=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ia){s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),this._start();return}s=a}this.clear()}},T2=class extends f0{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},A2=class extends f0{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Ru=!Uu&&"requestIdleCallback"in window?A2:T2,R2=class{constructor(){this._queue=new Ru}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},fp=class extends ht{constructor(e,t,i,s,a,o,c,h,p){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=s,this._coreService=a,this._coreBrowserService=h,this._renderer=this._register(new pl),this._pausedResizeTask=new R2,this._observerDisposable=this._register(new pl),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new we),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new we),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new we),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new we),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new C2((f,_)=>this._renderRows(f,_),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new D2(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(ii(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(c.onResize(()=>this._fullRefresh())),this._register(c.buffers.onBufferActivate(()=>{var f;return(f=this._renderer.value)==null?void 0:f.clear()})),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(o.onDecorationRegistered(()=>this._fullRefresh())),this._register(o.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(c.cols,c.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(c.buffer.y,c.buffer.y,!0))),this._register(p.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(f=>this._registerIntersectionObserver(f,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(s=>this._handleIntersectionChange(s[s.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=ii(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let s=this._syncOutputHandler.flush();s&&(e=Math.min(e,s.start),t=Math.max(t,s.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var e,t;this._renderer.value&&((t=(e=this._renderer.value).clearTextureAtlas)==null||t.call(e),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>{var i;return(i=this._renderer.value)==null?void 0:i.handleResize(e,t)}):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){var e;(e=this._renderer.value)==null||e.handleCharSizeChanged()}handleBlur(){var e;(e=this._renderer.value)==null||e.handleBlur()}handleFocus(){var e;(e=this._renderer.value)==null||e.handleFocus()}handleSelectionChanged(e,t,i){var s;this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,(s=this._renderer.value)==null||s.handleSelectionChanged(e,t,i)}handleCursorMove(){var e;(e=this._renderer.value)==null||e.handleCursorMove()}clear(){var e;(e=this._renderer.value)==null||e.clear()}};fp=ci([Re(2,gn),Re(3,Hu),Re(4,ba),Re(5,Uo),Re(6,mn),Re(7,ns),Re(8,xl)],fp);var D2=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function M2(e,t,i,s){let a=i.buffer.x,o=i.buffer.y;if(!i.buffer.hasScrollback)return O2(a,o,e,t,i,s)+$u(o,t,i,s)+z2(a,o,e,t,i,s);let c;if(o===t)return c=a>e?"D":"C",Bo(Math.abs(a-e),Mo(c,s));c=o>t?"D":"C";let h=Math.abs(o-t),p=L2(o>t?e:a,i)+(h-1)*i.cols+1+B2(o>t?a:e);return Bo(p,Mo(c,s))}function B2(e,t){return e-1}function L2(e,t){return t.cols-e}function O2(e,t,i,s,a,o){return $u(t,s,a,o).length===0?"":Bo(m0(e,t,e,t-xa(t,a),!1,a).length,Mo("D",o))}function $u(e,t,i,s){let a=e-xa(e,i),o=t-xa(t,i),c=Math.abs(a-o)-P2(e,t,i);return Bo(c,Mo(p0(e,t),s))}function z2(e,t,i,s,a,o){let c;$u(t,s,a,o).length>0?c=s-xa(s,a):c=t;let h=s,p=I2(e,t,i,s,a,o);return Bo(m0(e,c,i,h,p==="C",a).length,Mo(p,o))}function P2(e,t,i){var c;let s=0,a=e-xa(e,i),o=t-xa(t,i);for(let h=0;h=0&&e0?c=s-xa(s,a):c=t,e=i&&ct?"A":"B"}function m0(e,t,i,s,a,o){let c=e,h=t,p="";for(;(c!==i||h!==s)&&h>=0&&ho.cols-1?(p+=o.buffer.translateBufferLineToString(h,!1,e,c),c=0,e=0,h++):!a&&c<0&&(p+=o.buffer.translateBufferLineToString(h,!1,0,e+1),c=o.cols-1,e=c,h--);return p+o.buffer.translateBufferLineToString(h,!1,e,c)}function Mo(e,t){let i=t?"O":"[";return me.ESC+i+e}function Bo(e,t){e=Math.floor(e);let i="";for(let s=0;sthis._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function Bb(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var of=50,U2=15,$2=50,F2=500,q2=" ",W2=new RegExp(q2,"g"),pp=class extends ht{constructor(e,t,i,s,a,o,c,h,p){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=a,this._mouseService=o,this._optionsService=c,this._renderService=h,this._coreBrowserService=p,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new sr,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new we),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new we),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new we),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new we),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=f=>this._handleMouseMove(f),this._mouseUpListener=f=>this._handleMouseUp(f),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(f=>this._handleTrim(f)),this._register(this._bufferService.buffers.onBufferActivate(f=>this._handleBufferActivate(f))),this.enable(),this._model=new H2(this._bufferService),this._activeSelectionMode=0,this._register(ii(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(f=>{f.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let i=this._bufferService.buffer,s=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let a=e[0]a.replace(W2," ")).join(h0?`\r `:` -`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Zp&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s||!t?!1:this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s?!1:this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){var a,o;let i=(o=(a=this._linkifier.currentLink)==null?void 0:a.link)==null?void 0:o.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=Db(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let s=this._getMouseBufferCoords(e);return s?(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Xp(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-lf),lf),t/=lf,t/Math.abs(t)+Math.round(t*(B2-1)))}shouldForceSelection(e){return Au?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),L2)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Au&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){let a=e.loadCell(s,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:a>1&&t!==s&&(i+=a-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;let a=this._bufferService.buffer,o=a.lines.get(e[1]);if(!o)return;let c=a.translateBufferLineToString(e[1],!1),h=this._convertViewportColToCharacterIndex(o,e[0]),p=h,f=e[0]-h,_=0,x=0,b=0,v=0;if(c.charAt(h)===" "){for(;h>0&&c.charAt(h-1)===" ";)h--;for(;p1&&(v+=N-1,p+=N-1);R>0&&h>0&&!this._isCharWordSeparator(o.loadCell(R-1,this._workCell));){o.loadCell(R-1,this._workCell);let I=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,R--):I>1&&(b+=I-1,h-=I-1),h--,R--}for(;E1&&(v+=I-1,p+=I-1),p++,E++}}p++;let S=h+f-_+b,j=Math.min(this._bufferService.cols,p-h+_+x-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&S===0&&o.getCodePoint(0)!==32){let R=a.lines.get(e[1]-1);if(R&&o.isWrapped&&R.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(E){let N=this._bufferService.cols-E.start;S-=N,j+=N}}}if(s&&S+j===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let R=a.lines.get(e[1]+1);if(R!=null&&R.isWrapped&&R.getCodePoint(0)!==32){let E=this._getWordAt([0,e[1]+1],!1,!1,!0);E&&(j+=E.length)}}return{start:S,length:j}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Db(i,this._bufferService.cols)}};fp=ci([De(3,pn),De(4,ba),De(5,Fp),De(6,mn),De(7,rs),De(8,ns)],fp);var Mb=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},Bb=class{constructor(){this._color=new Mb,this._css=new Mb}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Ti=Object.freeze((()=>{let e=[ri.toColor("#2e3436"),ri.toColor("#cc0000"),ri.toColor("#4e9a06"),ri.toColor("#c4a000"),ri.toColor("#3465a4"),ri.toColor("#75507b"),ri.toColor("#06989a"),ri.toColor("#d3d7cf"),ri.toColor("#555753"),ri.toColor("#ef2929"),ri.toColor("#8ae234"),ri.toColor("#fce94f"),ri.toColor("#729fcf"),ri.toColor("#ad7fa8"),ri.toColor("#34e2e2"),ri.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:wi.toCss(s,a,o),rgba:wi.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:wi.toCss(s,s,s),rgba:wi.toRgba(s,s,s)})}return e})()),da=ri.toColor("#ffffff"),So=ri.toColor("#000000"),Lb=ri.toColor("#ffffff"),Ob=So,ho={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},I2=da,pp=class extends ut{constructor(e){super(),this._optionsService=e,this._contrastCache=new Bb,this._halfContrastCache=new Bb,this._onChangeColors=this._register(new Ce),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:da,background:So,cursor:Lb,cursorAccent:Ob,selectionForeground:void 0,selectionBackgroundTransparent:ho,selectionBackgroundOpaque:Qt.blend(So,ho),selectionInactiveBackgroundTransparent:ho,selectionInactiveBackgroundOpaque:Qt.blend(So,ho),scrollbarSliderBackground:Qt.opacity(da,.2),scrollbarSliderHoverBackground:Qt.opacity(da,.4),scrollbarSliderActiveBackground:Qt.opacity(da,.5),overviewRulerBorder:da,ansi:Ti.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=$t(e.foreground,da),t.background=$t(e.background,So),t.cursor=Qt.blend(t.background,$t(e.cursor,Lb)),t.cursorAccent=Qt.blend(t.background,$t(e.cursorAccent,Ob)),t.selectionBackgroundTransparent=$t(e.selectionBackground,ho),t.selectionBackgroundOpaque=Qt.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=$t(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Qt.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?$t(e.selectionForeground,Tb):void 0,t.selectionForeground===Tb&&(t.selectionForeground=void 0),Qt.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Qt.opacity(t.selectionBackgroundTransparent,.3)),Qt.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Qt.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=$t(e.scrollbarSliderBackground,Qt.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=$t(e.scrollbarSliderHoverBackground,Qt.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=$t(e.scrollbarSliderActiveBackground,Qt.opacity(t.foreground,.5)),t.overviewRulerBorder=$t(e.overviewRulerBorder,I2),t.ansi=Ti.slice(),t.ansi[0]=$t(e.black,Ti[0]),t.ansi[1]=$t(e.red,Ti[1]),t.ansi[2]=$t(e.green,Ti[2]),t.ansi[3]=$t(e.yellow,Ti[3]),t.ansi[4]=$t(e.blue,Ti[4]),t.ansi[5]=$t(e.magenta,Ti[5]),t.ansi[6]=$t(e.cyan,Ti[6]),t.ansi[7]=$t(e.white,Ti[7]),t.ansi[8]=$t(e.brightBlack,Ti[8]),t.ansi[9]=$t(e.brightRed,Ti[9]),t.ansi[10]=$t(e.brightGreen,Ti[10]),t.ansi[11]=$t(e.brightYellow,Ti[11]),t.ansi[12]=$t(e.brightBlue,Ti[12]),t.ansi[13]=$t(e.brightMagenta,Ti[13]),t.ansi[14]=$t(e.brightCyan,Ti[14]),t.ansi[15]=$t(e.brightWhite,Ti[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let s=0;so.index-c.index),s=[];for(let o of i){let c=this._services.get(o.id);if(!c)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${o.id._id}.`);s.push(c)}let a=i.length>0?i[0].index:t.length;if(t.length!==a)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${a+1} conflicts with ${t.length} static arguments`);return new e(...t,...s)}},$2={trace:0,debug:1,info:2,warn:3,error:4,off:5},F2="xterm.js: ",mp=class extends ut{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=$2[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;s--)this._array[this._getCyclicIndex(s+i.length)]=this._array[this._getCyclicIndex(s)];for(let s=0;sthis._maxLength){let s=this._length+i.length-this._maxLength;this._startIndex+=s,this._length=this._maxLength,this.onTrimEmitter.fire(s)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let a=t-1;a>=0;a--)this.set(e+a+i,this.get(e+a));let s=e+t+i-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s>22,i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):s]}set(t,i){this._data[t*ct+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*ct+0]=t|2097152|i[2]<<22):this._data[t*ct+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*ct+0]>>22}hasWidth(t){return this._data[t*ct+0]&12582912}getFg(t){return this._data[t*ct+1]}getBg(t){return this._data[t*ct+2]}hasContent(t){return this._data[t*ct+0]&4194303}getCodePoint(t){let i=this._data[t*ct+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*ct+0]&2097152}getString(t){let i=this._data[t*ct+0];return i&2097152?this._combined[t]:i&2097151?zs(i&2097151):""}isProtected(t){return this._data[t*ct+2]&536870912}loadCell(t,i){return su=t*ct,i.content=this._data[su+0],i.fg=this._data[su+1],i.bg=this._data[su+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*ct+0]=i.content,this._data[t*ct+1]=i.fg,this._data[t*ct+2]=i.bg}setCellFromCodepoint(t,i,s,a){a.bg&268435456&&(this._extendedAttrs[t]=a.extended),this._data[t*ct+0]=i|s<<22,this._data[t*ct+1]=a.fg,this._data[t*ct+2]=a.bg}addCodepointToCell(t,i,s){let a=this._data[t*ct+0];a&2097152?this._combined[t]+=zs(i):a&2097151?(this._combined[t]=zs(a&2097151)+zs(i),a&=-2097152,a|=2097152):a=i|1<<22,s&&(a&=-12582913,a|=s<<22),this._data[t*ct+0]=a}insertCells(t,i,s){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),i=0;--o)this.setCell(t+i+o,this.loadCell(t+o,a));for(let o=0;othis.length){if(this._data.buffer.byteLength>=s*4)this._data=new Uint32Array(this._data.buffer,0,s);else{let a=new Uint32Array(s);a.set(this._data),this._data=a}for(let a=this.length;a=t&&delete this._combined[h]}let o=Object.keys(this._extendedAttrs);for(let c=0;c=t&&delete this._extendedAttrs[h]}}return this.length=t,s*4*of=0;--t)if(this._data[t*ct+0]&4194303)return t+(this._data[t*ct+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ct+0]&4194303||this._data[t*ct+2]&50331648)return t+(this._data[t*ct+0]>>22);return 0}copyCellsFrom(t,i,s,a,o){let c=t._data;if(o)for(let p=a-1;p>=0;p--){for(let f=0;f=i&&(this._combined[f-i+s]=t._combined[f])}}translateToString(t,i,s,a){i=i??0,s=s??this.length,t&&(s=Math.min(s,this.getTrimmedLength())),a&&(a.length=0);let o="";for(;i>22||1}return a&&a.push(i),o}};function q2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(R>x||_[R].getTrimmedLength()===0);R--)j++;j>0&&(c.push(h+_.length-j),c.push(j)),h+=_.length-1}return c}function W2(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;cMo(e,f,t)).reduce((p,f)=>p+f),o=0,c=0,h=0;for(;hp&&(o-=p,c++);let f=e[c].getWidth(o-1)===2;f&&o--;let _=f?i-1:i;s.push(_),h+=_}return s}function Mo(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let s=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,a=e[t+1].getWidth(0)===2;return s&&a?i-1:i}var p0=class m0{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=m0._nextId++,this._onDispose=this.register(new Ce),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),ga(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};p0._nextId=1;var K2=p0,Di={},fa=Di.B;Di[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};Di.A={"#":"£"};Di.B=void 0;Di[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Di.C=Di[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Di.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Di.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Di.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Di.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Di.E=Di[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Di.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Di.H=Di[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Di["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Pb=4294967295,Ib=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Si.clone(),this.savedCharset=fa,this.markers=[],this._nullCell=sr.fromCharData([0,Dy,1,0]),this._whitespaceCell=sr.fromCharData([0,Is,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ru,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new zb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Nu),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Nu),this._whitespaceCell}getBlankLine(e,t){return new wo(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&ePb?Pb:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Si);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new zb(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Si),s=0,a=this._getCorrectBufferLength(t);if(a>this.lines.maxLength&&(this.lines.maxLength=a),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+o+1?(this.ybase--,o++,this.ydisp>0&&this.ydisp--):this.lines.push(new wo(e,i)));else for(let c=this._rows;c>t;c--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(a0&&(this.lines.trimStart(c),this.ybase=Math.max(this.ybase-c,0),this.ydisp=Math.max(this.ydisp-c,0),this.savedY=Math.max(this.savedY-c,0)),this.lines.maxLength=a}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),o&&(this.y+=o),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let o=0;o.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=q2(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Si),i);if(s.length>0){let a=W2(this.lines,s);G2(this.lines,a.layout),this._reflowLargerAdjustViewport(e,t,a.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(Si),a=i;for(;a-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;c--){let h=this.lines.get(c);if(!h||!h.isWrapped&&h.getTrimmedLength()<=e)continue;let p=[h];for(;h.isWrapped&&c>0;)h=this.lines.get(--c),p.unshift(h);if(!i){let I=this.ybase+this.y;if(I>=c&&I0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let S=_.length-1,j=_[S];j===0&&(S--,j=_[S]);let R=p.length-x-1,E=f;for(;R>=0;){let I=Math.min(E,j);if(p[S]===void 0)break;if(p[S].copyCellsFrom(p[R],E-I,j-I,I,!0),j-=I,j===0&&(S--,j=_[S]),E-=I,E===0){R--;let te=Math.max(R,0);E=Mo(p,te,this._cols)}}for(let I=0;I0;)this.ybase===0?this.y0){let c=[],h=[];for(let j=0;j=0;j--)if(x&&x.start>f+b){for(let R=x.newLines.length-1;R>=0;R--)this.lines.set(j--,x.newLines[R]);j++,c.push({index:f+1,amount:x.newLines.length}),b+=x.newLines.length,x=a[++_]}else this.lines.set(j,h[f--]);let v=0;for(let j=c.length-1;j>=0;j--)c[j].index+=v,this.lines.onInsertEmitter.fire(c[j]),v+=c[j].amount;let S=Math.max(0,p+o-this.lines.maxLength);S>0&&this.lines.onTrimEmitter.fire(S)}}translateBufferLineToString(e,t,i=0,s){let a=this.lines.get(e);return a?a.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.linei.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},V2=class extends ut{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new Ce),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new Ib(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Ib(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},g0=2,x0=1,gp=class extends ut{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new Ce),this.onResize=this._onResize.event,this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,g0),this.rows=Math.max(e.rawOptions.rows||0,x0),this.buffers=this._register(new V2(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,s=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,s;s=this._cachedBlankLine,(!s||s.length!==this.cols||s.getFg(0)!==e.fg||s.getBg(0)!==e.bg)&&(s=i.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;let a=i.ybase+i.scrollTop,o=i.ybase+i.scrollBottom;if(i.scrollTop===0){let c=i.lines.isFull;o===i.lines.length-1?c?i.lines.recycle().copyFrom(s):i.lines.push(s.clone()):i.lines.splice(o+1,0,s.clone()),c?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let c=o-a+1;i.lines.shiftElements(a+1,c-1,-1),i.lines.set(o,s.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let s=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),s!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};gp=ci([De(0,mn)],gp);var nl={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Au,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},X2=["normal","bold","100","200","300","400","500","600","700","800","900"],Z2=class extends ut{constructor(e){super(),this._onOptionChange=this._register(new Ce),this.onOptionChange=this._onOptionChange.event;let t={...nl};for(let i in e)if(i in t)try{let s=e[i];t[i]=this._sanitizeAndValidateOption(i,s)}catch(s){console.error(s)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(ii(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in nl))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in nl))throw new Error(`No option with key "${i}"`);s=this._sanitizeAndValidateOption(i,s),this.rawOptions[i]!==s&&(this.rawOptions[i]=s,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let s={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,s)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=nl[e]),!Q2(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=nl[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=X2.includes(t)?t:nl[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function Q2(e){return e==="block"||e==="underline"||e==="bar"}function Co(e,t=5){if(typeof e!="object")return e;let i=Array.isArray(e)?[]:{};for(let s in e)i[s]=t<=1?e[s]:e[s]&&Co(e[s],t-1);return i}var Hb=Object.freeze({insertMode:!1}),Ub=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),xp=class extends ut{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new Ce),this.onData=this._onData.event,this._onUserInput=this._register(new Ce),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new Ce),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new Ce),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Co(Hb),this.decPrivateModes=Co(Ub)}reset(){this.modes=Co(Hb),this.decPrivateModes=Co(Ub)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(s=>s.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};xp=ci([De(0,pn),De(1,zy),De(2,mn)],xp);var $b={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function cf(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}var uf=String.fromCharCode,Fb={DEFAULT:e=>{let t=[cf(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${uf(t[0])}${uf(t[1])}${uf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${cf(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${cf(e,!0)};${e.x};${e.y}${t}`}},_p=class extends ut{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new Ce),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys($b))this.addProtocol(s,$b[s]);for(let s of Object.keys(Fb))this.addEncoding(s,Fb[s]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let s=t/i,a=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(a/=s+0,Math.abs(e.deltaY)<50&&(a*=.3),this._wheelPartialScroll+=a,a=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(a*=this._bufferService.rows),a}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};_p=ci([De(0,pn),De(1,ba),De(2,mn)],_p);var hf=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],J2=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],Ai;function eE(e,t){let i=0,s=t.length-1,a;if(et[s][1])return!1;for(;s>=i;)if(a=i+s>>1,e>t[a][1])i=a+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),s=i===0&&t!==0;if(s){let a=pa.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return pa.createPropertyValue(0,i,s)}},pa=class yu{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new Ce,this.onChange=this._onChange.event;let t=new tE;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,i,s=!1){return(t&16777215)<<3|(i&3)<<1|(s?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let i=0,s=0,a=t.length;for(let o=0;o=a)return i+this.wcwidth(c);let f=t.charCodeAt(o);56320<=f&&f<=57343?c=(c-55296)*1024+f-56320+65536:i+=this.wcwidth(f)}let h=this.charProperties(c,s),p=yu.extractWidth(h);yu.extractShouldJoin(h)&&(p-=yu.extractWidth(s)),i+=p,s=h}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},iE=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function qb(e){var s;let t=(s=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1))==null?void 0:s.get(e.cols-1),i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);i&&t&&(i.isWrapped=t[3]!==0&&t[3]!==32)}var fo=2147483647,nE=256,_0=class bp{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>nE)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new bp;if(!t.length)return i;for(let s=Array.isArray(t[0])?1:0;s>8,a=this._subParamsIdx[i]&255;a-s>0&&t.push(Array.prototype.slice.call(this._subParams,s,a))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>fo?fo:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>fo?fo:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,s=this._subParamsIdx[t]&255;return s-i>0?this._subParams.subarray(i,s):null}getSubParamsAll(){let t={};for(let i=0;i>8,a=this._subParamsIdx[i]&255;a-s>0&&(t[i]=this._subParams.slice(s,a))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let s=this._digitIsSub?this._subParams:this.params,a=s[i-1];s[i-1]=~a?Math.min(a*10+t,fo):t}},po=[],rE=class{constructor(){this._state=0,this._active=po,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=po}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=po,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||po,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,i){if(!this._active.length)this._handlerFb(this._id,"PUT",Pu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,i)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].end(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=po,this._id=-1,this._state=0}}},zn=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Pu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,t}},mo=[],sE=class{constructor(){this._handlers=Object.create(null),this._active=mo,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=mo}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=mo,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||mo,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",Pu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].unhook(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=mo,this._ident=0}},ko=new _0;ko.addParam(0);var Wb=class{constructor(e){this._handler=e,this._data="",this._params=ko,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():ko,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Pu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(i=>(this._params=ko,this._data="",this._hitLimit=!1,i));return this._params=ko,this._data="",this._hitLimit=!1,t}},aE=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,s){this.table[t<<8|e]=i<<4|s}addMany(e,t,i,s){for(let a=0;ap),i=(h,p)=>t.slice(h,p),s=i(32,127),a=i(0,24);a.push(25),a.push.apply(a,i(28,32));let o=i(0,14),c;e.setDefault(1,0),e.addMany(s,0,2,0);for(c in o)e.addMany([24,26,153,154],c,3,0),e.addMany(i(128,144),c,3,0),e.addMany(i(144,152),c,3,0),e.add(156,c,0,0),e.add(27,c,11,1),e.add(157,c,4,8),e.addMany([152,158,159],c,0,7),e.add(155,c,11,3),e.add(144,c,11,9);return e.addMany(a,0,3,0),e.addMany(a,1,3,1),e.add(127,1,0,1),e.addMany(a,8,0,8),e.addMany(a,3,3,3),e.add(127,3,0,3),e.addMany(a,4,3,4),e.add(127,4,0,4),e.addMany(a,6,3,6),e.addMany(a,5,3,5),e.add(127,5,0,5),e.addMany(a,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(s,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(a,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(a,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(a,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(a,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(a,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(a,13,13,13),e.addMany(s,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(nr,0,2,0),e.add(nr,8,5,8),e.add(nr,6,0,6),e.add(nr,11,0,11),e.add(nr,13,13,13),e})(),oE=class extends ut{constructor(e=lE){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new _0,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,i,s)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,i)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(ii(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new rE),this._dcsParser=this._register(new sE),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let a=0;ao||o>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=o}}if(e.final.length!==1)throw new Error("final must be a single byte");let s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let i=this._identifier(e,[48,126]);this._escHandlers[i]===void 0&&(this._escHandlers[i]=[]);let s=this._escHandlers[i];return s.push(t),{dispose:()=>{let a=s.indexOf(t);a!==-1&&s.splice(a,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let i=this._identifier(e);this._csiHandlers[i]===void 0&&(this._csiHandlers[i]=[]);let s=this._csiHandlers[i];return s.push(t),{dispose:()=>{let a=s.indexOf(t);a!==-1&&s.splice(a,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,s,a){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=a}parse(e,t,i){let s=0,a=0,o=0,c;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(i===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let h=this._parseStack.handlers,p=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(i===!1&&p>-1){for(;p>=0&&(c=h[p](this._params),c!==!0);p--)if(c instanceof Promise)return this._parseStack.handlerPos=p,c}this._parseStack.handlers=[];break;case 4:if(i===!1&&p>-1){for(;p>=0&&(c=h[p](),c!==!0);p--)if(c instanceof Promise)return this._parseStack.handlerPos=p,c}this._parseStack.handlers=[];break;case 6:if(s=e[this._parseStack.chunkPos],c=this._dcsParser.unhook(s!==24&&s!==26,i),c)return c;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(s=e[this._parseStack.chunkPos],c=this._oscParser.end(s!==24&&s!==26,i),c)return c;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let h=o;h>4){case 2:for(let b=h+1;;++b){if(b>=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=0&&(c=p[f](this._params),c!==!0);f--)if(c instanceof Promise)return this._preserveStack(3,p,f,a,h),c;f<0&&this._csiHandlerFb(this._collect<<8|s,this._params),this.precedingJoinState=0;break;case 8:do switch(s){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(s-48)}while(++h47&&s<60);h--;break;case 9:this._collect<<=8,this._collect|=s;break;case 10:let _=this._escHandlers[this._collect<<8|s],x=_?_.length-1:-1;for(;x>=0&&(c=_[x](),c!==!0);x--)if(c instanceof Promise)return this._preserveStack(4,_,x,a,h),c;x<0&&this._escHandlerFb(this._collect<<8|s),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|s,this._params);break;case 13:for(let b=h+1;;++b)if(b>=t||(s=e[b])===24||s===26||s===27||s>127&&s=t||(s=e[b])<32||s>127&&s>4:o>>8}return s}}function df(e,t){let i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}function hE(e,t=16){let[i,s,a]=e;return`rgb:${df(i,t)}/${df(s,t)}/${df(a,t)}`}var dE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Ls=131072,Yb=10;function Kb(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Vb=5e3,Xb=0,fE=class extends ut{constructor(e,t,i,s,a,o,c,h,p=new oE){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=s,this._optionsService=a,this._oscLinkService=o,this._coreMouseService=c,this._unicodeService=h,this._parser=p,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new DC,this._utf8Decoder=new MC,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Si.clone(),this._eraseAttrDataInternal=Si.clone(),this._onRequestBell=this._register(new Ce),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new Ce),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new Ce),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new Ce),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new Ce),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new Ce),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new Ce),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new Ce),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new Ce),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new Ce),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new Ce),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new Ce),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new Ce),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new vp(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(f=>this._activeBuffer=f.activeBuffer)),this._parser.setCsiHandlerFallback((f,_)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(f),params:_.toArray()})}),this._parser.setEscHandlerFallback(f=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(f)})}),this._parser.setExecuteHandlerFallback(f=>{this._logService.debug("Unknown EXECUTE code: ",{code:f})}),this._parser.setOscHandlerFallback((f,_,x)=>{this._logService.debug("Unknown OSC code: ",{identifier:f,action:_,data:x})}),this._parser.setDcsHandlerFallback((f,_,x)=>{_==="HOOK"&&(x=x.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(f),action:_,payload:x})}),this._parser.setPrintHandler((f,_,x)=>this.print(f,_,x)),this._parser.registerCsiHandler({final:"@"},f=>this.insertChars(f)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},f=>this.scrollLeft(f)),this._parser.registerCsiHandler({final:"A"},f=>this.cursorUp(f)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},f=>this.scrollRight(f)),this._parser.registerCsiHandler({final:"B"},f=>this.cursorDown(f)),this._parser.registerCsiHandler({final:"C"},f=>this.cursorForward(f)),this._parser.registerCsiHandler({final:"D"},f=>this.cursorBackward(f)),this._parser.registerCsiHandler({final:"E"},f=>this.cursorNextLine(f)),this._parser.registerCsiHandler({final:"F"},f=>this.cursorPrecedingLine(f)),this._parser.registerCsiHandler({final:"G"},f=>this.cursorCharAbsolute(f)),this._parser.registerCsiHandler({final:"H"},f=>this.cursorPosition(f)),this._parser.registerCsiHandler({final:"I"},f=>this.cursorForwardTab(f)),this._parser.registerCsiHandler({final:"J"},f=>this.eraseInDisplay(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},f=>this.eraseInDisplay(f,!0)),this._parser.registerCsiHandler({final:"K"},f=>this.eraseInLine(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},f=>this.eraseInLine(f,!0)),this._parser.registerCsiHandler({final:"L"},f=>this.insertLines(f)),this._parser.registerCsiHandler({final:"M"},f=>this.deleteLines(f)),this._parser.registerCsiHandler({final:"P"},f=>this.deleteChars(f)),this._parser.registerCsiHandler({final:"S"},f=>this.scrollUp(f)),this._parser.registerCsiHandler({final:"T"},f=>this.scrollDown(f)),this._parser.registerCsiHandler({final:"X"},f=>this.eraseChars(f)),this._parser.registerCsiHandler({final:"Z"},f=>this.cursorBackwardTab(f)),this._parser.registerCsiHandler({final:"`"},f=>this.charPosAbsolute(f)),this._parser.registerCsiHandler({final:"a"},f=>this.hPositionRelative(f)),this._parser.registerCsiHandler({final:"b"},f=>this.repeatPrecedingCharacter(f)),this._parser.registerCsiHandler({final:"c"},f=>this.sendDeviceAttributesPrimary(f)),this._parser.registerCsiHandler({prefix:">",final:"c"},f=>this.sendDeviceAttributesSecondary(f)),this._parser.registerCsiHandler({final:"d"},f=>this.linePosAbsolute(f)),this._parser.registerCsiHandler({final:"e"},f=>this.vPositionRelative(f)),this._parser.registerCsiHandler({final:"f"},f=>this.hVPosition(f)),this._parser.registerCsiHandler({final:"g"},f=>this.tabClear(f)),this._parser.registerCsiHandler({final:"h"},f=>this.setMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"h"},f=>this.setModePrivate(f)),this._parser.registerCsiHandler({final:"l"},f=>this.resetMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"l"},f=>this.resetModePrivate(f)),this._parser.registerCsiHandler({final:"m"},f=>this.charAttributes(f)),this._parser.registerCsiHandler({final:"n"},f=>this.deviceStatus(f)),this._parser.registerCsiHandler({prefix:"?",final:"n"},f=>this.deviceStatusPrivate(f)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},f=>this.softReset(f)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},f=>this.setCursorStyle(f)),this._parser.registerCsiHandler({final:"r"},f=>this.setScrollRegion(f)),this._parser.registerCsiHandler({final:"s"},f=>this.saveCursor(f)),this._parser.registerCsiHandler({final:"t"},f=>this.windowOptions(f)),this._parser.registerCsiHandler({final:"u"},f=>this.restoreCursor(f)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},f=>this.insertColumns(f)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},f=>this.deleteColumns(f)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},f=>this.selectProtected(f)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},f=>this.requestMode(f,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},f=>this.requestMode(f,!1)),this._parser.setExecuteHandler(me.BEL,()=>this.bell()),this._parser.setExecuteHandler(me.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(me.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(me.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(me.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(me.BS,()=>this.backspace()),this._parser.setExecuteHandler(me.HT,()=>this.tab()),this._parser.setExecuteHandler(me.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(me.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(bu.IND,()=>this.index()),this._parser.setExecuteHandler(bu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(bu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new zn(f=>(this.setTitle(f),this.setIconName(f),!0))),this._parser.registerOscHandler(1,new zn(f=>this.setIconName(f))),this._parser.registerOscHandler(2,new zn(f=>this.setTitle(f))),this._parser.registerOscHandler(4,new zn(f=>this.setOrReportIndexedColor(f))),this._parser.registerOscHandler(8,new zn(f=>this.setHyperlink(f))),this._parser.registerOscHandler(10,new zn(f=>this.setOrReportFgColor(f))),this._parser.registerOscHandler(11,new zn(f=>this.setOrReportBgColor(f))),this._parser.registerOscHandler(12,new zn(f=>this.setOrReportCursorColor(f))),this._parser.registerOscHandler(104,new zn(f=>this.restoreIndexedColor(f))),this._parser.registerOscHandler(110,new zn(f=>this.restoreFgColor(f))),this._parser.registerOscHandler(111,new zn(f=>this.restoreBgColor(f))),this._parser.registerOscHandler(112,new zn(f=>this.restoreCursorColor(f))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let f in Di)this._parser.registerEscHandler({intermediates:"(",final:f},()=>this.selectCharset("("+f)),this._parser.registerEscHandler({intermediates:")",final:f},()=>this.selectCharset(")"+f)),this._parser.registerEscHandler({intermediates:"*",final:f},()=>this.selectCharset("*"+f)),this._parser.registerEscHandler({intermediates:"+",final:f},()=>this.selectCharset("+"+f)),this._parser.registerEscHandler({intermediates:"-",final:f},()=>this.selectCharset("-"+f)),this._parser.registerEscHandler({intermediates:".",final:f},()=>this.selectCharset("."+f)),this._parser.registerEscHandler({intermediates:"/",final:f},()=>this.selectCharset("/"+f));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(f=>(this._logService.error("Parsing error: ",f),f)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Wb((f,_)=>this.requestStatusString(f,_)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,i)=>setTimeout(()=>i("#SLOW_TIMEOUT"),Vb))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Vb} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,a=this._activeBuffer.y,o=0,c=this._parseStack.paused;if(c){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,a=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Ls&&(o=this._parseStack.position+Ls)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,f=>String.fromCharCode(f)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(f=>f.charCodeAt(0)):e),this._parseBuffer.lengthLs)for(let f=o;f0&&x.getWidth(this._activeBuffer.x-1)===2&&x.setCellFromCodepoint(this._activeBuffer.x-1,0,1,_);let b=this._parser.precedingJoinState;for(let v=t;vh){if(p){let E=x,N=this._activeBuffer.x-R;for(this._activeBuffer.x=R,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),x=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),R>0&&x instanceof wo&&x.copyCellsFrom(E,N,0,R,!1);N=0;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_);continue}if(f&&(x.insertCells(this._activeBuffer.x,a-R,this._activeBuffer.getNullCell(_)),x.getWidth(h-1)===2&&x.setCellFromCodepoint(h-1,0,1,_)),x.setCellFromCodepoint(this._activeBuffer.x++,s,a,_),a>0)for(;--a;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_)}this._parser.precedingJoinState=b,this._activeBuffer.x0&&x.getWidth(this._activeBuffer.x)===0&&!x.hasContent(this._activeBuffer.x)&&x.setCellFromCodepoint(this._activeBuffer.x,0,1,_),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,i=>Kb(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Wb(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new zn(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var e;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&((e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&e.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);t.hasWidth(this._activeBuffer.x)&&!t.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,a=!1){let o=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);o.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),a),s&&(o.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){var s;this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!((s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i))!=null&&s.getTrimmedLength()););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let a=this._activeBuffer.lines.length-this._bufferService.rows;a>0&&(this._activeBuffer.lines.trimStart(a),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-a,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-a,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let p=h;for(let f=1;f0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(me.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(me.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(me.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(me.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(me.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t(j[j.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",j[j.SET=1]="SET",j[j.RESET=2]="RESET",j[j.PERMANENTLY_SET=3]="PERMANENTLY_SET",j[j.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(void 0||(i={}));let s=this._coreService.decPrivateModes,{activeProtocol:a,activeEncoding:o}=this._coreMouseService,c=this._coreService,{buffers:h,cols:p}=this._bufferService,{active:f,alt:_}=h,x=this._optionsService.rawOptions,b=(j,R)=>(c.triggerDataEvent(`${me.ESC}[${t?"":"?"}${j};${R}$y`),!0),v=j=>j?1:2,S=e.params[0];return t?S===2?b(S,4):S===4?b(S,v(c.modes.insertMode)):S===12?b(S,3):S===20?b(S,v(x.convertEol)):b(S,0):S===1?b(S,v(s.applicationCursorKeys)):S===3?b(S,x.windowOptions.setWinLines?p===80?2:p===132?1:0:0):S===6?b(S,v(s.origin)):S===7?b(S,v(s.wraparound)):S===8?b(S,3):S===9?b(S,v(a==="X10")):S===12?b(S,v(x.cursorBlink)):S===25?b(S,v(!c.isCursorHidden)):S===45?b(S,v(s.reverseWraparound)):S===66?b(S,v(s.applicationKeypad)):S===67?b(S,4):S===1e3?b(S,v(a==="VT200")):S===1002?b(S,v(a==="DRAG")):S===1003?b(S,v(a==="ANY")):S===1004?b(S,v(s.sendFocus)):S===1005?b(S,4):S===1006?b(S,v(o==="SGR")):S===1015?b(S,4):S===1016?b(S,v(o==="SGR_PIXELS")):S===1048?b(S,1):S===47||S===1047||S===1049?b(S,v(f===_)):S===2004?b(S,v(s.bracketedPasteMode)):S===2026?b(S,v(s.synchronizedOutput)):b(S,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=Po.fromColorRGB([i,s,a])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let s=[0,0,-1,0,0,0],a=0,o=0;do{if(s[o+a]=e.params[t+o],e.hasSubParams(t+o)){let c=e.getSubParams(t+o),h=0;do s[1]===5&&(a=1),s[o+h+1+a]=c[h];while(++h=2||s[1]===2&&o+a>=5)break;s[1]&&(a=1)}while(++o+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=Si.fg,e.bg=Si.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,i,s=this._curAttrData;for(let a=0;a=30&&i<=37?(s.fg&=-50331904,s.fg|=16777216|i-30):i>=40&&i<=47?(s.bg&=-50331904,s.bg|=16777216|i-40):i>=90&&i<=97?(s.fg&=-50331904,s.fg|=16777216|i-90|8):i>=100&&i<=107?(s.bg&=-50331904,s.bg|=16777216|i-100|8):i===0?this._processSGR0(s):i===1?s.fg|=134217728:i===3?s.bg|=67108864:i===4?(s.fg|=268435456,this._processUnderline(e.hasSubParams(a)?e.getSubParams(a)[0]:1,s)):i===5?s.fg|=536870912:i===7?s.fg|=67108864:i===8?s.fg|=1073741824:i===9?s.fg|=2147483648:i===2?s.bg|=134217728:i===21?this._processUnderline(2,s):i===22?(s.fg&=-134217729,s.bg&=-134217729):i===23?s.bg&=-67108865:i===24?(s.fg&=-268435457,this._processUnderline(0,s)):i===25?s.fg&=-536870913:i===27?s.fg&=-67108865:i===28?s.fg&=-1073741825:i===29?s.fg&=2147483647:i===39?(s.fg&=-67108864,s.fg|=Si.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=Si.bg&16777215):i===38||i===48||i===58?a+=this._extractColor(e,a,s):i===53?s.bg|=1073741824:i===55?s.bg&=-1073741825:i===59?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):i===100?(s.fg&=-67108864,s.fg|=Si.fg&16777215,s.bg&=-67108864,s.bg|=Si.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${me.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${me.ESC}[${t};${i}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${me.ESC}[?${t};${i}R`);break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=Si.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Kb(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${me.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Yb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Yb&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],i=e.split(";");for(;i.length>1;){let s=i.shift(),a=i.shift();if(/^\d+$/.exec(s)){let o=parseInt(s);if(Zb(o))if(a==="?")t.push({type:0,index:o});else{let c=Gb(a);c&&t.push({type:1,index:o,color:c})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let i=e.slice(0,t).trim(),s=e.slice(t+1);return s?this._createHyperlink(i,s):i.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i=e.split(":"),s,a=i.findIndex(o=>o.startsWith("id="));return a!==-1&&(s=i[a].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let i=e.split(";");for(let s=0;s=this._specialColors.length);++s,++t)if(i[s]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let a=Gb(i[s]);a&&this._onColor.fire([{type:1,index:this._specialColors[t],color:a}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],i=e.split(";");for(let s=0;s=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=Si.clone(),this._eraseAttrDataInternal=Si.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new sr;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${me.ESC}${c}${me.ESC}\\`),!0),s=this._bufferService.buffer,a=this._optionsService.rawOptions;return i(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${s.scrollTop+1};${s.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[a.cursorStyle]-(a.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},vp=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Xb=e,e=t,t=Xb),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};vp=ci([De(0,pn)],vp);function Zb(e){return 0<=e&&e<256}var pE=5e7,Qb=12,mE=50,gE=class extends ut{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new Ce),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let i;for(;i=this._writeBuffer.shift();){this._action(i);let s=this._callbacks.shift();s&&s()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>pE)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let s=this._writeBuffer[this._bufferOffset],a=this._action(s,t);if(a){let c=h=>performance.now()-i>=Qb?setTimeout(()=>this._innerWrite(0,h)):this._innerWrite(i,h);a.catch(h=>(queueMicrotask(()=>{throw h}),Promise.resolve(!1))).then(c);return}let o=this._callbacks[this._bufferOffset];if(o&&o(),this._bufferOffset++,this._pendingData-=s.length,performance.now()-i>=Qb)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>mE&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},yp=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let h=t.addMarker(t.ybase+t.y),p={data:e,id:this._nextId++,lines:[h]};return h.onDispose(()=>this._removeMarkerFromLink(p,h)),this._dataByLinkId.set(p.id,p),p.id}let i=e,s=this._getEntryIdKey(i),a=this._entriesWithId.get(s);if(a)return this.addLineToLink(a.id,t.ybase+t.y),a.id;let o=t.addMarker(t.ybase+t.y),c={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[o]};return o.onDispose(()=>this._removeMarkerFromLink(c,o)),this._entriesWithId.set(c.key,c),this._dataByLinkId.set(c.id,c),c.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(s=>s.line!==t)){let s=this._bufferService.buffer.addMarker(t);i.lines.push(s),s.onDispose(()=>this._removeMarkerFromLink(i,s))}}getLinkData(e){var t;return(t=this._dataByLinkId.get(e))==null?void 0:t.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};yp=ci([De(0,pn)],yp);var Jb=!1,xE=class extends ut{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new pl),this._onBinary=this._register(new Ce),this.onBinary=this._onBinary.event,this._onData=this._register(new Ce),this.onData=this._onData.event,this._onLineFeed=this._register(new Ce),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new Ce),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new Ce),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new Ce),this._instantiationService=new U2,this.optionsService=this._register(new Z2(e)),this._instantiationService.setService(mn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(gp)),this._instantiationService.setService(pn,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(mp)),this._instantiationService.setService(zy,this._logService),this.coreService=this._register(this._instantiationService.createInstance(xp)),this._instantiationService.setService(ba,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(_p)),this._instantiationService.setService(Oy,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(pa)),this._instantiationService.setService(zC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(iE),this._instantiationService.setService(OC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(yp),this._instantiationService.setService(Py,this._oscLinkService),this._inputHandler=this._register(new fE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(en.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(en.forward(this._bufferService.onResize,this._onResize)),this._register(en.forward(this.coreService.onData,this._onData)),this._register(en.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new gE((t,i)=>this._inputHandler.parse(t,i))),this._register(en.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new Ce),this._onScroll.event(e=>{var t;(t=this._onScrollApi)==null||t.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!Jb&&(this._logService.warn("writeSync is unreliable and will be removed soon."),Jb=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,g0),t=Math.max(t,x0),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(qb.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(qb(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ii(()=>{for(let t of e)t.dispose()})}}},_E={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function bE(e,t,i,s){var c;let a={type:0,cancel:!1,key:void 0},o=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?a.key=me.ESC+"OA":a.key=me.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?a.key=me.ESC+"OD":a.key=me.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?a.key=me.ESC+"OC":a.key=me.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?a.key=me.ESC+"OB":a.key=me.ESC+"[B");break;case 8:a.key=e.ctrlKey?"\b":me.DEL,e.altKey&&(a.key=me.ESC+a.key);break;case 9:if(e.shiftKey){a.key=me.ESC+"[Z";break}a.key=me.HT,a.cancel=!0;break;case 13:a.key=e.altKey?me.ESC+me.CR:me.CR,a.cancel=!0;break;case 27:a.key=me.ESC,e.altKey&&(a.key=me.ESC+me.ESC),a.cancel=!0;break;case 37:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"D":t?a.key=me.ESC+"OD":a.key=me.ESC+"[D";break;case 39:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"C":t?a.key=me.ESC+"OC":a.key=me.ESC+"[C";break;case 38:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"A":t?a.key=me.ESC+"OA":a.key=me.ESC+"[A";break;case 40:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"B":t?a.key=me.ESC+"OB":a.key=me.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(a.key=me.ESC+"[2~");break;case 46:o?a.key=me.ESC+"[3;"+(o+1)+"~":a.key=me.ESC+"[3~";break;case 36:o?a.key=me.ESC+"[1;"+(o+1)+"H":t?a.key=me.ESC+"OH":a.key=me.ESC+"[H";break;case 35:o?a.key=me.ESC+"[1;"+(o+1)+"F":t?a.key=me.ESC+"OF":a.key=me.ESC+"[F";break;case 33:e.shiftKey?a.type=2:e.ctrlKey?a.key=me.ESC+"[5;"+(o+1)+"~":a.key=me.ESC+"[5~";break;case 34:e.shiftKey?a.type=3:e.ctrlKey?a.key=me.ESC+"[6;"+(o+1)+"~":a.key=me.ESC+"[6~";break;case 112:o?a.key=me.ESC+"[1;"+(o+1)+"P":a.key=me.ESC+"OP";break;case 113:o?a.key=me.ESC+"[1;"+(o+1)+"Q":a.key=me.ESC+"OQ";break;case 114:o?a.key=me.ESC+"[1;"+(o+1)+"R":a.key=me.ESC+"OR";break;case 115:o?a.key=me.ESC+"[1;"+(o+1)+"S":a.key=me.ESC+"OS";break;case 116:o?a.key=me.ESC+"[15;"+(o+1)+"~":a.key=me.ESC+"[15~";break;case 117:o?a.key=me.ESC+"[17;"+(o+1)+"~":a.key=me.ESC+"[17~";break;case 118:o?a.key=me.ESC+"[18;"+(o+1)+"~":a.key=me.ESC+"[18~";break;case 119:o?a.key=me.ESC+"[19;"+(o+1)+"~":a.key=me.ESC+"[19~";break;case 120:o?a.key=me.ESC+"[20;"+(o+1)+"~":a.key=me.ESC+"[20~";break;case 121:o?a.key=me.ESC+"[21;"+(o+1)+"~":a.key=me.ESC+"[21~";break;case 122:o?a.key=me.ESC+"[23;"+(o+1)+"~":a.key=me.ESC+"[23~";break;case 123:o?a.key=me.ESC+"[24;"+(o+1)+"~":a.key=me.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?a.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?a.key=me.NUL:e.keyCode>=51&&e.keyCode<=55?a.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?a.key=me.DEL:e.keyCode===219?a.key=me.ESC:e.keyCode===220?a.key=me.FS:e.keyCode===221&&(a.key=me.GS);else if((!i||s)&&e.altKey&&!e.metaKey){let h=(c=_E[e.keyCode])==null?void 0:c[e.shiftKey?1:0];if(h)a.key=me.ESC+h;else if(e.keyCode>=65&&e.keyCode<=90){let p=e.ctrlKey?e.keyCode-64:e.keyCode+32,f=String.fromCharCode(p);e.shiftKey&&(f=f.toUpperCase()),a.key=me.ESC+f}else if(e.keyCode===32)a.key=me.ESC+(e.ctrlKey?me.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let p=e.code.slice(3,4);e.shiftKey||(p=p.toLowerCase()),a.key=me.ESC+p,a.cancel=!0}}else i&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(a.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?a.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(a.key=me.US),e.key==="@"&&(a.key=me.NUL));break}return a}var pi=0,vE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ru,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ru,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((a,o)=>this._getKey(a)-this._getKey(o)),t=0,i=0,s=new Array(this._array.length+this._insertedValues.length);for(let a=0;a=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(s[a]=e[t],t++):s[a]=this._array[i++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(pi=this._search(t),pi===-1)||this._getKey(this._array[pi])!==t)return!1;do if(this._array[pi]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(pi),!0;while(++pia-o),t=0,i=new Array(this._array.length-e.length),s=0;for(let a=0;a0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(pi=this._search(e),!(pi<0||pi>=this._array.length)&&this._getKey(this._array[pi])===e))do yield this._array[pi];while(++pi=this._array.length)&&this._getKey(this._array[pi])===e))do t(this._array[pi]);while(++pi=t;){let s=t+i>>1,a=this._getKey(this._array[s]);if(a>e)i=s-1;else if(a0&&this._getKey(this._array[s-1])===e;)s--;return s}}return t}},ff=0,ev=0,yE=class extends ut{constructor(){super(),this._decorations=new vE(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new Ce),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new Ce),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(ii(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new SE(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),s=t.onDispose(()=>{s.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let s=0,a=0;for(let o of this._decorations.getKeyIterator(t))s=o.options.x??0,a=s+(o.options.width??1),e>=s&&e{ff=a.options.x??0,ev=ff+(a.options.width??1),e>=ff&&e=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){let a=s-this._lastRefreshMs,o=this._debounceThresholdMS-a;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},o)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},tv=20,Du=class extends ut{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let a=this._coreBrowserService.mainDocument;this._accessibilityContainer=a.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=a.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let o=0;othis._handleBoundaryFocus(o,0),this._bottomBoundaryFocusListener=o=>this._handleBoundaryFocus(o,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=a.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new CE(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(o=>this._handleResize(o.rows))),this._register(this._terminal.onRender(o=>this._refreshRows(o.start,o.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(o=>this._handleChar(o))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` -`))),this._register(this._terminal.onA11yTab(o=>this._handleTab(o))),this._register(this._terminal.onKey(o=>this._handleKey(o.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(Xe(a,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(ii(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` -`&&(this._liveRegionLineCount++,this._liveRegionLineCount===tv+1&&(this._liveRegion.textContent+=Uf.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,s=i.lines.length.toString();for(let a=e;a<=t;a++){let o=i.lines.get(i.ydisp+a),c=[],h=(o==null?void 0:o.translateToString(!0,void 0,void 0,c))||"",p=(i.ydisp+a+1).toString(),f=this._rowElements[a];f&&(h.length===0?(f.textContent=" ",this._rowColumns.set(f,[0,1])):(f.textContent=h,this._rowColumns.set(f,c)),f.setAttribute("aria-posinset",p),f.setAttribute("aria-setsize",s),this._alignRowWidth(f))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i=e.target,s=this._rowElements[t===0?1:this._rowElements.length-2],a=i.getAttribute("aria-posinset"),o=t===0?"1":`${this._terminal.buffer.lines.length}`;if(a===o||e.relatedTarget!==s)return;let c,h;if(t===0?(c=i,h=this._rowElements.pop(),this._rowContainer.removeChild(h)):(c=this._rowElements.shift(),h=i,this._rowContainer.removeChild(c)),c.removeEventListener("focus",this._topBoundaryFocusListener),h.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let p=this._createAccessibilityTreeNode();this._rowElements.unshift(p),this._rowContainer.insertAdjacentElement("afterbegin",p)}else{let p=this._createAccessibilityTreeNode();this._rowElements.push(p),this._rowContainer.appendChild(p)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){var h;if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let s=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:s,offset:((h=s.textContent)==null?void 0:h.length)??0}),!this._rowContainer.contains(i.node))return;let a=({node:p,offset:f})=>{let _=p instanceof Text?p.parentNode:p,x=parseInt(_==null?void 0:_.getAttribute("aria-posinset"),10)-1;if(isNaN(x))return console.warn("row is invalid. Race condition?"),null;let b=this._rowColumns.get(_);if(!b)return console.warn("columns is null. Race condition?"),null;let v=f=this._terminal.cols&&(++x,v=0),{row:x,column:v}},o=a(t),c=a(i);if(!(!o||!c)){if(o.row>c.row||o.row===c.row&&o.column>=c.column)throw new Error("invalid range");this._terminal.select(o.column,o.row,(c.row-o.row)*this._terminal.cols-o.column+c.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;te;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{var o;ga(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(o=this._activeProviderReplies)==null||o.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Xe(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Xe(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Xe(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Xe(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let i=e.composedPath();for(let s=0;s{o==null||o.forEach(c=>{c.link.dispose&&c.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(let[o,c]of this._linkProviderService.linkProviders.entries())t?(a=this._activeProviderReplies)!=null&&a.get(o)&&(i=this._checkLinkProviderResult(o,e,i)):c.provideLinks(e.y,h=>{var f,_;if(this._isMouseOut)return;let p=h==null?void 0:h.map(x=>({link:x}));(f=this._activeProviderReplies)==null||f.set(o,p),i=this._checkLinkProviderResult(o,e,i),((_=this._activeProviderReplies)==null?void 0:_.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let s=0;se?this._bufferService.cols:c.link.range.end.x;for(let f=h;f<=p;f++){if(i.has(f)){a.splice(o--,1);break}i.add(f)}}}}_checkLinkProviderResult(e,t,i){var o;if(!this._activeProviderReplies)return i;let s=this._activeProviderReplies.get(e),a=!1;for(let c=0;cthis._linkAtPosition(h.link,t));c&&(i=!0,this._handleNewLink(c))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let c=0;cthis._linkAtPosition(p.link,t));if(h){i=!0,this._handleNewLink(h);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&kE(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,ga(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.pointerCursor},set:i=>{var s;(s=this._currentLink)!=null&&s.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.underline},set:i=>{var s,a,o;(s=this._currentLink)!=null&&s.state&&((o=(a=this._currentLink)==null?void 0:a.state)==null?void 0:o.decorations.underline)!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let s=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,a=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=a&&(this._clearCurrentLink(s,a),this._lastMouseEvent)){let o=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);o&&this._askForLink(o,!1)}})))}_linkHover(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,s=this._bufferService.buffer.ydisp,a=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(a)}_linkLeave(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,a=t.y*this._bufferService.cols+t.x;return i<=a&&a<=s}_positionFromMouseEvent(e,t,i){let s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,a){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:a}}};Sp=ci([De(1,Fp),De(2,rs),De(3,pn),De(4,Hy)],Sp);function kE(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var EE=class extends xE{constructor(e={}){super(e),this._linkifier=this._register(new pl),this.browser=s0,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new pl),this._onCursorMove=this._register(new Ce),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new Ce),this.onKey=this._onKey.event,this._onRender=this._register(new Ce),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new Ce),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new Ce),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new Ce),this.onBell=this._onBell.event,this._onFocus=this._register(new Ce),this._onBlur=this._register(new Ce),this._onA11yCharEmitter=this._register(new Ce),this._onA11yTabEmitter=this._register(new Ce),this._onWillOpen=this._register(new Ce),this._setup(),this._decorationService=this._instantiationService.createInstance(yE),this._instantiationService.setService(Io,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(m2),this._instantiationService.setService(Hy,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Ff)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh((t==null?void 0:t.start)??0,(t==null?void 0:t.end)??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(en.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(en.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(en.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(en.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(ii(()=>{var t,i;this._customKeyEventHandler=void 0,(i=(t=this.element)==null?void 0:t.parentNode)==null||i.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let i,s="";switch(t.index){case 256:i="foreground",s="10";break;case 257:i="background",s="11";break;case 258:i="cursor",s="12";break;default:i="ansi",s="4;"+t.index}switch(t.type){case 0:let a=Qt.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${me.ESC}]${s};${hE(a)}${n0.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(o=>o.ansi[t.index]=wi.toColor(...t.color));else{let o=i;this._themeService.modifyColors(c=>c[o]=wi.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Du,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(me.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var e;return(e=this.textarea)==null?void 0:e.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(me.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,a=t.getWidth(i),o=this._renderService.dimensions.css.cell.width*a,c=this.buffer.y*this._renderService.dimensions.css.cell.height,h=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=h+"px",this.textarea.style.top=c+"px",this.textarea.style.width=o+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(Xe(this.element,"copy",t=>{this.hasSelection()&&AC(t,this._selectionService)}));let e=t=>RC(t,this.textarea,this.coreService,this.optionsService);this._register(Xe(this.textarea,"paste",e)),this._register(Xe(this.element,"paste",e)),a0?this._register(Xe(this.element,"mousedown",t=>{t.button===2&&hb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Xe(this.element,"contextmenu",t=>{hb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Zp&&this._register(Xe(this.element,"auxclick",t=>{t.button===1&&Ry(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Xe(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Xe(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Xe(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Xe(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Xe(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Xe(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Xe(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){var a;if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),((a=this.element)==null?void 0:a.ownerDocument.defaultView)&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(Xe(this.screenElement,"mousemove",o=>this.updateCursorStyle(o))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Hf.get()),c0||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>i.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(f2,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ns,this._coreBrowserService),this._register(Xe(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(Xe(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(up,this._document,this._helperContainer),this._instantiationService.setService(Iu,this._charSizeService),this._themeService=this._instantiationService.createInstance(pp),this._instantiationService.setService(xl,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Tu),this._instantiationService.setService(Iy,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(dp,this.rows,this.screenElement)),this._instantiationService.setService(rs,this._renderService),this._register(this._renderService.onRenderedViewportChange(o=>this._onRender.fire(o))),this.onResize(o=>this._renderService.resize(o.cols,o.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(lp,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(hp),this._instantiationService.setService(Fp,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(Sp,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(sp,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(o=>{super.scrollLines(o,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(fp,this.element,this.screenElement,s)),this._instantiationService.setService(IC,this._selectionService),this._register(this._selectionService.onRequestScrollLines(o=>this.scrollLines(o.amount,o.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(o=>this._renderService.handleSelectionChanged(o.start,o.end,o.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(o=>{this.textarea.value=o,this.textarea.focus(),this.textarea.select()})),this._register(en.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(ap,this.screenElement)),this._register(Xe(this.element,"mousedown",o=>this._selectionService.handleMouseDown(o))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Du,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(cp,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var f,_,x,b,v;let c=e._mouseService.getMouseReportCoords(o,e.screenElement);if(!c)return!1;let h,p;switch(o.overrideType||o.type){case"mousemove":p=32,o.buttons===void 0?(h=3,o.button!==void 0&&(h=o.button<3?o.button:3)):h=o.buttons&1?0:o.buttons&4?1:o.buttons&2?2:3;break;case"mouseup":p=0,h=o.button<3?o.button:3;break;case"mousedown":p=1,h=o.button<3?o.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(o)===!1)return!1;let S=o.deltaY;if(S===0||e.coreMouseService.consumeWheelEvent(o,(b=(x=(_=(f=e._renderService)==null?void 0:f.dimensions)==null?void 0:_.device)==null?void 0:x.cell)==null?void 0:b.height,(v=e._coreBrowserService)==null?void 0:v.dpr)===0)return!1;p=S<0?0:1,h=4;break;default:return!1}return p===void 0||h===void 0||h>4?!1:e.coreMouseService.triggerMouseEvent({col:c.col,row:c.row,x:c.x,y:c.y,button:h,action:p,ctrl:o.ctrlKey,alt:o.altKey,shift:o.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},a={mouseup:o=>(i(o),o.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(o)),wheel:o=>(i(o),this.cancel(o,!0)),mousedrag:o=>{o.buttons&&i(o)},mousemove:o=>{o.buttons||i(o)}};this._register(this.coreMouseService.onProtocolChange(o=>{o?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(o)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),o&8?s.mousemove||(t.addEventListener("mousemove",a.mousemove),s.mousemove=a.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),o&16?s.wheel||(t.addEventListener("wheel",a.wheel,{passive:!1}),s.wheel=a.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),o&2?s.mouseup||(s.mouseup=a.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),o&4?s.mousedrag||(s.mousedrag=a.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Xe(t,"mousedown",o=>{if(o.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(o)))return i(o),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(o)})),this._register(Xe(t,"wheel",o=>{var c,h,p,f,_;if(!s.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(o)===!1)return!1;if(!this.buffer.hasScrollback){if(o.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(o,(f=(p=(h=(c=e._renderService)==null?void 0:c.dimensions)==null?void 0:h.device)==null?void 0:p.cell)==null?void 0:f.height,(_=e._coreBrowserService)==null?void 0:_.dpr)===0)return this.cancel(o,!0);let x=me.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(o.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(x,!0),this.cancel(o,!0)}}},{passive:!1}))}refresh(e,t){var i;(i=this._renderService)==null||i.refreshRows(e,t)}updateCursorStyle(e){var t;(t=this._selectionService)!=null&&t.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){Ay(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var e;(e=this._selectionService)==null||e.clearSelection()}selectAll(){var e;(e=this._selectionService)==null||e.selectAll()}selectLines(e,t){var i;(i=this._selectionService)==null||i.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let i=bE(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),i.type===3||i.type===2){let s=this.rows-1;return this.scrollLines(i.type===2?-s:s),this.cancel(e,!0)}if(i.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((i.key===me.ETX||i.key===me.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(NE(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){var i;(i=this._charSizeService)==null||i.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new sr)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},iv=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new TE(t)}getNullCell(){return new sr}},AE=class extends ut{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Ce),this.onBufferChange=this._onBufferChange.event,this._normal=new iv(this._core.buffers.normal,"normal"),this._alternate=new iv(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},RE=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,i=>t(i.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(i,s)=>t(i,s.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},DE=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},ME=["cols","rows"],Er=0,BE=class extends ut{constructor(e){super(),this._core=this._register(new EE(e)),this._addonManager=this._register(new jE),this._publicOptions={...this._core.options};let t=s=>this._core.options[s],i=(s,a)=>{this._checkReadonlyOptions(s),this._core.options[s]=a};for(let s in this._core.options){let a={get:t.bind(this,s),set:i.bind(this,s)};Object.defineProperty(this._publicOptions,s,a)}}_checkReadonlyOptions(e){if(ME.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new RE(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new DE(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new AE(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r -`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Hf.get()},set promptLabel(e){Hf.set(e)},get tooMuchOutput(){return Uf.get()},set tooMuchOutput(e){Uf.set(e)}}}_verifyIntegers(...e){for(Er of e)if(Er===1/0||isNaN(Er)||Er%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Er of e)if(Er&&(Er===1/0||isNaN(Er)||Er%1!==0||Er<0))throw new Error("This API only accepts positive integers")}};/** +`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),Zp&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s||!t?!1:this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!i||!s?!1:this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){var a,o;let i=(o=(a=this._linkifier.currentLink)==null?void 0:a.link)==null?void 0:o.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=Bb(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let s=this._getMouseBufferCoords(e);return s?(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Xp(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-of),of),t/=of,t/Math.abs(t)+Math.round(t*(U2-1)))}shouldForceSelection(e){return Au?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),$2)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Au&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){let a=e.loadCell(s,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:a>1&&t!==s&&(i+=a-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;let a=this._bufferService.buffer,o=a.lines.get(e[1]);if(!o)return;let c=a.translateBufferLineToString(e[1],!1),h=this._convertViewportColToCharacterIndex(o,e[0]),p=h,f=e[0]-h,_=0,x=0,b=0,v=0;if(c.charAt(h)===" "){for(;h>0&&c.charAt(h-1)===" ";)h--;for(;p1&&(v+=N-1,p+=N-1);D>0&&h>0&&!this._isCharWordSeparator(o.loadCell(D-1,this._workCell));){o.loadCell(D-1,this._workCell);let I=this._workCell.getChars().length;this._workCell.getWidth()===0?(_++,D--):I>1&&(b+=I-1,h-=I-1),h--,D--}for(;E1&&(v+=I-1,p+=I-1),p++,E++}}p++;let S=h+f-_+b,j=Math.min(this._bufferService.cols,p-h+_+x-b-v);if(!(!t&&c.slice(h,p).trim()==="")){if(i&&S===0&&o.getCodePoint(0)!==32){let D=a.lines.get(e[1]-1);if(D&&o.isWrapped&&D.getCodePoint(this._bufferService.cols-1)!==32){let E=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(E){let N=this._bufferService.cols-E.start;S-=N,j+=N}}}if(s&&S+j===this._bufferService.cols&&o.getCodePoint(this._bufferService.cols-1)!==32){let D=a.lines.get(e[1]+1);if(D!=null&&D.isWrapped&&D.getCodePoint(0)!==32){let E=this._getWordAt([0,e[1]+1],!1,!1,!0);E&&(j+=E.length)}}return{start:S,length:j}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=Bb(i,this._bufferService.cols)}};pp=ci([Re(3,mn),Re(4,ba),Re(5,Fp),Re(6,gn),Re(7,rs),Re(8,ns)],pp);var Lb=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},Ob=class{constructor(){this._color=new Lb,this._css=new Lb}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Ti=Object.freeze((()=>{let e=[ri.toColor("#2e3436"),ri.toColor("#cc0000"),ri.toColor("#4e9a06"),ri.toColor("#c4a000"),ri.toColor("#3465a4"),ri.toColor("#75507b"),ri.toColor("#06989a"),ri.toColor("#d3d7cf"),ri.toColor("#555753"),ri.toColor("#ef2929"),ri.toColor("#8ae234"),ri.toColor("#fce94f"),ri.toColor("#729fcf"),ri.toColor("#ad7fa8"),ri.toColor("#34e2e2"),ri.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:wi.toCss(s,a,o),rgba:wi.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:wi.toCss(s,s,s),rgba:wi.toRgba(s,s,s)})}return e})()),da=ri.toColor("#ffffff"),So=ri.toColor("#000000"),zb=ri.toColor("#ffffff"),Pb=So,ho={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},G2=da,mp=class extends ht{constructor(e){super(),this._optionsService=e,this._contrastCache=new Ob,this._halfContrastCache=new Ob,this._onChangeColors=this._register(new we),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:da,background:So,cursor:zb,cursorAccent:Pb,selectionForeground:void 0,selectionBackgroundTransparent:ho,selectionBackgroundOpaque:Qt.blend(So,ho),selectionInactiveBackgroundTransparent:ho,selectionInactiveBackgroundOpaque:Qt.blend(So,ho),scrollbarSliderBackground:Qt.opacity(da,.2),scrollbarSliderHoverBackground:Qt.opacity(da,.4),scrollbarSliderActiveBackground:Qt.opacity(da,.5),overviewRulerBorder:da,ansi:Ti.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=$t(e.foreground,da),t.background=$t(e.background,So),t.cursor=Qt.blend(t.background,$t(e.cursor,zb)),t.cursorAccent=Qt.blend(t.background,$t(e.cursorAccent,Pb)),t.selectionBackgroundTransparent=$t(e.selectionBackground,ho),t.selectionBackgroundOpaque=Qt.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=$t(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=Qt.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?$t(e.selectionForeground,Rb):void 0,t.selectionForeground===Rb&&(t.selectionForeground=void 0),Qt.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=Qt.opacity(t.selectionBackgroundTransparent,.3)),Qt.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=Qt.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=$t(e.scrollbarSliderBackground,Qt.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=$t(e.scrollbarSliderHoverBackground,Qt.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=$t(e.scrollbarSliderActiveBackground,Qt.opacity(t.foreground,.5)),t.overviewRulerBorder=$t(e.overviewRulerBorder,G2),t.ansi=Ti.slice(),t.ansi[0]=$t(e.black,Ti[0]),t.ansi[1]=$t(e.red,Ti[1]),t.ansi[2]=$t(e.green,Ti[2]),t.ansi[3]=$t(e.yellow,Ti[3]),t.ansi[4]=$t(e.blue,Ti[4]),t.ansi[5]=$t(e.magenta,Ti[5]),t.ansi[6]=$t(e.cyan,Ti[6]),t.ansi[7]=$t(e.white,Ti[7]),t.ansi[8]=$t(e.brightBlack,Ti[8]),t.ansi[9]=$t(e.brightRed,Ti[9]),t.ansi[10]=$t(e.brightGreen,Ti[10]),t.ansi[11]=$t(e.brightYellow,Ti[11]),t.ansi[12]=$t(e.brightBlue,Ti[12]),t.ansi[13]=$t(e.brightMagenta,Ti[13]),t.ansi[14]=$t(e.brightCyan,Ti[14]),t.ansi[15]=$t(e.brightWhite,Ti[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let s=0;so.index-c.index),s=[];for(let o of i){let c=this._services.get(o.id);if(!c)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${o.id._id}.`);s.push(c)}let a=i.length>0?i[0].index:t.length;if(t.length!==a)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${a+1} conflicts with ${t.length} static arguments`);return new e(...t,...s)}},V2={trace:0,debug:1,info:2,warn:3,error:4,off:5},X2="xterm.js: ",gp=class extends ht{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel()))}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=V2[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;s--)this._array[this._getCyclicIndex(s+i.length)]=this._array[this._getCyclicIndex(s)];for(let s=0;sthis._maxLength){let s=this._length+i.length-this._maxLength;this._startIndex+=s,this._length=this._maxLength,this.onTrimEmitter.fire(s)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let a=t-1;a>=0;a--)this.set(e+a+i,this.get(e+a));let s=e+t+i-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s>22,i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):s]}set(t,i){this._data[t*ut+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*ut+0]=t|2097152|i[2]<<22):this._data[t*ut+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*ut+0]>>22}hasWidth(t){return this._data[t*ut+0]&12582912}getFg(t){return this._data[t*ut+1]}getBg(t){return this._data[t*ut+2]}hasContent(t){return this._data[t*ut+0]&4194303}getCodePoint(t){let i=this._data[t*ut+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*ut+0]&2097152}getString(t){let i=this._data[t*ut+0];return i&2097152?this._combined[t]:i&2097151?zs(i&2097151):""}isProtected(t){return this._data[t*ut+2]&536870912}loadCell(t,i){return lu=t*ut,i.content=this._data[lu+0],i.fg=this._data[lu+1],i.bg=this._data[lu+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*ut+0]=i.content,this._data[t*ut+1]=i.fg,this._data[t*ut+2]=i.bg}setCellFromCodepoint(t,i,s,a){a.bg&268435456&&(this._extendedAttrs[t]=a.extended),this._data[t*ut+0]=i|s<<22,this._data[t*ut+1]=a.fg,this._data[t*ut+2]=a.bg}addCodepointToCell(t,i,s){let a=this._data[t*ut+0];a&2097152?this._combined[t]+=zs(i):a&2097151?(this._combined[t]=zs(a&2097151)+zs(i),a&=-2097152,a|=2097152):a=i|1<<22,s&&(a&=-12582913,a|=s<<22),this._data[t*ut+0]=a}insertCells(t,i,s){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,s),i=0;--o)this.setCell(t+i+o,this.loadCell(t+o,a));for(let o=0;othis.length){if(this._data.buffer.byteLength>=s*4)this._data=new Uint32Array(this._data.buffer,0,s);else{let a=new Uint32Array(s);a.set(this._data),this._data=a}for(let a=this.length;a=t&&delete this._combined[h]}let o=Object.keys(this._extendedAttrs);for(let c=0;c=t&&delete this._extendedAttrs[h]}}return this.length=t,s*4*cf=0;--t)if(this._data[t*ut+0]&4194303)return t+(this._data[t*ut+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*ut+0]&4194303||this._data[t*ut+2]&50331648)return t+(this._data[t*ut+0]>>22);return 0}copyCellsFrom(t,i,s,a,o){let c=t._data;if(o)for(let p=a-1;p>=0;p--){for(let f=0;f=i&&(this._combined[f-i+s]=t._combined[f])}}translateToString(t,i,s,a){i=i??0,s=s??this.length,t&&(s=Math.min(s,this.getTrimmedLength())),a&&(a.length=0);let o="";for(;i>22||1}return a&&a.push(i),o}};function Z2(e,t,i,s,a,o){let c=[];for(let h=0;h=h&&s0&&(D>x||_[D].getTrimmedLength()===0);D--)j++;j>0&&(c.push(h+_.length-j),c.push(j)),h+=_.length-1}return c}function Q2(e,t){let i=[],s=0,a=t[s],o=0;for(let c=0;cLo(e,f,t)).reduce((p,f)=>p+f),o=0,c=0,h=0;for(;hp&&(o-=p,c++);let f=e[c].getWidth(o-1)===2;f&&o--;let _=f?i-1:i;s.push(_),h+=_}return s}function Lo(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let s=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,a=e[t+1].getWidth(0)===2;return s&&a?i-1:i}var x0=class _0{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=_0._nextId++,this._onDispose=this.register(new we),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),ga(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};x0._nextId=1;var tE=x0,Di={},fa=Di.B;Di[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"};Di.A={"#":"£"};Di.B=void 0;Di[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"};Di.C=Di[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Di.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"};Di.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"};Di.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"};Di.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"};Di.E=Di[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"};Di.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"};Di.H=Di[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"};Di["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"};var Hb=4294967295,Ub=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Si.clone(),this.savedCharset=fa,this.markers=[],this._nullCell=sr.fromCharData([0,Ly,1,0]),this._whitespaceCell=sr.fromCharData([0,Is,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ru,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new Ib(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Nu),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Nu),this._whitespaceCell}getBlankLine(e,t){return new wo(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&eHb?Hb:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Si);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new Ib(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Si),s=0,a=this._getCorrectBufferLength(t);if(a>this.lines.maxLength&&(this.lines.maxLength=a),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+o+1?(this.ybase--,o++,this.ydisp>0&&this.ydisp--):this.lines.push(new wo(e,i)));else for(let c=this._rows;c>t;c--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(a0&&(this.lines.trimStart(c),this.ybase=Math.max(this.ybase-c,0),this.ydisp=Math.max(this.ydisp-c,0),this.savedY=Math.max(this.savedY-c,0)),this.lines.maxLength=a}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),o&&(this.y+=o),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let o=0;o.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,s=Z2(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Si),i);if(s.length>0){let a=Q2(this.lines,s);J2(this.lines,a.layout),this._reflowLargerAdjustViewport(e,t,a.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let s=this.getNullCell(Si),a=i;for(;a-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;c--){let h=this.lines.get(c);if(!h||!h.isWrapped&&h.getTrimmedLength()<=e)continue;let p=[h];for(;h.isWrapped&&c>0;)h=this.lines.get(--c),p.unshift(h);if(!i){let I=this.ybase+this.y;if(I>=c&&I0&&(a.push({start:c+p.length+o,newLines:v}),o+=v.length),p.push(...v);let S=_.length-1,j=_[S];j===0&&(S--,j=_[S]);let D=p.length-x-1,E=f;for(;D>=0;){let I=Math.min(E,j);if(p[S]===void 0)break;if(p[S].copyCellsFrom(p[D],E-I,j-I,I,!0),j-=I,j===0&&(S--,j=_[S]),E-=I,E===0){D--;let te=Math.max(D,0);E=Lo(p,te,this._cols)}}for(let I=0;I0;)this.ybase===0?this.y0){let c=[],h=[];for(let j=0;j=0;j--)if(x&&x.start>f+b){for(let D=x.newLines.length-1;D>=0;D--)this.lines.set(j--,x.newLines[D]);j++,c.push({index:f+1,amount:x.newLines.length}),b+=x.newLines.length,x=a[++_]}else this.lines.set(j,h[f--]);let v=0;for(let j=c.length-1;j>=0;j--)c[j].index+=v,this.lines.onInsertEmitter.fire(c[j]),v+=c[j].amount;let S=Math.max(0,p+o-this.lines.maxLength);S>0&&this.lines.onTrimEmitter.fire(S)}}translateBufferLineToString(e,t,i=0,s){let a=this.lines.get(e);return a?a.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.linei.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},iE=class extends ht{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new we),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new Ub(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Ub(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},b0=2,v0=1,xp=class extends ht{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new we),this.onResize=this._onResize.event,this._onScroll=this._register(new we),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,b0),this.rows=Math.max(e.rawOptions.rows||0,v0),this.buffers=this._register(new iE(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,s=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:s})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,s;s=this._cachedBlankLine,(!s||s.length!==this.cols||s.getFg(0)!==e.fg||s.getBg(0)!==e.bg)&&(s=i.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;let a=i.ybase+i.scrollTop,o=i.ybase+i.scrollBottom;if(i.scrollTop===0){let c=i.lines.isFull;o===i.lines.length-1?c?i.lines.recycle().copyFrom(s):i.lines.push(s.clone()):i.lines.splice(o+1,0,s.clone()),c?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let c=o-a+1;i.lines.shiftElements(a+1,c-1,-1),i.lines.set(o,s.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let s=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),s!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};xp=ci([Re(0,gn)],xp);var nl={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Au,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},nE=["normal","bold","100","200","300","400","500","600","700","800","900"],rE=class extends ht{constructor(e){super(),this._onOptionChange=this._register(new we),this.onOptionChange=this._onOptionChange.event;let t={...nl};for(let i in e)if(i in t)try{let s=e[i];t[i]=this._sanitizeAndValidateOption(i,s)}catch(s){console.error(s)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(ii(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in nl))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,s)=>{if(!(i in nl))throw new Error(`No option with key "${i}"`);s=this._sanitizeAndValidateOption(i,s),this.rawOptions[i]!==s&&(this.rawOptions[i]=s,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let s={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,s)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=nl[e]),!sE(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=nl[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=nE.includes(t)?t:nl[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};function sE(e){return e==="block"||e==="underline"||e==="bar"}function Co(e,t=5){if(typeof e!="object")return e;let i=Array.isArray(e)?[]:{};for(let s in e)i[s]=t<=1?e[s]:e[s]&&Co(e[s],t-1);return i}var $b=Object.freeze({insertMode:!1}),Fb=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),_p=class extends ht{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new we),this.onData=this._onData.event,this._onUserInput=this._register(new we),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new we),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new we),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Co($b),this.decPrivateModes=Co(Fb)}reset(){this.modes=Co($b),this.decPrivateModes=Co(Fb)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(s=>s.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};_p=ci([Re(0,mn),Re(1,Hy),Re(2,gn)],_p);var qb={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function uf(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}var hf=String.fromCharCode,Wb={DEFAULT:e=>{let t=[uf(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${hf(t[0])}${hf(t[1])}${hf(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${uf(e,!0)};${e.x};${e.y}${t}`}},bp=class extends ht{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new we),this.onProtocolChange=this._onProtocolChange.event;for(let s of Object.keys(qb))this.addProtocol(s,qb[s]);for(let s of Object.keys(Wb))this.addEncoding(s,Wb[s]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let s=t/i,a=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(a/=s+0,Math.abs(e.deltaY)<50&&(a*=.3),this._wheelPartialScroll+=a,a=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(a*=this._bufferService.rows),a}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};bp=ci([Re(0,mn),Re(1,ba),Re(2,gn)],bp);var df=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],aE=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],Ai;function lE(e,t){let i=0,s=t.length-1,a;if(et[s][1])return!1;for(;s>=i;)if(a=i+s>>1,e>t[a][1])i=a+1;else if(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),s=i===0&&t!==0;if(s){let a=pa.extractWidth(t);a===0?s=!1:a>i&&(i=a)}return pa.createPropertyValue(0,i,s)}},pa=class yu{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new we,this.onChange=this._onChange.event;let t=new oE;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,i,s=!1){return(t&16777215)<<3|(i&3)<<1|(s?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let i=0,s=0,a=t.length;for(let o=0;o=a)return i+this.wcwidth(c);let f=t.charCodeAt(o);56320<=f&&f<=57343?c=(c-55296)*1024+f-56320+65536:i+=this.wcwidth(f)}let h=this.charProperties(c,s),p=yu.extractWidth(h);yu.extractShouldJoin(h)&&(p-=yu.extractWidth(s)),i+=p,s=h}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},cE=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Gb(e){var s;let t=(s=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1))==null?void 0:s.get(e.cols-1),i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);i&&t&&(i.isWrapped=t[3]!==0&&t[3]!==32)}var fo=2147483647,uE=256,y0=class vp{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>uE)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new vp;if(!t.length)return i;for(let s=Array.isArray(t[0])?1:0;s>8,a=this._subParamsIdx[i]&255;a-s>0&&t.push(Array.prototype.slice.call(this._subParams,s,a))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>fo?fo:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>fo?fo:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,s=this._subParamsIdx[t]&255;return s-i>0?this._subParams.subarray(i,s):null}getSubParamsAll(){let t={};for(let i=0;i>8,a=this._subParamsIdx[i]&255;a-s>0&&(t[i]=this._subParams.slice(s,a))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let s=this._digitIsSub?this._subParams:this.params,a=s[i-1];s[i-1]=~a?Math.min(a*10+t,fo):t}},po=[],hE=class{constructor(){this._state=0,this._active=po,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=po}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=po,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||po,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,i){if(!this._active.length)this._handlerFb(this._id,"PUT",Iu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,i)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].end(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=po,this._id=-1,this._state=0}}},Pn=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Iu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,t}},mo=[],dE=class{constructor(){this._handlers=Object.create(null),this._active=mo,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=mo}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=mo,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||mo,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",Iu(e,t,i));else for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let i=!1,s=this._active.length-1,a=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,a=this._stack.fallThrough,this._stack.paused=!1),!a&&i===!1){for(;s>=0&&(i=this._active[s].unhook(e),i!==!0);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}this._active=mo,this._ident=0}},ko=new y0;ko.addParam(0);var Yb=class{constructor(e){this._handler=e,this._data="",this._params=ko,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():ko,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Iu(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(i=>(this._params=ko,this._data="",this._hitLimit=!1,i));return this._params=ko,this._data="",this._hitLimit=!1,t}},fE=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,s){this.table[t<<8|e]=i<<4|s}addMany(e,t,i,s){for(let a=0;ap),i=(h,p)=>t.slice(h,p),s=i(32,127),a=i(0,24);a.push(25),a.push.apply(a,i(28,32));let o=i(0,14),c;e.setDefault(1,0),e.addMany(s,0,2,0);for(c in o)e.addMany([24,26,153,154],c,3,0),e.addMany(i(128,144),c,3,0),e.addMany(i(144,152),c,3,0),e.add(156,c,0,0),e.add(27,c,11,1),e.add(157,c,4,8),e.addMany([152,158,159],c,0,7),e.add(155,c,11,3),e.add(144,c,11,9);return e.addMany(a,0,3,0),e.addMany(a,1,3,1),e.add(127,1,0,1),e.addMany(a,8,0,8),e.addMany(a,3,3,3),e.add(127,3,0,3),e.addMany(a,4,3,4),e.add(127,4,0,4),e.addMany(a,6,3,6),e.addMany(a,5,3,5),e.add(127,5,0,5),e.addMany(a,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(s,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(a,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(a,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(a,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(a,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(a,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(a,13,13,13),e.addMany(s,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(nr,0,2,0),e.add(nr,8,5,8),e.add(nr,6,0,6),e.add(nr,11,0,11),e.add(nr,13,13,13),e})(),mE=class extends ht{constructor(e=pE){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new y0,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,i,s)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,i)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(ii(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new hE),this._dcsParser=this._register(new dE),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let a=0;ao||o>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=o}}if(e.final.length!==1)throw new Error("final must be a single byte");let s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let i=this._identifier(e,[48,126]);this._escHandlers[i]===void 0&&(this._escHandlers[i]=[]);let s=this._escHandlers[i];return s.push(t),{dispose:()=>{let a=s.indexOf(t);a!==-1&&s.splice(a,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let i=this._identifier(e);this._csiHandlers[i]===void 0&&(this._csiHandlers[i]=[]);let s=this._csiHandlers[i];return s.push(t),{dispose:()=>{let a=s.indexOf(t);a!==-1&&s.splice(a,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,s,a){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=a}parse(e,t,i){let s=0,a=0,o=0,c;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(i===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let h=this._parseStack.handlers,p=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(i===!1&&p>-1){for(;p>=0&&(c=h[p](this._params),c!==!0);p--)if(c instanceof Promise)return this._parseStack.handlerPos=p,c}this._parseStack.handlers=[];break;case 4:if(i===!1&&p>-1){for(;p>=0&&(c=h[p](),c!==!0);p--)if(c instanceof Promise)return this._parseStack.handlerPos=p,c}this._parseStack.handlers=[];break;case 6:if(s=e[this._parseStack.chunkPos],c=this._dcsParser.unhook(s!==24&&s!==26,i),c)return c;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(s=e[this._parseStack.chunkPos],c=this._oscParser.end(s!==24&&s!==26,i),c)return c;s===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let h=o;h>4){case 2:for(let b=h+1;;++b){if(b>=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=t||(s=e[b])<32||s>126&&s=0&&(c=p[f](this._params),c!==!0);f--)if(c instanceof Promise)return this._preserveStack(3,p,f,a,h),c;f<0&&this._csiHandlerFb(this._collect<<8|s,this._params),this.precedingJoinState=0;break;case 8:do switch(s){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(s-48)}while(++h47&&s<60);h--;break;case 9:this._collect<<=8,this._collect|=s;break;case 10:let _=this._escHandlers[this._collect<<8|s],x=_?_.length-1:-1;for(;x>=0&&(c=_[x](),c!==!0);x--)if(c instanceof Promise)return this._preserveStack(4,_,x,a,h),c;x<0&&this._escHandlerFb(this._collect<<8|s),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|s,this._params);break;case 13:for(let b=h+1;;++b)if(b>=t||(s=e[b])===24||s===26||s===27||s>127&&s=t||(s=e[b])<32||s>127&&s>4:o>>8}return s}}function ff(e,t){let i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}function _E(e,t=16){let[i,s,a]=e;return`rgb:${ff(i,t)}/${ff(s,t)}/${ff(a,t)}`}var bE={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Ls=131072,Vb=10;function Xb(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var Zb=5e3,Qb=0,vE=class extends ht{constructor(e,t,i,s,a,o,c,h,p=new mE){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=s,this._optionsService=a,this._oscLinkService=o,this._coreMouseService=c,this._unicodeService=h,this._parser=p,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new IC,this._utf8Decoder=new HC,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=Si.clone(),this._eraseAttrDataInternal=Si.clone(),this._onRequestBell=this._register(new we),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new we),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new we),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new we),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new we),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new we),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new we),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new we),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new we),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new we),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new we),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new we),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new we),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new yp(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(f=>this._activeBuffer=f.activeBuffer)),this._parser.setCsiHandlerFallback((f,_)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(f),params:_.toArray()})}),this._parser.setEscHandlerFallback(f=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(f)})}),this._parser.setExecuteHandlerFallback(f=>{this._logService.debug("Unknown EXECUTE code: ",{code:f})}),this._parser.setOscHandlerFallback((f,_,x)=>{this._logService.debug("Unknown OSC code: ",{identifier:f,action:_,data:x})}),this._parser.setDcsHandlerFallback((f,_,x)=>{_==="HOOK"&&(x=x.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(f),action:_,payload:x})}),this._parser.setPrintHandler((f,_,x)=>this.print(f,_,x)),this._parser.registerCsiHandler({final:"@"},f=>this.insertChars(f)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},f=>this.scrollLeft(f)),this._parser.registerCsiHandler({final:"A"},f=>this.cursorUp(f)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},f=>this.scrollRight(f)),this._parser.registerCsiHandler({final:"B"},f=>this.cursorDown(f)),this._parser.registerCsiHandler({final:"C"},f=>this.cursorForward(f)),this._parser.registerCsiHandler({final:"D"},f=>this.cursorBackward(f)),this._parser.registerCsiHandler({final:"E"},f=>this.cursorNextLine(f)),this._parser.registerCsiHandler({final:"F"},f=>this.cursorPrecedingLine(f)),this._parser.registerCsiHandler({final:"G"},f=>this.cursorCharAbsolute(f)),this._parser.registerCsiHandler({final:"H"},f=>this.cursorPosition(f)),this._parser.registerCsiHandler({final:"I"},f=>this.cursorForwardTab(f)),this._parser.registerCsiHandler({final:"J"},f=>this.eraseInDisplay(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},f=>this.eraseInDisplay(f,!0)),this._parser.registerCsiHandler({final:"K"},f=>this.eraseInLine(f,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},f=>this.eraseInLine(f,!0)),this._parser.registerCsiHandler({final:"L"},f=>this.insertLines(f)),this._parser.registerCsiHandler({final:"M"},f=>this.deleteLines(f)),this._parser.registerCsiHandler({final:"P"},f=>this.deleteChars(f)),this._parser.registerCsiHandler({final:"S"},f=>this.scrollUp(f)),this._parser.registerCsiHandler({final:"T"},f=>this.scrollDown(f)),this._parser.registerCsiHandler({final:"X"},f=>this.eraseChars(f)),this._parser.registerCsiHandler({final:"Z"},f=>this.cursorBackwardTab(f)),this._parser.registerCsiHandler({final:"`"},f=>this.charPosAbsolute(f)),this._parser.registerCsiHandler({final:"a"},f=>this.hPositionRelative(f)),this._parser.registerCsiHandler({final:"b"},f=>this.repeatPrecedingCharacter(f)),this._parser.registerCsiHandler({final:"c"},f=>this.sendDeviceAttributesPrimary(f)),this._parser.registerCsiHandler({prefix:">",final:"c"},f=>this.sendDeviceAttributesSecondary(f)),this._parser.registerCsiHandler({final:"d"},f=>this.linePosAbsolute(f)),this._parser.registerCsiHandler({final:"e"},f=>this.vPositionRelative(f)),this._parser.registerCsiHandler({final:"f"},f=>this.hVPosition(f)),this._parser.registerCsiHandler({final:"g"},f=>this.tabClear(f)),this._parser.registerCsiHandler({final:"h"},f=>this.setMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"h"},f=>this.setModePrivate(f)),this._parser.registerCsiHandler({final:"l"},f=>this.resetMode(f)),this._parser.registerCsiHandler({prefix:"?",final:"l"},f=>this.resetModePrivate(f)),this._parser.registerCsiHandler({final:"m"},f=>this.charAttributes(f)),this._parser.registerCsiHandler({final:"n"},f=>this.deviceStatus(f)),this._parser.registerCsiHandler({prefix:"?",final:"n"},f=>this.deviceStatusPrivate(f)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},f=>this.softReset(f)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},f=>this.setCursorStyle(f)),this._parser.registerCsiHandler({final:"r"},f=>this.setScrollRegion(f)),this._parser.registerCsiHandler({final:"s"},f=>this.saveCursor(f)),this._parser.registerCsiHandler({final:"t"},f=>this.windowOptions(f)),this._parser.registerCsiHandler({final:"u"},f=>this.restoreCursor(f)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},f=>this.insertColumns(f)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},f=>this.deleteColumns(f)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},f=>this.selectProtected(f)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},f=>this.requestMode(f,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},f=>this.requestMode(f,!1)),this._parser.setExecuteHandler(me.BEL,()=>this.bell()),this._parser.setExecuteHandler(me.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(me.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(me.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(me.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(me.BS,()=>this.backspace()),this._parser.setExecuteHandler(me.HT,()=>this.tab()),this._parser.setExecuteHandler(me.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(me.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(bu.IND,()=>this.index()),this._parser.setExecuteHandler(bu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(bu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Pn(f=>(this.setTitle(f),this.setIconName(f),!0))),this._parser.registerOscHandler(1,new Pn(f=>this.setIconName(f))),this._parser.registerOscHandler(2,new Pn(f=>this.setTitle(f))),this._parser.registerOscHandler(4,new Pn(f=>this.setOrReportIndexedColor(f))),this._parser.registerOscHandler(8,new Pn(f=>this.setHyperlink(f))),this._parser.registerOscHandler(10,new Pn(f=>this.setOrReportFgColor(f))),this._parser.registerOscHandler(11,new Pn(f=>this.setOrReportBgColor(f))),this._parser.registerOscHandler(12,new Pn(f=>this.setOrReportCursorColor(f))),this._parser.registerOscHandler(104,new Pn(f=>this.restoreIndexedColor(f))),this._parser.registerOscHandler(110,new Pn(f=>this.restoreFgColor(f))),this._parser.registerOscHandler(111,new Pn(f=>this.restoreBgColor(f))),this._parser.registerOscHandler(112,new Pn(f=>this.restoreCursorColor(f))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let f in Di)this._parser.registerEscHandler({intermediates:"(",final:f},()=>this.selectCharset("("+f)),this._parser.registerEscHandler({intermediates:")",final:f},()=>this.selectCharset(")"+f)),this._parser.registerEscHandler({intermediates:"*",final:f},()=>this.selectCharset("*"+f)),this._parser.registerEscHandler({intermediates:"+",final:f},()=>this.selectCharset("+"+f)),this._parser.registerEscHandler({intermediates:"-",final:f},()=>this.selectCharset("-"+f)),this._parser.registerEscHandler({intermediates:".",final:f},()=>this.selectCharset("."+f)),this._parser.registerEscHandler({intermediates:"/",final:f},()=>this.selectCharset("/"+f));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(f=>(this._logService.error("Parsing error: ",f),f)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new Yb((f,_)=>this.requestStatusString(f,_)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,i)=>setTimeout(()=>i("#SLOW_TIMEOUT"),Zb))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${Zb} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,a=this._activeBuffer.y,o=0,c=this._parseStack.paused;if(c){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,a=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Ls&&(o=this._parseStack.position+Ls)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,f=>String.fromCharCode(f)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(f=>f.charCodeAt(0)):e),this._parseBuffer.lengthLs)for(let f=o;f0&&x.getWidth(this._activeBuffer.x-1)===2&&x.setCellFromCodepoint(this._activeBuffer.x-1,0,1,_);let b=this._parser.precedingJoinState;for(let v=t;vh){if(p){let E=x,N=this._activeBuffer.x-D;for(this._activeBuffer.x=D,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),x=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),D>0&&x instanceof wo&&x.copyCellsFrom(E,N,0,D,!1);N=0;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_);continue}if(f&&(x.insertCells(this._activeBuffer.x,a-D,this._activeBuffer.getNullCell(_)),x.getWidth(h-1)===2&&x.setCellFromCodepoint(h-1,0,1,_)),x.setCellFromCodepoint(this._activeBuffer.x++,s,a,_),a>0)for(;--a;)x.setCellFromCodepoint(this._activeBuffer.x++,0,0,_)}this._parser.precedingJoinState=b,this._activeBuffer.x0&&x.getWidth(this._activeBuffer.x)===0&&!x.hasContent(this._activeBuffer.x)&&x.setCellFromCodepoint(this._activeBuffer.x,0,1,_),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,i=>Xb(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Yb(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Pn(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var e;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&((e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&e.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);t.hasWidth(this._activeBuffer.x)&&!t.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,a=!1){let o=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);o.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),a),s&&(o.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){var s;this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!((s=this._activeBuffer.lines.get(this._activeBuffer.ybase+i))!=null&&s.getTrimmedLength()););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let a=this._activeBuffer.lines.length-this._bufferService.rows;a>0&&(this._activeBuffer.lines.trimStart(a),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-a,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-a,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let p=h;for(let f=1;f0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(me.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(me.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(me.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(me.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(me.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t(j[j.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",j[j.SET=1]="SET",j[j.RESET=2]="RESET",j[j.PERMANENTLY_SET=3]="PERMANENTLY_SET",j[j.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(void 0||(i={}));let s=this._coreService.decPrivateModes,{activeProtocol:a,activeEncoding:o}=this._coreMouseService,c=this._coreService,{buffers:h,cols:p}=this._bufferService,{active:f,alt:_}=h,x=this._optionsService.rawOptions,b=(j,D)=>(c.triggerDataEvent(`${me.ESC}[${t?"":"?"}${j};${D}$y`),!0),v=j=>j?1:2,S=e.params[0];return t?S===2?b(S,4):S===4?b(S,v(c.modes.insertMode)):S===12?b(S,3):S===20?b(S,v(x.convertEol)):b(S,0):S===1?b(S,v(s.applicationCursorKeys)):S===3?b(S,x.windowOptions.setWinLines?p===80?2:p===132?1:0:0):S===6?b(S,v(s.origin)):S===7?b(S,v(s.wraparound)):S===8?b(S,3):S===9?b(S,v(a==="X10")):S===12?b(S,v(x.cursorBlink)):S===25?b(S,v(!c.isCursorHidden)):S===45?b(S,v(s.reverseWraparound)):S===66?b(S,v(s.applicationKeypad)):S===67?b(S,4):S===1e3?b(S,v(a==="VT200")):S===1002?b(S,v(a==="DRAG")):S===1003?b(S,v(a==="ANY")):S===1004?b(S,v(s.sendFocus)):S===1005?b(S,4):S===1006?b(S,v(o==="SGR")):S===1015?b(S,4):S===1016?b(S,v(o==="SGR_PIXELS")):S===1048?b(S,1):S===47||S===1047||S===1049?b(S,v(f===_)):S===2004?b(S,v(s.bracketedPasteMode)):S===2026?b(S,v(s.synchronizedOutput)):b(S,0)}_updateAttrColor(e,t,i,s,a){return t===2?(e|=50331648,e&=-16777216,e|=Ho.fromColorRGB([i,s,a])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let s=[0,0,-1,0,0,0],a=0,o=0;do{if(s[o+a]=e.params[t+o],e.hasSubParams(t+o)){let c=e.getSubParams(t+o),h=0;do s[1]===5&&(a=1),s[o+h+1+a]=c[h];while(++h=2||s[1]===2&&o+a>=5)break;s[1]&&(a=1)}while(++o+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=Si.fg,e.bg=Si.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,i,s=this._curAttrData;for(let a=0;a=30&&i<=37?(s.fg&=-50331904,s.fg|=16777216|i-30):i>=40&&i<=47?(s.bg&=-50331904,s.bg|=16777216|i-40):i>=90&&i<=97?(s.fg&=-50331904,s.fg|=16777216|i-90|8):i>=100&&i<=107?(s.bg&=-50331904,s.bg|=16777216|i-100|8):i===0?this._processSGR0(s):i===1?s.fg|=134217728:i===3?s.bg|=67108864:i===4?(s.fg|=268435456,this._processUnderline(e.hasSubParams(a)?e.getSubParams(a)[0]:1,s)):i===5?s.fg|=536870912:i===7?s.fg|=67108864:i===8?s.fg|=1073741824:i===9?s.fg|=2147483648:i===2?s.bg|=134217728:i===21?this._processUnderline(2,s):i===22?(s.fg&=-134217729,s.bg&=-134217729):i===23?s.bg&=-67108865:i===24?(s.fg&=-268435457,this._processUnderline(0,s)):i===25?s.fg&=-536870913:i===27?s.fg&=-67108865:i===28?s.fg&=-1073741825:i===29?s.fg&=2147483647:i===39?(s.fg&=-67108864,s.fg|=Si.fg&16777215):i===49?(s.bg&=-67108864,s.bg|=Si.bg&16777215):i===38||i===48||i===58?a+=this._extractColor(e,a,s):i===53?s.bg|=1073741824:i===55?s.bg&=-1073741825:i===59?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):i===100?(s.fg&=-67108864,s.fg|=Si.fg&16777215,s.bg&=-67108864,s.bg|=Si.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${me.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${me.ESC}[${t};${i}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${me.ESC}[?${t};${i}R`);break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=Si.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Xb(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${me.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Vb&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Vb&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],i=e.split(";");for(;i.length>1;){let s=i.shift(),a=i.shift();if(/^\d+$/.exec(s)){let o=parseInt(s);if(Jb(o))if(a==="?")t.push({type:0,index:o});else{let c=Kb(a);c&&t.push({type:1,index:o,color:c})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let i=e.slice(0,t).trim(),s=e.slice(t+1);return s?this._createHyperlink(i,s):i.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i=e.split(":"),s,a=i.findIndex(o=>o.startsWith("id="));return a!==-1&&(s=i[a].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let i=e.split(";");for(let s=0;s=this._specialColors.length);++s,++t)if(i[s]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let a=Kb(i[s]);a&&this._onColor.fire([{type:1,index:this._specialColors[t],color:a}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],i=e.split(";");for(let s=0;s=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=Si.clone(),this._eraseAttrDataInternal=Si.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new sr;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${me.ESC}${c}${me.ESC}\\`),!0),s=this._bufferService.buffer,a=this._optionsService.rawOptions;return i(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${s.scrollTop+1};${s.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[a.cursorStyle]-(a.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},yp=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(Qb=e,e=t,t=Qb),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};yp=ci([Re(0,mn)],yp);function Jb(e){return 0<=e&&e<256}var yE=5e7,ev=12,SE=50,wE=class extends ht{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new we),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let i;for(;i=this._writeBuffer.shift();){this._action(i);let s=this._callbacks.shift();s&&s()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>yE)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let s=this._writeBuffer[this._bufferOffset],a=this._action(s,t);if(a){let c=h=>performance.now()-i>=ev?setTimeout(()=>this._innerWrite(0,h)):this._innerWrite(i,h);a.catch(h=>(queueMicrotask(()=>{throw h}),Promise.resolve(!1))).then(c);return}let o=this._callbacks[this._bufferOffset];if(o&&o(),this._bufferOffset++,this._pendingData-=s.length,performance.now()-i>=ev)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>SE&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},Sp=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let h=t.addMarker(t.ybase+t.y),p={data:e,id:this._nextId++,lines:[h]};return h.onDispose(()=>this._removeMarkerFromLink(p,h)),this._dataByLinkId.set(p.id,p),p.id}let i=e,s=this._getEntryIdKey(i),a=this._entriesWithId.get(s);if(a)return this.addLineToLink(a.id,t.ybase+t.y),a.id;let o=t.addMarker(t.ybase+t.y),c={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[o]};return o.onDispose(()=>this._removeMarkerFromLink(c,o)),this._entriesWithId.set(c.key,c),this._dataByLinkId.set(c.id,c),c.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(s=>s.line!==t)){let s=this._bufferService.buffer.addMarker(t);i.lines.push(s),s.onDispose(()=>this._removeMarkerFromLink(i,s))}}getLinkData(e){var t;return(t=this._dataByLinkId.get(e))==null?void 0:t.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};Sp=ci([Re(0,mn)],Sp);var tv=!1,CE=class extends ht{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new pl),this._onBinary=this._register(new we),this.onBinary=this._onBinary.event,this._onData=this._register(new we),this.onData=this._onData.event,this._onLineFeed=this._register(new we),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new we),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new we),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new we),this._instantiationService=new K2,this.optionsService=this._register(new rE(e)),this._instantiationService.setService(gn,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(xp)),this._instantiationService.setService(mn,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(gp)),this._instantiationService.setService(Hy,this._logService),this.coreService=this._register(this._instantiationService.createInstance(_p)),this._instantiationService.setService(ba,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(bp)),this._instantiationService.setService(Iy,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(pa)),this._instantiationService.setService(qC,this.unicodeService),this._charsetService=this._instantiationService.createInstance(cE),this._instantiationService.setService(FC,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(Sp),this._instantiationService.setService(Uy,this._oscLinkService),this._inputHandler=this._register(new vE(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(en.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(en.forward(this._bufferService.onResize,this._onResize)),this._register(en.forward(this.coreService.onData,this._onData)),this._register(en.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new wE((t,i)=>this._inputHandler.parse(t,i))),this._register(en.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new we),this._onScroll.event(e=>{var t;(t=this._onScrollApi)==null||t.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!tv&&(this._logService.warn("writeSync is unreliable and will be removed soon."),tv=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,b0),t=Math.max(t,v0),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Gb.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(Gb(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ii(()=>{for(let t of e)t.dispose()})}}},kE={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};function EE(e,t,i,s){var c;let a={type:0,cancel:!1,key:void 0},o=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?a.key=me.ESC+"OA":a.key=me.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?a.key=me.ESC+"OD":a.key=me.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?a.key=me.ESC+"OC":a.key=me.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?a.key=me.ESC+"OB":a.key=me.ESC+"[B");break;case 8:a.key=e.ctrlKey?"\b":me.DEL,e.altKey&&(a.key=me.ESC+a.key);break;case 9:if(e.shiftKey){a.key=me.ESC+"[Z";break}a.key=me.HT,a.cancel=!0;break;case 13:a.key=e.altKey?me.ESC+me.CR:me.CR,a.cancel=!0;break;case 27:a.key=me.ESC,e.altKey&&(a.key=me.ESC+me.ESC),a.cancel=!0;break;case 37:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"D":t?a.key=me.ESC+"OD":a.key=me.ESC+"[D";break;case 39:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"C":t?a.key=me.ESC+"OC":a.key=me.ESC+"[C";break;case 38:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"A":t?a.key=me.ESC+"OA":a.key=me.ESC+"[A";break;case 40:if(e.metaKey)break;o?a.key=me.ESC+"[1;"+(o+1)+"B":t?a.key=me.ESC+"OB":a.key=me.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(a.key=me.ESC+"[2~");break;case 46:o?a.key=me.ESC+"[3;"+(o+1)+"~":a.key=me.ESC+"[3~";break;case 36:o?a.key=me.ESC+"[1;"+(o+1)+"H":t?a.key=me.ESC+"OH":a.key=me.ESC+"[H";break;case 35:o?a.key=me.ESC+"[1;"+(o+1)+"F":t?a.key=me.ESC+"OF":a.key=me.ESC+"[F";break;case 33:e.shiftKey?a.type=2:e.ctrlKey?a.key=me.ESC+"[5;"+(o+1)+"~":a.key=me.ESC+"[5~";break;case 34:e.shiftKey?a.type=3:e.ctrlKey?a.key=me.ESC+"[6;"+(o+1)+"~":a.key=me.ESC+"[6~";break;case 112:o?a.key=me.ESC+"[1;"+(o+1)+"P":a.key=me.ESC+"OP";break;case 113:o?a.key=me.ESC+"[1;"+(o+1)+"Q":a.key=me.ESC+"OQ";break;case 114:o?a.key=me.ESC+"[1;"+(o+1)+"R":a.key=me.ESC+"OR";break;case 115:o?a.key=me.ESC+"[1;"+(o+1)+"S":a.key=me.ESC+"OS";break;case 116:o?a.key=me.ESC+"[15;"+(o+1)+"~":a.key=me.ESC+"[15~";break;case 117:o?a.key=me.ESC+"[17;"+(o+1)+"~":a.key=me.ESC+"[17~";break;case 118:o?a.key=me.ESC+"[18;"+(o+1)+"~":a.key=me.ESC+"[18~";break;case 119:o?a.key=me.ESC+"[19;"+(o+1)+"~":a.key=me.ESC+"[19~";break;case 120:o?a.key=me.ESC+"[20;"+(o+1)+"~":a.key=me.ESC+"[20~";break;case 121:o?a.key=me.ESC+"[21;"+(o+1)+"~":a.key=me.ESC+"[21~";break;case 122:o?a.key=me.ESC+"[23;"+(o+1)+"~":a.key=me.ESC+"[23~";break;case 123:o?a.key=me.ESC+"[24;"+(o+1)+"~":a.key=me.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?a.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?a.key=me.NUL:e.keyCode>=51&&e.keyCode<=55?a.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?a.key=me.DEL:e.keyCode===219?a.key=me.ESC:e.keyCode===220?a.key=me.FS:e.keyCode===221&&(a.key=me.GS);else if((!i||s)&&e.altKey&&!e.metaKey){let h=(c=kE[e.keyCode])==null?void 0:c[e.shiftKey?1:0];if(h)a.key=me.ESC+h;else if(e.keyCode>=65&&e.keyCode<=90){let p=e.ctrlKey?e.keyCode-64:e.keyCode+32,f=String.fromCharCode(p);e.shiftKey&&(f=f.toUpperCase()),a.key=me.ESC+f}else if(e.keyCode===32)a.key=me.ESC+(e.ctrlKey?me.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let p=e.code.slice(3,4);e.shiftKey||(p=p.toLowerCase()),a.key=me.ESC+p,a.cancel=!0}}else i&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(a.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?a.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(a.key=me.US),e.key==="@"&&(a.key=me.NUL));break}return a}var pi=0,NE=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ru,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ru,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((a,o)=>this._getKey(a)-this._getKey(o)),t=0,i=0,s=new Array(this._array.length+this._insertedValues.length);for(let a=0;a=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(s[a]=e[t],t++):s[a]=this._array[i++];this._array=s,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(pi=this._search(t),pi===-1)||this._getKey(this._array[pi])!==t)return!1;do if(this._array[pi]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(pi),!0;while(++pia-o),t=0,i=new Array(this._array.length-e.length),s=0;for(let a=0;a0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(pi=this._search(e),!(pi<0||pi>=this._array.length)&&this._getKey(this._array[pi])===e))do yield this._array[pi];while(++pi=this._array.length)&&this._getKey(this._array[pi])===e))do t(this._array[pi]);while(++pi=t;){let s=t+i>>1,a=this._getKey(this._array[s]);if(a>e)i=s-1;else if(a0&&this._getKey(this._array[s-1])===e;)s--;return s}}return t}},pf=0,iv=0,jE=class extends ht{constructor(){super(),this._decorations=new NE(e=>e==null?void 0:e.marker.line),this._onDecorationRegistered=this._register(new we),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new we),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(ii(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new TE(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),s=t.onDispose(()=>{s.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let s=0,a=0;for(let o of this._decorations.getKeyIterator(t))s=o.options.x??0,a=s+(o.options.width??1),e>=s&&e{pf=a.options.x??0,iv=pf+(a.options.width??1),e>=pf&&e=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){let a=s-this._lastRefreshMs,o=this._debounceThresholdMS-a;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},o)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},nv=20,Du=class extends ht{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let a=this._coreBrowserService.mainDocument;this._accessibilityContainer=a.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=a.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let o=0;othis._handleBoundaryFocus(o,0),this._bottomBoundaryFocusListener=o=>this._handleBoundaryFocus(o,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=a.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new RE(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(o=>this._handleResize(o.rows))),this._register(this._terminal.onRender(o=>this._refreshRows(o.start,o.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(o=>this._handleChar(o))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` +`))),this._register(this._terminal.onA11yTab(o=>this._handleTab(o))),this._register(this._terminal.onKey(o=>this._handleKey(o.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(Ze(a,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(ii(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` +`&&(this._liveRegionLineCount++,this._liveRegionLineCount===nv+1&&(this._liveRegion.textContent+=$f.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,s=i.lines.length.toString();for(let a=e;a<=t;a++){let o=i.lines.get(i.ydisp+a),c=[],h=(o==null?void 0:o.translateToString(!0,void 0,void 0,c))||"",p=(i.ydisp+a+1).toString(),f=this._rowElements[a];f&&(h.length===0?(f.textContent=" ",this._rowColumns.set(f,[0,1])):(f.textContent=h,this._rowColumns.set(f,c)),f.setAttribute("aria-posinset",p),f.setAttribute("aria-setsize",s),this._alignRowWidth(f))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i=e.target,s=this._rowElements[t===0?1:this._rowElements.length-2],a=i.getAttribute("aria-posinset"),o=t===0?"1":`${this._terminal.buffer.lines.length}`;if(a===o||e.relatedTarget!==s)return;let c,h;if(t===0?(c=i,h=this._rowElements.pop(),this._rowContainer.removeChild(h)):(c=this._rowElements.shift(),h=i,this._rowContainer.removeChild(c)),c.removeEventListener("focus",this._topBoundaryFocusListener),h.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let p=this._createAccessibilityTreeNode();this._rowElements.unshift(p),this._rowContainer.insertAdjacentElement("afterbegin",p)}else{let p=this._createAccessibilityTreeNode();this._rowElements.push(p),this._rowContainer.appendChild(p)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){var h;if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let s=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:s,offset:((h=s.textContent)==null?void 0:h.length)??0}),!this._rowContainer.contains(i.node))return;let a=({node:p,offset:f})=>{let _=p instanceof Text?p.parentNode:p,x=parseInt(_==null?void 0:_.getAttribute("aria-posinset"),10)-1;if(isNaN(x))return console.warn("row is invalid. Race condition?"),null;let b=this._rowColumns.get(_);if(!b)return console.warn("columns is null. Race condition?"),null;let v=f=this._terminal.cols&&(++x,v=0),{row:x,column:v}},o=a(t),c=a(i);if(!(!o||!c)){if(o.row>c.row||o.row===c.row&&o.column>=c.column)throw new Error("invalid range");this._terminal.select(o.column,o.row,(c.row-o.row)*this._terminal.cols-o.column+c.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;te;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{var o;ga(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(o=this._activeProviderReplies)==null||o.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Ze(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Ze(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Ze(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Ze(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let i=e.composedPath();for(let s=0;s{o==null||o.forEach(c=>{c.link.dispose&&c.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(let[o,c]of this._linkProviderService.linkProviders.entries())t?(a=this._activeProviderReplies)!=null&&a.get(o)&&(i=this._checkLinkProviderResult(o,e,i)):c.provideLinks(e.y,h=>{var f,_;if(this._isMouseOut)return;let p=h==null?void 0:h.map(x=>({link:x}));(f=this._activeProviderReplies)==null||f.set(o,p),i=this._checkLinkProviderResult(o,e,i),((_=this._activeProviderReplies)==null?void 0:_.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let s=0;se?this._bufferService.cols:c.link.range.end.x;for(let f=h;f<=p;f++){if(i.has(f)){a.splice(o--,1);break}i.add(f)}}}}_checkLinkProviderResult(e,t,i){var o;if(!this._activeProviderReplies)return i;let s=this._activeProviderReplies.get(e),a=!1;for(let c=0;cthis._linkAtPosition(h.link,t));c&&(i=!0,this._handleNewLink(c))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let c=0;cthis._linkAtPosition(p.link,t));if(h){i=!0,this._handleNewLink(h);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&DE(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,ga(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.pointerCursor},set:i=>{var s;(s=this._currentLink)!=null&&s.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.underline},set:i=>{var s,a,o;(s=this._currentLink)!=null&&s.state&&((o=(a=this._currentLink)==null?void 0:a.state)==null?void 0:o.decorations.underline)!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let s=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,a=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=a&&(this._clearCurrentLink(s,a),this._lastMouseEvent)){let o=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);o&&this._askForLink(o,!1)}})))}_linkHover(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,s=this._bufferService.buffer.ydisp,a=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(a)}_linkLeave(e,t,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,a=t.y*this._bufferService.cols+t.x;return i<=a&&a<=s}_positionFromMouseEvent(e,t,i){let s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,a){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:a}}};wp=ci([Re(1,Fp),Re(2,rs),Re(3,mn),Re(4,Fy)],wp);function DE(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var ME=class extends CE{constructor(e={}){super(e),this._linkifier=this._register(new pl),this.browser=o0,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new pl),this._onCursorMove=this._register(new we),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new we),this.onKey=this._onKey.event,this._onRender=this._register(new we),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new we),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new we),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new we),this.onBell=this._onBell.event,this._onFocus=this._register(new we),this._onBlur=this._register(new we),this._onA11yCharEmitter=this._register(new we),this._onA11yTabEmitter=this._register(new we),this._onWillOpen=this._register(new we),this._setup(),this._decorationService=this._instantiationService.createInstance(jE),this._instantiationService.setService(Uo,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(S2),this._instantiationService.setService(Fy,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(qf)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh((t==null?void 0:t.start)??0,(t==null?void 0:t.end)??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(en.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(en.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(en.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(en.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(ii(()=>{var t,i;this._customKeyEventHandler=void 0,(i=(t=this.element)==null?void 0:t.parentNode)==null||i.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let i,s="";switch(t.index){case 256:i="foreground",s="10";break;case 257:i="background",s="11";break;case 258:i="cursor",s="12";break;default:i="ansi",s="4;"+t.index}switch(t.type){case 0:let a=Qt.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${me.ESC}]${s};${_E(a)}${a0.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(o=>o.ansi[t.index]=wi.toColor(...t.color));else{let o=i;this._themeService.modifyColors(c=>c[o]=wi.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Du,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(me.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var e;return(e=this.textarea)==null?void 0:e.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(me.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,a=t.getWidth(i),o=this._renderService.dimensions.css.cell.width*a,c=this.buffer.y*this._renderService.dimensions.css.cell.height,h=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=h+"px",this.textarea.style.top=c+"px",this.textarea.style.width=o+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(Ze(this.element,"copy",t=>{this.hasSelection()&&zC(t,this._selectionService)}));let e=t=>PC(t,this.textarea,this.coreService,this.optionsService);this._register(Ze(this.textarea,"paste",e)),this._register(Ze(this.element,"paste",e)),c0?this._register(Ze(this.element,"mousedown",t=>{t.button===2&&fb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Ze(this.element,"contextmenu",t=>{fb(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Zp&&this._register(Ze(this.element,"auxclick",t=>{t.button===1&&By(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Ze(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Ze(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Ze(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Ze(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Ze(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Ze(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Ze(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){var a;if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),((a=this.element)==null?void 0:a.ownerDocument.defaultView)&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(Ze(this.screenElement,"mousemove",o=>this.updateCursorStyle(o))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Uf.get()),d0||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>i.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(v2,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ns,this._coreBrowserService),this._register(Ze(this.textarea,"focus",o=>this._handleTextAreaFocus(o))),this._register(Ze(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(hp,this._document,this._helperContainer),this._instantiationService.setService(Hu,this._charSizeService),this._themeService=this._instantiationService.createInstance(mp),this._instantiationService.setService(xl,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Tu),this._instantiationService.setService($y,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(fp,this.rows,this.screenElement)),this._instantiationService.setService(rs,this._renderService),this._register(this._renderService.onRenderedViewportChange(o=>this._onRender.fire(o))),this.onResize(o=>this._renderService.resize(o.cols,o.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(op,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(dp),this._instantiationService.setService(Fp,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(wp,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(ap,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(o=>{super.scrollLines(o,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(pp,this.element,this.screenElement,s)),this._instantiationService.setService(GC,this._selectionService),this._register(this._selectionService.onRequestScrollLines(o=>this.scrollLines(o.amount,o.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(o=>this._renderService.handleSelectionChanged(o.start,o.end,o.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(o=>{this.textarea.value=o,this.textarea.focus(),this.textarea.select()})),this._register(en.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var o;this._selectionService.refresh(),(o=this._viewport)==null||o.queueSync()})),this._register(this._instantiationService.createInstance(lp,this.screenElement)),this._register(Ze(this.element,"mousedown",o=>this._selectionService.handleMouseDown(o))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Du,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",o=>this._handleScreenReaderModeOptionChange(o))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",o=>{!this._overviewRulerRenderer&&o&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(ju,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(up,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(o){var f,_,x,b,v;let c=e._mouseService.getMouseReportCoords(o,e.screenElement);if(!c)return!1;let h,p;switch(o.overrideType||o.type){case"mousemove":p=32,o.buttons===void 0?(h=3,o.button!==void 0&&(h=o.button<3?o.button:3)):h=o.buttons&1?0:o.buttons&4?1:o.buttons&2?2:3;break;case"mouseup":p=0,h=o.button<3?o.button:3;break;case"mousedown":p=1,h=o.button<3?o.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(o)===!1)return!1;let S=o.deltaY;if(S===0||e.coreMouseService.consumeWheelEvent(o,(b=(x=(_=(f=e._renderService)==null?void 0:f.dimensions)==null?void 0:_.device)==null?void 0:x.cell)==null?void 0:b.height,(v=e._coreBrowserService)==null?void 0:v.dpr)===0)return!1;p=S<0?0:1,h=4;break;default:return!1}return p===void 0||h===void 0||h>4?!1:e.coreMouseService.triggerMouseEvent({col:c.col,row:c.row,x:c.x,y:c.y,button:h,action:p,ctrl:o.ctrlKey,alt:o.altKey,shift:o.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},a={mouseup:o=>(i(o),o.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(o)),wheel:o=>(i(o),this.cancel(o,!0)),mousedrag:o=>{o.buttons&&i(o)},mousemove:o=>{o.buttons||i(o)}};this._register(this.coreMouseService.onProtocolChange(o=>{o?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(o)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),o&8?s.mousemove||(t.addEventListener("mousemove",a.mousemove),s.mousemove=a.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),o&16?s.wheel||(t.addEventListener("wheel",a.wheel,{passive:!1}),s.wheel=a.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),o&2?s.mouseup||(s.mouseup=a.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),o&4?s.mousedrag||(s.mousedrag=a.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Ze(t,"mousedown",o=>{if(o.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(o)))return i(o),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(o)})),this._register(Ze(t,"wheel",o=>{var c,h,p,f,_;if(!s.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(o)===!1)return!1;if(!this.buffer.hasScrollback){if(o.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(o,(f=(p=(h=(c=e._renderService)==null?void 0:c.dimensions)==null?void 0:h.device)==null?void 0:p.cell)==null?void 0:f.height,(_=e._coreBrowserService)==null?void 0:_.dpr)===0)return this.cancel(o,!0);let x=me.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(o.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(x,!0),this.cancel(o,!0)}}},{passive:!1}))}refresh(e,t){var i;(i=this._renderService)==null||i.refreshRows(e,t)}updateCursorStyle(e){var t;(t=this._selectionService)!=null&&t.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){My(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var e;(e=this._selectionService)==null||e.clearSelection()}selectAll(){var e;(e=this._selectionService)==null||e.selectAll()}selectLines(e,t){var i;(i=this._selectionService)==null||i.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let i=EE(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),i.type===3||i.type===2){let s=this.rows-1;return this.scrollLines(i.type===2?-s:s),this.cancel(e,!0)}if(i.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((i.key===me.ETX||i.key===me.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(BE(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){var i;(i=this._charSizeService)==null||i.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new sr)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},rv=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new OE(t)}getNullCell(){return new sr}},zE=class extends ht{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new we),this.onBufferChange=this._onBufferChange.event,this._normal=new rv(this._core.buffers.normal,"normal"),this._alternate=new rv(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},PE=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,i=>t(i.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(i,s)=>t(i,s.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},IE=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},HE=["cols","rows"],Er=0,UE=class extends ht{constructor(e){super(),this._core=this._register(new ME(e)),this._addonManager=this._register(new LE),this._publicOptions={...this._core.options};let t=s=>this._core.options[s],i=(s,a)=>{this._checkReadonlyOptions(s),this._core.options[s]=a};for(let s in this._core.options){let a={get:t.bind(this,s),set:i.bind(this,s)};Object.defineProperty(this._publicOptions,s,a)}}_checkReadonlyOptions(e){if(HE.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new PE(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new IE(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new zE(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r +`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Uf.get()},set promptLabel(e){Uf.set(e)},get tooMuchOutput(){return $f.get()},set tooMuchOutput(e){$f.set(e)}}}_verifyIntegers(...e){for(Er of e)if(Er===1/0||isNaN(Er)||Er%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Er of e)if(Er&&(Er===1/0||isNaN(Er)||Er%1!==0||Er<0))throw new Error("This API only accepts positive integers")}};/** * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. * @license MIT * @@ -83,7 +83,7 @@ WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){t * Fabrice Bellard's javascript vt100 for jslinux: * http://bellard.org/jslinux/ * Copyright (c) 2011 Fabrice Bellard - */var LE=2,OE=1,zE=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){var x;if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:((x=this._terminal.options.overviewRuler)==null?void 0:x.width)||14,i=window.getComputedStyle(this._terminal.element.parentElement),s=parseInt(i.getPropertyValue("height")),a=Math.max(0,parseInt(i.getPropertyValue("width"))),o=window.getComputedStyle(this._terminal.element),c={top:parseInt(o.getPropertyValue("padding-top")),bottom:parseInt(o.getPropertyValue("padding-bottom")),right:parseInt(o.getPropertyValue("padding-right")),left:parseInt(o.getPropertyValue("padding-left"))},h=c.top+c.bottom,p=c.right+c.left,f=s-h,_=a-p-t;return{cols:Math.max(LE,Math.floor(_/e.css.cell.width)),rows:Math.max(OE,Math.floor(f/e.css.cell.height))}}};/** + */var $E=2,FE=1,qE=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){var x;if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:((x=this._terminal.options.overviewRuler)==null?void 0:x.width)||14,i=window.getComputedStyle(this._terminal.element.parentElement),s=parseInt(i.getPropertyValue("height")),a=Math.max(0,parseInt(i.getPropertyValue("width"))),o=window.getComputedStyle(this._terminal.element),c={top:parseInt(o.getPropertyValue("padding-top")),bottom:parseInt(o.getPropertyValue("padding-bottom")),right:parseInt(o.getPropertyValue("padding-right")),left:parseInt(o.getPropertyValue("padding-left"))},h=c.top+c.bottom,p=c.right+c.left,f=s-h,_=a-p-t;return{cols:Math.max($E,Math.floor(_/e.css.cell.width)),rows:Math.max(FE,Math.floor(f/e.css.cell.height))}}};/** * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. * @license MIT * @@ -94,48 +94,48 @@ WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){t * Fabrice Bellard's javascript vt100 for jslinux: * http://bellard.org/jslinux/ * Copyright (c) 2011 Fabrice Bellard - */var Pi=0,Ii=0,Hi=0,oi=0,rn;(e=>{function t(a,o,c,h){return h!==void 0?`#${ca(a)}${ca(o)}${ca(c)}${ca(h)}`:`#${ca(a)}${ca(o)}${ca(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(rn||(rn={}));var PE;(e=>{function t(p,f){if(oi=(f.rgba&255)/255,oi===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,j=p.rgba>>8&255;Pi=v+Math.round((_-v)*oi),Ii=S+Math.round((x-S)*oi),Hi=j+Math.round((b-j)*oi);let R=rn.toCss(Pi,Ii,Hi),E=rn.toRgba(Pi,Ii,Hi);return{css:R,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=Su.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return rn.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Pi,Ii,Hi]=Su.toChannels(f),{css:rn.toCss(Pi,Ii,Hi),rgba:f}}e.opaque=a;function o(p,f){return oi=Math.round(f*255),[Pi,Ii,Hi]=Su.toChannels(p.rgba),{css:rn.toCss(Pi,Ii,Hi,oi),rgba:rn.toRgba(Pi,Ii,Hi,oi)}}e.opacity=o;function c(p,f){return oi=p.rgba&255,o(p,oi*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(PE||(PE={}));var Qi;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d",{willReadFrequently:!0});o&&(t=o,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return Pi=parseInt(a.slice(1,2).repeat(2),16),Ii=parseInt(a.slice(2,3).repeat(2),16),Hi=parseInt(a.slice(3,4).repeat(2),16),rn.toColor(Pi,Ii,Hi);case 5:return Pi=parseInt(a.slice(1,2).repeat(2),16),Ii=parseInt(a.slice(2,3).repeat(2),16),Hi=parseInt(a.slice(3,4).repeat(2),16),oi=parseInt(a.slice(4,5).repeat(2),16),rn.toColor(Pi,Ii,Hi,oi);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let o=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(o)return Pi=parseInt(o[1]),Ii=parseInt(o[2]),Hi=parseInt(o[3]),oi=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),rn.toColor(Pi,Ii,Hi,oi);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Pi,Ii,Hi,oi]=t.getImageData(0,0,1,1).data,oi!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:rn.toRgba(Pi,Ii,Hi,oi),css:a}}e.toColor=s})(Qi||(Qi={}));var dn;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,a,o){let c=s/255,h=a/255,p=o/255,f=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4),_=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4),x=p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4);return f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(dn||(dn={}));var Su;(e=>{function t(c,h){if(oi=(h&255)/255,oi===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Pi=x+Math.round((p-x)*oi),Ii=b+Math.round((f-b)*oi),Hi=v+Math.round((_-v)*oi),rn.toRgba(Pi,Ii,Hi)}e.blend=t;function i(c,h,p){let f=dn.relativeLuminance(c>>8),_=dn.relativeLuminance(h>>8);if(Jr(f,_)>8));if(S>8));return S>R?v:j}return v}let x=a(c,h,p),b=Jr(f,dn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Jr(dn.relativeLuminance2(b,v,S),dn.relativeLuminance2(f,_,x));for(;j0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),j=Jr(dn.relativeLuminance2(b,v,S),dn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Jr(dn.relativeLuminance2(b,v,S),dn.relativeLuminance2(f,_,x));for(;j>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(Su||(Su={}));function ca(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Jr(e,t){return e{let e=[Qi.toColor("#2e3436"),Qi.toColor("#cc0000"),Qi.toColor("#4e9a06"),Qi.toColor("#c4a000"),Qi.toColor("#3465a4"),Qi.toColor("#75507b"),Qi.toColor("#06989a"),Qi.toColor("#d3d7cf"),Qi.toColor("#555753"),Qi.toColor("#ef2929"),Qi.toColor("#8ae234"),Qi.toColor("#fce94f"),Qi.toColor("#729fcf"),Qi.toColor("#ad7fa8"),Qi.toColor("#34e2e2"),Qi.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:rn.toCss(s,a,o),rgba:rn.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:rn.toCss(s,s,s),rgba:rn.toRgba(s,s,s)})}return e})());function nv(e,t,i){return Math.max(t,Math.min(e,i))}function HE(e){switch(e){case"&":return"&";case"<":return"<"}return e}var b0=class{constructor(e){this._buffer=e}serialize(e,t){let i=this._buffer.getNullCell(),s=this._buffer.getNullCell(),a=i,o=e.start.y,c=e.end.y,h=e.start.x,p=e.end.x;this._beforeSerialize(c-o,o,c);for(let f=o;f<=c;f++){let _=this._buffer.getLine(f);if(_){let x=f===e.start.y?h:0,b=f===e.end.y?p:_.length;for(let v=x;v0&&!es(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`\x1B[${this._nullCellCount}X`);let i="";if(!t){e-this._firstRow>=this._terminal.rows&&((s=this._buffer.getLine(this._cursorStyleRow))==null||s.getCell(this._cursorStyleCol,this._backgroundCell));let a=this._buffer.getLine(e),o=this._buffer.getLine(e+1);if(!o.isWrapped)i=`\r -`,this._lastCursorRow=e+1,this._lastCursorCol=0;else{i="";let c=a.getCell(a.length-1,this._thisRowLastChar),h=a.getCell(a.length-2,this._thisRowLastSecondChar),p=o.getCell(0,this._nextRowFirstChar),f=p.getWidth()>1,_=!1;(p.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((c.getChars()||c.getWidth()===0)&&es(c,p)&&(_=!0),f&&(h.getChars()||h.getWidth()===0)&&es(c,p)&&es(h,p)&&(_=!0)),_||(i="-".repeat(this._nullCellCount+1),i+="\x1B[1D\x1B[1X",this._nullCellCount>0&&(i+="\x1B[A",i+=`\x1B[${a.length-this._nullCellCount}C`,i+=`\x1B[${this._nullCellCount}X`,i+=`\x1B[${a.length-this._nullCellCount}D`,i+="\x1B[B"),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=i,this._currentRow="",this._nullCellCount=0}_diffStyle(e,t){let i=[],s=!v0(e,t),a=!es(e,t),o=!y0(e,t);if(s||a||o)if(e.isAttributeDefault())t.isAttributeDefault()||i.push(0);else{if(s){let c=e.getFgColor();e.isFgRGB()?i.push(38,2,c>>>16&255,c>>>8&255,c&255):e.isFgPalette()?c>=16?i.push(38,5,c):i.push(c&8?90+(c&7):30+(c&7)):i.push(39)}if(a){let c=e.getBgColor();e.isBgRGB()?i.push(48,2,c>>>16&255,c>>>8&255,c&255):e.isBgPalette()?c>=16?i.push(48,5,c):i.push(c&8?100+(c&7):40+(c&7)):i.push(49)}o&&(e.isInverse()!==t.isInverse()&&i.push(e.isInverse()?7:27),e.isBold()!==t.isBold()&&i.push(e.isBold()?1:22),e.isUnderline()!==t.isUnderline()&&i.push(e.isUnderline()?4:24),e.isOverline()!==t.isOverline()&&i.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&i.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&i.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&i.push(e.isItalic()?3:23),e.isDim()!==t.isDim()&&i.push(e.isDim()?2:22),e.isStrikethrough()!==t.isStrikethrough()&&i.push(e.isStrikethrough()?9:29))}return i}_nextCell(e,t,i,s){if(e.getWidth()===0)return;let a=e.getChars()==="",o=this._diffStyle(e,this._cursorStyle);if(a?!es(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(es(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`\x1B[${this._nullCellCount}X`),this._currentRow+=`\x1B[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=i,this._lastContentCursorCol=this._lastCursorCol=s,this._currentRow+=`\x1B[${o.join(";")}m`;let c=this._buffer.getLine(i);c!==void 0&&(c.getCell(s,this._cursorStyle),this._cursorStyleRow=i,this._cursorStyleCol=s)}a?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(es(this._cursorStyle,this._backgroundCell)?this._currentRow+=`\x1B[${this._nullCellCount}C`:(this._currentRow+=`\x1B[${this._nullCellCount}X`,this._currentRow+=`\x1B[${this._nullCellCount}C`),this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=i,this._lastContentCursorCol=this._lastCursorCol=s+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let i="";for(let o=0;o{f>0?i+=`\x1B[${f}C`:f<0&&(i+=`\x1B[${-f}D`)};h&&((f=>{f>0?i+=`\x1B[${f}B`:f<0&&(i+=`\x1B[${-f}A`)})(o-this._lastCursorRow),p(c-this._lastCursorCol))}let s=this._terminal._core._inputHandler._curAttrData,a=this._diffStyle(s,this._cursorStyle);return a.length>0&&(i+=`\x1B[${a.join(";")}m`),i}},$E=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,i){let s=t.length,a=i===void 0?s:nv(i+e.rows,0,s);return this._serializeBufferByRange(e,t,{start:s-a,end:s-1},!1)}_serializeBufferByRange(e,t,i,s){return new UE(t,e).serialize({start:{x:0,y:typeof i.start=="number"?i.start:i.start.line},end:{x:e.cols,y:typeof i.end=="number"?i.end:i.end.line}},s)}_serializeBufferAsHTML(e,t){var h;let i=e.buffer.active,s=new FE(i,e,t),a=t.onlySelection??!1,o=t.range;if(o)return s.serialize({start:{x:o.startCol,y:(o.startLine,o.startLine)},end:{x:e.cols,y:(o.endLine,o.endLine)}});if(!a){let p=i.length,f=t.scrollback,_=f===void 0?p:nv(f+e.rows,0,p);return s.serialize({start:{x:0,y:p-_},end:{x:e.cols,y:p-1}})}let c=(h=this._terminal)==null?void 0:h.getSelectionPosition();return c!==void 0?s.serialize({start:{x:c.start.x,y:c.start.y},end:{x:c.end.x,y:c.end.y}}):""}_serializeModes(e){let t="",i=e.modes;if(i.applicationCursorKeysMode&&(t+="\x1B[?1h"),i.applicationKeypadMode&&(t+="\x1B[?66h"),i.bracketedPasteMode&&(t+="\x1B[?2004h"),i.insertMode&&(t+="\x1B[4h"),i.originMode&&(t+="\x1B[?6h"),i.reverseWraparoundMode&&(t+="\x1B[?45h"),i.sendFocusMode&&(t+="\x1B[?1004h"),i.wraparoundMode===!1&&(t+="\x1B[?7l"),i.mouseTrackingMode!=="none")switch(i.mouseTrackingMode){case"x10":t+="\x1B[?9h";break;case"vt200":t+="\x1B[?1000h";break;case"drag":t+="\x1B[?1002h";break;case"any":t+="\x1B[?1003h";break}return t}serialize(e){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let t=e!=null&&e.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,e.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,e==null?void 0:e.scrollback);if(!(e!=null&&e.excludeAltBuffer)&&this._terminal.buffer.active.type==="alternate"){let i=this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0);t+=`\x1B[?1049h\x1B[H${i}`}return e!=null&&e.excludeModes||(t+=this._serializeModes(this._terminal)),t}serializeAsHTML(e){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,e||{})}dispose(){}},FE=class extends b0{constructor(e,t,i){super(e),this._terminal=t,this._options=i,this._currentRow="",this._htmlContent="",t._core._themeService?this._ansiColors=t._core._themeService.colors.ansi:this._ansiColors=IE}_padStart(e,t,i){return t=t>>0,i=i??" ",e.length>t?e:(t-=e.length,t>i.length&&(i+=i.repeat(t/i.length)),i.slice(0,t)+e)}_beforeSerialize(e,t,i){var c,h;this._htmlContent+="
";let s="#000000",a="#ffffff";(this._options.includeGlobalBackground??!1)&&(s=((c=this._terminal.options.theme)==null?void 0:c.foreground)??"#ffffff",a=((h=this._terminal.options.theme)==null?void 0:h.background)??"#000000");let o=[];o.push("color: "+s+";"),o.push("background-color: "+a+";"),o.push("font-family: "+this._terminal.options.fontFamily+";"),o.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="
"}_afterSerialize(){this._htmlContent+="
",this._htmlContent+="
"}_rowEnd(e,t){this._htmlContent+="
"+this._currentRow+"
",this._currentRow=""}_getHexColor(e,t){let i=t?e.getFgColor():e.getBgColor();if(t?e.isFgRGB():e.isBgRGB())return"#"+[i>>16&255,i>>8&255,i&255].map(s=>this._padStart(s.toString(16),2,"0")).join("");if(t?e.isFgPalette():e.isBgPalette())return this._ansiColors[i].css}_diffStyle(e,t){let i=[],s=!v0(e,t),a=!es(e,t),o=!y0(e,t);if(s||a||o){let c=this._getHexColor(e,!0);c&&i.push("color: "+c+";");let h=this._getHexColor(e,!1);return h&&i.push("background-color: "+h+";"),e.isInverse()&&i.push("color: #000000; background-color: #BFBFBF;"),e.isBold()&&i.push("font-weight: bold;"),e.isUnderline()&&e.isOverline()?i.push("text-decoration: overline underline;"):e.isUnderline()?i.push("text-decoration: underline;"):e.isOverline()&&i.push("text-decoration: overline;"),e.isBlink()&&i.push("text-decoration: blink;"),e.isInvisible()&&i.push("visibility: hidden;"),e.isItalic()&&i.push("font-style: italic;"),e.isDim()&&i.push("opacity: 0.5;"),e.isStrikethrough()&&i.push("text-decoration: line-through;"),i}}_nextCell(e,t,i,s){if(e.getWidth()===0)return;let a=e.getChars()==="",o=this._diffStyle(e,t);o&&(this._currentRow+=o.length===0?"":""),a?this._currentRow+=" ":this._currentRow+=HE(e.getChars())}_serializeString(){return this._htmlContent}};const qE="__OWS_FRESH_SESSION__",rl="[REDACTED]",WE=[[/(authorization\s*:\s*bearer\s+)[^\s'"\x1b]+/gi,`$1${rl}`],[/(\bbearer\s+)[A-Za-z0-9._-]{12,}/gi,`$1${rl}`],[/(\btoken=)[^\s'"&\x1b]+/gi,`$1${rl}`],[/(OWS_PASSPHRASE\s*[=:]\s*)[^\s'"\x1b]+/gi,`$1${rl}`],[/(--passphrase[=\s]+)[^\s'"\x1b]+/gi,`$1${rl}`],[/(passphrase["']?\s*[:=]\s*["']?)[^\s'"\x1b]+/gi,`$1${rl}`]];function rv(e){let t=e;for(const[i,s]of WE)t=t.replace(i,s);return t}const sv="codex features enable image_generation";function GE(e,t){return e!=="cartoon"||!t?!1:!(t.codex.installed&&t.codex.imageGeneration==="enabled")}const YE={background:"#F0EBE1",foreground:"#2C1810",cursor:"#8B4513",cursorAccent:"#F0EBE1",selectionBackground:"#D4C5B0",selectionForeground:"#2C1810",black:"#2C1810",red:"#A63D40",green:"#4A7A4A",yellow:"#8B6914",blue:"#4A6FA5",magenta:"#7B4B8A",cyan:"#3D7A7A",white:"#E6DDD0",brightBlack:"#8B7355",brightRed:"#B85C5C",brightGreen:"#5A8A5A",brightYellow:"#A07D1C",brightBlue:"#5A82BA",brightMagenta:"#8E5D9F",brightCyan:"#5A8F8F",brightWhite:"#4A3728"},KE="plotlink-terminal",VE=1,Us="scrollback",av=10*1024*1024;function Qp(){return new Promise((e,t)=>{const i=indexedDB.open(KE,VE);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains(Us)||s.createObjectStore(Us)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function sl(e,t){const i=t.length>av?t.slice(-av):t,s=await Qp();return new Promise((a,o)=>{const c=s.transaction(Us,"readwrite");c.objectStore(Us).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function XE(e){const t=await Qp();return new Promise((i,s)=>{const o=t.transaction(Us,"readonly").objectStore(Us).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function pf(e){const t=await Qp();return new Promise((i,s)=>{const a=t.transaction(Us,"readwrite");a.objectStore(Us).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const Ri=new Map;function ZE({token:e,storyName:t,authFetch:i,onSelectStory:s,onDestroySession:a,onArchiveStory:o,confirmedStories:c,renameRef:h,bypassStories:p,agentProviders:f,readiness:_,contentType:x,needsProviderRepair:b,onRepairProvider:v}){const S=w.useRef(null),j=w.useRef(i),[R,E]=w.useState([]),[N,I]=w.useState(new Set),[te,F]=w.useState(null),[D,ie]=w.useState(null),[fe,Se]=w.useState(!1),[H,ce]=w.useState(!1),W=GE(x,_),K=!!b,X=w.useRef(()=>{});w.useEffect(()=>{j.current=i},[i]);const U=w.useCallback(Y=>{var _e;const{width:he}=Y.container.getBoundingClientRect();if(!(he<50))try{Y.fit.fit(),((_e=Y.ws)==null?void 0:_e.readyState)===WebSocket.OPEN&&Y.ws.send(JSON.stringify({type:"resize",cols:Y.term.cols,rows:Y.term.rows}))}catch{}},[]),A=w.useCallback(Y=>{for(const[he,_e]of Ri)_e.container.style.display=he===Y?"block":"none";if(Y){const he=Ri.get(Y);he&&setTimeout(()=>U(he),50)}},[U]),O=w.useRef({});w.useEffect(()=>{O.current=p||{}},[p]);const $=w.useRef({});w.useEffect(()=>{$.current=f||{}},[f]);const xe=w.useCallback((Y,he,_e)=>{const Be=window.location.protocol==="https:"?"wss:":"ws:",Le=O.current[Y]?"&bypass=true":"",je=$.current[Y],be=je?`&provider=${encodeURIComponent(je)}`:"",tt=new WebSocket(`${Be}//${window.location.host}/ws/terminal?story=${encodeURIComponent(Y)}&token=${e}&resume=${_e}${Le}${be}`);tt.onopen=()=>{he.connected=!0,he._retried=!1,I(ot=>{const We=new Set(ot);return We.delete(Y),We}),tt.send(JSON.stringify({type:"resize",cols:he.term.cols,rows:he.term.rows}))};let St=!0;tt.onmessage=ot=>{if(St&&(St=!1,typeof ot.data=="string"&&ot.data===qE)){he.term.reset(),pf(Y).catch(()=>{});return}he.term.write(typeof ot.data=="string"?rv(ot.data):ot.data)},tt.onclose=ot=>{if(he.connected=!1,he.ws===tt){he.ws=null;try{const We=he.serialize.serialize();sl(Y,We).catch(()=>{})}catch{}if(ot.code===4e3&&!he._retried){he._retried=!0,he.term.write(`\r + */var Pi=0,Ii=0,Hi=0,oi=0,rn;(e=>{function t(a,o,c,h){return h!==void 0?`#${ca(a)}${ca(o)}${ca(c)}${ca(h)}`:`#${ca(a)}${ca(o)}${ca(c)}`}e.toCss=t;function i(a,o,c,h=255){return(a<<24|o<<16|c<<8|h)>>>0}e.toRgba=i;function s(a,o,c,h){return{css:e.toCss(a,o,c,h),rgba:e.toRgba(a,o,c,h)}}e.toColor=s})(rn||(rn={}));var WE;(e=>{function t(p,f){if(oi=(f.rgba&255)/255,oi===1)return{css:f.css,rgba:f.rgba};let _=f.rgba>>24&255,x=f.rgba>>16&255,b=f.rgba>>8&255,v=p.rgba>>24&255,S=p.rgba>>16&255,j=p.rgba>>8&255;Pi=v+Math.round((_-v)*oi),Ii=S+Math.round((x-S)*oi),Hi=j+Math.round((b-j)*oi);let D=rn.toCss(Pi,Ii,Hi),E=rn.toRgba(Pi,Ii,Hi);return{css:D,rgba:E}}e.blend=t;function i(p){return(p.rgba&255)===255}e.isOpaque=i;function s(p,f,_){let x=Su.ensureContrastRatio(p.rgba,f.rgba,_);if(x)return rn.toColor(x>>24&255,x>>16&255,x>>8&255)}e.ensureContrastRatio=s;function a(p){let f=(p.rgba|255)>>>0;return[Pi,Ii,Hi]=Su.toChannels(f),{css:rn.toCss(Pi,Ii,Hi),rgba:f}}e.opaque=a;function o(p,f){return oi=Math.round(f*255),[Pi,Ii,Hi]=Su.toChannels(p.rgba),{css:rn.toCss(Pi,Ii,Hi,oi),rgba:rn.toRgba(Pi,Ii,Hi,oi)}}e.opacity=o;function c(p,f){return oi=p.rgba&255,o(p,oi*f/255)}e.multiplyOpacity=c;function h(p){return[p.rgba>>24&255,p.rgba>>16&255,p.rgba>>8&255]}e.toColorRGB=h})(WE||(WE={}));var Qi;(e=>{let t,i;try{let a=document.createElement("canvas");a.width=1,a.height=1;let o=a.getContext("2d",{willReadFrequently:!0});o&&(t=o,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function s(a){if(a.match(/#[\da-f]{3,8}/i))switch(a.length){case 4:return Pi=parseInt(a.slice(1,2).repeat(2),16),Ii=parseInt(a.slice(2,3).repeat(2),16),Hi=parseInt(a.slice(3,4).repeat(2),16),rn.toColor(Pi,Ii,Hi);case 5:return Pi=parseInt(a.slice(1,2).repeat(2),16),Ii=parseInt(a.slice(2,3).repeat(2),16),Hi=parseInt(a.slice(3,4).repeat(2),16),oi=parseInt(a.slice(4,5).repeat(2),16),rn.toColor(Pi,Ii,Hi,oi);case 7:return{css:a,rgba:(parseInt(a.slice(1),16)<<8|255)>>>0};case 9:return{css:a,rgba:parseInt(a.slice(1),16)>>>0}}let o=a.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(o)return Pi=parseInt(o[1]),Ii=parseInt(o[2]),Hi=parseInt(o[3]),oi=Math.round((o[5]===void 0?1:parseFloat(o[5]))*255),rn.toColor(Pi,Ii,Hi,oi);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=a,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[Pi,Ii,Hi,oi]=t.getImageData(0,0,1,1).data,oi!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:rn.toRgba(Pi,Ii,Hi,oi),css:a}}e.toColor=s})(Qi||(Qi={}));var dn;(e=>{function t(s){return i(s>>16&255,s>>8&255,s&255)}e.relativeLuminance=t;function i(s,a,o){let c=s/255,h=a/255,p=o/255,f=c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4),_=h<=.03928?h/12.92:Math.pow((h+.055)/1.055,2.4),x=p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4);return f*.2126+_*.7152+x*.0722}e.relativeLuminance2=i})(dn||(dn={}));var Su;(e=>{function t(c,h){if(oi=(h&255)/255,oi===1)return h;let p=h>>24&255,f=h>>16&255,_=h>>8&255,x=c>>24&255,b=c>>16&255,v=c>>8&255;return Pi=x+Math.round((p-x)*oi),Ii=b+Math.round((f-b)*oi),Hi=v+Math.round((_-v)*oi),rn.toRgba(Pi,Ii,Hi)}e.blend=t;function i(c,h,p){let f=dn.relativeLuminance(c>>8),_=dn.relativeLuminance(h>>8);if(Jr(f,_)>8));if(S>8));return S>D?v:j}return v}let x=a(c,h,p),b=Jr(f,dn.relativeLuminance(x>>8));if(b>8));return b>S?x:v}return x}}e.ensureContrastRatio=i;function s(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Jr(dn.relativeLuminance2(b,v,S),dn.relativeLuminance2(f,_,x));for(;j0||v>0||S>0);)b-=Math.max(0,Math.ceil(b*.1)),v-=Math.max(0,Math.ceil(v*.1)),S-=Math.max(0,Math.ceil(S*.1)),j=Jr(dn.relativeLuminance2(b,v,S),dn.relativeLuminance2(f,_,x));return(b<<24|v<<16|S<<8|255)>>>0}e.reduceLuminance=s;function a(c,h,p){let f=c>>24&255,_=c>>16&255,x=c>>8&255,b=h>>24&255,v=h>>16&255,S=h>>8&255,j=Jr(dn.relativeLuminance2(b,v,S),dn.relativeLuminance2(f,_,x));for(;j>>0}e.increaseLuminance=a;function o(c){return[c>>24&255,c>>16&255,c>>8&255,c&255]}e.toChannels=o})(Su||(Su={}));function ca(e){let t=e.toString(16);return t.length<2?"0"+t:t}function Jr(e,t){return e{let e=[Qi.toColor("#2e3436"),Qi.toColor("#cc0000"),Qi.toColor("#4e9a06"),Qi.toColor("#c4a000"),Qi.toColor("#3465a4"),Qi.toColor("#75507b"),Qi.toColor("#06989a"),Qi.toColor("#d3d7cf"),Qi.toColor("#555753"),Qi.toColor("#ef2929"),Qi.toColor("#8ae234"),Qi.toColor("#fce94f"),Qi.toColor("#729fcf"),Qi.toColor("#ad7fa8"),Qi.toColor("#34e2e2"),Qi.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let s=t[i/36%6|0],a=t[i/6%6|0],o=t[i%6];e.push({css:rn.toCss(s,a,o),rgba:rn.toRgba(s,a,o)})}for(let i=0;i<24;i++){let s=8+i*10;e.push({css:rn.toCss(s,s,s),rgba:rn.toRgba(s,s,s)})}return e})());function sv(e,t,i){return Math.max(t,Math.min(e,i))}function YE(e){switch(e){case"&":return"&";case"<":return"<"}return e}var S0=class{constructor(e){this._buffer=e}serialize(e,t){let i=this._buffer.getNullCell(),s=this._buffer.getNullCell(),a=i,o=e.start.y,c=e.end.y,h=e.start.x,p=e.end.x;this._beforeSerialize(c-o,o,c);for(let f=o;f<=c;f++){let _=this._buffer.getLine(f);if(_){let x=f===e.start.y?h:0,b=f===e.end.y?p:_.length;for(let v=x;v0&&!es(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`\x1B[${this._nullCellCount}X`);let i="";if(!t){e-this._firstRow>=this._terminal.rows&&((s=this._buffer.getLine(this._cursorStyleRow))==null||s.getCell(this._cursorStyleCol,this._backgroundCell));let a=this._buffer.getLine(e),o=this._buffer.getLine(e+1);if(!o.isWrapped)i=`\r +`,this._lastCursorRow=e+1,this._lastCursorCol=0;else{i="";let c=a.getCell(a.length-1,this._thisRowLastChar),h=a.getCell(a.length-2,this._thisRowLastSecondChar),p=o.getCell(0,this._nextRowFirstChar),f=p.getWidth()>1,_=!1;(p.getChars()&&f?this._nullCellCount<=1:this._nullCellCount<=0)&&((c.getChars()||c.getWidth()===0)&&es(c,p)&&(_=!0),f&&(h.getChars()||h.getWidth()===0)&&es(c,p)&&es(h,p)&&(_=!0)),_||(i="-".repeat(this._nullCellCount+1),i+="\x1B[1D\x1B[1X",this._nullCellCount>0&&(i+="\x1B[A",i+=`\x1B[${a.length-this._nullCellCount}C`,i+=`\x1B[${this._nullCellCount}X`,i+=`\x1B[${a.length-this._nullCellCount}D`,i+="\x1B[B"),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=i,this._currentRow="",this._nullCellCount=0}_diffStyle(e,t){let i=[],s=!w0(e,t),a=!es(e,t),o=!C0(e,t);if(s||a||o)if(e.isAttributeDefault())t.isAttributeDefault()||i.push(0);else{if(s){let c=e.getFgColor();e.isFgRGB()?i.push(38,2,c>>>16&255,c>>>8&255,c&255):e.isFgPalette()?c>=16?i.push(38,5,c):i.push(c&8?90+(c&7):30+(c&7)):i.push(39)}if(a){let c=e.getBgColor();e.isBgRGB()?i.push(48,2,c>>>16&255,c>>>8&255,c&255):e.isBgPalette()?c>=16?i.push(48,5,c):i.push(c&8?100+(c&7):40+(c&7)):i.push(49)}o&&(e.isInverse()!==t.isInverse()&&i.push(e.isInverse()?7:27),e.isBold()!==t.isBold()&&i.push(e.isBold()?1:22),e.isUnderline()!==t.isUnderline()&&i.push(e.isUnderline()?4:24),e.isOverline()!==t.isOverline()&&i.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&i.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&i.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&i.push(e.isItalic()?3:23),e.isDim()!==t.isDim()&&i.push(e.isDim()?2:22),e.isStrikethrough()!==t.isStrikethrough()&&i.push(e.isStrikethrough()?9:29))}return i}_nextCell(e,t,i,s){if(e.getWidth()===0)return;let a=e.getChars()==="",o=this._diffStyle(e,this._cursorStyle);if(a?!es(this._cursorStyle,e):o.length>0){this._nullCellCount>0&&(es(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`\x1B[${this._nullCellCount}X`),this._currentRow+=`\x1B[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=i,this._lastContentCursorCol=this._lastCursorCol=s,this._currentRow+=`\x1B[${o.join(";")}m`;let c=this._buffer.getLine(i);c!==void 0&&(c.getCell(s,this._cursorStyle),this._cursorStyleRow=i,this._cursorStyleCol=s)}a?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(es(this._cursorStyle,this._backgroundCell)?this._currentRow+=`\x1B[${this._nullCellCount}C`:(this._currentRow+=`\x1B[${this._nullCellCount}X`,this._currentRow+=`\x1B[${this._nullCellCount}C`),this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=i,this._lastContentCursorCol=this._lastCursorCol=s+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let i="";for(let o=0;o{f>0?i+=`\x1B[${f}C`:f<0&&(i+=`\x1B[${-f}D`)};h&&((f=>{f>0?i+=`\x1B[${f}B`:f<0&&(i+=`\x1B[${-f}A`)})(o-this._lastCursorRow),p(c-this._lastCursorCol))}let s=this._terminal._core._inputHandler._curAttrData,a=this._diffStyle(s,this._cursorStyle);return a.length>0&&(i+=`\x1B[${a.join(";")}m`),i}},VE=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,i){let s=t.length,a=i===void 0?s:sv(i+e.rows,0,s);return this._serializeBufferByRange(e,t,{start:s-a,end:s-1},!1)}_serializeBufferByRange(e,t,i,s){return new KE(t,e).serialize({start:{x:0,y:typeof i.start=="number"?i.start:i.start.line},end:{x:e.cols,y:typeof i.end=="number"?i.end:i.end.line}},s)}_serializeBufferAsHTML(e,t){var h;let i=e.buffer.active,s=new XE(i,e,t),a=t.onlySelection??!1,o=t.range;if(o)return s.serialize({start:{x:o.startCol,y:(o.startLine,o.startLine)},end:{x:e.cols,y:(o.endLine,o.endLine)}});if(!a){let p=i.length,f=t.scrollback,_=f===void 0?p:sv(f+e.rows,0,p);return s.serialize({start:{x:0,y:p-_},end:{x:e.cols,y:p-1}})}let c=(h=this._terminal)==null?void 0:h.getSelectionPosition();return c!==void 0?s.serialize({start:{x:c.start.x,y:c.start.y},end:{x:c.end.x,y:c.end.y}}):""}_serializeModes(e){let t="",i=e.modes;if(i.applicationCursorKeysMode&&(t+="\x1B[?1h"),i.applicationKeypadMode&&(t+="\x1B[?66h"),i.bracketedPasteMode&&(t+="\x1B[?2004h"),i.insertMode&&(t+="\x1B[4h"),i.originMode&&(t+="\x1B[?6h"),i.reverseWraparoundMode&&(t+="\x1B[?45h"),i.sendFocusMode&&(t+="\x1B[?1004h"),i.wraparoundMode===!1&&(t+="\x1B[?7l"),i.mouseTrackingMode!=="none")switch(i.mouseTrackingMode){case"x10":t+="\x1B[?9h";break;case"vt200":t+="\x1B[?1000h";break;case"drag":t+="\x1B[?1002h";break;case"any":t+="\x1B[?1003h";break}return t}serialize(e){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");let t=e!=null&&e.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,e.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,e==null?void 0:e.scrollback);if(!(e!=null&&e.excludeAltBuffer)&&this._terminal.buffer.active.type==="alternate"){let i=this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0);t+=`\x1B[?1049h\x1B[H${i}`}return e!=null&&e.excludeModes||(t+=this._serializeModes(this._terminal)),t}serializeAsHTML(e){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");return this._serializeBufferAsHTML(this._terminal,e||{})}dispose(){}},XE=class extends S0{constructor(e,t,i){super(e),this._terminal=t,this._options=i,this._currentRow="",this._htmlContent="",t._core._themeService?this._ansiColors=t._core._themeService.colors.ansi:this._ansiColors=GE}_padStart(e,t,i){return t=t>>0,i=i??" ",e.length>t?e:(t-=e.length,t>i.length&&(i+=i.repeat(t/i.length)),i.slice(0,t)+e)}_beforeSerialize(e,t,i){var c,h;this._htmlContent+="
";let s="#000000",a="#ffffff";(this._options.includeGlobalBackground??!1)&&(s=((c=this._terminal.options.theme)==null?void 0:c.foreground)??"#ffffff",a=((h=this._terminal.options.theme)==null?void 0:h.background)??"#000000");let o=[];o.push("color: "+s+";"),o.push("background-color: "+a+";"),o.push("font-family: "+this._terminal.options.fontFamily+";"),o.push("font-size: "+this._terminal.options.fontSize+"px;"),this._htmlContent+="
"}_afterSerialize(){this._htmlContent+="
",this._htmlContent+="
"}_rowEnd(e,t){this._htmlContent+="
"+this._currentRow+"
",this._currentRow=""}_getHexColor(e,t){let i=t?e.getFgColor():e.getBgColor();if(t?e.isFgRGB():e.isBgRGB())return"#"+[i>>16&255,i>>8&255,i&255].map(s=>this._padStart(s.toString(16),2,"0")).join("");if(t?e.isFgPalette():e.isBgPalette())return this._ansiColors[i].css}_diffStyle(e,t){let i=[],s=!w0(e,t),a=!es(e,t),o=!C0(e,t);if(s||a||o){let c=this._getHexColor(e,!0);c&&i.push("color: "+c+";");let h=this._getHexColor(e,!1);return h&&i.push("background-color: "+h+";"),e.isInverse()&&i.push("color: #000000; background-color: #BFBFBF;"),e.isBold()&&i.push("font-weight: bold;"),e.isUnderline()&&e.isOverline()?i.push("text-decoration: overline underline;"):e.isUnderline()?i.push("text-decoration: underline;"):e.isOverline()&&i.push("text-decoration: overline;"),e.isBlink()&&i.push("text-decoration: blink;"),e.isInvisible()&&i.push("visibility: hidden;"),e.isItalic()&&i.push("font-style: italic;"),e.isDim()&&i.push("opacity: 0.5;"),e.isStrikethrough()&&i.push("text-decoration: line-through;"),i}}_nextCell(e,t,i,s){if(e.getWidth()===0)return;let a=e.getChars()==="",o=this._diffStyle(e,t);o&&(this._currentRow+=o.length===0?"
":""),a?this._currentRow+=" ":this._currentRow+=YE(e.getChars())}_serializeString(){return this._htmlContent}};const ZE="__OWS_FRESH_SESSION__",rl="[REDACTED]",QE=[[/(authorization\s*:\s*bearer\s+)[^\s'"\x1b]+/gi,`$1${rl}`],[/(\bbearer\s+)[A-Za-z0-9._-]{12,}/gi,`$1${rl}`],[/(\btoken=)[^\s'"&\x1b]+/gi,`$1${rl}`],[/(OWS_PASSPHRASE\s*[=:]\s*)[^\s'"\x1b]+/gi,`$1${rl}`],[/(--passphrase[=\s]+)[^\s'"\x1b]+/gi,`$1${rl}`],[/(passphrase["']?\s*[:=]\s*["']?)[^\s'"\x1b]+/gi,`$1${rl}`]];function av(e){let t=e;for(const[i,s]of QE)t=t.replace(i,s);return t}const lv="codex features enable image_generation";function JE(e,t){return e!=="cartoon"||!t?!1:!(t.codex.installed&&t.codex.imageGeneration==="enabled")}const eN={background:"#F0EBE1",foreground:"#2C1810",cursor:"#8B4513",cursorAccent:"#F0EBE1",selectionBackground:"#D4C5B0",selectionForeground:"#2C1810",black:"#2C1810",red:"#A63D40",green:"#4A7A4A",yellow:"#8B6914",blue:"#4A6FA5",magenta:"#7B4B8A",cyan:"#3D7A7A",white:"#E6DDD0",brightBlack:"#8B7355",brightRed:"#B85C5C",brightGreen:"#5A8A5A",brightYellow:"#A07D1C",brightBlue:"#5A82BA",brightMagenta:"#8E5D9F",brightCyan:"#5A8F8F",brightWhite:"#4A3728"},tN="plotlink-terminal",iN=1,Us="scrollback",ov=10*1024*1024;function Qp(){return new Promise((e,t)=>{const i=indexedDB.open(tN,iN);i.onupgradeneeded=()=>{const s=i.result;s.objectStoreNames.contains(Us)||s.createObjectStore(Us)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)})}async function sl(e,t){const i=t.length>ov?t.slice(-ov):t,s=await Qp();return new Promise((a,o)=>{const c=s.transaction(Us,"readwrite");c.objectStore(Us).put(i,e),c.oncomplete=()=>{s.close(),a()},c.onerror=()=>{s.close(),o(c.error)}})}async function nN(e){const t=await Qp();return new Promise((i,s)=>{const o=t.transaction(Us,"readonly").objectStore(Us).get(e);o.onsuccess=()=>{t.close(),i(o.result??null)},o.onerror=()=>{t.close(),s(o.error)}})}async function mf(e){const t=await Qp();return new Promise((i,s)=>{const a=t.transaction(Us,"readwrite");a.objectStore(Us).delete(e),a.oncomplete=()=>{t.close(),i()},a.onerror=()=>{t.close(),s(a.error)}})}const Ri=new Map;function rN({token:e,storyName:t,authFetch:i,onSelectStory:s,onDestroySession:a,onArchiveStory:o,confirmedStories:c,renameRef:h,bypassStories:p,agentProviders:f,readiness:_,contentType:x,needsProviderRepair:b,onRepairProvider:v}){const S=w.useRef(null),j=w.useRef(i),[D,E]=w.useState([]),[N,I]=w.useState(new Set),[te,q]=w.useState(null),[R,ie]=w.useState(null),[fe,be]=w.useState(!1),[B,ne]=w.useState(!1),F=JE(x,_),G=!!b,Y=w.useRef(()=>{});w.useEffect(()=>{j.current=i},[i]);const U=w.useCallback(K=>{var _e;const{width:he}=K.container.getBoundingClientRect();if(!(he<50))try{K.fit.fit(),((_e=K.ws)==null?void 0:_e.readyState)===WebSocket.OPEN&&K.ws.send(JSON.stringify({type:"resize",cols:K.term.cols,rows:K.term.rows}))}catch{}},[]),A=w.useCallback(K=>{for(const[he,_e]of Ri)_e.container.style.display=he===K?"block":"none";if(K){const he=Ri.get(K);he&&setTimeout(()=>U(he),50)}},[U]),z=w.useRef({});w.useEffect(()=>{z.current=p||{}},[p]);const $=w.useRef({});w.useEffect(()=>{$.current=f||{}},[f]);const ge=w.useCallback((K,he,_e)=>{const Me=window.location.protocol==="https:"?"wss:":"ws:",Le=z.current[K]?"&bypass=true":"",He=$.current[K],ke=He?`&provider=${encodeURIComponent(He)}`:"",Ue=new WebSocket(`${Me}//${window.location.host}/ws/terminal?story=${encodeURIComponent(K)}&token=${e}&resume=${_e}${Le}${ke}`);Ue.onopen=()=>{he.connected=!0,he._retried=!1,I(at=>{const Ve=new Set(at);return Ve.delete(K),Ve}),Ue.send(JSON.stringify({type:"resize",cols:he.term.cols,rows:he.term.rows}))};let Je=!0;Ue.onmessage=at=>{if(Je&&(Je=!1,typeof at.data=="string"&&at.data===ZE)){he.term.reset(),mf(K).catch(()=>{});return}he.term.write(typeof at.data=="string"?av(at.data):at.data)},Ue.onclose=at=>{if(he.connected=!1,he.ws===Ue){he.ws=null;try{const Ve=he.serialize.serialize();sl(K,Ve).catch(()=>{})}catch{}if(at.code===4e3&&!he._retried){he._retried=!0,he.term.write(`\r \x1B[33m[Resume failed — starting fresh session...]\x1B[0m\r -`),X.current(Y,he,!1);return}I(We=>new Set(We).add(Y))}},he.term.onData(ot=>{tt.readyState===WebSocket.OPEN&&tt.send(ot)}),he.ws=tt},[e]);w.useEffect(()=>{X.current=xe},[xe]);const T=w.useCallback(async(Y,he)=>{if(!S.current||Ri.has(Y))return;const{resume:_e=!1,autoConnect:Be=!0}=he??{},Le=document.createElement("div");Le.style.width="100%",Le.style.height="100%",Le.style.display="none",Le.style.paddingLeft="10px",Le.style.boxSizing="border-box",S.current.appendChild(Le);const je=new BE({cols:80,scrollback:5e3,fontSize:13,fontFamily:'"Geist Mono", ui-monospace, monospace',lineHeight:1.05,letterSpacing:0,cursorBlink:!0,cursorStyle:"block",theme:YE,allowTransparency:!1,drawBoldTextInBrightColors:!1,minimumContrastRatio:7}),be=new zE,tt=new $E;je.loadAddon(be),je.loadAddon(tt),je.open(Le);const St={term:je,fit:be,serialize:tt,ws:null,container:Le,observer:null,connected:!1},ot=new ResizeObserver(()=>{var Mt;const{width:We}=Le.getBoundingClientRect();if(!(We<50))try{be.fit(),((Mt=St.ws)==null?void 0:Mt.readyState)===WebSocket.OPEN&&St.ws.send(JSON.stringify({type:"resize",cols:je.cols,rows:je.rows}))}catch{}});ot.observe(Le),St.observer=ot,Ri.set(Y,St),E(We=>[...We,Y]);try{const We=await XE(Y);if(We){const Mt=rv(We);je.write(Mt),Mt!==We&&sl(Y,Mt).catch(()=>{})}}catch{}Be?xe(Y,St,_e):I(We=>new Set(We).add(Y)),setTimeout(()=>U(St),50)},[xe,U]),M=w.useCallback(async(Y,he)=>{const _e=Ri.get(Y);_e&&(_e.ws&&(_e.ws.close(),_e.ws=null),he||(await j.current(`/api/terminal/${encodeURIComponent(Y)}`,{method:"DELETE"}).catch(()=>{}),_e.term.clear()),xe(Y,_e,he))},[xe]),G=w.useCallback(Y=>{const he=Ri.get(Y);if(he){try{const _e=he.serialize.serialize();sl(Y,_e).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),Ri.delete(Y),E(_e=>_e.filter(Be=>Be!==Y)),I(_e=>{const Be=new Set(_e);return Be.delete(Y),Be}),i(`/api/terminal/${encodeURIComponent(Y)}`,{method:"DELETE"}).catch(()=>{}),a==null||a(Y)}},[i,a]),C=w.useCallback(Y=>{var _e;const he=Ri.get(Y);he&&(((_e=he.ws)==null?void 0:_e.readyState)===WebSocket.OPEN&&he.ws.send(`exit -`),pf(Y).catch(()=>{}),he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),Ri.delete(Y),E(Be=>Be.filter(Le=>Le!==Y)),I(Be=>{const Le=new Set(Be);return Le.delete(Y),Le}),i(`/api/terminal/${encodeURIComponent(Y)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a(Y))},[i,a]),V=w.useCallback(async(Y,he,_e)=>{const Be=Ri.get(Y);if(!Be||Ri.has(he)||!(await j.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:Y,newName:he,..._e??{}})})).ok)return!1;Ri.delete(Y),Ri.set(he,Be);try{const je=Be.serialize.serialize();await pf(Y),await sl(he,je)}catch{}return E(je=>je.map(be=>be===Y?he:be)),I(je=>{if(!je.has(Y))return je;const be=new Set(je);return be.delete(Y),be.add(he),be}),(Be.connected||Be.ws)&&(await j.current(`/api/terminal/${encodeURIComponent(he)}`,{method:"DELETE"}).catch(()=>{}),Be.ws&&(Be.ws.close(),Be.ws=null),X.current(he,Be,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=V),()=>{h&&(h.current=null)}),[h,V]),w.useEffect(()=>{if(t){if(W){A(null);return}if(K){A(null);return}Ri.has(t)?A(t):j.current(`/api/terminal/session/${encodeURIComponent(t)}`).then(Y=>Y.ok?Y.json():null).then(Y=>{if(!Ri.has(t)){const he=(Y==null?void 0:Y.sessionId)&&!(Y!=null&&Y.running);T(t,{autoConnect:!he}),A(t)}}).catch(()=>{Ri.has(t)||(T(t),A(t))})}},[t,T,A,W,K]),w.useEffect(()=>{const Y=setInterval(()=>{for(const[he,_e]of Ri)if(_e.connected)try{const Be=_e.serialize.serialize();sl(he,Be).catch(()=>{})}catch{}},3e4);return()=>clearInterval(Y)},[]),w.useEffect(()=>()=>{for(const[Y,he]of Ri){try{const _e=he.serialize.serialize();sl(Y,_e).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),j.current(`/api/terminal/${encodeURIComponent(Y)}`,{method:"DELETE"}).catch(()=>{})}Ri.clear()},[]);const ne=t?N.has(t):!1,ae=R.length===0;return d.jsxs("div",{className:"h-full flex flex-col",children:[!ae&&d.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[R.map(Y=>d.jsxs("div",{onClick:()=>s==null?void 0:s(Y),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${Y===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${N.has(Y)?"bg-amber-500":Y===t?"bg-green-600":"bg-muted/50"}`}),d.jsx("span",{className:`truncate max-w-[120px] ${Y.startsWith("_new_")?"italic":""}`,children:Y.startsWith("_new_")?"Untitled":Y}),d.jsx("button",{onClick:he=>{he.stopPropagation(),Y.startsWith("_new_")?F(Y):G(Y)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},Y)),t!=null&&t.startsWith("_new_")?d.jsx("button",{onClick:()=>F(t),className:"ml-auto px-2 py-0.5 text-xs text-error hover:bg-surface rounded flex items-center gap-1 flex-shrink-0",children:"Cancel ×"}):t&&o&&(c!=null&&c.has(t))?d.jsx("button",{onClick:()=>ie(t),className:"ml-auto px-2 py-0.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1 flex-shrink-0",children:"Archive"}):null]}),d.jsxs("div",{className:"relative flex-1 min-h-0",children:[d.jsx("div",{ref:S,className:"h-full"}),ae&&!W&&!K&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a story on the left menu"}),d.jsx("p",{className:"text-sm mt-1",children:"to start an AI Writer session"})]})}),W&&d.jsx("div",{"data-testid":"cartoon-launch-blocked",className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Cartoon agent can't launch yet"}),d.jsx("p",{className:"text-xs text-muted",children:"This is a cartoon story. The writing agent needs Codex with image generation enabled before it can start, because the clean-image step relies on image generation support."}),_&&!_.codex.installed?d.jsxs("p",{className:"text-xs text-amber-700",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",d.jsx("span",{className:"font-mono",children:"codex login"}),"), then reopen this story."]}):Eu(_)?d.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[Up," Then reopen this story."]}):d.jsxs("div",{className:"space-y-1",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this story:"}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx("code",{className:"flex-1 truncate rounded border border-border bg-surface px-1.5 py-1 text-left text-[10px] font-mono text-foreground",children:sv}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable-launch",onClick:async()=>{try{await navigator.clipboard.writeText(sv),Se(!0),setTimeout(()=>Se(!1),2e3)}catch{}},className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:fe?"Copied!":"Copy"})]})]})]})}),K&&!W&&d.jsx("div",{"data-testid":"legacy-cartoon-provider-repair",className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Set this cartoon story's provider"}),d.jsx("p",{className:"text-xs text-muted",children:"This cartoon story was created before provider tracking, so it has no provider recorded and would launch with Claude — which can't generate the clean images cartoons need. Set this story's provider to Codex to continue."}),d.jsx("p",{className:"text-[11px] text-muted",children:"Only this story is changed. Other stories and fiction are not affected."}),d.jsx("button",{type:"button","data-testid":"repair-provider-codex",disabled:H,onClick:async()=>{if(!H){ce(!0);try{await(v==null?void 0:v())}finally{ce(!1)}}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:H?"Setting…":"Set this story's provider to Codex"})]})}),te&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Discard this session?"}),d.jsx("p",{className:"text-xs text-muted",children:"This session will be lost — your AI hasn't created a story structure yet."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>F(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:()=>{const Y=te;F(null),C(Y)},className:"px-4 py-1.5 bg-error text-white text-sm rounded hover:opacity-80",children:"Discard"})]})]})}),D&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Archive this story?"}),d.jsx("p",{className:"text-xs text-muted",children:"You can restore it later from the Archives view."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>ie(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:async()=>{const Y=D;ie(null);try{(await j.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Y})})).ok&&(G(Y),o==null||o(Y))}catch{}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Archive"})]})]})}),ne&&t&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("p",{className:"text-sm font-serif text-foreground",children:"Terminal disconnected"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>M(t,!0),className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Resume Session"}),d.jsx("button",{onClick:()=>M(t,!1),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Start Fresh"})]}),d.jsx("p",{className:"text-xs text-muted",children:"Resume continues your previous Claude conversation"})]})})]})]})}function QE(e,t){const i={};return(e[e.length-1]===""?[...e,""]:e).join((i.padRight?" ":"")+","+(i.padLeft===!1?"":" ")).trim()}const JE=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,eN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,tN={};function lv(e,t){return(tN.jsx?eN:JE).test(e)}const iN=/[ \t\n\f\r]/g;function nN(e){return typeof e=="object"?e.type==="text"?ov(e.value):!1:ov(e)}function ov(e){return e.replace(iN,"")===""}class $o{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}$o.prototype.normal={};$o.prototype.property={};$o.prototype.space=void 0;function S0(e,t){const i={},s={};for(const a of e)Object.assign(i,a.property),Object.assign(s,a.normal);return new $o(i,s,t)}function wp(e){return e.toLowerCase()}class kn{constructor(t,i){this.attribute=i,this.property=t}}kn.prototype.attribute="";kn.prototype.booleanish=!1;kn.prototype.boolean=!1;kn.prototype.commaOrSpaceSeparated=!1;kn.prototype.commaSeparated=!1;kn.prototype.defined=!1;kn.prototype.mustUseProperty=!1;kn.prototype.number=!1;kn.prototype.overloadedBoolean=!1;kn.prototype.property="";kn.prototype.spaceSeparated=!1;kn.prototype.space=void 0;let rN=0;const at=va(),yi=va(),Cp=va(),ve=va(),Yt=va(),hl=va(),Pn=va();function va(){return 2**++rN}const kp=Object.freeze(Object.defineProperty({__proto__:null,boolean:at,booleanish:yi,commaOrSpaceSeparated:Pn,commaSeparated:hl,number:ve,overloadedBoolean:Cp,spaceSeparated:Yt},Symbol.toStringTag,{value:"Module"})),mf=Object.keys(kp);class Jp extends kn{constructor(t,i,s,a){let o=-1;if(super(t,i),cv(this,"space",a),typeof s=="number")for(;++o4&&i.slice(0,4)==="data"&&cN.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(uv,dN);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!uv.test(o)){let c=o.replace(oN,hN);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}a=Jp}return new a(s,t)}function hN(e){return"-"+e.toLowerCase()}function dN(e){return e.charAt(1).toUpperCase()}const fN=S0([w0,sN,E0,N0,j0],"html"),em=S0([w0,aN,E0,N0,j0],"svg");function pN(e){return e.join(" ").trim()}var al={},gf,hv;function mN(){if(hv)return gf;hv=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,i=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,h=/^\s+|\s+$/g,p=` -`,f="/",_="*",x="",b="comment",v="declaration";function S(R,E){if(typeof R!="string")throw new TypeError("First argument must be a string");if(!R)return[];E=E||{};var N=1,I=1;function te(X){var U=X.match(t);U&&(N+=U.length);var A=X.lastIndexOf(p);I=~A?X.length-A:I+X.length}function F(){var X={line:N,column:I};return function(U){return U.position=new D(X),Se(),U}}function D(X){this.start=X,this.end={line:N,column:I},this.source=E.source}D.prototype.content=R;function ie(X){var U=new Error(E.source+":"+N+":"+I+": "+X);if(U.reason=X,U.filename=E.source,U.line=N,U.column=I,U.source=R,!E.silent)throw U}function fe(X){var U=X.exec(R);if(U){var A=U[0];return te(A),R=R.slice(A.length),U}}function Se(){fe(i)}function H(X){var U;for(X=X||[];U=ce();)U!==!1&&X.push(U);return X}function ce(){var X=F();if(!(f!=R.charAt(0)||_!=R.charAt(1))){for(var U=2;x!=R.charAt(U)&&(_!=R.charAt(U)||f!=R.charAt(U+1));)++U;if(U+=2,x===R.charAt(U-1))return ie("End of comment missing");var A=R.slice(2,U-2);return I+=2,te(A),R=R.slice(U),I+=2,X({type:b,comment:A})}}function W(){var X=F(),U=fe(s);if(U){if(ce(),!fe(a))return ie("property missing ':'");var A=fe(o),O=X({type:v,property:j(U[0].replace(e,x)),value:A?j(A[0].replace(e,x)):x});return fe(c),O}}function K(){var X=[];H(X);for(var U;U=W();)U!==!1&&(X.push(U),H(X));return X}return Se(),K()}function j(R){return R?R.replace(h,x):x}return gf=S,gf}var dv;function gN(){if(dv)return al;dv=1;var e=al&&al.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(al,"__esModule",{value:!0}),al.default=i;const t=e(mN());function i(s,a){let o=null;if(!s||typeof s!="string")return o;const c=(0,t.default)(s),h=typeof a=="function";return c.forEach(p=>{if(p.type!=="declaration")return;const{property:f,value:_}=p;h?a(f,_,p):_&&(o=o||{},o[f]=_)}),o}return al}var go={},fv;function xN(){if(fv)return go;fv=1,Object.defineProperty(go,"__esModule",{value:!0}),go.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,i=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(f){return!f||i.test(f)||e.test(f)},c=function(f,_){return _.toUpperCase()},h=function(f,_){return"".concat(_,"-")},p=function(f,_){return _===void 0&&(_={}),o(f)?f:(f=f.toLowerCase(),_.reactCompat?f=f.replace(a,h):f=f.replace(s,h),f.replace(t,c))};return go.camelCase=p,go}var xo,pv;function _N(){if(pv)return xo;pv=1;var e=xo&&xo.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(gN()),i=xN();function s(a,o){var c={};return!a||typeof a!="string"||(0,t.default)(a,function(h,p){h&&p&&(c[(0,i.camelCase)(h,o)]=p)}),c}return s.default=s,xo=s,xo}var bN=_N();const vN=zu(bN),T0=A0("end"),tm=A0("start");function A0(e){return t;function t(i){const s=i&&i.position&&i.position[e]||{};if(typeof s.line=="number"&&s.line>0&&typeof s.column=="number"&&s.column>0)return{line:s.line,column:s.column,offset:typeof s.offset=="number"&&s.offset>-1?s.offset:void 0}}}function R0(e){const t=tm(e),i=T0(e);if(t&&i)return{start:t,end:i}}function No(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?mv(e.position):"start"in e||"end"in e?mv(e):"line"in e||"column"in e?Ep(e):""}function Ep(e){return gv(e&&e.line)+":"+gv(e&&e.column)}function mv(e){return Ep(e&&e.start)+"-"+Ep(e&&e.end)}function gv(e){return e&&typeof e=="number"?e:1}class an extends Error{constructor(t,i,s){super(),typeof i=="string"&&(s=i,i=void 0);let a="",o={},c=!1;if(i&&("line"in i&&"column"in i?o={place:i}:"start"in i&&"end"in i?o={place:i}:"type"in i?o={ancestors:[i],place:i.position}:o={...i}),typeof t=="string"?a=t:!o.cause&&t&&(c=!0,a=t.message,o.cause=t),!o.ruleId&&!o.source&&typeof s=="string"){const p=s.indexOf(":");p===-1?o.ruleId=s:(o.source=s.slice(0,p),o.ruleId=s.slice(p+1))}if(!o.place&&o.ancestors&&o.ancestors){const p=o.ancestors[o.ancestors.length-1];p&&(o.place=p.position)}const h=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=h?h.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=h?h.line:void 0,this.name=No(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=c&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}an.prototype.file="";an.prototype.name="";an.prototype.reason="";an.prototype.message="";an.prototype.stack="";an.prototype.column=void 0;an.prototype.line=void 0;an.prototype.ancestors=void 0;an.prototype.cause=void 0;an.prototype.fatal=void 0;an.prototype.place=void 0;an.prototype.ruleId=void 0;an.prototype.source=void 0;const im={}.hasOwnProperty,yN=new Map,SN=/[A-Z]/g,wN=new Set(["table","tbody","thead","tfoot","tr"]),CN=new Set(["td","th"]),D0="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function kN(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const i=t.filePath||void 0;let s;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");s=MN(i,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");s=DN(i,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:s,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:i,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?em:fN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=M0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function M0(e,t,i){if(t.type==="element")return EN(e,t,i);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return NN(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return TN(e,t,i);if(t.type==="mdxjsEsm")return jN(e,t);if(t.type==="root")return AN(e,t,i);if(t.type==="text")return RN(e,t)}function EN(e,t,i){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=em,e.schema=a),e.ancestors.push(t);const o=L0(e,t.tagName,!1),c=BN(e,t);let h=rm(e,t);return wN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!nN(p):!0})),B0(e,c,o,t),nm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function NN(e,t){if(t.data&&t.data.estree&&e.evaluater){const s=t.data.estree.body[0];return s.type,e.evaluater.evaluateExpression(s.expression)}Bo(e,t.position)}function jN(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Bo(e,t.position)}function TN(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=em,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:L0(e,t.name,!0),c=LN(e,t),h=rm(e,t);return B0(e,c,o,t),nm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function AN(e,t,i){const s={};return nm(s,rm(e,t)),e.create(t,e.Fragment,s,i)}function RN(e,t){return t.value}function B0(e,t,i,s){typeof i!="string"&&i!==e.Fragment&&e.passNode&&(t.node=s)}function nm(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function DN(e,t,i){return s;function s(a,o,c,h){const f=Array.isArray(c.children)?i:t;return h?f(o,c,h):f(o,c)}}function MN(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=tm(s);return t(a,o,c,h,{columnNumber:p?p.column-1:void 0,fileName:e,lineNumber:p?p.line:void 0},void 0)}}function BN(e,t){const i={};let s,a;for(a in t.properties)if(a!=="children"&&im.call(t.properties,a)){const o=ON(e,a,t.properties[a]);if(o){const[c,h]=o;e.tableCellAlignToStyle&&c==="align"&&typeof h=="string"&&CN.has(t.tagName)?s=h:i[c]=h}}if(s){const o=i.style||(i.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=s}return i}function LN(e,t){const i={};for(const s of t.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&e.evaluater){const o=s.data.estree.body[0];o.type;const c=o.expression;c.type;const h=c.properties[0];h.type,Object.assign(i,e.evaluater.evaluateExpression(h.argument))}else Bo(e,t.position);else{const a=s.name;let o;if(s.value&&typeof s.value=="object")if(s.value.data&&s.value.data.estree&&e.evaluater){const h=s.value.data.estree.body[0];h.type,o=e.evaluater.evaluateExpression(h.expression)}else Bo(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function rm(e,t){const i=[];let s=-1;const a=e.passKeys?new Map:yN;for(;++sa?0:a+t:t=t>a?a:t,i=i>0?i:0,s.length<1e4)c=Array.from(s),c.unshift(t,i),e.splice(...c);else for(i&&e.splice(t,i);o0?(Hn(e,e.length,0,t),e):t}const bv={}.hasOwnProperty;function z0(e){const t={};let i=-1;for(;++i13&&i<32||i>126&&i<160||i>55295&&i<57344||i>64975&&i<65008||(i&65535)===65535||(i&65535)===65534||i>1114111?"�":String.fromCodePoint(i)}function fr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const fn=$s(/[A-Za-z]/),sn=$s(/[\dA-Za-z]/),WN=$s(/[#-'*+\--9=?A-Z^-~]/);function Mu(e){return e!==null&&(e<32||e===127)}const Np=$s(/\d/),GN=$s(/[\dA-Fa-f]/),YN=$s(/[!-/:-@[-`{-~]/);function Ye(e){return e!==null&&e<-2}function qt(e){return e!==null&&(e<0||e===32)}function gt(e){return e===-2||e===-1||e===32}const $u=$s(new RegExp("\\p{P}|\\p{S}","u")),_a=$s(/\s/);function $s(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function vl(e){const t=[];let i=-1,s=0,a=0;for(;++i55295&&o<57344){const h=e.charCodeAt(i+1);o<56320&&h>56319&&h<57344?(c=String.fromCharCode(o,h),a=1):c="�"}else c=String.fromCharCode(o);c&&(t.push(e.slice(s,i),encodeURIComponent(c)),s=i+a+1,c=""),a&&(i+=a,a=0)}return t.join("")+e.slice(s)}function kt(e,t,i,s){const a=s?s-1:Number.POSITIVE_INFINITY;let o=0;return c;function c(p){return gt(p)?(e.enter(i),h(p)):t(p)}function h(p){return gt(p)&&o++c))return;const ie=t.events.length;let fe=ie,Se,H;for(;fe--;)if(t.events[fe][0]==="exit"&&t.events[fe][1].type==="chunkFlow"){if(Se){H=t.events[fe][1].end;break}Se=!0}for(E(s),D=ie;DI;){const F=i[te];t.containerState=F[1],F[0].exit.call(t,e)}i.length=I}function N(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function QN(e,t,i){return kt(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ml(e){if(e===null||qt(e)||_a(e))return 1;if($u(e))return 2}function Fu(e,t,i){const s=[];let a=-1;for(;++a1&&e[i][1].end.offset-e[i][1].start.offset>1?2:1;const x={...e[s][1].end},b={...e[i][1].start};yv(x,-p),yv(b,p),c={type:p>1?"strongSequence":"emphasisSequence",start:x,end:{...e[s][1].end}},h={type:p>1?"strongSequence":"emphasisSequence",start:{...e[i][1].start},end:b},o={type:p>1?"strongText":"emphasisText",start:{...e[s][1].end},end:{...e[i][1].start}},a={type:p>1?"strong":"emphasis",start:{...c.start},end:{...h.end}},e[s][1].end={...c.start},e[i][1].start={...h.end},f=[],e[s][1].end.offset-e[s][1].start.offset&&(f=rr(f,[["enter",e[s][1],t],["exit",e[s][1],t]])),f=rr(f,[["enter",a,t],["enter",c,t],["exit",c,t],["enter",o,t]]),f=rr(f,Fu(t.parser.constructs.insideSpan.null,e.slice(s+1,i),t)),f=rr(f,[["exit",o,t],["enter",h,t],["exit",h,t],["exit",a,t]]),e[i][1].end.offset-e[i][1].start.offset?(_=2,f=rr(f,[["enter",e[i][1],t],["exit",e[i][1],t]])):_=0,Hn(e,s-1,i-s+3,f),i=s+f.length-_-2;break}}for(i=-1;++i0&>(D)?kt(e,N,"linePrefix",o+1)(D):N(D)}function N(D){return D===null||Ye(D)?e.check(Sv,j,te)(D):(e.enter("codeFlowValue"),I(D))}function I(D){return D===null||Ye(D)?(e.exit("codeFlowValue"),N(D)):(e.consume(D),I)}function te(D){return e.exit("codeFenced"),t(D)}function F(D,ie,fe){let Se=0;return H;function H(U){return D.enter("lineEnding"),D.consume(U),D.exit("lineEnding"),ce}function ce(U){return D.enter("codeFencedFence"),gt(U)?kt(D,W,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(U):W(U)}function W(U){return U===h?(D.enter("codeFencedFenceSequence"),K(U)):fe(U)}function K(U){return U===h?(Se++,D.consume(U),K):Se>=c?(D.exit("codeFencedFenceSequence"),gt(U)?kt(D,X,"whitespace")(U):X(U)):fe(U)}function X(U){return U===null||Ye(U)?(D.exit("codeFencedFence"),ie(U)):fe(U)}}}function u5(e,t,i){const s=this;return a;function a(c){return c===null?i(c):(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o)}function o(c){return s.parser.lazy[s.now().line]?i(c):t(c)}}const _f={name:"codeIndented",tokenize:d5},h5={partial:!0,tokenize:f5};function d5(e,t,i){const s=this;return a;function a(f){return e.enter("codeIndented"),kt(e,o,"linePrefix",5)(f)}function o(f){const _=s.events[s.events.length-1];return _&&_[1].type==="linePrefix"&&_[2].sliceSerialize(_[1],!0).length>=4?c(f):i(f)}function c(f){return f===null?p(f):Ye(f)?e.attempt(h5,c,p)(f):(e.enter("codeFlowValue"),h(f))}function h(f){return f===null||Ye(f)?(e.exit("codeFlowValue"),c(f)):(e.consume(f),h)}function p(f){return e.exit("codeIndented"),t(f)}}function f5(e,t,i){const s=this;return a;function a(c){return s.parser.lazy[s.now().line]?i(c):Ye(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):kt(e,o,"linePrefix",5)(c)}function o(c){const h=s.events[s.events.length-1];return h&&h[1].type==="linePrefix"&&h[2].sliceSerialize(h[1],!0).length>=4?t(c):Ye(c)?a(c):i(c)}}const p5={name:"codeText",previous:g5,resolve:m5,tokenize:x5};function m5(e){let t=e.length-4,i=3,s,a;if((e[i][1].type==="lineEnding"||e[i][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(s=i;++s=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-s+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-s+this.left.length).reverse())}splice(t,i,s){const a=i||0;this.setCursor(Math.trunc(t));const o=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return s&&_o(this.left,s),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),_o(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),_o(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(c):e.interrupt(s.parser.constructs.flow,i,t)(c)}}function F0(e,t,i,s,a,o,c,h,p){const f=p||Number.POSITIVE_INFINITY;let _=0;return x;function x(E){return E===60?(e.enter(s),e.enter(a),e.enter(o),e.consume(E),e.exit(o),b):E===null||E===32||E===41||Mu(E)?i(E):(e.enter(s),e.enter(c),e.enter(h),e.enter("chunkString",{contentType:"string"}),j(E))}function b(E){return E===62?(e.enter(o),e.consume(E),e.exit(o),e.exit(a),e.exit(s),t):(e.enter(h),e.enter("chunkString",{contentType:"string"}),v(E))}function v(E){return E===62?(e.exit("chunkString"),e.exit(h),b(E)):E===null||E===60||Ye(E)?i(E):(e.consume(E),E===92?S:v)}function S(E){return E===60||E===62||E===92?(e.consume(E),v):v(E)}function j(E){return!_&&(E===null||E===41||qt(E))?(e.exit("chunkString"),e.exit(h),e.exit(c),e.exit(s),t(E)):_999||v===null||v===91||v===93&&!p||v===94&&!h&&"_hiddenFootnoteSupport"in c.parser.constructs?i(v):v===93?(e.exit(o),e.enter(a),e.consume(v),e.exit(a),e.exit(s),t):Ye(v)?(e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),_):(e.enter("chunkString",{contentType:"string"}),x(v))}function x(v){return v===null||v===91||v===93||Ye(v)||h++>999?(e.exit("chunkString"),_(v)):(e.consume(v),p||(p=!gt(v)),v===92?b:x)}function b(v){return v===91||v===92||v===93?(e.consume(v),h++,x):x(v)}}function W0(e,t,i,s,a,o){let c;return h;function h(b){return b===34||b===39||b===40?(e.enter(s),e.enter(a),e.consume(b),e.exit(a),c=b===40?41:b,p):i(b)}function p(b){return b===c?(e.enter(a),e.consume(b),e.exit(a),e.exit(s),t):(e.enter(o),f(b))}function f(b){return b===c?(e.exit(o),p(c)):b===null?i(b):Ye(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),kt(e,f,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),_(b))}function _(b){return b===c||b===null||Ye(b)?(e.exit("chunkString"),f(b)):(e.consume(b),b===92?x:_)}function x(b){return b===c||b===92?(e.consume(b),_):_(b)}}function jo(e,t){let i;return s;function s(a){return Ye(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):gt(a)?kt(e,s,i?"linePrefix":"lineSuffix")(a):t(a)}}const k5={name:"definition",tokenize:N5},E5={partial:!0,tokenize:j5};function N5(e,t,i){const s=this;let a;return o;function o(v){return e.enter("definition"),c(v)}function c(v){return q0.call(s,e,h,i,"definitionLabel","definitionLabelMarker","definitionLabelString")(v)}function h(v){return a=fr(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),v===58?(e.enter("definitionMarker"),e.consume(v),e.exit("definitionMarker"),p):i(v)}function p(v){return qt(v)?jo(e,f)(v):f(v)}function f(v){return F0(e,_,i,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function _(v){return e.attempt(E5,x,x)(v)}function x(v){return gt(v)?kt(e,b,"whitespace")(v):b(v)}function b(v){return v===null||Ye(v)?(e.exit("definition"),s.parser.defined.push(a),t(v)):i(v)}}function j5(e,t,i){return s;function s(h){return qt(h)?jo(e,a)(h):i(h)}function a(h){return W0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return gt(h)?kt(e,c,"whitespace")(h):c(h)}function c(h){return h===null||Ye(h)?t(h):i(h)}}const T5={name:"hardBreakEscape",tokenize:A5};function A5(e,t,i){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),a}function a(o){return Ye(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const R5={name:"headingAtx",resolve:D5,tokenize:M5};function D5(e,t){let i=e.length-2,s=3,a,o;return e[s][1].type==="whitespace"&&(s+=2),i-2>s&&e[i][1].type==="whitespace"&&(i-=2),e[i][1].type==="atxHeadingSequence"&&(s===i-1||i-4>s&&e[i-2][1].type==="whitespace")&&(i-=s+1===i?2:4),i>s&&(a={type:"atxHeadingText",start:e[s][1].start,end:e[i][1].end},o={type:"chunkText",start:e[s][1].start,end:e[i][1].end,contentType:"text"},Hn(e,s,i-s+1,[["enter",a,t],["enter",o,t],["exit",o,t],["exit",a,t]])),e}function M5(e,t,i){let s=0;return a;function a(_){return e.enter("atxHeading"),o(_)}function o(_){return e.enter("atxHeadingSequence"),c(_)}function c(_){return _===35&&s++<6?(e.consume(_),c):_===null||qt(_)?(e.exit("atxHeadingSequence"),h(_)):i(_)}function h(_){return _===35?(e.enter("atxHeadingSequence"),p(_)):_===null||Ye(_)?(e.exit("atxHeading"),t(_)):gt(_)?kt(e,h,"whitespace")(_):(e.enter("atxHeadingText"),f(_))}function p(_){return _===35?(e.consume(_),p):(e.exit("atxHeadingSequence"),h(_))}function f(_){return _===null||_===35||qt(_)?(e.exit("atxHeadingText"),h(_)):(e.consume(_),f)}}const B5=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Cv=["pre","script","style","textarea"],L5={concrete:!0,name:"htmlFlow",resolveTo:P5,tokenize:I5},O5={partial:!0,tokenize:U5},z5={partial:!0,tokenize:H5};function P5(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function I5(e,t,i){const s=this;let a,o,c,h,p;return f;function f(C){return _(C)}function _(C){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(C),x}function x(C){return C===33?(e.consume(C),b):C===47?(e.consume(C),o=!0,j):C===63?(e.consume(C),a=3,s.interrupt?t:T):fn(C)?(e.consume(C),c=String.fromCharCode(C),R):i(C)}function b(C){return C===45?(e.consume(C),a=2,v):C===91?(e.consume(C),a=5,h=0,S):fn(C)?(e.consume(C),a=4,s.interrupt?t:T):i(C)}function v(C){return C===45?(e.consume(C),s.interrupt?t:T):i(C)}function S(C){const V="CDATA[";return C===V.charCodeAt(h++)?(e.consume(C),h===V.length?s.interrupt?t:W:S):i(C)}function j(C){return fn(C)?(e.consume(C),c=String.fromCharCode(C),R):i(C)}function R(C){if(C===null||C===47||C===62||qt(C)){const V=C===47,ne=c.toLowerCase();return!V&&!o&&Cv.includes(ne)?(a=1,s.interrupt?t(C):W(C)):B5.includes(c.toLowerCase())?(a=6,V?(e.consume(C),E):s.interrupt?t(C):W(C)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(C):o?N(C):I(C))}return C===45||sn(C)?(e.consume(C),c+=String.fromCharCode(C),R):i(C)}function E(C){return C===62?(e.consume(C),s.interrupt?t:W):i(C)}function N(C){return gt(C)?(e.consume(C),N):H(C)}function I(C){return C===47?(e.consume(C),H):C===58||C===95||fn(C)?(e.consume(C),te):gt(C)?(e.consume(C),I):H(C)}function te(C){return C===45||C===46||C===58||C===95||sn(C)?(e.consume(C),te):F(C)}function F(C){return C===61?(e.consume(C),D):gt(C)?(e.consume(C),F):I(C)}function D(C){return C===null||C===60||C===61||C===62||C===96?i(C):C===34||C===39?(e.consume(C),p=C,ie):gt(C)?(e.consume(C),D):fe(C)}function ie(C){return C===p?(e.consume(C),p=null,Se):C===null||Ye(C)?i(C):(e.consume(C),ie)}function fe(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||qt(C)?F(C):(e.consume(C),fe)}function Se(C){return C===47||C===62||gt(C)?I(C):i(C)}function H(C){return C===62?(e.consume(C),ce):i(C)}function ce(C){return C===null||Ye(C)?W(C):gt(C)?(e.consume(C),ce):i(C)}function W(C){return C===45&&a===2?(e.consume(C),A):C===60&&a===1?(e.consume(C),O):C===62&&a===4?(e.consume(C),M):C===63&&a===3?(e.consume(C),T):C===93&&a===5?(e.consume(C),xe):Ye(C)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(O5,G,K)(C)):C===null||Ye(C)?(e.exit("htmlFlowData"),K(C)):(e.consume(C),W)}function K(C){return e.check(z5,X,G)(C)}function X(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),U}function U(C){return C===null||Ye(C)?K(C):(e.enter("htmlFlowData"),W(C))}function A(C){return C===45?(e.consume(C),T):W(C)}function O(C){return C===47?(e.consume(C),c="",$):W(C)}function $(C){if(C===62){const V=c.toLowerCase();return Cv.includes(V)?(e.consume(C),M):W(C)}return fn(C)&&c.length<8?(e.consume(C),c+=String.fromCharCode(C),$):W(C)}function xe(C){return C===93?(e.consume(C),T):W(C)}function T(C){return C===62?(e.consume(C),M):C===45&&a===2?(e.consume(C),T):W(C)}function M(C){return C===null||Ye(C)?(e.exit("htmlFlowData"),G(C)):(e.consume(C),M)}function G(C){return e.exit("htmlFlow"),t(C)}}function H5(e,t,i){const s=this;return a;function a(c){return Ye(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o):i(c)}function o(c){return s.parser.lazy[s.now().line]?i(c):t(c)}}function U5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Fo,t,i)}}const $5={name:"htmlText",tokenize:F5};function F5(e,t,i){const s=this;let a,o,c;return h;function h(T){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(T),p}function p(T){return T===33?(e.consume(T),f):T===47?(e.consume(T),F):T===63?(e.consume(T),I):fn(T)?(e.consume(T),fe):i(T)}function f(T){return T===45?(e.consume(T),_):T===91?(e.consume(T),o=0,S):fn(T)?(e.consume(T),N):i(T)}function _(T){return T===45?(e.consume(T),v):i(T)}function x(T){return T===null?i(T):T===45?(e.consume(T),b):Ye(T)?(c=x,O(T)):(e.consume(T),x)}function b(T){return T===45?(e.consume(T),v):x(T)}function v(T){return T===62?A(T):T===45?b(T):x(T)}function S(T){const M="CDATA[";return T===M.charCodeAt(o++)?(e.consume(T),o===M.length?j:S):i(T)}function j(T){return T===null?i(T):T===93?(e.consume(T),R):Ye(T)?(c=j,O(T)):(e.consume(T),j)}function R(T){return T===93?(e.consume(T),E):j(T)}function E(T){return T===62?A(T):T===93?(e.consume(T),E):j(T)}function N(T){return T===null||T===62?A(T):Ye(T)?(c=N,O(T)):(e.consume(T),N)}function I(T){return T===null?i(T):T===63?(e.consume(T),te):Ye(T)?(c=I,O(T)):(e.consume(T),I)}function te(T){return T===62?A(T):I(T)}function F(T){return fn(T)?(e.consume(T),D):i(T)}function D(T){return T===45||sn(T)?(e.consume(T),D):ie(T)}function ie(T){return Ye(T)?(c=ie,O(T)):gt(T)?(e.consume(T),ie):A(T)}function fe(T){return T===45||sn(T)?(e.consume(T),fe):T===47||T===62||qt(T)?Se(T):i(T)}function Se(T){return T===47?(e.consume(T),A):T===58||T===95||fn(T)?(e.consume(T),H):Ye(T)?(c=Se,O(T)):gt(T)?(e.consume(T),Se):A(T)}function H(T){return T===45||T===46||T===58||T===95||sn(T)?(e.consume(T),H):ce(T)}function ce(T){return T===61?(e.consume(T),W):Ye(T)?(c=ce,O(T)):gt(T)?(e.consume(T),ce):Se(T)}function W(T){return T===null||T===60||T===61||T===62||T===96?i(T):T===34||T===39?(e.consume(T),a=T,K):Ye(T)?(c=W,O(T)):gt(T)?(e.consume(T),W):(e.consume(T),X)}function K(T){return T===a?(e.consume(T),a=void 0,U):T===null?i(T):Ye(T)?(c=K,O(T)):(e.consume(T),K)}function X(T){return T===null||T===34||T===39||T===60||T===61||T===96?i(T):T===47||T===62||qt(T)?Se(T):(e.consume(T),X)}function U(T){return T===47||T===62||qt(T)?Se(T):i(T)}function A(T){return T===62?(e.consume(T),e.exit("htmlTextData"),e.exit("htmlText"),t):i(T)}function O(T){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),$}function $(T){return gt(T)?kt(e,xe,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):xe(T)}function xe(T){return e.enter("htmlTextData"),c(T)}}const lm={name:"labelEnd",resolveAll:Y5,resolveTo:K5,tokenize:V5},q5={tokenize:X5},W5={tokenize:Z5},G5={tokenize:Q5};function Y5(e){let t=-1;const i=[];for(;++t=3&&(f===null||Ye(f))?(e.exit("thematicBreak"),t(f)):i(f)}function p(f){return f===a?(e.consume(f),s++,p):(e.exit("thematicBreakSequence"),gt(f)?kt(e,h,"whitespace")(f):h(f))}}const Cn={continuation:{tokenize:oj},exit:uj,name:"list",tokenize:lj},sj={partial:!0,tokenize:hj},aj={partial:!0,tokenize:cj};function lj(e,t,i){const s=this,a=s.events[s.events.length-1];let o=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,c=0;return h;function h(v){const S=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(S==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:Np(v)){if(s.containerState.type||(s.containerState.type=S,e.enter(S,{_container:!0})),S==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(wu,i,f)(v):f(v);if(!s.interrupt||v===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),p(v)}return i(v)}function p(v){return Np(v)&&++c<10?(e.consume(v),p):(!s.interrupt||c<2)&&(s.containerState.marker?v===s.containerState.marker:v===41||v===46)?(e.exit("listItemValue"),f(v)):i(v)}function f(v){return e.enter("listItemMarker"),e.consume(v),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||v,e.check(Fo,s.interrupt?i:_,e.attempt(sj,b,x))}function _(v){return s.containerState.initialBlankLine=!0,o++,b(v)}function x(v){return gt(v)?(e.enter("listItemPrefixWhitespace"),e.consume(v),e.exit("listItemPrefixWhitespace"),b):i(v)}function b(v){return s.containerState.size=o+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(v)}}function oj(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Fo,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,kt(e,t,"listItemIndent",s.containerState.size+1)(h)}function o(h){return s.containerState.furtherBlankLines||!gt(h)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,c(h)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(aj,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,kt(e,e.attempt(Cn,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function cj(e,t,i){const s=this;return kt(e,a,"listItemIndent",s.containerState.size+1);function a(o){const c=s.events[s.events.length-1];return c&&c[1].type==="listItemIndent"&&c[2].sliceSerialize(c[1],!0).length===s.containerState.size?t(o):i(o)}}function uj(e){e.exit(this.containerState.type)}function hj(e,t,i){const s=this;return kt(e,a,"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(o){const c=s.events[s.events.length-1];return!gt(o)&&c&&c[1].type==="listItemPrefixWhitespace"?t(o):i(o)}}const kv={name:"setextUnderline",resolveTo:dj,tokenize:fj};function dj(e,t){let i=e.length,s,a,o;for(;i--;)if(e[i][0]==="enter"){if(e[i][1].type==="content"){s=i;break}e[i][1].type==="paragraph"&&(a=i)}else e[i][1].type==="content"&&e.splice(i,1),!o&&e[i][1].type==="definition"&&(o=i);const c={type:"setextHeading",start:{...e[s][1].start},end:{...e[e.length-1][1].end}};return e[a][1].type="setextHeadingText",o?(e.splice(a,0,["enter",c,t]),e.splice(o+1,0,["exit",e[s][1],t]),e[s][1].end={...e[o][1].end}):e[s][1]=c,e.push(["exit",c,t]),e}function fj(e,t,i){const s=this;let a;return o;function o(f){let _=s.events.length,x;for(;_--;)if(s.events[_][1].type!=="lineEnding"&&s.events[_][1].type!=="linePrefix"&&s.events[_][1].type!=="content"){x=s.events[_][1].type==="paragraph";break}return!s.parser.lazy[s.now().line]&&(s.interrupt||x)?(e.enter("setextHeadingLine"),a=f,c(f)):i(f)}function c(f){return e.enter("setextHeadingLineSequence"),h(f)}function h(f){return f===a?(e.consume(f),h):(e.exit("setextHeadingLineSequence"),gt(f)?kt(e,p,"lineSuffix")(f):p(f))}function p(f){return f===null||Ye(f)?(e.exit("setextHeadingLine"),t(f)):i(f)}}const pj={tokenize:mj};function mj(e){const t=this,i=e.attempt(Fo,s,e.attempt(this.parser.constructs.flowInitial,a,kt(e,e.attempt(this.parser.constructs.flow,a,e.attempt(v5,a)),"linePrefix")));return i;function s(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),t.currentConstruct=void 0,i}function a(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),t.currentConstruct=void 0,i}}const gj={resolveAll:Y0()},xj=G0("string"),_j=G0("text");function G0(e){return{resolveAll:Y0(e==="text"?bj:void 0),tokenize:t};function t(i){const s=this,a=this.parser.constructs[e],o=i.attempt(a,c,h);return c;function c(_){return f(_)?o(_):h(_)}function h(_){if(_===null){i.consume(_);return}return i.enter("data"),i.consume(_),p}function p(_){return f(_)?(i.exit("data"),o(_)):(i.consume(_),p)}function f(_){if(_===null)return!0;const x=a[_];let b=-1;if(x)for(;++b-1){const h=c[0];typeof h=="string"?c[0]=h.slice(s):c.shift()}o>0&&c.push(e[a].slice(0,o))}return c}function Dj(e,t){let i=-1;const s=[];let a;for(;++inew Set(Ve).add(K))}},he.term.onData(at=>{Ue.readyState===WebSocket.OPEN&&Ue.send(at)}),he.ws=Ue},[e]);w.useEffect(()=>{Y.current=ge},[ge]);const T=w.useCallback(async(K,he)=>{if(!S.current||Ri.has(K))return;const{resume:_e=!1,autoConnect:Me=!0}=he??{},Le=document.createElement("div");Le.style.width="100%",Le.style.height="100%",Le.style.display="none",Le.style.paddingLeft="10px",Le.style.boxSizing="border-box",S.current.appendChild(Le);const He=new UE({cols:80,scrollback:5e3,fontSize:13,fontFamily:'"Geist Mono", ui-monospace, monospace',lineHeight:1.05,letterSpacing:0,cursorBlink:!0,cursorStyle:"block",theme:eN,allowTransparency:!1,drawBoldTextInBrightColors:!1,minimumContrastRatio:7}),ke=new qE,Ue=new VE;He.loadAddon(ke),He.loadAddon(Ue),He.open(Le);const Je={term:He,fit:ke,serialize:Ue,ws:null,container:Le,observer:null,connected:!1},at=new ResizeObserver(()=>{var Et;const{width:Ve}=Le.getBoundingClientRect();if(!(Ve<50))try{ke.fit(),((Et=Je.ws)==null?void 0:Et.readyState)===WebSocket.OPEN&&Je.ws.send(JSON.stringify({type:"resize",cols:He.cols,rows:He.rows}))}catch{}});at.observe(Le),Je.observer=at,Ri.set(K,Je),E(Ve=>[...Ve,K]);try{const Ve=await nN(K);if(Ve){const Et=av(Ve);He.write(Et),Et!==Ve&&sl(K,Et).catch(()=>{})}}catch{}Me?ge(K,Je,_e):I(Ve=>new Set(Ve).add(K)),setTimeout(()=>U(Je),50)},[ge,U]),M=w.useCallback(async(K,he)=>{const _e=Ri.get(K);_e&&(_e.ws&&(_e.ws.close(),_e.ws=null),he||(await j.current(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{}),_e.term.clear()),ge(K,_e,he))},[ge]),V=w.useCallback(K=>{const he=Ri.get(K);if(he){try{const _e=he.serialize.serialize();sl(K,_e).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),Ri.delete(K),E(_e=>_e.filter(Me=>Me!==K)),I(_e=>{const Me=new Set(_e);return Me.delete(K),Me}),i(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{}),a==null||a(K)}},[i,a]),C=w.useCallback(K=>{var _e;const he=Ri.get(K);he&&(((_e=he.ws)==null?void 0:_e.readyState)===WebSocket.OPEN&&he.ws.send(`exit +`),mf(K).catch(()=>{}),he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),Ri.delete(K),E(Me=>Me.filter(Le=>Le!==K)),I(Me=>{const Le=new Set(Me);return Le.delete(K),Le}),i(`/api/terminal/${encodeURIComponent(K)}/discard`,{method:"DELETE"}).catch(()=>{}),a==null||a(K))},[i,a]),X=w.useCallback(async(K,he,_e)=>{const Me=Ri.get(K);if(!Me||Ri.has(he)||!(await j.current("/api/terminal/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldName:K,newName:he,..._e??{}})})).ok)return!1;Ri.delete(K),Ri.set(he,Me);try{const He=Me.serialize.serialize();await mf(K),await sl(he,He)}catch{}return E(He=>He.map(ke=>ke===K?he:ke)),I(He=>{if(!He.has(K))return He;const ke=new Set(He);return ke.delete(K),ke.add(he),ke}),(Me.connected||Me.ws)&&(await j.current(`/api/terminal/${encodeURIComponent(he)}`,{method:"DELETE"}).catch(()=>{}),Me.ws&&(Me.ws.close(),Me.ws=null),Y.current(he,Me,!0)),!0},[]);w.useEffect(()=>(h&&(h.current=X),()=>{h&&(h.current=null)}),[h,X]),w.useEffect(()=>{if(t){if(F){A(null);return}if(G){A(null);return}Ri.has(t)?A(t):j.current(`/api/terminal/session/${encodeURIComponent(t)}`).then(K=>K.ok?K.json():null).then(K=>{if(!Ri.has(t)){const he=(K==null?void 0:K.sessionId)&&!(K!=null&&K.running);T(t,{autoConnect:!he}),A(t)}}).catch(()=>{Ri.has(t)||(T(t),A(t))})}},[t,T,A,F,G]),w.useEffect(()=>{const K=setInterval(()=>{for(const[he,_e]of Ri)if(_e.connected)try{const Me=_e.serialize.serialize();sl(he,Me).catch(()=>{})}catch{}},3e4);return()=>clearInterval(K)},[]),w.useEffect(()=>()=>{for(const[K,he]of Ri){try{const _e=he.serialize.serialize();sl(K,_e).catch(()=>{})}catch{}he.observer.disconnect(),he.ws&&he.ws.close(),he.term.dispose(),he.container.remove(),j.current(`/api/terminal/${encodeURIComponent(K)}`,{method:"DELETE"}).catch(()=>{})}Ri.clear()},[]);const se=t?N.has(t):!1,le=D.length===0;return d.jsxs("div",{className:"h-full flex flex-col",children:[!le&&d.jsxs("div",{className:"px-2 py-1 border-b border-border flex items-center gap-1 overflow-x-auto",children:[D.map(K=>d.jsxs("div",{onClick:()=>s==null?void 0:s(K),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono cursor-pointer ${K===t?"bg-accent/10 text-accent":"text-muted hover:text-foreground"}`,children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${N.has(K)?"bg-amber-500":K===t?"bg-green-600":"bg-muted/50"}`}),d.jsx("span",{className:`truncate max-w-[120px] ${K.startsWith("_new_")?"italic":""}`,children:K.startsWith("_new_")?"Untitled":K}),d.jsx("button",{onClick:he=>{he.stopPropagation(),K.startsWith("_new_")?q(K):V(K)},className:"ml-0.5 text-muted hover:text-error text-[10px] leading-none",title:"Close terminal",children:"×"})]},K)),t!=null&&t.startsWith("_new_")?d.jsx("button",{onClick:()=>q(t),className:"ml-auto px-2 py-0.5 text-xs text-error hover:bg-surface rounded flex items-center gap-1 flex-shrink-0",children:"Cancel ×"}):t&&o&&(c!=null&&c.has(t))?d.jsx("button",{onClick:()=>ie(t),className:"ml-auto px-2 py-0.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded flex items-center gap-1 flex-shrink-0",children:"Archive"}):null]}),d.jsxs("div",{className:"relative flex-1 min-h-0",children:[d.jsx("div",{ref:S,className:"h-full"}),le&&!F&&!G&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a story on the left menu"}),d.jsx("p",{className:"text-sm mt-1",children:"to start an AI Writer session"})]})}),F&&d.jsx("div",{"data-testid":"cartoon-launch-blocked",className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Cartoon agent can't launch yet"}),d.jsx("p",{className:"text-xs text-muted",children:"This is a cartoon story. The writing agent needs Codex with image generation enabled before it can start, because the clean-image step relies on image generation support."}),_&&!_.codex.installed?d.jsxs("p",{className:"text-xs text-amber-700",children:["Codex was not detected. Install the Codex CLI and sign in (e.g. ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," then"," ",d.jsx("span",{className:"font-mono",children:"codex login"}),"), then reopen this story."]}):Eu(_)?d.jsxs("p",{className:"text-xs text-amber-700","data-testid":"codex-auth-unknown-launch",children:[Up," Then reopen this story."]}):d.jsxs("div",{className:"space-y-1",children:[d.jsx("p",{className:"text-xs text-amber-700",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this story:"}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx("code",{className:"flex-1 truncate rounded border border-border bg-surface px-1.5 py-1 text-left text-[10px] font-mono text-foreground",children:lv}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable-launch",onClick:async()=>{try{await navigator.clipboard.writeText(lv),be(!0),setTimeout(()=>be(!1),2e3)}catch{}},className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:fe?"Copied!":"Copy"})]})]})]})}),G&&!F&&d.jsx("div",{"data-testid":"legacy-cartoon-provider-repair",className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-md",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Set this cartoon story's provider"}),d.jsx("p",{className:"text-xs text-muted",children:"This cartoon story was created before provider tracking, so it has no provider recorded and would launch with Claude — which can't generate the clean images cartoons need. Set this story's provider to Codex to continue."}),d.jsx("p",{className:"text-[11px] text-muted",children:"Only this story is changed. Other stories and fiction are not affected."}),d.jsx("button",{type:"button","data-testid":"repair-provider-codex",disabled:B,onClick:async()=>{if(!B){ne(!0);try{await(v==null?void 0:v())}finally{ne(!1)}}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:B?"Setting…":"Set this story's provider to Codex"})]})}),te&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Discard this session?"}),d.jsx("p",{className:"text-xs text-muted",children:"This session will be lost — your AI hasn't created a story structure yet."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>q(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:()=>{const K=te;q(null),C(K)},className:"px-4 py-1.5 bg-error text-white text-sm rounded hover:opacity-80",children:"Discard"})]})]})}),R&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3 p-6 bg-surface border border-border rounded-lg shadow-lg max-w-sm",children:[d.jsx("p",{className:"text-sm font-serif text-foreground font-medium",children:"Archive this story?"}),d.jsx("p",{className:"text-xs text-muted",children:"You can restore it later from the Archives view."}),d.jsxs("div",{className:"flex items-center justify-center gap-2",children:[d.jsx("button",{onClick:()=>ie(null),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Cancel"}),d.jsx("button",{onClick:async()=>{const K=R;ie(null);try{(await j.current("/api/stories/archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:K})})).ok&&(V(K),o==null||o(K))}catch{}},className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Archive"})]})]})}),se&&t&&d.jsx("div",{className:"absolute inset-0 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("p",{className:"text-sm font-serif text-foreground",children:"Terminal disconnected"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>M(t,!0),className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim",children:"Resume Session"}),d.jsx("button",{onClick:()=>M(t,!1),className:"px-4 py-1.5 border border-border text-sm rounded hover:bg-surface",children:"Start Fresh"})]}),d.jsx("p",{className:"text-xs text-muted",children:"Resume continues your previous Claude conversation"})]})})]})]})}function sN(e,t){const i={};return(e[e.length-1]===""?[...e,""]:e).join((i.padRight?" ":"")+","+(i.padLeft===!1?"":" ")).trim()}const aN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,lN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,oN={};function cv(e,t){return(oN.jsx?lN:aN).test(e)}const cN=/[ \t\n\f\r]/g;function uN(e){return typeof e=="object"?e.type==="text"?uv(e.value):!1:uv(e)}function uv(e){return e.replace(cN,"")===""}class qo{constructor(t,i,s){this.normal=i,this.property=t,s&&(this.space=s)}}qo.prototype.normal={};qo.prototype.property={};qo.prototype.space=void 0;function k0(e,t){const i={},s={};for(const a of e)Object.assign(i,a.property),Object.assign(s,a.normal);return new qo(i,s,t)}function Cp(e){return e.toLowerCase()}class En{constructor(t,i){this.attribute=i,this.property=t}}En.prototype.attribute="";En.prototype.booleanish=!1;En.prototype.boolean=!1;En.prototype.commaOrSpaceSeparated=!1;En.prototype.commaSeparated=!1;En.prototype.defined=!1;En.prototype.mustUseProperty=!1;En.prototype.number=!1;En.prototype.overloadedBoolean=!1;En.prototype.property="";En.prototype.spaceSeparated=!1;En.prototype.space=void 0;let hN=0;const ot=va(),yi=va(),kp=va(),ve=va(),Yt=va(),hl=va(),In=va();function va(){return 2**++hN}const Ep=Object.freeze(Object.defineProperty({__proto__:null,boolean:ot,booleanish:yi,commaOrSpaceSeparated:In,commaSeparated:hl,number:ve,overloadedBoolean:kp,spaceSeparated:Yt},Symbol.toStringTag,{value:"Module"})),gf=Object.keys(Ep);class Jp extends En{constructor(t,i,s,a){let o=-1;if(super(t,i),hv(this,"space",a),typeof s=="number")for(;++o4&&i.slice(0,4)==="data"&&gN.test(t)){if(t.charAt(4)==="-"){const o=t.slice(5).replace(dv,bN);s="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=t.slice(4);if(!dv.test(o)){let c=o.replace(mN,_N);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}a=Jp}return new a(s,t)}function _N(e){return"-"+e.toLowerCase()}function bN(e){return e.charAt(1).toUpperCase()}const vN=k0([E0,dN,T0,A0,R0],"html"),em=k0([E0,fN,T0,A0,R0],"svg");function yN(e){return e.join(" ").trim()}var al={},xf,fv;function SN(){if(fv)return xf;fv=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,i=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,h=/^\s+|\s+$/g,p=` +`,f="/",_="*",x="",b="comment",v="declaration";function S(D,E){if(typeof D!="string")throw new TypeError("First argument must be a string");if(!D)return[];E=E||{};var N=1,I=1;function te(Y){var U=Y.match(t);U&&(N+=U.length);var A=Y.lastIndexOf(p);I=~A?Y.length-A:I+Y.length}function q(){var Y={line:N,column:I};return function(U){return U.position=new R(Y),be(),U}}function R(Y){this.start=Y,this.end={line:N,column:I},this.source=E.source}R.prototype.content=D;function ie(Y){var U=new Error(E.source+":"+N+":"+I+": "+Y);if(U.reason=Y,U.filename=E.source,U.line=N,U.column=I,U.source=D,!E.silent)throw U}function fe(Y){var U=Y.exec(D);if(U){var A=U[0];return te(A),D=D.slice(A.length),U}}function be(){fe(i)}function B(Y){var U;for(Y=Y||[];U=ne();)U!==!1&&Y.push(U);return Y}function ne(){var Y=q();if(!(f!=D.charAt(0)||_!=D.charAt(1))){for(var U=2;x!=D.charAt(U)&&(_!=D.charAt(U)||f!=D.charAt(U+1));)++U;if(U+=2,x===D.charAt(U-1))return ie("End of comment missing");var A=D.slice(2,U-2);return I+=2,te(A),D=D.slice(U),I+=2,Y({type:b,comment:A})}}function F(){var Y=q(),U=fe(s);if(U){if(ne(),!fe(a))return ie("property missing ':'");var A=fe(o),z=Y({type:v,property:j(U[0].replace(e,x)),value:A?j(A[0].replace(e,x)):x});return fe(c),z}}function G(){var Y=[];B(Y);for(var U;U=F();)U!==!1&&(Y.push(U),B(Y));return Y}return be(),G()}function j(D){return D?D.replace(h,x):x}return xf=S,xf}var pv;function wN(){if(pv)return al;pv=1;var e=al&&al.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(al,"__esModule",{value:!0}),al.default=i;const t=e(SN());function i(s,a){let o=null;if(!s||typeof s!="string")return o;const c=(0,t.default)(s),h=typeof a=="function";return c.forEach(p=>{if(p.type!=="declaration")return;const{property:f,value:_}=p;h?a(f,_,p):_&&(o=o||{},o[f]=_)}),o}return al}var go={},mv;function CN(){if(mv)return go;mv=1,Object.defineProperty(go,"__esModule",{value:!0}),go.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,i=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(f){return!f||i.test(f)||e.test(f)},c=function(f,_){return _.toUpperCase()},h=function(f,_){return"".concat(_,"-")},p=function(f,_){return _===void 0&&(_={}),o(f)?f:(f=f.toLowerCase(),_.reactCompat?f=f.replace(a,h):f=f.replace(s,h),f.replace(t,c))};return go.camelCase=p,go}var xo,gv;function kN(){if(gv)return xo;gv=1;var e=xo&&xo.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(wN()),i=CN();function s(a,o){var c={};return!a||typeof a!="string"||(0,t.default)(a,function(h,p){h&&p&&(c[(0,i.camelCase)(h,o)]=p)}),c}return s.default=s,xo=s,xo}var EN=kN();const NN=Pu(EN),D0=M0("end"),tm=M0("start");function M0(e){return t;function t(i){const s=i&&i.position&&i.position[e]||{};if(typeof s.line=="number"&&s.line>0&&typeof s.column=="number"&&s.column>0)return{line:s.line,column:s.column,offset:typeof s.offset=="number"&&s.offset>-1?s.offset:void 0}}}function B0(e){const t=tm(e),i=D0(e);if(t&&i)return{start:t,end:i}}function To(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?xv(e.position):"start"in e||"end"in e?xv(e):"line"in e||"column"in e?Np(e):""}function Np(e){return _v(e&&e.line)+":"+_v(e&&e.column)}function xv(e){return Np(e&&e.start)+"-"+Np(e&&e.end)}function _v(e){return e&&typeof e=="number"?e:1}class an extends Error{constructor(t,i,s){super(),typeof i=="string"&&(s=i,i=void 0);let a="",o={},c=!1;if(i&&("line"in i&&"column"in i?o={place:i}:"start"in i&&"end"in i?o={place:i}:"type"in i?o={ancestors:[i],place:i.position}:o={...i}),typeof t=="string"?a=t:!o.cause&&t&&(c=!0,a=t.message,o.cause=t),!o.ruleId&&!o.source&&typeof s=="string"){const p=s.indexOf(":");p===-1?o.ruleId=s:(o.source=s.slice(0,p),o.ruleId=s.slice(p+1))}if(!o.place&&o.ancestors&&o.ancestors){const p=o.ancestors[o.ancestors.length-1];p&&(o.place=p.position)}const h=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=h?h.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=h?h.line:void 0,this.name=To(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=c&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}an.prototype.file="";an.prototype.name="";an.prototype.reason="";an.prototype.message="";an.prototype.stack="";an.prototype.column=void 0;an.prototype.line=void 0;an.prototype.ancestors=void 0;an.prototype.cause=void 0;an.prototype.fatal=void 0;an.prototype.place=void 0;an.prototype.ruleId=void 0;an.prototype.source=void 0;const im={}.hasOwnProperty,jN=new Map,TN=/[A-Z]/g,AN=new Set(["table","tbody","thead","tfoot","tr"]),RN=new Set(["td","th"]),L0="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function DN(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const i=t.filePath||void 0;let s;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");s=HN(i,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");s=IN(i,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:s,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:i,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?em:vN,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},o=O0(a,e,void 0);return o&&typeof o!="string"?o:a.create(e,a.Fragment,{children:o||void 0},void 0)}function O0(e,t,i){if(t.type==="element")return MN(e,t,i);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return BN(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return ON(e,t,i);if(t.type==="mdxjsEsm")return LN(e,t);if(t.type==="root")return zN(e,t,i);if(t.type==="text")return PN(e,t)}function MN(e,t,i){const s=e.schema;let a=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(a=em,e.schema=a),e.ancestors.push(t);const o=P0(e,t.tagName,!1),c=UN(e,t);let h=rm(e,t);return AN.has(t.tagName)&&(h=h.filter(function(p){return typeof p=="string"?!uN(p):!0})),z0(e,c,o,t),nm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function BN(e,t){if(t.data&&t.data.estree&&e.evaluater){const s=t.data.estree.body[0];return s.type,e.evaluater.evaluateExpression(s.expression)}Oo(e,t.position)}function LN(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Oo(e,t.position)}function ON(e,t,i){const s=e.schema;let a=s;t.name==="svg"&&s.space==="html"&&(a=em,e.schema=a),e.ancestors.push(t);const o=t.name===null?e.Fragment:P0(e,t.name,!0),c=$N(e,t),h=rm(e,t);return z0(e,c,o,t),nm(c,h),e.ancestors.pop(),e.schema=s,e.create(t,o,c,i)}function zN(e,t,i){const s={};return nm(s,rm(e,t)),e.create(t,e.Fragment,s,i)}function PN(e,t){return t.value}function z0(e,t,i,s){typeof i!="string"&&i!==e.Fragment&&e.passNode&&(t.node=s)}function nm(e,t){if(t.length>0){const i=t.length>1?t:t[0];i&&(e.children=i)}}function IN(e,t,i){return s;function s(a,o,c,h){const f=Array.isArray(c.children)?i:t;return h?f(o,c,h):f(o,c)}}function HN(e,t){return i;function i(s,a,o,c){const h=Array.isArray(o.children),p=tm(s);return t(a,o,c,h,{columnNumber:p?p.column-1:void 0,fileName:e,lineNumber:p?p.line:void 0},void 0)}}function UN(e,t){const i={};let s,a;for(a in t.properties)if(a!=="children"&&im.call(t.properties,a)){const o=FN(e,a,t.properties[a]);if(o){const[c,h]=o;e.tableCellAlignToStyle&&c==="align"&&typeof h=="string"&&RN.has(t.tagName)?s=h:i[c]=h}}if(s){const o=i.style||(i.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=s}return i}function $N(e,t){const i={};for(const s of t.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&e.evaluater){const o=s.data.estree.body[0];o.type;const c=o.expression;c.type;const h=c.properties[0];h.type,Object.assign(i,e.evaluater.evaluateExpression(h.argument))}else Oo(e,t.position);else{const a=s.name;let o;if(s.value&&typeof s.value=="object")if(s.value.data&&s.value.data.estree&&e.evaluater){const h=s.value.data.estree.body[0];h.type,o=e.evaluater.evaluateExpression(h.expression)}else Oo(e,t.position);else o=s.value===null?!0:s.value;i[a]=o}return i}function rm(e,t){const i=[];let s=-1;const a=e.passKeys?new Map:jN;for(;++sa?0:a+t:t=t>a?a:t,i=i>0?i:0,s.length<1e4)c=Array.from(s),c.unshift(t,i),e.splice(...c);else for(i&&e.splice(t,i);o0?(Hn(e,e.length,0,t),e):t}const yv={}.hasOwnProperty;function H0(e){const t={};let i=-1;for(;++i13&&i<32||i>126&&i<160||i>55295&&i<57344||i>64975&&i<65008||(i&65535)===65535||(i&65535)===65534||i>1114111?"�":String.fromCodePoint(i)}function fr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const pn=$s(/[A-Za-z]/),sn=$s(/[\dA-Za-z]/),QN=$s(/[#-'*+\--9=?A-Z^-~]/);function Mu(e){return e!==null&&(e<32||e===127)}const jp=$s(/\d/),JN=$s(/[\dA-Fa-f]/),e5=$s(/[!-/:-@[-`{-~]/);function Ye(e){return e!==null&&e<-2}function qt(e){return e!==null&&(e<0||e===32)}function xt(e){return e===-2||e===-1||e===32}const Fu=$s(new RegExp("\\p{P}|\\p{S}","u")),_a=$s(/\s/);function $s(e){return t;function t(i){return i!==null&&i>-1&&e.test(String.fromCharCode(i))}}function vl(e){const t=[];let i=-1,s=0,a=0;for(;++i55295&&o<57344){const h=e.charCodeAt(i+1);o<56320&&h>56319&&h<57344?(c=String.fromCharCode(o,h),a=1):c="�"}else c=String.fromCharCode(o);c&&(t.push(e.slice(s,i),encodeURIComponent(c)),s=i+a+1,c=""),a&&(i+=a,a=0)}return t.join("")+e.slice(s)}function kt(e,t,i,s){const a=s?s-1:Number.POSITIVE_INFINITY;let o=0;return c;function c(p){return xt(p)?(e.enter(i),h(p)):t(p)}function h(p){return xt(p)&&o++c))return;const ie=t.events.length;let fe=ie,be,B;for(;fe--;)if(t.events[fe][0]==="exit"&&t.events[fe][1].type==="chunkFlow"){if(be){B=t.events[fe][1].end;break}be=!0}for(E(s),R=ie;RI;){const q=i[te];t.containerState=q[1],q[0].exit.call(t,e)}i.length=I}function N(){a.write([null]),o=void 0,a=void 0,t.containerState._closeFlow=void 0}}function s5(e,t,i){return kt(e,e.attempt(this.parser.constructs.document,t,i),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ml(e){if(e===null||qt(e)||_a(e))return 1;if(Fu(e))return 2}function qu(e,t,i){const s=[];let a=-1;for(;++a1&&e[i][1].end.offset-e[i][1].start.offset>1?2:1;const x={...e[s][1].end},b={...e[i][1].start};wv(x,-p),wv(b,p),c={type:p>1?"strongSequence":"emphasisSequence",start:x,end:{...e[s][1].end}},h={type:p>1?"strongSequence":"emphasisSequence",start:{...e[i][1].start},end:b},o={type:p>1?"strongText":"emphasisText",start:{...e[s][1].end},end:{...e[i][1].start}},a={type:p>1?"strong":"emphasis",start:{...c.start},end:{...h.end}},e[s][1].end={...c.start},e[i][1].start={...h.end},f=[],e[s][1].end.offset-e[s][1].start.offset&&(f=rr(f,[["enter",e[s][1],t],["exit",e[s][1],t]])),f=rr(f,[["enter",a,t],["enter",c,t],["exit",c,t],["enter",o,t]]),f=rr(f,qu(t.parser.constructs.insideSpan.null,e.slice(s+1,i),t)),f=rr(f,[["exit",o,t],["enter",h,t],["exit",h,t],["exit",a,t]]),e[i][1].end.offset-e[i][1].start.offset?(_=2,f=rr(f,[["enter",e[i][1],t],["exit",e[i][1],t]])):_=0,Hn(e,s-1,i-s+3,f),i=s+f.length-_-2;break}}for(i=-1;++i0&&xt(R)?kt(e,N,"linePrefix",o+1)(R):N(R)}function N(R){return R===null||Ye(R)?e.check(Cv,j,te)(R):(e.enter("codeFlowValue"),I(R))}function I(R){return R===null||Ye(R)?(e.exit("codeFlowValue"),N(R)):(e.consume(R),I)}function te(R){return e.exit("codeFenced"),t(R)}function q(R,ie,fe){let be=0;return B;function B(U){return R.enter("lineEnding"),R.consume(U),R.exit("lineEnding"),ne}function ne(U){return R.enter("codeFencedFence"),xt(U)?kt(R,F,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(U):F(U)}function F(U){return U===h?(R.enter("codeFencedFenceSequence"),G(U)):fe(U)}function G(U){return U===h?(be++,R.consume(U),G):be>=c?(R.exit("codeFencedFenceSequence"),xt(U)?kt(R,Y,"whitespace")(U):Y(U)):fe(U)}function Y(U){return U===null||Ye(U)?(R.exit("codeFencedFence"),ie(U)):fe(U)}}}function x5(e,t,i){const s=this;return a;function a(c){return c===null?i(c):(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o)}function o(c){return s.parser.lazy[s.now().line]?i(c):t(c)}}const bf={name:"codeIndented",tokenize:b5},_5={partial:!0,tokenize:v5};function b5(e,t,i){const s=this;return a;function a(f){return e.enter("codeIndented"),kt(e,o,"linePrefix",5)(f)}function o(f){const _=s.events[s.events.length-1];return _&&_[1].type==="linePrefix"&&_[2].sliceSerialize(_[1],!0).length>=4?c(f):i(f)}function c(f){return f===null?p(f):Ye(f)?e.attempt(_5,c,p)(f):(e.enter("codeFlowValue"),h(f))}function h(f){return f===null||Ye(f)?(e.exit("codeFlowValue"),c(f)):(e.consume(f),h)}function p(f){return e.exit("codeIndented"),t(f)}}function v5(e,t,i){const s=this;return a;function a(c){return s.parser.lazy[s.now().line]?i(c):Ye(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),a):kt(e,o,"linePrefix",5)(c)}function o(c){const h=s.events[s.events.length-1];return h&&h[1].type==="linePrefix"&&h[2].sliceSerialize(h[1],!0).length>=4?t(c):Ye(c)?a(c):i(c)}}const y5={name:"codeText",previous:w5,resolve:S5,tokenize:C5};function S5(e){let t=e.length-4,i=3,s,a;if((e[i][1].type==="lineEnding"||e[i][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(s=i;++s=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-s+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-s+this.left.length).reverse())}splice(t,i,s){const a=i||0;this.setCursor(Math.trunc(t));const o=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return s&&_o(this.left,s),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),_o(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),_o(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(c):e.interrupt(s.parser.constructs.flow,i,t)(c)}}function G0(e,t,i,s,a,o,c,h,p){const f=p||Number.POSITIVE_INFINITY;let _=0;return x;function x(E){return E===60?(e.enter(s),e.enter(a),e.enter(o),e.consume(E),e.exit(o),b):E===null||E===32||E===41||Mu(E)?i(E):(e.enter(s),e.enter(c),e.enter(h),e.enter("chunkString",{contentType:"string"}),j(E))}function b(E){return E===62?(e.enter(o),e.consume(E),e.exit(o),e.exit(a),e.exit(s),t):(e.enter(h),e.enter("chunkString",{contentType:"string"}),v(E))}function v(E){return E===62?(e.exit("chunkString"),e.exit(h),b(E)):E===null||E===60||Ye(E)?i(E):(e.consume(E),E===92?S:v)}function S(E){return E===60||E===62||E===92?(e.consume(E),v):v(E)}function j(E){return!_&&(E===null||E===41||qt(E))?(e.exit("chunkString"),e.exit(h),e.exit(c),e.exit(s),t(E)):_999||v===null||v===91||v===93&&!p||v===94&&!h&&"_hiddenFootnoteSupport"in c.parser.constructs?i(v):v===93?(e.exit(o),e.enter(a),e.consume(v),e.exit(a),e.exit(s),t):Ye(v)?(e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),_):(e.enter("chunkString",{contentType:"string"}),x(v))}function x(v){return v===null||v===91||v===93||Ye(v)||h++>999?(e.exit("chunkString"),_(v)):(e.consume(v),p||(p=!xt(v)),v===92?b:x)}function b(v){return v===91||v===92||v===93?(e.consume(v),h++,x):x(v)}}function K0(e,t,i,s,a,o){let c;return h;function h(b){return b===34||b===39||b===40?(e.enter(s),e.enter(a),e.consume(b),e.exit(a),c=b===40?41:b,p):i(b)}function p(b){return b===c?(e.enter(a),e.consume(b),e.exit(a),e.exit(s),t):(e.enter(o),f(b))}function f(b){return b===c?(e.exit(o),p(c)):b===null?i(b):Ye(b)?(e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),kt(e,f,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),_(b))}function _(b){return b===c||b===null||Ye(b)?(e.exit("chunkString"),f(b)):(e.consume(b),b===92?x:_)}function x(b){return b===c||b===92?(e.consume(b),_):_(b)}}function Ao(e,t){let i;return s;function s(a){return Ye(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i=!0,s):xt(a)?kt(e,s,i?"linePrefix":"lineSuffix")(a):t(a)}}const D5={name:"definition",tokenize:B5},M5={partial:!0,tokenize:L5};function B5(e,t,i){const s=this;let a;return o;function o(v){return e.enter("definition"),c(v)}function c(v){return Y0.call(s,e,h,i,"definitionLabel","definitionLabelMarker","definitionLabelString")(v)}function h(v){return a=fr(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),v===58?(e.enter("definitionMarker"),e.consume(v),e.exit("definitionMarker"),p):i(v)}function p(v){return qt(v)?Ao(e,f)(v):f(v)}function f(v){return G0(e,_,i,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(v)}function _(v){return e.attempt(M5,x,x)(v)}function x(v){return xt(v)?kt(e,b,"whitespace")(v):b(v)}function b(v){return v===null||Ye(v)?(e.exit("definition"),s.parser.defined.push(a),t(v)):i(v)}}function L5(e,t,i){return s;function s(h){return qt(h)?Ao(e,a)(h):i(h)}function a(h){return K0(e,o,i,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function o(h){return xt(h)?kt(e,c,"whitespace")(h):c(h)}function c(h){return h===null||Ye(h)?t(h):i(h)}}const O5={name:"hardBreakEscape",tokenize:z5};function z5(e,t,i){return s;function s(o){return e.enter("hardBreakEscape"),e.consume(o),a}function a(o){return Ye(o)?(e.exit("hardBreakEscape"),t(o)):i(o)}}const P5={name:"headingAtx",resolve:I5,tokenize:H5};function I5(e,t){let i=e.length-2,s=3,a,o;return e[s][1].type==="whitespace"&&(s+=2),i-2>s&&e[i][1].type==="whitespace"&&(i-=2),e[i][1].type==="atxHeadingSequence"&&(s===i-1||i-4>s&&e[i-2][1].type==="whitespace")&&(i-=s+1===i?2:4),i>s&&(a={type:"atxHeadingText",start:e[s][1].start,end:e[i][1].end},o={type:"chunkText",start:e[s][1].start,end:e[i][1].end,contentType:"text"},Hn(e,s,i-s+1,[["enter",a,t],["enter",o,t],["exit",o,t],["exit",a,t]])),e}function H5(e,t,i){let s=0;return a;function a(_){return e.enter("atxHeading"),o(_)}function o(_){return e.enter("atxHeadingSequence"),c(_)}function c(_){return _===35&&s++<6?(e.consume(_),c):_===null||qt(_)?(e.exit("atxHeadingSequence"),h(_)):i(_)}function h(_){return _===35?(e.enter("atxHeadingSequence"),p(_)):_===null||Ye(_)?(e.exit("atxHeading"),t(_)):xt(_)?kt(e,h,"whitespace")(_):(e.enter("atxHeadingText"),f(_))}function p(_){return _===35?(e.consume(_),p):(e.exit("atxHeadingSequence"),h(_))}function f(_){return _===null||_===35||qt(_)?(e.exit("atxHeadingText"),h(_)):(e.consume(_),f)}}const U5=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Ev=["pre","script","style","textarea"],$5={concrete:!0,name:"htmlFlow",resolveTo:W5,tokenize:G5},F5={partial:!0,tokenize:K5},q5={partial:!0,tokenize:Y5};function W5(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function G5(e,t,i){const s=this;let a,o,c,h,p;return f;function f(C){return _(C)}function _(C){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(C),x}function x(C){return C===33?(e.consume(C),b):C===47?(e.consume(C),o=!0,j):C===63?(e.consume(C),a=3,s.interrupt?t:T):pn(C)?(e.consume(C),c=String.fromCharCode(C),D):i(C)}function b(C){return C===45?(e.consume(C),a=2,v):C===91?(e.consume(C),a=5,h=0,S):pn(C)?(e.consume(C),a=4,s.interrupt?t:T):i(C)}function v(C){return C===45?(e.consume(C),s.interrupt?t:T):i(C)}function S(C){const X="CDATA[";return C===X.charCodeAt(h++)?(e.consume(C),h===X.length?s.interrupt?t:F:S):i(C)}function j(C){return pn(C)?(e.consume(C),c=String.fromCharCode(C),D):i(C)}function D(C){if(C===null||C===47||C===62||qt(C)){const X=C===47,se=c.toLowerCase();return!X&&!o&&Ev.includes(se)?(a=1,s.interrupt?t(C):F(C)):U5.includes(c.toLowerCase())?(a=6,X?(e.consume(C),E):s.interrupt?t(C):F(C)):(a=7,s.interrupt&&!s.parser.lazy[s.now().line]?i(C):o?N(C):I(C))}return C===45||sn(C)?(e.consume(C),c+=String.fromCharCode(C),D):i(C)}function E(C){return C===62?(e.consume(C),s.interrupt?t:F):i(C)}function N(C){return xt(C)?(e.consume(C),N):B(C)}function I(C){return C===47?(e.consume(C),B):C===58||C===95||pn(C)?(e.consume(C),te):xt(C)?(e.consume(C),I):B(C)}function te(C){return C===45||C===46||C===58||C===95||sn(C)?(e.consume(C),te):q(C)}function q(C){return C===61?(e.consume(C),R):xt(C)?(e.consume(C),q):I(C)}function R(C){return C===null||C===60||C===61||C===62||C===96?i(C):C===34||C===39?(e.consume(C),p=C,ie):xt(C)?(e.consume(C),R):fe(C)}function ie(C){return C===p?(e.consume(C),p=null,be):C===null||Ye(C)?i(C):(e.consume(C),ie)}function fe(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||qt(C)?q(C):(e.consume(C),fe)}function be(C){return C===47||C===62||xt(C)?I(C):i(C)}function B(C){return C===62?(e.consume(C),ne):i(C)}function ne(C){return C===null||Ye(C)?F(C):xt(C)?(e.consume(C),ne):i(C)}function F(C){return C===45&&a===2?(e.consume(C),A):C===60&&a===1?(e.consume(C),z):C===62&&a===4?(e.consume(C),M):C===63&&a===3?(e.consume(C),T):C===93&&a===5?(e.consume(C),ge):Ye(C)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(F5,V,G)(C)):C===null||Ye(C)?(e.exit("htmlFlowData"),G(C)):(e.consume(C),F)}function G(C){return e.check(q5,Y,V)(C)}function Y(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),U}function U(C){return C===null||Ye(C)?G(C):(e.enter("htmlFlowData"),F(C))}function A(C){return C===45?(e.consume(C),T):F(C)}function z(C){return C===47?(e.consume(C),c="",$):F(C)}function $(C){if(C===62){const X=c.toLowerCase();return Ev.includes(X)?(e.consume(C),M):F(C)}return pn(C)&&c.length<8?(e.consume(C),c+=String.fromCharCode(C),$):F(C)}function ge(C){return C===93?(e.consume(C),T):F(C)}function T(C){return C===62?(e.consume(C),M):C===45&&a===2?(e.consume(C),T):F(C)}function M(C){return C===null||Ye(C)?(e.exit("htmlFlowData"),V(C)):(e.consume(C),M)}function V(C){return e.exit("htmlFlow"),t(C)}}function Y5(e,t,i){const s=this;return a;function a(c){return Ye(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),o):i(c)}function o(c){return s.parser.lazy[s.now().line]?i(c):t(c)}}function K5(e,t,i){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(Wo,t,i)}}const V5={name:"htmlText",tokenize:X5};function X5(e,t,i){const s=this;let a,o,c;return h;function h(T){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(T),p}function p(T){return T===33?(e.consume(T),f):T===47?(e.consume(T),q):T===63?(e.consume(T),I):pn(T)?(e.consume(T),fe):i(T)}function f(T){return T===45?(e.consume(T),_):T===91?(e.consume(T),o=0,S):pn(T)?(e.consume(T),N):i(T)}function _(T){return T===45?(e.consume(T),v):i(T)}function x(T){return T===null?i(T):T===45?(e.consume(T),b):Ye(T)?(c=x,z(T)):(e.consume(T),x)}function b(T){return T===45?(e.consume(T),v):x(T)}function v(T){return T===62?A(T):T===45?b(T):x(T)}function S(T){const M="CDATA[";return T===M.charCodeAt(o++)?(e.consume(T),o===M.length?j:S):i(T)}function j(T){return T===null?i(T):T===93?(e.consume(T),D):Ye(T)?(c=j,z(T)):(e.consume(T),j)}function D(T){return T===93?(e.consume(T),E):j(T)}function E(T){return T===62?A(T):T===93?(e.consume(T),E):j(T)}function N(T){return T===null||T===62?A(T):Ye(T)?(c=N,z(T)):(e.consume(T),N)}function I(T){return T===null?i(T):T===63?(e.consume(T),te):Ye(T)?(c=I,z(T)):(e.consume(T),I)}function te(T){return T===62?A(T):I(T)}function q(T){return pn(T)?(e.consume(T),R):i(T)}function R(T){return T===45||sn(T)?(e.consume(T),R):ie(T)}function ie(T){return Ye(T)?(c=ie,z(T)):xt(T)?(e.consume(T),ie):A(T)}function fe(T){return T===45||sn(T)?(e.consume(T),fe):T===47||T===62||qt(T)?be(T):i(T)}function be(T){return T===47?(e.consume(T),A):T===58||T===95||pn(T)?(e.consume(T),B):Ye(T)?(c=be,z(T)):xt(T)?(e.consume(T),be):A(T)}function B(T){return T===45||T===46||T===58||T===95||sn(T)?(e.consume(T),B):ne(T)}function ne(T){return T===61?(e.consume(T),F):Ye(T)?(c=ne,z(T)):xt(T)?(e.consume(T),ne):be(T)}function F(T){return T===null||T===60||T===61||T===62||T===96?i(T):T===34||T===39?(e.consume(T),a=T,G):Ye(T)?(c=F,z(T)):xt(T)?(e.consume(T),F):(e.consume(T),Y)}function G(T){return T===a?(e.consume(T),a=void 0,U):T===null?i(T):Ye(T)?(c=G,z(T)):(e.consume(T),G)}function Y(T){return T===null||T===34||T===39||T===60||T===61||T===96?i(T):T===47||T===62||qt(T)?be(T):(e.consume(T),Y)}function U(T){return T===47||T===62||qt(T)?be(T):i(T)}function A(T){return T===62?(e.consume(T),e.exit("htmlTextData"),e.exit("htmlText"),t):i(T)}function z(T){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),$}function $(T){return xt(T)?kt(e,ge,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):ge(T)}function ge(T){return e.enter("htmlTextData"),c(T)}}const lm={name:"labelEnd",resolveAll:ej,resolveTo:tj,tokenize:ij},Z5={tokenize:nj},Q5={tokenize:rj},J5={tokenize:sj};function ej(e){let t=-1;const i=[];for(;++t=3&&(f===null||Ye(f))?(e.exit("thematicBreak"),t(f)):i(f)}function p(f){return f===a?(e.consume(f),s++,p):(e.exit("thematicBreakSequence"),xt(f)?kt(e,h,"whitespace")(f):h(f))}}const kn={continuation:{tokenize:mj},exit:xj,name:"list",tokenize:pj},dj={partial:!0,tokenize:_j},fj={partial:!0,tokenize:gj};function pj(e,t,i){const s=this,a=s.events[s.events.length-1];let o=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,c=0;return h;function h(v){const S=s.containerState.type||(v===42||v===43||v===45?"listUnordered":"listOrdered");if(S==="listUnordered"?!s.containerState.marker||v===s.containerState.marker:jp(v)){if(s.containerState.type||(s.containerState.type=S,e.enter(S,{_container:!0})),S==="listUnordered")return e.enter("listItemPrefix"),v===42||v===45?e.check(wu,i,f)(v):f(v);if(!s.interrupt||v===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),p(v)}return i(v)}function p(v){return jp(v)&&++c<10?(e.consume(v),p):(!s.interrupt||c<2)&&(s.containerState.marker?v===s.containerState.marker:v===41||v===46)?(e.exit("listItemValue"),f(v)):i(v)}function f(v){return e.enter("listItemMarker"),e.consume(v),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||v,e.check(Wo,s.interrupt?i:_,e.attempt(dj,b,x))}function _(v){return s.containerState.initialBlankLine=!0,o++,b(v)}function x(v){return xt(v)?(e.enter("listItemPrefixWhitespace"),e.consume(v),e.exit("listItemPrefixWhitespace"),b):i(v)}function b(v){return s.containerState.size=o+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(v)}}function mj(e,t,i){const s=this;return s.containerState._closeFlow=void 0,e.check(Wo,a,o);function a(h){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,kt(e,t,"listItemIndent",s.containerState.size+1)(h)}function o(h){return s.containerState.furtherBlankLines||!xt(h)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,c(h)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(fj,t,c)(h))}function c(h){return s.containerState._closeFlow=!0,s.interrupt=void 0,kt(e,e.attempt(kn,t,i),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function gj(e,t,i){const s=this;return kt(e,a,"listItemIndent",s.containerState.size+1);function a(o){const c=s.events[s.events.length-1];return c&&c[1].type==="listItemIndent"&&c[2].sliceSerialize(c[1],!0).length===s.containerState.size?t(o):i(o)}}function xj(e){e.exit(this.containerState.type)}function _j(e,t,i){const s=this;return kt(e,a,"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(o){const c=s.events[s.events.length-1];return!xt(o)&&c&&c[1].type==="listItemPrefixWhitespace"?t(o):i(o)}}const Nv={name:"setextUnderline",resolveTo:bj,tokenize:vj};function bj(e,t){let i=e.length,s,a,o;for(;i--;)if(e[i][0]==="enter"){if(e[i][1].type==="content"){s=i;break}e[i][1].type==="paragraph"&&(a=i)}else e[i][1].type==="content"&&e.splice(i,1),!o&&e[i][1].type==="definition"&&(o=i);const c={type:"setextHeading",start:{...e[s][1].start},end:{...e[e.length-1][1].end}};return e[a][1].type="setextHeadingText",o?(e.splice(a,0,["enter",c,t]),e.splice(o+1,0,["exit",e[s][1],t]),e[s][1].end={...e[o][1].end}):e[s][1]=c,e.push(["exit",c,t]),e}function vj(e,t,i){const s=this;let a;return o;function o(f){let _=s.events.length,x;for(;_--;)if(s.events[_][1].type!=="lineEnding"&&s.events[_][1].type!=="linePrefix"&&s.events[_][1].type!=="content"){x=s.events[_][1].type==="paragraph";break}return!s.parser.lazy[s.now().line]&&(s.interrupt||x)?(e.enter("setextHeadingLine"),a=f,c(f)):i(f)}function c(f){return e.enter("setextHeadingLineSequence"),h(f)}function h(f){return f===a?(e.consume(f),h):(e.exit("setextHeadingLineSequence"),xt(f)?kt(e,p,"lineSuffix")(f):p(f))}function p(f){return f===null||Ye(f)?(e.exit("setextHeadingLine"),t(f)):i(f)}}const yj={tokenize:Sj};function Sj(e){const t=this,i=e.attempt(Wo,s,e.attempt(this.parser.constructs.flowInitial,a,kt(e,e.attempt(this.parser.constructs.flow,a,e.attempt(N5,a)),"linePrefix")));return i;function s(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),t.currentConstruct=void 0,i}function a(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),t.currentConstruct=void 0,i}}const wj={resolveAll:X0()},Cj=V0("string"),kj=V0("text");function V0(e){return{resolveAll:X0(e==="text"?Ej:void 0),tokenize:t};function t(i){const s=this,a=this.parser.constructs[e],o=i.attempt(a,c,h);return c;function c(_){return f(_)?o(_):h(_)}function h(_){if(_===null){i.consume(_);return}return i.enter("data"),i.consume(_),p}function p(_){return f(_)?(i.exit("data"),o(_)):(i.consume(_),p)}function f(_){if(_===null)return!0;const x=a[_];let b=-1;if(x)for(;++b-1){const h=c[0];typeof h=="string"?c[0]=h.slice(s):c.shift()}o>0&&c.push(e[a].slice(0,o))}return c}function Ij(e,t){let i=-1;const s=[];let a;for(;++i0){const Wt=Te.tokenStack[Te.tokenStack.length-1];(Wt[1]||Nv).call(Te,void 0,Wt[0])}for(ge.position={start:Os(Q.length>0?Q[0][1].start:{line:1,column:1,offset:0}),end:Os(Q.length>0?Q[Q.length-2][1].end:{line:1,column:1,offset:0})},it=-1;++it0&&(s.className=["language-"+a[0]]);let o={type:"element",tagName:"code",properties:s,children:[{type:"text",value:i}]};return t.meta&&(o.data={meta:t.meta}),e.patch(t,o),o=e.applyData(t,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(t,o),o}function Gj(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function Yj(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function Kj(e,t){const i=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),a=vl(s.toLowerCase()),o=e.footnoteOrder.indexOf(s);let c,h=e.footnoteCounts.get(s);h===void 0?(h=0,e.footnoteOrder.push(s),c=e.footnoteOrder.length):c=o+1,h+=1,e.footnoteCounts.set(s,h);const p={type:"element",tagName:"a",properties:{href:"#"+i+"fn-"+a,id:i+"fnref-"+a+(h>1?"-"+h:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(c)}]};e.patch(t,p);const f={type:"element",tagName:"sup",properties:{},children:[p]};return e.patch(t,f),e.applyData(t,f)}function Vj(e,t){const i={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function Xj(e,t){if(e.options.allowDangerousHtml){const i={type:"raw",value:t.value};return e.patch(t,i),e.applyData(t,i)}}function X0(e,t){const i=t.referenceType;let s="]";if(i==="collapsed"?s+="[]":i==="full"&&(s+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+s}];const a=e.all(t),o=a[0];o&&o.type==="text"?o.value="["+o.value:a.unshift({type:"text",value:"["});const c=a[a.length-1];return c&&c.type==="text"?c.value+=s:a.push({type:"text",value:s}),a}function Zj(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return X0(e,t);const a={src:vl(s.url||""),alt:t.alt};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,o),e.applyData(t,o)}function Qj(e,t){const i={src:vl(t.url)};t.alt!==null&&t.alt!==void 0&&(i.alt=t.alt),t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"img",properties:i,children:[]};return e.patch(t,s),e.applyData(t,s)}function Jj(e,t){const i={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,i);const s={type:"element",tagName:"code",properties:{},children:[i]};return e.patch(t,s),e.applyData(t,s)}function eT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return X0(e,t);const a={href:vl(s.url||"")};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,o),e.applyData(t,o)}function tT(e,t){const i={href:vl(t.url)};t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"a",properties:i,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function iT(e,t,i){const s=e.all(t),a=i?nT(i):Z0(t),o={},c=[];if(typeof t.checked=="boolean"){const _=s[0];let x;_&&_.type==="element"&&_.tagName==="p"?x=_:(x={type:"element",tagName:"p",properties:{},children:[]},s.unshift(x)),x.children.length>0&&x.children.unshift({type:"text",value:" "}),x.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let h=-1;for(;++h0){const Wt=je.tokenStack[je.tokenStack.length-1];(Wt[1]||Tv).call(je,void 0,Wt[0])}for(xe.position={start:Os(Q.length>0?Q[0][1].start:{line:1,column:1,offset:0}),end:Os(Q.length>0?Q[Q.length-2][1].end:{line:1,column:1,offset:0})},nt=-1;++nt0&&(s.className=["language-"+a[0]]);let o={type:"element",tagName:"code",properties:s,children:[{type:"text",value:i}]};return t.meta&&(o.data={meta:t.meta}),e.patch(t,o),o=e.applyData(t,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(t,o),o}function Jj(e,t){const i={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function eT(e,t){const i={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function tT(e,t){const i=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),a=vl(s.toLowerCase()),o=e.footnoteOrder.indexOf(s);let c,h=e.footnoteCounts.get(s);h===void 0?(h=0,e.footnoteOrder.push(s),c=e.footnoteOrder.length):c=o+1,h+=1,e.footnoteCounts.set(s,h);const p={type:"element",tagName:"a",properties:{href:"#"+i+"fn-"+a,id:i+"fnref-"+a+(h>1?"-"+h:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(c)}]};e.patch(t,p);const f={type:"element",tagName:"sup",properties:{},children:[p]};return e.patch(t,f),e.applyData(t,f)}function iT(e,t){const i={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function nT(e,t){if(e.options.allowDangerousHtml){const i={type:"raw",value:t.value};return e.patch(t,i),e.applyData(t,i)}}function J0(e,t){const i=t.referenceType;let s="]";if(i==="collapsed"?s+="[]":i==="full"&&(s+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+s}];const a=e.all(t),o=a[0];o&&o.type==="text"?o.value="["+o.value:a.unshift({type:"text",value:"["});const c=a[a.length-1];return c&&c.type==="text"?c.value+=s:a.push({type:"text",value:s}),a}function rT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return J0(e,t);const a={src:vl(s.url||""),alt:t.alt};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,o),e.applyData(t,o)}function sT(e,t){const i={src:vl(t.url)};t.alt!==null&&t.alt!==void 0&&(i.alt=t.alt),t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"img",properties:i,children:[]};return e.patch(t,s),e.applyData(t,s)}function aT(e,t){const i={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,i);const s={type:"element",tagName:"code",properties:{},children:[i]};return e.patch(t,s),e.applyData(t,s)}function lT(e,t){const i=String(t.identifier).toUpperCase(),s=e.definitionById.get(i);if(!s)return J0(e,t);const a={href:vl(s.url||"")};s.title!==null&&s.title!==void 0&&(a.title=s.title);const o={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,o),e.applyData(t,o)}function oT(e,t){const i={href:vl(t.url)};t.title!==null&&t.title!==void 0&&(i.title=t.title);const s={type:"element",tagName:"a",properties:i,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function cT(e,t,i){const s=e.all(t),a=i?uT(i):eS(t),o={},c=[];if(typeof t.checked=="boolean"){const _=s[0];let x;_&&_.type==="element"&&_.tagName==="p"?x=_:(x={type:"element",tagName:"p",properties:{},children:[]},s.unshift(x)),x.children.length>0&&x.children.unshift({type:"text",value:" "}),x.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let h=-1;for(;++h1}function rT(e,t){const i={},s=e.all(t);let a=-1;for(typeof t.start=="number"&&t.start!==1&&(i.start=t.start);++a0){const c={type:"element",tagName:"tbody",properties:{},children:e.wrap(i,!0)},h=tm(t.children[1]),p=T0(t.children[t.children.length-1]);h&&p&&(c.position={start:h,end:p}),a.push(c)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(a,!0)};return e.patch(t,o),e.applyData(t,o)}function cT(e,t,i){const s=i?i.children:void 0,o=(s?s.indexOf(t):1)===0?"th":"td",c=i&&i.type==="table"?i.align:void 0,h=c?c.length:t.children.length;let p=-1;const f=[];for(;++p0,!0),s[0]),a=s.index+s[0].length,s=i.exec(t);return o.push(Av(t.slice(a),a>0,!1)),o.join("")}function Av(e,t,i){let s=0,a=e.length;if(t){let o=e.codePointAt(s);for(;o===jv||o===Tv;)s++,o=e.codePointAt(s)}if(i){let o=e.codePointAt(a-1);for(;o===jv||o===Tv;)a--,o=e.codePointAt(a-1)}return a>s?e.slice(s,a):""}function dT(e,t){const i={type:"text",value:hT(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function fT(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const pT={blockquote:Fj,break:qj,code:Wj,delete:Gj,emphasis:Yj,footnoteReference:Kj,heading:Vj,html:Xj,imageReference:Zj,image:Qj,inlineCode:Jj,linkReference:eT,link:tT,listItem:iT,list:rT,paragraph:sT,root:aT,strong:lT,table:oT,tableCell:uT,tableRow:cT,text:dT,thematicBreak:fT,toml:au,yaml:au,definition:au,footnoteDefinition:au};function au(){}const Q0=-1,qu=0,To=1,Bu=2,om=3,cm=4,um=5,hm=6,J0=7,eS=8,Rv=typeof self=="object"?self:globalThis,mT=(e,t)=>{const i=(a,o)=>(e.set(o,a),a),s=a=>{if(e.has(a))return e.get(a);const[o,c]=t[a];switch(o){case qu:case Q0:return i(c,a);case To:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Bu:{const h=i({},a);for(const[p,f]of c)h[s(p)]=s(f);return h}case om:return i(new Date(c),a);case cm:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case um:{const h=i(new Map,a);for(const[p,f]of c)h.set(s(p),s(f));return h}case hm:{const h=i(new Set,a);for(const p of c)h.add(s(p));return h}case J0:{const{name:h,message:p}=c;return i(new Rv[h](p),a)}case eS:return i(BigInt(c),a);case"BigInt":return i(Object(BigInt(c)),a);case"ArrayBuffer":return i(new Uint8Array(c).buffer,c);case"DataView":{const{buffer:h}=new Uint8Array(c);return i(new DataView(h),c)}}return i(new Rv[o](c),a)};return s},Dv=e=>mT(new Map,e)(0),ll="",{toString:gT}={},{keys:xT}=Object,bo=e=>{const t=typeof e;if(t!=="object"||!e)return[qu,t];const i=gT.call(e).slice(8,-1);switch(i){case"Array":return[To,ll];case"Object":return[Bu,ll];case"Date":return[om,ll];case"RegExp":return[cm,ll];case"Map":return[um,ll];case"Set":return[hm,ll];case"DataView":return[To,i]}return i.includes("Array")?[To,i]:i.includes("Error")?[J0,i]:[Bu,i]},lu=([e,t])=>e===qu&&(t==="function"||t==="symbol"),_T=(e,t,i,s)=>{const a=(c,h)=>{const p=s.push(c)-1;return i.set(h,p),p},o=c=>{if(i.has(c))return i.get(c);let[h,p]=bo(c);switch(h){case qu:{let _=c;switch(p){case"bigint":h=eS,_=c.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);_=null;break;case"undefined":return a([Q0],c)}return a([h,_],c)}case To:{if(p){let b=c;return p==="DataView"?b=new Uint8Array(c.buffer):p==="ArrayBuffer"&&(b=new Uint8Array(c)),a([p,[...b]],c)}const _=[],x=a([h,_],c);for(const b of c)_.push(o(b));return x}case Bu:{if(p)switch(p){case"BigInt":return a([p,c.toString()],c);case"Boolean":case"Number":case"String":return a([p,c.valueOf()],c)}if(t&&"toJSON"in c)return o(c.toJSON());const _=[],x=a([h,_],c);for(const b of xT(c))(e||!lu(bo(c[b])))&&_.push([o(b),o(c[b])]);return x}case om:return a([h,c.toISOString()],c);case cm:{const{source:_,flags:x}=c;return a([h,{source:_,flags:x}],c)}case um:{const _=[],x=a([h,_],c);for(const[b,v]of c)(e||!(lu(bo(b))||lu(bo(v))))&&_.push([o(b),o(v)]);return x}case hm:{const _=[],x=a([h,_],c);for(const b of c)(e||!lu(bo(b)))&&_.push(o(b));return x}}const{message:f}=c;return a([h,{name:p,message:f}],c)};return o},Mv=(e,{json:t,lossy:i}={})=>{const s=[];return _T(!(t||i),!!t,new Map,s)(e),s},Lo=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Dv(Mv(e,t)):structuredClone(e):(e,t)=>Dv(Mv(e,t));function bT(e,t){const i=[{type:"text",value:"↩"}];return t>1&&i.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),i}function vT(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function yT(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||bT,s=e.options.footnoteBackLabel||vT,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&S.push({type:"text",value:" "});let N=typeof i=="string"?i:i(p,v);typeof N=="string"&&(N={type:"text",value:N}),S.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+b+(v>1?"-"+v:""),dataFootnoteBackref:"",ariaLabel:typeof s=="string"?s:s(p,v),className:["data-footnote-backref"]},children:Array.isArray(N)?N:[N]})}const R=_[_.length-1];if(R&&R.type==="element"&&R.tagName==="p"){const N=R.children[R.children.length-1];N&&N.type==="text"?N.value+=" ":R.children.push({type:"text",value:" "}),R.children.push(...S)}else _.push(...S);const E={type:"element",tagName:"li",properties:{id:t+"fn-"+b},children:e.wrap(_,!0)};e.patch(f,E),h.push(E)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Lo(c),id:"footnote-label"},children:[{type:"text",value:a}]},{type:"text",value:` +`});const f={type:"element",tagName:"li",properties:o,children:c};return e.patch(t,f),e.applyData(t,f)}function uT(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const i=e.children;let s=-1;for(;!t&&++s1}function hT(e,t){const i={},s=e.all(t);let a=-1;for(typeof t.start=="number"&&t.start!==1&&(i.start=t.start);++a0){const c={type:"element",tagName:"tbody",properties:{},children:e.wrap(i,!0)},h=tm(t.children[1]),p=D0(t.children[t.children.length-1]);h&&p&&(c.position={start:h,end:p}),a.push(c)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(a,!0)};return e.patch(t,o),e.applyData(t,o)}function gT(e,t,i){const s=i?i.children:void 0,o=(s?s.indexOf(t):1)===0?"th":"td",c=i&&i.type==="table"?i.align:void 0,h=c?c.length:t.children.length;let p=-1;const f=[];for(;++p0,!0),s[0]),a=s.index+s[0].length,s=i.exec(t);return o.push(Dv(t.slice(a),a>0,!1)),o.join("")}function Dv(e,t,i){let s=0,a=e.length;if(t){let o=e.codePointAt(s);for(;o===Av||o===Rv;)s++,o=e.codePointAt(s)}if(i){let o=e.codePointAt(a-1);for(;o===Av||o===Rv;)a--,o=e.codePointAt(a-1)}return a>s?e.slice(s,a):""}function bT(e,t){const i={type:"text",value:_T(String(t.value))};return e.patch(t,i),e.applyData(t,i)}function vT(e,t){const i={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,i),e.applyData(t,i)}const yT={blockquote:Xj,break:Zj,code:Qj,delete:Jj,emphasis:eT,footnoteReference:tT,heading:iT,html:nT,imageReference:rT,image:sT,inlineCode:aT,linkReference:lT,link:oT,listItem:cT,list:hT,paragraph:dT,root:fT,strong:pT,table:mT,tableCell:xT,tableRow:gT,text:bT,thematicBreak:vT,toml:ou,yaml:ou,definition:ou,footnoteDefinition:ou};function ou(){}const tS=-1,Wu=0,Ro=1,Bu=2,om=3,cm=4,um=5,hm=6,iS=7,nS=8,Mv=typeof self=="object"?self:globalThis,ST=(e,t)=>{const i=(a,o)=>(e.set(o,a),a),s=a=>{if(e.has(a))return e.get(a);const[o,c]=t[a];switch(o){case Wu:case tS:return i(c,a);case Ro:{const h=i([],a);for(const p of c)h.push(s(p));return h}case Bu:{const h=i({},a);for(const[p,f]of c)h[s(p)]=s(f);return h}case om:return i(new Date(c),a);case cm:{const{source:h,flags:p}=c;return i(new RegExp(h,p),a)}case um:{const h=i(new Map,a);for(const[p,f]of c)h.set(s(p),s(f));return h}case hm:{const h=i(new Set,a);for(const p of c)h.add(s(p));return h}case iS:{const{name:h,message:p}=c;return i(new Mv[h](p),a)}case nS:return i(BigInt(c),a);case"BigInt":return i(Object(BigInt(c)),a);case"ArrayBuffer":return i(new Uint8Array(c).buffer,c);case"DataView":{const{buffer:h}=new Uint8Array(c);return i(new DataView(h),c)}}return i(new Mv[o](c),a)};return s},Bv=e=>ST(new Map,e)(0),ll="",{toString:wT}={},{keys:CT}=Object,bo=e=>{const t=typeof e;if(t!=="object"||!e)return[Wu,t];const i=wT.call(e).slice(8,-1);switch(i){case"Array":return[Ro,ll];case"Object":return[Bu,ll];case"Date":return[om,ll];case"RegExp":return[cm,ll];case"Map":return[um,ll];case"Set":return[hm,ll];case"DataView":return[Ro,i]}return i.includes("Array")?[Ro,i]:i.includes("Error")?[iS,i]:[Bu,i]},cu=([e,t])=>e===Wu&&(t==="function"||t==="symbol"),kT=(e,t,i,s)=>{const a=(c,h)=>{const p=s.push(c)-1;return i.set(h,p),p},o=c=>{if(i.has(c))return i.get(c);let[h,p]=bo(c);switch(h){case Wu:{let _=c;switch(p){case"bigint":h=nS,_=c.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+p);_=null;break;case"undefined":return a([tS],c)}return a([h,_],c)}case Ro:{if(p){let b=c;return p==="DataView"?b=new Uint8Array(c.buffer):p==="ArrayBuffer"&&(b=new Uint8Array(c)),a([p,[...b]],c)}const _=[],x=a([h,_],c);for(const b of c)_.push(o(b));return x}case Bu:{if(p)switch(p){case"BigInt":return a([p,c.toString()],c);case"Boolean":case"Number":case"String":return a([p,c.valueOf()],c)}if(t&&"toJSON"in c)return o(c.toJSON());const _=[],x=a([h,_],c);for(const b of CT(c))(e||!cu(bo(c[b])))&&_.push([o(b),o(c[b])]);return x}case om:return a([h,c.toISOString()],c);case cm:{const{source:_,flags:x}=c;return a([h,{source:_,flags:x}],c)}case um:{const _=[],x=a([h,_],c);for(const[b,v]of c)(e||!(cu(bo(b))||cu(bo(v))))&&_.push([o(b),o(v)]);return x}case hm:{const _=[],x=a([h,_],c);for(const b of c)(e||!cu(bo(b)))&&_.push(o(b));return x}}const{message:f}=c;return a([h,{name:p,message:f}],c)};return o},Lv=(e,{json:t,lossy:i}={})=>{const s=[];return kT(!(t||i),!!t,new Map,s)(e),s},zo=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Bv(Lv(e,t)):structuredClone(e):(e,t)=>Bv(Lv(e,t));function ET(e,t){const i=[{type:"text",value:"↩"}];return t>1&&i.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),i}function NT(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function jT(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=e.options.footnoteBackContent||ET,s=e.options.footnoteBackLabel||NT,a=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",c=e.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let p=-1;for(;++p0&&S.push({type:"text",value:" "});let N=typeof i=="string"?i:i(p,v);typeof N=="string"&&(N={type:"text",value:N}),S.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+b+(v>1?"-"+v:""),dataFootnoteBackref:"",ariaLabel:typeof s=="string"?s:s(p,v),className:["data-footnote-backref"]},children:Array.isArray(N)?N:[N]})}const D=_[_.length-1];if(D&&D.type==="element"&&D.tagName==="p"){const N=D.children[D.children.length-1];N&&N.type==="text"?N.value+=" ":D.children.push({type:"text",value:" "}),D.children.push(...S)}else _.push(...S);const E={type:"element",tagName:"li",properties:{id:t+"fn-"+b},children:e.wrap(_,!0)};e.patch(f,E),h.push(E)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...zo(c),id:"footnote-label"},children:[{type:"text",value:a}]},{type:"text",value:` `},{type:"element",tagName:"ol",properties:{},children:e.wrap(h,!0)},{type:"text",value:` -`}]}}const Wu=(function(e){if(e==null)return kT;if(typeof e=="function")return Gu(e);if(typeof e=="object")return Array.isArray(e)?ST(e):wT(e);if(typeof e=="string")return CT(e);throw new Error("Expected function, string, or object as test")});function ST(e){const t=[];let i=-1;for(;++i":""))+")"})}return b;function b(){let v=tS,S,j,R;if((!t||o(p,f,_[_.length-1]||void 0))&&(v=TT(i(p,_)),v[0]===Tp))return v;if("children"in p&&p.children){const E=p;if(E.children&&v[0]!==jT)for(j=(s?E.children.length:-1)+c,R=_.concat(E);j>-1&&j":""))+")"})}return b;function b(){let v=rS,S,j,D;if((!t||o(p,f,_[_.length-1]||void 0))&&(v=OT(i(p,_)),v[0]===Ap))return v;if("children"in p&&p.children){const E=p;if(E.children&&v[0]!==LT)for(j=(s?E.children.length:-1)+c,D=_.concat(E);j>-1&&j0&&i.push({type:"text",value:` -`}),i}function Bv(e){let t=0,i=e.charCodeAt(t);for(;i===9||i===32;)t++,i=e.charCodeAt(t);return e.slice(t)}function Lv(e,t){const i=RT(e,t),s=i.one(e,void 0),a=yT(i),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return a&&o.children.push({type:"text",value:` -`},a),o}function OT(e,t){return e&&"run"in e?async function(i,s){const a=Lv(i,{file:s,...t});await e.run(a,s)}:function(i,s){return Lv(i,{file:s,...e||t})}}function Ov(e){if(e)throw e}var vf,zv;function zT(){if(zv)return vf;zv=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=function(f){return typeof Array.isArray=="function"?Array.isArray(f):t.call(f)==="[object Array]"},o=function(f){if(!f||t.call(f)!=="[object Object]")return!1;var _=e.call(f,"constructor"),x=f.constructor&&f.constructor.prototype&&e.call(f.constructor.prototype,"isPrototypeOf");if(f.constructor&&!_&&!x)return!1;var b;for(b in f);return typeof b>"u"||e.call(f,b)},c=function(f,_){i&&_.name==="__proto__"?i(f,_.name,{enumerable:!0,configurable:!0,value:_.newValue,writable:!0}):f[_.name]=_.newValue},h=function(f,_){if(_==="__proto__")if(e.call(f,_)){if(s)return s(f,_).value}else return;return f[_]};return vf=function p(){var f,_,x,b,v,S,j=arguments[0],R=1,E=arguments.length,N=!1;for(typeof j=="boolean"&&(N=j,j=arguments[1]||{},R=2),(j==null||typeof j!="object"&&typeof j!="function")&&(j={});Rc.length;let p;h&&c.push(a);try{p=e.apply(this,c)}catch(f){const _=f;if(h&&i)throw _;return a(_)}h||(p&&p.then&&typeof p.then=="function"?p.then(o,a):p instanceof Error?a(p):o(p))}function a(c,...h){i||(i=!0,t(c,...h))}function o(c){a(null,c)}}const jr={basename:UT,dirname:$T,extname:FT,join:qT,sep:"/"};function UT(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');qo(e);let i=0,s=-1,a=e.length,o;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else s<0&&(o=!0,s=a+1);return s<0?"":e.slice(i,s)}if(t===e)return"";let c=-1,h=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else c<0&&(o=!0,c=a+1),h>-1&&(e.codePointAt(a)===t.codePointAt(h--)?h<0&&(s=a):(h=-1,s=c));return i===s?s=c:s<0&&(s=e.length),e.slice(i,s)}function $T(e){if(qo(e),e.length===0)return".";let t=-1,i=e.length,s;for(;--i;)if(e.codePointAt(i)===47){if(s){t=i;break}}else s||(s=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function FT(e){qo(e);let t=e.length,i=-1,s=0,a=-1,o=0,c;for(;t--;){const h=e.codePointAt(t);if(h===47){if(c){s=t+1;break}continue}i<0&&(c=!0,i=t+1),h===46?a<0?a=t:o!==1&&(o=1):a>-1&&(o=-1)}return a<0||i<0||o===0||o===1&&a===i-1&&a===s+1?"":e.slice(a,i)}function qT(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function GT(e,t){let i="",s=0,a=-1,o=0,c=-1,h,p;for(;++c<=e.length;){if(c2){if(p=i.lastIndexOf("/"),p!==i.length-1){p<0?(i="",s=0):(i=i.slice(0,p),s=i.length-1-i.lastIndexOf("/")),a=c,o=0;continue}}else if(i.length>0){i="",s=0,a=c,o=0;continue}}t&&(i=i.length>0?i+"/..":"..",s=2)}else i.length>0?i+="/"+e.slice(a+1,c):i=e.slice(a+1,c),s=c-a-1;a=c,o=0}else h===46&&o>-1?o++:o=-1}return i}function qo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const YT={cwd:KT};function KT(){return"/"}function Dp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function VT(e){if(typeof e=="string")e=new URL(e);else if(!Dp(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return XT(e)}function XT(e){if(e.hostname!==""){const s=new TypeError('File URL host must be "localhost" or empty on darwin');throw s.code="ERR_INVALID_FILE_URL_HOST",s}const t=e.pathname;let i=-1;for(;++i0){let[v,...S]=_;const j=s[b][1];Rp(j)&&Rp(v)&&(v=yf(!0,j,v)),s[b]=[f,v,...S]}}}}const eA=new fm().freeze();function kf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Ef(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Nf(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Iv(e){if(!Rp(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Hv(e,t,i){if(!i)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function ou(e){return tA(e)?e:new nS(e)}function tA(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function iA(e){return typeof e=="string"||nA(e)}function nA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const rA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Uv=[],$v={allowDangerousHtml:!0},sA=/^(https?|ircs?|mailto|xmpp)$/i,aA=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function rS(e){const t=lA(e),i=oA(e);return cA(t.runSync(t.parse(i),i),e)}function lA(e){const t=e.rehypePlugins||Uv,i=e.remarkPlugins||Uv,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...$v}:$v;return eA().use($j).use(i).use(OT,s).use(t)}function oA(e){const t=e.children||"",i=new nS;return typeof t=="string"&&(i.value=t),i}function cA(e,t){const i=t.allowedElements,s=t.allowElement,a=t.components,o=t.disallowedElements,c=t.skipHtml,h=t.unwrapDisallowed,p=t.urlTransform||uA;for(const _ of aA)Object.hasOwn(t,_.from)&&(""+_.from+(_.to?"use `"+_.to+"` instead":"remove it")+rA+_.id,void 0);return dm(e,f),kN(e,{Fragment:d.Fragment,components:a,ignoreInvalidStyle:!0,jsx:d.jsx,jsxs:d.jsxs,passKeys:!0,passNode:!0});function f(_,x,b){if(_.type==="raw"&&b&&typeof x=="number")return c?b.children.splice(x,1):b.children[x]={type:"text",value:_.value},x;if(_.type==="element"){let v;for(v in xf)if(Object.hasOwn(xf,v)&&Object.hasOwn(_.properties,v)){const S=_.properties[v],j=xf[v];(j===null||j.includes(_.tagName))&&(_.properties[v]=p(String(S||""),v,_))}}if(_.type==="element"){let v=i?!i.includes(_.tagName):o?o.includes(_.tagName):!1;if(!v&&s&&typeof x=="number"&&(v=!s(_,x,b)),v&&b&&typeof x=="number")return h&&_.children?b.children.splice(x,1,..._.children):b.children.splice(x,1),x}}}function uA(e){const t=e.indexOf(":"),i=e.indexOf("?"),s=e.indexOf("#"),a=e.indexOf("/");return t===-1||a!==-1&&t>a||i!==-1&&t>i||s!==-1&&t>s||sA.test(e.slice(0,t))?e:""}function hA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function sS(e,t,i){const a=Wu((i||{}).ignore||[]),o=dA(t);let c=-1;for(;++c0?{type:"text",value:D}:void 0),D===!1?b.lastIndex=te+1:(S!==te&&N.push({type:"text",value:f.value.slice(S,te)}),Array.isArray(D)?N.push(...D):D&&N.push(D),S=te+I[0].length,E=!0),!b.global)break;I=b.exec(f.value)}return E?(S?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=Fv(e,"(");let o=Fv(e,")");for(;s!==-1&&a>o;)e+=i.slice(0,s+1),i=i.slice(s+1),s=i.indexOf(")"),o++;return[e,i]}function lS(e,t){const i=e.input.charCodeAt(e.index-1);return(e.index===0||_a(i)||$u(i))&&(!t||i!==47)}oS.peek=zA;function TA(){this.buffer()}function AA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function RA(){this.buffer()}function DA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function MA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=fr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function BA(e){this.exit(e)}function LA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=fr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function OA(e){this.exit(e)}function zA(){return"["}function oS(e,t,i,s){const a=i.createTracker(s);let o=a.move("[^");const c=i.enter("footnoteReference"),h=i.enter("reference");return o+=a.move(i.safe(i.associationId(e),{after:"]",before:o})),h(),c(),o+=a.move("]"),o}function PA(){return{enter:{gfmFootnoteCallString:TA,gfmFootnoteCall:AA,gfmFootnoteDefinitionLabelString:RA,gfmFootnoteDefinition:DA},exit:{gfmFootnoteCallString:MA,gfmFootnoteCall:BA,gfmFootnoteDefinitionLabelString:LA,gfmFootnoteDefinition:OA}}}function IA(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:i,footnoteReference:oS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function i(s,a,o,c){const h=o.createTracker(c);let p=h.move("[^");const f=o.enter("footnoteDefinition"),_=o.enter("label");return p+=h.move(o.safe(o.associationId(s),{before:p,after:"]"})),_(),p+=h.move("]:"),s.children&&s.children.length>0&&(h.shift(4),p+=h.move((t?` -`:" ")+o.indentLines(o.containerFlow(s,h.current()),t?cS:HA))),f(),p}}function HA(e,t,i){return t===0?e:cS(e,t,i)}function cS(e,t,i){return(i?"":" ")+e}const UA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];uS.peek=GA;function $A(){return{canContainEols:["delete"],enter:{strikethrough:qA},exit:{strikethrough:WA}}}function FA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:UA}],handlers:{delete:uS}}}function qA(e){this.enter({type:"delete",children:[]},e)}function WA(e){this.exit(e)}function uS(e,t,i,s){const a=i.createTracker(s),o=i.enter("strikethrough");let c=a.move("~~");return c+=i.containerPhrasing(e,{...a.current(),before:c,after:"~"}),c+=a.move("~~"),o(),c}function GA(){return"~"}function YA(e){return e.length}function KA(e,t){const i=t||{},s=(i.align||[]).concat(),a=i.stringLength||YA,o=[],c=[],h=[],p=[];let f=0,_=-1;for(;++_f&&(f=e[_].length);++Ep[E])&&(p[E]=I)}j.push(N)}c[_]=j,h[_]=R}let x=-1;if(typeof s=="object"&&"length"in s)for(;++xp[x]&&(p[x]=N),v[x]=N),b[x]=I}c.splice(1,0,b),h.splice(1,0,v),_=-1;const S=[];for(;++_ "),o.shift(2);const c=i.indentLines(i.containerFlow(e,o.current()),ZA);return a(),c}function ZA(e,t,i){return">"+(i?"":" ")+e}function QA(e,t){return Wv(e,t.inConstruct,!0)&&!Wv(e,t.notInConstruct,!1)}function Wv(e,t,i){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return i;let s=-1;for(;++sc&&(c=o):o=1,a=s+t.length,s=i.indexOf(t,a);return c}function eR(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function tR(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function iR(e,t,i,s){const a=tR(i),o=e.value||"",c=a==="`"?"GraveAccent":"Tilde";if(eR(e,i)){const x=i.enter("codeIndented"),b=i.indentLines(o,nR);return x(),b}const h=i.createTracker(s),p=a.repeat(Math.max(JA(o,a)+1,3)),f=i.enter("codeFenced");let _=h.move(p);if(e.lang){const x=i.enter(`codeFencedLang${c}`);_+=h.move(i.safe(e.lang,{before:_,after:" ",encode:["`"],...h.current()})),x()}if(e.lang&&e.meta){const x=i.enter(`codeFencedMeta${c}`);_+=h.move(" "),_+=h.move(i.safe(e.meta,{before:_,after:` +`}),i}function Ov(e){let t=0,i=e.charCodeAt(t);for(;i===9||i===32;)t++,i=e.charCodeAt(t);return e.slice(t)}function zv(e,t){const i=PT(e,t),s=i.one(e,void 0),a=jT(i),o=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return a&&o.children.push({type:"text",value:` +`},a),o}function FT(e,t){return e&&"run"in e?async function(i,s){const a=zv(i,{file:s,...t});await e.run(a,s)}:function(i,s){return zv(i,{file:s,...e||t})}}function Pv(e){if(e)throw e}var yf,Iv;function qT(){if(Iv)return yf;Iv=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=function(f){return typeof Array.isArray=="function"?Array.isArray(f):t.call(f)==="[object Array]"},o=function(f){if(!f||t.call(f)!=="[object Object]")return!1;var _=e.call(f,"constructor"),x=f.constructor&&f.constructor.prototype&&e.call(f.constructor.prototype,"isPrototypeOf");if(f.constructor&&!_&&!x)return!1;var b;for(b in f);return typeof b>"u"||e.call(f,b)},c=function(f,_){i&&_.name==="__proto__"?i(f,_.name,{enumerable:!0,configurable:!0,value:_.newValue,writable:!0}):f[_.name]=_.newValue},h=function(f,_){if(_==="__proto__")if(e.call(f,_)){if(s)return s(f,_).value}else return;return f[_]};return yf=function p(){var f,_,x,b,v,S,j=arguments[0],D=1,E=arguments.length,N=!1;for(typeof j=="boolean"&&(N=j,j=arguments[1]||{},D=2),(j==null||typeof j!="object"&&typeof j!="function")&&(j={});Dc.length;let p;h&&c.push(a);try{p=e.apply(this,c)}catch(f){const _=f;if(h&&i)throw _;return a(_)}h||(p&&p.then&&typeof p.then=="function"?p.then(o,a):p instanceof Error?a(p):o(p))}function a(c,...h){i||(i=!0,t(c,...h))}function o(c){a(null,c)}}const jr={basename:KT,dirname:VT,extname:XT,join:ZT,sep:"/"};function KT(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Go(e);let i=0,s=-1,a=e.length,o;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else s<0&&(o=!0,s=a+1);return s<0?"":e.slice(i,s)}if(t===e)return"";let c=-1,h=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(o){i=a+1;break}}else c<0&&(o=!0,c=a+1),h>-1&&(e.codePointAt(a)===t.codePointAt(h--)?h<0&&(s=a):(h=-1,s=c));return i===s?s=c:s<0&&(s=e.length),e.slice(i,s)}function VT(e){if(Go(e),e.length===0)return".";let t=-1,i=e.length,s;for(;--i;)if(e.codePointAt(i)===47){if(s){t=i;break}}else s||(s=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function XT(e){Go(e);let t=e.length,i=-1,s=0,a=-1,o=0,c;for(;t--;){const h=e.codePointAt(t);if(h===47){if(c){s=t+1;break}continue}i<0&&(c=!0,i=t+1),h===46?a<0?a=t:o!==1&&(o=1):a>-1&&(o=-1)}return a<0||i<0||o===0||o===1&&a===i-1&&a===s+1?"":e.slice(a,i)}function ZT(...e){let t=-1,i;for(;++t0&&e.codePointAt(e.length-1)===47&&(i+="/"),t?"/"+i:i}function JT(e,t){let i="",s=0,a=-1,o=0,c=-1,h,p;for(;++c<=e.length;){if(c2){if(p=i.lastIndexOf("/"),p!==i.length-1){p<0?(i="",s=0):(i=i.slice(0,p),s=i.length-1-i.lastIndexOf("/")),a=c,o=0;continue}}else if(i.length>0){i="",s=0,a=c,o=0;continue}}t&&(i=i.length>0?i+"/..":"..",s=2)}else i.length>0?i+="/"+e.slice(a+1,c):i=e.slice(a+1,c),s=c-a-1;a=c,o=0}else h===46&&o>-1?o++:o=-1}return i}function Go(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const eA={cwd:tA};function tA(){return"/"}function Mp(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function iA(e){if(typeof e=="string")e=new URL(e);else if(!Mp(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return nA(e)}function nA(e){if(e.hostname!==""){const s=new TypeError('File URL host must be "localhost" or empty on darwin');throw s.code="ERR_INVALID_FILE_URL_HOST",s}const t=e.pathname;let i=-1;for(;++i0){let[v,...S]=_;const j=s[b][1];Dp(j)&&Dp(v)&&(v=Sf(!0,j,v)),s[b]=[f,v,...S]}}}}const lA=new fm().freeze();function Ef(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Nf(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function jf(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Uv(e){if(!Dp(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function $v(e,t,i){if(!i)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function uu(e){return oA(e)?e:new aS(e)}function oA(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function cA(e){return typeof e=="string"||uA(e)}function uA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const hA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Fv=[],qv={allowDangerousHtml:!0},dA=/^(https?|ircs?|mailto|xmpp)$/i,fA=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function lS(e){const t=pA(e),i=mA(e);return gA(t.runSync(t.parse(i),i),e)}function pA(e){const t=e.rehypePlugins||Fv,i=e.remarkPlugins||Fv,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...qv}:qv;return lA().use(Vj).use(i).use(FT,s).use(t)}function mA(e){const t=e.children||"",i=new aS;return typeof t=="string"&&(i.value=t),i}function gA(e,t){const i=t.allowedElements,s=t.allowElement,a=t.components,o=t.disallowedElements,c=t.skipHtml,h=t.unwrapDisallowed,p=t.urlTransform||xA;for(const _ of fA)Object.hasOwn(t,_.from)&&(""+_.from+(_.to?"use `"+_.to+"` instead":"remove it")+hA+_.id,void 0);return dm(e,f),DN(e,{Fragment:d.Fragment,components:a,ignoreInvalidStyle:!0,jsx:d.jsx,jsxs:d.jsxs,passKeys:!0,passNode:!0});function f(_,x,b){if(_.type==="raw"&&b&&typeof x=="number")return c?b.children.splice(x,1):b.children[x]={type:"text",value:_.value},x;if(_.type==="element"){let v;for(v in _f)if(Object.hasOwn(_f,v)&&Object.hasOwn(_.properties,v)){const S=_.properties[v],j=_f[v];(j===null||j.includes(_.tagName))&&(_.properties[v]=p(String(S||""),v,_))}}if(_.type==="element"){let v=i?!i.includes(_.tagName):o?o.includes(_.tagName):!1;if(!v&&s&&typeof x=="number"&&(v=!s(_,x,b)),v&&b&&typeof x=="number")return h&&_.children?b.children.splice(x,1,..._.children):b.children.splice(x,1),x}}}function xA(e){const t=e.indexOf(":"),i=e.indexOf("?"),s=e.indexOf("#"),a=e.indexOf("/");return t===-1||a!==-1&&t>a||i!==-1&&t>i||s!==-1&&t>s||dA.test(e.slice(0,t))?e:""}function _A(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function oS(e,t,i){const a=Gu((i||{}).ignore||[]),o=bA(t);let c=-1;for(;++c0?{type:"text",value:R}:void 0),R===!1?b.lastIndex=te+1:(S!==te&&N.push({type:"text",value:f.value.slice(S,te)}),Array.isArray(R)?N.push(...R):R&&N.push(R),S=te+I[0].length,E=!0),!b.global)break;I=b.exec(f.value)}return E?(S?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let i=t[0],s=i.indexOf(")");const a=Wv(e,"(");let o=Wv(e,")");for(;s!==-1&&a>o;)e+=i.slice(0,s+1),i=i.slice(s+1),s=i.indexOf(")"),o++;return[e,i]}function uS(e,t){const i=e.input.charCodeAt(e.index-1);return(e.index===0||_a(i)||Fu(i))&&(!t||i!==47)}hS.peek=qA;function OA(){this.buffer()}function zA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function PA(){this.buffer()}function IA(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function HA(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=fr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function UA(e){this.exit(e)}function $A(e){const t=this.resume(),i=this.stack[this.stack.length-1];i.type,i.identifier=fr(this.sliceSerialize(e)).toLowerCase(),i.label=t}function FA(e){this.exit(e)}function qA(){return"["}function hS(e,t,i,s){const a=i.createTracker(s);let o=a.move("[^");const c=i.enter("footnoteReference"),h=i.enter("reference");return o+=a.move(i.safe(i.associationId(e),{after:"]",before:o})),h(),c(),o+=a.move("]"),o}function WA(){return{enter:{gfmFootnoteCallString:OA,gfmFootnoteCall:zA,gfmFootnoteDefinitionLabelString:PA,gfmFootnoteDefinition:IA},exit:{gfmFootnoteCallString:HA,gfmFootnoteCall:UA,gfmFootnoteDefinitionLabelString:$A,gfmFootnoteDefinition:FA}}}function GA(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:i,footnoteReference:hS},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function i(s,a,o,c){const h=o.createTracker(c);let p=h.move("[^");const f=o.enter("footnoteDefinition"),_=o.enter("label");return p+=h.move(o.safe(o.associationId(s),{before:p,after:"]"})),_(),p+=h.move("]:"),s.children&&s.children.length>0&&(h.shift(4),p+=h.move((t?` +`:" ")+o.indentLines(o.containerFlow(s,h.current()),t?dS:YA))),f(),p}}function YA(e,t,i){return t===0?e:dS(e,t,i)}function dS(e,t,i){return(i?"":" ")+e}const KA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];fS.peek=JA;function VA(){return{canContainEols:["delete"],enter:{strikethrough:ZA},exit:{strikethrough:QA}}}function XA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:KA}],handlers:{delete:fS}}}function ZA(e){this.enter({type:"delete",children:[]},e)}function QA(e){this.exit(e)}function fS(e,t,i,s){const a=i.createTracker(s),o=i.enter("strikethrough");let c=a.move("~~");return c+=i.containerPhrasing(e,{...a.current(),before:c,after:"~"}),c+=a.move("~~"),o(),c}function JA(){return"~"}function eR(e){return e.length}function tR(e,t){const i=t||{},s=(i.align||[]).concat(),a=i.stringLength||eR,o=[],c=[],h=[],p=[];let f=0,_=-1;for(;++_f&&(f=e[_].length);++Ep[E])&&(p[E]=I)}j.push(N)}c[_]=j,h[_]=D}let x=-1;if(typeof s=="object"&&"length"in s)for(;++xp[x]&&(p[x]=N),v[x]=N),b[x]=I}c.splice(1,0,b),h.splice(1,0,v),_=-1;const S=[];for(;++_ "),o.shift(2);const c=i.indentLines(i.containerFlow(e,o.current()),rR);return a(),c}function rR(e,t,i){return">"+(i?"":" ")+e}function sR(e,t){return Yv(e,t.inConstruct,!0)&&!Yv(e,t.notInConstruct,!1)}function Yv(e,t,i){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return i;let s=-1;for(;++sc&&(c=o):o=1,a=s+t.length,s=i.indexOf(t,a);return c}function lR(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function oR(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function cR(e,t,i,s){const a=oR(i),o=e.value||"",c=a==="`"?"GraveAccent":"Tilde";if(lR(e,i)){const x=i.enter("codeIndented"),b=i.indentLines(o,uR);return x(),b}const h=i.createTracker(s),p=a.repeat(Math.max(aR(o,a)+1,3)),f=i.enter("codeFenced");let _=h.move(p);if(e.lang){const x=i.enter(`codeFencedLang${c}`);_+=h.move(i.safe(e.lang,{before:_,after:" ",encode:["`"],...h.current()})),x()}if(e.lang&&e.meta){const x=i.enter(`codeFencedMeta${c}`);_+=h.move(" "),_+=h.move(i.safe(e.meta,{before:_,after:` `,encode:["`"],...h.current()})),x()}return _+=h.move(` `),o&&(_+=h.move(o+` -`)),_+=h.move(p),f(),_}function nR(e,t,i){return(i?"":" ")+e}function pm(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function rR(e,t,i,s){const a=pm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("definition");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("[");return f+=p.move(i.safe(i.associationId(e),{before:f,after:"]",...p.current()})),f+=p.move("]: "),h(),!e.url||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":` -`,...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),c(),f}function sR(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Oo(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Lu(e,t,i){const s=ml(e),a=ml(t);return s===void 0?a===void 0?i==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:s===1?a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}hS.peek=aR;function hS(e,t,i,s){const a=sR(i),o=i.enter("emphasis"),c=i.createTracker(s),h=c.move(a);let p=c.move(i.containerPhrasing(e,{after:a,before:h,...c.current()}));const f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Oo(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Oo(x));const v=c.move(a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function aR(e,t,i){return i.options.emphasis||"*"}function lR(e,t){let i=!1;return dm(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,Tp}),!!((!e.depth||e.depth<3)&&sm(e)&&(t.options.setext||i))}function oR(e,t,i,s){const a=Math.max(Math.min(6,e.depth||1),1),o=i.createTracker(s);if(lR(e,i)){const _=i.enter("headingSetext"),x=i.enter("phrasing"),b=i.containerPhrasing(e,{...o.current(),before:` +`)),_+=h.move(p),f(),_}function uR(e,t,i){return(i?"":" ")+e}function pm(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function hR(e,t,i,s){const a=pm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("definition");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("[");return f+=p.move(i.safe(i.associationId(e),{before:f,after:"]",...p.current()})),f+=p.move("]: "),h(),!e.url||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":` +`,...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),c(),f}function dR(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Po(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Lu(e,t,i){const s=ml(e),a=ml(t);return s===void 0?a===void 0?i==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:s===1?a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}pS.peek=fR;function pS(e,t,i,s){const a=dR(i),o=i.enter("emphasis"),c=i.createTracker(s),h=c.move(a);let p=c.move(i.containerPhrasing(e,{after:a,before:h,...c.current()}));const f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Po(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Po(x));const v=c.move(a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function fR(e,t,i){return i.options.emphasis||"*"}function pR(e,t){let i=!1;return dm(e,function(s){if("value"in s&&/\r?\n|\r/.test(s.value)||s.type==="break")return i=!0,Ap}),!!((!e.depth||e.depth<3)&&sm(e)&&(t.options.setext||i))}function mR(e,t,i,s){const a=Math.max(Math.min(6,e.depth||1),1),o=i.createTracker(s);if(pR(e,i)){const _=i.enter("headingSetext"),x=i.enter("phrasing"),b=i.containerPhrasing(e,{...o.current(),before:` `,after:` `});return x(),_(),b+` `+(a===1?"=":"-").repeat(b.length-(Math.max(b.lastIndexOf("\r"),b.lastIndexOf(` `))+1))}const c="#".repeat(a),h=i.enter("headingAtx"),p=i.enter("phrasing");o.move(c+" ");let f=i.containerPhrasing(e,{before:"# ",after:` -`,...o.current()});return/^[\t ]/.test(f)&&(f=Oo(f.charCodeAt(0))+f.slice(1)),f=f?c+" "+f:c,i.options.closeAtx&&(f+=" "+c),p(),h(),f}dS.peek=cR;function dS(e){return e.value||""}function cR(){return"<"}fS.peek=uR;function fS(e,t,i,s){const a=pm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("image");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("![");return f+=p.move(i.safe(e.alt,{before:f,after:"]",...p.current()})),f+=p.move("]("),h(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":")",...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),f+=p.move(")"),c(),f}function uR(){return"!"}pS.peek=hR;function pS(e,t,i,s){const a=e.referenceType,o=i.enter("imageReference");let c=i.enter("label");const h=i.createTracker(s);let p=h.move("![");const f=i.safe(e.alt,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),c();const _=i.stack;i.stack=[],c=i.enter("reference");const x=i.safe(i.associationId(e),{before:p,after:"]",...h.current()});return c(),i.stack=_,o(),a==="full"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function hR(){return"!"}mS.peek=dR;function mS(e,t,i){let s=e.value||"",a="`",o=-1;for(;new RegExp("(^|[^`])"+a+"([^`]|$)").test(s);)a+="`";for(/[^ \r\n]/.test(s)&&(/^[ \r\n]/.test(s)&&/[ \r\n]$/.test(s)||/^`|`$/.test(s))&&(s=" "+s+" ");++o\u007F]/.test(e.url))}xS.peek=fR;function xS(e,t,i,s){const a=pm(i),o=a==='"'?"Quote":"Apostrophe",c=i.createTracker(s);let h,p;if(gS(e,i)){const _=i.stack;i.stack=[],h=i.enter("autolink");let x=c.move("<");return x+=c.move(i.containerPhrasing(e,{before:x,after:">",...c.current()})),x+=c.move(">"),h(),i.stack=_,x}h=i.enter("link"),p=i.enter("label");let f=c.move("[");return f+=c.move(i.containerPhrasing(e,{before:f,after:"](",...c.current()})),f+=c.move("]("),p(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(p=i.enter("destinationLiteral"),f+=c.move("<"),f+=c.move(i.safe(e.url,{before:f,after:">",...c.current()})),f+=c.move(">")):(p=i.enter("destinationRaw"),f+=c.move(i.safe(e.url,{before:f,after:e.title?" ":")",...c.current()}))),p(),e.title&&(p=i.enter(`title${o}`),f+=c.move(" "+a),f+=c.move(i.safe(e.title,{before:f,after:a,...c.current()})),f+=c.move(a),p()),f+=c.move(")"),h(),f}function fR(e,t,i){return gS(e,i)?"<":"["}_S.peek=pR;function _S(e,t,i,s){const a=e.referenceType,o=i.enter("linkReference");let c=i.enter("label");const h=i.createTracker(s);let p=h.move("[");const f=i.containerPhrasing(e,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),c();const _=i.stack;i.stack=[],c=i.enter("reference");const x=i.safe(i.associationId(e),{before:p,after:"]",...h.current()});return c(),i.stack=_,o(),a==="full"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function pR(){return"["}function mm(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function mR(e){const t=mm(e),i=e.options.bulletOther;if(!i)return t==="*"?"-":"*";if(i!=="*"&&i!=="+"&&i!=="-")throw new Error("Cannot serialize items with `"+i+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(i===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+i+"`) to be different");return i}function gR(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function bS(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function xR(e,t,i,s){const a=i.enter("list"),o=i.bulletCurrent;let c=e.ordered?gR(i):mm(i);const h=e.ordered?c==="."?")":".":mR(i);let p=t&&i.bulletLastUsed?c===i.bulletLastUsed:!1;if(!e.ordered){const _=e.children?e.children[0]:void 0;if((c==="*"||c==="-")&&_&&(!_.children||!_.children[0])&&i.stack[i.stack.length-1]==="list"&&i.stack[i.stack.length-2]==="listItem"&&i.stack[i.stack.length-3]==="list"&&i.stack[i.stack.length-4]==="listItem"&&i.indexStack[i.indexStack.length-1]===0&&i.indexStack[i.indexStack.length-2]===0&&i.indexStack[i.indexStack.length-3]===0&&(p=!0),bS(i)===c&&_){let x=-1;for(;++x-1?t.start:1)+(i.options.incrementListMarker===!1?0:t.children.indexOf(e))+o);let c=o.length+1;(a==="tab"||a==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(c=Math.ceil(c/4)*4);const h=i.createTracker(s);h.move(o+" ".repeat(c-o.length)),h.shift(c);const p=i.enter("listItem"),f=i.indentLines(i.containerFlow(e,h.current()),_);return p(),f;function _(x,b,v){return b?(v?"":" ".repeat(c))+x:(v?o:o+" ".repeat(c-o.length))+x}}function vR(e,t,i,s){const a=i.enter("paragraph"),o=i.enter("phrasing"),c=i.containerPhrasing(e,s);return o(),a(),c}const yR=Wu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function SR(e,t,i,s){return(e.children.some(function(c){return yR(c)})?i.containerPhrasing:i.containerFlow).call(i,e,s)}function wR(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}vS.peek=CR;function vS(e,t,i,s){const a=wR(i),o=i.enter("strong"),c=i.createTracker(s),h=c.move(a+a);let p=c.move(i.containerPhrasing(e,{after:a,before:h,...c.current()}));const f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Oo(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Oo(x));const v=c.move(a+a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function CR(e,t,i){return i.options.strong||"*"}function kR(e,t,i,s){return i.safe(e.value,s)}function ER(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function NR(e,t,i){const s=(bS(i)+(i.options.ruleSpaces?" ":"")).repeat(ER(i));return i.options.ruleSpaces?s.slice(0,-1):s}const yS={blockquote:XA,break:Gv,code:iR,definition:rR,emphasis:hS,hardBreak:Gv,heading:oR,html:dS,image:fS,imageReference:pS,inlineCode:mS,link:xS,linkReference:_S,list:xR,listItem:bR,paragraph:vR,root:SR,strong:vS,text:kR,thematicBreak:NR};function jR(){return{enter:{table:TR,tableData:Yv,tableHeader:Yv,tableRow:RR},exit:{codeText:DR,table:AR,tableData:Rf,tableHeader:Rf,tableRow:Rf}}}function TR(e){const t=e._align;this.enter({type:"table",align:t.map(function(i){return i==="none"?null:i}),children:[]},e),this.data.inTable=!0}function AR(e){this.exit(e),this.data.inTable=void 0}function RR(e){this.enter({type:"tableRow",children:[]},e)}function Rf(e){this.exit(e)}function Yv(e){this.enter({type:"tableCell",children:[]},e)}function DR(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,MR));const i=this.stack[this.stack.length-1];i.type,i.value=t,this.exit(e)}function MR(e,t){return t==="|"?t:e}function BR(e){const t=e||{},i=t.tableCellPadding,s=t.tablePipeAlign,a=t.stringLength,o=i?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` -`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:b,table:c,tableCell:p,tableRow:h}};function c(v,S,j,R){return f(_(v,j,R),v.align)}function h(v,S,j,R){const E=x(v,j,R),N=f([E]);return N.slice(0,N.indexOf(` -`))}function p(v,S,j,R){const E=j.enter("tableCell"),N=j.enter("phrasing"),I=j.containerPhrasing(v,{...R,before:o,after:o});return N(),E(),I}function f(v,S){return KA(v,{align:S,alignDelimiters:s,padding:i,stringLength:a})}function _(v,S,j){const R=v.children;let E=-1;const N=[],I=S.enter("table");for(;++E0&&!i&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),i}const QR={tokenize:a3,partial:!0};function JR(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:n3,continuation:{tokenize:r3},exit:s3}},text:{91:{name:"gfmFootnoteCall",tokenize:i3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:e3,resolveTo:t3}}}}function e3(e,t,i){const s=this;let a=s.events.length;const o=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let c;for(;a--;){const p=s.events[a][1];if(p.type==="labelImage"){c=p;break}if(p.type==="gfmFootnoteCall"||p.type==="labelLink"||p.type==="label"||p.type==="image"||p.type==="link")break}return h;function h(p){if(!c||!c._balanced)return i(p);const f=fr(s.sliceSerialize({start:c.end,end:s.now()}));return f.codePointAt(0)!==94||!o.includes(f.slice(1))?i(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function t3(e,t){let i=e.length;for(;i--;)if(e[i][1].type==="labelImage"&&e[i][0]==="enter"){e[i][1];break}e[i+1][1].type="data",e[i+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},e[i+3][1].start),end:Object.assign({},e[e.length-1][1].end)},a={type:"gfmFootnoteCallMarker",start:Object.assign({},e[i+3][1].end),end:Object.assign({},e[i+3][1].end)};a.end.column++,a.end.offset++,a.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},c={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},h=[e[i+1],e[i+2],["enter",s,t],e[i+3],e[i+4],["enter",a,t],["exit",a,t],["enter",o,t],["enter",c,t],["exit",c,t],["exit",o,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(i,e.length-i+1,...h),e}function i3(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o=0,c;return h;function h(x){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),p}function p(x){return x!==94?i(x):(e.enter("gfmFootnoteCallMarker"),e.consume(x),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",f)}function f(x){if(o>999||x===93&&!c||x===null||x===91||qt(x))return i(x);if(x===93){e.exit("chunkString");const b=e.exit("gfmFootnoteCallString");return a.includes(fr(s.sliceSerialize(b)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):i(x)}return qt(x)||(c=!0),o++,e.consume(x),x===92?_:f}function _(x){return x===91||x===92||x===93?(e.consume(x),o++,f):f(x)}}function n3(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",_):i(S)}function _(S){if(c>999||S===93&&!h||S===null||S===91||qt(S))return i(S);if(S===93){e.exit("chunkString");const j=e.exit("gfmFootnoteDefinitionLabelString");return o=fr(s.sliceSerialize(j)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return qt(S)||(h=!0),c++,e.consume(S),S===92?x:_}function x(S){return S===91||S===92||S===93?(e.consume(S),c++,_):_(S)}function b(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),a.includes(o)||a.push(o),kt(e,v,"gfmFootnoteDefinitionWhitespace")):i(S)}function v(S){return t(S)}}function r3(e,t,i){return e.check(Fo,t,e.attempt(QR,t,i))}function s3(e){e.exit("gfmFootnoteDefinition")}function a3(e,t,i){const s=this;return kt(e,a,"gfmFootnoteDefinitionIndent",5);function a(o){const c=s.events[s.events.length-1];return c&&c[1].type==="gfmFootnoteDefinitionIndent"&&c[2].sliceSerialize(c[1],!0).length===4?t(o):i(o)}}function l3(e){let i=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:o,resolveAll:a};return i==null&&(i=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function a(c,h){let p=-1;for(;++p1?p(S):(c.consume(S),x++,v);if(x<2&&!i)return p(S);const R=c.exit("strikethroughSequenceTemporary"),E=ml(S);return R._open=!E||E===2&&!!j,R._close=!j||j===2&&!!E,h(S)}}}class o3{constructor(){this.map=[]}add(t,i,s){c3(this,t,i,s)}consume(t){if(this.map.sort(function(o,c){return o[0]-c[0]}),this.map.length===0)return;let i=this.map.length;const s=[];for(;i>0;)i-=1,s.push(t.slice(this.map[i][0]+this.map[i][1]),this.map[i][2]),t.length=this.map[i][0];s.push(t.slice()),t.length=0;let a=s.pop();for(;a;){for(const o of a)t.push(o);a=s.pop()}this.map.length=0}}function c3(e,t,i,s){let a=0;if(!(i===0&&s.length===0)){for(;a-1;){const X=s.events[ce][1].type;if(X==="lineEnding"||X==="linePrefix")ce--;else break}const W=ce>-1?s.events[ce][1].type:null,K=W==="tableHead"||W==="tableRow"?D:p;return K===D&&s.parser.lazy[s.now().line]?i(H):K(H)}function p(H){return e.enter("tableHead"),e.enter("tableRow"),f(H)}function f(H){return H===124||(c=!0,o+=1),_(H)}function _(H){return H===null?i(H):Ye(H)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(H),e.exit("lineEnding"),v):i(H):gt(H)?kt(e,_,"whitespace")(H):(o+=1,c&&(c=!1,a+=1),H===124?(e.enter("tableCellDivider"),e.consume(H),e.exit("tableCellDivider"),c=!0,_):(e.enter("data"),x(H)))}function x(H){return H===null||H===124||qt(H)?(e.exit("data"),_(H)):(e.consume(H),H===92?b:x)}function b(H){return H===92||H===124?(e.consume(H),x):x(H)}function v(H){return s.interrupt=!1,s.parser.lazy[s.now().line]?i(H):(e.enter("tableDelimiterRow"),c=!1,gt(H)?kt(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(H):S(H))}function S(H){return H===45||H===58?R(H):H===124?(c=!0,e.enter("tableCellDivider"),e.consume(H),e.exit("tableCellDivider"),j):F(H)}function j(H){return gt(H)?kt(e,R,"whitespace")(H):R(H)}function R(H){return H===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(H),e.exit("tableDelimiterMarker"),E):H===45?(o+=1,E(H)):H===null||Ye(H)?te(H):F(H)}function E(H){return H===45?(e.enter("tableDelimiterFiller"),N(H)):F(H)}function N(H){return H===45?(e.consume(H),N):H===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(H),e.exit("tableDelimiterMarker"),I):(e.exit("tableDelimiterFiller"),I(H))}function I(H){return gt(H)?kt(e,te,"whitespace")(H):te(H)}function te(H){return H===124?S(H):H===null||Ye(H)?!c||a!==o?F(H):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(H)):F(H)}function F(H){return i(H)}function D(H){return e.enter("tableRow"),ie(H)}function ie(H){return H===124?(e.enter("tableCellDivider"),e.consume(H),e.exit("tableCellDivider"),ie):H===null||Ye(H)?(e.exit("tableRow"),t(H)):gt(H)?kt(e,ie,"whitespace")(H):(e.enter("data"),fe(H))}function fe(H){return H===null||H===124||qt(H)?(e.exit("data"),ie(H)):(e.consume(H),H===92?Se:fe)}function Se(H){return H===92||H===124?(e.consume(H),fe):fe(H)}}function f3(e,t){let i=-1,s=!0,a=0,o=[0,0,0,0],c=[0,0,0,0],h=!1,p=0,f,_,x;const b=new o3;for(;++ii[2]+1){const S=i[2]+1,j=i[3]-i[2]-1;e.add(S,j,[])}}e.add(i[3]+1,0,[["exit",x,t]])}return a!==void 0&&(o.end=Object.assign({},ol(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function Vv(e,t,i,s,a){const o=[],c=ol(t.events,i);a&&(a.end=Object.assign({},c),o.push(["exit",a,t])),s.end=Object.assign({},c),o.push(["exit",s,t]),e.add(i+1,0,o)}function ol(e,t){const i=e[t],s=i[0]==="enter"?"start":"end";return i[1][s]}const p3={name:"tasklistCheck",tokenize:g3};function m3(){return{text:{91:p3}}}function g3(e,t,i){const s=this;return a;function a(p){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?i(p):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),o)}function o(p){return qt(p)?(e.enter("taskListCheckValueUnchecked"),e.consume(p),e.exit("taskListCheckValueUnchecked"),c):p===88||p===120?(e.enter("taskListCheckValueChecked"),e.consume(p),e.exit("taskListCheckValueChecked"),c):i(p)}function c(p){return p===93?(e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),h):i(p)}function h(p){return Ye(p)?t(p):gt(p)?e.check({tokenize:x3},t,i)(p):i(p)}}function x3(e,t,i){return kt(e,s,"whitespace");function s(a){return a===null?i(a):t(a)}}function _3(e){return z0([FR(),JR(),l3(e),h3(),m3()])}const b3={};function AS(e){const t=this,i=e||b3,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(_3(i)),o.push(IR()),c.push(HR(i))}const ha=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],gl={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...ha,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...ha],h2:[["className","sr-only"]],img:[...ha,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...ha,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...ha],table:[...ha],ul:[...ha,["className","contains-task-list"]],"*":["abbr","accept","acceptCharset","accessKey","action","align","alt","axis","border","cellPadding","cellSpacing","char","charOff","charSet","checked","clear","colSpan","color","cols","compact","coords","dateTime","dir","encType","frame","hSpace","headers","height","hrefLang","htmlFor","id","isMap","itemProp","label","lang","maxLength","media","method","multiple","name","noHref","noShade","noWrap","open","prompt","readOnly","rev","rowSpan","rows","rules","scope","selected","shape","size","span","start","summary","tabIndex","title","useMap","vAlign","value","width"]},clobber:["ariaDescribedBy","ariaLabelledBy","id","name"],clobberPrefix:"user-content-",protocols:{cite:["http","https"],href:["http","https","irc","ircs","mailto","xmpp"],longDesc:["http","https"],src:["http","https"]},required:{input:{disabled:!0,type:"checkbox"}},strip:["script"],tagNames:["a","b","blockquote","br","code","dd","del","details","div","dl","dt","em","h1","h2","h3","h4","h5","h6","hr","i","img","input","ins","kbd","li","ol","p","picture","pre","q","rp","rt","ruby","s","samp","section","source","span","strike","strong","sub","summary","sup","table","tbody","td","tfoot","th","thead","tr","tt","ul","var"]},Ps={}.hasOwnProperty;function v3(e,t){let i={type:"root",children:[]};const s={schema:t?{...gl,...t}:gl,stack:[]},a=RS(s,e);return a&&(Array.isArray(a)?a.length===1?i=a[0]:i.children=a:i=a),i}function RS(e,t){if(t&&typeof t=="object"){const i=t;switch(typeof i.type=="string"?i.type:""){case"comment":return y3(e,i);case"doctype":return S3(e,i);case"element":return w3(e,i);case"root":return C3(e,i);case"text":return k3(e,i)}}}function y3(e,t){if(e.schema.allowComments){const i=typeof t.value=="string"?t.value:"",s=i.indexOf("-->"),o={type:"comment",value:s<0?i:i.slice(0,s)};return Wo(o,t),o}}function S3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return Wo(i,t),i}}function w3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=DS(e,t.children),a=E3(e,t.properties);e.stack.pop();let o=!1;if(i&&i!=="*"&&(!e.schema.tagNames||e.schema.tagNames.includes(i))&&(o=!0,e.schema.ancestors&&Ps.call(e.schema.ancestors,i))){const h=e.schema.ancestors[i];let p=-1;for(o=!1;++p1){let a=!1,o=0;for(;++o-1&&o>p||c>-1&&o>c||h>-1&&o>h)return!0;let f=-1;for(;++f4&&t.slice(0,4).toLowerCase()==="data")return i}function BS(e){return function(t){return v3(t,e)}}const dl=["Romance","Fantasy","Science Fiction","Mystery","Thriller","Horror","Adventure","Historical Fiction","Contemporary Lit","Humor","Poetry","Non-Fiction","Fanfiction","Short Story","Paranormal","Werewolf","LGBTQ+","New Adult","Teen Fiction","Diverse Lit","Others"],ts=["English","Chinese","Korean","Japanese","Spanish","French","Hindi","Arabic","Portuguese","Russian","Others"];function LS(e){return e.toLowerCase().replace(/[^a-z0-9+]/g,"")}const T3=Object.fromEntries(dl.map(e=>[LS(e),e])),A3={scifi:"Science Fiction",sf:"Science Fiction",comedy:"Humor",humour:"Humor",ya:"Teen Fiction",youngadult:"Teen Fiction",lgbt:"LGBTQ+",lgbtq:"LGBTQ+","lgbtqia+":"LGBTQ+",historical:"Historical Fiction",scary:"Horror"};function Cu(e){if(!e)return null;const t=LS(e.trim());return t?T3[t]??A3[t]??null:null}function OS(e,t){const i=t.startsWith("assets/")?t.slice(7):t;return`/api/stories/${e}/asset/${i}`}function zS(e,t,i){const[s,a]=w.useState({url:null,loading:!!t,error:!1});return w.useEffect(()=>{if(!t){a({url:null,loading:!1,error:!1});return}let o=null,c=!1;return a({url:null,loading:!0,error:!1}),(async()=>{try{const h=await i(OS(e,t));if(!h.ok)throw new Error(`asset request failed (${h.status})`);const p=await h.blob();if(c)return;o=URL.createObjectURL(p),a({url:o,loading:!1,error:!1})}catch{c||a({url:null,loading:!1,error:!0})}})(),()=>{c=!0,o&&URL.revokeObjectURL(o)}},[e,t,i]),s}function Bp({storyName:e,assetPath:t,authFetch:i,alt:s,className:a}){const{url:o,loading:c,error:h}=zS(e,t,i);return h||!c&&!o?d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center",children:d.jsx("span",{className:"text-xs text-muted",children:"Image not available"})}):o?d.jsx("img",{src:o,alt:s,className:a??"w-full rounded border border-border"}):d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center","data-testid":"asset-loading",children:d.jsx("span",{className:"text-xs text-muted",children:"Loading image…"})})}function Qv(e,t,i,s){const a=t.split(/\s+/).filter(Boolean);if(a.length===0)return[""];const o=[];let c="";for(const h of a){const p=c?`${c} ${h}`:h;!c||e(p,s)<=i?c=p:(o.push(c),c=h)}return c&&o.push(c),o}function uu(e,t,i,s,a){const o=a.lineHeightFactor??1.2,c=a.speakerScale??.8,h=a.paddingX??Math.max(2,i*.06),p=a.paddingY??Math.max(2,s*.08),f=Math.max(1,i-2*h),_=Math.max(1,s-2*p),x=Math.max(a.minFontSize,a.maxFontSize),b=Math.max(1,Math.min(a.minFontSize,x)),v=j=>{const R=a.hasSpeaker?j*c:0,E=a.hasSpeaker?R*o:0,N=Math.max(1,_-E),I=a.fontWeight??400,te=Qv((ie,fe)=>e(ie,fe,I),t,f,j),F=te.length*j*o,D=te.every(ie=>e(ie,j,I)<=f+.5);return{lines:te,ok:F<=N&&D}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const j=Math.max(1,a.fontSize),{lines:R,ok:E}=v(j);return{lines:R,fontSize:j,lineHeight:j*o,speakerFontSize:a.hasSpeaker?j*c:0,overflow:!E}}for(let j=x;j>=b;j-=.5){const{lines:R,ok:E}=v(j);if(E)return{lines:R,fontSize:j,lineHeight:j*o,speakerFontSize:a.hasSpeaker?j*c:0,overflow:!1}}return{lines:Qv(e,t,f,b),fontSize:b,lineHeight:b*o,speakerFontSize:a.hasSpeaker?b*c:0,overflow:!0}}function R3(e){return{minFontSize:Math.max(1,e*.022),maxFontSize:Math.max(1,e*.05)}}const PS=["speech","narration","sfx"],D3=2;function Ar(e,t,i){return Math.min(i,Math.max(t,e))}function fl(e,t,i){return typeof e=="number"&&Number.isFinite(e)?Ar(e,t,i):void 0}function xm(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=fl(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=fl(t.lineHeightFactor,.9,2),c=fl(t.speakerScale,.5,1.5);if(!(!i&&s===void 0&&a===void 0&&o===void 0&&c===void 0))return{...i?{mode:i}:{},...s!==void 0?{fontScale:s}:{},...a!==void 0?{fontWeight:a}:{},...o!==void 0?{lineHeightFactor:o}:{},...c!==void 0?{speakerScale:c}:{}}}function Yu(e){if(!e||typeof e!="object")return;const t=e,i=fl(t.paddingX,0,.25),s=fl(t.paddingY,0,.25),a=fl(t.cornerRadius,0,.49);if(!(i===void 0&&s===void 0&&a===void 0))return{...i!==void 0?{paddingX:i}:{},...s!==void 0?{paddingY:s}:{},...a!==void 0?{cornerRadius:a}:{}}}function hu(e,t,i,s){const{minFontSize:a,maxFontSize:o}=R3(t),c=xm(e.textStyle),h=Yu(e.bubbleStyle);return{minFontSize:a,maxFontSize:o,hasSpeaker:e.type!=="sfx"&&!!e.speaker,...(c==null?void 0:c.lineHeightFactor)!==void 0?{lineHeightFactor:c.lineHeightFactor}:{},...(c==null?void 0:c.speakerScale)!==void 0?{speakerScale:c.speakerScale}:{},...(c==null?void 0:c.fontWeight)!==void 0?{fontWeight:c.fontWeight}:{},...(c==null?void 0:c.mode)==="manual"&&c.fontScale!==void 0?{fontSize:Math.max(1,t*c.fontScale)}:{},...(h==null?void 0:h.paddingX)!==void 0?{paddingX:i*h.paddingX}:{},...(h==null?void 0:h.paddingY)!==void 0?{paddingY:s*h.paddingY}:{}}}function M3(e,t,i){const s=Yu(e.bubbleStyle);return(s==null?void 0:s.cornerRadius)!==void 0?Math.min(t,i)*s.cornerRadius:void 0}function IS(e,t){const i=Math.min(e,t);return Math.max(0,Math.min(i*.4,i/2))}function Jv(e,t,i,s,a){const o=Math.max(0,i-2*s),c=Math.max(1,Math.min(a,o)/2),h=t+s+c,p=t+i-s-c;return{center:p>=h?Ar(e,h,p):t+i/2,half:c}}function HS(e,t,i,s,a,o){const c=e+i/2,h=t+s/2,p=e+a.x*i,f=t+a.y*s;if(p>=e&&p<=e+i&&f>=t&&f<=t+s)return null;const _=p-c,x=f-h,b=Math.max(6,Math.min(i,s)*.3),v=o??IS(i,s);if(Math.abs(x)>=Math.abs(_)){const E=x>=0?t+s:t,{center:N,half:I}=Jv(p,e,i,v,b);return{tip:{x:p,y:f},base1:{x:N-I,y:E},base2:{x:N+I,y:E}}}const S=_>=0?e+i:e,{center:j,half:R}=Jv(f,t,s,v,b);return{tip:{x:p,y:f},base1:{x:S,y:j-R},base2:{x:S,y:j+R}}}function B3(e){return e.type!=="speech"||!e.tailAnchor?!1:HS(0,0,1,1,e.tailAnchor)!==null}function L3(e,t,i,s,a,o){const c=o??IS(i,s),h=e+i,p=t+s,f=!!a&&a.base1.y===t&&a.base2.y===t,_=!!a&&a.base1.x===h&&a.base2.x===h,x=!!a&&a.base1.y===p&&a.base2.y===p,b=!!a&&a.base1.x===e&&a.base2.x===e,v=[{k:"M",x:e+c,y:t}];return f&&a&&v.push({k:"L",x:a.base1.x,y:t},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:a.base2.x,y:t}),v.push({k:"L",x:h-c,y:t},{k:"A",cornerX:h,cornerY:t,x:h,y:t+c,r:c}),_&&a&&v.push({k:"L",x:h,y:a.base1.y},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:h,y:a.base2.y}),v.push({k:"L",x:h,y:p-c},{k:"A",cornerX:h,cornerY:p,x:h-c,y:p,r:c}),x&&a&&v.push({k:"L",x:a.base2.x,y:p},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:a.base1.x,y:p}),v.push({k:"L",x:e+c,y:p},{k:"A",cornerX:e,cornerY:p,x:e,y:p-c,r:c}),b&&a&&v.push({k:"L",x:e,y:a.base2.y},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:e,y:a.base1.y}),v.push({k:"L",x:e,y:t+c},{k:"A",cornerX:e,cornerY:t,x:e+c,y:t,r:c}),v}function O3(e,t,i,s,a,o){const c=L3(e,t,i,s,a,o).map(h=>h.k==="A"?`A ${h.r} ${h.r} 0 0 1 ${h.x} ${h.y}`:`${h.k} ${h.x} ${h.y}`);return c.push("Z"),c.join(" ")}function z3(e){return e.x<-1e-6||e.y<-1e-6||e.x+e.width>1+1e-6||e.y+e.height>1+1e-6}let ey=0;function Lp(e,t=.1,i=.1){return ey++,{id:`overlay-${Date.now()}-${ey}`,type:e,x:t,y:i,width:e==="sfx"?.15:.25,height:e==="sfx"?.08:.12,text:"",...e==="speech"?{speaker:"",tailAnchor:{x:.5,y:1.2}}:{}}}function US(e,t,i){return{width:Math.min(e==="sfx"?.3:.5,Math.max(.15,1-t)),height:Math.min(e==="sfx"?.1:.2,Math.max(.06,1-i))}}const du=.05;function Ui(e){return typeof e=="number"&&Number.isFinite(e)}function P3(e,t,i){const s=e.toLowerCase(),a=/\bleft\b/.test(s),o=/\bright\b/.test(s),c=/\b(?:top|upper)\b/.test(s),h=/\b(?:bottom|lower)\b/.test(s),p=/\b(?:center|centre|middle)\b/.test(s);if(!a&&!o&&!c&&!h&&!p)return null;const f=a?du:Ar(o?1-t-du:(1-t)/2,0,1),_=c?du:Ar(h?1-i-du:(1-i)/2,0,1);return{x:f,y:_}}let I3=0;function H3(e){if(!e||typeof e!="object")return null;const t=e,i=PS.includes(t.type)?t.type:"speech",s=typeof t.text=="string"?t.text:"";let a=Ui(t.width)&&t.width>0?t.width:i==="sfx"?.15:.4,o=Ui(t.height)&&t.height>0?t.height:i==="sfx"?.08:.16,c,h;if(Ui(t.x)&&Ui(t.y))c=t.x,h=t.y;else{const b=typeof t.position=="string"?P3(t.position,a,o):null;if(!b)return null;c=b.x,h=b.y}c=Ar(c,0,1),h=Ar(h,0,1),a=Ar(a,.02,1),o=Ar(o,.02,1);const f={id:typeof t.id=="string"&&t.id?t.id:`overlay-norm-${++I3}`,type:i,x:c,y:h,width:a,height:o,text:s};if(i==="speech"){f.speaker=typeof t.speaker=="string"?t.speaker:"";const b=t.tailAnchor;f.tailAnchor=b&&Ui(b.x)&&Ui(b.y)?{x:b.x,y:b.y}:{x:.5,y:1.2}}else typeof t.speaker=="string"&&t.speaker&&(f.speaker=t.speaker);const _=xm(t.textStyle),x=Yu(t.bubbleStyle);return _&&(f.textStyle=_),x&&(f.bubbleStyle=x),f}function U3(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&!!t.id&&PS.includes(t.type)&&Ui(t.x)&&Ui(t.y)&&Ui(t.width)&&Ui(t.height)&&typeof t.text=="string"}function $3(e){const t=Array.isArray(e)?e:[],i=[],s=[];let a=!Array.isArray(e);return t.forEach((o,c)=>{const h=H3(o);if(!h){s.push({index:c,reason:"overlay has no numeric x/y/width/height and no recognizable position"}),a=!0;return}i.push(h),U3(o)||(a=!0)}),{overlays:i,changed:a,invalid:s}}function e4(e){for(let t=0;t0&&i.height>0))return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid geometry — repair or re-place it in the lettering editor before export`};const a=xm(i==null?void 0:i.textStyle);if(i!=null&&i.textStyle&&!a)return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid typography controls — reset them in the lettering editor before export`};const o=Yu(i==null?void 0:i.bubbleStyle);if(i!=null&&i.bubbleStyle&&!o)return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid bubble controls — reset them in the lettering editor before export`}}return{valid:!0}}const ty=new Set(["speech","narration"]),F3=.12;function iy(e){return Ui(e==null?void 0:e.x)&&Ui(e==null?void 0:e.y)&&Ui(e==null?void 0:e.width)&&Ui(e==null?void 0:e.height)&&e.width>0&&e.height>0}function q3(e,t=F3){const i=[];for(let s=0;s0?f/_:0;x>=t&&i.push({indexA:s,indexB:o,idA:a.id,idB:c.id,ratio:x})}}return i}function In(e){return e.kind==="text"}function W3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||In(e)?{key:"letter",label:"Letter this cut",opensEditor:!0}:{key:"add-art",label:"Add clean art for this cut",opensEditor:!1}}function $S(e,t=D3){return!e.finalImagePath||!(e.overlays??[]).some(B3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ny,height:Math.round(ny*s/i)}}function fu({cut:e}){return e.dialogue.length>0||e.narration||e.sfx?d.jsxs("div",{className:"space-y-1.5","data-testid":`cut-${e.id}-overlay`,children:[e.dialogue.map((i,s)=>d.jsxs("div",{className:"flex gap-2 text-xs",children:[d.jsxs("span",{className:"font-medium text-foreground flex-shrink-0",children:[i.speaker,":"]}),d.jsx("span",{className:"text-foreground",children:i.text})]},s)),e.narration&&d.jsx("div",{className:"border-l-2 border-border pl-3",children:d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})}),e.sfx&&d.jsxs("p",{className:"text-xs font-mono text-muted",children:["SFX: ",e.sfx]})]}):null}function Y3({cut:e,storyName:t,authFetch:i,onEditCut:s}){const a=!!e.finalImagePath,o=!!e.cleanImagePath,c=a||o,h=e.dialogue.length>0||!!e.narration||!!e.sfx,p=e.kind==="text";return d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:"text-[10px] font-mono text-muted bg-surface border border-border rounded px-1.5 py-0.5",children:["#",e.id]}),d.jsx("span",{className:"text-[10px] font-mono text-muted",children:e.shotType}),e.characters.length>0&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:e.characters.join(", ")})]}),a&&d.jsx(Bp,{storyName:t,assetPath:e.finalImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),!a&&o&&d.jsxs("div",{className:"border border-border rounded overflow-hidden",children:[d.jsx(Bp,{storyName:t,assetPath:e.cleanImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),d.jsx("div",{className:"px-3 py-2 bg-surface/80 border-t border-border",children:d.jsx(fu,{cut:e})})]}),!c&&p&&d.jsxs("div",{className:"w-full border border-border rounded p-4 space-y-2",style:{background:e.background||void 0},"data-testid":`cut-${e.id}-textpanel`,children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Text panel"}),h?d.jsx(fu,{cut:e}):d.jsx("p",{className:"text-xs text-muted italic",children:"Empty text panel — open the editor to add text."})]}),!c&&!p&&d.jsxs("div",{className:"w-full bg-surface border border-dashed border-border rounded p-4 space-y-2","data-testid":`cut-${e.id}-pending`,children:[d.jsxs("div",{className:"aspect-video flex flex-col items-center justify-center gap-1 text-center",children:[d.jsx("span",{className:"text-xs text-muted font-medium",children:"Image pending"}),d.jsx("span",{className:"text-[10px] text-muted",children:"Planned image cut — generate & upload the art"})]}),h&&d.jsxs("div",{className:"border-t border-dashed border-border pt-2 space-y-1",children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Planned text (will be lettered onto the image)"}),d.jsx(fu,{cut:e})]})]}),e.description&&d.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&d.jsx(fu,{cut:e}),s&&(()=>{const f=W3(e);return d.jsx("button",{type:"button","data-testid":`cut-${e.id}-cta`,"data-cut-action":f.key,onClick:()=>s(e.id,f.opensEditor),className:"w-full px-3 py-1.5 text-xs font-medium rounded bg-accent text-white hover:bg-accent-dim",children:f.label})})()]})}function K3({storyName:e,fileName:t,authFetch:i,onEditCut:s}){const[a,o]=w.useState(null),[c,h]=w.useState(!0),[p,f]=w.useState(null),_=t.replace(/\.md$/,""),x=w.useCallback(async()=>{h(!0),f(null);try{const b=await i(`/api/stories/${e}/cuts/${_}`);if(b.status===404){o(null),h(!1);return}if(!b.ok){const S=await b.json();f(S.error||"Failed to load cuts"),h(!1);return}const v=await b.json();o(v)}catch{f("Failed to load cuts")}finally{h(!1)}},[i,e,_]);return w.useEffect(()=>{x();const b=setInterval(x,5e3);return()=>clearInterval(b)},[x]),c&&!a?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Loading cuts..."}):p?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:p}),d.jsxs("p",{className:"text-xs text-muted max-w-sm",children:[_,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema shown in the cartoon writing instructions."]}),d.jsx("button",{onClick:x,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]}):!a||a.cuts.length===0?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]}):d.jsx("div",{className:"h-full overflow-y-auto",children:d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6 space-y-6",children:a.cuts.map(b=>d.jsx(Y3,{cut:b,storyName:e,authFetch:i,onEditCut:s},b.id))})})}const ry=/!\[[^\]]*\]\([^)]*\)/g,V3=//g,FS=200;function X3(e){const t=(e.match(ry)||[]).length,i=e.length,s=e.replace(V3," ").replace(ry," ").replace(/\s+/g," ").trim();return{imageCount:t,charCount:i,nonImageProse:s,nonImageProsePreview:s.slice(0,FS)}}function Z3(e){return`${e}: re-export required before publish — this final image uses an older speech-bubble tail style that can show a visible seam`}const Q3=[/placeholder only/i,/\bOWS (?:should )?generates? the publish markdown/i,/generate(?:s|d)? the publish markdown from/i,/after clean images are approved/i,/lettered final images are created/i,/do not hand-?write/i,/\b(?:TODO|FIXME)\b/];function J3(e){for(const t of Q3){const i=e.match(t);if(i)return i[0]}return null}function _m(e,t){const i=``,s=``,a=e.indexOf(i),o=e.indexOf(s);return a===-1||o===-1||ob[1].trim());x.length===0?i.push(`${p}: block has no image reference`):x.length>1?i.push(`${p}: block must contain exactly one image reference`):h.uploadedUrl&&x[0]!==h.uploadedUrl&&i.push(`${p}: image URL does not match the recorded uploaded URL`)}/awaiting upload|image pending|final image pending|pending upload/i.test(e)&&i.push("Markdown contains awaiting-upload placeholders");const s=J3(e);s&&i.push(`This episode still has placeholder/instructional text ("${s.slice(0,60)}") — remove it or re-run “Prepare episode for publish” so the published episode is images only`);const a=new Set(t.map(c=>c.uploadedUrl).filter(c=>!!c&&/^https?:\/\//i.test(c))),o=[...e.matchAll(/!\[[^\]]*\]\(([^)]*)\)/g)];for(const c of o){const h=c[1].trim();/^https?:\/\//i.test(h)?a.has(h)||i.push(`Image reference is not a recorded uploaded cut URL: ${h.slice(0,60)}`):i.push(`Invalid image reference (not an http(s) URL): ${h.slice(0,60)}`)}return e.length>1e4&&i.push(`Markdown is ${e.length} chars (limit 10,000)`),{ready:i.length===0,issues:i}}function WS(e,t){const i=t.length;if(i===0)return{stage:"not-started",issues:[],awaitingCount:0,totalCuts:0};if(eD(e,t))return{stage:"planning",issues:[],awaitingCount:0,totalCuts:i};const{ready:s,issues:a}=qS(e,t);if(s)return{stage:"ready",issues:[],awaitingCount:0,totalCuts:i};const o=new Set;for(let p=0;p!c.has(p));return h.length>0?{stage:"error",issues:h,awaitingCount:o.size,totalCuts:i}:{stage:"awaiting-upload",issues:[],awaitingCount:o.size,totalCuts:i}}const Df=[{key:"assemble",title:"Prepare the episode for publish",test:/markdown block|missing or incomplete/i},{key:"export",title:"Export final images",test:/re-export|older speech-bubble|visible seam/i},{key:"upload",title:"Upload final images",test:/not uploaded|no recorded uploaded url/i},{key:"images",title:"Fix image references",test:/image reference|not an http|does not match|exactly one image/i},{key:"cleanup",title:"Remove leftover text",test:/placeholder|instructional|awaiting-upload|awaiting upload/i},{key:"size",title:"Shorten the episode",test:/\blimit\b|\bchars\b/i}];function tD(e){const t=new Map,i=[],s=[];for(const o of e){const c=o.match(/^Cut (\d+): (.+)$/);if(c){const h=c[2];t.has(h)||(t.set(h,[]),i.push(h)),t.get(h).push(Number(c[1]))}else s.push(o)}return[...i.map(o=>{const c=t.get(o).slice().sort((p,f)=>p-f);return`${c.length===1?`Cut ${c[0]}`:`Cuts ${c.join(", ")}`}: ${o}`}),...s]}function GS(e){const t=c=>{var h;return((h=Df.find(p=>p.test.test(c)))==null?void 0:h.key)??"other"},i=new Map;for(const c of e){const h=t(c);i.has(h)||i.set(h,[]),i.get(h).push(c)}const s=[...Df.map(c=>c.key),"other"],a=c=>{var h;return((h=Df.find(p=>p.key===c))==null?void 0:h.title)??"Other issues"},o=[];for(const c of s){const h=i.get(c);!h||h.length===0||o.push({key:c,title:a(c),lines:tD(h)})}return o}const iD=220,Mf=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function bm(e){const t=[],i=[],s=e??"",a=s.match(/^#[ \t]+(.+)$/m),o=!!(a&&a[1].trim());o||t.push("Add a “# Title” heading — the Story opening needs a real title readers see first.");const c=s.replace(/^#\s+.+$/m,"").trim();if(c.lengthx.trim()).filter(Boolean),p=h.filter(x=>/^([-*+]|\d+[.)])\s/.test(x)||Mf.test(x)).length,f=c.split(/\n\s*\n/).map(x=>x.trim()).filter(Boolean),_=f.some(x=>x.length>=120&&!/^([-*+]|\d+[.)])\s/.test(x)&&!Mf.test(x));h.length>0&&p/h.length>=.5||!_?t.push("This reads like a synopsis or outline. Write the Genesis as a reader-facing opening scene that sets up the first beat and stakes, then bridges into Episode 01 — not a logline, genre pitch, or character list."):f.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Mf.test(b)).length<2&&t.push("Give the opening room to build: open across a few short paragraphs — the premise, what the lead wants, and the hook — that lead into Episode 01, instead of a single dense block that drops readers into a cold scene.")}return{hasTitle:o,blockers:t,warnings:i}}function nD(e){return/\.(webp|jpe?g)$/i.test(e)}function Op(e){var c,h;let t=0,i=0,s=0,a=0,o=0;for(const p of e)In(p)?(((h=p.overlays)==null?void 0:h.length)??0)>0&&s++:(t++,p.cleanImagePath&&nD(p.cleanImagePath)&&(i++,(((c=p.overlays)==null?void 0:c.length)??0)>0&&s++)),p.finalImagePath&&p.exportedAt&&a++,p.uploadedUrl&&o++;return{total:e.length,needClean:t,withClean:i,withText:s,exported:a,uploaded:o}}const rD={plan:"Plan cuts",clean:"Create clean images",letter:"Add speech bubbles & captions",export:"Export final images",upload:"Upload final images",publish:"Publish to PlotLink"};function vo(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function sD(e){const{cuts:t,published:i=!1}=e,s=Op(t);if(s.total===0)return{steps:[],nextStep:null};const a=s.total>0,o=a&&s.withClean===s.needClean,c=o&&s.withText===s.total,h=c&&s.exported===s.total,p=h&&s.uploaded===s.total,_={plan:a,clean:o,letter:c,export:h,upload:p,publish:p&&i},x=["plan","clean","letter","export","upload","publish"],b=x.findIndex(N=>!_[N]),v=N=>s.needClean>0?vo(N,s.needClean):"no image cuts",S={plan:vo(s.total,s.total),clean:v(s.withClean),letter:vo(s.withText,s.total),export:vo(s.exported,s.total),upload:vo(s.uploaded,s.total),publish:null},j=x.map((N,I)=>({key:N,label:rD[N],status:b===-1||IFS,a=oD({stage:t,imageCount:i.imageCount,hasNonImageProse:i.nonImageProse.length>0});return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"cartoon-publish-preview",children:[d.jsxs("div",{className:"px-4 py-2 border-b border-border text-[10px] text-muted flex flex-wrap items-center gap-x-3 gap-y-1","data-testid":"cartoon-publish-summary",children:[d.jsxs("span",{children:[i.imageCount," image",i.imageCount===1?"":"s"]}),d.jsxs("span",{children:[i.charCount.toLocaleString()," / 10,000 chars"]}),d.jsx("span",{className:`rounded-full px-2 py-0.5 font-medium ${a.possible?"bg-green-100 text-green-800":"bg-background text-muted"}`,"data-testid":"publish-possible",children:a.possible?"Publish possible":"Publish not possible yet"}),d.jsx("span",{className:`rounded-full px-2 py-0.5 font-medium ${a.recommended?"bg-green-100 text-green-800":a.tone==="warning"?"bg-amber-100 text-amber-800":"bg-background text-muted"}`,"data-testid":"publish-recommended",children:a.recommended?"Recommended":"Not recommended yet"})]}),d.jsxs("div",{className:`px-4 py-2 border-b text-[11px] ${uD[a.tone]}`,"data-testid":"cartoon-publish-verdict",children:[d.jsx("p",{className:"font-medium",children:a.headline}),a.detail&&d.jsx("p",{className:"mt-0.5 opacity-90",children:a.detail}),a.action&&d.jsxs("p",{className:"mt-0.5 opacity-90",children:["→ ",a.action]})]}),i.nonImageProse&&d.jsxs("div",{className:"px-4 py-2 border-b border-amber-300 bg-amber-50 text-[11px] text-amber-800","data-testid":"cartoon-nonimage-prose",children:[d.jsx("p",{className:"font-medium",children:"⚠ Non-image text in the published markdown:"}),d.jsxs("p",{className:"font-mono mt-1 whitespace-pre-wrap break-words",children:[i.nonImageProsePreview,s?"…":""]}),d.jsx("p",{className:"mt-1",children:"This text publishes verbatim around the comic images. Remove it (or re-run “Prepare episode for publish”) if it is planning or placeholder prose."})]}),d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6",children:e.trim()?d.jsx("div",{className:"prose max-w-none",children:d.jsx(rS,{remarkPlugins:[aS,AS],rehypePlugins:[[BS,cD]],children:e})}):d.jsx("p",{className:"text-muted italic text-sm","data-testid":"cartoon-publish-empty",children:"No publish markdown yet — build it from the cut plan (Edit → Upload & Prepare for Publish)."})})]})}const dD="modulepreload",fD=function(e){return"/"+e},sy={},ay=function(t,i,s){let a=Promise.resolve();if(i&&i.length>0){let c=function(f){return Promise.all(f.map(_=>Promise.resolve(_).then(x=>({status:"fulfilled",value:x}),x=>({status:"rejected",reason:x}))))};document.getElementsByTagName("link");const h=document.querySelector("meta[property=csp-nonce]"),p=(h==null?void 0:h.nonce)||(h==null?void 0:h.getAttribute("nonce"));a=c(i.map(f=>{if(f=fD(f),f in sy)return;sy[f]=!0;const _=f.endsWith(".css"),x=_?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${x}`))return;const b=document.createElement("link");if(b.rel=_?"stylesheet":dD,_||(b.as="script"),b.crossOrigin="",b.href=f,p&&b.setAttribute("nonce",p),document.head.appendChild(b),_)return new Promise((v,S)=>{b.addEventListener("load",v),b.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${f}`)))})}))}function o(c){const h=new Event("vite:preloadError",{cancelable:!0});if(h.payload=c,window.dispatchEvent(h),!h.defaultPrevented)throw c}return a.then(c=>{for(const h of c||[])h.status==="rejected"&&o(h.reason);return t().catch(o)})},vm=[{family:"Noto Sans",googleFontsId:"Noto+Sans",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans/about",category:"body",weights:[400,500,700],languages:["English","Spanish","French","Portuguese","Russian","Others"]},{family:"Noto Sans KR",googleFontsId:"Noto+Sans+KR",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+KR/about",category:"body",weights:[400,500,700],languages:["Korean"]},{family:"Noto Sans JP",googleFontsId:"Noto+Sans+JP",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+JP/about",category:"body",weights:[400,500,700],languages:["Japanese"]},{family:"Noto Sans SC",googleFontsId:"Noto+Sans+SC",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+SC/about",category:"body",weights:[400,500,700],languages:["Chinese"]},{family:"Noto Sans Devanagari",googleFontsId:"Noto+Sans+Devanagari",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+Devanagari/about",category:"body",weights:[400,500,700],languages:["Hindi"]},{family:"Noto Naskh Arabic",googleFontsId:"Noto+Naskh+Arabic",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Naskh+Arabic/about",category:"body",weights:[400,500,700],languages:["Arabic"]},{family:"Bangers",googleFontsId:"Bangers",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/specimen/Bangers/about",category:"display",weights:[400],languages:[]}],pD="system-ui, sans-serif",mD=vm.find(e=>e.family==="Noto Sans"),gD=vm.find(e=>e.category==="display");function xD(e){return vm.find(i=>i.category==="body"&&i.languages.includes(e))||mD}function _D(){return gD}function bD(e){const t=e.weights.join(";");return`https://fonts.googleapis.com/css2?family=${e.googleFontsId}:wght@${t}&display=swap`}function ly(e){return`"${e.family}", ${pD}`}function vD(e,t={}){var a,o,c,h;const i=!t.staleExport&&(!!e.finalImagePath||!!e.exportedAt),s=!t.staleExport&&(!!e.uploadedUrl||!!e.uploadedCid);return{hasCleanImage:!!e.cleanImagePath,hasScriptText:(((a=e.dialogue)==null?void 0:a.length)??0)>0||!!((o=e.narration)!=null&&o.trim())||!!((c=e.sfx)!=null&&c.trim()),bubblesPlaced:((h=e.overlays)==null?void 0:h.length)??0,exported:i,uploaded:s}}function ul(e){return JSON.stringify((e??[]).map(t=>[t.type,t.x,t.y,t.width,t.height,t.text,t.speaker??"",t.tailAnchor??null,t.textStyle??null,t.bubbleStyle??null]))}function yD(e){return!e.exported&&!e.uploaded?!1:e.baselineSig!==ul(e.current)}function ym(e){var i,s;const t=[];return(e.dialogue??[]).forEach((a,o)=>{var c;(c=a==null?void 0:a.text)!=null&&c.trim()&&t.push({type:"speech",speaker:a.speaker,text:a.text.trim(),key:`speech-${o}`})}),(i=e.narration)!=null&&i.trim()&&t.push({type:"narration",text:e.narration.trim(),key:"narration"}),(s=e.sfx)!=null&&s.trim()&&t.push({type:"sfx",text:e.sfx.trim(),key:"sfx"}),t}function SD(e,t,i){if(e==="narration")return{x:.08,y:.05+Math.min(t,2)*.18};if(e==="sfx"){const c=t%2,h=Math.floor(t/2);return{x:c===0?.1:.62,y:.68+h*.12}}const s=Math.floor(t/2),a=t%2===0,o=.08+s*Math.max(.15,Math.min(.22,i>4?.16:.2));return{x:a?.05:.45,y:o}}function oy(e){const t=ym(e);return t.map((i,s)=>{const{x:a,y:o}=SD(i.type,s,t.length),c=Lp(i.type,a,o),h=US(i.type,a,o);return{...c,...h,text:i.text,...i.type==="speech"?{speaker:i.speaker??""}:{}}})}function wn(e,t){return e*t}function cy(e,t){return t===0?0:e/t}function uy(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=bD(e),document.head.appendChild(i)}const ku={speech:"Speech",narration:"Narration",sfx:"SFX"},wD={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Bf(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:ku[e.type]}const hy=.05,CD=[{key:"down",label:"Down",anchor:{x:.5,y:1.2}},{key:"up",label:"Up",anchor:{x:.5,y:-.2}},{key:"left",label:"Left",anchor:{x:-.2,y:.5}},{key:"right",label:"Right",anchor:{x:1.2,y:.5}}];function pu(e,t,i){return Math.min(i,Math.max(t,e))}function kD({storyName:e,cut:t,plotFile:i,onSave:s,onClose:a,onExported:o,language:c="English",authFetch:h,targetLabel:p,returnOnSave:f=!1,workspaceVisible:_=!1,onToggleWorkspaceVisible:x}){var Wt,ui,Bt,vt,At,Ze,hi;const b=xD(c),v=_D(),S=ly(b),j=ly(v);w.useEffect(()=>{uy(b),uy(v)},[b,v]),w.useEffect(()=>{let P=!1;return K(!1),(async()=>{try{const{ensureFontsReady:we}=await ay(async()=>{const{ensureFontsReady:ze}=await import("./export-cut-CDJl8Zjg.js");return{ensureFontsReady:ze}},[]);await we([b.family,v.family])}catch{}P||K(!0)})(),()=>{P=!0}},[b.family,v.family]);const R=zS(e,t.cleanImagePath,h),E=w.useMemo(()=>$3(t.overlays),[t.overlays]),N=E.invalid.length,[I,te]=w.useState(!1),F=N===0&&E.changed&&E.overlays.length>0,[D,ie]=w.useState(()=>E.overlays),[fe,Se]=w.useState(()=>ul(E.overlays)),H=w.useRef(null),ce=w.useCallback(P=>(we,ze,Re=400)=>{var $e;!H.current&&typeof document<"u"&&(H.current=document.createElement("canvas"));const Ge=($e=H.current)==null?void 0:$e.getContext("2d");return Ge?(Ge.font=`${Re} ${ze}px ${P}`,Ge.measureText(we).width):we.length*ze*.5},[]),[W,K]=w.useState(!1),[X,U]=w.useState(null),[A,O]=w.useState(!1),[$,xe]=w.useState(!1),[T,M]=w.useState(null),[G,C]=w.useState(null),[V,ne]=w.useState({x:0,y:0,width:0,height:0}),ae=w.useRef(null),Y=w.useRef(null),he=w.useRef(null),_e=w.useCallback(()=>{const P=ae.current;if(!P)return;const we=P.clientWidth,ze=P.clientHeight;let Re,Ge;if(t.kind==="text"){const lt=G3(t.aspectRatio)??{width:800,height:600};Re=lt.width,Ge=lt.height}else{const lt=Y.current;if(!lt||!lt.naturalWidth)return;Re=lt.naturalWidth,Ge=lt.naturalHeight}if(!we||!ze)return;const $e=Math.min(we/Re,ze/Ge),ht=Re*$e,dt=Ge*$e;ne({x:(we-ht)/2,y:(ze-dt)/2,width:ht,height:dt})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const P=ae.current;if(!P)return;const we=new ResizeObserver(()=>_e());return we.observe(P),()=>we.disconnect()},[_e]);const Be=w.useCallback(P=>{const we=US(P.type,P.x,P.y),ze=we.width,Re=Math.max(.08,1-P.y);if(!P.text||!W||V.width<=0)return we;const Ge=P.type==="sfx"?j:S,$e=wn(ze,V.width);let ht=P.type==="sfx"?.08:.12;for(let dt=0;dt<24;dt++){const lt=Math.min(ht,Re),Vt=wn(lt,V.height);if(!uu(ce(Ge),P.text,$e,Vt,hu({...P},V.height||300,$e,Vt)).overflow||lt>=Re)return{width:ze,height:lt};ht+=.03}return{width:ze,height:Math.min(ht,Re)}},[W,V,ce,S,j]),Le=w.useCallback(P=>{const we=Lp(P,.1+Math.random()*.3,.1+Math.random()*.3),ze={...we,...Be(we)};ie(Re=>[...Re,ze]),U(ze.id)},[Be]),je=w.useCallback(P=>{const ze={...Lp(P.type,.1+Math.random()*.3,.1+Math.random()*.3),text:P.text,...P.type==="speech"&&P.speaker?{speaker:P.speaker}:{}},Re={...ze,...Be(ze)};ie(Ge=>[...Ge,Re]),U(Re.id)},[Be]),be=w.useCallback((P,we)=>{ie(ze=>ze.map(Re=>Re.id===P?{...Re,...we}:Re))},[]),tt=w.useCallback(P=>{var ht;const we=V.height||300,ze=V.width>0?wn(P.width,V.width):200,Re=V.height>0?wn(P.height,V.height):100,Ge=P.type==="sfx"?j:S,$e=uu(ce(Ge),P.text,ze,Re,hu({...P,textStyle:void 0},we,ze,Re));be(P.id,{textStyle:{mode:"manual",fontScale:$e.fontSize/Math.max(1,we),fontWeight:((ht=P.textStyle)==null?void 0:ht.fontWeight)??400,lineHeightFactor:$e.fontSize>0?$e.lineHeight/$e.fontSize:1.2,speakerScale:$e.fontSize>0&&$e.speakerFontSize>0?$e.speakerFontSize/$e.fontSize:.8}})},[V,j,S,ce,be]),St=w.useCallback(P=>{ie(we=>we.filter(ze=>ze.id!==P)),U(null),O(!1)},[]),ot=w.useCallback(()=>{U(null),O(!1)},[]),We=w.useCallback((P,we)=>{P.stopPropagation(),U(we),O(!1)},[]),Mt=w.useCallback((P,we,ze)=>{P.stopPropagation(),P.preventDefault();const Re=D.find(Ge=>Ge.id===we);Re&&(U(we),he.current={id:we,mode:ze,startX:P.clientX,startY:P.clientY,origX:Re.x,origY:Re.y,origW:Re.width,origH:Re.height})},[D]);w.useEffect(()=>{const P=ze=>{const Re=he.current;if(!Re||V.width===0)return;const Ge=cy(ze.clientX-Re.startX,V.width),$e=cy(ze.clientY-Re.startY,V.height);if(Re.mode==="move"){const ht=pu(Re.origX+Ge,0,1-Re.origW),dt=pu(Re.origY+$e,0,1-Re.origH);be(Re.id,{x:ht,y:dt})}else{const ht=pu(Re.origW+Ge,hy,1-Re.origX),dt=pu(Re.origH+$e,hy,1-Re.origY);be(Re.id,{width:ht,height:dt})}},we=()=>{he.current=null};return window.addEventListener("mousemove",P),window.addEventListener("mouseup",we),()=>{window.removeEventListener("mousemove",P),window.removeEventListener("mouseup",we)}},[V,be]);const He=w.useCallback(async()=>{var P;C(null);try{const we=ul(D),ze=((P=t.aiDraft)==null?void 0:P.status)==="generated"&&we!==(t.aiDraft.baseSig??"")?{...t.aiDraft,status:"edited",updatedAt:new Date().toISOString()}:t.aiDraft??void 0;await s(D,ze??null),f&&a()}catch(we){C(we instanceof Error?we.message:"Failed to save overlays")}},[D,s,a,f,t.aiDraft]),xt=w.useCallback(async()=>{if(N>0&&!I){const P=N;M(`${P} overlay${P===1?"":"s"} from the cut plan ${P===1?"has":"have"} no usable position and cannot be exported — re-place ${P===1?"it":"them"} or discard ${P===1?"it":"them"} first.`);return}xe(!0),M(null);try{await s(D);const{exportCut:P,ensureFontsReady:we}=await ay(async()=>{const{exportCut:ft,ensureFontsReady:Fi}=await import("./export-cut-CDJl8Zjg.js");return{exportCut:ft,ensureFontsReady:Fi}},[]),ze=D.some(ft=>ft.type==="sfx"),Re=[b.family,...ze?[v.family]:[]],{ready:Ge,missing:$e}=await we(Re);if(!Ge){M(`Fonts not loaded: ${$e.join(", ")}. Check your connection and retry.`),xe(!1);return}if(t.cleanImagePath&&!R.url){M(R.error?"Clean image failed to load — cannot export. Retry once it renders.":"Clean image still loading — wait for it to render, then export."),xe(!1);return}const ht=R.url,dt=await P(ht,D,S,j,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),lt=new FormData,Vt=dt.type==="image/webp"?"webp":"jpg";lt.append("file",dt,`cut-${t.id}.${Vt}`);const Ci=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:lt});if(Ci.ok)Se(ul(D)),o==null||o();else{const ft=await Ci.json();M(ft.error||"Export failed")}}catch(P){M(P instanceof Error?P.message:"Export failed")}finally{xe(!1)}},[t,R,D,e,i,b,v,S,j,h,s,o,N,I]),Ae=D.find(P=>P.id===X),Kt=w.useMemo(()=>q3(D),[D]),mi=w.useRef(t.id);w.useEffect(()=>{mi.current!==t.id&&(mi.current=t.id,Se(ul(E.overlays)))},[t.id,E.overlays]);const wt=yD({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:fe,current:D}),Qe=w.useMemo(()=>vD({...t,overlays:D},{staleExport:wt}),[t,D,wt]),Q=w.useMemo(()=>ym(t),[t]),ge=w.useMemo(()=>{const P={};for(const we of D){const ze=z3(we);let Re=!1;if(W&&V.width>0&&we.text){const Ge=we.type==="sfx"?j:S,$e=wn(we.width,V.width),ht=wn(we.height,V.height);Re=uu(ce(Ge),we.text,$e,ht,hu(we,V.height||300,$e,ht)).overflow}(ze||Re)&&(P[we.id]={outOfBounds:ze,overflow:Re})}return P},[D,W,V,ce,S,j]),Te=Object.keys(ge).length,Ue=t.kind==="text",it=!t.cleanImagePath;return!Ue&&it&&D.length===0&&!t.narration&&!((Wt=t.dialogue)!=null&&Wt.length)?d.jsx("div",{className:"h-full flex items-center justify-center text-sm text-muted",children:"No clean image — upload one first, or add overlays for a narration cut."}):d.jsxs("div",{className:"h-full flex flex-col","data-testid":"focused-lettering-editor",children:[d.jsxs("div",{className:"px-4 py-3 border-b border-border bg-surface/40 flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-[10px] font-bold uppercase tracking-[0.16em] text-accent",children:"Focused lettering editor"}),d.jsx("span",{className:"text-xs font-mono text-muted",children:p??`Cut #${t.id}`})]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Place bubbles, captions, SFX, or between-scene card text, then save back to the full cut review."}),d.jsxs("span",{className:"text-[10px] text-muted","data-testid":"overlay-count",children:[D.length," overlays"]})]}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap justify-end",children:[d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:text-foreground","data-testid":"return-to-cut-review-btn",children:"Back to cut review"}),x&&d.jsx("button",{onClick:x,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:border-accent hover:text-accent","data-testid":"toggle-work-area-btn",children:_?"Hide work area":"Show work area"}),d.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[d.jsx("button",{onClick:()=>Le("speech"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-speech",children:"Speech"}),d.jsx("button",{onClick:()=>Le("narration"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-narration",children:"Narration"}),d.jsx("button",{onClick:()=>Le("sfx"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-sfx",children:"SFX"})]}),T&&d.jsx("span",{className:"text-[10px] text-error",children:T}),G&&d.jsx("span",{className:"text-[10px] text-error",children:G}),d.jsx("button",{onClick:xt,disabled:$,className:"px-3 py-1 text-xs border border-accent text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"export-btn",children:$?"Exporting...":"Export"}),d.jsx("button",{onClick:()=>{He()},className:"px-3 py-1 text-xs bg-accent text-white rounded hover:bg-accent-dim","data-testid":"save-lettering-btn",children:"Save"}),d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs text-muted hover:text-foreground border border-border rounded","data-testid":"cancel-lettering-btn",children:"Cancel"})]})]}),N>0&&!I?d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-error/10 text-[10px] text-error flex items-center gap-2 flex-wrap","data-testid":"overlay-repair-note",children:[d.jsxs("span",{children:[N," overlay",N===1?"":"s"," ","from the cut plan ",N===1?"has":"have"," no usable position and cannot be exported. Re-place"," ",N===1?"it":"them",", or"]}),d.jsxs("button",{onClick:()=>te(!0),"data-testid":"discard-invalid-overlays",className:"px-1.5 py-0.5 border border-error/40 rounded hover:bg-error/10",children:["discard ",N," unplaceable overlay",N===1?"":"s"]})]}):N>0?d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-repair-note",children:["Discarded ",N," unplaceable overlay",N===1?"":"s"," — the export will not include"," ",N===1?"it":"them","."]}):F?d.jsx("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-repair-note",children:"Auto-placed overlays from the cut plan — review their positions before exporting."}):null,Kt.length>0&&d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-overlap-warning",children:["Cut #",t.id,": ",Kt.length," bubble"," ",Kt.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",Kt.map(P=>`#${P.indexA+1} ${Bf(D[P.indexA])} ↔ #${P.indexB+1} ${Bf(D[P.indexB])}`).join("; "),". Move them apart, or export as-is if the overlap is intended."]}),d.jsx("div",{className:"px-3 py-1 border-b border-border flex items-center gap-3 flex-wrap text-[10px] text-muted","data-testid":"lettering-checklist",children:[["clean-image","Clean image",Qe.hasCleanImage],["script-text","Script text",Qe.hasScriptText],["bubbles",`Bubbles placed${Qe.bubblesPlaced?` (${Qe.bubblesPlaced})`:""}`,Qe.bubblesPlaced>0],["exported","Final exported",Qe.exported],["uploaded","Uploaded",Qe.uploaded]].map(([P,we,ze])=>d.jsxs("span",{"data-testid":`lettering-check-${P}`,"data-done":ze?"true":"false",className:`flex items-center gap-1 ${ze?"text-green-700":"text-muted/70"}`,children:[d.jsx("span",{"aria-hidden":!0,children:ze?"✓":"○"}),we]},P))}),wt&&d.jsx("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"lettering-stale-export-warning",children:"Bubbles changed since the last export — re-export this cut and upload the new final image before publishing."}),Te>0&&d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"lettering-export-warning",children:[Te," bubble",Te===1?"":"s"," may not export cleanly:"," ",Object.entries(ge).map(([P,we])=>{const ze=D.findIndex(Ge=>Ge.id===P),Re=[we.outOfBounds?"outside image":null,we.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${ze+1} ${Bf(D[ze])} (${Re})`}).join("; "),". Resize or reposition before exporting."]}),d.jsxs("div",{className:"flex-1 min-h-0 flex",children:[d.jsxs("div",{ref:ae,className:"flex-1 min-w-0 relative overflow-hidden bg-[#f8f5ef]",onClick:ot,"data-testid":"editor-surface",children:[t.cleanImagePath&&R.error?d.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted text-xs","data-testid":"clean-image-error",children:"Clean image not available"}):t.cleanImagePath&&!R.url?d.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted text-xs","data-testid":"clean-image-loading",children:"Loading clean image…"}):t.cleanImagePath?d.jsx("img",{ref:Y,src:R.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:_e}):Ue?V.width>0&&d.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:V.x,top:V.y,width:V.width,height:V.height,background:t.background||"#ffffff"},"data-testid":"text-panel-canvas",children:"Text panel"}):d.jsx("div",{className:"w-full h-full bg-white flex items-center justify-center text-muted text-xs",ref:P=>{if(P&&V.width===0){const we=P.getBoundingClientRect();we.width>0&&ne({x:0,y:0,width:we.width,height:we.height})}},children:"Narration cut"}),V.width>0&&d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:D.map(P=>{if(P.type!=="speech")return null;const we=V.x+wn(P.x,V.width),ze=V.y+wn(P.y,V.height),Re=wn(P.width,V.width),Ge=wn(P.height,V.height),$e=M3(P,Re,Ge),ht=P.tailAnchor?HS(we,ze,Re,Ge,P.tailAnchor,$e):null,dt=Math.max(1.5,V.height*.004),lt=P.id===X;return d.jsx("path",{"data-testid":`balloon-${P.id}`,d:O3(we,ze,Re,Ge,ht,$e),className:`fill-white/95 ${lt?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:lt?dt+.5:dt,strokeLinejoin:"round"},P.id)})}),V.width>0&&D.map(P=>{const we=V.x+wn(P.x,V.width),ze=V.y+wn(P.y,V.height),Re=wn(P.width,V.width),Ge=wn(P.height,V.height),$e=P.id===X,ht=P.type==="speech",dt=P.type==="narration",lt=!!ge[P.id];return d.jsxs("div",{"data-testid":`overlay-${P.id}`,"data-warning":lt?"true":"false",onClick:Vt=>We(Vt,P.id),onMouseDown:Vt=>Mt(Vt,P.id,"move"),className:`absolute rounded cursor-move select-none ${ht?"":`border-2 ${wD[P.type]}`} ${dt?"bg-[#f4efe6]/85 rounded-md":""} ${$e&&!ht?"ring-2 ring-accent":""} ${lt?"ring-2 ring-amber-500":""}`,style:{left:we,top:ze,width:Re,height:Ge},children:[(()=>{var Fi,En;const Vt=P.type==="sfx"?j:S;if(!P.text)return d.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:Vt},children:ku[P.type]});const Ci=P.type!=="sfx"&&!!P.speaker;if(!W)return d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 overflow-hidden pointer-events-none text-center break-words",style:{fontFamily:Vt,fontSize:Math.max(9,Math.min(Ge*.05,16)),fontWeight:((Fi=P.textStyle)==null?void 0:Fi.fontWeight)??400},"data-testid":`overlay-text-${P.id}`,"data-fonts-ready":"false",children:Ci?`${P.speaker}: ${P.text}`:P.text});const ft=uu(ce(Vt),P.text,Re,Ge,hu(P,V.height,Re,Ge));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 overflow-hidden pointer-events-none text-center",style:{fontFamily:Vt},"data-testid":`overlay-text-${P.id}`,"data-fonts-ready":"true",children:[Ci&&d.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:ft.speakerFontSize,lineHeight:1.2},children:P.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:ft.fontSize,lineHeight:`${ft.lineHeight}px`,fontWeight:((En=P.textStyle)==null?void 0:En.fontWeight)??400},children:ft.lines.map((ln,Un)=>d.jsx("span",{className:"block",children:ln},Un))})]})})(),$e&&d.jsx("div",{onMouseDown:Vt=>{Vt.stopPropagation(),Mt(Vt,P.id,"resize")},className:"absolute bottom-0 right-0 w-2 h-2 bg-accent cursor-se-resize","data-testid":`resize-${P.id}`})]},P.id)})]}),d.jsxs("div",{className:"w-64 border-l border-border p-3 overflow-y-auto flex-shrink-0",children:[((ui=t.aiDraft)==null?void 0:ui.status)==="generated"&&d.jsxs("div",{className:"mb-3 rounded border border-accent/30 bg-accent/5 p-2 space-y-1","data-testid":"ai-draft-current-target",children:[d.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"AI draft ready"}),d.jsx("p",{className:"text-[11px] text-muted",children:"These first-pass overlays came from the cut script. Review and tune them here before exporting the final panel."})]}),Q.length>0&&d.jsxs("div",{className:"mb-3 space-y-1.5","data-testid":"script-insert-panel",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"From script"}),d.jsx("div",{className:"flex flex-col gap-1",children:Q.map(P=>d.jsxs("button",{onClick:()=>je(P),"data-testid":`script-insert-${P.key}`,title:`Add ${P.type} overlay with this text`,className:"text-left px-2 py-1 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5",children:[d.jsxs("span",{className:"font-medium text-accent",children:["+ ",ku[P.type]]})," ",d.jsxs("span",{className:"text-muted",children:[P.speaker?`${P.speaker}: `:"",P.text.length>32?`${P.text.slice(0,32)}…`:P.text]})]},P.key))})]}),Ae?d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-xs font-medium text-foreground",children:ku[Ae.type]}),Ae.speaker!==void 0&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Speaker"}),d.jsx("input",{value:Ae.speaker||"",onChange:P=>be(Ae.id,{speaker:P.target.value}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",placeholder:"Character name","data-testid":"inspector-speaker"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Text"}),d.jsx("textarea",{value:Ae.text,onChange:P=>be(Ae.id,{text:P.target.value}),rows:3,className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent resize-none focus:border-accent focus:outline-none",placeholder:"Overlay text","data-testid":"inspector-text"})]}),d.jsx("button",{onClick:()=>be(Ae.id,Be(Ae)),"data-testid":"inspector-fit-text",className:"w-full px-2 py-1 text-[11px] border border-border rounded hover:border-accent hover:text-accent",title:"Resize this overlay so its text fits without overflowing",children:"Fit box to text"}),d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-typography",children:[d.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Typography"}),((Bt=Ae.textStyle)==null?void 0:Bt.mode)==="manual"?d.jsx("button",{type:"button",onClick:()=>be(Ae.id,{textStyle:void 0}),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"inspector-text-auto",children:"Auto-fit"}):d.jsx("button",{type:"button",onClick:()=>tt(Ae),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"inspector-text-manual",children:"Manual"})]}),((vt=Ae.textStyle)==null?void 0:vt.mode)==="manual"?d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Font size (% panel height)"}),d.jsx("input",{type:"number",step:"0.1",min:"1.5",max:"12",value:((Ae.textStyle.fontScale??.032)*100).toFixed(1),onChange:P=>be(Ae.id,{textStyle:{...Ae.textStyle,mode:"manual",fontScale:Math.max(.015,Math.min(.12,(parseFloat(P.target.value)||3.2)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-font-scale"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Weight"}),d.jsxs("select",{value:String(Ae.textStyle.fontWeight??400),onChange:P=>be(Ae.id,{textStyle:{...Ae.textStyle,mode:"manual",fontWeight:P.target.value==="700"?700:400}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-font-weight",children:[d.jsx("option",{value:"400",children:"Regular"}),d.jsx("option",{value:"700",children:"Bold"})]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Line height"}),d.jsx("input",{type:"number",step:"0.05",min:"0.9",max:"2",value:(Ae.textStyle.lineHeightFactor??1.2).toFixed(2),onChange:P=>be(Ae.id,{textStyle:{...Ae.textStyle,mode:"manual",lineHeightFactor:Math.max(.9,Math.min(2,parseFloat(P.target.value)||1.2))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-line-height"})]}),Ae.type!=="sfx"&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Speaker scale"}),d.jsx("input",{type:"number",step:"0.05",min:"0.5",max:"1.5",value:(Ae.textStyle.speakerScale??.8).toFixed(2),onChange:P=>be(Ae.id,{textStyle:{...Ae.textStyle,mode:"manual",speakerScale:Math.max(.5,Math.min(1.5,parseFloat(P.target.value)||.8))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-speaker-scale"})]})]}):d.jsx("p",{className:"text-[10px] text-muted",children:"Auto-fit stays on by default and resizes text to the box."})]}),Ae.type==="speech"&&(()=>{const P=Ae.tailAnchor||{x:.5,y:1.2};return d.jsxs("div",{className:"space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Tail anchor"}),d.jsx("div",{className:"flex flex-wrap gap-1","data-testid":"inspector-tail-presets",children:CD.map(we=>d.jsx("button",{type:"button",onClick:()=>be(Ae.id,{tailAnchor:we.anchor}),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":`inspector-tail-${we.key}`,children:we.label},we.key))}),d.jsxs("div",{className:"flex gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["x",d.jsx("input",{type:"number",step:"0.1",value:P.x,onChange:we=>be(Ae.id,{tailAnchor:{...P,x:parseFloat(we.target.value)||0}}),className:"w-14 px-1 py-0.5 text-[10px] border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-tail-x"})]}),d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["y",d.jsx("input",{type:"number",step:"0.1",value:P.y,onChange:we=>be(Ae.id,{tailAnchor:{...P,y:parseFloat(we.target.value)||0}}),className:"w-14 px-1 py-0.5 text-[10px] border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-tail-y"})]})]})]})})(),Ae.type!=="sfx"&&d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-bubble-style",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Bubble controls"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding X (% width)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((At=Ae.bubbleStyle)==null?void 0:At.paddingX)??.06)*100).toFixed(0),onChange:P=>be(Ae.id,{bubbleStyle:{...Ae.bubbleStyle,paddingX:Math.max(0,Math.min(.25,(parseFloat(P.target.value)||6)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-padding-x"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding Y (% height)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Ze=Ae.bubbleStyle)==null?void 0:Ze.paddingY)??.08)*100).toFixed(0),onChange:P=>be(Ae.id,{bubbleStyle:{...Ae.bubbleStyle,paddingY:Math.max(0,Math.min(.25,(parseFloat(P.target.value)||8)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-padding-y"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Corner roundness (% short side)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"49",value:((((hi=Ae.bubbleStyle)==null?void 0:hi.cornerRadius)??.4)*100).toFixed(0),onChange:P=>be(Ae.id,{bubbleStyle:{...Ae.bubbleStyle,cornerRadius:Math.max(0,Math.min(.49,(parseFloat(P.target.value)||40)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-corner-radius"})]})]}),d.jsxs("div",{className:"text-[10px] text-muted","data-testid":"inspector-font",children:["Font:"," ",Ae.type==="sfx"?v.family:b.family]}),d.jsxs("div",{className:"text-[10px] font-mono text-muted space-y-0.5",children:[d.jsxs("p",{children:["x: ",Ae.x.toFixed(3),", y:"," ",Ae.y.toFixed(3)]}),d.jsxs("p",{children:["w: ",Ae.width.toFixed(3),", h:"," ",Ae.height.toFixed(3)]})]}),d.jsx("button",{onClick:()=>{A?St(Ae.id):O(!0)},className:"w-full px-2 py-1 text-xs text-error border border-error/30 rounded hover:bg-error/5","data-testid":"delete-overlay",children:A?"Click again to delete":"Delete"})]}):d.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}const ED={wide:"Wide",medium:"Medium","close-up":"Close-up","extreme-close-up":"Extreme close-up"},ND="No speech bubbles, captions, sound effects, narration, or any text or lettering in the image.",jD="Style lock — illustrated comic/webtoon panel art: clean black contour/ink lines, flat or cel shading, simplified but realistic (semi-realistic) anatomy and faces, backgrounds drawn as illustrated comic panels. Hold this same style on every cut for character and panel consistency. Hard negatives — NOT photorealistic, NOT a photograph, NOT a glossy or painterly digital painting, NOT concept art, NOT a 3D/CGI render, NOT airbrushed, no photoreal textures.";function TD(e){var a;const t=ED[e.shotType]??e.shotType,i=((a=e.description)==null?void 0:a.trim())||`Cut ${e.id}`,s=[`${t} shot. ${i}`];return e.characters.length>0&&s.push(`Characters: ${e.characters.join(", ")}.`),s.push(jD),s.push(ND),s.join(` -`).trim()}function AD(e,t){return`assets/${e}/cut-${String(t).padStart(2,"0")}-clean.webp`}function dy(e,t){const i=AD(t,e.id);return[`Generate the clean image for cut ${e.id}.`,"","Image description:",TD(e),"","How to hand it off:","- Produce the actual image — do not just describe it or return a prompt.",`- If your image tool can write a WebP or JPEG under 1MB, save it at ${i} and run "Sync clean images".`,'- If it only produces a PNG (e.g. built-in image generation saves to ~/.codex/generated_images), that is fine — do NOT convert or rename it yourself. Leave it there and import it into this cut with the OWS "Import from Codex" button, which converts the PNG automatically.',"- Clean image only: no text, speech bubbles, captions, sound effects, signage, watermark, or signature.","- Hold the style lock above — an illustrated comic/webtoon panel, NOT a photoreal photo, painterly concept art, or 3D render. If a result reads photorealistic, regenerate it as illustrated panel art.","- Do not letter or upload anything — final lettering and upload happen later in OWS."].join(` -`)}const YS=12e3,RD=5,DD=6e4,MD=6e4,BD=5;function LD(e,t){return e===429?!0:!!t&&/rate[\s-]?limit/i.test(t)}function OD(e,t=YS){return Math.min(t*2**e,DD)}const KS=e=>new Promise(t=>setTimeout(t,e));async function zD(e,t={}){var c;const i=t.sleep??KS,s=t.maxRetries??RD,a=t.baseDelayMs??YS;let o=0;for(;;){const h=await e();if(h.ok||!LD(h.status,h.errorMessage)||o>=s)return h;const p=OD(o,a);o+=1,(c=t.onWaiting)==null||c.call(t,{attempt:o,maxRetries:s,waitMs:p}),await i(p)}}function PD(e={}){const t=e.limit??BD,i=e.windowMs??MD,s=e.sleep??KS,a=e.now??(()=>Date.now()),o=[],c=()=>{const h=a()-i;for(;o.length&&o[0]<=h;)o.shift()};return async function(){var p;if(c(),o.length>=t){const f=o[0]+i-a();f>0&&((p=e.onWaiting)==null||p.call(e,{waitMs:f}),await s(f)),c()}o.push(a())}}const zp=1024*1024;function fy(e,t,i){return new Promise((s,a)=>{e.toBlob(o=>o?s(o):a(new Error(`Failed to export as ${t}`)),t,i)})}async function ID(e){const t=[.9,.8,.7,.6];for(const s of t)try{const a=await fy(e,"image/webp",s);if(a.type!=="image/webp")break;if(a.size<=zp)return a}catch{break}const i=[.85,.7,.5];for(const s of i){const a=await fy(e,"image/jpeg",s);if(a.size<=zp)return a}throw new Error("Cannot compress image under 1MB — reduce overlay count or image size")}const HD=["image/webp","image/jpeg"];function VS(e){return HD.includes(e.type)&&e.size<=zp}async function UD(e){var i;if(typeof createImageBitmap!="function")throw new Error("This browser cannot decode the image for import");let t;try{t=await createImageBitmap(e)}catch{throw new Error("Could not read the selected image — pick a PNG, WebP, or JPEG file")}try{const s=document.createElement("canvas");s.width=t.width,s.height=t.height;const a=s.getContext("2d");if(!a)throw new Error("Could not process the image for import");return a.drawImage(t,0,0),s}finally{(i=t.close)==null||i.call(t)}}async function Ku(e){if(VS(e))return e;const t=await UD(e);return ID(t)}function $D(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.token=="string"&&t.token.length>0&&typeof t.name=="string"&&typeof t.size=="number"&&typeof t.mtimeMs=="number"}async function FD(e){let t;try{t=await e("/api/codex/images")}catch{return[]}if(!t.ok)return[];let i;try{i=await t.json()}catch{return[]}const s=i==null?void 0:i.images;return Array.isArray(s)?s.filter($D):[]}async function qD(e,t){let i;try{i=await e(`/api/codex/images/${encodeURIComponent(t.token)}`)}catch{throw new Error("Could not read the generated image from the Codex cache")}if(!i.ok)throw new Error("Could not read the generated image from the Codex cache");const s=await i.blob(),a=s.type||i.headers.get("Content-Type")||"image/png";return new File([s],t.name||"codex-image.png",{type:a})}function WD(e,t){const[i,s]=w.useState(null);return w.useEffect(()=>{let a=null,o=!1;return(async()=>{try{const c=await t(e);if(!c.ok)return;const h=await c.blob();if(o)return;a=URL.createObjectURL(h),s(a)}catch{}})(),()=>{o=!0,a&&URL.revokeObjectURL(a)}},[e,t]),i}function GD(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function YD(e,t){const i=t-e;if(!Number.isFinite(i)||i<45e3)return"just now";const s=Math.round(i/6e4);if(s<60)return`${s}m ago`;const a=Math.round(i/36e5);if(a<24)return`${a}h ago`;const o=Math.round(i/864e5);return o<7?`${o}d ago`:`${Math.round(i/(7*864e5))}w ago`}function KD({image:e,authFetch:t}){const i=WD(`/api/codex/images/${encodeURIComponent(e.token)}`,t);return i?d.jsx("img",{src:i,alt:e.name,className:"w-16 h-16 flex-shrink-0 rounded border border-border object-cover bg-white"}):d.jsx("div",{className:"w-16 h-16 flex-shrink-0 rounded border border-border bg-surface"})}function VD({authFetch:e,cutId:t,onImport:i,onClose:s}){const[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState("");w.useEffect(()=>{let E=!1;return(async()=>{const N=await FD(e);E||o(N)})(),()=>{E=!0}},[e]);const b=_.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(E=>E.name.toLowerCase().includes(b)):a:[],[a,b]),S=Date.now(),j=async E=>{h(null),f(E.token);try{const N=await qD(e,E);await i(N)}catch(N){h(N instanceof Error?N.message:"Could not import the generated image")}finally{f(null)}},R=a!==null&&a.length>0;return d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-2","data-testid":`codex-picker-${t}`,children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Import a Codex-generated image"}),d.jsx("button",{onClick:s,"data-testid":`codex-picker-close-${t}`,className:"text-[11px] text-muted hover:text-foreground",children:"Close"})]}),R&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"search",value:_,onChange:E=>x(E.target.value),placeholder:"Filter by file name…","data-testid":`codex-picker-search-${t}`,className:"min-w-0 flex-1 px-2 py-1 text-[11px] border border-border rounded bg-transparent focus:border-accent focus:outline-none"}),d.jsx("span",{className:"text-[10px] text-muted whitespace-nowrap","data-testid":`codex-picker-count-${t}`,children:b?`${v.length} of ${a.length}`:`${a.length} image${a.length===1?"":"s"}`})]}),a===null&&d.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-loading-${t}`,children:"Looking for generated images…"}),a!==null&&a.length===0&&d.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-empty-${t}`,children:"No generated images found in the Codex cache yet. Generate art in Codex, then reopen this list — or use “Upload clean image” to pick a file."}),R&&v.length===0&&d.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",_.trim(),"”."]}),R&&v.length>0&&d.jsx("ul",{className:"space-y-1 max-h-72 overflow-y-auto",children:v.map(E=>d.jsxs("li",{"data-testid":`codex-image-${E.token}`,className:"flex items-center gap-2 rounded border border-border bg-background/40 p-1.5",children:[d.jsx(KD,{image:E,authFetch:e}),d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsxs("p",{className:"text-[11px] text-foreground",children:[YD(E.mtimeMs,S)," · ",GD(E.size)]}),d.jsx("p",{className:"truncate text-[10px] font-mono text-muted",title:E.name,children:E.name})]}),d.jsx("button",{onClick:()=>j(E),disabled:p!==null,"data-testid":`codex-import-${E.token}`,className:"px-2 py-1 text-[11px] border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:p===E.token?"Importing…":"Import to this cut"})]},E.token))}),c&&d.jsx("p",{className:"text-[11px] text-error",children:c})]})}const XD={done:"✓",current:"▸",todo:"○"};function ZD({checklist:e,issues:t,onFinish:i,finishing:s,progressText:a,canFinish:o,markdownReady:c=!1,published:h=!1}){var E;if(!e||e.steps.length===0)return null;const p=GS(t),f=((E=e.steps.find(N=>N.key==="upload"))==null?void 0:E.status)==="done",_=f&&c&&!h,x=h||c?"done":f?"current":"todo",b=h?"done":_?"current":"todo",v=[...e.steps.filter(N=>N.key!=="publish"),{key:"assemble",label:"Episode sequence prepared",status:x,detail:null},{key:"ready",label:h?"Published to PlotLink":"Ready to publish",status:b,detail:null}],S=s?a||"Finishing…":h?"Published ✓":_?"Episode ready to publish":"Finish episode",j=v.filter(N=>N.status!=="done").length,R=p.reduce((N,I)=>N+I.lines.length,0);return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/50 flex-shrink-0","data-testid":"finish-episode-panel",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&d.jsxs("span",{className:"min-w-0 flex-1 text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]}),d.jsx("button",{onClick:i,disabled:s||!o,"data-testid":"finish-episode-btn",title:"Upload the exported final panels, then prepare the episode for publishing — picks up where it left off",className:"px-2.5 py-0.5 text-[11px] border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:S})]}),d.jsxs("details",{className:"mt-1","data-testid":"finish-episode-details",children:[d.jsxs("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:[j===0?"Progress details":`${j} step${j===1?"":"s"} left`,R>0?` · ${R} blocker${R===1?"":"s"}`:""]}),d.jsxs("div",{className:"mt-1.5 space-y-1.5",children:[d.jsx("ol",{className:"flex flex-wrap gap-1.5",children:v.map(N=>d.jsxs("li",{"data-testid":`finish-step-${N.key}`,"data-status":N.status,className:`flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${N.status==="current"?"border-accent/40 bg-accent/10 text-accent":N.status==="done"?"border-border bg-background/70 text-foreground":"border-border/70 bg-background/40 text-muted"}`,children:[d.jsx("span",{"aria-hidden":!0,children:XD[N.status]}),d.jsx("span",{children:N.label}),N.detail&&d.jsxs("span",{className:"text-muted",children:["· ",N.detail]})]},N.key))}),p.length>0&&d.jsx("div",{className:"space-y-1.5","data-testid":"finish-issues",children:p.map(N=>d.jsxs("div",{"data-testid":`finish-issue-group-${N.key}`,className:"text-[10px]",children:[d.jsx("p",{className:"font-medium text-amber-700",children:N.title}),d.jsx("ul",{className:"ml-3 list-disc text-muted",children:N.lines.map((I,te)=>d.jsx("li",{children:I},te))})]},N.key))})]})]})]})}function QD(e){return{planned:e.filter(t=>t.state==="planned").length,needsConversion:e.filter(t=>t.state==="needs-conversion").length,missing:e.filter(t=>t.state==="missing").length,cleanReady:e.filter(t=>t.state==="clean-ready").length,finalReady:e.filter(t=>t.state==="final-ready").length,uploaded:e.filter(t=>t.state==="uploaded").length}}function Ao(e){return(!!e.cleanImagePath||In(e))&&ym(e).length>0}function py(e){const t=new Date().toISOString();return{status:"generated",baseSig:ul(e),generatedAt:t,updatedAt:t}}function XS(e){return e.uploadedCid?"uploaded":e.finalImagePath||e.exportedAt?"lettered":e.cleanImagePath?"clean":In(e)?"text":"missing"}const my={muted:"text-muted",amber:"text-amber-700",green:"text-green-700",accent:"text-accent"},JD={muted:"bg-muted/40",amber:"bg-amber-500",green:"bg-green-600",accent:"bg-accent"};function eM(e,t,i){var s;return e.uploadedCid||e.uploadedUrl?{key:"uploaded",label:"Uploaded",tone:"green"}:t?{key:"convert",label:"Needs conversion",tone:"amber"}:i?e.finalImagePath?{key:"review",label:"Needs review",tone:"amber"}:{key:"needs-image",label:"Needs image",tone:"muted"}:e.finalImagePath?{key:"exported",label:"Exported",tone:"green"}:In(e)?{key:"text",label:"Ready for captions",tone:"accent"}:e.cleanImagePath?(((s=e.overlays)==null?void 0:s.length)??0)>0?{key:"review",label:"Needs review",tone:"amber"}:{key:"letter",label:"Ready for lettering",tone:"green"}:{key:"needs-image",label:"Needs image",tone:"muted"}}function tM(e){var t,i;return e.uploadedCid||e.uploadedUrl?{label:"Complete",detail:"Final image uploaded",tone:"green"}:e.finalImagePath||e.exportedAt?{label:"Exported",detail:"Ready to upload",tone:"green"}:(((t=e.overlays)==null?void 0:t.length)??0)>0?((i=e.aiDraft)==null?void 0:i.status)==="generated"?{label:"Draft ready",detail:`${e.overlays.length} AI-drafted overlay${e.overlays.length===1?"":"s"} ready to review`,tone:"amber"}:{label:"User-edited",detail:`${e.overlays.length} overlay${e.overlays.length===1?"":"s"} adjusted and ready to review`,tone:"amber"}:Ao(e)?{label:"No draft",detail:"Draft with AI or place bubbles manually",tone:"muted"}:In(e)?{label:"Between-scene card",detail:"Open to add narration or title text",tone:"accent"}:e.cleanImagePath?{label:"Unlettered",detail:"Clean art ready for bubble placement",tone:"muted"}:{label:"Needs artwork",detail:"Add or sync clean art first",tone:"muted"}}function iM({cut:e,storyName:t,plotFile:i,expanded:s,onToggle:a,authFetch:o,onUpdated:c,onOpenEditor:h,detectedLocalClean:p,onSyncClean:f,syncing:_,onAiDraft:x,aiDrafting:b,staleMessages:v,onRepairStale:S,repairing:j,conversionPng:R,onConvert:E,converting:N,rowRef:I}){var Be,Le;const te=w.useRef(null),[F,D]=w.useState(!1),[ie,fe]=w.useState(null),[Se,H]=w.useState(!1),[ce,W]=w.useState(!1),[K,X]=w.useState(!1),[U,A]=w.useState(!1),O=XS(e),$=v.length>0,xe=!!R,T=w.useCallback(async()=>{R&&(A(!0),await E(e.id,R),A(!1),c())},[R,E,e.id,c]),M=w.useCallback(async je=>{D(!0),fe(null);try{let be=je;if(!VS(je))try{be=await Ku(je)}catch(We){return fe(We instanceof Error?We.message:"Could not import image"),!1}const tt=be.type==="image/jpeg"?"jpg":"webp",St=new FormData;St.append("file",new File([be],`clean.${tt}`,{type:be.type}));const ot=await o(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:St});if(!ot.ok){const We=await ot.json();return fe(We.error||"Upload failed"),!1}return c(),!0}catch{return fe("Upload failed"),!1}finally{D(!1)}},[o,t,i,e.id,c]),G=eM(e,xe,$),C=e.cleanImagePath??R??null,V=((Be=e.overlays)==null?void 0:Be.length)??0,ne=!In(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!$&&!xe,ae=!$&&!xe&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&Ao(e),Y=(((Le=e.overlays)==null?void 0:Le.length)??0)>0?"Re-draft with AI":"AI draft lettering",he=G.key==="convert"?{label:U?"Converting…":"Convert image",onClick:T,testid:`card-convert-${e.id}`}:G.key==="review"?{label:"Review cut",onClick:h,testid:`card-review-${e.id}`}:G.key==="text"?{label:"Add captions",onClick:h,testid:`card-letter-${e.id}`}:G.key==="needs-image"?{label:"Add artwork",onClick:a,testid:`card-addart-${e.id}`}:null,_e=tM(e);return d.jsxs("div",{ref:I,"data-cut-row":e.id,className:`border rounded ${s?"border-accent/30":"border-border"}`,children:[d.jsxs("div",{className:"px-3 py-2 space-y-2","data-testid":`cut-card-${e.id}`,children:[d.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[d.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${JD[G.tone]}`}),d.jsxs("span",{className:"font-medium text-xs text-foreground",children:["Cut ",String(e.id).padStart(2,"0")]}),d.jsxs("span",{className:"font-mono text-[10px] text-muted",children:["· ",e.shotType]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium flex-shrink-0 ${my[G.tone]}`,"data-testid":`cut-card-status-${e.id}`,children:G.label})]}),C?d.jsx(Bp,{storyName:t,assetPath:C,authFetch:o,alt:`Cut ${e.id} artwork`,className:"w-full max-h-[32rem] object-contain rounded border border-border bg-white"}):d.jsx("div",{className:"w-full min-h-28 rounded border border-dashed border-border bg-surface/40 flex items-center justify-center text-[10px] text-muted","data-testid":`cut-card-noart-${e.id}`,children:In(e)?"Text panel — no artwork needed":"No artwork yet"}),d.jsxs("div",{className:`rounded border border-border/70 bg-surface/50 px-2 py-1.5 text-[11px] ${my[_e.tone]}`,"data-testid":`lettering-review-state-${e.id}`,children:[d.jsx("span",{className:"font-semibold",children:_e.label}),d.jsxs("span",{className:"text-muted",children:[" · ",_e.detail]})]}),d.jsx("button",{onClick:a,"data-testid":`cut-desc-${e.id}`,className:"block w-full text-left text-[11px] text-muted hover:text-foreground",children:e.description||"No description"}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[ne?d.jsxs(d.Fragment,{children:[d.jsx("button",{onClick:h,"data-testid":`add-bubbles-${e.id}`,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim",children:V>0?"Review lettering":"Open focused editor"}),ae&&d.jsx("button",{onClick:x,disabled:b,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:b?"Drafting…":Y})]}):he?d.jsx("button",{onClick:he.onClick,disabled:G.key==="convert"&&(U||N),"data-testid":he.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:he.label}):null,!ne&&!he&&ae&&d.jsx("button",{onClick:x,disabled:b,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:b?"Drafting…":Y}),d.jsx("button",{onClick:a,"data-testid":`cut-details-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-border text-muted hover:border-accent hover:text-accent",children:s?"Hide details":"Open details"})]})]}),s&&d.jsxs("div",{className:"px-3 pb-3 space-y-3 border-t border-border",children:[xe&&d.jsxs("div",{className:"mt-2 rounded border border-amber-500/40 bg-amber-500/10 p-2 space-y-1","data-testid":`needs-conversion-${e.id}`,children:[d.jsx("p",{className:"text-[11px] text-amber-800",children:"This cut’s artwork is a PNG. Convert it to WebP so it can be lettered and published."}),d.jsx("button",{onClick:T,disabled:U||N,"data-testid":`convert-cut-${e.id}`,className:"px-2 py-1 text-[11px] border border-amber-500/50 text-amber-800 rounded hover:bg-amber-500/20 disabled:opacity-50",children:U?"Converting…":"Convert image"})]}),$&&!xe&&d.jsxs("div",{className:"mt-2 rounded border border-error/40 bg-error/5 p-2 space-y-1","data-testid":`stale-asset-${e.id}`,children:[v.map((je,be)=>d.jsx("p",{className:"text-[11px] text-error",children:je},be)),d.jsx("button",{onClick:S,disabled:j,"data-testid":`repair-stale-${e.id}`,className:"px-2 py-1 text-[11px] border border-error/40 text-error rounded hover:bg-error/10 disabled:opacity-50",children:j?"Repairing…":"Clear stale path"})]}),!In(e)&&d.jsxs("div",{className:"mt-2 space-y-2",children:[d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(dy(e,i)),H(!0),setTimeout(()=>H(!1),2e3)},"data-testid":`copy-prompt-${e.id}`,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5",children:Se?"Copied!":"Copy Codex task"}),d.jsx("input",{ref:te,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:je=>{var tt;const be=(tt=je.target.files)==null?void 0:tt[0];be&&M(be),je.target.value=""}}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsx("button",{onClick:()=>{var je;return(je=te.current)==null?void 0:je.click()},disabled:F,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:F?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),d.jsx("button",{onClick:()=>X(je=>!je),disabled:F,"data-testid":`import-codex-${e.id}`,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:K?"Hide Codex images":"Import from Codex"})]}),K&&d.jsx(VD,{authFetch:o,cutId:e.id,onImport:async je=>{await M(je)&&X(!1)},onClose:()=>X(!1)}),!e.cleanImagePath&&d.jsx("p",{className:"text-xs text-muted","data-testid":`clean-image-handoff-${e.id}`,children:"Generate this cut in Codex, then import the cached PNG with “Import from Codex” — or upload an image manually. Letter it next."}),O==="missing"&&d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-1","data-testid":`ask-codex-${e.id}`,children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Generate this cut in Codex"}),d.jsxs("p",{className:"text-[10px] text-muted",children:["Copy the task below and paste it into Codex. Codex usually saves a PNG to its image cache — bring it into this cut with “Import from Codex” above (the PNG becomes a WebP automatically). If Codex instead writes a WebP/JPEG at"," ",d.jsxs("span",{className:"font-mono",children:["assets/",i,"/cut-",String(e.id).padStart(2,"0"),"-clean.webp"]}),", it’s picked up by “Sync clean images”."]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(dy(e,i)),W(!0),setTimeout(()=>W(!1),2e3)},"data-testid":`ask-codex-copy-${e.id}`,className:"px-2 py-1 text-[11px] border border-border rounded hover:border-accent hover:bg-accent/5",children:ce?"Copied!":"Copy Codex task"})]}),O==="missing"&&p&&d.jsx("button",{onClick:f,disabled:_,"data-testid":`found-local-clean-${e.id}`,className:"px-3 py-1.5 text-xs border border-green-700/40 text-green-700 rounded hover:bg-green-700/5 disabled:opacity-50",children:_?"Syncing...":"Found local clean image — sync to cut plan"}),ie&&d.jsx("p",{className:"text-xs text-error mt-1",children:ie})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||In(e))&&d.jsx("button",{onClick:h,"data-testid":`open-editor-${e.id}`,className:"px-3 py-1.5 text-xs border border-accent/30 text-accent rounded hover:bg-accent/5",children:"Open editor"}),e.characters.length>0&&d.jsxs("p",{className:"text-xs text-muted",children:["Characters: ",e.characters.join(", ")]}),e.dialogue.length>0&&d.jsx("div",{className:"text-xs text-muted",children:e.dialogue.map((je,be)=>d.jsxs("p",{children:[d.jsxs("span",{className:"font-medium",children:[je.speaker,":"]})," ",je.text]},be))}),e.narration&&d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})]})]})}function gy({storyName:e,fileName:t,authFetch:i,language:s,uploadRetry:a,onCutsChanged:o,focusRequest:c,onFocusHandled:h,onFocusedLetteringModeChange:p,workspaceVisible:f=!1,onWorkspaceVisibleChange:_}){var pr,Lt,le;const[x,b]=w.useState(null),v=w.useRef(o);v.current=o;const S=w.useRef(h);S.current=h;const[j,R]=w.useState(!0),[E,N]=w.useState(null),[I,te]=w.useState(null),[F,D]=w.useState(null),[ie,fe]=w.useState(!1),[Se,H]=w.useState([]),[ce,W]=w.useState(!1),[K,X]=w.useState(""),[U,A]=w.useState({markdownReady:!1,published:!1}),[O,$]=w.useState(!1),[xe,T]=w.useState(!1),[M,G]=w.useState(!1),[C,V]=w.useState(null),[ne,ae]=w.useState(null),[Y,he]=w.useState(null),[_e,Be]=w.useState(!1),[Le,je]=w.useState(new Set),[be,tt]=w.useState(new Map),[St,ot]=w.useState(!1),[We,Mt]=w.useState(null),[He,xt]=w.useState(!1),[Ae,Kt]=w.useState(null),mi=w.useRef(new Map),wt=w.useRef(null),Qe=t.replace(/\.md$/,"");w.useEffect(()=>{var L;c&&wt.current!==c.seq&&(wt.current=c.seq,c.openEditor?D(c.cutId):(te(c.cutId),Kt(c.cutId)),(L=S.current)==null||L.call(S))},[c]),w.useEffect(()=>(p==null||p(F!==null),()=>p==null?void 0:p(!1)),[F,p]),w.useEffect(()=>{var oe;if(Ae==null)return;const L=mi.current.get(Ae);L&&((oe=L.scrollIntoView)==null||oe.call(L,{behavior:"smooth",block:"center"}),Kt(null))},[Ae,x]);const Q=w.useCallback(async()=>{var L;try{const oe=await i(`/api/stories/${e}/cuts/${Qe}`);if(oe.status===404){b(null);return}if(!oe.ok){const Me=await oe.json();N(Me.error||"Failed to load cuts");return}const Ee=await oe.json();b(Ee),N(null);try{const Me=await i(`/api/stories/${e}/${t}`);if(Me.ok){const Ne=await Me.json(),Pe=typeof(Ne==null?void 0:Ne.content)=="string"?Ne.content:"",qe=Array.isArray(Ee==null?void 0:Ee.cuts)?Ee.cuts:[],nt=Pe.length>0&&qS(Pe,qe).ready,Ve=(Ne==null?void 0:Ne.status)==="published"||(Ne==null?void 0:Ne.status)==="published-not-indexed";A({markdownReady:nt,published:Ve})}else A({markdownReady:!1,published:!1})}catch{A({markdownReady:!1,published:!1})}(L=v.current)==null||L.call(v)}catch{N("Failed to load cuts")}finally{R(!1)}},[i,e,Qe,t]),ge=w.useCallback(async L=>!!(await i(`/api/stories/${e}/cuts/${Qe}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)})).ok,[i,e,Qe]),Te=w.useCallback(async()=>{ot(!1);try{const L=await i(`/api/stories/${e}/cuts/${Qe}/detect-clean-images`);if(!L.ok)return;const oe=await L.json();je(new Set(Array.isArray(oe.detected)?oe.detected:[]));const Ee=new Map,Me=oe.stale;if(Array.isArray(Me))for(const Ne of Me){if(typeof(Ne==null?void 0:Ne.cutId)!="number"||typeof(Ne==null?void 0:Ne.message)!="string")continue;const Pe=Ee.get(Ne.cutId)??[];Pe.push(Ne.message),Ee.set(Ne.cutId,Pe)}tt(Ee),ot(!0)}catch{}},[i,e,Qe]),Ue=w.useCallback(async()=>{Mt(null);try{const L=await i(`/api/stories/${e}/cuts/${Qe}/asset-diagnostics`);if(!L.ok)return;const oe=await L.json();Mt(Array.isArray(oe.diagnostics)?oe.diagnostics:null)}catch{}},[i,e,Qe]),it=w.useCallback(async()=>{xt(!0);try{await Promise.all([Q(),Te(),Ue()])}finally{xt(!1)}},[Q,Te,Ue]),Wt=w.useCallback(async(L,oe={})=>{var Ne;if(!x)return!1;const Ee=x.cuts.find(Pe=>Pe.id===L);if(!Ee||!Ao(Ee)||(((Ne=Ee.overlays)==null?void 0:Ne.length)??0)>0&&!window.confirm("This cut already has overlays. Re-drafting with AI will replace the current draft overlays for this cut. Continue?"))return!1;const Me=oy(Ee);if(Me.length===0)return ae(`Cut ${Ee.id}: no script lines available to draft.`),!1;he(L),ae(null);try{const Pe={...x,cuts:x.cuts.map(nt=>nt.id===L?{...nt,overlays:Me,aiDraft:py(Me)}:nt)};return await ge(Pe)?(ae(`Cut ${Ee.id}: AI draft ready`),await Q(),oe.openEditor&&D(L),!0):(ae(`Cut ${Ee.id}: AI draft failed`),!1)}finally{he(null)}},[x,ge,Q]),ui=w.useCallback(async()=>{if(!x)return;const L=x.cuts.filter(oe=>{var Ee;return Ao(oe)&&(((Ee=oe.overlays)==null?void 0:Ee.length)??0)===0&&!oe.finalImagePath&&!oe.uploadedCid&&!oe.uploadedUrl});if(L.length===0){ae("No unlettered cuts need an AI draft");return}Be(!0),ae(null);try{const oe={...x,cuts:x.cuts.map(Me=>{if(!L.some(Pe=>Pe.id===Me.id))return Me;const Ne=oy(Me);return Ne.length>0?{...Me,overlays:Ne,aiDraft:py(Ne)}:Me})};if(!await ge(oe)){ae("AI draft failed");return}ae(`AI draft ready for ${L.length} cut${L.length===1?"":"s"}`),await Q()}finally{Be(!1)}},[x,ge,Q]),Bt=w.useCallback(async()=>{$(!0),ae(null),H([]);try{const L=await i(`/api/stories/${e}/cuts/${Qe}/sync-clean-images`,{method:"POST"}),oe=await L.json().catch(()=>({}));if(!L.ok)ae(oe.error||"Sync failed");else{const Ee=Array.isArray(oe.synced)?oe.synced.length:0,Me=Array.isArray(oe.cleared)?oe.cleared.length:0,Ne=Array.isArray(oe.rejected)?oe.rejected:[];Ne.length>0&&H(Ne.map(qe=>`Cut ${qe.cutId}: ${qe.reason}`));const Pe=[];Ee>0&&Pe.push(`Synced ${Ee}`),Me>0&&Pe.push(`Cleared ${Me} stale path${Me===1?"":"s"}`),ae(Pe.length>0?Pe.join(", "):"No new clean images"),await Q(),await Te(),await Ue()}}catch{ae("Sync failed")}$(!1)},[i,e,Qe,Q,Te,Ue]),vt=w.useCallback(async(L,oe)=>{try{const Ee=await i(OS(e,oe));if(!Ee.ok)return!1;const Me=await Ee.blob(),Ne=await Ku(new File([Me],"clean.png",{type:Me.type||"image/png"})),Pe=Ne.type==="image/jpeg"?"jpg":"webp",qe=new FormData;return qe.append("file",new File([Ne],`clean.${Pe}`,{type:Ne.type})),(await i(`/api/stories/${e}/cuts/${Qe}/upload-clean/${L}`,{method:"POST",body:qe})).ok}catch{return!1}},[i,e,Qe]),At=w.useCallback(async L=>{G(!0),V(null);let oe=0;const Ee=[];for(const Me of L)await vt(Me.cutId,Me.pngPath)?oe++:Ee.push(Me.cutId);await it(),G(!1),V(Ee.length===0?`Converted ${oe} image${oe===1?"":"s"} to WebP`:`Converted ${oe}; ${Ee.length} failed (Cut ${Ee.join(", ")}) — try Convert image on each`)},[vt,it]),Ze=w.useCallback(async()=>{var Ne;if(!x)return;W(!0),X(""),H([]);const L=x.cuts.filter(Pe=>Pe.finalImagePath&&!Pe.uploadedCid),oe=[],Ee=PD({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:Pe})=>X(`Upload limit reached — waiting ${Math.round(Pe/1e3)}s before continuing…`)});for(let Pe=0;Pe{const Jt=await i("/api/publish/upload-plot-image",{method:"POST",body:Nt});if(Jt.ok){const{cid:$n,url:gr}=await Jt.json();return{ok:!0,status:Jt.status,cid:$n,url:gr}}const qi=await Jt.json().catch(()=>({}));return{ok:!1,status:Jt.status,errorMessage:qi.error}},{...a,onWaiting:({attempt:Jt,maxRetries:qi,waitMs:$n})=>X(`Cut ${qe.id} rate-limited — waiting ${Math.round($n/1e3)}s before retry ${Jt}/${qi}...`)});if(!Gt.ok){oe.push(`Cut ${qe.id}: upload failed — ${Gt.errorMessage||"unknown"}`);continue}const{cid:Rt,url:ki}=Gt;(await i(`/api/stories/${e}/cuts/${Qe}/set-uploaded/${qe.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:Rt,url:ki})})).ok||oe.push(`Cut ${qe.id}: failed to record upload`)}catch(nt){oe.push(`Cut ${qe.id}: ${nt instanceof Error?nt.message:"failed"}`)}}if(oe.length>0){H(oe),W(!1),X(""),Q();return}X("Preparing episode for publishing…");const Me=await i(`/api/stories/${e}/cuts/${Qe}/generate-markdown`,{method:"POST"});if(Me.ok){const Pe=await Me.json();((Ne=Pe.warnings)==null?void 0:Ne.length)>0&&H(Pe.warnings)}W(!1),X(""),Q()},[x,i,e,Qe,a,Q]),hi=w.useCallback(async()=>{T(!0),ae(null);try{const L=await i(`/api/stories/${e}/cuts/${Qe}/repair-asset-paths`,{method:"POST"}),oe=await L.json().catch(()=>({}));if(!L.ok)ae(oe.error||"Repair failed");else{const Ee=Array.isArray(oe.cleared)?oe.cleared.length:0;ae(Ee>0?`Cleared ${Ee} stale path${Ee===1?"":"s"}`:"No stale paths to clear"),await Q(),await Te()}}catch{ae("Repair failed")}T(!1)},[i,e,Qe,Q,Te]),[P,we]=w.useState(!1),ze=w.useCallback(async(L,oe=!0)=>{if(x){we(!0);try{const Ee=x.cuts.reduce((nt,Ve)=>Math.max(nt,Ve.id),0)+1,Me={id:Ee,shotType:"wide",description:"Text panel",characters:[],dialogue:[],narration:"",sfx:"",cleanImagePath:null,finalImagePath:null,exportedAt:null,uploadedCid:null,uploadedUrl:null,overlays:[],kind:"text",background:"#101820",aspectRatio:"4:5"},Ne=[...x.cuts];Ne.splice(Math.max(0,Math.min(L,Ne.length)),0,Me);const Pe={...x,cuts:Ne},qe=await i(`/api/stories/${e}/cuts/${Qe}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Pe)});if(qe.ok)oe?D(Ee):te(Ee),await Q();else{const nt=await qe.json().catch(()=>({}));ae(nt.error||"Could not add text panel")}}catch{ae("Could not add text panel")}we(!1)}},[x,i,e,Qe,Q]),Re=w.useCallback(()=>ze((x==null?void 0:x.cuts.length)??0,!0),[ze,x]);if(w.useEffect(()=>{Q(),Te(),Ue()},[Q,Te,Ue]),j)return d.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(E)return d.jsxs("div",{className:"p-4 space-y-2","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:E}),d.jsxs("p",{className:"text-xs text-muted",children:[Qe,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema from the cartoon writing instructions."]}),d.jsx("button",{onClick:Q,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!x||x.cuts.length===0)return d.jsxs("div",{className:"p-4 text-center space-y-1",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]});const Ge=F!==null?x.cuts.find(L=>L.id===F):null;if(Ge)return d.jsx(kD,{storyName:e,cut:Ge,plotFile:Qe,language:s,authFetch:i,targetLabel:In(Ge)?`Between-scene card ${Ge.id}`:`Cut ${String(Ge.id).padStart(2,"0")}`,returnOnSave:!0,workspaceVisible:f,onToggleWorkspaceVisible:_?()=>_(!f):void 0,onSave:async(L,oe)=>{const Ee={...x,cuts:x.cuts.map(Ne=>Ne.id===F?{...Ne,overlays:L,aiDraft:oe??Ne.aiDraft??null}:Ne)};if(!await ge(Ee))throw new Error("Failed to save overlays")},onExported:()=>Q(),onClose:()=>{D(null),Q()}});const $e=x.cuts.reduce((L,oe)=>{const Ee=XS(oe);return L[Ee]++,L},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),ht=x.cuts.filter(L=>!In(L)).length,dt=x.cuts.filter(L=>$S(L)).map(L=>L.id),lt=sD({cuts:x.cuts,published:U.published}),Vt=((pr=lt.steps.find(L=>L.key==="upload"))==null?void 0:pr.status)==="done",Ci=x.cuts.some(L=>L.finalImagePath&&!L.uploadedCid)||Vt&&!U.markdownReady,ft=(We??[]).filter(L=>L.state==="needs-conversion"&&L.convertiblePng).map(L=>({cutId:L.cutId,pngPath:L.convertiblePng})),Fi=new Map(ft.map(L=>[L.cutId,L.pngPath])),En=(We??[]).filter(L=>L.state==="needs-conversion"&&L.issue).map(L=>L.issue),ln=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((Lt=Qe.match(/\d+/))==null?void 0:Lt[0])??"0",10)+1}`,Un=typeof x.title=="string"?x.title:null,on=x.cuts.filter(L=>!In(L)),gn={cuts:x.cuts.length,artwork:on.filter(L=>L.cleanImagePath||Fi.has(L.id)).length,converted:on.filter(L=>L.cleanImagePath&&/\.(webp|jpe?g)$/i.test(L.cleanImagePath)).length,lettered:x.cuts.filter(L=>{var oe;return(((oe=L.overlays)==null?void 0:oe.length)??0)>0||!!L.finalImagePath}).length,uploaded:x.cuts.filter(L=>L.uploadedCid||L.uploadedUrl).length},cn=x.cuts.filter(L=>{var oe;return Ao(L)&&(((oe=L.overlays)==null?void 0:oe.length)??0)===0&&!L.finalImagePath&&!L.uploadedCid&&!L.uploadedUrl}).length;return d.jsxs("div",{className:"h-full min-h-[22rem] flex flex-col overflow-hidden","data-testid":"cut-list-panel",children:[d.jsx("div",{className:"px-3 py-2 border-b border-border flex-shrink-0","data-testid":"cut-board-header",children:d.jsxs("div",{className:"flex items-start gap-3 justify-between",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"font-serif text-foreground truncate",children:ln}),Un&&d.jsxs("span",{className:"text-muted truncate",children:["· ",Un]})]}),d.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[gn.cuts," cuts · ",gn.artwork," artwork found ·"," ",gn.converted," converted · ",gn.lettered," ","lettered · ",gn.uploaded," uploaded"]})]}),cn>0&&d.jsx("button",{onClick:ui,disabled:_e,"data-testid":"ai-draft-all-btn",className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:_e?"Drafting…":`AI draft all unlettered (${cn})`})]})}),d.jsxs("details",{className:"border-b border-border flex-shrink-0","data-testid":"cut-advanced",children:[d.jsx("summary",{className:"px-3 py-1.5 text-[10px] text-muted cursor-pointer hover:text-foreground",children:"Technical details"}),d.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-2 text-[10px]",children:[d.jsxs("span",{className:"font-mono text-muted",children:[x.cuts.length," cuts"]}),$e.missing>0&&d.jsxs("span",{className:"text-muted",children:[$e.missing," missing"]}),$e.clean>0&&d.jsxs("span",{className:"text-green-700",children:[$e.clean," clean"]}),$e.lettered>0&&d.jsxs("span",{className:"text-amber-700",children:[$e.lettered," lettered"]}),$e.uploaded>0&&d.jsxs("span",{className:"text-green-700",children:[$e.uploaded," uploaded"]}),$e.text>0&&d.jsxs("span",{className:"text-accent",children:[$e.text," text ",$e.text===1?"panel":"panels"]}),d.jsx("button",{onClick:async()=>{fe(!0),H([]);try{const L=await i(`/api/stories/${e}/cuts/${Qe}/generate-markdown`,{method:"POST"});if(L.ok){const oe=await L.json();H(oe.warnings||[])}}catch{}fe(!1)},disabled:ie,className:"ml-auto px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"generate-markdown-btn",title:"Build the publish-ready episode from the uploaded cut images",children:ie?"Preparing…":"Prepare episode for publish"}),d.jsx("button",{onClick:Re,disabled:P,className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"add-text-panel-btn",title:"Insert a narration/title card between art panels — a solid card exported as a final image panel, no drawing needed",children:P?"Adding…":"Add narration/text panel"}),d.jsx("button",{onClick:it,disabled:He,className:"px-2 py-0.5 border border-border text-muted rounded hover:border-accent hover:text-accent disabled:opacity-50","data-testid":"refresh-assets-btn",title:"Re-check the story folder for agent-generated images and report each cut's asset state — read only, nothing is uploaded or published",children:He?"Checking…":"Refresh assets"}),d.jsx("button",{onClick:Bt,disabled:O,className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"sync-clean-btn",children:O?"Syncing...":"Sync clean images"}),d.jsx("button",{onClick:Ze,disabled:ce||!(x!=null&&x.cuts.some(L=>L.finalImagePath&&!L.uploadedCid)),className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"upload-generate-btn",title:"Upload each cut's final lettered image, then prepare the episode for publishing",children:K||"Upload & Prepare for Publish"})]})]}),d.jsxs("details",{className:"px-3 py-1.5 border-b border-border bg-surface/40 flex-shrink-0","data-testid":"cartoon-workflow-help",children:[d.jsx("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:"Cut workflow help"}),d.jsxs("div",{className:"mt-1.5",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[10px] text-muted",children:[d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"1. Letter"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"2. Export"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"3. Upload"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"4. Prepare episode for publish"})]}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted",children:["Use ",d.jsx("span",{className:"text-accent",children:"Add narration/text panel"})," ","for a narration or title card. It becomes a solid card exported as a final image."]})]})]}),dt.length>0&&d.jsxs("div",{className:"px-3 py-1.5 border-b border-amber-500/40 bg-amber-500/10 text-[10px] text-amber-700 flex-shrink-0","data-testid":"stale-bubble-export-warning",children:[dt.length===1?"Cut":"Cuts"," ",dt.join(", ")," ",dt.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export"," ",dt.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),St&&ht>0&&$e.missing===0&&be.size===0&&d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-green-600/10 text-[10px] text-green-700 flex items-center gap-1 flex-shrink-0","data-testid":"clean-assets-ready",children:[d.jsx("span",{"aria-hidden":!0,children:"✓"}),d.jsxs("span",{children:["All ",ht," clean image",ht===1?"":"s"," ","present — clean-asset generation is complete. Ready for lettering in OWS."]})]}),ne&&d.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:ne}),ft.length>0&&d.jsxs("div",{className:"px-3 py-2 border-b border-amber-500/40 bg-amber-500/10 text-[11px] flex-shrink-0","data-testid":"convert-artwork",children:[d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsxs("span",{className:"font-medium text-amber-700","data-testid":"convert-artwork-count",children:[ft.length," PNG image",ft.length===1?"":"s"," found"]}),d.jsx("button",{onClick:()=>At(ft),disabled:M,"data-testid":"convert-all-btn",className:"ml-auto px-2 py-0.5 border border-amber-500/50 text-amber-800 rounded hover:bg-amber-500/20 disabled:opacity-50",children:M?"Converting…":"Convert all to WebP"})]}),d.jsx("p",{className:"mt-1 text-[10px] text-muted",children:"PNG artwork is fine while drafting. Convert it before lettering/export so PlotLink can publish it safely."}),C&&d.jsx("p",{className:"mt-1 text-[10px] text-muted","data-testid":"convert-result",children:C}),En.length>0&&d.jsxs("details",{className:"mt-1","data-testid":"convert-technical-details",children:[d.jsx("summary",{className:"text-[10px] text-muted cursor-pointer",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc text-[10px] text-muted",children:En.map((L,oe)=>d.jsx("li",{children:L},oe))})]})]}),We&&We.length>0&&(()=>{const L=QD(We),oe=We.filter(Ee=>Ee.state==="missing");return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/40 text-[10px] flex-shrink-0","data-testid":"asset-diagnostics",children:[d.jsxs("span",{className:"text-muted","data-testid":"asset-diag-summary",children:["Assets: ",L.uploaded," uploaded · ",L.finalReady," final ·"," ",L.cleanReady," clean · ",L.planned," planned",L.needsConversion>0?` · ${L.needsConversion} needs conversion`:"",L.missing>0?` · ${L.missing} missing`:""]}),oe.length>0&&d.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:oe.map(Ee=>d.jsx("li",{children:Ee.issue},Ee.cutId))})]})})(),d.jsx(ZD,{checklist:lt,issues:Se,onFinish:Ze,finishing:ce,progressText:K,canFinish:Ci,markdownReady:U.markdownReady,published:U.published}),d.jsxs("div",{className:"flex-1 min-h-56 overflow-y-auto p-3 space-y-3","data-testid":"lettering-review-board",children:[x.cuts.map((L,oe)=>{var Ee;return d.jsxs(w.Fragment,{children:[d.jsx(xy,{index:oe,beforeLabel:oe===0?"Episode opening":`After cut ${(Ee=x.cuts[oe-1])==null?void 0:Ee.id}`,afterLabel:`Before cut ${L.id}`,disabled:P,onAdd:()=>ze(oe)}),d.jsx(iM,{cut:L,storyName:e,plotFile:Qe,expanded:I===L.id,onToggle:()=>te(I===L.id?null:L.id),authFetch:i,onUpdated:()=>{Q(),Te(),Ue()},onOpenEditor:()=>D(L.id),detectedLocalClean:Le.has(L.id),onSyncClean:Bt,syncing:O,onAiDraft:()=>{Wt(L.id,{openEditor:!0})},aiDrafting:Y===L.id,staleMessages:be.get(L.id)??[],onRepairStale:hi,repairing:xe,conversionPng:Fi.get(L.id)??null,onConvert:vt,converting:M,rowRef:Me=>{Me?mi.current.set(L.id,Me):mi.current.delete(L.id)}})]},L.id)}),d.jsx(xy,{index:x.cuts.length,beforeLabel:`After cut ${(le=x.cuts[x.cuts.length-1])==null?void 0:le.id}`,afterLabel:"Episode ending",disabled:P,onAdd:()=>ze(x.cuts.length)})]})]})}function xy({index:e,beforeLabel:t,afterLabel:i,disabled:s,onAdd:a}){return d.jsxs("div",{className:"rounded border border-dashed border-border bg-surface/35 px-3 py-2 text-[11px] text-muted flex items-center gap-3","data-testid":`between-scene-slot-${e}`,children:[d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:"font-medium text-foreground",children:"Between-scene lettering"}),d.jsxs("span",{className:"block truncate",children:[t," · ",i]})]}),d.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex-shrink-0 rounded border border-accent/40 px-2.5 py-1 text-[11px] font-medium text-accent hover:bg-accent/5 disabled:opacity-50","data-testid":`add-between-scene-${e}`,children:"Add card"})]})}function Sm({coach:e,onAction:t,className:i="",showEmptyState:s=!1}){const[a,o]=w.useState(null),c=a!==null&&a===(e==null?void 0:e.prompt);return e===void 0?null:e?d.jsx("div",{className:`m-3 rounded-lg border border-accent/40 bg-accent/10 px-4 py-3 shadow-sm ${i}`,"data-testid":"workflow-coach","data-stage":e.stageLabel,"data-action-kind":e.actionKind,"data-ui-action":e.uiAction??"",children:d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:"inline-flex rounded-full bg-background px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] text-accent","data-testid":"workflow-coach-stage",children:e.stageLabel}),d.jsxs("p",{className:"mt-1 text-sm text-foreground","data-testid":"workflow-coach-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:e.action})]}),c&&d.jsx("p",{className:"mt-1 text-[11px] font-medium text-accent",children:"Prompt copied."})]}),e.actionKind==="agent"&&e.prompt?d.jsx("button",{onClick:()=>{var p;if(!e.prompt)return;const h=e.prompt;(p=navigator.clipboard)==null||p.writeText(h).then(()=>o(h)).catch(()=>{})},"data-testid":"workflow-coach-copy",className:"flex-shrink-0 rounded bg-accent px-4 py-2.5 text-sm font-bold text-white shadow-sm transition-colors hover:bg-accent-dim",children:"Next Action"}):e.actionKind==="ui"&&e.uiAction?d.jsx("button",{onClick:()=>t(e.uiAction,e.episodeFile),"data-testid":"workflow-coach-do",className:"flex-shrink-0 rounded bg-accent px-4 py-2.5 text-sm font-bold text-white shadow-sm transition-colors hover:bg-accent-dim",children:"Next Action"}):null]})}):s?d.jsx("div",{className:`m-3 rounded-lg border border-green-700/25 bg-green-950/5 px-4 py-3 ${i}`,"data-testid":"workflow-coach","data-state":"complete",children:d.jsxs("div",{className:"flex items-start gap-3",children:[d.jsx("span",{className:"rounded-full bg-green-700/10 px-2 py-1 text-[10px] font-bold uppercase tracking-[0.16em] text-green-700",children:"Complete"}),d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsx("p",{className:"text-sm font-semibold text-foreground",children:"No next action available"}),d.jsx("p",{className:"mt-0.5 text-xs text-muted",children:"This workflow has no queued next step right now."})]})]})}):null}function nM({storyName:e,fileName:t,authFetch:i,refreshKey:s=0,onAction:a,showEmptyState:o=!1}){const[c,h]=w.useState(void 0),p=JSON.stringify([e,t??"",s]),[f,_]=w.useState(null);return f!==p&&(h(void 0),_(p)),w.useEffect(()=>{let x=!1;const b=t?`?focus=${encodeURIComponent(t)}`:"";return i(`/api/stories/${e}/progress${b}`).then(v=>v.ok?v.json():null).then(v=>{x||h((v==null?void 0:v.coach)??null)}).catch(()=>{}),()=>{x=!0}},[e,t,i,s]),d.jsx(Sm,{coach:c,onAction:a,showEmptyState:o})}const rM=1024*1024,sM=["image/webp","image/jpeg"],aM="Cover: WebP or JPEG, max 1MB, 600×900 portrait recommended. Use clean cover art — avoid unreadable AI text or broken lettering.";function lM(e){return e.attached?{state:"attached",label:"Cover attached to your story.",tone:"success"}:e.invalid?{state:"invalid",label:"Cover file can't be used — must be WebP or JPEG, max 1MB.",tone:"error"}:e.hasSelectedCover?{state:"selected",label:"Cover selected — it will be uploaded when you publish.",tone:"accent"}:{state:"none",label:"No cover yet — add one before publishing (recommended).",tone:"muted"}}function _y(e){return e.size>rM?"Image exceeds 1MB limit":sM.includes(e.type)?null:"Only WebP and JPEG images are accepted"}async function oM(e,t,i){const s=new FormData;s.append("file",i);const a=await e("/api/publish/upload-cover",{method:"POST",body:s});if(!a.ok)return null;const{cid:o}=await a.json();return!o||!(await e("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:t,coverCid:o})})).ok?null:o}function Pp(e){const t=e.match(/^#\s+(.+)$/m),i=t?t[1].trim():"";return i||null}function cM(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ")}function zo(e,t){const i=(e??"").trim().toLowerCase();if(!i)return!0;if(t==="genesis.md")return i==="genesis";const s=t.match(/^(plot-\d+)\.md$/);return s?i===s[1].toLowerCase()||/^plot-\d+$/.test(i):!1}function uM(e){const t=e.match(/^plot-(\d+)\.md$/);if(!t)return null;const i=t[1];return`Episode ${i.length<2?i.padStart(2,"0"):i}`}function Ip(e){const t=(e??"").trim();return!!(!t||/^(?:episode|ep|chapter|ch|part|pt|plot)\.?\s*[-–—:#]?\s*\d+$/i.test(t)||/^\d+$/.test(t)||/^plot[-_\s]?\d+$/i.test(t))}function wm(e){var s;const t=Pp(e.fileContent);if(t)return!Ip(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!Ip(i)}function Cm(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=Pp(i);if(t==="genesis.md"){const p=a?Pp(a):null;return(h??p??cM(s)).slice(0,60)}if(h)return h.slice(0,60);if(o==="cartoon"){const p=c==null?void 0:c.trim(),f=uM(t);return((p||f)??t.replace(/\.md$/,"")).slice(0,60)}return t.replace(/\.md$/,"").slice(0,60)}function hM(e){return!!(e!=null&&e.txHash)&&(e==null?void 0:e.plotIndex)!=null&&e.plotIndex>0}function dM(e){return hM(e)&&(e==null?void 0:e.status)!=="published-not-indexed"}function by(e,t,i){if(e[t]==="cartoon"&&!i)return"cartoon"}function fM(e,t,i){return!(e!=="cartoon"||t||!i||i.startsWith("_new_"))}function Lf(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function Of(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?(t/1e18).toFixed(6):null}function pM(e){return!!e&&e.ready===!1}function mM(e){const t=Of(e.requiredBalance)??Of(e.creationFee),i=Of(e.ethBalance);return e.hasEnoughEth===!1&&t&&i?`Insufficient ETH: need at least ${t} ETH to publish; current balance is ${i} ETH.`+(e.address?` Top up the OWS wallet (${e.address}) and try again.`:" Top up the OWS wallet and try again."):e.error||"Publish preflight failed — the OWS wallet isn't ready to publish."}const gM={...gl,attributes:{...gl.attributes,img:["src","alt","title"]}},xM="https://ipfs.filebase.io/ipfs/";function _M(e){const t=[],i=/!\[([^\]]*)\]\(([^)]+)\)/g;let s;for(;(s=i.exec(e))!==null;)t.push({full:s[0],alt:s[1],url:s[2]});return t}function bM(e){const t=_M(e),i=[];for(const a of t)a.url.startsWith(xM)||i.push(`Non-IPFS image URL: ${a.url.length>60?a.url.slice(0,60)+"...":a.url}`);return e.match(/!\[[^\]]*\]\([^)]*$|!\[[^\]]*$(?!\])/gm)&&i.push("Malformed image markdown detected — check brackets and parentheses"),{count:t.length,warnings:i}}function vM({storyName:e,fileName:t,authFetch:i,onPublish:s,publishingFile:a,walletAddress:o,contentType:c="fiction",language:h,genre:p,isNsfw:f,hasGenesis:_=!1,onViewProgress:x,onOpenFile:b,onViewPublish:v,focusedLetteringMode:S=!1,focusedLetteringWorkspaceVisible:j=!1,onFocusedLetteringModeChange:R,onFocusedLetteringWorkspaceVisibleChange:E}){const[N,I]=w.useState(null),[te,F]=w.useState(!1),[D,ie]=w.useState("preview"),[fe,Se]=w.useState("publish"),[H,ce]=w.useState("text"),[W,K]=w.useState(null),X=w.useCallback((re,ye)=>{ie("edit"),K(ke=>({cutId:re,openEditor:ye,seq:((ke==null?void 0:ke.seq)??0)+1}))},[]),[U,A]=w.useState(""),[O,$]=w.useState(!1),[xe,T]=w.useState(!1),[M,G]=w.useState(!1),[C,V]=w.useState(null),[ne,ae]=w.useState(""),[Y,he]=w.useState(""),[_e,Be]=w.useState(!1),[Le,je]=w.useState(null),[be,tt]=w.useState(0),[St,ot]=w.useState(0),[We,Mt]=w.useState(null),[He,xt]=w.useState(null),[Ae,Kt]=w.useState(null),[mi,wt]=w.useState(0),Qe=w.useRef(null),Q=w.useRef(!1),[ge,Te]=w.useState(!1),[Ue,it]=w.useState(dl[0]),[Wt,ui]=w.useState(ts[0]),[Bt,vt]=w.useState(!1),[At,Ze]=w.useState(null),[hi,P]=w.useState(null),[we,ze]=w.useState(!1),[Re,Ge]=w.useState(!1),[$e,ht]=w.useState(!1),[dt,lt]=w.useState(null),[Vt,Ci]=w.useState(!1),ft=w.useRef(null),Fi=w.useRef(null),[En,ln]=w.useState(!1),[Un,on]=w.useState(null),[gn,cn]=w.useState(null),[pr,Lt]=w.useState("unknown"),le=w.useRef(!1),[L,oe]=w.useState(!1),[Ee,Me]=w.useState(!1),[Ne,Pe]=w.useState(null),[qe,nt]=w.useState([]),[Ve,Et]=w.useState(null),Nt=w.useRef(null),Gt=w.useRef(null),Rt=w.useCallback(async()=>{if(!e||!t){I(null);return}const re=`${e}/${t}`,ye=Gt.current!==re;ye&&(Gt.current=re);try{const ke=await i(`/api/stories/${e}/${t}`);if(ke.ok){const Je=await ke.json();I(Je),(ye||!Q.current)&&(A(Je.content??""),ye&&(T(!1),Q.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{F(!0),Rt().finally(()=>F(!1))},[Rt]),w.useEffect(()=>{if(!e||!t||D==="edit"&&xe)return;const re=setInterval(Rt,3e3);return()=>clearInterval(re)},[e,t,Rt,D,xe]);const[ki,mr]=w.useState(null),Jt=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!Jt||!e){mr(null);return}let re=!1;return i(`/api/stories/${e}/cuts/genesis`).then(ye=>ye.ok?ye.json():null).then(ye=>{re||mr(ye?Op(ye.cuts||[]):null)}).catch(()=>{re||mr(null)}),()=>{re=!0}},[Jt,e,i]);const qi=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!qi||!e||!t){je(null),tt(0),ot(0),Mt(null);return}let re=!1;const ye=t.replace(/\.md$/,"");return Mt(null),(async()=>{try{const[ke,Je]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${ye}`)]);if(re)return;if(!Je.ok){je("error"),tt(0),ot(0),Mt(null);return}const Pt=await Je.json(),Ni=Pt.cuts||[],Gn=ke.ok?(await ke.json()).content??"":"",or=WS(Gn,Ni);re||(je(or.stage),tt(or.awaitingCount),ot(or.totalCuts),Mt(Op(Ni)),Kt(typeof Pt.title=="string"?Pt.title:null))}catch{re||(je("error"),tt(0),ot(0),Mt(null))}})(),()=>{re=!0}},[qi,e,t,i,N==null?void 0:N.content,N==null?void 0:N.status,mi]),w.useEffect(()=>{if(!e){xt(null);return}let re=!1;return i(`/api/stories/${e}/structure.md`).then(ye=>ye.ok?ye.json():null).then(ye=>{re||xt((ye==null?void 0:ye.content)??null)}).catch(()=>{}),()=>{re=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const re=Cu(p);let ye=re??"";if(!re&&He){const Je=He.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);Je&&(ye=Cu(Je[1].replace(/\*+/g,"").trim())??"")}ae(ye);let ke=h&&ts.find(Je=>Je.toLowerCase()===h.toLowerCase())||"";if(!ke&&He){const Je=He.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);Je&&(ke=ts.find(Pt=>Pt.toLowerCase()===Je[1].replace(/\*+/g,"").trim().toLowerCase())||"")}he(ke),Be(f??!1)},[e,p,h,f,He]);const $n=w.useCallback(re=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(re)}).catch(()=>{})},[e,i]),gr=w.useCallback(async()=>{if(!(!e||!t)){$(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:U})})).ok&&(T(!1),Q.current=!1,I(ye=>ye&&{...ye,content:U}))}catch{}$(!1)}},[e,t,i,U]),ei=w.useCallback(async()=>{if(!e||!t)return;const re=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${re}/generate-markdown`,{method:"POST"})).ok&&(await Rt(),wt(ke=>ke+1))}catch{}},[e,t,i,Rt]),Br=w.useCallback((re,ye)=>{if(re==="view-progress"){x==null||x();return}if(ye&&ye!==t){b==null||b(ye);return}switch(re){case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":ie("edit"),ce("cuts");break;case"generate-markdown":ei();break;case"publish":ie("preview");break}},[t,x,b,ei]),Fn=w.useCallback(re=>{var Je;const ye=(Je=re.target.files)==null?void 0:Je[0];if(!ye)return;le.current=!0,on(null),cn(null);const ke=_y(ye);if(ke){Ze(null),P(Pt=>(Pt&&URL.revokeObjectURL(Pt),null)),ft.current&&(ft.current.value=""),lt(ke),Lt("invalid");return}Ze(ye),P(Pt=>(Pt&&URL.revokeObjectURL(Pt),URL.createObjectURL(ye))),lt(null),Lt("selected")},[]),ar=w.useCallback(async re=>{var ke;const ye=(ke=re.target.files)==null?void 0:ke[0];if(Fi.current&&(Fi.current.value=""),!(!ye||!e)){le.current=!0,on(null),ln(!0),lt(null);try{let Je;try{Je=await Ku(ye)}catch(vr){Ze(null),P(Yi=>(Yi&&URL.revokeObjectURL(Yi),null)),lt(vr instanceof Error?vr.message:"Could not import image");return}const Pt=Je.type==="image/jpeg"?"jpg":"webp",Ni=new File([Je],`cover.${Pt}`,{type:Je.type}),Gn=new FormData;Gn.append("file",Ni);const or=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:Gn});if(!or.ok){const vr=await or.json().catch(()=>({}));lt(vr.error||"Cover import failed");return}Ze(Ni),P(vr=>(vr&&URL.revokeObjectURL(vr),URL.createObjectURL(Ni))),cn(null),Lt("selected"),lt(null)}catch{lt("Cover import failed")}finally{ln(!1)}}},[e,i]),Wi=w.useCallback(async re=>{if(re.size>1024*1024){Pe("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(re.type)){Pe("Only WebP and JPEG images are accepted");return}Me(!0),Pe(null);try{const ke=new FormData;ke.append("file",re);const Je=await i("/api/publish/upload-plot-image",{method:"POST",body:ke});if(!Je.ok){const Ni=await Je.json();throw new Error(Ni.error||"Upload failed")}const Pt=await Je.json();nt(Ni=>[...Ni,{cid:Pt.cid,url:Pt.url}])}catch(ke){Pe(ke instanceof Error?ke.message:"Upload failed")}finally{Me(!1),Nt.current&&(Nt.current.value="")}},[i]),Ct=w.useCallback(re=>{var ke;const ye=(ke=re.target.files)==null?void 0:ke[0];ye&&Wi(ye)},[Wi]),qn=w.useCallback(async()=>{if(N!=null&&N.storylineId){ze(!0),lt(null),Ci(!1);try{let re;if(At){const ke=new FormData;ke.append("file",At);const Je=await i("/api/publish/upload-cover",{method:"POST",body:ke});if(!Je.ok){const Ni=await Je.json();throw new Error(Ni.error||"Cover upload failed")}re=(await Je.json()).cid}const ye=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:N.storylineId,...re!==void 0&&{coverCid:re},genre:Ue,language:Wt,isNsfw:Bt})});if(!ye.ok){const ke=await ye.json();throw new Error(ke.error||"Update failed")}Ci(!0),Ze(null),re!==void 0&&(ht(!0),P(ke=>(ke&&URL.revokeObjectURL(ke),null)),Lt("unknown"),ft.current&&(ft.current.value="")),setTimeout(()=>Ci(!1),3e3)}catch(re){lt(re instanceof Error?re.message:"Update failed")}finally{ze(!1)}}},[N==null?void 0:N.storylineId,At,Ue,Wt,Bt,i]);w.useEffect(()=>{Te(!1),Ze(null),P(null),lt(null),Ci(!1),Ge(!1),oe(!1),nt([]),Pe(null),on(null),cn(null),Lt("unknown"),le.current=!1,ce("text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!N||N.storylineId||N.status==="published"||N.status==="published-not-indexed"||le.current)return;let re=!1;return(async()=>{try{const ye=await i(`/api/stories/${e}/cover-asset`);if(re||!ye.ok)return;const ke=await ye.json();if(re)return;if(!(ke!=null&&ke.found)){Lt("none");return}if(!ke.valid){cn(ke.error||"Detected cover asset is invalid and was not used"),Lt("invalid");return}const Je=await i(`/api/stories/${e}/asset/${ke.path.replace(/^assets\//,"")}`);if(re||!Je.ok)return;const Pt=await Je.blob(),Ni=new File([Pt],ke.path.split("/").pop()||"cover.webp",{type:ke.type});if(_y(Ni)||re||le.current)return;Ze(Ni),P(Gn=>(Gn&&URL.revokeObjectURL(Gn),URL.createObjectURL(Ni))),on(ke.path),Lt("detected")}catch{}})(),()=>{re=!0}},[e,t,N,N==null?void 0:N.status,N==null?void 0:N.storylineId,i]),w.useEffect(()=>{if(!ge||!(N!=null&&N.storylineId))return;Ge(!1);const re="https://plotlink.xyz";let ye=!1;return fetch(`${re}/api/storyline/${N.storylineId}`).then(ke=>ke.ok?ke.json():null).then(ke=>{if(!ye){if(!ke){lt("Could not load current story metadata");return}if(ke.genre){const Je=Cu(ke.genre);Je&&it(Je)}if(ke.language){const Je=ts.find(Pt=>Pt.toLowerCase()===ke.language.toLowerCase());Je&&ui(Je)}ke.isNsfw!==void 0&&vt(!!ke.isNsfw),ht(!!(ke.coverCid||ke.coverUrl||ke.cover)),Ge(!0)}}).catch(()=>{ye||lt("Could not load current story metadata")}),()=>{ye=!0}},[ge,N==null?void 0:N.storylineId]),w.useEffect(()=>{if(D!=="edit")return;const re=ye=>{(ye.metaKey||ye.ctrlKey)&&ye.key==="s"&&(ye.preventDefault(),gr())};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[D,gr]),w.useEffect(()=>{if((N==null?void 0:N.status)!=="published-not-indexed"||!N.publishedAt)return;const re=new Date(N.publishedAt).getTime(),ye=300*1e3,ke=()=>{const Pt=Math.max(0,ye-(Date.now()-re));V(Pt)};ke();const Je=setInterval(ke,1e3);return()=>clearInterval(Je)},[N==null?void 0:N.status,N==null?void 0:N.publishedAt]);const ya=C!==null&&C<=0,Lr=C!==null&&C>0?`${Math.floor(C/6e4)}:${String(Math.floor(C%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),d.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(te&&!N)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const xr=(D==="edit"?U:(N==null?void 0:N.content)??"").length,Ei=t==="genesis.md",gi=t?/^plot-\d+\.md$/.test(t):!1,Gi=c==="cartoon"&&gi,Nn=c==="cartoon"&&Ei,Or=Nn||Gi,jn=(N==null?void 0:N.status)==="published"||(N==null?void 0:N.status)==="published-not-indexed",Sa=S&&Or,yl=Nn?ki?ki.total:null:Gi?Le===null?null:St:null,_r=lD({fileName:t??"",contentType:c,hasGenesis:_,isPublished:jn,cutCount:yl,cutProgress:Nn?ki:null}),Go=(Nn||Gi)&&!jn,as=Go?Cm({fileName:t,fileContent:(N==null?void 0:N.content)??"",storySlug:e??"",structureContent:He,contentType:"cartoon",episodeTitle:Ae}):null,wa=!!as&&zo(as,t),Ca=Gi&&!jn&&!wm({fileContent:(N==null?void 0:N.content)??"",episodeTitle:Ae}),qs=Nn&&!jn?bm((N==null?void 0:N.content)??""):null,Yo=!!qs&&qs.blockers.length>0,ka="w-full max-w-[32rem] rounded-xl border px-3 py-3",lr={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},Ea=re=>{if(!Nn)return null;const ye=lM({hasSelectedCover:!!At,invalid:pr==="invalid",attached:re});return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":ye.state,children:[d.jsx("span",{className:`text-[11px] font-medium ${lr[ye.tone]}`,children:ye.label}),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cover-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Cover tips"}),d.jsx("span",{className:"block mt-0.5","data-testid":"cartoon-cover-guidance",children:aM})]})]})},Ws=wa||Ca,ls=()=>{if(!Go||!as)return null;const re=Ei?"Story title":"Episode title";return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":wa?"true":"false","data-blocked":Ws?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[re,":"]})," ",d.jsx("span",{className:Ws?"text-error font-medium":"text-foreground",children:as})]}),wa?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename."," ",Ei?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," ","before publishing."]}):Ca?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",as,"” is a generic placeholder, not a reader-facing title, so it can’t be published. Set a real episode title in the cut plan (or add a “# Title” to the episode) — e.g. “Episode 01 — The Couple Coupon” — before publishing."]}):null]})},os=()=>qs?d.jsxs("div",{className:"flex flex-col gap-1 rounded border border-border bg-surface/50 p-2","data-testid":"cartoon-genesis-readiness","data-blocked":Yo?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.jsx("span",{className:"text-[10px] text-muted","data-testid":"genesis-readiness-hint",children:"Genesis is the first thing readers see. Write it as the story opening/prologue, not a synopsis — set up the premise and stakes, then bridge into Episode 01."}),qs.blockers.map((re,ye)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:re},`b-${ye}`)),qs.warnings.map((re,ye)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:re},`w-${ye}`))]}):null,cs=Ei||gi?1e4:null,us=!jn&&cs!==null&&xr>cs,Ko=(N==null?void 0:N.content)??"",br=jn?{count:0,warnings:[]}:bM(Ko),Wn=d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden","data-testid":"prose-editor-shell",style:{background:"var(--paper-bg)"},children:[d.jsx("textarea",{ref:Qe,value:U,onChange:re=>{A(re.target.value),T(!0),Q.current=!0},className:"flex-1 min-h-0 w-full resize-none px-4 py-3 text-sm leading-relaxed focus:outline-none",style:{fontFamily:'"Geist Mono", ui-monospace, monospace',background:"var(--paper-bg)",color:"var(--text)"},spellCheck:!1,"data-testid":"prose-editor-textarea"}),d.jsxs("div",{className:"shrink-0 px-3 py-1.5 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"prose-editor-savebar",children:[d.jsx("span",{className:"text-xs text-muted",children:xe?"Unsaved changes":"No changes"}),d.jsx("button",{onClick:gr,disabled:!xe||O,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:O?"Saving...":"Save"})]})]});return d.jsxs("div",{className:"h-full min-h-0 flex flex-col",children:[!Sa&&d.jsxs("div",{className:"border-b border-border",children:[d.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[x&&d.jsx("button",{onClick:x,"data-testid":"view-progress-btn",className:"text-accent hover:underline font-sans",title:"Story progress overview",children:"← Progress"}),d.jsxs("span",{children:[e,"/",t]}),(N==null?void 0:N.status)==="published"&&d.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(N==null?void 0:N.status)==="published-not-indexed"&&d.jsx("span",{className:"text-amber-700 font-medium",title:N.indexError,children:"Published (not indexed)"}),(N==null?void 0:N.status)==="pending"&&d.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:`text-xs font-mono ${us?"text-error font-medium":"text-muted"}`,children:[xr.toLocaleString(),cs!==null?`/${cs.toLocaleString()}`:" chars"]}),us&&d.jsxs("span",{className:"text-error text-xs font-medium",children:[(xr-cs).toLocaleString()," over limit"]})]})]}),d.jsxs("div",{className:"flex px-3 gap-1",children:[d.jsx("button",{onClick:()=>ie("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${D==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),d.jsxs("button",{onClick:()=>ie("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${D==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",xe&&d.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),!Sa&&c==="cartoon"&&e&&t&&d.jsx(nM,{storyName:e,fileName:t,authFetch:i,refreshKey:mi,onAction:Br,showEmptyState:!0}),D==="preview"?Gi?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"cartoon-mode-publish",onClick:()=>Se("publish"),className:`px-2 py-0.5 text-[11px] rounded ${fe==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),d.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>Se("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${fe==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:fe==="publish"?d.jsx(hD,{content:(N==null?void 0:N.content)??"",stage:Le}):d.jsx(K3,{storyName:e,fileName:t,authFetch:i,onEditCut:X})})]}):d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:N!=null&&N.content?d.jsx("div",{className:"prose max-w-none",children:d.jsx(rS,{remarkPlugins:[aS,AS],rehypePlugins:[[BS,gM]],children:N.content})}):d.jsx("p",{className:"text-muted italic",children:"No content"})}):Gi?d.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:d.jsx(gy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>wt(re=>re+1),focusRequest:W,onFocusHandled:()=>K(null),onFocusedLetteringModeChange:R,workspaceVisible:j,onWorkspaceVisibleChange:E})}):Nn?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"genesis-edit-mode-text",onClick:()=>ce("text"),className:`px-2 py-0.5 text-[11px] rounded ${H==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),d.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>ce("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${H==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:H==="cuts"?d.jsx(gy,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>wt(re=>re+1),focusRequest:W,onFocusHandled:()=>K(null),onFocusedLetteringModeChange:R,workspaceVisible:j,onWorkspaceVisibleChange:E}):Wn})]}):Wn,!Sa&&d.jsx("div",{className:"shrink-0 px-3 py-2 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"preview-panel-footer",children:t==="structure.md"?d.jsx("p",{className:"text-muted text-xs italic","data-testid":"footer-guidance",children:_r}):(N==null?void 0:N.status)==="published-not-indexed"?d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!ya&&d.jsx("button",{onClick:async()=>{if(!(!e||!t||!N.txHash)){G(!0);try{(await(await i("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:N.txHash,content:N.content,storylineId:N.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:N.txHash,storylineId:N.storylineId,contentCid:"",gasCost:""})}),Rt())}catch{}G(!1)}},disabled:M,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:M?"Retrying...":`Retry Index${Lr?` (${Lr})`:""}`}),gi&&d.jsx("button",{onClick:()=>{!e||!t||!window.confirm(`This episode is already on-chain — try “Retry Index” first. +`,...o.current()});return/^[\t ]/.test(f)&&(f=Po(f.charCodeAt(0))+f.slice(1)),f=f?c+" "+f:c,i.options.closeAtx&&(f+=" "+c),p(),h(),f}mS.peek=gR;function mS(e){return e.value||""}function gR(){return"<"}gS.peek=xR;function gS(e,t,i,s){const a=pm(i),o=a==='"'?"Quote":"Apostrophe",c=i.enter("image");let h=i.enter("label");const p=i.createTracker(s);let f=p.move("![");return f+=p.move(i.safe(e.alt,{before:f,after:"]",...p.current()})),f+=p.move("]("),h(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(h=i.enter("destinationLiteral"),f+=p.move("<"),f+=p.move(i.safe(e.url,{before:f,after:">",...p.current()})),f+=p.move(">")):(h=i.enter("destinationRaw"),f+=p.move(i.safe(e.url,{before:f,after:e.title?" ":")",...p.current()}))),h(),e.title&&(h=i.enter(`title${o}`),f+=p.move(" "+a),f+=p.move(i.safe(e.title,{before:f,after:a,...p.current()})),f+=p.move(a),h()),f+=p.move(")"),c(),f}function xR(){return"!"}xS.peek=_R;function xS(e,t,i,s){const a=e.referenceType,o=i.enter("imageReference");let c=i.enter("label");const h=i.createTracker(s);let p=h.move("![");const f=i.safe(e.alt,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),c();const _=i.stack;i.stack=[],c=i.enter("reference");const x=i.safe(i.associationId(e),{before:p,after:"]",...h.current()});return c(),i.stack=_,o(),a==="full"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function _R(){return"!"}_S.peek=bR;function _S(e,t,i){let s=e.value||"",a="`",o=-1;for(;new RegExp("(^|[^`])"+a+"([^`]|$)").test(s);)a+="`";for(/[^ \r\n]/.test(s)&&(/^[ \r\n]/.test(s)&&/[ \r\n]$/.test(s)||/^`|`$/.test(s))&&(s=" "+s+" ");++o\u007F]/.test(e.url))}vS.peek=vR;function vS(e,t,i,s){const a=pm(i),o=a==='"'?"Quote":"Apostrophe",c=i.createTracker(s);let h,p;if(bS(e,i)){const _=i.stack;i.stack=[],h=i.enter("autolink");let x=c.move("<");return x+=c.move(i.containerPhrasing(e,{before:x,after:">",...c.current()})),x+=c.move(">"),h(),i.stack=_,x}h=i.enter("link"),p=i.enter("label");let f=c.move("[");return f+=c.move(i.containerPhrasing(e,{before:f,after:"](",...c.current()})),f+=c.move("]("),p(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(p=i.enter("destinationLiteral"),f+=c.move("<"),f+=c.move(i.safe(e.url,{before:f,after:">",...c.current()})),f+=c.move(">")):(p=i.enter("destinationRaw"),f+=c.move(i.safe(e.url,{before:f,after:e.title?" ":")",...c.current()}))),p(),e.title&&(p=i.enter(`title${o}`),f+=c.move(" "+a),f+=c.move(i.safe(e.title,{before:f,after:a,...c.current()})),f+=c.move(a),p()),f+=c.move(")"),h(),f}function vR(e,t,i){return bS(e,i)?"<":"["}yS.peek=yR;function yS(e,t,i,s){const a=e.referenceType,o=i.enter("linkReference");let c=i.enter("label");const h=i.createTracker(s);let p=h.move("[");const f=i.containerPhrasing(e,{before:p,after:"]",...h.current()});p+=h.move(f+"]["),c();const _=i.stack;i.stack=[],c=i.enter("reference");const x=i.safe(i.associationId(e),{before:p,after:"]",...h.current()});return c(),i.stack=_,o(),a==="full"||!f||f!==x?p+=h.move(x+"]"):a==="shortcut"?p=p.slice(0,-1):p+=h.move("]"),p}function yR(){return"["}function mm(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function SR(e){const t=mm(e),i=e.options.bulletOther;if(!i)return t==="*"?"-":"*";if(i!=="*"&&i!=="+"&&i!=="-")throw new Error("Cannot serialize items with `"+i+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(i===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+i+"`) to be different");return i}function wR(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function SS(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function CR(e,t,i,s){const a=i.enter("list"),o=i.bulletCurrent;let c=e.ordered?wR(i):mm(i);const h=e.ordered?c==="."?")":".":SR(i);let p=t&&i.bulletLastUsed?c===i.bulletLastUsed:!1;if(!e.ordered){const _=e.children?e.children[0]:void 0;if((c==="*"||c==="-")&&_&&(!_.children||!_.children[0])&&i.stack[i.stack.length-1]==="list"&&i.stack[i.stack.length-2]==="listItem"&&i.stack[i.stack.length-3]==="list"&&i.stack[i.stack.length-4]==="listItem"&&i.indexStack[i.indexStack.length-1]===0&&i.indexStack[i.indexStack.length-2]===0&&i.indexStack[i.indexStack.length-3]===0&&(p=!0),SS(i)===c&&_){let x=-1;for(;++x-1?t.start:1)+(i.options.incrementListMarker===!1?0:t.children.indexOf(e))+o);let c=o.length+1;(a==="tab"||a==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(c=Math.ceil(c/4)*4);const h=i.createTracker(s);h.move(o+" ".repeat(c-o.length)),h.shift(c);const p=i.enter("listItem"),f=i.indentLines(i.containerFlow(e,h.current()),_);return p(),f;function _(x,b,v){return b?(v?"":" ".repeat(c))+x:(v?o:o+" ".repeat(c-o.length))+x}}function NR(e,t,i,s){const a=i.enter("paragraph"),o=i.enter("phrasing"),c=i.containerPhrasing(e,s);return o(),a(),c}const jR=Gu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function TR(e,t,i,s){return(e.children.some(function(c){return jR(c)})?i.containerPhrasing:i.containerFlow).call(i,e,s)}function AR(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}wS.peek=RR;function wS(e,t,i,s){const a=AR(i),o=i.enter("strong"),c=i.createTracker(s),h=c.move(a+a);let p=c.move(i.containerPhrasing(e,{after:a,before:h,...c.current()}));const f=p.charCodeAt(0),_=Lu(s.before.charCodeAt(s.before.length-1),f,a);_.inside&&(p=Po(f)+p.slice(1));const x=p.charCodeAt(p.length-1),b=Lu(s.after.charCodeAt(0),x,a);b.inside&&(p=p.slice(0,-1)+Po(x));const v=c.move(a+a);return o(),i.attentionEncodeSurroundingInfo={after:b.outside,before:_.outside},h+p+v}function RR(e,t,i){return i.options.strong||"*"}function DR(e,t,i,s){return i.safe(e.value,s)}function MR(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function BR(e,t,i){const s=(SS(i)+(i.options.ruleSpaces?" ":"")).repeat(MR(i));return i.options.ruleSpaces?s.slice(0,-1):s}const CS={blockquote:nR,break:Kv,code:cR,definition:hR,emphasis:pS,hardBreak:Kv,heading:mR,html:mS,image:gS,imageReference:xS,inlineCode:_S,link:vS,linkReference:yS,list:CR,listItem:ER,paragraph:NR,root:TR,strong:wS,text:DR,thematicBreak:BR};function LR(){return{enter:{table:OR,tableData:Vv,tableHeader:Vv,tableRow:PR},exit:{codeText:IR,table:zR,tableData:Df,tableHeader:Df,tableRow:Df}}}function OR(e){const t=e._align;this.enter({type:"table",align:t.map(function(i){return i==="none"?null:i}),children:[]},e),this.data.inTable=!0}function zR(e){this.exit(e),this.data.inTable=void 0}function PR(e){this.enter({type:"tableRow",children:[]},e)}function Df(e){this.exit(e)}function Vv(e){this.enter({type:"tableCell",children:[]},e)}function IR(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,HR));const i=this.stack[this.stack.length-1];i.type,i.value=t,this.exit(e)}function HR(e,t){return t==="|"?t:e}function UR(e){const t=e||{},i=t.tableCellPadding,s=t.tablePipeAlign,a=t.stringLength,o=i?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` +`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:b,table:c,tableCell:p,tableRow:h}};function c(v,S,j,D){return f(_(v,j,D),v.align)}function h(v,S,j,D){const E=x(v,j,D),N=f([E]);return N.slice(0,N.indexOf(` +`))}function p(v,S,j,D){const E=j.enter("tableCell"),N=j.enter("phrasing"),I=j.containerPhrasing(v,{...D,before:o,after:o});return N(),E(),I}function f(v,S){return tR(v,{align:S,alignDelimiters:s,padding:i,stringLength:a})}function _(v,S,j){const D=v.children;let E=-1;const N=[],I=S.enter("table");for(;++E0&&!i&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),i}const s3={tokenize:f3,partial:!0};function a3(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:u3,continuation:{tokenize:h3},exit:d3}},text:{91:{name:"gfmFootnoteCall",tokenize:c3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:l3,resolveTo:o3}}}}function l3(e,t,i){const s=this;let a=s.events.length;const o=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let c;for(;a--;){const p=s.events[a][1];if(p.type==="labelImage"){c=p;break}if(p.type==="gfmFootnoteCall"||p.type==="labelLink"||p.type==="label"||p.type==="image"||p.type==="link")break}return h;function h(p){if(!c||!c._balanced)return i(p);const f=fr(s.sliceSerialize({start:c.end,end:s.now()}));return f.codePointAt(0)!==94||!o.includes(f.slice(1))?i(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function o3(e,t){let i=e.length;for(;i--;)if(e[i][1].type==="labelImage"&&e[i][0]==="enter"){e[i][1];break}e[i+1][1].type="data",e[i+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},e[i+3][1].start),end:Object.assign({},e[e.length-1][1].end)},a={type:"gfmFootnoteCallMarker",start:Object.assign({},e[i+3][1].end),end:Object.assign({},e[i+3][1].end)};a.end.column++,a.end.offset++,a.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},c={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},h=[e[i+1],e[i+2],["enter",s,t],e[i+3],e[i+4],["enter",a,t],["exit",a,t],["enter",o,t],["enter",c,t],["exit",c,t],["exit",o,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(i,e.length-i+1,...h),e}function c3(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o=0,c;return h;function h(x){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),p}function p(x){return x!==94?i(x):(e.enter("gfmFootnoteCallMarker"),e.consume(x),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",f)}function f(x){if(o>999||x===93&&!c||x===null||x===91||qt(x))return i(x);if(x===93){e.exit("chunkString");const b=e.exit("gfmFootnoteCallString");return a.includes(fr(s.sliceSerialize(b)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(x),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):i(x)}return qt(x)||(c=!0),o++,e.consume(x),x===92?_:f}function _(x){return x===91||x===92||x===93?(e.consume(x),o++,f):f(x)}}function u3(e,t,i){const s=this,a=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o,c=0,h;return p;function p(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",_):i(S)}function _(S){if(c>999||S===93&&!h||S===null||S===91||qt(S))return i(S);if(S===93){e.exit("chunkString");const j=e.exit("gfmFootnoteDefinitionLabelString");return o=fr(s.sliceSerialize(j)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),b}return qt(S)||(h=!0),c++,e.consume(S),S===92?x:_}function x(S){return S===91||S===92||S===93?(e.consume(S),c++,_):_(S)}function b(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),a.includes(o)||a.push(o),kt(e,v,"gfmFootnoteDefinitionWhitespace")):i(S)}function v(S){return t(S)}}function h3(e,t,i){return e.check(Wo,t,e.attempt(s3,t,i))}function d3(e){e.exit("gfmFootnoteDefinition")}function f3(e,t,i){const s=this;return kt(e,a,"gfmFootnoteDefinitionIndent",5);function a(o){const c=s.events[s.events.length-1];return c&&c[1].type==="gfmFootnoteDefinitionIndent"&&c[2].sliceSerialize(c[1],!0).length===4?t(o):i(o)}}function p3(e){let i=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:o,resolveAll:a};return i==null&&(i=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function a(c,h){let p=-1;for(;++p1?p(S):(c.consume(S),x++,v);if(x<2&&!i)return p(S);const D=c.exit("strikethroughSequenceTemporary"),E=ml(S);return D._open=!E||E===2&&!!j,D._close=!j||j===2&&!!E,h(S)}}}class m3{constructor(){this.map=[]}add(t,i,s){g3(this,t,i,s)}consume(t){if(this.map.sort(function(o,c){return o[0]-c[0]}),this.map.length===0)return;let i=this.map.length;const s=[];for(;i>0;)i-=1,s.push(t.slice(this.map[i][0]+this.map[i][1]),this.map[i][2]),t.length=this.map[i][0];s.push(t.slice()),t.length=0;let a=s.pop();for(;a;){for(const o of a)t.push(o);a=s.pop()}this.map.length=0}}function g3(e,t,i,s){let a=0;if(!(i===0&&s.length===0)){for(;a-1;){const Y=s.events[ne][1].type;if(Y==="lineEnding"||Y==="linePrefix")ne--;else break}const F=ne>-1?s.events[ne][1].type:null,G=F==="tableHead"||F==="tableRow"?R:p;return G===R&&s.parser.lazy[s.now().line]?i(B):G(B)}function p(B){return e.enter("tableHead"),e.enter("tableRow"),f(B)}function f(B){return B===124||(c=!0,o+=1),_(B)}function _(B){return B===null?i(B):Ye(B)?o>1?(o=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(B),e.exit("lineEnding"),v):i(B):xt(B)?kt(e,_,"whitespace")(B):(o+=1,c&&(c=!1,a+=1),B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),c=!0,_):(e.enter("data"),x(B)))}function x(B){return B===null||B===124||qt(B)?(e.exit("data"),_(B)):(e.consume(B),B===92?b:x)}function b(B){return B===92||B===124?(e.consume(B),x):x(B)}function v(B){return s.interrupt=!1,s.parser.lazy[s.now().line]?i(B):(e.enter("tableDelimiterRow"),c=!1,xt(B)?kt(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(B):S(B))}function S(B){return B===45||B===58?D(B):B===124?(c=!0,e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),j):q(B)}function j(B){return xt(B)?kt(e,D,"whitespace")(B):D(B)}function D(B){return B===58?(o+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),E):B===45?(o+=1,E(B)):B===null||Ye(B)?te(B):q(B)}function E(B){return B===45?(e.enter("tableDelimiterFiller"),N(B)):q(B)}function N(B){return B===45?(e.consume(B),N):B===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(B),e.exit("tableDelimiterMarker"),I):(e.exit("tableDelimiterFiller"),I(B))}function I(B){return xt(B)?kt(e,te,"whitespace")(B):te(B)}function te(B){return B===124?S(B):B===null||Ye(B)?!c||a!==o?q(B):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(B)):q(B)}function q(B){return i(B)}function R(B){return e.enter("tableRow"),ie(B)}function ie(B){return B===124?(e.enter("tableCellDivider"),e.consume(B),e.exit("tableCellDivider"),ie):B===null||Ye(B)?(e.exit("tableRow"),t(B)):xt(B)?kt(e,ie,"whitespace")(B):(e.enter("data"),fe(B))}function fe(B){return B===null||B===124||qt(B)?(e.exit("data"),ie(B)):(e.consume(B),B===92?be:fe)}function be(B){return B===92||B===124?(e.consume(B),fe):fe(B)}}function v3(e,t){let i=-1,s=!0,a=0,o=[0,0,0,0],c=[0,0,0,0],h=!1,p=0,f,_,x;const b=new m3;for(;++ii[2]+1){const S=i[2]+1,j=i[3]-i[2]-1;e.add(S,j,[])}}e.add(i[3]+1,0,[["exit",x,t]])}return a!==void 0&&(o.end=Object.assign({},ol(t.events,a)),e.add(a,0,[["exit",o,t]]),o=void 0),o}function Zv(e,t,i,s,a){const o=[],c=ol(t.events,i);a&&(a.end=Object.assign({},c),o.push(["exit",a,t])),s.end=Object.assign({},c),o.push(["exit",s,t]),e.add(i+1,0,o)}function ol(e,t){const i=e[t],s=i[0]==="enter"?"start":"end";return i[1][s]}const y3={name:"tasklistCheck",tokenize:w3};function S3(){return{text:{91:y3}}}function w3(e,t,i){const s=this;return a;function a(p){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?i(p):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),o)}function o(p){return qt(p)?(e.enter("taskListCheckValueUnchecked"),e.consume(p),e.exit("taskListCheckValueUnchecked"),c):p===88||p===120?(e.enter("taskListCheckValueChecked"),e.consume(p),e.exit("taskListCheckValueChecked"),c):i(p)}function c(p){return p===93?(e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),h):i(p)}function h(p){return Ye(p)?t(p):xt(p)?e.check({tokenize:C3},t,i)(p):i(p)}}function C3(e,t,i){return kt(e,s,"whitespace");function s(a){return a===null?i(a):t(a)}}function k3(e){return H0([XR(),a3(),p3(e),_3(),S3()])}const E3={};function MS(e){const t=this,i=e||E3,s=t.data(),a=s.micromarkExtensions||(s.micromarkExtensions=[]),o=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);a.push(k3(i)),o.push(GR()),c.push(YR(i))}const ha=["ariaDescribedBy","ariaLabel","ariaLabelledBy"],gl={ancestors:{tbody:["table"],td:["table"],th:["table"],thead:["table"],tfoot:["table"],tr:["table"]},attributes:{a:[...ha,"dataFootnoteBackref","dataFootnoteRef",["className","data-footnote-backref"],"href"],blockquote:["cite"],code:[["className",/^language-./]],del:["cite"],div:["itemScope","itemType"],dl:[...ha],h2:[["className","sr-only"]],img:[...ha,"longDesc","src"],input:[["disabled",!0],["type","checkbox"]],ins:["cite"],li:[["className","task-list-item"]],ol:[...ha,["className","contains-task-list"]],q:["cite"],section:["dataFootnotes",["className","footnotes"]],source:["srcSet"],summary:[...ha],table:[...ha],ul:[...ha,["className","contains-task-list"]],"*":["abbr","accept","acceptCharset","accessKey","action","align","alt","axis","border","cellPadding","cellSpacing","char","charOff","charSet","checked","clear","colSpan","color","cols","compact","coords","dateTime","dir","encType","frame","hSpace","headers","height","hrefLang","htmlFor","id","isMap","itemProp","label","lang","maxLength","media","method","multiple","name","noHref","noShade","noWrap","open","prompt","readOnly","rev","rowSpan","rows","rules","scope","selected","shape","size","span","start","summary","tabIndex","title","useMap","vAlign","value","width"]},clobber:["ariaDescribedBy","ariaLabelledBy","id","name"],clobberPrefix:"user-content-",protocols:{cite:["http","https"],href:["http","https","irc","ircs","mailto","xmpp"],longDesc:["http","https"],src:["http","https"]},required:{input:{disabled:!0,type:"checkbox"}},strip:["script"],tagNames:["a","b","blockquote","br","code","dd","del","details","div","dl","dt","em","h1","h2","h3","h4","h5","h6","hr","i","img","input","ins","kbd","li","ol","p","picture","pre","q","rp","rt","ruby","s","samp","section","source","span","strike","strong","sub","summary","sup","table","tbody","td","tfoot","th","thead","tr","tt","ul","var"]},Ps={}.hasOwnProperty;function N3(e,t){let i={type:"root",children:[]};const s={schema:t?{...gl,...t}:gl,stack:[]},a=BS(s,e);return a&&(Array.isArray(a)?a.length===1?i=a[0]:i.children=a:i=a),i}function BS(e,t){if(t&&typeof t=="object"){const i=t;switch(typeof i.type=="string"?i.type:""){case"comment":return j3(e,i);case"doctype":return T3(e,i);case"element":return A3(e,i);case"root":return R3(e,i);case"text":return D3(e,i)}}}function j3(e,t){if(e.schema.allowComments){const i=typeof t.value=="string"?t.value:"",s=i.indexOf("-->"),o={type:"comment",value:s<0?i:i.slice(0,s)};return Yo(o,t),o}}function T3(e,t){if(e.schema.allowDoctypes){const i={type:"doctype"};return Yo(i,t),i}}function A3(e,t){const i=typeof t.tagName=="string"?t.tagName:"";e.stack.push(i);const s=LS(e,t.children),a=M3(e,t.properties);e.stack.pop();let o=!1;if(i&&i!=="*"&&(!e.schema.tagNames||e.schema.tagNames.includes(i))&&(o=!0,e.schema.ancestors&&Ps.call(e.schema.ancestors,i))){const h=e.schema.ancestors[i];let p=-1;for(o=!1;++p1){let a=!1,o=0;for(;++o-1&&o>p||c>-1&&o>c||h>-1&&o>h)return!0;let f=-1;for(;++f4&&t.slice(0,4).toLowerCase()==="data")return i}function zS(e){return function(t){return N3(t,e)}}const dl=["Romance","Fantasy","Science Fiction","Mystery","Thriller","Horror","Adventure","Historical Fiction","Contemporary Lit","Humor","Poetry","Non-Fiction","Fanfiction","Short Story","Paranormal","Werewolf","LGBTQ+","New Adult","Teen Fiction","Diverse Lit","Others"],ts=["English","Chinese","Korean","Japanese","Spanish","French","Hindi","Arabic","Portuguese","Russian","Others"];function PS(e){return e.toLowerCase().replace(/[^a-z0-9+]/g,"")}const O3=Object.fromEntries(dl.map(e=>[PS(e),e])),z3={scifi:"Science Fiction",sf:"Science Fiction",comedy:"Humor",humour:"Humor",ya:"Teen Fiction",youngadult:"Teen Fiction",lgbt:"LGBTQ+",lgbtq:"LGBTQ+","lgbtqia+":"LGBTQ+",historical:"Historical Fiction",scary:"Horror"};function Cu(e){if(!e)return null;const t=PS(e.trim());return t?O3[t]??z3[t]??null:null}function IS(e,t){const i=t.startsWith("assets/")?t.slice(7):t;return`/api/stories/${e}/asset/${i}`}function xm(e,t,i){const[s,a]=w.useState({url:null,loading:!!t,error:!1});return w.useEffect(()=>{if(!t){a({url:null,loading:!1,error:!1});return}let o=null,c=!1;return a({url:null,loading:!0,error:!1}),(async()=>{try{const h=await i(IS(e,t));if(!h.ok)throw new Error(`asset request failed (${h.status})`);const p=await h.blob();if(c)return;o=URL.createObjectURL(p),a({url:o,loading:!1,error:!1})}catch{c||a({url:null,loading:!1,error:!0})}})(),()=>{c=!0,o&&URL.revokeObjectURL(o)}},[e,t,i]),s}function ey({storyName:e,assetPath:t,authFetch:i,alt:s,className:a}){const{url:o,loading:c,error:h}=xm(e,t,i);return h||!c&&!o?d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center",children:d.jsx("span",{className:"text-xs text-muted",children:"Image not available"})}):o?d.jsx("img",{src:o,alt:s,className:a??"w-full rounded border border-border"}):d.jsx("div",{className:"w-full aspect-video bg-surface border border-border rounded flex items-center justify-center","data-testid":"asset-loading",children:d.jsx("span",{className:"text-xs text-muted",children:"Loading image…"})})}function ty(e,t,i,s){const a=t.split(/\s+/).filter(Boolean);if(a.length===0)return[""];const o=[];let c="";for(const h of a){const p=c?`${c} ${h}`:h;!c||e(p,s)<=i?c=p:(o.push(c),c=h)}return c&&o.push(c),o}function Eo(e,t,i,s,a){const o=a.lineHeightFactor??1.2,c=a.speakerScale??.8,h=a.paddingX??Math.max(2,i*.06),p=a.paddingY??Math.max(2,s*.08),f=Math.max(1,i-2*h),_=Math.max(1,s-2*p),x=Math.max(a.minFontSize,a.maxFontSize),b=Math.max(1,Math.min(a.minFontSize,x)),v=j=>{const D=a.hasSpeaker?j*c:0,E=a.hasSpeaker?D*o:0,N=Math.max(1,_-E),I=a.fontWeight??400,te=ty((ie,fe)=>e(ie,fe,I),t,f,j),q=te.length*j*o,R=te.every(ie=>e(ie,j,I)<=f+.5);return{lines:te,ok:q<=N&&R}};if(typeof a.fontSize=="number"&&Number.isFinite(a.fontSize)&&a.fontSize>0){const j=Math.max(1,a.fontSize),{lines:D,ok:E}=v(j);return{lines:D,fontSize:j,lineHeight:j*o,speakerFontSize:a.hasSpeaker?j*c:0,overflow:!E}}for(let j=x;j>=b;j-=.5){const{lines:D,ok:E}=v(j);if(E)return{lines:D,fontSize:j,lineHeight:j*o,speakerFontSize:a.hasSpeaker?j*c:0,overflow:!1}}return{lines:ty(e,t,f,b),fontSize:b,lineHeight:b*o,speakerFontSize:a.hasSpeaker?b*c:0,overflow:!0}}function P3(e){return{minFontSize:Math.max(1,e*.022),maxFontSize:Math.max(1,e*.05)}}const HS=["speech","narration","sfx"],I3=2;function Ar(e,t,i){return Math.min(i,Math.max(t,e))}function fl(e,t,i){return typeof e=="number"&&Number.isFinite(e)?Ar(e,t,i):void 0}function _m(e){if(!e||typeof e!="object")return;const t=e,i=t.mode==="manual"?"manual":t.mode==="auto"?"auto":void 0,s=fl(t.fontScale,.015,.12),a=t.fontWeight===700?700:t.fontWeight===400?400:void 0,o=fl(t.lineHeightFactor,.9,2),c=fl(t.speakerScale,.5,1.5);if(!(!i&&s===void 0&&a===void 0&&o===void 0&&c===void 0))return{...i?{mode:i}:{},...s!==void 0?{fontScale:s}:{},...a!==void 0?{fontWeight:a}:{},...o!==void 0?{lineHeightFactor:o}:{},...c!==void 0?{speakerScale:c}:{}}}function Ku(e){if(!e||typeof e!="object")return;const t=e,i=fl(t.paddingX,0,.25),s=fl(t.paddingY,0,.25),a=fl(t.cornerRadius,0,.49);if(!(i===void 0&&s===void 0&&a===void 0))return{...i!==void 0?{paddingX:i}:{},...s!==void 0?{paddingY:s}:{},...a!==void 0?{cornerRadius:a}:{}}}function No(e,t,i,s){const{minFontSize:a,maxFontSize:o}=P3(t),c=_m(e.textStyle),h=Ku(e.bubbleStyle);return{minFontSize:a,maxFontSize:o,hasSpeaker:e.type!=="sfx"&&!!e.speaker,...(c==null?void 0:c.lineHeightFactor)!==void 0?{lineHeightFactor:c.lineHeightFactor}:{},...(c==null?void 0:c.speakerScale)!==void 0?{speakerScale:c.speakerScale}:{},...(c==null?void 0:c.fontWeight)!==void 0?{fontWeight:c.fontWeight}:{},...(c==null?void 0:c.mode)==="manual"&&c.fontScale!==void 0?{fontSize:Math.max(1,t*c.fontScale)}:{},...(h==null?void 0:h.paddingX)!==void 0?{paddingX:i*h.paddingX}:{},...(h==null?void 0:h.paddingY)!==void 0?{paddingY:s*h.paddingY}:{}}}function US(e,t,i){const s=Ku(e.bubbleStyle);return(s==null?void 0:s.cornerRadius)!==void 0?Math.min(t,i)*s.cornerRadius:void 0}function $S(e,t){const i=Math.min(e,t);return Math.max(0,Math.min(i*.4,i/2))}function iy(e,t,i,s,a){const o=Math.max(0,i-2*s),c=Math.max(1,Math.min(a,o)/2),h=t+s+c,p=t+i-s-c;return{center:p>=h?Ar(e,h,p):t+i/2,half:c}}function bm(e,t,i,s,a,o){const c=e+i/2,h=t+s/2,p=e+a.x*i,f=t+a.y*s;if(p>=e&&p<=e+i&&f>=t&&f<=t+s)return null;const _=p-c,x=f-h,b=Math.max(6,Math.min(i,s)*.3),v=o??$S(i,s);if(Math.abs(x)>=Math.abs(_)){const E=x>=0?t+s:t,{center:N,half:I}=iy(p,e,i,v,b);return{tip:{x:p,y:f},base1:{x:N-I,y:E},base2:{x:N+I,y:E}}}const S=_>=0?e+i:e,{center:j,half:D}=iy(f,t,s,v,b);return{tip:{x:p,y:f},base1:{x:S,y:j-D},base2:{x:S,y:j+D}}}function H3(e){return e.type!=="speech"||!e.tailAnchor?!1:bm(0,0,1,1,e.tailAnchor)!==null}function U3(e,t,i,s,a,o){const c=o??$S(i,s),h=e+i,p=t+s,f=!!a&&a.base1.y===t&&a.base2.y===t,_=!!a&&a.base1.x===h&&a.base2.x===h,x=!!a&&a.base1.y===p&&a.base2.y===p,b=!!a&&a.base1.x===e&&a.base2.x===e,v=[{k:"M",x:e+c,y:t}];return f&&a&&v.push({k:"L",x:a.base1.x,y:t},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:a.base2.x,y:t}),v.push({k:"L",x:h-c,y:t},{k:"A",cornerX:h,cornerY:t,x:h,y:t+c,r:c}),_&&a&&v.push({k:"L",x:h,y:a.base1.y},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:h,y:a.base2.y}),v.push({k:"L",x:h,y:p-c},{k:"A",cornerX:h,cornerY:p,x:h-c,y:p,r:c}),x&&a&&v.push({k:"L",x:a.base2.x,y:p},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:a.base1.x,y:p}),v.push({k:"L",x:e+c,y:p},{k:"A",cornerX:e,cornerY:p,x:e,y:p-c,r:c}),b&&a&&v.push({k:"L",x:e,y:a.base2.y},{k:"L",x:a.tip.x,y:a.tip.y},{k:"L",x:e,y:a.base1.y}),v.push({k:"L",x:e,y:t+c},{k:"A",cornerX:e,cornerY:t,x:e+c,y:t,r:c}),v}function FS(e,t,i,s,a,o){const c=U3(e,t,i,s,a,o).map(h=>h.k==="A"?`A ${h.r} ${h.r} 0 0 1 ${h.x} ${h.y}`:`${h.k} ${h.x} ${h.y}`);return c.push("Z"),c.join(" ")}function $3(e){return e.x<-1e-6||e.y<-1e-6||e.x+e.width>1+1e-6||e.y+e.height>1+1e-6}let ny=0;function Lp(e,t=.1,i=.1){return ny++,{id:`overlay-${Date.now()}-${ny}`,type:e,x:t,y:i,width:e==="sfx"?.15:.25,height:e==="sfx"?.08:.12,text:"",...e==="speech"?{speaker:"",tailAnchor:{x:.5,y:1.2}}:{}}}function qS(e,t,i){return{width:Math.min(e==="sfx"?.3:.5,Math.max(.15,1-t)),height:Math.min(e==="sfx"?.1:.2,Math.max(.06,1-i))}}const du=.05;function Ui(e){return typeof e=="number"&&Number.isFinite(e)}function F3(e,t,i){const s=e.toLowerCase(),a=/\bleft\b/.test(s),o=/\bright\b/.test(s),c=/\b(?:top|upper)\b/.test(s),h=/\b(?:bottom|lower)\b/.test(s),p=/\b(?:center|centre|middle)\b/.test(s);if(!a&&!o&&!c&&!h&&!p)return null;const f=a?du:Ar(o?1-t-du:(1-t)/2,0,1),_=c?du:Ar(h?1-i-du:(1-i)/2,0,1);return{x:f,y:_}}let q3=0;function W3(e){if(!e||typeof e!="object")return null;const t=e,i=HS.includes(t.type)?t.type:"speech",s=typeof t.text=="string"?t.text:"";let a=Ui(t.width)&&t.width>0?t.width:i==="sfx"?.15:.4,o=Ui(t.height)&&t.height>0?t.height:i==="sfx"?.08:.16,c,h;if(Ui(t.x)&&Ui(t.y))c=t.x,h=t.y;else{const b=typeof t.position=="string"?F3(t.position,a,o):null;if(!b)return null;c=b.x,h=b.y}c=Ar(c,0,1),h=Ar(h,0,1),a=Ar(a,.02,1),o=Ar(o,.02,1);const f={id:typeof t.id=="string"&&t.id?t.id:`overlay-norm-${++q3}`,type:i,x:c,y:h,width:a,height:o,text:s};if(i==="speech"){f.speaker=typeof t.speaker=="string"?t.speaker:"";const b=t.tailAnchor;f.tailAnchor=b&&Ui(b.x)&&Ui(b.y)?{x:b.x,y:b.y}:{x:.5,y:1.2}}else typeof t.speaker=="string"&&t.speaker&&(f.speaker=t.speaker);const _=_m(t.textStyle),x=Ku(t.bubbleStyle);return _&&(f.textStyle=_),x&&(f.bubbleStyle=x),f}function G3(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&!!t.id&&HS.includes(t.type)&&Ui(t.x)&&Ui(t.y)&&Ui(t.width)&&Ui(t.height)&&typeof t.text=="string"}function Y3(e){const t=Array.isArray(e)?e:[],i=[],s=[];let a=!Array.isArray(e);return t.forEach((o,c)=>{const h=W3(o);if(!h){s.push({index:c,reason:"overlay has no numeric x/y/width/height and no recognizable position"}),a=!0;return}i.push(h),G3(o)||(a=!0)}),{overlays:i,changed:a,invalid:s}}function i4(e){for(let t=0;t0&&i.height>0))return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid geometry — repair or re-place it in the lettering editor before export`};const a=_m(i==null?void 0:i.textStyle);if(i!=null&&i.textStyle&&!a)return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid typography controls — reset them in the lettering editor before export`};const o=Ku(i==null?void 0:i.bubbleStyle);if(i!=null&&i.bubbleStyle&&!o)return{valid:!1,error:`Overlay ${t+1}${i!=null&&i.type?` (${i.type})`:""} has invalid bubble controls — reset them in the lettering editor before export`}}return{valid:!0}}const ry=new Set(["speech","narration"]),K3=.12;function sy(e){return Ui(e==null?void 0:e.x)&&Ui(e==null?void 0:e.y)&&Ui(e==null?void 0:e.width)&&Ui(e==null?void 0:e.height)&&e.width>0&&e.height>0}function V3(e,t=K3){const i=[];for(let s=0;s0?f/_:0;x>=t&&i.push({indexA:s,indexB:o,idA:a.id,idB:c.id,ratio:x})}}return i}function fn(e){return e.kind==="text"}function X3(e){return!!e.finalImagePath||!!e.exportedAt?{key:"review",label:"Review final panel",opensEditor:!0}:e.cleanImagePath||fn(e)?{key:"letter",label:"Letter this cut",opensEditor:!0}:{key:"add-art",label:"Add clean art for this cut",opensEditor:!1}}function WS(e,t=I3){return!e.finalImagePath||!(e.overlays??[]).some(H3)?!1:(e.finalRendererVersion??0)0)||!(s>0)?null:{width:ay,height:Math.round(ay*s/i)}}function fu({cut:e}){return e.dialogue.length>0||e.narration||e.sfx?d.jsxs("div",{className:"space-y-1.5","data-testid":`cut-${e.id}-overlay`,children:[e.dialogue.map((i,s)=>d.jsxs("div",{className:"flex gap-2 text-xs",children:[d.jsxs("span",{className:"font-medium text-foreground flex-shrink-0",children:[i.speaker,":"]}),d.jsx("span",{className:"text-foreground",children:i.text})]},s)),e.narration&&d.jsx("div",{className:"border-l-2 border-border pl-3",children:d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})}),e.sfx&&d.jsxs("p",{className:"text-xs font-mono text-muted",children:["SFX: ",e.sfx]})]}):null}function Z3({cut:e,storyName:t,authFetch:i,onEditCut:s}){const a=!!e.finalImagePath,o=!!e.cleanImagePath,c=a||o,h=e.dialogue.length>0||!!e.narration||!!e.sfx,p=e.kind==="text";return d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:"text-[10px] font-mono text-muted bg-surface border border-border rounded px-1.5 py-0.5",children:["#",e.id]}),d.jsx("span",{className:"text-[10px] font-mono text-muted",children:e.shotType}),e.characters.length>0&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:e.characters.join(", ")})]}),a&&d.jsx(ey,{storyName:t,assetPath:e.finalImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),!a&&o&&d.jsxs("div",{className:"border border-border rounded overflow-hidden",children:[d.jsx(ey,{storyName:t,assetPath:e.cleanImagePath,authFetch:i,alt:e.description||`Cut ${e.id}`}),d.jsx("div",{className:"px-3 py-2 bg-surface/80 border-t border-border",children:d.jsx(fu,{cut:e})})]}),!c&&p&&d.jsxs("div",{className:"w-full border border-border rounded p-4 space-y-2",style:{background:e.background||void 0},"data-testid":`cut-${e.id}-textpanel`,children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Text panel"}),h?d.jsx(fu,{cut:e}):d.jsx("p",{className:"text-xs text-muted italic",children:"Empty text panel — open the editor to add text."})]}),!c&&!p&&d.jsxs("div",{className:"w-full bg-surface border border-dashed border-border rounded p-4 space-y-2","data-testid":`cut-${e.id}-pending`,children:[d.jsxs("div",{className:"aspect-video flex flex-col items-center justify-center gap-1 text-center",children:[d.jsx("span",{className:"text-xs text-muted font-medium",children:"Image pending"}),d.jsx("span",{className:"text-[10px] text-muted",children:"Planned image cut — generate & upload the art"})]}),h&&d.jsxs("div",{className:"border-t border-dashed border-border pt-2 space-y-1",children:[d.jsx("span",{className:"text-[10px] font-mono text-muted",children:"Planned text (will be lettered onto the image)"}),d.jsx(fu,{cut:e})]})]}),e.description&&d.jsx("p",{className:"text-xs text-muted italic",children:e.description}),a&&d.jsx(fu,{cut:e}),s&&(()=>{const f=X3(e);return d.jsx("button",{type:"button","data-testid":`cut-${e.id}-cta`,"data-cut-action":f.key,onClick:()=>s(e.id,f.opensEditor),className:"w-full px-3 py-1.5 text-xs font-medium rounded bg-accent text-white hover:bg-accent-dim",children:f.label})})()]})}function Q3({storyName:e,fileName:t,authFetch:i,onEditCut:s}){const[a,o]=w.useState(null),[c,h]=w.useState(!0),[p,f]=w.useState(null),_=t.replace(/\.md$/,""),x=w.useCallback(async()=>{h(!0),f(null);try{const b=await i(`/api/stories/${e}/cuts/${_}`);if(b.status===404){o(null),h(!1);return}if(!b.ok){const S=await b.json();f(S.error||"Failed to load cuts"),h(!1);return}const v=await b.json();o(v)}catch{f("Failed to load cuts")}finally{h(!1)}},[i,e,_]);return w.useEffect(()=>{x();const b=setInterval(x,5e3);return()=>clearInterval(b)},[x]),c&&!a?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Loading cuts..."}):p?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:p}),d.jsxs("p",{className:"text-xs text-muted max-w-sm",children:[_,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema shown in the cartoon writing instructions."]}),d.jsx("button",{onClick:x,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]}):!a||a.cuts.length===0?d.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-2 px-4 text-center",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]}):d.jsx("div",{className:"h-full overflow-y-auto",children:d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6 space-y-6",children:a.cuts.map(b=>d.jsx(Z3,{cut:b,storyName:e,authFetch:i,onEditCut:s},b.id))})})}const ly=/!\[[^\]]*\]\([^)]*\)/g,J3=//g,YS=200;function eD(e){const t=(e.match(ly)||[]).length,i=e.length,s=e.replace(J3," ").replace(ly," ").replace(/\s+/g," ").trim();return{imageCount:t,charCount:i,nonImageProse:s,nonImageProsePreview:s.slice(0,YS)}}function tD(e){return`${e}: re-export required before publish — this final image uses an older speech-bubble tail style that can show a visible seam`}const iD=[/placeholder only/i,/\bOWS (?:should )?generates? the publish markdown/i,/generate(?:s|d)? the publish markdown from/i,/after clean images are approved/i,/lettered final images are created/i,/do not hand-?write/i,/\b(?:TODO|FIXME)\b/];function nD(e){for(const t of iD){const i=e.match(t);if(i)return i[0]}return null}function vm(e,t){const i=``,s=``,a=e.indexOf(i),o=e.indexOf(s);return a===-1||o===-1||ob[1].trim());x.length===0?i.push(`${p}: block has no image reference`):x.length>1?i.push(`${p}: block must contain exactly one image reference`):h.uploadedUrl&&x[0]!==h.uploadedUrl&&i.push(`${p}: image URL does not match the recorded uploaded URL`)}/awaiting upload|image pending|final image pending|pending upload/i.test(e)&&i.push("Markdown contains awaiting-upload placeholders");const s=nD(e);s&&i.push(`This episode still has placeholder/instructional text ("${s.slice(0,60)}") — remove it or re-run “Prepare episode for publish” so the published episode is images only`);const a=new Set(t.map(c=>c.uploadedUrl).filter(c=>!!c&&/^https?:\/\//i.test(c))),o=[...e.matchAll(/!\[[^\]]*\]\(([^)]*)\)/g)];for(const c of o){const h=c[1].trim();/^https?:\/\//i.test(h)?a.has(h)||i.push(`Image reference is not a recorded uploaded cut URL: ${h.slice(0,60)}`):i.push(`Invalid image reference (not an http(s) URL): ${h.slice(0,60)}`)}return e.length>1e4&&i.push(`Markdown is ${e.length} chars (limit 10,000)`),{ready:i.length===0,issues:i}}function VS(e,t){const i=t.length;if(i===0)return{stage:"not-started",issues:[],awaitingCount:0,totalCuts:0};if(rD(e,t))return{stage:"planning",issues:[],awaitingCount:0,totalCuts:i};const{ready:s,issues:a}=KS(e,t);if(s)return{stage:"ready",issues:[],awaitingCount:0,totalCuts:i};const o=new Set;for(let p=0;p!c.has(p));return h.length>0?{stage:"error",issues:h,awaitingCount:o.size,totalCuts:i}:{stage:"awaiting-upload",issues:[],awaitingCount:o.size,totalCuts:i}}const Mf=[{key:"assemble",title:"Prepare the episode for publish",test:/markdown block|missing or incomplete/i},{key:"export",title:"Export final images",test:/re-export|older speech-bubble|visible seam/i},{key:"upload",title:"Upload final images",test:/not uploaded|no recorded uploaded url/i},{key:"images",title:"Fix image references",test:/image reference|not an http|does not match|exactly one image/i},{key:"cleanup",title:"Remove leftover text",test:/placeholder|instructional|awaiting-upload|awaiting upload/i},{key:"size",title:"Shorten the episode",test:/\blimit\b|\bchars\b/i}];function sD(e){const t=new Map,i=[],s=[];for(const o of e){const c=o.match(/^Cut (\d+): (.+)$/);if(c){const h=c[2];t.has(h)||(t.set(h,[]),i.push(h)),t.get(h).push(Number(c[1]))}else s.push(o)}return[...i.map(o=>{const c=t.get(o).slice().sort((p,f)=>p-f);return`${c.length===1?`Cut ${c[0]}`:`Cuts ${c.join(", ")}`}: ${o}`}),...s]}function XS(e){const t=c=>{var h;return((h=Mf.find(p=>p.test.test(c)))==null?void 0:h.key)??"other"},i=new Map;for(const c of e){const h=t(c);i.has(h)||i.set(h,[]),i.get(h).push(c)}const s=[...Mf.map(c=>c.key),"other"],a=c=>{var h;return((h=Mf.find(p=>p.key===c))==null?void 0:h.title)??"Other issues"},o=[];for(const c of s){const h=i.get(c);!h||h.length===0||o.push({key:c,title:a(c),lines:sD(h)})}return o}const aD=220,Bf=/^(genre|logline|synopsis|premise|setting|tone|theme|themes|summary|hook|characters?|cast|arc|status|word\s*count|length|title)\b\s*[:\-–]/i;function ym(e){const t=[],i=[],s=e??"",a=s.match(/^#[ \t]+(.+)$/m),o=!!(a&&a[1].trim());o||t.push("Add a “# Title” heading — the Story opening needs a real title readers see first.");const c=s.replace(/^#\s+.+$/m,"").trim();if(c.lengthx.trim()).filter(Boolean),p=h.filter(x=>/^([-*+]|\d+[.)])\s/.test(x)||Bf.test(x)).length,f=c.split(/\n\s*\n/).map(x=>x.trim()).filter(Boolean),_=f.some(x=>x.length>=120&&!/^([-*+]|\d+[.)])\s/.test(x)&&!Bf.test(x));h.length>0&&p/h.length>=.5||!_?t.push("This reads like a synopsis or outline. Write the Genesis as a reader-facing opening scene that sets up the first beat and stakes, then bridges into Episode 01 — not a logline, genre pitch, or character list."):f.filter(b=>b.length>=40&&!/^([-*+]|\d+[.)])\s/.test(b)&&!Bf.test(b)).length<2&&t.push("Give the opening room to build: open across a few short paragraphs — the premise, what the lead wants, and the hook — that lead into Episode 01, instead of a single dense block that drops readers into a cold scene.")}return{hasTitle:o,blockers:t,warnings:i}}function lD(e){return/\.(webp|jpe?g)$/i.test(e)}function Op(e){var c,h;let t=0,i=0,s=0,a=0,o=0;for(const p of e)fn(p)?(((h=p.overlays)==null?void 0:h.length)??0)>0&&s++:(t++,p.cleanImagePath&&lD(p.cleanImagePath)&&(i++,(((c=p.overlays)==null?void 0:c.length)??0)>0&&s++)),p.finalImagePath&&p.exportedAt&&a++,p.uploadedUrl&&o++;return{total:e.length,needClean:t,withClean:i,withText:s,exported:a,uploaded:o}}const oD={plan:"Plan cuts",clean:"Create clean images",letter:"Add speech bubbles & captions",export:"Export final images",upload:"Upload final images",publish:"Publish to PlotLink"};function vo(e,t){return`${e} / ${t} cut${t===1?"":"s"}`}function cD(e){const{cuts:t,published:i=!1}=e,s=Op(t);if(s.total===0)return{steps:[],nextStep:null};const a=s.total>0,o=a&&s.withClean===s.needClean,c=o&&s.withText===s.total,h=c&&s.exported===s.total,p=h&&s.uploaded===s.total,_={plan:a,clean:o,letter:c,export:h,upload:p,publish:p&&i},x=["plan","clean","letter","export","upload","publish"],b=x.findIndex(N=>!_[N]),v=N=>s.needClean>0?vo(N,s.needClean):"no image cuts",S={plan:vo(s.total,s.total),clean:v(s.withClean),letter:vo(s.withText,s.total),export:vo(s.exported,s.total),upload:vo(s.uploaded,s.total),publish:null},j=x.map((N,I)=>({key:N,label:oD[N],status:b===-1||IYS,a=dD({stage:t,imageCount:i.imageCount,hasNonImageProse:i.nonImageProse.length>0});return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"cartoon-publish-preview",children:[d.jsxs("div",{className:"px-4 py-2 border-b border-border text-[10px] text-muted flex flex-wrap items-center gap-x-3 gap-y-1","data-testid":"cartoon-publish-summary",children:[d.jsxs("span",{children:[i.imageCount," image",i.imageCount===1?"":"s"]}),d.jsxs("span",{children:[i.charCount.toLocaleString()," / 10,000 chars"]}),d.jsx("span",{className:`rounded-full px-2 py-0.5 font-medium ${a.possible?"bg-green-100 text-green-800":"bg-background text-muted"}`,"data-testid":"publish-possible",children:a.possible?"Publish possible":"Publish not possible yet"}),d.jsx("span",{className:`rounded-full px-2 py-0.5 font-medium ${a.recommended?"bg-green-100 text-green-800":a.tone==="warning"?"bg-amber-100 text-amber-800":"bg-background text-muted"}`,"data-testid":"publish-recommended",children:a.recommended?"Recommended":"Not recommended yet"})]}),d.jsxs("div",{className:`px-4 py-2 border-b text-[11px] ${pD[a.tone]}`,"data-testid":"cartoon-publish-verdict",children:[d.jsx("p",{className:"font-medium",children:a.headline}),a.detail&&d.jsx("p",{className:"mt-0.5 opacity-90",children:a.detail}),a.action&&d.jsxs("p",{className:"mt-0.5 opacity-90",children:["→ ",a.action]})]}),i.nonImageProse&&d.jsxs("div",{className:"px-4 py-2 border-b border-amber-300 bg-amber-50 text-[11px] text-amber-800","data-testid":"cartoon-nonimage-prose",children:[d.jsx("p",{className:"font-medium",children:"⚠ Non-image text in the published markdown:"}),d.jsxs("p",{className:"font-mono mt-1 whitespace-pre-wrap break-words",children:[i.nonImageProsePreview,s?"…":""]}),d.jsx("p",{className:"mt-1",children:"This text publishes verbatim around the comic images. Remove it (or re-run “Prepare episode for publish”) if it is planning or placeholder prose."})]}),d.jsx("div",{className:"max-w-lg mx-auto px-4 py-6",children:e.trim()?d.jsx("div",{className:"prose max-w-none",children:d.jsx(lS,{remarkPlugins:[cS,MS],rehypePlugins:[[zS,fD]],children:e})}):d.jsx("p",{className:"text-muted italic text-sm","data-testid":"cartoon-publish-empty",children:"No publish markdown yet — build it from the cut plan (Edit → Upload & Prepare for Publish)."})})]})}const gD="modulepreload",xD=function(e){return"/"+e},oy={},cy=function(t,i,s){let a=Promise.resolve();if(i&&i.length>0){let c=function(f){return Promise.all(f.map(_=>Promise.resolve(_).then(x=>({status:"fulfilled",value:x}),x=>({status:"rejected",reason:x}))))};document.getElementsByTagName("link");const h=document.querySelector("meta[property=csp-nonce]"),p=(h==null?void 0:h.nonce)||(h==null?void 0:h.getAttribute("nonce"));a=c(i.map(f=>{if(f=xD(f),f in oy)return;oy[f]=!0;const _=f.endsWith(".css"),x=_?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${x}`))return;const b=document.createElement("link");if(b.rel=_?"stylesheet":gD,_||(b.as="script"),b.crossOrigin="",b.href=f,p&&b.setAttribute("nonce",p),document.head.appendChild(b),_)return new Promise((v,S)=>{b.addEventListener("load",v),b.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${f}`)))})}))}function o(c){const h=new Event("vite:preloadError",{cancelable:!0});if(h.payload=c,window.dispatchEvent(h),!h.defaultPrevented)throw c}return a.then(c=>{for(const h of c||[])h.status==="rejected"&&o(h.reason);return t().catch(o)})},Sm=[{family:"Noto Sans",googleFontsId:"Noto+Sans",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans/about",category:"body",weights:[400,500,700],languages:["English","Spanish","French","Portuguese","Russian","Others"]},{family:"Noto Sans KR",googleFontsId:"Noto+Sans+KR",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+KR/about",category:"body",weights:[400,500,700],languages:["Korean"]},{family:"Noto Sans JP",googleFontsId:"Noto+Sans+JP",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+JP/about",category:"body",weights:[400,500,700],languages:["Japanese"]},{family:"Noto Sans SC",googleFontsId:"Noto+Sans+SC",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+SC/about",category:"body",weights:[400,500,700],languages:["Chinese"]},{family:"Noto Sans Devanagari",googleFontsId:"Noto+Sans+Devanagari",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Sans+Devanagari/about",category:"body",weights:[400,500,700],languages:["Hindi"]},{family:"Noto Naskh Arabic",googleFontsId:"Noto+Naskh+Arabic",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/noto/specimen/Noto+Naskh+Arabic/about",category:"body",weights:[400,500,700],languages:["Arabic"]},{family:"Bangers",googleFontsId:"Bangers",license:"OFL-1.1",licenseUrl:"https://fonts.google.com/specimen/Bangers/about",category:"display",weights:[400],languages:[]}],_D="system-ui, sans-serif",bD=Sm.find(e=>e.family==="Noto Sans"),vD=Sm.find(e=>e.category==="display");function ZS(e){return Sm.find(i=>i.category==="body"&&i.languages.includes(e))||bD}function QS(){return vD}function JS(e){const t=e.weights.join(";");return`https://fonts.googleapis.com/css2?family=${e.googleFontsId}:wght@${t}&display=swap`}function Ou(e){return`"${e.family}", ${_D}`}function yD(e,t={}){var a,o,c,h;const i=!t.staleExport&&(!!e.finalImagePath||!!e.exportedAt),s=!t.staleExport&&(!!e.uploadedUrl||!!e.uploadedCid);return{hasCleanImage:!!e.cleanImagePath,hasScriptText:(((a=e.dialogue)==null?void 0:a.length)??0)>0||!!((o=e.narration)!=null&&o.trim())||!!((c=e.sfx)!=null&&c.trim()),bubblesPlaced:((h=e.overlays)==null?void 0:h.length)??0,exported:i,uploaded:s}}function ul(e){return JSON.stringify((e??[]).map(t=>[t.type,t.x,t.y,t.width,t.height,t.text,t.speaker??"",t.tailAnchor??null,t.textStyle??null,t.bubbleStyle??null]))}function SD(e){return!e.exported&&!e.uploaded?!1:e.baselineSig!==ul(e.current)}function wm(e){var i,s;const t=[];return(e.dialogue??[]).forEach((a,o)=>{var c;(c=a==null?void 0:a.text)!=null&&c.trim()&&t.push({type:"speech",speaker:a.speaker,text:a.text.trim(),key:`speech-${o}`})}),(i=e.narration)!=null&&i.trim()&&t.push({type:"narration",text:e.narration.trim(),key:"narration"}),(s=e.sfx)!=null&&s.trim()&&t.push({type:"sfx",text:e.sfx.trim(),key:"sfx"}),t}function wD(e,t,i){if(e==="narration")return{x:.08,y:.05+Math.min(t,2)*.18};if(e==="sfx"){const c=t%2,h=Math.floor(t/2);return{x:c===0?.1:.62,y:.68+h*.12}}const s=Math.floor(t/2),a=t%2===0,o=.08+s*Math.max(.15,Math.min(.22,i>4?.16:.2));return{x:a?.05:.45,y:o}}function uy(e){const t=wm(e);return t.map((i,s)=>{const{x:a,y:o}=wD(i.type,s,t.length),c=Lp(i.type,a,o),h=qS(i.type,a,o);return{...c,...h,text:i.text,...i.type==="speech"?{speaker:i.speaker??""}:{}}})}function Cn(e,t){return e*t}function hy(e,t){return t===0?0:e/t}function dy(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=JS(e),document.head.appendChild(i)}const ku={speech:"Speech",narration:"Narration",sfx:"SFX"},CD={speech:"border-foreground/40",narration:"border-muted/40",sfx:"border-accent/40"};function Lf(e){const t=(e.speaker||e.text||"").trim().replace(/\s+/g," ");return t?`“${t.length>18?`${t.slice(0,18)}…`:t}”`:ku[e.type]}const fy=.05,kD=[{key:"down",label:"Down",anchor:{x:.5,y:1.2}},{key:"up",label:"Up",anchor:{x:.5,y:-.2}},{key:"left",label:"Left",anchor:{x:-.2,y:.5}},{key:"right",label:"Right",anchor:{x:1.2,y:.5}}];function pu(e,t,i){return Math.min(i,Math.max(t,e))}function ED({storyName:e,cut:t,plotFile:i,onSave:s,onClose:a,onExported:o,language:c="English",authFetch:h,targetLabel:p,returnOnSave:f=!1,workspaceVisible:_=!1,onToggleWorkspaceVisible:x}){var Wt,ui,Bt,yt,Rt,Qe,hi;const b=ZS(c),v=QS(),S=Ou(b),j=Ou(v);w.useEffect(()=>{dy(b),dy(v)},[b,v]),w.useEffect(()=>{let H=!1;return G(!1),(async()=>{try{const{ensureFontsReady:Se}=await cy(async()=>{const{ensureFontsReady:Oe}=await import("./export-cut-HPHvubLr.js");return{ensureFontsReady:Oe}},[]);await Se([b.family,v.family])}catch{}H||G(!0)})(),()=>{H=!0}},[b.family,v.family]);const D=xm(e,t.cleanImagePath,h),E=w.useMemo(()=>Y3(t.overlays),[t.overlays]),N=E.invalid.length,[I,te]=w.useState(!1),q=N===0&&E.changed&&E.overlays.length>0,[R,ie]=w.useState(()=>E.overlays),[fe,be]=w.useState(()=>ul(E.overlays)),B=w.useRef(null),ne=w.useCallback(H=>(Se,Oe,Ae=400)=>{var Fe;!B.current&&typeof document<"u"&&(B.current=document.createElement("canvas"));const Ge=(Fe=B.current)==null?void 0:Fe.getContext("2d");return Ge?(Ge.font=`${Ae} ${Oe}px ${H}`,Ge.measureText(Se).width):Se.length*Oe*.5},[]),[F,G]=w.useState(!1),[Y,U]=w.useState(null),[A,z]=w.useState(!1),[$,ge]=w.useState(!1),[T,M]=w.useState(null),[V,C]=w.useState(null),[X,se]=w.useState({x:0,y:0,width:0,height:0}),le=w.useRef(null),K=w.useRef(null),he=w.useRef(null),_e=w.useCallback(()=>{const H=le.current;if(!H)return;const Se=H.clientWidth,Oe=H.clientHeight;let Ae,Ge;if(t.kind==="text"){const ct=GS(t.aspectRatio)??{width:800,height:600};Ae=ct.width,Ge=ct.height}else{const ct=K.current;if(!ct||!ct.naturalWidth)return;Ae=ct.naturalWidth,Ge=ct.naturalHeight}if(!Se||!Oe)return;const Fe=Math.min(Se/Ae,Oe/Ge),dt=Ae*Fe,ft=Ge*Fe;se({x:(Se-dt)/2,y:(Oe-ft)/2,width:dt,height:ft})},[t.kind,t.aspectRatio]);w.useEffect(()=>{const H=le.current;if(!H)return;const Se=new ResizeObserver(()=>_e());return Se.observe(H),()=>Se.disconnect()},[_e]);const Me=w.useCallback(H=>{const Se=qS(H.type,H.x,H.y),Oe=Se.width,Ae=Math.max(.08,1-H.y);if(!H.text||!F||X.width<=0)return Se;const Ge=H.type==="sfx"?j:S,Fe=Cn(Oe,X.width);let dt=H.type==="sfx"?.08:.12;for(let ft=0;ft<24;ft++){const ct=Math.min(dt,Ae),Vt=Cn(ct,X.height);if(!Eo(ne(Ge),H.text,Fe,Vt,No({...H},X.height||300,Fe,Vt)).overflow||ct>=Ae)return{width:Oe,height:ct};dt+=.03}return{width:Oe,height:Math.min(dt,Ae)}},[F,X,ne,S,j]),Le=w.useCallback(H=>{const Se=Lp(H,.1+Math.random()*.3,.1+Math.random()*.3),Oe={...Se,...Me(Se)};ie(Ae=>[...Ae,Oe]),U(Oe.id)},[Me]),He=w.useCallback(H=>{const Oe={...Lp(H.type,.1+Math.random()*.3,.1+Math.random()*.3),text:H.text,...H.type==="speech"&&H.speaker?{speaker:H.speaker}:{}},Ae={...Oe,...Me(Oe)};ie(Ge=>[...Ge,Ae]),U(Ae.id)},[Me]),ke=w.useCallback((H,Se)=>{ie(Oe=>Oe.map(Ae=>Ae.id===H?{...Ae,...Se}:Ae))},[]),Ue=w.useCallback(H=>{var dt;const Se=X.height||300,Oe=X.width>0?Cn(H.width,X.width):200,Ae=X.height>0?Cn(H.height,X.height):100,Ge=H.type==="sfx"?j:S,Fe=Eo(ne(Ge),H.text,Oe,Ae,No({...H,textStyle:void 0},Se,Oe,Ae));ke(H.id,{textStyle:{mode:"manual",fontScale:Fe.fontSize/Math.max(1,Se),fontWeight:((dt=H.textStyle)==null?void 0:dt.fontWeight)??400,lineHeightFactor:Fe.fontSize>0?Fe.lineHeight/Fe.fontSize:1.2,speakerScale:Fe.fontSize>0&&Fe.speakerFontSize>0?Fe.speakerFontSize/Fe.fontSize:.8}})},[X,j,S,ne,ke]),Je=w.useCallback(H=>{ie(Se=>Se.filter(Oe=>Oe.id!==H)),U(null),z(!1)},[]),at=w.useCallback(()=>{U(null),z(!1)},[]),Ve=w.useCallback((H,Se)=>{H.stopPropagation(),U(Se),z(!1)},[]),Et=w.useCallback((H,Se,Oe)=>{H.stopPropagation(),H.preventDefault();const Ae=R.find(Ge=>Ge.id===Se);Ae&&(U(Se),he.current={id:Se,mode:Oe,startX:H.clientX,startY:H.clientY,origX:Ae.x,origY:Ae.y,origW:Ae.width,origH:Ae.height})},[R]);w.useEffect(()=>{const H=Oe=>{const Ae=he.current;if(!Ae||X.width===0)return;const Ge=hy(Oe.clientX-Ae.startX,X.width),Fe=hy(Oe.clientY-Ae.startY,X.height);if(Ae.mode==="move"){const dt=pu(Ae.origX+Ge,0,1-Ae.origW),ft=pu(Ae.origY+Fe,0,1-Ae.origH);ke(Ae.id,{x:dt,y:ft})}else{const dt=pu(Ae.origW+Ge,fy,1-Ae.origX),ft=pu(Ae.origH+Fe,fy,1-Ae.origY);ke(Ae.id,{width:dt,height:ft})}},Se=()=>{he.current=null};return window.addEventListener("mousemove",H),window.addEventListener("mouseup",Se),()=>{window.removeEventListener("mousemove",H),window.removeEventListener("mouseup",Se)}},[X,ke]);const ze=w.useCallback(async()=>{var H;C(null);try{const Se=ul(R),Oe=((H=t.aiDraft)==null?void 0:H.status)==="generated"&&Se!==(t.aiDraft.baseSig??"")?{...t.aiDraft,status:"edited",updatedAt:new Date().toISOString()}:t.aiDraft??void 0;await s(R,Oe??null),f&&a()}catch(Se){C(Se instanceof Error?Se.message:"Failed to save overlays")}},[R,s,a,f,t.aiDraft]),_t=w.useCallback(async()=>{if(N>0&&!I){const H=N;M(`${H} overlay${H===1?"":"s"} from the cut plan ${H===1?"has":"have"} no usable position and cannot be exported — re-place ${H===1?"it":"them"} or discard ${H===1?"it":"them"} first.`);return}ge(!0),M(null);try{await s(R);const{exportCut:H,ensureFontsReady:Se}=await cy(async()=>{const{exportCut:pt,ensureFontsReady:Fi}=await import("./export-cut-HPHvubLr.js");return{exportCut:pt,ensureFontsReady:Fi}},[]),Oe=R.some(pt=>pt.type==="sfx"),Ae=[b.family,...Oe?[v.family]:[]],{ready:Ge,missing:Fe}=await Se(Ae);if(!Ge){M(`Fonts not loaded: ${Fe.join(", ")}. Check your connection and retry.`),ge(!1);return}if(t.cleanImagePath&&!D.url){M(D.error?"Clean image failed to load — cannot export. Retry once it renders.":"Clean image still loading — wait for it to render, then export."),ge(!1);return}const dt=D.url,ft=await H(dt,R,S,j,{narration:t.narration,dialogue:t.dialogue},t.kind==="text"?{background:t.background,aspectRatio:t.aspectRatio}:void 0),ct=new FormData,Vt=ft.type==="image/webp"?"webp":"jpg";ct.append("file",ft,`cut-${t.id}.${Vt}`);const Ci=await h(`/api/stories/${e}/cuts/${i}/export-final/${t.id}`,{method:"POST",body:ct});if(Ci.ok)be(ul(R)),o==null||o();else{const pt=await Ci.json();M(pt.error||"Export failed")}}catch(H){M(H instanceof Error?H.message:"Export failed")}finally{ge(!1)}},[t,D,R,e,i,b,v,S,j,h,s,o,N,I]),Te=R.find(H=>H.id===Y),Kt=w.useMemo(()=>V3(R),[R]),mi=w.useRef(t.id);w.useEffect(()=>{mi.current!==t.id&&(mi.current=t.id,be(ul(E.overlays)))},[t.id,E.overlays]);const wt=SD({exported:!!t.finalImagePath||!!t.exportedAt,uploaded:!!t.uploadedUrl||!!t.uploadedCid,baselineSig:fe,current:R}),et=w.useMemo(()=>yD({...t,overlays:R},{staleExport:wt}),[t,R,wt]),Q=w.useMemo(()=>wm(t),[t]),xe=w.useMemo(()=>{const H={};for(const Se of R){const Oe=$3(Se);let Ae=!1;if(F&&X.width>0&&Se.text){const Ge=Se.type==="sfx"?j:S,Fe=Cn(Se.width,X.width),dt=Cn(Se.height,X.height);Ae=Eo(ne(Ge),Se.text,Fe,dt,No(Se,X.height||300,Fe,dt)).overflow}(Oe||Ae)&&(H[Se.id]={outOfBounds:Oe,overflow:Ae})}return H},[R,F,X,ne,S,j]),je=Object.keys(xe).length,$e=t.kind==="text",nt=!t.cleanImagePath;return!$e&&nt&&R.length===0&&!t.narration&&!((Wt=t.dialogue)!=null&&Wt.length)?d.jsx("div",{className:"h-full flex items-center justify-center text-sm text-muted",children:"No clean image — upload one first, or add overlays for a narration cut."}):d.jsxs("div",{className:"h-full flex flex-col","data-testid":"focused-lettering-editor",children:[d.jsxs("div",{className:"px-4 py-3 border-b border-border bg-surface/40 flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"text-[10px] font-bold uppercase tracking-[0.16em] text-accent",children:"Focused lettering editor"}),d.jsx("span",{className:"text-xs font-mono text-muted",children:p??`Cut #${t.id}`})]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Place bubbles, captions, SFX, or between-scene card text, then save back to the full cut review."}),d.jsxs("span",{className:"text-[10px] text-muted","data-testid":"overlay-count",children:[R.length," overlays"]})]}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap justify-end",children:[d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:text-foreground","data-testid":"return-to-cut-review-btn",children:"Back to cut review"}),x&&d.jsx("button",{onClick:x,className:"px-3 py-1 text-xs border border-border rounded text-muted hover:border-accent hover:text-accent","data-testid":"toggle-work-area-btn",children:_?"Hide work area":"Show work area"}),d.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[d.jsx("button",{onClick:()=>Le("speech"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-speech",children:"Speech"}),d.jsx("button",{onClick:()=>Le("narration"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-narration",children:"Narration"}),d.jsx("button",{onClick:()=>Le("sfx"),className:"px-2 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"add-sfx",children:"SFX"})]}),T&&d.jsx("span",{className:"text-[10px] text-error",children:T}),V&&d.jsx("span",{className:"text-[10px] text-error",children:V}),d.jsx("button",{onClick:_t,disabled:$,className:"px-3 py-1 text-xs border border-accent text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"export-btn",children:$?"Exporting...":"Export"}),d.jsx("button",{onClick:()=>{ze()},className:"px-3 py-1 text-xs bg-accent text-white rounded hover:bg-accent-dim","data-testid":"save-lettering-btn",children:"Save"}),d.jsx("button",{onClick:a,className:"px-3 py-1 text-xs text-muted hover:text-foreground border border-border rounded","data-testid":"cancel-lettering-btn",children:"Cancel"})]})]}),N>0&&!I?d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-error/10 text-[10px] text-error flex items-center gap-2 flex-wrap","data-testid":"overlay-repair-note",children:[d.jsxs("span",{children:[N," overlay",N===1?"":"s"," ","from the cut plan ",N===1?"has":"have"," no usable position and cannot be exported. Re-place"," ",N===1?"it":"them",", or"]}),d.jsxs("button",{onClick:()=>te(!0),"data-testid":"discard-invalid-overlays",className:"px-1.5 py-0.5 border border-error/40 rounded hover:bg-error/10",children:["discard ",N," unplaceable overlay",N===1?"":"s"]})]}):N>0?d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-repair-note",children:["Discarded ",N," unplaceable overlay",N===1?"":"s"," — the export will not include"," ",N===1?"it":"them","."]}):q?d.jsx("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-repair-note",children:"Auto-placed overlays from the cut plan — review their positions before exporting."}):null,Kt.length>0&&d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"overlay-overlap-warning",children:["Cut #",t.id,": ",Kt.length," bubble"," ",Kt.length===1?"pair overlaps":"pairs overlap"," and may be hard to read —"," ",Kt.map(H=>`#${H.indexA+1} ${Lf(R[H.indexA])} ↔ #${H.indexB+1} ${Lf(R[H.indexB])}`).join("; "),". Move them apart, or export as-is if the overlap is intended."]}),d.jsx("div",{className:"px-3 py-1 border-b border-border flex items-center gap-3 flex-wrap text-[10px] text-muted","data-testid":"lettering-checklist",children:[["clean-image","Clean image",et.hasCleanImage],["script-text","Script text",et.hasScriptText],["bubbles",`Bubbles placed${et.bubblesPlaced?` (${et.bubblesPlaced})`:""}`,et.bubblesPlaced>0],["exported","Final exported",et.exported],["uploaded","Uploaded",et.uploaded]].map(([H,Se,Oe])=>d.jsxs("span",{"data-testid":`lettering-check-${H}`,"data-done":Oe?"true":"false",className:`flex items-center gap-1 ${Oe?"text-green-700":"text-muted/70"}`,children:[d.jsx("span",{"aria-hidden":!0,children:Oe?"✓":"○"}),Se]},H))}),wt&&d.jsx("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"lettering-stale-export-warning",children:"Bubbles changed since the last export — re-export this cut and upload the new final image before publishing."}),je>0&&d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-amber-500/10 text-[10px] text-amber-700","data-testid":"lettering-export-warning",children:[je," bubble",je===1?"":"s"," may not export cleanly:"," ",Object.entries(xe).map(([H,Se])=>{const Oe=R.findIndex(Ge=>Ge.id===H),Ae=[Se.outOfBounds?"outside image":null,Se.overflow?"text overflow":null].filter(Boolean).join(", ");return`#${Oe+1} ${Lf(R[Oe])} (${Ae})`}).join("; "),". Resize or reposition before exporting."]}),d.jsxs("div",{className:"flex-1 min-h-0 flex",children:[d.jsxs("div",{ref:le,className:"flex-1 min-w-0 relative overflow-hidden bg-[#f8f5ef]",onClick:at,"data-testid":"editor-surface",children:[t.cleanImagePath&&D.error?d.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted text-xs","data-testid":"clean-image-error",children:"Clean image not available"}):t.cleanImagePath&&!D.url?d.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted text-xs","data-testid":"clean-image-loading",children:"Loading clean image…"}):t.cleanImagePath?d.jsx("img",{ref:K,src:D.url,alt:`Cut ${t.id} clean`,className:"w-full h-full object-contain",draggable:!1,onLoad:_e}):$e?X.width>0&&d.jsx("div",{className:"absolute flex items-center justify-center text-muted text-xs",style:{left:X.x,top:X.y,width:X.width,height:X.height,background:t.background||"#ffffff"},"data-testid":"text-panel-canvas",children:"Text panel"}):d.jsx("div",{className:"w-full h-full bg-white flex items-center justify-center text-muted text-xs",ref:H=>{if(H&&X.width===0){const Se=H.getBoundingClientRect();Se.width>0&&se({x:0,y:0,width:Se.width,height:Se.height})}},children:"Narration cut"}),X.width>0&&d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":"balloon-layer",children:R.map(H=>{if(H.type!=="speech")return null;const Se=X.x+Cn(H.x,X.width),Oe=X.y+Cn(H.y,X.height),Ae=Cn(H.width,X.width),Ge=Cn(H.height,X.height),Fe=US(H,Ae,Ge),dt=H.tailAnchor?bm(Se,Oe,Ae,Ge,H.tailAnchor,Fe):null,ft=Math.max(1.5,X.height*.004),ct=H.id===Y;return d.jsx("path",{"data-testid":`balloon-${H.id}`,d:FS(Se,Oe,Ae,Ge,dt,Fe),className:`fill-white/95 ${ct?"stroke-accent":"stroke-[#1a1a1a]"}`,strokeWidth:ct?ft+.5:ft,strokeLinejoin:"round"},H.id)})}),X.width>0&&R.map(H=>{const Se=X.x+Cn(H.x,X.width),Oe=X.y+Cn(H.y,X.height),Ae=Cn(H.width,X.width),Ge=Cn(H.height,X.height),Fe=H.id===Y,dt=H.type==="speech",ft=H.type==="narration",ct=!!xe[H.id];return d.jsxs("div",{"data-testid":`overlay-${H.id}`,"data-warning":ct?"true":"false",onClick:Vt=>Ve(Vt,H.id),onMouseDown:Vt=>Et(Vt,H.id,"move"),className:`absolute rounded cursor-move select-none ${dt?"":`border-2 ${CD[H.type]}`} ${ft?"bg-[#f4efe6]/85 rounded-md":""} ${Fe&&!dt?"ring-2 ring-accent":""} ${ct?"ring-2 ring-amber-500":""}`,style:{left:Se,top:Oe,width:Ae,height:Ge},children:[(()=>{var Fi,Nn;const Vt=H.type==="sfx"?j:S;if(!H.text)return d.jsx("span",{className:"text-[9px] px-1 text-muted truncate block pointer-events-none",style:{fontFamily:Vt},children:ku[H.type]});const Ci=H.type!=="sfx"&&!!H.speaker;if(!F)return d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 overflow-hidden pointer-events-none text-center break-words",style:{fontFamily:Vt,fontSize:Math.max(9,Math.min(Ge*.05,16)),fontWeight:((Fi=H.textStyle)==null?void 0:Fi.fontWeight)??400},"data-testid":`overlay-text-${H.id}`,"data-fonts-ready":"false",children:Ci?`${H.speaker}: ${H.text}`:H.text});const pt=Eo(ne(Vt),H.text,Ae,Ge,No(H,X.height,Ae,Ge));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 overflow-hidden pointer-events-none text-center",style:{fontFamily:Vt},"data-testid":`overlay-text-${H.id}`,"data-fonts-ready":"true",children:[Ci&&d.jsx("span",{className:"font-bold text-[#3a3a3a] block",style:{fontSize:pt.speakerFontSize,lineHeight:1.2},children:H.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:pt.fontSize,lineHeight:`${pt.lineHeight}px`,fontWeight:((Nn=H.textStyle)==null?void 0:Nn.fontWeight)??400},children:pt.lines.map((ln,Un)=>d.jsx("span",{className:"block",children:ln},Un))})]})})(),Fe&&d.jsx("div",{onMouseDown:Vt=>{Vt.stopPropagation(),Et(Vt,H.id,"resize")},className:"absolute bottom-0 right-0 w-2 h-2 bg-accent cursor-se-resize","data-testid":`resize-${H.id}`})]},H.id)})]}),d.jsxs("div",{className:"w-64 border-l border-border p-3 overflow-y-auto flex-shrink-0",children:[((ui=t.aiDraft)==null?void 0:ui.status)==="generated"&&d.jsxs("div",{className:"mb-3 rounded border border-accent/30 bg-accent/5 p-2 space-y-1","data-testid":"ai-draft-current-target",children:[d.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"AI draft ready"}),d.jsx("p",{className:"text-[11px] text-muted",children:"These first-pass overlays came from the cut script. Review and tune them here before exporting the final panel."})]}),Q.length>0&&d.jsxs("div",{className:"mb-3 space-y-1.5","data-testid":"script-insert-panel",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"From script"}),d.jsx("div",{className:"flex flex-col gap-1",children:Q.map(H=>d.jsxs("button",{onClick:()=>He(H),"data-testid":`script-insert-${H.key}`,title:`Add ${H.type} overlay with this text`,className:"text-left px-2 py-1 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5",children:[d.jsxs("span",{className:"font-medium text-accent",children:["+ ",ku[H.type]]})," ",d.jsxs("span",{className:"text-muted",children:[H.speaker?`${H.speaker}: `:"",H.text.length>32?`${H.text.slice(0,32)}…`:H.text]})]},H.key))})]}),Te?d.jsxs("div",{className:"space-y-3",children:[d.jsx("p",{className:"text-xs font-medium text-foreground",children:ku[Te.type]}),Te.speaker!==void 0&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Speaker"}),d.jsx("input",{value:Te.speaker||"",onChange:H=>ke(Te.id,{speaker:H.target.value}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",placeholder:"Character name","data-testid":"inspector-speaker"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Text"}),d.jsx("textarea",{value:Te.text,onChange:H=>ke(Te.id,{text:H.target.value}),rows:3,className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent resize-none focus:border-accent focus:outline-none",placeholder:"Overlay text","data-testid":"inspector-text"})]}),d.jsx("button",{onClick:()=>ke(Te.id,Me(Te)),"data-testid":"inspector-fit-text",className:"w-full px-2 py-1 text-[11px] border border-border rounded hover:border-accent hover:text-accent",title:"Resize this overlay so its text fits without overflowing",children:"Fit box to text"}),d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-typography",children:[d.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Typography"}),((Bt=Te.textStyle)==null?void 0:Bt.mode)==="manual"?d.jsx("button",{type:"button",onClick:()=>ke(Te.id,{textStyle:void 0}),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"inspector-text-auto",children:"Auto-fit"}):d.jsx("button",{type:"button",onClick:()=>Ue(Te),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":"inspector-text-manual",children:"Manual"})]}),((yt=Te.textStyle)==null?void 0:yt.mode)==="manual"?d.jsxs("div",{className:"space-y-1.5",children:[d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Font size (% panel height)"}),d.jsx("input",{type:"number",step:"0.1",min:"1.5",max:"12",value:((Te.textStyle.fontScale??.032)*100).toFixed(1),onChange:H=>ke(Te.id,{textStyle:{...Te.textStyle,mode:"manual",fontScale:Math.max(.015,Math.min(.12,(parseFloat(H.target.value)||3.2)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-font-scale"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Weight"}),d.jsxs("select",{value:String(Te.textStyle.fontWeight??400),onChange:H=>ke(Te.id,{textStyle:{...Te.textStyle,mode:"manual",fontWeight:H.target.value==="700"?700:400}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-font-weight",children:[d.jsx("option",{value:"400",children:"Regular"}),d.jsx("option",{value:"700",children:"Bold"})]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Line height"}),d.jsx("input",{type:"number",step:"0.05",min:"0.9",max:"2",value:(Te.textStyle.lineHeightFactor??1.2).toFixed(2),onChange:H=>ke(Te.id,{textStyle:{...Te.textStyle,mode:"manual",lineHeightFactor:Math.max(.9,Math.min(2,parseFloat(H.target.value)||1.2))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-line-height"})]}),Te.type!=="sfx"&&d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Speaker scale"}),d.jsx("input",{type:"number",step:"0.05",min:"0.5",max:"1.5",value:(Te.textStyle.speakerScale??.8).toFixed(2),onChange:H=>ke(Te.id,{textStyle:{...Te.textStyle,mode:"manual",speakerScale:Math.max(.5,Math.min(1.5,parseFloat(H.target.value)||.8))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-speaker-scale"})]})]}):d.jsx("p",{className:"text-[10px] text-muted",children:"Auto-fit stays on by default and resizes text to the box."})]}),Te.type==="speech"&&(()=>{const H=Te.tailAnchor||{x:.5,y:1.2};return d.jsxs("div",{className:"space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Tail anchor"}),d.jsx("div",{className:"flex flex-wrap gap-1","data-testid":"inspector-tail-presets",children:kD.map(Se=>d.jsx("button",{type:"button",onClick:()=>ke(Te.id,{tailAnchor:Se.anchor}),className:"px-1.5 py-0.5 text-[10px] border border-border rounded hover:border-accent hover:bg-accent/5","data-testid":`inspector-tail-${Se.key}`,children:Se.label},Se.key))}),d.jsxs("div",{className:"flex gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["x",d.jsx("input",{type:"number",step:"0.1",value:H.x,onChange:Se=>ke(Te.id,{tailAnchor:{...H,x:parseFloat(Se.target.value)||0}}),className:"w-14 px-1 py-0.5 text-[10px] border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-tail-x"})]}),d.jsxs("label",{className:"flex items-center gap-1 text-[10px] font-mono text-muted",children:["y",d.jsx("input",{type:"number",step:"0.1",value:H.y,onChange:Se=>ke(Te.id,{tailAnchor:{...H,y:parseFloat(Se.target.value)||0}}),className:"w-14 px-1 py-0.5 text-[10px] border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-tail-y"})]})]})]})})(),Te.type!=="sfx"&&d.jsxs("div",{className:"space-y-1.5 rounded border border-border/70 p-2","data-testid":"inspector-bubble-style",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Bubble controls"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding X (% width)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Rt=Te.bubbleStyle)==null?void 0:Rt.paddingX)??.06)*100).toFixed(0),onChange:H=>ke(Te.id,{bubbleStyle:{...Te.bubbleStyle,paddingX:Math.max(0,Math.min(.25,(parseFloat(H.target.value)||6)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-padding-x"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Padding Y (% height)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"25",value:((((Qe=Te.bubbleStyle)==null?void 0:Qe.paddingY)??.08)*100).toFixed(0),onChange:H=>ke(Te.id,{bubbleStyle:{...Te.bubbleStyle,paddingY:Math.max(0,Math.min(.25,(parseFloat(H.target.value)||8)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-padding-y"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] text-muted",children:"Corner roundness (% short side)"}),d.jsx("input",{type:"number",step:"1",min:"0",max:"49",value:((((hi=Te.bubbleStyle)==null?void 0:hi.cornerRadius)??.4)*100).toFixed(0),onChange:H=>ke(Te.id,{bubbleStyle:{...Te.bubbleStyle,cornerRadius:Math.max(0,Math.min(.49,(parseFloat(H.target.value)||40)/100))}}),className:"w-full px-2 py-1 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"inspector-corner-radius"})]})]}),d.jsxs("div",{className:"text-[10px] text-muted","data-testid":"inspector-font",children:["Font:"," ",Te.type==="sfx"?v.family:b.family]}),d.jsxs("div",{className:"text-[10px] font-mono text-muted space-y-0.5",children:[d.jsxs("p",{children:["x: ",Te.x.toFixed(3),", y:"," ",Te.y.toFixed(3)]}),d.jsxs("p",{children:["w: ",Te.width.toFixed(3),", h:"," ",Te.height.toFixed(3)]})]}),d.jsx("button",{onClick:()=>{A?Je(Te.id):z(!0)},className:"w-full px-2 py-1 text-xs text-error border border-error/30 rounded hover:bg-error/5","data-testid":"delete-overlay",children:A?"Click again to delete":"Delete"})]}):d.jsx("p",{className:"text-xs text-muted","data-testid":"inspector-empty",children:"Select an overlay to inspect."})]})]})]})}function py(e){const t=`gfont-${e.googleFontsId}`;if(document.getElementById(t))return;const i=document.createElement("link");i.id=t,i.rel="stylesheet",i.href=JS(e),document.head.appendChild(i)}function ND({storyName:e,assetPath:t,authFetch:i,alt:s,overlays:a,language:o="English",background:c,aspectRatio:h,className:p,onClick:f,testId:_}){const x=ZS(o),b=QS(),v=Ou(x),S=Ou(b),j=xm(e,t,i),D=w.useRef(null),E=w.useMemo(()=>typeof document<"u"?document.createElement("canvas").getContext("2d"):null,[]),[N,I]=w.useState(!1),[te,q]=w.useState(()=>GS(h)??{width:800,height:600}),[R,ie]=w.useState({width:0,height:0});w.useEffect(()=>{py(x),py(b)},[x,b]),w.useEffect(()=>{let B=!1;return(async()=>{var ne;try{(ne=document.fonts)!=null&&ne.load&&await Promise.all([document.fonts.load(`16px "${x.family}"`),document.fonts.load(`16px "${b.family}"`)])}catch{}B||I(!0)})(),()=>{B=!0}},[x.family,b.family]),w.useEffect(()=>{const B=D.current;if(!B)return;const ne=new ResizeObserver(()=>{ie({width:B.clientWidth,height:B.clientHeight})});return ne.observe(B),()=>ne.disconnect()},[]);const fe=w.useCallback(B=>(ne,F,G=400)=>E?(E.font=`${G} ${F}px ${B}`,E.measureText(ne).width):ne.length*F*.5,[E]),be=d.jsx("div",{className:p??"w-full rounded border border-border bg-white","data-testid":_,ref:D,style:{aspectRatio:`${te.width} / ${te.height}`,maxHeight:"32rem"},children:d.jsxs("div",{className:"relative w-full h-full overflow-hidden rounded border border-border bg-white",children:[t?j.error||!j.loading&&!j.url?d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Image not available"}):j.url?d.jsx("img",{src:j.url,alt:s,className:"absolute inset-0 w-full h-full object-contain",draggable:!1,onLoad:B=>{const ne=B.currentTarget.naturalWidth||te.width,F=B.currentTarget.naturalHeight||te.height;ne>0&&F>0&&q({width:ne,height:F})}}):d.jsx("div",{className:"w-full h-full flex items-center justify-center text-[10px] text-muted bg-surface/40",children:"Loading image…"}):d.jsx("div",{className:"absolute inset-0",style:{background:c||"#101820"}}),R.width>0&&R.height>0&&a.length>0&&d.jsxs(d.Fragment,{children:[d.jsx("svg",{className:"absolute inset-0 w-full h-full pointer-events-none","data-testid":_?`${_}-overlay-layer`:void 0,children:a.map(B=>{if(B.type!=="speech")return null;const ne=B.x*R.width,F=B.y*R.height,G=B.width*R.width,Y=B.height*R.height,U=US(B,G,Y),A=B.tailAnchor?bm(ne,F,G,Y,B.tailAnchor,U):null,z=Math.max(1.25,R.height*.004);return d.jsx("path",{"data-testid":_?`${_}-overlay-${B.id}`:void 0,d:FS(ne,F,G,Y,A,U),className:"fill-white/95 stroke-[#1a1a1a]",strokeWidth:z,strokeLinejoin:"round"},B.id)})}),a.map(B=>{var $;const ne=B.x*R.width,F=B.y*R.height,G=B.width*R.width,Y=B.height*R.height,U=B.type==="sfx"?S:v,A=B.type==="speech";B.type;const z=B.type!=="sfx"&&!!B.speaker;return d.jsx("div",{className:`absolute rounded overflow-hidden ${A?"":"border-2"} ${B.type==="narration"?"border-muted/40 bg-[#f4efe6]/85 rounded-md":B.type==="sfx"?"border-accent/40":""}`,style:{left:ne,top:F,width:G,height:Y},children:B.text?N?(()=>{var T;const ge=Eo(fe(U),B.text,G,Y,No(B,R.height,G,Y));return d.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center px-1 text-center",style:{fontFamily:U},children:[z&&d.jsx("span",{className:"block font-bold text-[#3a3a3a]",style:{fontSize:ge.speakerFontSize,lineHeight:1.2},children:B.speaker}),d.jsx("span",{className:"text-[#1a1a1a]",style:{fontSize:ge.fontSize,lineHeight:`${ge.lineHeight}px`,fontWeight:((T=B.textStyle)==null?void 0:T.fontWeight)??400},children:ge.lines.map((M,V)=>d.jsx("span",{className:"block",children:M},V))})]})})():d.jsx("div",{className:"absolute inset-0 flex items-center justify-center px-1 text-center break-words",style:{fontFamily:U,fontSize:Math.max(8,Math.min(Y*.05,14)),fontWeight:(($=B.textStyle)==null?void 0:$.fontWeight)??400},children:z?`${B.speaker}: ${B.text}`:B.text}):d.jsx("span",{className:"block truncate px-1 text-[9px] text-muted",style:{fontFamily:U},children:B.type})},B.id)})]})]})});return f?d.jsx("button",{type:"button",onClick:f,className:"block w-full text-left","data-testid":_?`${_}-open`:void 0,children:be}):be}const jD={wide:"Wide",medium:"Medium","close-up":"Close-up","extreme-close-up":"Extreme close-up"},TD="No speech bubbles, captions, sound effects, narration, or any text or lettering in the image.",AD="Style lock — illustrated comic/webtoon panel art: clean black contour/ink lines, flat or cel shading, simplified but realistic (semi-realistic) anatomy and faces, backgrounds drawn as illustrated comic panels. Hold this same style on every cut for character and panel consistency. Hard negatives — NOT photorealistic, NOT a photograph, NOT a glossy or painterly digital painting, NOT concept art, NOT a 3D/CGI render, NOT airbrushed, no photoreal textures.";function RD(e){var a;const t=jD[e.shotType]??e.shotType,i=((a=e.description)==null?void 0:a.trim())||`Cut ${e.id}`,s=[`${t} shot. ${i}`];return e.characters.length>0&&s.push(`Characters: ${e.characters.join(", ")}.`),s.push(AD),s.push(TD),s.join(` +`).trim()}function DD(e,t){return`assets/${e}/cut-${String(t).padStart(2,"0")}-clean.webp`}function my(e,t){const i=DD(t,e.id);return[`Generate the clean image for cut ${e.id}.`,"","Image description:",RD(e),"","How to hand it off:","- Produce the actual image — do not just describe it or return a prompt.",`- If your image tool can write a WebP or JPEG under 1MB, save it at ${i} and run "Sync clean images".`,'- If it only produces a PNG (e.g. built-in image generation saves to ~/.codex/generated_images), that is fine — do NOT convert or rename it yourself. Leave it there and import it into this cut with the OWS "Import from Codex" button, which converts the PNG automatically.',"- Clean image only: no text, speech bubbles, captions, sound effects, signage, watermark, or signature.","- Hold the style lock above — an illustrated comic/webtoon panel, NOT a photoreal photo, painterly concept art, or 3D render. If a result reads photorealistic, regenerate it as illustrated panel art.","- Do not letter or upload anything — final lettering and upload happen later in OWS."].join(` +`)}const e1=12e3,MD=5,BD=6e4,LD=6e4,OD=5;function zD(e,t){return e===429?!0:!!t&&/rate[\s-]?limit/i.test(t)}function PD(e,t=e1){return Math.min(t*2**e,BD)}const t1=e=>new Promise(t=>setTimeout(t,e));async function ID(e,t={}){var c;const i=t.sleep??t1,s=t.maxRetries??MD,a=t.baseDelayMs??e1;let o=0;for(;;){const h=await e();if(h.ok||!zD(h.status,h.errorMessage)||o>=s)return h;const p=PD(o,a);o+=1,(c=t.onWaiting)==null||c.call(t,{attempt:o,maxRetries:s,waitMs:p}),await i(p)}}function HD(e={}){const t=e.limit??OD,i=e.windowMs??LD,s=e.sleep??t1,a=e.now??(()=>Date.now()),o=[],c=()=>{const h=a()-i;for(;o.length&&o[0]<=h;)o.shift()};return async function(){var p;if(c(),o.length>=t){const f=o[0]+i-a();f>0&&((p=e.onWaiting)==null||p.call(e,{waitMs:f}),await s(f)),c()}o.push(a())}}const zp=1024*1024;function gy(e,t,i){return new Promise((s,a)=>{e.toBlob(o=>o?s(o):a(new Error(`Failed to export as ${t}`)),t,i)})}async function UD(e){const t=[.9,.8,.7,.6];for(const s of t)try{const a=await gy(e,"image/webp",s);if(a.type!=="image/webp")break;if(a.size<=zp)return a}catch{break}const i=[.85,.7,.5];for(const s of i){const a=await gy(e,"image/jpeg",s);if(a.size<=zp)return a}throw new Error("Cannot compress image under 1MB — reduce overlay count or image size")}const $D=["image/webp","image/jpeg"];function i1(e){return $D.includes(e.type)&&e.size<=zp}async function FD(e){var i;if(typeof createImageBitmap!="function")throw new Error("This browser cannot decode the image for import");let t;try{t=await createImageBitmap(e)}catch{throw new Error("Could not read the selected image — pick a PNG, WebP, or JPEG file")}try{const s=document.createElement("canvas");s.width=t.width,s.height=t.height;const a=s.getContext("2d");if(!a)throw new Error("Could not process the image for import");return a.drawImage(t,0,0),s}finally{(i=t.close)==null||i.call(t)}}async function Vu(e){if(i1(e))return e;const t=await FD(e);return UD(t)}function qD(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.token=="string"&&t.token.length>0&&typeof t.name=="string"&&typeof t.size=="number"&&typeof t.mtimeMs=="number"}async function WD(e){let t;try{t=await e("/api/codex/images")}catch{return[]}if(!t.ok)return[];let i;try{i=await t.json()}catch{return[]}const s=i==null?void 0:i.images;return Array.isArray(s)?s.filter(qD):[]}async function GD(e,t){let i;try{i=await e(`/api/codex/images/${encodeURIComponent(t.token)}`)}catch{throw new Error("Could not read the generated image from the Codex cache")}if(!i.ok)throw new Error("Could not read the generated image from the Codex cache");const s=await i.blob(),a=s.type||i.headers.get("Content-Type")||"image/png";return new File([s],t.name||"codex-image.png",{type:a})}function YD(e,t){const[i,s]=w.useState(null);return w.useEffect(()=>{let a=null,o=!1;return(async()=>{try{const c=await t(e);if(!c.ok)return;const h=await c.blob();if(o)return;a=URL.createObjectURL(h),s(a)}catch{}})(),()=>{o=!0,a&&URL.revokeObjectURL(a)}},[e,t]),i}function KD(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function VD(e,t){const i=t-e;if(!Number.isFinite(i)||i<45e3)return"just now";const s=Math.round(i/6e4);if(s<60)return`${s}m ago`;const a=Math.round(i/36e5);if(a<24)return`${a}h ago`;const o=Math.round(i/864e5);return o<7?`${o}d ago`:`${Math.round(i/(7*864e5))}w ago`}function XD({image:e,authFetch:t}){const i=YD(`/api/codex/images/${encodeURIComponent(e.token)}`,t);return i?d.jsx("img",{src:i,alt:e.name,className:"w-16 h-16 flex-shrink-0 rounded border border-border object-cover bg-white"}):d.jsx("div",{className:"w-16 h-16 flex-shrink-0 rounded border border-border bg-surface"})}function ZD({authFetch:e,cutId:t,onImport:i,onClose:s}){const[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState("");w.useEffect(()=>{let E=!1;return(async()=>{const N=await WD(e);E||o(N)})(),()=>{E=!0}},[e]);const b=_.trim().toLowerCase(),v=w.useMemo(()=>a?b?a.filter(E=>E.name.toLowerCase().includes(b)):a:[],[a,b]),S=Date.now(),j=async E=>{h(null),f(E.token);try{const N=await GD(e,E);await i(N)}catch(N){h(N instanceof Error?N.message:"Could not import the generated image")}finally{f(null)}},D=a!==null&&a.length>0;return d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-2","data-testid":`codex-picker-${t}`,children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Import a Codex-generated image"}),d.jsx("button",{onClick:s,"data-testid":`codex-picker-close-${t}`,className:"text-[11px] text-muted hover:text-foreground",children:"Close"})]}),D&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"search",value:_,onChange:E=>x(E.target.value),placeholder:"Filter by file name…","data-testid":`codex-picker-search-${t}`,className:"min-w-0 flex-1 px-2 py-1 text-[11px] border border-border rounded bg-transparent focus:border-accent focus:outline-none"}),d.jsx("span",{className:"text-[10px] text-muted whitespace-nowrap","data-testid":`codex-picker-count-${t}`,children:b?`${v.length} of ${a.length}`:`${a.length} image${a.length===1?"":"s"}`})]}),a===null&&d.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-loading-${t}`,children:"Looking for generated images…"}),a!==null&&a.length===0&&d.jsx("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-empty-${t}`,children:"No generated images found in the Codex cache yet. Generate art in Codex, then reopen this list — or use “Upload clean image” to pick a file."}),D&&v.length===0&&d.jsxs("p",{className:"text-[11px] text-muted","data-testid":`codex-picker-no-match-${t}`,children:["No generated images match “",_.trim(),"”."]}),D&&v.length>0&&d.jsx("ul",{className:"space-y-1 max-h-72 overflow-y-auto",children:v.map(E=>d.jsxs("li",{"data-testid":`codex-image-${E.token}`,className:"flex items-center gap-2 rounded border border-border bg-background/40 p-1.5",children:[d.jsx(XD,{image:E,authFetch:e}),d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsxs("p",{className:"text-[11px] text-foreground",children:[VD(E.mtimeMs,S)," · ",KD(E.size)]}),d.jsx("p",{className:"truncate text-[10px] font-mono text-muted",title:E.name,children:E.name})]}),d.jsx("button",{onClick:()=>j(E),disabled:p!==null,"data-testid":`codex-import-${E.token}`,className:"px-2 py-1 text-[11px] border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:p===E.token?"Importing…":"Import to this cut"})]},E.token))}),c&&d.jsx("p",{className:"text-[11px] text-error",children:c})]})}const QD={done:"✓",current:"▸",todo:"○"};function JD({checklist:e,issues:t,onFinish:i,finishing:s,progressText:a,canFinish:o,markdownReady:c=!1,published:h=!1}){var E;if(!e||e.steps.length===0)return null;const p=XS(t),f=((E=e.steps.find(N=>N.key==="upload"))==null?void 0:E.status)==="done",_=f&&c&&!h,x=h||c?"done":f?"current":"todo",b=h?"done":_?"current":"todo",v=[...e.steps.filter(N=>N.key!=="publish"),{key:"assemble",label:"Episode sequence prepared",status:x,detail:null},{key:"ready",label:h?"Published to PlotLink":"Ready to publish",status:b,detail:null}],S=s?a||"Finishing…":h?"Published ✓":_?"Episode ready to publish":"Finish episode",j=v.filter(N=>N.status!=="done").length,D=p.reduce((N,I)=>N+I.lines.length,0);return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/50 flex-shrink-0","data-testid":"finish-episode-panel",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Finish episode"}),e.nextStep&&d.jsxs("span",{className:"min-w-0 flex-1 text-[10px] text-muted truncate","data-testid":"finish-next-step",children:["Next: ",e.nextStep]}),d.jsx("button",{onClick:i,disabled:s||!o,"data-testid":"finish-episode-btn",title:"Upload the exported final panels, then prepare the episode for publishing — picks up where it left off",className:"px-2.5 py-0.5 text-[11px] border border-accent/40 text-accent rounded hover:bg-accent/5 disabled:opacity-50",children:S})]}),d.jsxs("details",{className:"mt-1","data-testid":"finish-episode-details",children:[d.jsxs("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:[j===0?"Progress details":`${j} step${j===1?"":"s"} left`,D>0?` · ${D} blocker${D===1?"":"s"}`:""]}),d.jsxs("div",{className:"mt-1.5 space-y-1.5",children:[d.jsx("ol",{className:"flex flex-wrap gap-1.5",children:v.map(N=>d.jsxs("li",{"data-testid":`finish-step-${N.key}`,"data-status":N.status,className:`flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${N.status==="current"?"border-accent/40 bg-accent/10 text-accent":N.status==="done"?"border-border bg-background/70 text-foreground":"border-border/70 bg-background/40 text-muted"}`,children:[d.jsx("span",{"aria-hidden":!0,children:QD[N.status]}),d.jsx("span",{children:N.label}),N.detail&&d.jsxs("span",{className:"text-muted",children:["· ",N.detail]})]},N.key))}),p.length>0&&d.jsx("div",{className:"space-y-1.5","data-testid":"finish-issues",children:p.map(N=>d.jsxs("div",{"data-testid":`finish-issue-group-${N.key}`,className:"text-[10px]",children:[d.jsx("p",{className:"font-medium text-amber-700",children:N.title}),d.jsx("ul",{className:"ml-3 list-disc text-muted",children:N.lines.map((I,te)=>d.jsx("li",{children:I},te))})]},N.key))})]})]})]})}function eM(e){return{planned:e.filter(t=>t.state==="planned").length,needsConversion:e.filter(t=>t.state==="needs-conversion").length,missing:e.filter(t=>t.state==="missing").length,cleanReady:e.filter(t=>t.state==="clean-ready").length,finalReady:e.filter(t=>t.state==="final-ready").length,uploaded:e.filter(t=>t.state==="uploaded").length}}function Do(e){return(!!e.cleanImagePath||fn(e))&&wm(e).length>0}function xy(e){const t=new Date().toISOString();return{status:"generated",baseSig:ul(e),generatedAt:t,updatedAt:t}}function n1(e){return e.uploadedCid?"uploaded":e.finalImagePath||e.exportedAt?"lettered":e.cleanImagePath?"clean":fn(e)?"text":"missing"}const _y={muted:"text-muted",amber:"text-amber-700",green:"text-green-700",accent:"text-accent"},tM={muted:"bg-muted/40",amber:"bg-amber-500",green:"bg-green-600",accent:"bg-accent"};function iM(e,t,i){var s;return e.uploadedCid||e.uploadedUrl?{key:"uploaded",label:"Uploaded",tone:"green"}:t?{key:"convert",label:"Needs conversion",tone:"amber"}:i?e.finalImagePath?{key:"review",label:"Needs review",tone:"amber"}:{key:"needs-image",label:"Needs image",tone:"muted"}:e.finalImagePath?{key:"exported",label:"Exported",tone:"green"}:fn(e)?{key:"text",label:"Ready for captions",tone:"accent"}:e.cleanImagePath?(((s=e.overlays)==null?void 0:s.length)??0)>0?{key:"review",label:"Needs review",tone:"amber"}:{key:"letter",label:"Ready for lettering",tone:"green"}:{key:"needs-image",label:"Needs image",tone:"muted"}}function nM(e){var t,i;return e.uploadedCid||e.uploadedUrl?{label:"Complete",detail:"Final image uploaded",tone:"green"}:e.finalImagePath||e.exportedAt?{label:"Exported",detail:"Ready to upload",tone:"green"}:(((t=e.overlays)==null?void 0:t.length)??0)>0?((i=e.aiDraft)==null?void 0:i.status)==="generated"?{label:"Draft ready",detail:`${e.overlays.length} AI-drafted overlay${e.overlays.length===1?"":"s"} ready to review`,tone:"amber"}:{label:"User-edited",detail:`${e.overlays.length} overlay${e.overlays.length===1?"":"s"} adjusted and ready to review`,tone:"amber"}:Do(e)?{label:"No draft",detail:"Draft with AI or place bubbles manually",tone:"muted"}:fn(e)?{label:"Between-scene card",detail:"Open to add narration or title text",tone:"accent"}:e.cleanImagePath?{label:"Unlettered",detail:"Clean art ready for bubble placement",tone:"muted"}:{label:"Needs artwork",detail:"Add or sync clean art first",tone:"muted"}}function rM({cut:e,storyName:t,plotFile:i,language:s,expanded:a,onToggle:o,authFetch:c,onUpdated:h,onOpenEditor:p,detectedLocalClean:f,onSyncClean:_,syncing:x,onAiDraft:b,aiDrafting:v,staleMessages:S,onRepairStale:j,repairing:D,conversionPng:E,onConvert:N,converting:I,rowRef:te}){var He,ke;const q=w.useRef(null),[R,ie]=w.useState(!1),[fe,be]=w.useState(null),[B,ne]=w.useState(!1),[F,G]=w.useState(!1),[Y,U]=w.useState(!1),[A,z]=w.useState(!1),$=n1(e),ge=S.length>0,T=!!E,M=w.useCallback(async()=>{E&&(z(!0),await N(e.id,E),z(!1),h())},[E,N,e.id,h]),V=w.useCallback(async Ue=>{ie(!0),be(null);try{let Je=Ue;if(!i1(Ue))try{Je=await Vu(Ue)}catch(ze){return be(ze instanceof Error?ze.message:"Could not import image"),!1}const at=Je.type==="image/jpeg"?"jpg":"webp",Ve=new FormData;Ve.append("file",new File([Je],`clean.${at}`,{type:Je.type}));const Et=await c(`/api/stories/${t}/cuts/${i}/upload-clean/${e.id}`,{method:"POST",body:Ve});if(!Et.ok){const ze=await Et.json();return be(ze.error||"Upload failed"),!1}return h(),!0}catch{return be("Upload failed"),!1}finally{ie(!1)}},[c,t,i,e.id,h]),C=iM(e,T,ge),X=e.cleanImagePath??E??null,se=((He=e.overlays)==null?void 0:He.length)??0,le=!fn(e)&&!!e.cleanImagePath&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&!ge&&!T,K=!ge&&!T&&!e.finalImagePath&&!e.uploadedCid&&!e.uploadedUrl&&Do(e),he=(((ke=e.overlays)==null?void 0:ke.length)??0)>0?"Re-draft with AI":"AI draft lettering",_e=C.key==="convert"?{label:A?"Converting…":"Convert image",onClick:M,testid:`card-convert-${e.id}`}:C.key==="review"?{label:"Review cut",onClick:p,testid:`card-review-${e.id}`}:C.key==="text"?{label:"Add captions",onClick:p,testid:`card-letter-${e.id}`}:C.key==="needs-image"?{label:"Add artwork",onClick:o,testid:`card-addart-${e.id}`}:null,Me=nM(e),Le=!!e.cleanImagePath||!!e.narration||e.dialogue.length>0||fn(e);return d.jsxs("div",{ref:te,"data-cut-row":e.id,className:`border rounded ${a?"border-accent/30":"border-border"}`,children:[d.jsxs("div",{className:"px-3 py-2 space-y-2","data-testid":`cut-card-${e.id}`,children:[d.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[d.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${tM[C.tone]}`}),d.jsxs("span",{className:"font-medium text-xs text-foreground",children:["Cut ",String(e.id).padStart(2,"0")]}),d.jsxs("span",{className:"font-mono text-[10px] text-muted",children:["· ",e.shotType]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium flex-shrink-0 ${_y[C.tone]}`,"data-testid":`cut-card-status-${e.id}`,children:C.label})]}),X||fn(e)?d.jsx(ND,{storyName:t,assetPath:X,authFetch:c,alt:`Cut ${e.id} artwork`,overlays:e.overlays,language:s,background:e.background,aspectRatio:e.aspectRatio,onClick:Le?p:void 0,className:"w-full",testId:`cut-preview-${e.id}`}):d.jsx("div",{className:"w-full min-h-28 rounded border border-dashed border-border bg-surface/40 flex items-center justify-center text-[10px] text-muted","data-testid":`cut-card-noart-${e.id}`,children:fn(e)?"Text panel — no artwork needed":"No artwork yet"}),d.jsxs("div",{className:`rounded border border-border/70 bg-surface/50 px-2 py-1.5 text-[11px] ${_y[Me.tone]}`,"data-testid":`lettering-review-state-${e.id}`,children:[d.jsx("span",{className:"font-semibold",children:Me.label}),d.jsxs("span",{className:"text-muted",children:[" · ",Me.detail]})]}),d.jsx("button",{onClick:o,"data-testid":`cut-desc-${e.id}`,className:"block w-full text-left text-[11px] text-muted hover:text-foreground",children:e.description||"No description"}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[le?d.jsxs(d.Fragment,{children:[d.jsx("button",{onClick:p,"data-testid":`add-bubbles-${e.id}`,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim",children:se>0?"Review lettering":"Open focused editor"}),K&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":he})]}):_e?d.jsx("button",{onClick:_e.onClick,disabled:C.key==="convert"&&(A||I),"data-testid":_e.testid,className:"px-2.5 py-1 text-[11px] font-medium rounded bg-accent text-white hover:bg-accent-dim disabled:opacity-50",children:_e.label}):null,!le&&!_e&&K&&d.jsx("button",{onClick:b,disabled:v,"data-testid":`ai-draft-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:v?"Drafting…":he}),d.jsx("button",{onClick:o,"data-testid":`cut-details-${e.id}`,className:"px-2.5 py-1 text-[11px] rounded border border-border text-muted hover:border-accent hover:text-accent",children:a?"Hide details":"Open details"})]})]}),a&&d.jsxs("div",{className:"px-3 pb-3 space-y-3 border-t border-border",children:[T&&d.jsxs("div",{className:"mt-2 rounded border border-amber-500/40 bg-amber-500/10 p-2 space-y-1","data-testid":`needs-conversion-${e.id}`,children:[d.jsx("p",{className:"text-[11px] text-amber-800",children:"This cut’s artwork is a PNG. Convert it to WebP so it can be lettered and published."}),d.jsx("button",{onClick:M,disabled:A||I,"data-testid":`convert-cut-${e.id}`,className:"px-2 py-1 text-[11px] border border-amber-500/50 text-amber-800 rounded hover:bg-amber-500/20 disabled:opacity-50",children:A?"Converting…":"Convert image"})]}),ge&&!T&&d.jsxs("div",{className:"mt-2 rounded border border-error/40 bg-error/5 p-2 space-y-1","data-testid":`stale-asset-${e.id}`,children:[S.map((Ue,Je)=>d.jsx("p",{className:"text-[11px] text-error",children:Ue},Je)),d.jsx("button",{onClick:j,disabled:D,"data-testid":`repair-stale-${e.id}`,className:"px-2 py-1 text-[11px] border border-error/40 text-error rounded hover:bg-error/10 disabled:opacity-50",children:D?"Repairing…":"Clear stale path"})]}),!fn(e)&&d.jsxs("div",{className:"mt-2 space-y-2",children:[d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(my(e,i)),ne(!0),setTimeout(()=>ne(!1),2e3)},"data-testid":`copy-prompt-${e.id}`,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5",children:B?"Copied!":"Copy Codex task"}),d.jsx("input",{ref:q,type:"file",accept:"image/webp,image/jpeg,image/png",className:"hidden",onChange:Ue=>{var at;const Je=(at=Ue.target.files)==null?void 0:at[0];Je&&V(Je),Ue.target.value=""}}),d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsx("button",{onClick:()=>{var Ue;return(Ue=q.current)==null?void 0:Ue.click()},disabled:R,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:R?"Uploading...":e.cleanImagePath?"Replace clean image":"Upload clean image"}),d.jsx("button",{onClick:()=>U(Ue=>!Ue),disabled:R,"data-testid":`import-codex-${e.id}`,className:"px-3 py-1.5 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50",children:Y?"Hide Codex images":"Import from Codex"})]}),Y&&d.jsx(ZD,{authFetch:c,cutId:e.id,onImport:async Ue=>{await V(Ue)&&U(!1)},onClose:()=>U(!1)}),!e.cleanImagePath&&d.jsx("p",{className:"text-xs text-muted","data-testid":`clean-image-handoff-${e.id}`,children:"Generate this cut in Codex, then import the cached PNG with “Import from Codex” — or upload an image manually. Letter it next."}),$==="missing"&&d.jsxs("div",{className:"rounded border border-border bg-surface/60 p-2 space-y-1","data-testid":`ask-codex-${e.id}`,children:[d.jsx("p",{className:"text-[11px] font-medium text-foreground",children:"Generate this cut in Codex"}),d.jsxs("p",{className:"text-[10px] text-muted",children:["Copy the task below and paste it into Codex. Codex usually saves a PNG to its image cache — bring it into this cut with “Import from Codex” above (the PNG becomes a WebP automatically). If Codex instead writes a WebP/JPEG at"," ",d.jsxs("span",{className:"font-mono",children:["assets/",i,"/cut-",String(e.id).padStart(2,"0"),"-clean.webp"]}),", it’s picked up by “Sync clean images”."]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(my(e,i)),G(!0),setTimeout(()=>G(!1),2e3)},"data-testid":`ask-codex-copy-${e.id}`,className:"px-2 py-1 text-[11px] border border-border rounded hover:border-accent hover:bg-accent/5",children:F?"Copied!":"Copy Codex task"})]}),$==="missing"&&f&&d.jsx("button",{onClick:_,disabled:x,"data-testid":`found-local-clean-${e.id}`,className:"px-3 py-1.5 text-xs border border-green-700/40 text-green-700 rounded hover:bg-green-700/5 disabled:opacity-50",children:x?"Syncing...":"Found local clean image — sync to cut plan"}),fe&&d.jsx("p",{className:"text-xs text-error mt-1",children:fe})]}),(e.cleanImagePath||e.narration||e.dialogue.length>0||fn(e))&&d.jsx("button",{onClick:p,"data-testid":`open-editor-${e.id}`,className:"px-3 py-1.5 text-xs border border-accent/30 text-accent rounded hover:bg-accent/5",children:"Open editor"}),e.characters.length>0&&d.jsxs("p",{className:"text-xs text-muted",children:["Characters: ",e.characters.join(", ")]}),e.dialogue.length>0&&d.jsx("div",{className:"text-xs text-muted",children:e.dialogue.map((Ue,Je)=>d.jsxs("p",{children:[d.jsxs("span",{className:"font-medium",children:[Ue.speaker,":"]})," ",Ue.text]},Je))}),e.narration&&d.jsx("p",{className:"text-xs text-muted italic",children:e.narration})]})]})}function by({storyName:e,fileName:t,authFetch:i,language:s,uploadRetry:a,onCutsChanged:o,focusRequest:c,onFocusHandled:h,onFocusedLetteringModeChange:p,workspaceVisible:f=!1,onWorkspaceVisibleChange:_}){var pr,Lt,oe;const[x,b]=w.useState(null),v=w.useRef(o);v.current=o;const S=w.useRef(h);S.current=h;const[j,D]=w.useState(!0),[E,N]=w.useState(null),[I,te]=w.useState(null),[q,R]=w.useState(null),[ie,fe]=w.useState(!1),[be,B]=w.useState([]),[ne,F]=w.useState(!1),[G,Y]=w.useState(""),[U,A]=w.useState({markdownReady:!1,published:!1}),[z,$]=w.useState(!1),[ge,T]=w.useState(!1),[M,V]=w.useState(!1),[C,X]=w.useState(null),[se,le]=w.useState(null),[K,he]=w.useState(null),[_e,Me]=w.useState(!1),[Le,He]=w.useState(new Set),[ke,Ue]=w.useState(new Map),[Je,at]=w.useState(!1),[Ve,Et]=w.useState(null),[ze,_t]=w.useState(!1),[Te,Kt]=w.useState(null),mi=w.useRef(new Map),wt=w.useRef(null),et=t.replace(/\.md$/,"");w.useEffect(()=>{var O;c&&wt.current!==c.seq&&(wt.current=c.seq,c.openEditor?R(c.cutId):(te(c.cutId),Kt(c.cutId)),(O=S.current)==null||O.call(S))},[c]),w.useEffect(()=>(p==null||p(q!==null),()=>p==null?void 0:p(!1)),[q,p]),w.useEffect(()=>{var ce;if(Te==null)return;const O=mi.current.get(Te);O&&((ce=O.scrollIntoView)==null||ce.call(O,{behavior:"smooth",block:"center"}),Kt(null))},[Te,x]);const Q=w.useCallback(async()=>{var O;try{const ce=await i(`/api/stories/${e}/cuts/${et}`);if(ce.status===404){b(null);return}if(!ce.ok){const De=await ce.json();N(De.error||"Failed to load cuts");return}const Ee=await ce.json();b(Ee),N(null);try{const De=await i(`/api/stories/${e}/${t}`);if(De.ok){const Ne=await De.json(),Pe=typeof(Ne==null?void 0:Ne.content)=="string"?Ne.content:"",We=Array.isArray(Ee==null?void 0:Ee.cuts)?Ee.cuts:[],rt=Pe.length>0&&KS(Pe,We).ready,Xe=(Ne==null?void 0:Ne.status)==="published"||(Ne==null?void 0:Ne.status)==="published-not-indexed";A({markdownReady:rt,published:Xe})}else A({markdownReady:!1,published:!1})}catch{A({markdownReady:!1,published:!1})}(O=v.current)==null||O.call(v)}catch{N("Failed to load cuts")}finally{D(!1)}},[i,e,et,t]),xe=w.useCallback(async O=>!!(await i(`/api/stories/${e}/cuts/${et}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)})).ok,[i,e,et]),je=w.useCallback(async()=>{at(!1);try{const O=await i(`/api/stories/${e}/cuts/${et}/detect-clean-images`);if(!O.ok)return;const ce=await O.json();He(new Set(Array.isArray(ce.detected)?ce.detected:[]));const Ee=new Map,De=ce.stale;if(Array.isArray(De))for(const Ne of De){if(typeof(Ne==null?void 0:Ne.cutId)!="number"||typeof(Ne==null?void 0:Ne.message)!="string")continue;const Pe=Ee.get(Ne.cutId)??[];Pe.push(Ne.message),Ee.set(Ne.cutId,Pe)}Ue(Ee),at(!0)}catch{}},[i,e,et]),$e=w.useCallback(async()=>{Et(null);try{const O=await i(`/api/stories/${e}/cuts/${et}/asset-diagnostics`);if(!O.ok)return;const ce=await O.json();Et(Array.isArray(ce.diagnostics)?ce.diagnostics:null)}catch{}},[i,e,et]),nt=w.useCallback(async()=>{_t(!0);try{await Promise.all([Q(),je(),$e()])}finally{_t(!1)}},[Q,je,$e]),Wt=w.useCallback(async(O,ce={})=>{var Ne;if(!x)return!1;const Ee=x.cuts.find(Pe=>Pe.id===O);if(!Ee||!Do(Ee)||(((Ne=Ee.overlays)==null?void 0:Ne.length)??0)>0&&!window.confirm("This cut already has overlays. Re-drafting with AI will replace the current draft overlays for this cut. Continue?"))return!1;const De=uy(Ee);if(De.length===0)return le(`Cut ${Ee.id}: no script lines available to draft.`),!1;he(O),le(null);try{const Pe={...x,cuts:x.cuts.map(rt=>rt.id===O?{...rt,overlays:De,aiDraft:xy(De)}:rt)};return await xe(Pe)?(le(`Cut ${Ee.id}: AI draft ready`),await Q(),ce.openEditor&&R(O),!0):(le(`Cut ${Ee.id}: AI draft failed`),!1)}finally{he(null)}},[x,xe,Q]),ui=w.useCallback(async()=>{if(!x)return;const O=x.cuts.filter(ce=>{var Ee;return Do(ce)&&(((Ee=ce.overlays)==null?void 0:Ee.length)??0)===0&&!ce.finalImagePath&&!ce.uploadedCid&&!ce.uploadedUrl});if(O.length===0){le("No unlettered cuts need an AI draft");return}Me(!0),le(null);try{const ce={...x,cuts:x.cuts.map(De=>{if(!O.some(Pe=>Pe.id===De.id))return De;const Ne=uy(De);return Ne.length>0?{...De,overlays:Ne,aiDraft:xy(Ne)}:De})};if(!await xe(ce)){le("AI draft failed");return}le(`AI draft ready for ${O.length} cut${O.length===1?"":"s"}`),await Q()}finally{Me(!1)}},[x,xe,Q]),Bt=w.useCallback(async()=>{$(!0),le(null),B([]);try{const O=await i(`/api/stories/${e}/cuts/${et}/sync-clean-images`,{method:"POST"}),ce=await O.json().catch(()=>({}));if(!O.ok)le(ce.error||"Sync failed");else{const Ee=Array.isArray(ce.synced)?ce.synced.length:0,De=Array.isArray(ce.cleared)?ce.cleared.length:0,Ne=Array.isArray(ce.rejected)?ce.rejected:[];Ne.length>0&&B(Ne.map(We=>`Cut ${We.cutId}: ${We.reason}`));const Pe=[];Ee>0&&Pe.push(`Synced ${Ee}`),De>0&&Pe.push(`Cleared ${De} stale path${De===1?"":"s"}`),le(Pe.length>0?Pe.join(", "):"No new clean images"),await Q(),await je(),await $e()}}catch{le("Sync failed")}$(!1)},[i,e,et,Q,je,$e]),yt=w.useCallback(async(O,ce)=>{try{const Ee=await i(IS(e,ce));if(!Ee.ok)return!1;const De=await Ee.blob(),Ne=await Vu(new File([De],"clean.png",{type:De.type||"image/png"})),Pe=Ne.type==="image/jpeg"?"jpg":"webp",We=new FormData;return We.append("file",new File([Ne],`clean.${Pe}`,{type:Ne.type})),(await i(`/api/stories/${e}/cuts/${et}/upload-clean/${O}`,{method:"POST",body:We})).ok}catch{return!1}},[i,e,et]),Rt=w.useCallback(async O=>{V(!0),X(null);let ce=0;const Ee=[];for(const De of O)await yt(De.cutId,De.pngPath)?ce++:Ee.push(De.cutId);await nt(),V(!1),X(Ee.length===0?`Converted ${ce} image${ce===1?"":"s"} to WebP`:`Converted ${ce}; ${Ee.length} failed (Cut ${Ee.join(", ")}) — try Convert image on each`)},[yt,nt]),Qe=w.useCallback(async()=>{var Ne;if(!x)return;F(!0),Y(""),B([]);const O=x.cuts.filter(Pe=>Pe.finalImagePath&&!Pe.uploadedCid),ce=[],Ee=HD({sleep:a==null?void 0:a.sleep,onWaiting:({waitMs:Pe})=>Y(`Upload limit reached — waiting ${Math.round(Pe/1e3)}s before continuing…`)});for(let Pe=0;Pe{const Jt=await i("/api/publish/upload-plot-image",{method:"POST",body:jt});if(Jt.ok){const{cid:$n,url:gr}=await Jt.json();return{ok:!0,status:Jt.status,cid:$n,url:gr}}const qi=await Jt.json().catch(()=>({}));return{ok:!1,status:Jt.status,errorMessage:qi.error}},{...a,onWaiting:({attempt:Jt,maxRetries:qi,waitMs:$n})=>Y(`Cut ${We.id} rate-limited — waiting ${Math.round($n/1e3)}s before retry ${Jt}/${qi}...`)});if(!Gt.ok){ce.push(`Cut ${We.id}: upload failed — ${Gt.errorMessage||"unknown"}`);continue}const{cid:Dt,url:ki}=Gt;(await i(`/api/stories/${e}/cuts/${et}/set-uploaded/${We.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cid:Dt,url:ki})})).ok||ce.push(`Cut ${We.id}: failed to record upload`)}catch(rt){ce.push(`Cut ${We.id}: ${rt instanceof Error?rt.message:"failed"}`)}}if(ce.length>0){B(ce),F(!1),Y(""),Q();return}Y("Preparing episode for publishing…");const De=await i(`/api/stories/${e}/cuts/${et}/generate-markdown`,{method:"POST"});if(De.ok){const Pe=await De.json();((Ne=Pe.warnings)==null?void 0:Ne.length)>0&&B(Pe.warnings)}F(!1),Y(""),Q()},[x,i,e,et,a,Q]),hi=w.useCallback(async()=>{T(!0),le(null);try{const O=await i(`/api/stories/${e}/cuts/${et}/repair-asset-paths`,{method:"POST"}),ce=await O.json().catch(()=>({}));if(!O.ok)le(ce.error||"Repair failed");else{const Ee=Array.isArray(ce.cleared)?ce.cleared.length:0;le(Ee>0?`Cleared ${Ee} stale path${Ee===1?"":"s"}`:"No stale paths to clear"),await Q(),await je()}}catch{le("Repair failed")}T(!1)},[i,e,et,Q,je]),[H,Se]=w.useState(!1),Oe=w.useCallback(async(O,ce=!0)=>{if(x){Se(!0);try{const Ee=x.cuts.reduce((rt,Xe)=>Math.max(rt,Xe.id),0)+1,De={id:Ee,shotType:"wide",description:"Text panel",characters:[],dialogue:[],narration:"",sfx:"",cleanImagePath:null,finalImagePath:null,exportedAt:null,uploadedCid:null,uploadedUrl:null,overlays:[],kind:"text",background:"#101820",aspectRatio:"4:5"},Ne=[...x.cuts];Ne.splice(Math.max(0,Math.min(O,Ne.length)),0,De);const Pe={...x,cuts:Ne},We=await i(`/api/stories/${e}/cuts/${et}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Pe)});if(We.ok)ce?R(Ee):te(Ee),await Q();else{const rt=await We.json().catch(()=>({}));le(rt.error||"Could not add text panel")}}catch{le("Could not add text panel")}Se(!1)}},[x,i,e,et,Q]),Ae=w.useCallback(()=>Oe((x==null?void 0:x.cuts.length)??0,!0),[Oe,x]);if(w.useEffect(()=>{Q(),je(),$e()},[Q,je,$e]),j)return d.jsx("div",{className:"p-4 text-sm text-muted",children:"Loading cuts..."});if(E)return d.jsxs("div",{className:"p-4 space-y-2","data-testid":"cuts-error",children:[d.jsx("p",{className:"text-sm text-error font-medium",children:"Invalid cuts file"}),d.jsx("p",{className:"text-xs text-error",children:E}),d.jsxs("p",{className:"text-xs text-muted",children:[et,".cuts.json must follow the OWS v1 schema. Ask Claude to regenerate it using the v1 cuts schema from the cartoon writing instructions."]}),d.jsx("button",{onClick:Q,className:"text-xs text-accent hover:text-accent-dim",children:"Retry"})]});if(!x||x.cuts.length===0)return d.jsxs("div",{className:"p-4 text-center space-y-1",children:[d.jsx("p",{className:"text-sm text-muted",children:"No cuts yet"}),d.jsx("p",{className:"text-xs text-muted",children:"Ask Claude to create a cut plan for this episode."})]});const Ge=q!==null?x.cuts.find(O=>O.id===q):null;if(Ge)return d.jsx(ED,{storyName:e,cut:Ge,plotFile:et,language:s,authFetch:i,targetLabel:fn(Ge)?`Between-scene card ${Ge.id}`:`Cut ${String(Ge.id).padStart(2,"0")}`,returnOnSave:!0,workspaceVisible:f,onToggleWorkspaceVisible:_?()=>_(!f):void 0,onSave:async(O,ce)=>{const Ee={...x,cuts:x.cuts.map(Ne=>Ne.id===q?{...Ne,overlays:O,aiDraft:ce??Ne.aiDraft??null}:Ne)};if(!await xe(Ee))throw new Error("Failed to save overlays")},onExported:()=>Q(),onClose:()=>{R(null),Q()}});const Fe=x.cuts.reduce((O,ce)=>{const Ee=n1(ce);return O[Ee]++,O},{missing:0,clean:0,lettered:0,uploaded:0,text:0}),dt=x.cuts.filter(O=>!fn(O)).length,ft=x.cuts.filter(O=>WS(O)).map(O=>O.id),ct=cD({cuts:x.cuts,published:U.published}),Vt=((pr=ct.steps.find(O=>O.key==="upload"))==null?void 0:pr.status)==="done",Ci=x.cuts.some(O=>O.finalImagePath&&!O.uploadedCid)||Vt&&!U.markdownReady,pt=(Ve??[]).filter(O=>O.state==="needs-conversion"&&O.convertiblePng).map(O=>({cutId:O.cutId,pngPath:O.convertiblePng})),Fi=new Map(pt.map(O=>[O.cutId,O.pngPath])),Nn=(Ve??[]).filter(O=>O.state==="needs-conversion"&&O.issue).map(O=>O.issue),ln=t==="genesis.md"?"Genesis / Episode 1":`Episode ${parseInt(((Lt=et.match(/\d+/))==null?void 0:Lt[0])??"0",10)+1}`,Un=typeof x.title=="string"?x.title:null,on=x.cuts.filter(O=>!fn(O)),xn={cuts:x.cuts.length,artwork:on.filter(O=>O.cleanImagePath||Fi.has(O.id)).length,converted:on.filter(O=>O.cleanImagePath&&/\.(webp|jpe?g)$/i.test(O.cleanImagePath)).length,lettered:x.cuts.filter(O=>{var ce;return(((ce=O.overlays)==null?void 0:ce.length)??0)>0||!!O.finalImagePath}).length,uploaded:x.cuts.filter(O=>O.uploadedCid||O.uploadedUrl).length},cn=x.cuts.filter(O=>{var ce;return Do(O)&&(((ce=O.overlays)==null?void 0:ce.length)??0)===0&&!O.finalImagePath&&!O.uploadedCid&&!O.uploadedUrl}).length;return d.jsxs("div",{className:"h-full min-h-[22rem] flex flex-col overflow-hidden","data-testid":"cut-list-panel",children:[d.jsx("div",{className:"px-3 py-2 border-b border-border flex-shrink-0","data-testid":"cut-board-header",children:d.jsxs("div",{className:"flex items-start gap-3 justify-between",children:[d.jsxs("div",{className:"min-w-0",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"font-serif text-foreground truncate",children:ln}),Un&&d.jsxs("span",{className:"text-muted truncate",children:["· ",Un]})]}),d.jsxs("div",{className:"mt-0.5 text-[10px] text-muted","data-testid":"cut-board-summary",children:[xn.cuts," cuts · ",xn.artwork," artwork found ·"," ",xn.converted," converted · ",xn.lettered," ","lettered · ",xn.uploaded," uploaded"]})]}),cn>0&&d.jsx("button",{onClick:ui,disabled:_e,"data-testid":"ai-draft-all-btn",className:"px-2.5 py-1 text-[11px] rounded border border-accent/40 text-accent hover:bg-accent/5 disabled:opacity-50",children:_e?"Drafting…":`AI draft all unlettered (${cn})`})]})}),d.jsxs("details",{className:"border-b border-border flex-shrink-0","data-testid":"cut-advanced",children:[d.jsx("summary",{className:"px-3 py-1.5 text-[10px] text-muted cursor-pointer hover:text-foreground",children:"Technical details"}),d.jsxs("div",{className:"px-3 py-2 flex flex-wrap items-center gap-2 text-[10px]",children:[d.jsxs("span",{className:"font-mono text-muted",children:[x.cuts.length," cuts"]}),Fe.missing>0&&d.jsxs("span",{className:"text-muted",children:[Fe.missing," missing"]}),Fe.clean>0&&d.jsxs("span",{className:"text-green-700",children:[Fe.clean," clean"]}),Fe.lettered>0&&d.jsxs("span",{className:"text-amber-700",children:[Fe.lettered," lettered"]}),Fe.uploaded>0&&d.jsxs("span",{className:"text-green-700",children:[Fe.uploaded," uploaded"]}),Fe.text>0&&d.jsxs("span",{className:"text-accent",children:[Fe.text," text ",Fe.text===1?"panel":"panels"]}),d.jsx("button",{onClick:async()=>{fe(!0),B([]);try{const O=await i(`/api/stories/${e}/cuts/${et}/generate-markdown`,{method:"POST"});if(O.ok){const ce=await O.json();B(ce.warnings||[])}}catch{}fe(!1)},disabled:ie,className:"ml-auto px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"generate-markdown-btn",title:"Build the publish-ready episode from the uploaded cut images",children:ie?"Preparing…":"Prepare episode for publish"}),d.jsx("button",{onClick:Ae,disabled:H,className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"add-text-panel-btn",title:"Insert a narration/title card between art panels — a solid card exported as a final image panel, no drawing needed",children:H?"Adding…":"Add narration/text panel"}),d.jsx("button",{onClick:nt,disabled:ze,className:"px-2 py-0.5 border border-border text-muted rounded hover:border-accent hover:text-accent disabled:opacity-50","data-testid":"refresh-assets-btn",title:"Re-check the story folder for agent-generated images and report each cut's asset state — read only, nothing is uploaded or published",children:ze?"Checking…":"Refresh assets"}),d.jsx("button",{onClick:Bt,disabled:z,className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"sync-clean-btn",children:z?"Syncing...":"Sync clean images"}),d.jsx("button",{onClick:Qe,disabled:ne||!(x!=null&&x.cuts.some(O=>O.finalImagePath&&!O.uploadedCid)),className:"px-2 py-0.5 border border-accent/30 text-accent rounded hover:bg-accent/5 disabled:opacity-50","data-testid":"upload-generate-btn",title:"Upload each cut's final lettered image, then prepare the episode for publishing",children:G||"Upload & Prepare for Publish"})]})]}),d.jsxs("details",{className:"px-3 py-1.5 border-b border-border bg-surface/40 flex-shrink-0","data-testid":"cartoon-workflow-help",children:[d.jsx("summary",{className:"cursor-pointer select-none text-[10px] text-muted hover:text-foreground",children:"Cut workflow help"}),d.jsxs("div",{className:"mt-1.5",children:[d.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[10px] text-muted",children:[d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"1. Letter"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"2. Export"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"3. Upload"}),d.jsx("span",{"aria-hidden":!0,children:"→"}),d.jsx("span",{className:"rounded-full border border-border bg-background px-2 py-0.5 text-foreground",children:"4. Prepare episode for publish"})]}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted",children:["Use ",d.jsx("span",{className:"text-accent",children:"Add narration/text panel"})," ","for a narration or title card. It becomes a solid card exported as a final image."]})]})]}),ft.length>0&&d.jsxs("div",{className:"px-3 py-1.5 border-b border-amber-500/40 bg-amber-500/10 text-[10px] text-amber-700 flex-shrink-0","data-testid":"stale-bubble-export-warning",children:[ft.length===1?"Cut":"Cuts"," ",ft.join(", ")," ",ft.length===1?"was":"were"," lettered with an older speech-bubble style whose tail can show a visible seam. Re-export"," ",ft.length===1?"it":"them"," (open lettering → Export) and re-upload before publishing so the bubble tails are seamless."]}),Je&&dt>0&&Fe.missing===0&&ke.size===0&&d.jsxs("div",{className:"px-3 py-1 border-b border-border bg-green-600/10 text-[10px] text-green-700 flex items-center gap-1 flex-shrink-0","data-testid":"clean-assets-ready",children:[d.jsx("span",{"aria-hidden":!0,children:"✓"}),d.jsxs("span",{children:["All ",dt," clean image",dt===1?"":"s"," ","present — clean-asset generation is complete. Ready for lettering in OWS."]})]}),se&&d.jsx("div",{className:"px-3 py-1 border-b border-border text-[10px] text-muted flex-shrink-0","data-testid":"sync-result",children:se}),pt.length>0&&d.jsxs("div",{className:"px-3 py-2 border-b border-amber-500/40 bg-amber-500/10 text-[11px] flex-shrink-0","data-testid":"convert-artwork",children:[d.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[d.jsxs("span",{className:"font-medium text-amber-700","data-testid":"convert-artwork-count",children:[pt.length," PNG image",pt.length===1?"":"s"," found"]}),d.jsx("button",{onClick:()=>Rt(pt),disabled:M,"data-testid":"convert-all-btn",className:"ml-auto px-2 py-0.5 border border-amber-500/50 text-amber-800 rounded hover:bg-amber-500/20 disabled:opacity-50",children:M?"Converting…":"Convert all to WebP"})]}),d.jsx("p",{className:"mt-1 text-[10px] text-muted",children:"PNG artwork is fine while drafting. Convert it before lettering/export so PlotLink can publish it safely."}),C&&d.jsx("p",{className:"mt-1 text-[10px] text-muted","data-testid":"convert-result",children:C}),Nn.length>0&&d.jsxs("details",{className:"mt-1","data-testid":"convert-technical-details",children:[d.jsx("summary",{className:"text-[10px] text-muted cursor-pointer",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc text-[10px] text-muted",children:Nn.map((O,ce)=>d.jsx("li",{children:O},ce))})]})]}),Ve&&Ve.length>0&&(()=>{const O=eM(Ve),ce=Ve.filter(Ee=>Ee.state==="missing");return d.jsxs("div",{className:"px-3 py-1.5 border-b border-border bg-surface/40 text-[10px] flex-shrink-0","data-testid":"asset-diagnostics",children:[d.jsxs("span",{className:"text-muted","data-testid":"asset-diag-summary",children:["Assets: ",O.uploaded," uploaded · ",O.finalReady," final ·"," ",O.cleanReady," clean · ",O.planned," planned",O.needsConversion>0?` · ${O.needsConversion} needs conversion`:"",O.missing>0?` · ${O.missing} missing`:""]}),ce.length>0&&d.jsx("ul",{className:"mt-1 ml-3 list-disc text-error","data-testid":"asset-diag-issues",children:ce.map(Ee=>d.jsx("li",{children:Ee.issue},Ee.cutId))})]})})(),d.jsx(JD,{checklist:ct,issues:be,onFinish:Qe,finishing:ne,progressText:G,canFinish:Ci,markdownReady:U.markdownReady,published:U.published}),d.jsxs("div",{className:"flex-1 min-h-56 overflow-y-auto p-3 space-y-3","data-testid":"lettering-review-board",children:[x.cuts.map((O,ce)=>{var Ee;return d.jsxs(w.Fragment,{children:[d.jsx(vy,{index:ce,beforeLabel:ce===0?"Episode opening":`After cut ${(Ee=x.cuts[ce-1])==null?void 0:Ee.id}`,afterLabel:`Before cut ${O.id}`,disabled:H,onAdd:()=>Oe(ce)}),d.jsx(rM,{cut:O,storyName:e,plotFile:et,language:s,expanded:I===O.id,onToggle:()=>te(I===O.id?null:O.id),authFetch:i,onUpdated:()=>{Q(),je(),$e()},onOpenEditor:()=>R(O.id),detectedLocalClean:Le.has(O.id),onSyncClean:Bt,syncing:z,onAiDraft:()=>{Wt(O.id,{openEditor:!0})},aiDrafting:K===O.id,staleMessages:ke.get(O.id)??[],onRepairStale:hi,repairing:ge,conversionPng:Fi.get(O.id)??null,onConvert:yt,converting:M,rowRef:De=>{De?mi.current.set(O.id,De):mi.current.delete(O.id)}})]},O.id)}),d.jsx(vy,{index:x.cuts.length,beforeLabel:`After cut ${(oe=x.cuts[x.cuts.length-1])==null?void 0:oe.id}`,afterLabel:"Episode ending",disabled:H,onAdd:()=>Oe(x.cuts.length)})]})]})}function vy({index:e,beforeLabel:t,afterLabel:i,disabled:s,onAdd:a}){return d.jsxs("div",{className:"rounded border border-dashed border-border bg-surface/35 px-3 py-2 text-[11px] text-muted flex items-center gap-3","data-testid":`between-scene-slot-${e}`,children:[d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:"font-medium text-foreground",children:"Between-scene lettering"}),d.jsxs("span",{className:"block truncate",children:[t," · ",i]})]}),d.jsx("button",{type:"button",onClick:a,disabled:s,className:"flex-shrink-0 rounded border border-accent/40 px-2.5 py-1 text-[11px] font-medium text-accent hover:bg-accent/5 disabled:opacity-50","data-testid":`add-between-scene-${e}`,children:"Add card"})]})}function Cm({coach:e,onAction:t,className:i="",showEmptyState:s=!1}){const[a,o]=w.useState(null),c=a!==null&&a===(e==null?void 0:e.prompt);return e===void 0?null:e?d.jsx("div",{className:`m-3 rounded-lg border border-accent/40 bg-accent/10 px-4 py-3 shadow-sm ${i}`,"data-testid":"workflow-coach","data-stage":e.stageLabel,"data-action-kind":e.actionKind,"data-ui-action":e.uiAction??"",children:d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:"inline-flex rounded-full bg-background px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] text-accent","data-testid":"workflow-coach-stage",children:e.stageLabel}),d.jsxs("p",{className:"mt-1 text-sm text-foreground","data-testid":"workflow-coach-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:e.action})]}),c&&d.jsx("p",{className:"mt-1 text-[11px] font-medium text-accent",children:"Prompt copied."})]}),e.actionKind==="agent"&&e.prompt?d.jsx("button",{onClick:()=>{var p;if(!e.prompt)return;const h=e.prompt;(p=navigator.clipboard)==null||p.writeText(h).then(()=>o(h)).catch(()=>{})},"data-testid":"workflow-coach-copy",className:"flex-shrink-0 rounded bg-accent px-4 py-2.5 text-sm font-bold text-white shadow-sm transition-colors hover:bg-accent-dim",children:"Next Action"}):e.actionKind==="ui"&&e.uiAction?d.jsx("button",{onClick:()=>t(e.uiAction,e.episodeFile),"data-testid":"workflow-coach-do",className:"flex-shrink-0 rounded bg-accent px-4 py-2.5 text-sm font-bold text-white shadow-sm transition-colors hover:bg-accent-dim",children:"Next Action"}):null]})}):s?d.jsx("div",{className:`m-3 rounded-lg border border-green-700/25 bg-green-950/5 px-4 py-3 ${i}`,"data-testid":"workflow-coach","data-state":"complete",children:d.jsxs("div",{className:"flex items-start gap-3",children:[d.jsx("span",{className:"rounded-full bg-green-700/10 px-2 py-1 text-[10px] font-bold uppercase tracking-[0.16em] text-green-700",children:"Complete"}),d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsx("p",{className:"text-sm font-semibold text-foreground",children:"No next action available"}),d.jsx("p",{className:"mt-0.5 text-xs text-muted",children:"This workflow has no queued next step right now."})]})]})}):null}function sM({storyName:e,fileName:t,authFetch:i,refreshKey:s=0,onAction:a,showEmptyState:o=!1}){const[c,h]=w.useState(void 0),p=JSON.stringify([e,t??"",s]),[f,_]=w.useState(null);return f!==p&&(h(void 0),_(p)),w.useEffect(()=>{let x=!1;const b=t?`?focus=${encodeURIComponent(t)}`:"";return i(`/api/stories/${e}/progress${b}`).then(v=>v.ok?v.json():null).then(v=>{x||h((v==null?void 0:v.coach)??null)}).catch(()=>{}),()=>{x=!0}},[e,t,i,s]),d.jsx(Cm,{coach:c,onAction:a,showEmptyState:o})}const aM=1024*1024,lM=["image/webp","image/jpeg"],oM="Cover: WebP or JPEG, max 1MB, 600×900 portrait recommended. Use clean cover art — avoid unreadable AI text or broken lettering.";function cM(e){return e.attached?{state:"attached",label:"Cover attached to your story.",tone:"success"}:e.invalid?{state:"invalid",label:"Cover file can't be used — must be WebP or JPEG, max 1MB.",tone:"error"}:e.hasSelectedCover?{state:"selected",label:"Cover selected — it will be uploaded when you publish.",tone:"accent"}:{state:"none",label:"No cover yet — add one before publishing (recommended).",tone:"muted"}}function yy(e){return e.size>aM?"Image exceeds 1MB limit":lM.includes(e.type)?null:"Only WebP and JPEG images are accepted"}async function uM(e,t,i){const s=new FormData;s.append("file",i);const a=await e("/api/publish/upload-cover",{method:"POST",body:s});if(!a.ok)return null;const{cid:o}=await a.json();return!o||!(await e("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:t,coverCid:o})})).ok?null:o}function Pp(e){const t=e.match(/^#\s+(.+)$/m),i=t?t[1].trim():"";return i||null}function hM(e){return e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ")}function Io(e,t){const i=(e??"").trim().toLowerCase();if(!i)return!0;if(t==="genesis.md")return i==="genesis";const s=t.match(/^(plot-\d+)\.md$/);return s?i===s[1].toLowerCase()||/^plot-\d+$/.test(i):!1}function dM(e){const t=e.match(/^plot-(\d+)\.md$/);if(!t)return null;const i=t[1];return`Episode ${i.length<2?i.padStart(2,"0"):i}`}function Ip(e){const t=(e??"").trim();return!!(!t||/^(?:episode|ep|chapter|ch|part|pt|plot)\.?\s*[-–—:#]?\s*\d+$/i.test(t)||/^\d+$/.test(t)||/^plot[-_\s]?\d+$/i.test(t))}function km(e){var s;const t=Pp(e.fileContent);if(t)return!Ip(t);const i=((s=e.episodeTitle)==null?void 0:s.trim())||null;return!!i&&!Ip(i)}function Em(e){const{fileName:t,fileContent:i,storySlug:s,structureContent:a,contentType:o,episodeTitle:c}=e,h=Pp(i);if(t==="genesis.md"){const p=a?Pp(a):null;return(h??p??hM(s)).slice(0,60)}if(h)return h.slice(0,60);if(o==="cartoon"){const p=c==null?void 0:c.trim(),f=dM(t);return((p||f)??t.replace(/\.md$/,"")).slice(0,60)}return t.replace(/\.md$/,"").slice(0,60)}function fM(e){return!!(e!=null&&e.txHash)&&(e==null?void 0:e.plotIndex)!=null&&e.plotIndex>0}function pM(e){return fM(e)&&(e==null?void 0:e.status)!=="published-not-indexed"}function Sy(e,t,i){if(e[t]==="cartoon"&&!i)return"cartoon"}function mM(e,t,i){return!(e!=="cartoon"||t||!i||i.startsWith("_new_"))}function Of(e,t,i){if(e)return t[e]||i.get(e)||"fiction"}function zf(e){if(!e)return null;const t=Number(e);return Number.isFinite(t)?(t/1e18).toFixed(6):null}function gM(e){return!!e&&e.ready===!1}function xM(e){const t=zf(e.requiredBalance)??zf(e.creationFee),i=zf(e.ethBalance);return e.hasEnoughEth===!1&&t&&i?`Insufficient ETH: need at least ${t} ETH to publish; current balance is ${i} ETH.`+(e.address?` Top up the OWS wallet (${e.address}) and try again.`:" Top up the OWS wallet and try again."):e.error||"Publish preflight failed — the OWS wallet isn't ready to publish."}const _M={...gl,attributes:{...gl.attributes,img:["src","alt","title"]}},bM="https://ipfs.filebase.io/ipfs/";function vM(e){const t=[],i=/!\[([^\]]*)\]\(([^)]+)\)/g;let s;for(;(s=i.exec(e))!==null;)t.push({full:s[0],alt:s[1],url:s[2]});return t}function yM(e){const t=vM(e),i=[];for(const a of t)a.url.startsWith(bM)||i.push(`Non-IPFS image URL: ${a.url.length>60?a.url.slice(0,60)+"...":a.url}`);return e.match(/!\[[^\]]*\]\([^)]*$|!\[[^\]]*$(?!\])/gm)&&i.push("Malformed image markdown detected — check brackets and parentheses"),{count:t.length,warnings:i}}function SM({storyName:e,fileName:t,authFetch:i,onPublish:s,publishingFile:a,walletAddress:o,contentType:c="fiction",language:h,genre:p,isNsfw:f,hasGenesis:_=!1,onViewProgress:x,onOpenFile:b,onViewPublish:v,focusedLetteringMode:S=!1,focusedLetteringWorkspaceVisible:j=!1,onFocusedLetteringModeChange:D,onFocusedLetteringWorkspaceVisibleChange:E}){const[N,I]=w.useState(null),[te,q]=w.useState(!1),[R,ie]=w.useState("preview"),[fe,be]=w.useState("publish"),[B,ne]=w.useState("text"),[F,G]=w.useState(null),Y=w.useCallback((re,ye)=>{ie("edit"),G(Ce=>({cutId:re,openEditor:ye,seq:((Ce==null?void 0:Ce.seq)??0)+1}))},[]),[U,A]=w.useState(""),[z,$]=w.useState(!1),[ge,T]=w.useState(!1),[M,V]=w.useState(!1),[C,X]=w.useState(null),[se,le]=w.useState(""),[K,he]=w.useState(""),[_e,Me]=w.useState(!1),[Le,He]=w.useState(null),[ke,Ue]=w.useState(0),[Je,at]=w.useState(0),[Ve,Et]=w.useState(null),[ze,_t]=w.useState(null),[Te,Kt]=w.useState(null),[mi,wt]=w.useState(0),et=w.useRef(null),Q=w.useRef(!1),[xe,je]=w.useState(!1),[$e,nt]=w.useState(dl[0]),[Wt,ui]=w.useState(ts[0]),[Bt,yt]=w.useState(!1),[Rt,Qe]=w.useState(null),[hi,H]=w.useState(null),[Se,Oe]=w.useState(!1),[Ae,Ge]=w.useState(!1),[Fe,dt]=w.useState(!1),[ft,ct]=w.useState(null),[Vt,Ci]=w.useState(!1),pt=w.useRef(null),Fi=w.useRef(null),[Nn,ln]=w.useState(!1),[Un,on]=w.useState(null),[xn,cn]=w.useState(null),[pr,Lt]=w.useState("unknown"),oe=w.useRef(!1),[O,ce]=w.useState(!1),[Ee,De]=w.useState(!1),[Ne,Pe]=w.useState(null),[We,rt]=w.useState([]),[Xe,Nt]=w.useState(null),jt=w.useRef(null),Gt=w.useRef(null),Dt=w.useCallback(async()=>{if(!e||!t){I(null);return}const re=`${e}/${t}`,ye=Gt.current!==re;ye&&(Gt.current=re);try{const Ce=await i(`/api/stories/${e}/${t}`);if(Ce.ok){const tt=await Ce.json();I(tt),(ye||!Q.current)&&(A(tt.content??""),ye&&(T(!1),Q.current=!1))}}catch{}},[e,t,i]);w.useEffect(()=>{q(!0),Dt().finally(()=>q(!1))},[Dt]),w.useEffect(()=>{if(!e||!t||R==="edit"&&ge)return;const re=setInterval(Dt,3e3);return()=>clearInterval(re)},[e,t,Dt,R,ge]);const[ki,mr]=w.useState(null),Jt=c==="cartoon"&&t==="genesis.md";w.useEffect(()=>{if(!Jt||!e){mr(null);return}let re=!1;return i(`/api/stories/${e}/cuts/genesis`).then(ye=>ye.ok?ye.json():null).then(ye=>{re||mr(ye?Op(ye.cuts||[]):null)}).catch(()=>{re||mr(null)}),()=>{re=!0}},[Jt,e,i]);const qi=c==="cartoon"&&!!t&&/^plot-\d+\.md$/.test(t);w.useEffect(()=>{if(!qi||!e||!t){He(null),Ue(0),at(0),Et(null);return}let re=!1;const ye=t.replace(/\.md$/,"");return Et(null),(async()=>{try{const[Ce,tt]=await Promise.all([i(`/api/stories/${e}/${t}`),i(`/api/stories/${e}/cuts/${ye}`)]);if(re)return;if(!tt.ok){He("error"),Ue(0),at(0),Et(null);return}const Pt=await tt.json(),Ni=Pt.cuts||[],Gn=Ce.ok?(await Ce.json()).content??"":"",or=VS(Gn,Ni);re||(He(or.stage),Ue(or.awaitingCount),at(or.totalCuts),Et(Op(Ni)),Kt(typeof Pt.title=="string"?Pt.title:null))}catch{re||(He("error"),Ue(0),at(0),Et(null))}})(),()=>{re=!0}},[qi,e,t,i,N==null?void 0:N.content,N==null?void 0:N.status,mi]),w.useEffect(()=>{if(!e){_t(null);return}let re=!1;return i(`/api/stories/${e}/structure.md`).then(ye=>ye.ok?ye.json():null).then(ye=>{re||_t((ye==null?void 0:ye.content)??null)}).catch(()=>{}),()=>{re=!0}},[e,i]),w.useEffect(()=>{if(!e)return;const re=Cu(p);let ye=re??"";if(!re&&ze){const tt=ze.match(/\*{0,2}genre\*{0,2}[:\s]+(.+)/i);tt&&(ye=Cu(tt[1].replace(/\*+/g,"").trim())??"")}le(ye);let Ce=h&&ts.find(tt=>tt.toLowerCase()===h.toLowerCase())||"";if(!Ce&&ze){const tt=ze.match(/\*{0,2}language\*{0,2}[:\s]+(.+)/i);tt&&(Ce=ts.find(Pt=>Pt.toLowerCase()===tt[1].replace(/\*+/g,"").trim().toLowerCase())||"")}he(Ce),Me(f??!1)},[e,p,h,f,ze]);const $n=w.useCallback(re=>{e&&i(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(re)}).catch(()=>{})},[e,i]),gr=w.useCallback(async()=>{if(!(!e||!t)){$(!0);try{(await i(`/api/stories/${e}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:U})})).ok&&(T(!1),Q.current=!1,I(ye=>ye&&{...ye,content:U}))}catch{}$(!1)}},[e,t,i,U]),ei=w.useCallback(async()=>{if(!e||!t)return;const re=t.replace(/\.md$/,"");try{(await i(`/api/stories/${e}/cuts/${re}/generate-markdown`,{method:"POST"})).ok&&(await Dt(),wt(Ce=>Ce+1))}catch{}},[e,t,i,Dt]),Br=w.useCallback((re,ye)=>{if(re==="view-progress"){x==null||x();return}if(ye&&ye!==t){b==null||b(ye);return}switch(re){case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":ie("edit"),ne("cuts");break;case"generate-markdown":ei();break;case"publish":ie("preview");break}},[t,x,b,ei]),Fn=w.useCallback(re=>{var tt;const ye=(tt=re.target.files)==null?void 0:tt[0];if(!ye)return;oe.current=!0,on(null),cn(null);const Ce=yy(ye);if(Ce){Qe(null),H(Pt=>(Pt&&URL.revokeObjectURL(Pt),null)),pt.current&&(pt.current.value=""),ct(Ce),Lt("invalid");return}Qe(ye),H(Pt=>(Pt&&URL.revokeObjectURL(Pt),URL.createObjectURL(ye))),ct(null),Lt("selected")},[]),ar=w.useCallback(async re=>{var Ce;const ye=(Ce=re.target.files)==null?void 0:Ce[0];if(Fi.current&&(Fi.current.value=""),!(!ye||!e)){oe.current=!0,on(null),ln(!0),ct(null);try{let tt;try{tt=await Vu(ye)}catch(vr){Qe(null),H(Yi=>(Yi&&URL.revokeObjectURL(Yi),null)),ct(vr instanceof Error?vr.message:"Could not import image");return}const Pt=tt.type==="image/jpeg"?"jpg":"webp",Ni=new File([tt],`cover.${Pt}`,{type:tt.type}),Gn=new FormData;Gn.append("file",Ni);const or=await i(`/api/stories/${e}/import-cover`,{method:"POST",body:Gn});if(!or.ok){const vr=await or.json().catch(()=>({}));ct(vr.error||"Cover import failed");return}Qe(Ni),H(vr=>(vr&&URL.revokeObjectURL(vr),URL.createObjectURL(Ni))),cn(null),Lt("selected"),ct(null)}catch{ct("Cover import failed")}finally{ln(!1)}}},[e,i]),Wi=w.useCallback(async re=>{if(re.size>1024*1024){Pe("Image exceeds 1MB limit");return}if(!["image/webp","image/jpeg"].includes(re.type)){Pe("Only WebP and JPEG images are accepted");return}De(!0),Pe(null);try{const Ce=new FormData;Ce.append("file",re);const tt=await i("/api/publish/upload-plot-image",{method:"POST",body:Ce});if(!tt.ok){const Ni=await tt.json();throw new Error(Ni.error||"Upload failed")}const Pt=await tt.json();rt(Ni=>[...Ni,{cid:Pt.cid,url:Pt.url}])}catch(Ce){Pe(Ce instanceof Error?Ce.message:"Upload failed")}finally{De(!1),jt.current&&(jt.current.value="")}},[i]),Ct=w.useCallback(re=>{var Ce;const ye=(Ce=re.target.files)==null?void 0:Ce[0];ye&&Wi(ye)},[Wi]),qn=w.useCallback(async()=>{if(N!=null&&N.storylineId){Oe(!0),ct(null),Ci(!1);try{let re;if(Rt){const Ce=new FormData;Ce.append("file",Rt);const tt=await i("/api/publish/upload-cover",{method:"POST",body:Ce});if(!tt.ok){const Ni=await tt.json();throw new Error(Ni.error||"Cover upload failed")}re=(await tt.json()).cid}const ye=await i("/api/publish/update-storyline",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storylineId:N.storylineId,...re!==void 0&&{coverCid:re},genre:$e,language:Wt,isNsfw:Bt})});if(!ye.ok){const Ce=await ye.json();throw new Error(Ce.error||"Update failed")}Ci(!0),Qe(null),re!==void 0&&(dt(!0),H(Ce=>(Ce&&URL.revokeObjectURL(Ce),null)),Lt("unknown"),pt.current&&(pt.current.value="")),setTimeout(()=>Ci(!1),3e3)}catch(re){ct(re instanceof Error?re.message:"Update failed")}finally{Oe(!1)}}},[N==null?void 0:N.storylineId,Rt,$e,Wt,Bt,i]);w.useEffect(()=>{je(!1),Qe(null),H(null),ct(null),Ci(!1),Ge(!1),ce(!1),rt([]),Pe(null),on(null),cn(null),Lt("unknown"),oe.current=!1,ne("text")},[e,t]),w.useEffect(()=>{if(t!=="genesis.md"||!e||!N||N.storylineId||N.status==="published"||N.status==="published-not-indexed"||oe.current)return;let re=!1;return(async()=>{try{const ye=await i(`/api/stories/${e}/cover-asset`);if(re||!ye.ok)return;const Ce=await ye.json();if(re)return;if(!(Ce!=null&&Ce.found)){Lt("none");return}if(!Ce.valid){cn(Ce.error||"Detected cover asset is invalid and was not used"),Lt("invalid");return}const tt=await i(`/api/stories/${e}/asset/${Ce.path.replace(/^assets\//,"")}`);if(re||!tt.ok)return;const Pt=await tt.blob(),Ni=new File([Pt],Ce.path.split("/").pop()||"cover.webp",{type:Ce.type});if(yy(Ni)||re||oe.current)return;Qe(Ni),H(Gn=>(Gn&&URL.revokeObjectURL(Gn),URL.createObjectURL(Ni))),on(Ce.path),Lt("detected")}catch{}})(),()=>{re=!0}},[e,t,N,N==null?void 0:N.status,N==null?void 0:N.storylineId,i]),w.useEffect(()=>{if(!xe||!(N!=null&&N.storylineId))return;Ge(!1);const re="https://plotlink.xyz";let ye=!1;return fetch(`${re}/api/storyline/${N.storylineId}`).then(Ce=>Ce.ok?Ce.json():null).then(Ce=>{if(!ye){if(!Ce){ct("Could not load current story metadata");return}if(Ce.genre){const tt=Cu(Ce.genre);tt&&nt(tt)}if(Ce.language){const tt=ts.find(Pt=>Pt.toLowerCase()===Ce.language.toLowerCase());tt&&ui(tt)}Ce.isNsfw!==void 0&&yt(!!Ce.isNsfw),dt(!!(Ce.coverCid||Ce.coverUrl||Ce.cover)),Ge(!0)}}).catch(()=>{ye||ct("Could not load current story metadata")}),()=>{ye=!0}},[xe,N==null?void 0:N.storylineId]),w.useEffect(()=>{if(R!=="edit")return;const re=ye=>{(ye.metaKey||ye.ctrlKey)&&ye.key==="s"&&(ye.preventDefault(),gr())};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[R,gr]),w.useEffect(()=>{if((N==null?void 0:N.status)!=="published-not-indexed"||!N.publishedAt)return;const re=new Date(N.publishedAt).getTime(),ye=300*1e3,Ce=()=>{const Pt=Math.max(0,ye-(Date.now()-re));X(Pt)};Ce();const tt=setInterval(Ce,1e3);return()=>clearInterval(tt)},[N==null?void 0:N.status,N==null?void 0:N.publishedAt]);const ya=C!==null&&C<=0,Lr=C!==null&&C>0?`${Math.floor(C/6e4)}:${String(Math.floor(C%6e4/1e3)).padStart(2,"0")}`:null;if(!e||!t)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:d.jsxs("div",{className:"text-center",children:[d.jsx("p",{className:"text-lg font-serif",children:"Select a file to preview"}),d.jsx("p",{className:"text-sm mt-1",children:"Click a story file in the sidebar"})]})});if(te&&!N)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted",children:"Loading..."});const xr=(R==="edit"?U:(N==null?void 0:N.content)??"").length,Ei=t==="genesis.md",gi=t?/^plot-\d+\.md$/.test(t):!1,Gi=c==="cartoon"&&gi,jn=c==="cartoon"&&Ei,Or=jn||Gi,Tn=(N==null?void 0:N.status)==="published"||(N==null?void 0:N.status)==="published-not-indexed",Sa=S&&Or,yl=jn?ki?ki.total:null:Gi?Le===null?null:Je:null,_r=hD({fileName:t??"",contentType:c,hasGenesis:_,isPublished:Tn,cutCount:yl,cutProgress:jn?ki:null}),Ko=(jn||Gi)&&!Tn,as=Ko?Em({fileName:t,fileContent:(N==null?void 0:N.content)??"",storySlug:e??"",structureContent:ze,contentType:"cartoon",episodeTitle:Te}):null,wa=!!as&&Io(as,t),Ca=Gi&&!Tn&&!km({fileContent:(N==null?void 0:N.content)??"",episodeTitle:Te}),qs=jn&&!Tn?ym((N==null?void 0:N.content)??""):null,Vo=!!qs&&qs.blockers.length>0,ka="w-full max-w-[32rem] rounded-xl border px-3 py-3",lr={muted:"text-muted",accent:"text-accent",error:"text-error",success:"text-green-700"},Ea=re=>{if(!jn)return null;const ye=cM({hasSelectedCover:!!Rt,invalid:pr==="invalid",attached:re});return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"cartoon-cover-status","data-state":ye.state,children:[d.jsx("span",{className:`text-[11px] font-medium ${lr[ye.tone]}`,children:ye.label}),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cover-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Cover tips"}),d.jsx("span",{className:"block mt-0.5","data-testid":"cartoon-cover-guidance",children:oM})]})]})},Ws=wa||Ca,ls=()=>{if(!Ko||!as)return null;const re=Ei?"Story title":"Episode title";return d.jsxs("div",{className:"flex flex-col gap-0.5","data-testid":"publish-title-preview","data-raw":wa?"true":"false","data-blocked":Ws?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[re,":"]})," ",d.jsx("span",{className:Ws?"text-error font-medium":"text-foreground",children:as})]}),wa?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename."," ",Ei?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," ","before publishing."]}):Ca?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",as,"” is a generic placeholder, not a reader-facing title, so it can’t be published. Set a real episode title in the cut plan (or add a “# Title” to the episode) — e.g. “Episode 01 — The Couple Coupon” — before publishing."]}):null]})},os=()=>qs?d.jsxs("div",{className:"flex flex-col gap-1 rounded border border-border bg-surface/50 p-2","data-testid":"cartoon-genesis-readiness","data-blocked":Vo?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.jsx("span",{className:"text-[10px] text-muted","data-testid":"genesis-readiness-hint",children:"Genesis is the first thing readers see. Write it as the story opening/prologue, not a synopsis — set up the premise and stakes, then bridge into Episode 01."}),qs.blockers.map((re,ye)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:re},`b-${ye}`)),qs.warnings.map((re,ye)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:re},`w-${ye}`))]}):null,cs=Ei||gi?1e4:null,us=!Tn&&cs!==null&&xr>cs,Xo=(N==null?void 0:N.content)??"",br=Tn?{count:0,warnings:[]}:yM(Xo),Wn=d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden","data-testid":"prose-editor-shell",style:{background:"var(--paper-bg)"},children:[d.jsx("textarea",{ref:et,value:U,onChange:re=>{A(re.target.value),T(!0),Q.current=!0},className:"flex-1 min-h-0 w-full resize-none px-4 py-3 text-sm leading-relaxed focus:outline-none",style:{fontFamily:'"Geist Mono", ui-monospace, monospace',background:"var(--paper-bg)",color:"var(--text)"},spellCheck:!1,"data-testid":"prose-editor-textarea"}),d.jsxs("div",{className:"shrink-0 px-3 py-1.5 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"prose-editor-savebar",children:[d.jsx("span",{className:"text-xs text-muted",children:ge?"Unsaved changes":"No changes"}),d.jsx("button",{onClick:gr,disabled:!ge||z,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:z?"Saving...":"Save"})]})]});return d.jsxs("div",{className:"h-full min-h-0 flex flex-col",children:[!Sa&&d.jsxs("div",{className:"border-b border-border",children:[d.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs font-mono text-muted",children:[x&&d.jsx("button",{onClick:x,"data-testid":"view-progress-btn",className:"text-accent hover:underline font-sans",title:"Story progress overview",children:"← Progress"}),d.jsxs("span",{children:[e,"/",t]}),(N==null?void 0:N.status)==="published"&&d.jsx("span",{className:"text-green-700 font-medium",children:"Published"}),(N==null?void 0:N.status)==="published-not-indexed"&&d.jsx("span",{className:"text-amber-700 font-medium",title:N.indexError,children:"Published (not indexed)"}),(N==null?void 0:N.status)==="pending"&&d.jsx("span",{className:"text-amber-700 font-medium",children:"Pending"})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("span",{className:`text-xs font-mono ${us?"text-error font-medium":"text-muted"}`,children:[xr.toLocaleString(),cs!==null?`/${cs.toLocaleString()}`:" chars"]}),us&&d.jsxs("span",{className:"text-error text-xs font-medium",children:[(xr-cs).toLocaleString()," over limit"]})]})]}),d.jsxs("div",{className:"flex px-3 gap-1",children:[d.jsx("button",{onClick:()=>ie("preview"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${R==="preview"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:"Preview"}),d.jsxs("button",{onClick:()=>ie("edit"),className:`px-3 py-1 text-xs font-medium border-b-2 transition-colors ${R==="edit"?"border-accent text-accent":"border-transparent text-muted hover:text-foreground"}`,children:["Edit",ge&&d.jsx("span",{className:"ml-1 text-amber-600",children:"*"})]})]})]}),!Sa&&c==="cartoon"&&e&&t&&d.jsx(sM,{storyName:e,fileName:t,authFetch:i,refreshKey:mi,onAction:Br,showEmptyState:!0}),R==="preview"?Gi?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"cartoon-mode-publish",onClick:()=>be("publish"),className:`px-2 py-0.5 text-[11px] rounded ${fe==="publish"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Publish Preview"}),d.jsx("button",{"data-testid":"cartoon-mode-inspect",onClick:()=>be("inspect"),className:`px-2 py-0.5 text-[11px] rounded ${fe==="inspect"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cut Inspector"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:fe==="publish"?d.jsx(mD,{content:(N==null?void 0:N.content)??"",stage:Le}):d.jsx(Q3,{storyName:e,fileName:t,authFetch:i,onEditCut:Y})})]}):d.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4",style:{background:"var(--paper-bg)"},children:N!=null&&N.content?d.jsx("div",{className:"prose max-w-none",children:d.jsx(lS,{remarkPlugins:[cS,MS],rehypePlugins:[[zS,_M]],children:N.content})}):d.jsx("p",{className:"text-muted italic",children:"No content"})}):Gi?d.jsx("div",{className:"flex-1 min-h-[22rem] overflow-hidden",style:{background:"var(--paper-bg)"},children:d.jsx(by,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>wt(re=>re+1),focusRequest:F,onFocusHandled:()=>G(null),onFocusedLetteringModeChange:D,workspaceVisible:j,onWorkspaceVisibleChange:E})}):jn?d.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",style:{background:"var(--paper-bg)"},children:[d.jsxs("div",{className:"flex gap-1 px-3 py-1 border-b border-border",children:[d.jsx("button",{"data-testid":"genesis-edit-mode-text",onClick:()=>ne("text"),className:`px-2 py-0.5 text-[11px] rounded ${B==="text"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Opening text"}),d.jsx("button",{"data-testid":"genesis-edit-mode-cuts",onClick:()=>ne("cuts"),className:`px-2 py-0.5 text-[11px] rounded ${B==="cuts"?"bg-accent text-white":"text-muted hover:text-foreground"}`,children:"Cuts"})]}),d.jsx("div",{className:"flex-1 min-h-0",children:B==="cuts"?d.jsx(by,{storyName:e,fileName:t,authFetch:i,language:h,onCutsChanged:()=>wt(re=>re+1),focusRequest:F,onFocusHandled:()=>G(null),onFocusedLetteringModeChange:D,workspaceVisible:j,onWorkspaceVisibleChange:E}):Wn})]}):Wn,!Sa&&d.jsx("div",{className:"shrink-0 px-3 py-2 border-t border-border flex items-center justify-between bg-surface/95","data-testid":"preview-panel-footer",children:t==="structure.md"?d.jsx("p",{className:"text-muted text-xs italic","data-testid":"footer-guidance",children:_r}):(N==null?void 0:N.status)==="published-not-indexed"?d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-amber-700",children:"Published on-chain but not indexed on PlotLink"}),!ya&&d.jsx("button",{onClick:async()=>{if(!(!e||!t||!N.txHash)){V(!0);try{(await(await i("/api/publish/retry-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:e,fileName:t,txHash:N.txHash,content:N.content,storylineId:N.storylineId})})).json()).ok&&(await i(`/api/stories/${e}/${t}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:N.txHash,storylineId:N.storylineId,contentCid:"",gasCost:""})}),Dt())}catch{}V(!1)}},disabled:M,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:M?"Retrying...":`Retry Index${Lr?` (${Lr})`:""}`}),gi&&d.jsx("button",{onClick:()=>{!e||!t||!window.confirm(`This episode is already on-chain — try “Retry Index” first. Retry Publish creates a NEW on-chain transaction and a SECOND, permanent chapter on PlotLink (PlotLink content is immutable). Only do this if the chapter never appeared after indexing. -Create a new on-chain chapter anyway?`)||s==null||s(e,t,ne,Y,_e)},disabled:!!a,"data-testid":"retry-publish-btn",className:"px-3 py-1 border border-border text-xs rounded hover:bg-surface disabled:opacity-50",children:a===t?"Publishing...":"Retry Publish"}),N.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${N.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),d.jsx("p",{className:"text-muted text-xs",children:ya?gi?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":gi?"Try Retry Index first (available for 5 min after publish). If that fails, Retry Publish creates a new on-chain tx.":"Retry Index is available for 5 min after publish."}),N.indexError&&d.jsx("p",{className:"text-error text-xs",children:N.indexError})]}):(N==null?void 0:N.status)==="published"?d.jsxs("div",{className:"flex flex-col gap-2",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-green-700",children:"Published"}),N.storylineId&&d.jsx("a",{href:(()=>{var ke;const re=`https://plotlink.xyz/story/${N.storylineId}`;if(!gi)return re;const ye=N.plotIndex!=null&&N.plotIndex>0?N.plotIndex:parseInt(((ke=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:ke[1])??"1");return`${re}/${ye}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),N.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${N.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),Ei&&o&&N.storylineId&&(!N.authorAddress||N.authorAddress.toLowerCase()===o.toLowerCase())&&d.jsx("button",{onClick:()=>Te(re=>!re),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:ge?"Close Edit":"Edit Story"})]}),ge&&Ei&&N.storylineId&&d.jsxs("div",{className:"border border-border rounded p-3 flex flex-col gap-3 bg-surface",children:[d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Cover Image"}),Ea($e),d.jsxs("div",{className:"flex items-start gap-3",children:[hi&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:hi,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{Ze(null),P(null),cn(null),Lt("unknown"),ft.current&&(ft.current.value="")},className:"absolute -top-1.5 -right-1.5 w-4 h-4 bg-error text-white rounded-full text-xs flex items-center justify-center",children:"x"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:ft,type:"file",accept:"image/webp,image/jpeg",onChange:Fn,className:"text-xs","data-testid":"cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"})]})]})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("select",{value:Ue,onChange:re=>it(re.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:dl.map(re=>d.jsx("option",{value:re,children:re},re))}),d.jsx("select",{value:Wt,onChange:re=>ui(re.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:ts.map(re=>d.jsx("option",{value:re,children:re},re))})]}),d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Bt,onChange:re=>vt(re.target.checked),className:"rounded border-border"}),"This story contains adult content (18+)"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:qn,disabled:we||!Re,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:we?"Saving...":Re?"Save Changes":"Loading..."}),Vt&&d.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),dt&&d.jsx("span",{className:"text-error text-xs",children:dt})]})]})]}):d.jsxs("div",{className:"flex flex-col gap-2",children:[Gi&&We&&We.total>0&&d.jsxs("div",{className:"flex items-center flex-wrap gap-x-3 gap-y-0.5 text-[10px] text-muted","data-testid":"cartoon-status-summary",children:[d.jsxs("span",{children:["Cuts:"," ",d.jsx("span",{className:"text-foreground font-medium",children:We.total})]}),d.jsxs("span",{children:["Clean:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[We.withClean,"/",We.needClean]})]}),d.jsxs("span",{children:["Lettered:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[We.withText,"/",We.total]})]}),d.jsxs("span",{children:["Uploaded:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[We.uploaded,"/",We.total]})]}),x&&d.jsx("button",{onClick:x,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),Nn&&ki&&d.jsxs("div",{className:"text-xs text-muted","data-testid":"genesis-cuts-summary",children:["Episode 1 (Genesis) cuts: ",ki.total," planned",ki.total>0&&d.jsxs(d.Fragment,{children:[" ","· ",ki.withClean," clean ·"," ",ki.withText," lettered ·"," ",ki.exported," exported ·"," ",ki.uploaded," uploaded"]})]}),(Nn||Gi)&&_r&&d.jsxs("div",{className:`${ka} flex flex-col gap-1 border-border bg-surface/50`,"data-testid":"cartoon-not-started",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted",children:yl===0?"Not started":"Next step"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:Nn?"Genesis (Episode 1)":"Future episode"})]}),d.jsx("span",{className:"text-xs text-muted",children:_r})]}),gi&&!Gi&&D==="preview"&&d.jsxs("div",{children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:L,onChange:re=>oe(re.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),L&&d.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[d.jsxs("div",{className:"border-2 border-dashed border-border rounded p-3 flex flex-col items-center gap-1.5 cursor-pointer hover:border-accent transition-colors",onClick:()=>{var re;return(re=Nt.current)==null?void 0:re.click()},onDragOver:re=>{re.preventDefault(),re.stopPropagation()},onDrop:re=>{var ke;re.preventDefault(),re.stopPropagation();const ye=(ke=re.dataTransfer.files)==null?void 0:ke[0];ye&&Wi(ye)},children:[d.jsx("input",{ref:Nt,type:"file",accept:"image/webp,image/jpeg",onChange:Ct,className:"hidden"}),d.jsx("span",{className:"text-xs text-muted",children:Ee?"Uploading...":"Drop image here or click to browse"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),Ne&&d.jsx("span",{className:"text-error text-xs",children:Ne}),qe.map((re,ye)=>d.jsxs("div",{className:"border border-border rounded p-2 flex flex-col gap-1 bg-surface",children:[d.jsx("span",{className:"text-xs text-green-700",children:"Image uploaded! Copy the markdown below and paste it where you want the illustration to appear in your plot:"}),d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsxs("code",{className:"flex-1 text-xs bg-background px-2 py-1 rounded font-mono break-all",children:["![Scene description](",re.url,")"]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${re.url})`),Et(ye),setTimeout(()=>Et(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:Ve===ye?"Copied!":"Copy"})]})]},re.cid))]})]}),Ei&&c!=="cartoon"&&!(D==="edit"&&H==="cuts")&&d.jsxs("div",{className:"flex flex-col gap-1.5","data-testid":"prepublish-cover",children:[d.jsxs("span",{className:"text-xs font-medium text-foreground",children:["Cover Image"," ",d.jsx("span",{className:"text-muted font-normal",children:"(optional)"})]}),Ea(!1),d.jsxs("div",{className:"flex items-start gap-3",children:[hi&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:hi,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{le.current=!0,on(null),cn(null),Lt("unknown"),Ze(null),P(re=>(re&&URL.revokeObjectURL(re),null)),ft.current&&(ft.current.value="")},className:"absolute -top-1.5 -right-1.5 w-4 h-4 bg-error text-white rounded-full text-xs flex items-center justify-center",children:"x"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:ft,type:"file",accept:"image/webp,image/jpeg",onChange:Fn,className:"text-xs","data-testid":"prepublish-cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"}),d.jsx("input",{ref:Fi,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:ar,className:"hidden","data-testid":"prepublish-cover-import-input"}),d.jsx("button",{type:"button",onClick:()=>{var re;return(re=Fi.current)==null?void 0:re.click()},disabled:En,className:"self-start px-2 py-1 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50","data-testid":"prepublish-cover-import",children:En?"Importing…":"Import generated image (PNG ok)"}),At&&d.jsx("span",{className:"text-green-700 text-xs","data-testid":"prepublish-cover-will-upload",children:"This cover will be uploaded as the PlotLink storyline cover when you publish."}),Un&&d.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",Un," — pick a file to override."]}),gn&&d.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[gn," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&pr==="none"&&!At&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"prepublish-cover-none",children:["No generated cover detected. Create"," ",d.jsx("span",{className:"font-mono",children:"assets/cover.webp"})," ","or use “Import generated image” — it will be uploaded as the PlotLink storyline cover when you publish."]}),dt&&d.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:dt})]})]})]}),!Or&&ls(),!Or&&os(),!Or&&d.jsxs("div",{className:"flex items-center gap-2",children:[Ei&&c!=="cartoon"&&d.jsxs(d.Fragment,{children:[d.jsxs("select",{value:ne,"data-testid":"publish-genre-select",onChange:re=>{ae(re.target.value),re.target.value&&$n({genre:re.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${ne?"border-border":"border-amber-500"}`,children:[!ne&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),dl.map(re=>d.jsx("option",{value:re,children:re},re))]}),d.jsxs("select",{value:Y,"data-testid":"publish-language-select",onChange:re=>{he(re.target.value),re.target.value&&$n({language:re.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${Y?"border-border":"border-amber-500"}`,children:[!Y&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),ts.map(re=>d.jsx("option",{value:re,children:re},re))]})]}),d.jsx("button",{onClick:async()=>{if(!e||!t)return;if(br.count>0){const ye=`This plot contains ${br.count} illustration(s). Content is immutable after publishing — image references cannot be changed or removed. +Create a new on-chain chapter anyway?`)||s==null||s(e,t,se,K,_e)},disabled:!!a,"data-testid":"retry-publish-btn",className:"px-3 py-1 border border-border text-xs rounded hover:bg-surface disabled:opacity-50",children:a===t?"Publishing...":"Retry Publish"}),N.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${N.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"})]}),d.jsx("p",{className:"text-muted text-xs",children:ya?gi?"Index window expired. Use Retry Publish to create a new on-chain tx.":"Index window expired. Contact support or re-publish manually.":gi?"Try Retry Index first (available for 5 min after publish). If that fails, Retry Publish creates a new on-chain tx.":"Retry Index is available for 5 min after publish."}),N.indexError&&d.jsx("p",{className:"text-error text-xs",children:N.indexError})]}):(N==null?void 0:N.status)==="published"?d.jsxs("div",{className:"flex flex-col gap-2",children:[d.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:"text-green-700",children:"Published"}),N.storylineId&&d.jsx("a",{href:(()=>{var Ce;const re=`https://plotlink.xyz/story/${N.storylineId}`;if(!gi)return re;const ye=N.plotIndex!=null&&N.plotIndex>0?N.plotIndex:parseInt(((Ce=t==null?void 0:t.match(/^plot-(\d+)\.md$/))==null?void 0:Ce[1])??"1");return`${re}/${ye}`})(),target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"View on PlotLink"}),N.txHash&&d.jsx("a",{href:`https://basescan.org/tx/${N.txHash}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted underline",children:"BaseScan"}),Ei&&o&&N.storylineId&&(!N.authorAddress||N.authorAddress.toLowerCase()===o.toLowerCase())&&d.jsx("button",{onClick:()=>je(re=>!re),className:"px-2 py-0.5 border border-border text-xs rounded hover:bg-surface",children:xe?"Close Edit":"Edit Story"})]}),xe&&Ei&&N.storylineId&&d.jsxs("div",{className:"border border-border rounded p-3 flex flex-col gap-3 bg-surface",children:[d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Cover Image"}),Ea(Fe),d.jsxs("div",{className:"flex items-start gap-3",children:[hi&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:hi,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{Qe(null),H(null),cn(null),Lt("unknown"),pt.current&&(pt.current.value="")},className:"absolute -top-1.5 -right-1.5 w-4 h-4 bg-error text-white rounded-full text-xs flex items-center justify-center",children:"x"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:pt,type:"file",accept:"image/webp,image/jpeg",onChange:Fn,className:"text-xs","data-testid":"cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"})]})]})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("select",{value:$e,onChange:re=>nt(re.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:dl.map(re=>d.jsx("option",{value:re,children:re},re))}),d.jsx("select",{value:Wt,onChange:re=>ui(re.target.value),className:"px-2 py-1.5 text-xs border border-border rounded bg-surface text-foreground",children:ts.map(re=>d.jsx("option",{value:re,children:re},re))})]}),d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:Bt,onChange:re=>yt(re.target.checked),className:"rounded border-border"}),"This story contains adult content (18+)"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:qn,disabled:Se||!Ae,className:"px-3 py-1 bg-accent text-white text-xs rounded hover:bg-accent-dim disabled:opacity-50",children:Se?"Saving...":Ae?"Save Changes":"Loading..."}),Vt&&d.jsx("span",{className:"text-green-700 text-xs",children:"Updated!"}),ft&&d.jsx("span",{className:"text-error text-xs",children:ft})]})]})]}):d.jsxs("div",{className:"flex flex-col gap-2",children:[Gi&&Ve&&Ve.total>0&&d.jsxs("div",{className:"flex items-center flex-wrap gap-x-3 gap-y-0.5 text-[10px] text-muted","data-testid":"cartoon-status-summary",children:[d.jsxs("span",{children:["Cuts:"," ",d.jsx("span",{className:"text-foreground font-medium",children:Ve.total})]}),d.jsxs("span",{children:["Clean:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Ve.withClean,"/",Ve.needClean]})]}),d.jsxs("span",{children:["Lettered:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Ve.withText,"/",Ve.total]})]}),d.jsxs("span",{children:["Uploaded:"," ",d.jsxs("span",{className:"text-foreground font-medium",children:[Ve.uploaded,"/",Ve.total]})]}),x&&d.jsx("button",{onClick:x,className:"ml-auto text-accent hover:underline","data-testid":"status-view-progress",children:"View progress →"})]}),jn&&ki&&d.jsxs("div",{className:"text-xs text-muted","data-testid":"genesis-cuts-summary",children:["Episode 1 (Genesis) cuts: ",ki.total," planned",ki.total>0&&d.jsxs(d.Fragment,{children:[" ","· ",ki.withClean," clean ·"," ",ki.withText," lettered ·"," ",ki.exported," exported ·"," ",ki.uploaded," uploaded"]})]}),(jn||Gi)&&_r&&d.jsxs("div",{className:`${ka} flex flex-col gap-1 border-border bg-surface/50`,"data-testid":"cartoon-not-started",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-background px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted",children:yl===0?"Not started":"Next step"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:jn?"Genesis (Episode 1)":"Future episode"})]}),d.jsx("span",{className:"text-xs text-muted",children:_r})]}),gi&&!Gi&&R==="preview"&&d.jsxs("div",{children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:O,onChange:re=>ce(re.target.checked),className:"rounded border-border"}),"Add illustrations in the plot"]}),O&&d.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[d.jsxs("div",{className:"border-2 border-dashed border-border rounded p-3 flex flex-col items-center gap-1.5 cursor-pointer hover:border-accent transition-colors",onClick:()=>{var re;return(re=jt.current)==null?void 0:re.click()},onDragOver:re=>{re.preventDefault(),re.stopPropagation()},onDrop:re=>{var Ce;re.preventDefault(),re.stopPropagation();const ye=(Ce=re.dataTransfer.files)==null?void 0:Ce[0];ye&&Wi(ye)},children:[d.jsx("input",{ref:jt,type:"file",accept:"image/webp,image/jpeg",onChange:Ct,className:"hidden"}),d.jsx("span",{className:"text-xs text-muted",children:Ee?"Uploading...":"Drop image here or click to browse"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB"})]}),Ne&&d.jsx("span",{className:"text-error text-xs",children:Ne}),We.map((re,ye)=>d.jsxs("div",{className:"border border-border rounded p-2 flex flex-col gap-1 bg-surface",children:[d.jsx("span",{className:"text-xs text-green-700",children:"Image uploaded! Copy the markdown below and paste it where you want the illustration to appear in your plot:"}),d.jsxs("div",{className:"flex items-center gap-1.5",children:[d.jsxs("code",{className:"flex-1 text-xs bg-background px-2 py-1 rounded font-mono break-all",children:["![Scene description](",re.url,")"]}),d.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`![Scene description](${re.url})`),Nt(ye),setTimeout(()=>Nt(null),2e3)},className:"px-2 py-1 text-xs border border-border rounded hover:bg-surface shrink-0",children:Xe===ye?"Copied!":"Copy"})]})]},re.cid))]})]}),Ei&&c!=="cartoon"&&!(R==="edit"&&B==="cuts")&&d.jsxs("div",{className:"flex flex-col gap-1.5","data-testid":"prepublish-cover",children:[d.jsxs("span",{className:"text-xs font-medium text-foreground",children:["Cover Image"," ",d.jsx("span",{className:"text-muted font-normal",children:"(optional)"})]}),Ea(!1),d.jsxs("div",{className:"flex items-start gap-3",children:[hi&&d.jsxs("div",{className:"relative",children:[d.jsx("img",{src:hi,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsx("button",{onClick:()=>{oe.current=!0,on(null),cn(null),Lt("unknown"),Qe(null),H(re=>(re&&URL.revokeObjectURL(re),null)),pt.current&&(pt.current.value="")},className:"absolute -top-1.5 -right-1.5 w-4 h-4 bg-error text-white rounded-full text-xs flex items-center justify-center",children:"x"})]}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("input",{ref:pt,type:"file",accept:"image/webp,image/jpeg",onChange:Fn,className:"text-xs","data-testid":"prepublish-cover-input"}),d.jsx("span",{className:"text-xs text-muted",children:"WebP/JPEG, max 1MB, 600x900px recommended"}),d.jsx("input",{ref:Fi,type:"file",accept:"image/png,image/webp,image/jpeg",onChange:ar,className:"hidden","data-testid":"prepublish-cover-import-input"}),d.jsx("button",{type:"button",onClick:()=>{var re;return(re=Fi.current)==null?void 0:re.click()},disabled:Nn,className:"self-start px-2 py-1 text-xs border border-border rounded hover:border-accent hover:bg-accent/5 disabled:opacity-50","data-testid":"prepublish-cover-import",children:Nn?"Importing…":"Import generated image (PNG ok)"}),Rt&&d.jsx("span",{className:"text-green-700 text-xs","data-testid":"prepublish-cover-will-upload",children:"This cover will be uploaded as the PlotLink storyline cover when you publish."}),Un&&d.jsxs("span",{className:"text-accent text-xs","data-testid":"prepublish-cover-detected",children:["Auto-detected generated cover ",Un," — pick a file to override."]}),xn&&d.jsxs("span",{className:"text-amber-700 text-xs","data-testid":"prepublish-cover-detected-warning",children:[xn," Use “Import generated image” below to convert/compress it, or pick a file."]}),c==="cartoon"&&pr==="none"&&!Rt&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"prepublish-cover-none",children:["No generated cover detected. Create"," ",d.jsx("span",{className:"font-mono",children:"assets/cover.webp"})," ","or use “Import generated image” — it will be uploaded as the PlotLink storyline cover when you publish."]}),ft&&d.jsx("span",{className:"text-error text-xs","data-testid":"prepublish-cover-error",children:ft})]})]})]}),!Or&&ls(),!Or&&os(),!Or&&d.jsxs("div",{className:"flex items-center gap-2",children:[Ei&&c!=="cartoon"&&d.jsxs(d.Fragment,{children:[d.jsxs("select",{value:se,"data-testid":"publish-genre-select",onChange:re=>{le(re.target.value),re.target.value&&$n({genre:re.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${se?"border-border":"border-amber-500"}`,children:[!se&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select genre"}),dl.map(re=>d.jsx("option",{value:re,children:re},re))]}),d.jsxs("select",{value:K,"data-testid":"publish-language-select",onChange:re=>{he(re.target.value),re.target.value&&$n({language:re.target.value})},className:`px-2 py-1.5 text-xs border rounded bg-surface text-foreground ${K?"border-border":"border-amber-500"}`,children:[!K&&d.jsx("option",{value:"",disabled:!0,children:"Needs metadata — select language"}),ts.map(re=>d.jsx("option",{value:re,children:re},re))]})]}),d.jsx("button",{onClick:async()=>{if(!e||!t)return;if(br.count>0){const ye=`This plot contains ${br.count} illustration(s). Content is immutable after publishing — image references cannot be changed or removed. Please verify illustrations appear correctly in Preview before continuing. -Publish now?`;if(!window.confirm(ye))return}const re=Ei?At:null;re?await(s==null?void 0:s(e,t,ne,Y,_e,re))&&(le.current=!0,on(null),cn(null),Lt("unknown"),Ze(null),P(ke=>(ke&&URL.revokeObjectURL(ke),null)),ft.current&&(ft.current.value="")):s==null||s(e,t,ne,Y,_e)},disabled:!!a||us||Ws||Yo||Ei&&(!ne||!Y)||Gi&&Le!=="ready",className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:a===t?"Publishing...":"Publish to PlotLink"}),Ei&&c==="cartoon"&&(!ne||!Y)&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"cartoon-metadata-needs-story-info",children:"Set the genre and language in Story Info before publishing"}),Ei&&c!=="cartoon"&&!ne&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),Ei&&c!=="cartoon"&&ne&&!Y&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),us&&d.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),Gi&&Le==="error"&&d.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),Gi&&Le==="planning"&&d.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),Gi&&Le==="awaiting-upload"&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:["Upload all final images, then “Prepare episode for publish” — ",be," of ",St," ","still need an uploaded image"]})]}),Or&&d.jsx("button",{onClick:()=>v==null?void 0:v(),"data-testid":"cartoon-review-publish",className:"self-start rounded border border-accent/40 px-3 py-1 text-xs text-accent hover:bg-accent/5 transition-colors",children:"Review publish checklist →"}),br.warnings.length>0&&d.jsx("div",{className:"flex flex-col gap-0.5",children:br.warnings.map((re,ye)=>d.jsx("span",{className:"text-amber-600 text-xs",children:re},ye))}),Ei&&c!=="cartoon"&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:_e,onChange:re=>{Be(re.target.checked),$n({isNsfw:re.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),_e&&d.jsx("span",{className:"text-xs text-amber-600",children:"Adult content will be hidden from the default browse view."})]})]})})]})}function yM(e){if(e.cover!=="present")return e.cover==="invalid"?"Replace the cover image - it must be a valid WebP or JPEG.":"Add a cover image before publishing.";const t=[];return e.metadata.language||t.push("language"),e.metadata.genre||t.push("genre"),e.metadata.title||t.push("title"),`Add the story ${t.join(" and ")||"details"} before publishing.`}function ZS(e){const t=e.coach??null,i=e.metadata,s=e.setup.hasStructure,a=e.setup.hasGenesis,o=e.cover==="present",c=!i.title||!i.language||!i.genre,h=e.episodes.find(f=>!f.published)??null,p=!!h&&h.state!=="ready";return s?a?c?"story-info":p&&(t!=null&&t.episodeFile)?t.episodeFile:o?(t==null?void 0:t.episodeFile)??null:"story-info":"genesis.md":"whitepaper"}function SM({progress:e,onOpenStoryInfo:t}){return d.jsx("div",{className:"m-3 rounded-lg border border-accent/40 bg-accent/10 px-4 py-3 shadow-sm","data-testid":"story-info-cta",children:d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:"inline-flex rounded-full bg-background px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"Story info"}),d.jsxs("p",{className:"mt-1 text-sm text-foreground","data-testid":"story-info-next-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:yM(e)})]})]}),d.jsx("button",{type:"button",onClick:t,disabled:!t,className:"flex-shrink-0 rounded bg-accent px-4 py-2.5 text-sm font-bold text-white shadow-sm transition-colors hover:bg-accent-dim disabled:cursor-not-allowed disabled:opacity-50","data-testid":"story-info-next-action-btn",children:"Next Action"})]})})}function QS({progress:e,onCoachAction:t,onOpenStoryInfo:i}){return ZS(e)==="story-info"?d.jsx(SM,{progress:e,onOpenStoryInfo:i}):d.jsx(Sm,{coach:e.coach??null,showEmptyState:!0,onAction:t})}function wM({storyName:e,authFetch:t,refreshKey:i=0,onCoachAction:s,onOpenStoryInfo:a}){const[o,c]=w.useState(void 0),h=JSON.stringify([e,i]),[p,f]=w.useState(null);return p!==h&&(c(void 0),f(h)),w.useEffect(()=>{let _=!1;return t(`/api/stories/${e}/progress`).then(x=>x.ok?x.json():null).then(x=>{_||c(CM(x)?x:null)}).catch(()=>{_||c(null)}),()=>{_=!0}},[e,t,i]),o===void 0?null:o?d.jsx(QS,{progress:o,onCoachAction:s,onOpenStoryInfo:a}):d.jsx(Sm,{coach:null,showEmptyState:!0,onAction:s})}function CM(e){return!!e&&!!e.metadata&&!!e.setup&&Array.isArray(e.episodes)}function kM({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,refreshKey:a=0}){const[o,c]=w.useState(null),[h,p]=w.useState(!0);return w.useEffect(()=>{let f=!1;return(async()=>{p(!0);try{const x=await t(`/api/stories/${e}/progress`),b=x.ok?await x.json():null;f||(c(b),p(!1))}catch{f||(c(null),p(!1))}})(),()=>{f=!0}},[e,t,a]),h?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"progress-loading",children:"Loading progress…"}):!o||!o.metadata||!Array.isArray(o.episodes)?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story progress."}):o.contentType==="cartoon"?d.jsx(DM,{progress:o,storyName:e,onOpenFile:i,onOpenStoryInfo:s}):d.jsx(LM,{progress:o,storyName:e,onOpenFile:i})}function mu({label:e,value:t,tone:i="muted"}){const s=i==="ok"?"text-green-700":i==="warn"?"text-amber-700":"text-muted";return d.jsxs("span",{className:"text-[11px]",children:[d.jsxs("span",{className:"text-muted",children:[e,": "]}),d.jsx("span",{className:`font-medium ${s}`,children:t})]})}function JS({progress:e}){const t=e.contentType==="cartoon",i=e.cover==="present"?"ok":e.cover==="invalid"?"warn":"muted";return d.jsxs("div",{className:"px-4 py-3 border-b border-border",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h2",{className:"text-base font-serif text-foreground truncate",children:e.metadata.title||e.name}),d.jsx("span",{className:`rounded px-1.5 py-0.5 text-[10px] font-medium ${t?"bg-accent/10 text-accent":"bg-surface text-muted"}`,children:t?"Cartoon":"Fiction"})]}),d.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[d.jsx(mu,{label:"Language",value:e.metadata.language||"Needs metadata",tone:e.metadata.language?"muted":"warn"}),d.jsx(mu,{label:"Genre",value:e.metadata.genre||"Needs metadata",tone:e.metadata.genre?"muted":"warn"}),e.metadata.isNsfw!=null&&d.jsx(mu,{label:"Adult",value:e.metadata.isNsfw?"Yes (18+)":"No"}),t&&d.jsx(mu,{label:"Cover",value:e.cover==="present"?"Ready":e.cover==="invalid"?"Invalid":"Missing",tone:i})]})]})}const e1={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},Ou={published:"text-green-700",done:"text-green-700",current:"text-accent","needs-action":"text-amber-700","not-started":"text-muted"},t1={published:"Published",done:"Complete",current:"Current","needs-action":"Needs action","not-started":"Not started"},EM={done:"✓",current:"◓",todo:"○"},NM={done:"text-green-700",current:"text-accent",todo:"text-muted"};function i1({item:e}){return d.jsxs("div",{className:"flex items-baseline gap-2 text-[11px]","data-testid":"checklist-item","data-status":e.status,children:[d.jsx("span",{className:`${NM[e.status]} flex-shrink-0`,"aria-hidden":!0,children:EM[e.status]}),d.jsx("span",{className:e.status==="todo"?"text-muted":"text-foreground",children:e.label}),e.detail&&d.jsxs("span",{className:"text-muted",children:["· ",e.detail]})]})}function vy({index:e,title:t,status:i,items:s,fileName:a,openFile:o}){const c=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${Ou[i]}`,"aria-hidden":!0,children:e1[i]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",t]}),a&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:a}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${Ou[i]} flex-shrink-0`,children:t1[i]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":i,children:[o?d.jsx("button",{onClick:o,className:"w-full text-left rounded hover:bg-surface -mx-1 px-1 py-0.5","data-testid":`section-open-${e}`,children:c}):c,d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:s.map((h,p)=>d.jsx(i1,{item:h},p))})]})}function jM(e,t){return e.published?"published":t?"current":e.state==="placeholder"?"not-started":(e.state==="blocked","needs-action")}function TM(e,t=!0){const i=e.checklist??[],s=[];if(e.kind==="genesis"&&s.push({label:"Opening text",status:t?"done":"todo"}),i.length===0)return s.push({label:"Cut plan",status:"todo"}),s.push({label:"Clean artwork",status:"todo"}),s;for(const a of i)s.push(AM(a));return s}function AM(e){return{label:e.label,status:e.status,detail:e.detail}}const RM={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function DM({progress:e,storyName:t,onOpenFile:i,onOpenStoryInfo:s}){const a=e.metadata,o=e.setup.hasStructure,c=e.cover==="present",p=!a.title||!a.language||!a.genre||!c,f=ZS(e),_=d.jsx(QS,{progress:e,onOpenStoryInfo:s,onCoachAction:(E,N)=>{E!=="view-progress"&&N&&i(t,N)}}),x=[{label:"Public title",status:a.title?"done":"todo",detail:a.title??null},{label:"Language",status:a.language?"done":"todo",detail:a.language??null},{label:"Genre",status:a.genre?"done":"todo",detail:a.genre??null},{label:"Cover image",status:c?"done":"todo",detail:e.cover==="invalid"?"Invalid — re-import":c?null:"Missing"}],b=f==="story-info"?"current":p?"needs-action":"done",v=o?"done":f==="whitepaper"?"current":"not-started",S=e.episodes.find(E=>E.kind==="genesis")??null,j=e.episodes.filter(E=>E.kind==="plot");let R=0;return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(JS,{progress:e}),d.jsx("div",{className:"border-b border-border","data-testid":"persistent-next-action",children:_}),d.jsx("p",{className:"px-4 pt-3 pb-1 text-[11px] font-medium text-muted uppercase tracking-wider",children:"Production Progress"}),d.jsx(vy,{index:++R,title:"Define Story Info",status:b,items:x}),d.jsx(vy,{index:++R,title:"Story Whitepaper",status:v,fileName:"structure.md",openFile:o?()=>i(t,"structure.md"):void 0,items:[{label:"Planning document",status:o?"done":"todo",detail:o?null:"Not written yet"}]}),S?d.jsx(zf,{index:++R,ep:S,isActive:f===S.file,storyName:t,onOpenFile:i}):d.jsx(zf,{index:++R,ep:RM,isActive:f==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i}),j.map(E=>d.jsx(zf,{index:++R,ep:E,isActive:f===E.file,storyName:t,onOpenFile:i},E.file)),d.jsxs("div",{className:"px-4 py-2 text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[d.jsxs("span",{children:[e.summary.published," published"]}),d.jsxs("span",{children:[e.summary.readyToPublish," ready"]}),e.summary.placeholders>0&&d.jsxs("span",{children:[e.summary.placeholders," not started"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function zf({index:e,ep:t,isActive:i,storyName:s,onOpenFile:a,openingDone:o=!0,canOpen:c=!0}){const h=jM(t,i),p=TM(t,o),f=t.title?`${t.label} · ${t.title}`:t.label,_=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${Ou[h]}`,"aria-hidden":!0,children:e1[h]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",f]}),d.jsx("span",{className:"text-[10px] text-muted truncate",children:t.file}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${Ou[h]} flex-shrink-0`,children:t1[h]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":h,children:[c?d.jsx("button",{onClick:()=>a(s,t.file),"data-testid":`progress-episode-${t.file}`,"data-state":t.state,className:"w-full text-left rounded hover:bg-surface -mx-1 px-1 py-0.5",children:_}):d.jsx("div",{"data-state":t.state,children:_}),d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:p.map((x,b)=>d.jsx(i1,{item:x},b))})]})}const MM={published:"✓",ready:"●","in-progress":"◐",planning:"○",placeholder:"○",blocked:"✕",draft:"○"},yy={published:"text-green-700",ready:"text-green-700","in-progress":"text-accent",planning:"text-accent",placeholder:"text-muted",blocked:"text-error",draft:"text-muted"},BM={published:"Published",ready:"Ready","in-progress":"In progress",planning:"Planning",placeholder:"Not started",blocked:"Needs fixes",draft:"Draft"};function LM({progress:e,storyName:t,onOpenFile:i}){const[s,a]=w.useState(!1);return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(JS,{progress:e}),e.nextAction&&d.jsxs("div",{className:"px-4 py-2 border-b border-accent/30 bg-accent/5 text-xs space-y-1.5","data-testid":"progress-next-action",children:[d.jsxs("div",{children:[d.jsx("span",{className:"font-medium text-foreground",children:"Next: "}),d.jsx("span",{className:"text-muted",children:e.nextAction})]}),e.nextPrompt&&d.jsxs("div",{className:"flex items-start gap-1.5","data-testid":"progress-next-prompt",children:[d.jsx("code",{className:"flex-1 rounded border border-border bg-surface px-1.5 py-1 text-[10px] text-foreground break-words",children:e.nextPrompt}),d.jsx("button",{onClick:()=>{var o;e.nextPrompt&&((o=navigator.clipboard)==null||o.writeText(e.nextPrompt).then(()=>{a(!0)}).catch(()=>{}))},"data-testid":"copy-next-prompt",className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors flex-shrink-0",children:s?"Copied!":"Copy"})]})]}),d.jsxs("div",{className:"px-4 py-2 border-b border-border flex flex-col gap-1",children:[d.jsx(Sy,{done:e.setup.hasStructure,label:"Story bible (structure.md)",onClick:e.setup.hasStructure?()=>i(t,"structure.md"):void 0}),d.jsx(Sy,{done:e.setup.hasGenesis,label:"Genesis written",onClick:e.setup.hasGenesis?()=>i(t,"genesis.md"):void 0})]}),d.jsxs("div",{className:"px-4 py-2",children:[d.jsx("p",{className:"text-[11px] font-medium text-muted uppercase tracking-wider mb-1.5",children:"Chapters"}),e.episodes.length===0?d.jsx("p",{className:"text-xs text-muted italic","data-testid":"progress-no-episodes",children:"No chapters yet — write the Genesis to start."}):d.jsx("ol",{className:"flex flex-col gap-1",children:e.episodes.map(o=>d.jsx("li",{children:d.jsxs("button",{onClick:()=>i(t,o.file),"data-testid":`progress-episode-${o.file}`,"data-state":o.state,className:"w-full text-left flex items-start gap-2 rounded px-2 py-1.5 hover:bg-surface",children:[d.jsx("span",{className:`mt-0.5 ${yy[o.state]}`,"aria-hidden":!0,children:MM[o.state]}),d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:o.label}),o.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",o.title]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${yy[o.state]}`,children:BM[o.state]})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:o.summary})]})]})},o.file))})]}),d.jsxs("div",{className:"px-4 py-2 border-t border-border text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[d.jsxs("span",{children:[e.summary.published," published"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Sy({done:e,label:t,onClick:i}){const s=d.jsxs("span",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:e?"text-green-700":"text-muted","aria-hidden":!0,children:e?"✓":"○"}),d.jsx("span",{className:e?"text-foreground":"text-muted",children:t})]});return i?d.jsx("button",{onClick:i,className:"text-left hover:underline",children:s}):d.jsx("div",{children:s})}const OM=[{key:"progress",label:"Progress"},{key:"story-info",label:"Story Info"},{key:"whitepaper",label:"Whitepaper"},{key:"genesis",label:"Genesis / Ep 1"},{key:"episodes",label:"Episodes"},{key:"publish",label:"Publish"}];function zM({storyTitle:e,active:t,onSelect:i}){return d.jsxs("div",{className:"flex-shrink-0 border-b border-border bg-surface/40","data-testid":"cartoon-workflow-nav",children:[d.jsxs("div",{className:"flex items-center gap-2 px-3 pt-2",children:[d.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.14em] text-accent",children:"Cartoon"}),d.jsx("span",{className:"text-xs font-serif text-foreground truncate",children:e})]}),d.jsx("div",{className:"flex items-center gap-1 px-2 py-1.5 overflow-x-auto",role:"tablist",children:OM.map(s=>{const a=s.key===t;return d.jsx("button",{role:"tab","aria-selected":a,"data-testid":`nav-tab-${s.key}`,"data-active":a,onClick:()=>i(s.key),className:`flex-shrink-0 rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors ${a?"bg-accent text-white":"text-muted hover:text-foreground hover:bg-surface"}`,children:s.label},s.key)})})]})}function PM({storyName:e,authFetch:t,onSaved:i}){const[s,a]=w.useState(!0),[o,c]=w.useState(!1),[h,p]=w.useState(""),[f,_]=w.useState(""),[x,b]=w.useState(""),[v,S]=w.useState(""),[j,R]=w.useState(!1),[E,N]=w.useState("cartoon"),[I,te]=w.useState("unknown"),[F,D]=w.useState(!1),[ie,fe]=w.useState(!1),[Se,H]=w.useState(null),[ce,W]=w.useState(!1),[K,X]=w.useState(null),[U,A]=w.useState(!1),O=w.useRef(null);w.useEffect(()=>{let C=!1;return a(!0),c(!1),fe(!1),H(null),(async()=>{try{const[V,ne]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!V.ok){C||(c(!0),a(!1));return}const ae=await V.json(),Y=ne.ok?await ne.json().catch(()=>null):null;if(C)return;p(ae.title??""),_(ae.description??""),b(Cu(ae.genre)??""),S(ae.language&&ts.find(he=>he.toLowerCase()===ae.language.toLowerCase())||""),R(!!ae.isNsfw),N(ae.contentType==="fiction"?"fiction":"cartoon"),te((Y==null?void 0:Y.cover)??"unknown"),a(!1)}catch{C||(c(!0),a(!1))}})(),()=>{C=!0}},[e,t]);const $=w.useCallback(async()=>{D(!0),fe(!1),H(null);const C={title:h.trim(),description:f.trim(),genre:x,language:v,isNsfw:j};try{const V=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(V.ok)fe(!0),i==null||i({genre:x,language:v,isNsfw:j});else{const ne=await V.json().catch(()=>({}));H(ne.error||"Could not save story info.")}}catch{H("Could not save story info.")}D(!1)},[e,t,h,f,x,v,j,i]),xe=w.useCallback(async C=>{var ne;const V=(ne=C.target.files)==null?void 0:ne[0];if(O.current&&(O.current.value=""),!!V){W(!0),H(null);try{let ae;try{ae=await Ku(V)}catch(Le){H(Le instanceof Error?Le.message:"Could not import image");return}const Y=ae.type==="image/jpeg"?"jpg":"webp",he=new File([ae],`cover.${Y}`,{type:ae.type}),_e=new FormData;_e.append("file",he);const Be=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:_e});if(!Be.ok){const Le=await Be.json().catch(()=>({}));H(Le.error||"Cover import failed.");return}te("present"),X(Le=>(Le&&URL.revokeObjectURL(Le),URL.createObjectURL(he)))}catch{H("Cover import failed.")}finally{W(!1)}}},[e,t]),T=w.useCallback(()=>{var V;const C=`Generate a cover image for this story (${h||e}) and save it as assets/cover.webp — portrait 600x900, WebP, under 1MB. Don't publish.`;(V=navigator.clipboard)==null||V.writeText(C).then(()=>{A(!0)}).catch(()=>{})},[h,e]);if(s)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"story-info-loading",children:"Loading story info…"});if(o)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story info."});const M=I==="present"?"Cover set":I==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",G=I==="present"?"text-green-700":I==="invalid"?"text-amber-700":"text-muted";return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"story-info-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Story Info"}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"These details appear on PlotLink when the story is published."}),d.jsxs("div",{className:"mt-4 flex flex-col gap-4 max-w-xl",children:[d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Public title"}),d.jsx("input",{type:"text",value:h,onChange:C=>{p(C.target.value),fe(!1)},"data-testid":"story-info-title",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Short description"}),d.jsx("textarea",{value:f,onChange:C=>{_(C.target.value),fe(!1)},rows:3,"data-testid":"story-info-description",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none resize-y"})]}),d.jsxs("div",{className:"flex flex-wrap gap-4",children:[d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Genre"}),d.jsxs("select",{value:x,onChange:C=>{b(C.target.value),fe(!1)},"data-testid":"story-info-genre",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[d.jsx("option",{value:"",children:"Needs metadata"}),dl.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Language"}),d.jsxs("select",{value:v,onChange:C=>{S(C.target.value),fe(!1)},"data-testid":"story-info-language",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[d.jsx("option",{value:"",children:"Needs metadata"}),ts.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Content type"}),d.jsx("span",{className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-surface text-muted","data-testid":"story-info-content-type",title:"Content type is locked after creation.",children:E==="cartoon"?"Cartoon · locked":"Fiction · locked"})]})]}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Cover image"}),d.jsxs("div",{className:"flex items-start gap-3",children:[K&&d.jsx("img",{src:K,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:`text-[11px] font-medium ${G}`,"data-testid":"story-info-cover-status",children:M}),d.jsx("span",{className:"text-[10px] text-muted",children:"WebP or JPEG, max 1MB, 600×900 recommended."}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{type:"button",onClick:()=>{var C;return(C=O.current)==null?void 0:C.click()},disabled:ce,"data-testid":"story-info-import-cover",className:"rounded border border-border px-2.5 py-1 text-[11px] text-foreground hover:border-accent hover:text-accent transition-colors disabled:opacity-50",children:ce?"Importing…":"Import cover"}),d.jsx("button",{type:"button",onClick:T,"data-testid":"story-info-cover-prompt",className:"rounded border border-border px-2.5 py-1 text-[11px] text-muted hover:border-accent hover:text-accent transition-colors",children:U?"Copied!":"Ask agent for cover prompt"})]}),d.jsx("input",{ref:O,type:"file",accept:"image/*",onChange:xe,className:"hidden"})]})]})]}),d.jsxs("label",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"checkbox",checked:j,onChange:C=>{R(C.target.checked),fe(!1)},"data-testid":"story-info-nsfw"}),d.jsx("span",{className:"text-xs text-foreground",children:"This story contains adult content (18+)"})]}),d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{type:"button",onClick:$,disabled:F,"data-testid":"story-info-save",className:"rounded bg-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-dim transition-colors disabled:opacity-50",children:F?"Saving…":"Save Story Info"}),ie&&d.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),Se&&d.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:Se})]})]})]})}function IM({storyName:e,authFetch:t,onOpenFile:i}){const[s,a]=w.useState(null),[o,c]=w.useState(!0);return w.useEffect(()=>{let h=!1;return(async()=>{c(!0);try{const f=await t(`/api/stories/${e}/progress`),_=f.ok?await f.json():null;h||(a(Array.isArray(_==null?void 0:_.episodes)?_.episodes:null),c(!1))}catch{h||(a(null),c(!1))}})(),()=>{h=!0}},[e,t]),o?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"episodes-loading",children:"Loading episodes…"}):s?d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"episodes-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Episodes"}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Genesis is Episode 1; each plot file is the next episode."}),s.length===0?d.jsx("p",{className:"mt-4 text-xs text-muted italic","data-testid":"episodes-empty",children:"No episodes yet — write the Genesis to start Episode 1."}):d.jsx("ol",{className:"mt-3 flex flex-col gap-1",children:s.map(h=>d.jsx("li",{children:d.jsx("button",{onClick:()=>i(e,h.file),"data-testid":`episodes-row-${h.file}`,"data-state":h.state,className:"w-full text-left flex items-start gap-2 rounded px-2 py-1.5 hover:bg-surface",children:d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:h.label}),h.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",h.title]}),d.jsx("span",{className:"ml-auto text-[10px] text-muted",children:h.file})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:h.summary})]})})},h.file))})]}):d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load episodes."})}function HM({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,onPublish:a,publishingFile:o,genre:c,language:h,isNsfw:p,refreshKey:f=0}){var We,Mt;const[_,x]=w.useState(null),[b,v]=w.useState(!0),[S,j]=w.useState(!1),[R,E]=w.useState(null),[N,I]=w.useState(null),[te,F]=w.useState(null),[D,ie]=w.useState(null),[fe,Se]=w.useState(null),H=async()=>{try{const He=await t(`/api/stories/${e}/cover-asset`),xt=He.ok?await He.json():null;if(!(xt!=null&&xt.found)||!xt.valid||!xt.path)return null;const Ae=await t(`/api/stories/${e}/asset/${String(xt.path).replace(/^assets\//,"")}`);if(!Ae.ok)return null;const Kt=await Ae.blob();return new File([Kt],String(xt.path).split("/").pop()||"cover.webp",{type:xt.type||Kt.type})}catch{return null}};w.useEffect(()=>{let He=!1;return(async()=>{v(!0),j(!1);try{const Ae=await t(`/api/stories/${e}/progress`),Kt=Ae.ok?await Ae.json():null;if(He)return;!Kt||!Array.isArray(Kt.episodes)?(j(!0),x(null)):x(Kt),v(!1)}catch{He||(j(!0),x(null),v(!1))}})(),()=>{He=!0}},[e,t,f]);const ce=((Mt=(We=_==null?void 0:_.episodes)==null?void 0:We.find(He=>!He.published))==null?void 0:Mt.file)??null,W=ce==="genesis.md",K=JSON.stringify([ce??"",f]),[X,U]=w.useState(null);if(X!==K&&(U(K),I(null),F(null),ie(null),Se(null)),w.useEffect(()=>{if(!ce)return;let He=!1;const xt=ce.replace(/\.md$/,"");return(async()=>{var Ae;try{const Kt=[t(`/api/stories/${e}/${ce}`),t(`/api/stories/${e}/cuts/${xt}`)];W&&Kt.push(t(`/api/stories/${e}/structure.md`));const[mi,wt,Qe]=await Promise.all(Kt);if(He)return;if(I(mi.ok?(await mi.json()).content??"":""),wt.ok){const Q=await wt.json();if(He)return;F(Array.isArray(Q.cuts)?Q.cuts:[]),ie(typeof Q.title=="string"?Q.title:null)}else F(null),ie(null);Se(W&&Qe&&Qe.ok?((Ae=await Qe.json())==null?void 0:Ae.content)??null:null)}catch{He||(I(""),F(null),ie(null),Se(null))}})(),()=>{He=!0}},[ce,W,e,t,f]),b)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"publish-page-loading",children:"Loading publish readiness…"});if(S||!_)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load publish readiness."});const A=_.episodes.find(He=>!He.published);if(!A)return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Publish"}),d.jsx("p",{className:"mt-2 text-xs text-green-700","data-testid":"publish-all-done",children:_.episodes.length>0?"All episodes are published to PlotLink. Plan the next episode to continue.":"No episodes yet — write the Genesis (Episode 1) to begin."})]});const O=A.cuts,$=_.cover==="present",xe=[{label:"Opening text ready",status:"done"},{label:"Cut plan",status:O&&O.total>0?"done":"todo",detail:O?`${O.total} cut${O.total===1?"":"s"} planned`:"not started"},{label:"Clean images converted",status:O&&O.needClean>0&&O.withClean===O.needClean?"done":"todo",detail:O?`${O.withClean} / ${O.needClean}`:null},{label:"Cuts lettered",status:O&&O.total>0&&O.withText===O.total?"done":"todo",detail:O?`${O.withText} / ${O.total}`:null},{label:"Final images exported",status:O&&O.total>0&&O.exported===O.total?"done":"todo",detail:O?`${O.exported} / ${O.total}`:null},{label:"Final images uploaded",status:O&&O.total>0&&O.uploaded===O.total?"done":"todo",detail:O?`${O.uploaded} / ${O.total}`:null},{label:"Cover image",status:$?"done":"todo",detail:$?null:"recommended before publishing"},{label:"Publish to PlotLink",status:A.published?"done":"todo"}],T=A.state==="ready",M=A.state==="blocked",G=A.file==="genesis.md",C=!G||!!c&&!!h,V=!!o&&o===A.file,ne=N!==null,ae=ne?Cm({fileName:A.file,fileContent:N??"",storySlug:e,structureContent:fe,contentType:"cartoon",episodeTitle:D}):null,Y=!!ae&&zo(ae,A.file),he=!G&&ne&&!wm({fileContent:N??"",episodeTitle:D}),_e=Y||he,Be=G&&ne?bm(N??""):null,Le=!!Be&&Be.blockers.length>0,je=!G&&ne&&te!==null?WS(N??"",te):null,be=je&&je.stage==="error"?je.issues:[],St=T&&C&&(ne&&(G||te!==null))&&!_e&&!Le&&!V&&!!a,ot=async()=>{if(!(!St||!a)){E(null);try{const He=G?await H():null;await a(e,A.file,c??"",h??"",!!p,He)}catch{E("Publish could not be started. Please try again.")}}};return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsxs("h2",{className:"text-base font-serif text-foreground",children:["Publish ",A.label]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Finalize this episode: convert, letter, export, upload, then publish to PlotLink."}),d.jsx("ul",{className:"mt-3 flex flex-col gap-1.5 max-w-xl","data-testid":"publish-checklist",children:xe.map((He,xt)=>d.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":He.status,children:[d.jsx("span",{className:`flex-shrink-0 ${He.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:He.status==="done"?"✓":"○"}),d.jsx("span",{className:He.status==="done"?"text-foreground":"text-muted",children:He.label}),He.detail&&d.jsxs("span",{className:"text-muted",children:["· ",He.detail]})]},xt))}),ae&&d.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":Y?"true":"false","data-blocked":_e?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[G?"Story title":"Episode title",":"]})," ",d.jsx("span",{className:_e?"text-error font-medium":"text-foreground",children:ae})]}),Y?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",G?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):he?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",ae,"” is a generic placeholder, not a reader-facing title, so it can’t be published. Set a real episode title in the cut plan (or add a “# Title” to the episode) — e.g. “Episode 01 — The Couple Coupon” — before publishing."]}):null]}),Be&&d.jsxs("div",{className:"mt-4 flex flex-col gap-1 rounded border border-border bg-surface/50 p-2 max-w-xl","data-testid":"cartoon-genesis-readiness","data-blocked":Le?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.jsx("span",{className:"text-[10px] text-muted","data-testid":"genesis-readiness-hint",children:"Genesis is the first thing readers see. Write it as the story opening/prologue, not a synopsis — set up the premise and stakes, then bridge into Episode 01."}),Be.blockers.map((He,xt)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:He},`b-${xt}`)),Be.warnings.map((He,xt)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:He},`w-${xt}`))]}),be.length>0&&d.jsxs("div",{className:"mt-4 flex flex-col gap-2 rounded-xl border border-error/30 bg-error/5 px-3 py-3 max-w-xl","data-testid":"cartoon-publish-issues",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-error px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-white",children:"Before publish"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Finish these workflow steps"})]}),GS(be).map(He=>d.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${He.key}`,children:d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:He.title})},He.key)),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cartoon-technical-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc",children:be.map((He,xt)=>d.jsx("li",{className:"font-mono break-words",children:He},xt))})]})]}),d.jsxs("div",{className:"mt-4 flex flex-col gap-2 max-w-xl",children:[!$&&d.jsx("button",{onClick:s,"data-testid":"publish-add-cover",className:"self-start rounded border border-border px-3 py-1.5 text-xs text-foreground hover:border-accent hover:text-accent transition-colors",children:"Add a cover image (Story Info)"}),G&&!C&&d.jsx("button",{onClick:s,"data-testid":"publish-set-metadata",className:"self-start rounded border border-border px-3 py-1.5 text-xs text-foreground hover:border-accent hover:text-accent transition-colors",children:"Set genre & language (Story Info)"}),!T&&d.jsxs("button",{onClick:()=>i(e,A.file),"data-testid":"publish-open-episode",className:"self-start rounded border border-accent/40 px-3 py-1.5 text-xs text-accent hover:bg-accent/5 transition-colors",children:["Open ",A.label," to finish ",M?"and fix issues":"(letter / export / upload)"]}),d.jsx("button",{onClick:ot,disabled:!St,"data-testid":"publish-cta",className:"self-start rounded bg-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-dim disabled:opacity-50 transition-colors",title:St?void 0:"Finish the remaining steps above first",children:V?"Publishing…":`Publish ${A.label} to PlotLink`}),T?C?_e||Le?d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-title-blocked-reason",children:Le?"Fix the Story opening issues above before publishing.":"Set a real reader-facing title above before publishing."}):null:d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"publish-needs-metadata",children:"Set the genre and language in Story Info before publishing."}):d.jsx("p",{className:"text-[11px] text-muted","data-testid":"publish-blocked-reason",children:M?`Not publishable yet — ${A.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${A.summary.toLowerCase()}.`}),R&&d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:R})]}),d.jsxs("details",{className:"mt-4 max-w-xl","data-testid":"publish-technical-details",children:[d.jsx("summary",{className:"text-[11px] text-muted cursor-pointer hover:text-foreground",children:"Technical validation details"}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted space-y-0.5",children:[d.jsxs("p",{children:["Episode file: ",d.jsx("span",{className:"font-mono",children:A.file})]}),d.jsxs("p",{children:["State: ",A.state," — ",A.summary]}),d.jsx("p",{children:"Per-cut production (cut plan, clean images, lettering, export, upload) happens in the episode’s cut workspace; open it above to finish any remaining step."})]})]})]})}function UM(e,t){var s;const i=[e.plots,e.chapters].filter(Boolean);for(const a of i){let c=t!=null?a.find(p=>p.plotIndex===t||p.index===t):void 0;if(!c&&a.length===1){const p=a[0];(!(p.plotIndex!=null||p.index!=null)||t==null)&&(c=p)}const h=(s=(c==null?void 0:c.title)??(c==null?void 0:c.name))==null?void 0:s.trim();if(h)return h}}function $M(e){var o;const{fileName:t,detail:i,plotIndex:s}=e;if(!i)return{ok:!0,checked:!1};if(t==="genesis.md"){const c=(o=i.title??i.name)==null?void 0:o.trim();return c?zo(c,"genesis.md")?{ok:!1,checked:!0,publicTitle:c,reason:`PlotLink indexed the storyline title as “${c}”, a raw filename rather than the reader-facing title.`}:{ok:!0,checked:!0,publicTitle:c}:{ok:!0,checked:!1}}const a=UM(i,s);return a?zo(a,t)||Ip(a)?{ok:!1,checked:!0,publicTitle:a,reason:`PlotLink indexed the episode title as “${a}”, a generic placeholder rather than a reader-facing episode title.`}:{ok:!0,checked:!0,publicTitle:a}:{ok:!0,checked:!1}}function FM(e){return`${e.reason??"PlotLink indexed a raw/generic public title for this publish."} Published metadata is immutable on-chain and cannot be edited — the next publish must use corrected, reader-facing metadata. (The webtoon pilot stays blocked until a publish indexes a real public title.)`}const n1="plotlink-panel-ratio",qM=.6,wy=300,Pf=224,If=6;function WM(){try{const e=localStorage.getItem(n1);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return qM}function Cy(e,t){if(t<=0)return e;const i=wy/t,s=1-wy/t;return i>=s?.5:Math.min(s,Math.max(i,e))}function GM({token:e,authFetch:t}){const[i,s]=w.useState(null),[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState(0),[b,v]=w.useState(""),[S,j]=w.useState(null),[R,E]=w.useState(null),[N,I]=w.useState(WM),[te,F]=w.useState([]),[D,ie]=w.useState(!1),[fe,Se]=w.useState(""),[H,ce]=w.useState(""),[W,K]=w.useState(""),[X,U]=w.useState("English"),[A,O]=w.useState("normal"),[$,xe]=w.useState("claude"),[T,M]=w.useState(null),[G,C]=w.useState(!1),[V,ne]=w.useState({}),[ae,Y]=w.useState({}),[he,_e]=w.useState(new Set),[Be,Le]=w.useState(new Set),[je,be]=w.useState({}),[tt,St]=w.useState({}),[ot,We]=w.useState({}),[Mt,He]=w.useState({}),[xt,Ae]=w.useState({}),[Kt,mi]=w.useState({}),[wt,Qe]=w.useState(!1),[Q,ge]=w.useState(!0),Te=w.useRef(new Map),Ue=w.useRef(new Map),it=w.useRef(new Map),Wt=w.useRef(new Map),ui=w.useRef(new Set),Bt=w.useRef(null),vt=w.useRef(null),At=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(le=>le.ok?le.json():null).then(le=>{le!=null&&le.address&&E(le.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(le=>le.ok?le.json():null).then(le=>{le&&M(le)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(n1,String(N))}catch{}},[N]),w.useEffect(()=>{const le=()=>{if(!vt.current)return;const L=vt.current.getBoundingClientRect().width-Pf-If;I(oe=>Cy(oe,L))};return window.addEventListener("resize",le),le(),()=>window.removeEventListener("resize",le)},[]);const Ze=w.useCallback(()=>{Se(""),ce(""),K(""),O("normal"),xe("claude"),ie(!0)},[]),hi=w.useCallback(async(le,L,oe,Ee)=>{const Me=fe.trim();if(!Me)return;const Ne=le==="cartoon"?"codex":Ee;try{const Pe=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:Me,description:H.trim()||void 0,language:L,genre:W||void 0,contentType:le,agentMode:oe,agentProvider:Ne})});if(!Pe.ok)return;const qe=await Pe.json();ie(!1),be(nt=>({...nt,[qe.name]:le})),St(nt=>({...nt,[qe.name]:L})),W&&We(nt=>({...nt,[qe.name]:W})),Y(nt=>({...nt,[qe.name]:Ne})),oe==="bypass"&&ne(nt=>({...nt,[qe.name]:!0})),s(qe.name),o(null)}catch{}},[t,fe,H,W]);w.useEffect(()=>{if(te.length===0)return;const le=setInterval(async()=>{try{const L=await t("/api/stories");if(!L.ok)return;const oe=await L.json(),Ee=new Set(oe.stories.filter(Me=>Me.name!=="_example").map(Me=>Me.name));for(const Me of Ee)if(!ui.current.has(Me)&&te.length>0){const Ne=te[0],Pe=Te.current.get(Ne)||"fiction",qe=Ue.current.get(Ne)||"English",nt=it.current.get(Ne)||"normal",Ve=Wt.current.get(Ne)||"claude";let Et=!1;Bt.current&&(Et=await Bt.current(Ne,Me,{contentType:Pe,language:qe,agentMode:nt,agentProvider:Ve}).catch(()=>!1)),Et&&(F(Nt=>Nt.slice(1)),Te.current.delete(Ne),Ue.current.delete(Ne),it.current.delete(Ne),Wt.current.delete(Ne),nt==="bypass"&&ne(Nt=>{const Gt={...Nt,[Me]:!0};return delete Gt[Ne],Gt}),Y(Nt=>{const Gt={...Nt,[Me]:Ve};return delete Gt[Ne],Gt}),t(`/api/stories/${Me}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:Pe,language:qe,agentMode:nt,agentProvider:Ve})}).catch(()=>{})),s(Me),o(null)}ui.current=Ee}catch{}},3e3);return()=>clearInterval(le)},[t,te]),w.useEffect(()=>{t("/api/stories").then(le=>{if(le.ok)return le.json()}).then(le=>{le!=null&&le.stories&&(ui.current=new Set(le.stories.filter(L=>L.name!=="_example").map(L=>L.name)))}).catch(()=>{})},[t]);const P=w.useCallback((le,L)=>{s(le),o(L),h(null)},[]),we=w.useRef(null),ze=w.useCallback(async le=>{var L,oe,Ee,Me;we.current=le,s(le),o(null),h(null);try{const Ne=await t(`/api/stories/${le}`);if(Ne.ok&&we.current===le){const Pe=await Ne.json();if(Pe.contentType==="cartoon")return;const qe=Pe.files||[],Ve=((L=qe.map(Et=>{var Nt;return{file:Et.file,num:(Nt=Et.file.match(/^plot-(\d+)\.md$/))==null?void 0:Nt[1]}}).filter(Et=>Et.num!=null).sort((Et,Nt)=>parseInt(Nt.num)-parseInt(Et.num))[0])==null?void 0:L.file)??((oe=qe.find(Et=>Et.file==="genesis.md"))==null?void 0:oe.file)??((Ee=qe.find(Et=>Et.file==="structure.md"))==null?void 0:Ee.file)??((Me=qe[0])==null?void 0:Me.file);Ve&&we.current===le&&o(Ve)}}catch{}},[t]),Re=w.useCallback(le=>{le.preventDefault(),At.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const L=Ee=>{if(!At.current||!vt.current)return;const Me=vt.current.getBoundingClientRect(),Ne=Me.width-Pf-If,Pe=Ee.clientX-Me.left-Pf;I(Cy(Pe/Ne,Ne))},oe=()=>{At.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",L),window.removeEventListener("mouseup",oe)};window.addEventListener("mousemove",L),window.addEventListener("mouseup",oe)},[]),Ge=w.useCallback(async(le,L,oe,Ee,Me,Ne)=>{var Ve;f(L),v("Reading file..."),j(null);let Pe=!1,qe=null,nt=!1;try{const Et=await t(`/api/stories/${le}/${L}`);if(!Et.ok)throw new Error("Failed to read file");const Nt=await Et.json(),Gt=je[le];let Rt=null,ki=null;if(L==="genesis.md")try{const ei=await t(`/api/stories/${le}/structure.md`);ei.ok&&(Rt=(await ei.json()).content??null)}catch{}else if(Gt==="cartoon"&&L.match(/^plot-\d+\.md$/))try{const ei=await t(`/api/stories/${le}/cuts/${L.replace(/\.md$/,"")}`);ei.ok&&(ki=(await ei.json()).title??null)}catch{}const mr=Cm({fileName:L,fileContent:Nt.content,storySlug:le,structureContent:Rt,contentType:Gt,episodeTitle:ki});if(Gt==="cartoon"&&zo(mr,L))return v(L==="genesis.md"?"Add a real “# Title” heading to genesis.md before publishing — it would otherwise publish as a raw filename.":"Set an episode title in the cut plan before publishing — it would otherwise publish as a raw filename."),setTimeout(()=>{f(null),v("")},6e3),!1;if(Gt==="cartoon"&&L.match(/^plot-\d+\.md$/)&&!wm({fileContent:Nt.content,episodeTitle:ki}))return v("Set a real episode title in the cut plan (or add a “# Title” to the episode) before publishing — a generic “Episode NN” placeholder can’t be published."),setTimeout(()=>{f(null),v("")},6e3),!1;if(Gt==="cartoon"&&L==="genesis.md"){const ei=bm(Nt.content).blockers;if(ei.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${ei[0]}`),setTimeout(()=>{f(null),v("")},6e3),!1}let Jt;if(L.match(/^plot-\d+\.md$/)){if(dM(Nt)){v("Already published on PlotLink — republishing would create a duplicate chapter. Open it on PlotLink instead (or use Retry Index if it isn't showing yet)."),setTimeout(()=>{f(null),v("")},6e3);return}try{const ei=await t(`/api/stories/${le}`);if(ei.ok){const Fn=(await ei.json()).files.find(ar=>ar.file==="genesis.md"&&ar.storylineId);Jt=Fn==null?void 0:Fn.storylineId}}catch{}if(!Jt)return v("Error: Publish genesis first to create the storyline"),setTimeout(()=>{f(null),v("")},3e3),!1}v("Checking wallet balance...");try{const ei=await t("/api/publish/preflight");if(ei.ok){const Br=await ei.json();if(pM(Br))return j(mM(Br)),f(null),v(""),!1}}catch{}v("Publishing...");const qi=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:le,fileName:L,title:mr,content:Nt.content,genre:oe,language:Ee,isNsfw:Me,storylineId:Jt,...by(je,le,Jt)?{contentType:by(je,le,Jt)}:{}})});if(!qi.ok){const ei=await qi.json();throw new Error(ei.error||"Publish failed")}const $n=(Ve=qi.body)==null?void 0:Ve.getReader(),gr=new TextDecoder;if($n)for(;;){const{done:ei,value:Br}=await $n.read();if(ei)break;const ar=gr.decode(Br).split(` -`).filter(Wi=>Wi.startsWith("data: "));for(const Wi of ar)try{const Ct=JSON.parse(Wi.slice(6));if(Ct.step&&v(Ct.message||Ct.step),Ct.step==="done"&&Ct.txHash){if(nt=!0,await t(`/api/stories/${le}/${L}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:Ct.txHash,storylineId:Ct.storylineId,plotIndex:Ct.plotIndex,contentCid:Ct.contentCid,gasCost:Ct.gasCost,indexError:Ct.indexError,authorAddress:R})}),x(qn=>qn+1),Ne&&L==="genesis.md"&&Ct.storylineId){v("Uploading cover...");let qn=null;try{qn=await oM(t,Ct.storylineId,Ne)}catch{}qn||(Pe=!0)}if(Gt==="cartoon"&&Ct.storylineId)try{const qn=L!=="genesis.md",ya=`storylineId=${Ct.storylineId}`+(qn&&Ct.plotIndex!=null?`&plotIndex=${Ct.plotIndex}`:""),Lr=await t(`/api/publish/public-title?${ya}`);if(Lr.ok){const Fs=await Lr.json(),xr=qn?{plots:Fs.plotTitle!=null?[{plotIndex:Ct.plotIndex,title:Fs.plotTitle}]:[]}:{title:Fs.storylineTitle},Ei=$M({fileName:L,detail:xr,plotIndex:Ct.plotIndex});Ei.ok||(qe=FM(Ei))}}catch{}}}catch{}}qe&&j(qe),v(Pe?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(Et){const Nt=Et instanceof Error?Et.message:"Publish failed";v(`Error: ${Nt}`)}finally{setTimeout(()=>{f(null),v("")},3e3)}return nt&&!Pe},[t,je,R]),$e=w.useCallback(le=>{le.startsWith("_new_")&&(F(L=>L.filter(oe=>oe!==le)),Te.current.delete(le),Ue.current.delete(le),it.current.delete(le),Wt.current.delete(le),ne(L=>{if(!(le in L))return L;const oe={...L};return delete oe[le],oe}),Y(L=>{if(!(le in L))return L;const oe={...L};return delete oe[le],oe}))},[]);w.useEffect(()=>{const le=oe=>{_e(new Set(oe.filter(Ve=>Ve.hasStructure).map(Ve=>Ve.name))),Le(new Set(oe.filter(Ve=>Ve.hasGenesis).map(Ve=>Ve.name)));const Ee={},Me={},Ne={},Pe={},qe={},nt={};for(const Ve of oe)Ee[Ve.name]=Ve.contentType||"fiction",Me[Ve.name]=Ve.language,Ne[Ve.name]=Ve.genre,Pe[Ve.name]=Ve.isNsfw,qe[Ve.name]=Ve.agentProvider,Ve.title&&(nt[Ve.name]=Ve.title);be(Ee),St(Me),We(Ne),He(Pe),mi(qe),Ae(nt)};t("/api/stories").then(oe=>oe.ok?oe.json():null).then(oe=>{oe!=null&&oe.stories&&le(oe.stories)}).catch(()=>{});const L=setInterval(async()=>{try{const oe=await t("/api/stories");if(oe.ok){const Ee=await oe.json();le(Ee.stories)}}catch{}},5e3);return()=>clearInterval(L)},[t]);const ht=!!T&&T.codex.installed&&T.codex.imageGeneration==="enabled",dt=!!T&&!ht,lt=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),C(!0),setTimeout(()=>C(!1),2e3)}catch{}},[]),Vt=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const le=i;if((await t(`/api/stories/${le}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){mi(oe=>({...oe,[le]:"codex"})),Y(oe=>({...oe,[le]:"codex"}));try{const oe=await t("/api/stories");if(oe.ok){const Ee=await oe.json();if(Ee!=null&&Ee.stories){const Me={};for(const Ne of Ee.stories)Me[Ne.name]=Ne.agentProvider;mi(Me)}}}catch{}}},[t,i]),Ci=w.useCallback(le=>{i===le&&(s(null),o(null))},[i]),ft=i?ae[i]??Kt[i]:void 0,Fi=Lf(i,je,Te.current),En=fM(Fi,ft,i),ln=!!i&&Fi==="cartoon",Un=c==="story-info"?"story-info":c==="episodes"?"episodes":c==="publish"?"publish":a==="structure.md"?"whitepaper":a==="genesis.md"?"genesis":a&&/^plot-\d+\.md$/.test(a)?"episodes":"progress",on=w.useCallback(le=>{const L=i;if(L)switch(le){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":P(L,"structure.md");break;case"genesis":P(L,"genesis.md");break;case"publish":h("publish");break}},[i,P]),gn=w.useCallback((le,L)=>{const oe=i;if(oe)switch(le){case"view-progress":h(null),o(null);break;case"publish":h("publish");break;case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":case"generate-markdown":L&&P(oe,L);break}},[i,P]),cn=w.useCallback(le=>{i&&(le.genre!==void 0&&We(L=>({...L,[i]:le.genre||void 0})),le.language!==void 0&&St(L=>({...L,[i]:le.language||void 0})),le.isNsfw!==void 0&&He(L=>({...L,[i]:le.isNsfw})))},[i]),pr=w.useCallback(le=>{Qe(le),ge(!le)},[]),Lt=wt&&!Q;return d.jsxs("div",{ref:vt,className:"h-[calc(100vh-3.5rem)] flex","data-testid":Lt?"stories-focused-lettering-mode":"stories-default-layout",children:[!Lt&&d.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:d.jsx(kC,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:P,onNewStory:Ze,untitledSessions:te})}),!Lt&&d.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${N} 0 0`},children:d.jsx(ZE,{token:e,storyName:i,authFetch:t,onSelectStory:ze,onDestroySession:$e,onArchiveStory:Ci,confirmedStories:he,renameRef:Bt,bypassStories:V,agentProviders:ae,readiness:T,contentType:Lf(i,je,Te.current),needsProviderRepair:En,onRepairProvider:Vt})}),!Lt&&d.jsx("div",{onMouseDown:Re,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:If,cursor:"col-resize",background:"var(--border)"},children:d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}})]})}),d.jsxs("div",{className:"min-w-0 min-h-0 flex flex-col",style:Lt?{flex:"1 0 0"}:{flex:`${1-N} 0 0`},children:[!wt&&ln&&i&&d.jsx(zM,{storyTitle:xt[i]||i,active:Un,onSelect:on}),!wt&&ln&&i&&c!==null&&d.jsx("div",{className:"flex-shrink-0 border-b border-border","data-testid":"workflow-context-next-action",children:d.jsx(wM,{storyName:i,authFetch:t,refreshKey:_,onCoachAction:gn,onOpenStoryInfo:()=>h("story-info")})}),d.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:ln&&c==="story-info"&&i?d.jsx(PM,{storyName:i,authFetch:t,onSaved:cn}):ln&&c==="episodes"&&i?d.jsx(IM,{storyName:i,authFetch:t,onOpenFile:P}):ln&&c==="publish"&&i?d.jsx(HM,{storyName:i,authFetch:t,onOpenFile:P,onOpenStoryInfo:()=>h("story-info"),onPublish:Ge,publishingFile:p,genre:ot[i],language:tt[i],isNsfw:Mt[i],refreshKey:_}):i&&!a?d.jsx(kM,{storyName:i,authFetch:t,onOpenFile:P,onOpenStoryInfo:()=>h("story-info")}):d.jsx(vM,{storyName:i,fileName:a,authFetch:t,onPublish:Ge,publishingFile:p,walletAddress:R,contentType:Lf(i,je,Te.current)||"fiction",language:i?tt[i]:void 0,genre:i?ot[i]:void 0,isNsfw:i?Mt[i]:void 0,hasGenesis:i?Be.has(i):!1,onViewProgress:()=>o(null),onOpenFile:le=>i&&P(i,le),onViewPublish:()=>h("publish"),focusedLetteringMode:wt,focusedLetteringWorkspaceVisible:Q,onFocusedLetteringModeChange:pr,onFocusedLetteringWorkspaceVisibleChange:ge})}),b&&d.jsx("div",{className:"shrink-0 px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),S&&d.jsxs("div",{className:"shrink-0 px-3 py-2 bg-error/10 border-t border-error/40 text-xs text-error flex items-start justify-between gap-3","data-testid":"publish-block-error",role:"alert",children:[d.jsx("span",{children:S}),d.jsx("button",{type:"button",onClick:()=>j(null),className:"shrink-0 text-error/70 hover:text-error underline","data-testid":"publish-block-error-dismiss",children:"Dismiss"})]})]}),D&&d.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"bg-surface border border-border rounded-lg shadow-lg p-6 max-w-sm w-full space-y-4",children:[d.jsx("h3",{className:"text-sm font-serif font-medium text-foreground text-center",children:"New Story"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsxs("span",{className:"text-[10px] font-medium text-muted",children:["Title ",d.jsx("span",{className:"text-accent",children:"*"})]}),d.jsx("input",{type:"text",value:fe,onChange:le=>Se(le.target.value),placeholder:"e.g. 신의 세포","data-testid":"new-story-title",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Short description (optional)"}),d.jsx("input",{type:"text",value:H,onChange:le=>ce(le.target.value),placeholder:"One line about the story","data-testid":"new-story-description",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Genre (optional)"}),d.jsxs("select",{value:W,onChange:le=>K(le.target.value),"data-testid":"new-story-genre",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[d.jsx("option",{value:"",children:"— Select later —"}),dl.map(le=>d.jsx("option",{value:le,children:le},le))]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Language"}),d.jsx("select",{value:X,onChange:le=>U(le.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:ts.map(le=>d.jsx("option",{value:le,children:le},le))})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Agent mode"}),d.jsxs("select",{value:A,onChange:le=>O(le.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"agent-mode-select",children:[d.jsx("option",{value:"normal",children:"Normal (approve each action)"}),d.jsx("option",{value:"bypass",children:"Permissions Bypass (advanced)"})]}),A==="bypass"&&d.jsx("p",{className:"text-[10px] text-amber-700","data-testid":"agent-mode-warning",children:"Less safe: Claude can run actions without per-command approval."})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Provider"}),d.jsxs("select",{value:$,onChange:le=>xe(le.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"agent-provider-select",children:[d.jsx("option",{value:"claude",children:"🤖 Claude (default)"}),d.jsx("option",{value:"codex",children:"🎨 Codex"})]}),d.jsx("p",{className:"text-[10px] text-muted","data-testid":"agent-provider-helper",children:$==="codex"?"Codex can generate clean cartoon images directly in the terminal.":"Claude prepares image prompts; you generate and upload clean images externally."})]}),d.jsx("p",{className:"text-xs text-muted text-center",children:"Choose a content type to create"}),!fe.trim()&&d.jsx("p",{className:"text-[10px] text-amber-700 text-center","data-testid":"new-story-title-required",children:"Enter a title to create your story."}),d.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[d.jsxs("button",{onClick:()=>hi("fiction",X,A,$),disabled:!fe.trim(),"data-testid":"create-fiction",className:"border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Fiction"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Novels, short stories, poetry"})]}),d.jsxs("div",{className:"space-y-1",children:[d.jsxs("button",{onClick:()=>hi("cartoon",X,A,"codex"),disabled:dt||!fe.trim(),"data-testid":"create-cartoon",className:"w-full border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Cartoon"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Comics, manga, webtoons"}),d.jsx("p",{className:"text-[11px] text-muted","data-testid":"cartoon-codex-note",children:"Cartoon mode requires Codex because the clean-image step needs image generation support."})]}),T&&!T.codex.installed&&d.jsxs("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-warning",children:["Codex was not detected. Install the Codex CLI and sign in (e.g."," ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," ","then ",d.jsx("span",{className:"font-mono",children:"codex login"}),") to create cartoons."]}),Eu(T)&&d.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:Up}),T&&T.codex.installed&&!Eu(T)&&T.codex.imageGeneration!=="enabled"&&d.jsxs("div",{"data-testid":"cartoon-codex-warning",children:[d.jsx("p",{className:"text-[11px] text-amber-700 text-left",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this dialog:"}),d.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[d.jsx("code",{className:"flex-1 truncate rounded border border-border bg-surface px-1.5 py-1 text-left text-[10px] font-mono text-foreground",children:"codex features enable image_generation"}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable",onClick:lt,className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:G?"Copied!":"Copy"})]})]})]})]}),d.jsx("button",{onClick:()=>ie(!1),className:"w-full px-3 py-1.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded text-center",children:"Cancel"})]})})]})}function YM({token:e,onComplete:t}){const[i,s]=w.useState(!1),[a,o]=w.useState(null),[c,h]=w.useState(!1),p=async()=>{s(!0),o(null);try{const f=await fetch("/api/wallet/create",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),_=await f.json();if(!f.ok)throw new Error(_.error||"Wallet creation failed");h(!0)}catch(f){o(f instanceof Error?f.message:"Wallet creation failed")}s(!1)};return w.useEffect(()=>{p()},[]),d.jsxs("div",{className:"mx-auto max-w-sm p-6 text-center",children:[d.jsx("h2",{className:"text-accent mb-1 text-lg font-bold",children:"Wallet Setup"}),d.jsx("p",{className:"text-muted mb-6 text-xs",children:"creating your OWS wallet for on-chain publishing"}),i&&d.jsx("p",{className:"text-accent text-sm",children:"creating wallet..."}),a&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"rounded border border-red-700/30 p-3 text-xs text-red-700",children:a}),d.jsx("button",{onClick:p,className:"border-accent text-accent hover:bg-accent/10 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:"retry"})]}),c&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"text-accent text-2xl",children:"✓"}),d.jsx("p",{className:"text-foreground text-sm font-medium",children:"wallet created"}),d.jsx("button",{onClick:t,className:"border-accent text-accent hover:bg-accent/10 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:"continue"})]})]})}function KM({token:e,onLogout:t}){const[i,s]=w.useState("home"),[a,o]=w.useState(0),[c,h]=w.useState(null),p=w.useCallback(async(f,_)=>fetch(f,{..._,headers:{...(_==null?void 0:_.headers)||{},Authorization:`Bearer ${e}`}}),[e]);return w.useEffect(()=>{fetch("/api/health").then(f=>f.json()).then(f=>{f.version&&h(f.version)}).catch(()=>{})},[]),w.useEffect(()=>{async function f(){try{if(!(await(await p("/api/wallet")).json()).exists){s("wallet-setup");return}const b=await p("/api/stories");if(b.ok){const v=await b.json();o(v.stories.filter(S=>S.name!=="_example").length)}}catch{}}f()},[e]),d.jsxs("div",{className:"flex h-screen flex-col",children:[d.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{onClick:()=>{i!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:d.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),d.jsxs("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:["writer",c?` v${c}`:""]})]}),i!=="wallet-setup"&&d.jsxs("nav",{className:"flex items-center gap-4",children:[d.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${i==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),d.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${i==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),d.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${i==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),d.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),d.jsxs("main",{className:"flex-1 min-h-0",children:[i==="home"&&d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[d.jsxs("div",{className:"text-center space-y-2",children:[d.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),d.jsx("p",{className:"text-muted text-sm",children:"Claude or Codex helps create your story. You publish it on-chain."})]}),d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("button",{onClick:()=>s("stories"),className:"bg-accent text-white hover:bg-accent-dim px-6 py-2.5 rounded text-sm font-medium transition-colors",children:"Start Writing"}),a>0&&d.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),d.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[d.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),d.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[d.jsxs("li",{children:["Open the ",d.jsx("strong",{children:"Stories"})," tab — your writing agent launches in the terminal"]}),d.jsx("li",{children:"Tell the agent your story idea — it brainstorms, outlines, and writes"}),d.jsx("li",{children:"Review the live preview as the agent creates files"}),d.jsxs("li",{children:["Click ",d.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),d.jsxs("li",{children:["Earn 5% royalties on every trade at ",d.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]}),d.jsx("p",{className:"text-[11px] text-muted",children:"Fiction defaults to Claude; cartoon mode uses Codex for clean-image generation."})]}),d.jsx("div",{className:"text-center",children:d.jsx("a",{href:"https://github.com/realproject7/plotlink-ows#-wallet-setup",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted hover:text-accent underline transition-colors",children:"Wallet Setup Guide"})}),d.jsx(jy,{token:e})]}),i==="stories"&&d.jsx(GM,{token:e,authFetch:p}),i==="dashboard"&&d.jsx(SC,{token:e}),i==="wallet-setup"&&d.jsx(YM,{token:e,onComplete:()=>s("home")}),i==="settings"&&d.jsx(vC,{token:e,onLogout:t})]})]})}function VM(){const[e,t]=w.useState(()=>localStorage.getItem("ows-token")),[i,s]=w.useState(null),[a,o]=w.useState(!0);w.useEffect(()=>{fetch("/api/auth/status").then(f=>f.json()).then(f=>s(f.configured)).catch(()=>s(null))},[]),w.useEffect(()=>{if(!e){o(!1);return}fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${e}`}}).then(f=>{f.ok||(localStorage.removeItem("ows-token"),t(null))}).catch(()=>{localStorage.removeItem("ows-token"),t(null)}).finally(()=>o(!1))},[e]);const c=async f=>{try{const _=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),x=await _.json();return _.ok?(localStorage.setItem("ows-token",x.token),t(x.token),null):x.error||"Login failed"}catch{return"Cannot connect to server"}},h=async f=>{try{const _=await fetch("/api/auth/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),x=await _.json();return _.ok?(localStorage.setItem("ows-token",x.token),t(x.token),s(!0),null):x.error||"Setup failed"}catch{return"Cannot connect to server"}},p=()=>{localStorage.removeItem("ows-token"),t(null)};return a||i===null?d.jsx("div",{className:"flex h-screen items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"connecting..."})}):i?e?d.jsx(KM,{token:e,onLogout:p}):d.jsx(_C,{onLogin:c}):d.jsx(bC,{onSetup:h})}xC.createRoot(document.getElementById("root")).render(d.jsx(cC.StrictMode,{children:d.jsx(VM,{})}));export{zp as M,hu as a,M3 as b,ID as c,L3 as d,uu as l,HS as s,G3 as t,e4 as v}; +Publish now?`;if(!window.confirm(ye))return}const re=Ei?Rt:null;re?await(s==null?void 0:s(e,t,se,K,_e,re))&&(oe.current=!0,on(null),cn(null),Lt("unknown"),Qe(null),H(Ce=>(Ce&&URL.revokeObjectURL(Ce),null)),pt.current&&(pt.current.value="")):s==null||s(e,t,se,K,_e)},disabled:!!a||us||Ws||Vo||Ei&&(!se||!K)||Gi&&Le!=="ready",className:"px-4 py-1.5 bg-accent text-white text-sm rounded hover:bg-accent-dim disabled:opacity-50 disabled:cursor-not-allowed",children:a===t?"Publishing...":"Publish to PlotLink"}),Ei&&c==="cartoon"&&(!se||!K)&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"cartoon-metadata-needs-story-info",children:"Set the genre and language in Story Info before publishing"}),Ei&&c!=="cartoon"&&!se&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"genre-needs-metadata",children:"Needs metadata — choose a genre before publishing"}),Ei&&c!=="cartoon"&&se&&!K&&d.jsx("span",{className:"text-amber-600 text-xs","data-testid":"language-needs-metadata",children:"Needs metadata — choose a language before publishing"}),us&&d.jsx("span",{className:"text-error text-xs",children:"Reduce content to publish"}),Gi&&Le==="error"&&d.jsx("span",{className:"text-error text-xs","data-testid":"publish-disabled-reason",children:"Fix the issues below before publishing"}),Gi&&Le==="planning"&&d.jsx("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:"Prepare the episode for publish to continue"}),Gi&&Le==="awaiting-upload"&&d.jsxs("span",{className:"text-muted text-xs","data-testid":"publish-disabled-reason",children:["Upload all final images, then “Prepare episode for publish” — ",ke," of ",Je," ","still need an uploaded image"]})]}),Or&&d.jsx("button",{onClick:()=>v==null?void 0:v(),"data-testid":"cartoon-review-publish",className:"self-start rounded border border-accent/40 px-3 py-1 text-xs text-accent hover:bg-accent/5 transition-colors",children:"Review publish checklist →"}),br.warnings.length>0&&d.jsx("div",{className:"flex flex-col gap-0.5",children:br.warnings.map((re,ye)=>d.jsx("span",{className:"text-amber-600 text-xs",children:re},ye))}),Ei&&c!=="cartoon"&&d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted cursor-pointer",children:[d.jsx("input",{type:"checkbox",checked:_e,onChange:re=>{Me(re.target.checked),$n({isNsfw:re.target.checked})},className:"rounded border-border"}),"This story contains adult content (18+)"]}),_e&&d.jsx("span",{className:"text-xs text-amber-600",children:"Adult content will be hidden from the default browse view."})]})]})})]})}function wM(e){if(e.cover!=="present")return e.cover==="invalid"?"Replace the cover image - it must be a valid WebP or JPEG.":"Add a cover image before publishing.";const t=[];return e.metadata.language||t.push("language"),e.metadata.genre||t.push("genre"),e.metadata.title||t.push("title"),`Add the story ${t.join(" and ")||"details"} before publishing.`}function r1(e){const t=e.coach??null,i=e.metadata,s=e.setup.hasStructure,a=e.setup.hasGenesis,o=e.cover==="present",c=!i.title||!i.language||!i.genre,h=e.episodes.find(f=>!f.published)??null,p=!!h&&h.state!=="ready";return s?a?c?"story-info":p&&(t!=null&&t.episodeFile)?t.episodeFile:o?(t==null?void 0:t.episodeFile)??null:"story-info":"genesis.md":"whitepaper"}function CM({progress:e,onOpenStoryInfo:t}){return d.jsx("div",{className:"m-3 rounded-lg border border-accent/40 bg-accent/10 px-4 py-3 shadow-sm","data-testid":"story-info-cta",children:d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsxs("div",{className:"min-w-0 flex-1",children:[d.jsx("span",{className:"inline-flex rounded-full bg-background px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] text-accent",children:"Story info"}),d.jsxs("p",{className:"mt-1 text-sm text-foreground","data-testid":"story-info-next-action",children:[d.jsx("span",{className:"font-semibold",children:"Next: "}),d.jsx("span",{children:wM(e)})]})]}),d.jsx("button",{type:"button",onClick:t,disabled:!t,className:"flex-shrink-0 rounded bg-accent px-4 py-2.5 text-sm font-bold text-white shadow-sm transition-colors hover:bg-accent-dim disabled:cursor-not-allowed disabled:opacity-50","data-testid":"story-info-next-action-btn",children:"Next Action"})]})})}function s1({progress:e,onCoachAction:t,onOpenStoryInfo:i}){return r1(e)==="story-info"?d.jsx(CM,{progress:e,onOpenStoryInfo:i}):d.jsx(Cm,{coach:e.coach??null,showEmptyState:!0,onAction:t})}function kM({storyName:e,authFetch:t,refreshKey:i=0,onCoachAction:s,onOpenStoryInfo:a}){const[o,c]=w.useState(void 0),h=JSON.stringify([e,i]),[p,f]=w.useState(null);return p!==h&&(c(void 0),f(h)),w.useEffect(()=>{let _=!1;return t(`/api/stories/${e}/progress`).then(x=>x.ok?x.json():null).then(x=>{_||c(EM(x)?x:null)}).catch(()=>{_||c(null)}),()=>{_=!0}},[e,t,i]),o===void 0?null:o?d.jsx(s1,{progress:o,onCoachAction:s,onOpenStoryInfo:a}):d.jsx(Cm,{coach:null,showEmptyState:!0,onAction:s})}function EM(e){return!!e&&!!e.metadata&&!!e.setup&&Array.isArray(e.episodes)}function NM({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,refreshKey:a=0}){const[o,c]=w.useState(null),[h,p]=w.useState(!0);return w.useEffect(()=>{let f=!1;return(async()=>{p(!0);try{const x=await t(`/api/stories/${e}/progress`),b=x.ok?await x.json():null;f||(c(b),p(!1))}catch{f||(c(null),p(!1))}})(),()=>{f=!0}},[e,t,a]),h?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"progress-loading",children:"Loading progress…"}):!o||!o.metadata||!Array.isArray(o.episodes)?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story progress."}):o.contentType==="cartoon"?d.jsx(BM,{progress:o,storyName:e,onOpenFile:i,onOpenStoryInfo:s}):d.jsx(zM,{progress:o,storyName:e,onOpenFile:i})}function mu({label:e,value:t,tone:i="muted"}){const s=i==="ok"?"text-green-700":i==="warn"?"text-amber-700":"text-muted";return d.jsxs("span",{className:"text-[11px]",children:[d.jsxs("span",{className:"text-muted",children:[e,": "]}),d.jsx("span",{className:`font-medium ${s}`,children:t})]})}function a1({progress:e}){const t=e.contentType==="cartoon",i=e.cover==="present"?"ok":e.cover==="invalid"?"warn":"muted";return d.jsxs("div",{className:"px-4 py-3 border-b border-border",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h2",{className:"text-base font-serif text-foreground truncate",children:e.metadata.title||e.name}),d.jsx("span",{className:`rounded px-1.5 py-0.5 text-[10px] font-medium ${t?"bg-accent/10 text-accent":"bg-surface text-muted"}`,children:t?"Cartoon":"Fiction"})]}),d.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1",children:[d.jsx(mu,{label:"Language",value:e.metadata.language||"Needs metadata",tone:e.metadata.language?"muted":"warn"}),d.jsx(mu,{label:"Genre",value:e.metadata.genre||"Needs metadata",tone:e.metadata.genre?"muted":"warn"}),e.metadata.isNsfw!=null&&d.jsx(mu,{label:"Adult",value:e.metadata.isNsfw?"Yes (18+)":"No"}),t&&d.jsx(mu,{label:"Cover",value:e.cover==="present"?"Ready":e.cover==="invalid"?"Invalid":"Missing",tone:i})]})]})}const l1={published:"✓",done:"●",current:"◉","needs-action":"●","not-started":"○"},zu={published:"text-green-700",done:"text-green-700",current:"text-accent","needs-action":"text-amber-700","not-started":"text-muted"},o1={published:"Published",done:"Complete",current:"Current","needs-action":"Needs action","not-started":"Not started"},jM={done:"✓",current:"◓",todo:"○"},TM={done:"text-green-700",current:"text-accent",todo:"text-muted"};function c1({item:e}){return d.jsxs("div",{className:"flex items-baseline gap-2 text-[11px]","data-testid":"checklist-item","data-status":e.status,children:[d.jsx("span",{className:`${TM[e.status]} flex-shrink-0`,"aria-hidden":!0,children:jM[e.status]}),d.jsx("span",{className:e.status==="todo"?"text-muted":"text-foreground",children:e.label}),e.detail&&d.jsxs("span",{className:"text-muted",children:["· ",e.detail]})]})}function wy({index:e,title:t,status:i,items:s,fileName:a,openFile:o}){const c=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[i]}`,"aria-hidden":!0,children:l1[i]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",t]}),a&&d.jsx("span",{className:"text-[10px] text-muted truncate",children:a}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[i]} flex-shrink-0`,children:o1[i]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":i,children:[o?d.jsx("button",{onClick:o,className:"w-full text-left rounded hover:bg-surface -mx-1 px-1 py-0.5","data-testid":`section-open-${e}`,children:c}):c,d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:s.map((h,p)=>d.jsx(c1,{item:h},p))})]})}function AM(e,t){return e.published?"published":t?"current":e.state==="placeholder"?"not-started":(e.state==="blocked","needs-action")}function RM(e,t=!0){const i=e.checklist??[],s=[];if(e.kind==="genesis"&&s.push({label:"Opening text",status:t?"done":"todo"}),i.length===0)return s.push({label:"Cut plan",status:"todo"}),s.push({label:"Clean artwork",status:"todo"}),s;for(const a of i)s.push(DM(a));return s}function DM(e){return{label:e.label,status:e.status,detail:e.detail}}const MM={file:"genesis.md",label:"Episode 1 / Genesis",kind:"genesis",title:null,state:"placeholder",summary:"",published:!1,checklist:[],cuts:null};function BM({progress:e,storyName:t,onOpenFile:i,onOpenStoryInfo:s}){const a=e.metadata,o=e.setup.hasStructure,c=e.cover==="present",p=!a.title||!a.language||!a.genre||!c,f=r1(e),_=d.jsx(s1,{progress:e,onOpenStoryInfo:s,onCoachAction:(E,N)=>{E!=="view-progress"&&N&&i(t,N)}}),x=[{label:"Public title",status:a.title?"done":"todo",detail:a.title??null},{label:"Language",status:a.language?"done":"todo",detail:a.language??null},{label:"Genre",status:a.genre?"done":"todo",detail:a.genre??null},{label:"Cover image",status:c?"done":"todo",detail:e.cover==="invalid"?"Invalid — re-import":c?null:"Missing"}],b=f==="story-info"?"current":p?"needs-action":"done",v=o?"done":f==="whitepaper"?"current":"not-started",S=e.episodes.find(E=>E.kind==="genesis")??null,j=e.episodes.filter(E=>E.kind==="plot");let D=0;return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(a1,{progress:e}),d.jsx("div",{className:"border-b border-border","data-testid":"persistent-next-action",children:_}),d.jsx("p",{className:"px-4 pt-3 pb-1 text-[11px] font-medium text-muted uppercase tracking-wider",children:"Production Progress"}),d.jsx(wy,{index:++D,title:"Define Story Info",status:b,items:x}),d.jsx(wy,{index:++D,title:"Story Whitepaper",status:v,fileName:"structure.md",openFile:o?()=>i(t,"structure.md"):void 0,items:[{label:"Planning document",status:o?"done":"todo",detail:o?null:"Not written yet"}]}),S?d.jsx(Pf,{index:++D,ep:S,isActive:f===S.file,storyName:t,onOpenFile:i}):d.jsx(Pf,{index:++D,ep:MM,isActive:f==="genesis.md",openingDone:!1,canOpen:!1,storyName:t,onOpenFile:i}),j.map(E=>d.jsx(Pf,{index:++D,ep:E,isActive:f===E.file,storyName:t,onOpenFile:i},E.file)),d.jsxs("div",{className:"px-4 py-2 text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[d.jsxs("span",{children:[e.summary.published," published"]}),d.jsxs("span",{children:[e.summary.readyToPublish," ready"]}),e.summary.placeholders>0&&d.jsxs("span",{children:[e.summary.placeholders," not started"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function Pf({index:e,ep:t,isActive:i,storyName:s,onOpenFile:a,openingDone:o=!0,canOpen:c=!0}){const h=AM(t,i),p=RM(t,o),f=t.title?`${t.label} · ${t.title}`:t.label,_=d.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[d.jsx("span",{className:`flex-shrink-0 ${zu[h]}`,"aria-hidden":!0,children:l1[h]}),d.jsxs("span",{className:"text-xs font-medium text-foreground truncate",children:[e,". ",f]}),d.jsx("span",{className:"text-[10px] text-muted truncate",children:t.file}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${zu[h]} flex-shrink-0`,children:o1[h]})]});return d.jsxs("div",{className:"px-4 py-2.5 border-b border-border","data-testid":`workflow-section-${e}`,"data-status":h,children:[c?d.jsx("button",{onClick:()=>a(s,t.file),"data-testid":`progress-episode-${t.file}`,"data-state":t.state,className:"w-full text-left rounded hover:bg-surface -mx-1 px-1 py-0.5",children:_}):d.jsx("div",{"data-state":t.state,children:_}),d.jsx("div",{className:"mt-1.5 ml-1 flex flex-col gap-1 border-l border-border pl-3",children:p.map((x,b)=>d.jsx(c1,{item:x},b))})]})}const LM={published:"✓",ready:"●","in-progress":"◐",planning:"○",placeholder:"○",blocked:"✕",draft:"○"},Cy={published:"text-green-700",ready:"text-green-700","in-progress":"text-accent",planning:"text-accent",placeholder:"text-muted",blocked:"text-error",draft:"text-muted"},OM={published:"Published",ready:"Ready","in-progress":"In progress",planning:"Planning",placeholder:"Not started",blocked:"Needs fixes",draft:"Draft"};function zM({progress:e,storyName:t,onOpenFile:i}){const[s,a]=w.useState(!1);return d.jsxs("div",{className:"h-full overflow-y-auto","data-testid":"story-progress-panel",children:[d.jsx(a1,{progress:e}),e.nextAction&&d.jsxs("div",{className:"px-4 py-2 border-b border-accent/30 bg-accent/5 text-xs space-y-1.5","data-testid":"progress-next-action",children:[d.jsxs("div",{children:[d.jsx("span",{className:"font-medium text-foreground",children:"Next: "}),d.jsx("span",{className:"text-muted",children:e.nextAction})]}),e.nextPrompt&&d.jsxs("div",{className:"flex items-start gap-1.5","data-testid":"progress-next-prompt",children:[d.jsx("code",{className:"flex-1 rounded border border-border bg-surface px-1.5 py-1 text-[10px] text-foreground break-words",children:e.nextPrompt}),d.jsx("button",{onClick:()=>{var o;e.nextPrompt&&((o=navigator.clipboard)==null||o.writeText(e.nextPrompt).then(()=>{a(!0)}).catch(()=>{}))},"data-testid":"copy-next-prompt",className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors flex-shrink-0",children:s?"Copied!":"Copy"})]})]}),d.jsxs("div",{className:"px-4 py-2 border-b border-border flex flex-col gap-1",children:[d.jsx(ky,{done:e.setup.hasStructure,label:"Story bible (structure.md)",onClick:e.setup.hasStructure?()=>i(t,"structure.md"):void 0}),d.jsx(ky,{done:e.setup.hasGenesis,label:"Genesis written",onClick:e.setup.hasGenesis?()=>i(t,"genesis.md"):void 0})]}),d.jsxs("div",{className:"px-4 py-2",children:[d.jsx("p",{className:"text-[11px] font-medium text-muted uppercase tracking-wider mb-1.5",children:"Chapters"}),e.episodes.length===0?d.jsx("p",{className:"text-xs text-muted italic","data-testid":"progress-no-episodes",children:"No chapters yet — write the Genesis to start."}):d.jsx("ol",{className:"flex flex-col gap-1",children:e.episodes.map(o=>d.jsx("li",{children:d.jsxs("button",{onClick:()=>i(t,o.file),"data-testid":`progress-episode-${o.file}`,"data-state":o.state,className:"w-full text-left flex items-start gap-2 rounded px-2 py-1.5 hover:bg-surface",children:[d.jsx("span",{className:`mt-0.5 ${Cy[o.state]}`,"aria-hidden":!0,children:LM[o.state]}),d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:o.label}),o.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",o.title]}),d.jsx("span",{className:`ml-auto text-[10px] font-medium ${Cy[o.state]}`,children:OM[o.state]})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:o.summary})]})]})},o.file))})]}),d.jsxs("div",{className:"px-4 py-2 border-t border-border text-[11px] text-muted flex flex-wrap gap-x-3","data-testid":"progress-summary",children:[d.jsxs("span",{children:[e.summary.published," published"]}),e.summary.blocked>0&&d.jsxs("span",{className:"text-error",children:[e.summary.blocked," need fixes"]})]})]})}function ky({done:e,label:t,onClick:i}){const s=d.jsxs("span",{className:"flex items-center gap-2 text-xs",children:[d.jsx("span",{className:e?"text-green-700":"text-muted","aria-hidden":!0,children:e?"✓":"○"}),d.jsx("span",{className:e?"text-foreground":"text-muted",children:t})]});return i?d.jsx("button",{onClick:i,className:"text-left hover:underline",children:s}):d.jsx("div",{children:s})}const PM=[{key:"progress",label:"Progress"},{key:"story-info",label:"Story Info"},{key:"whitepaper",label:"Whitepaper"},{key:"genesis",label:"Genesis / Ep 1"},{key:"episodes",label:"Episodes"},{key:"publish",label:"Publish"}];function IM({storyTitle:e,active:t,onSelect:i}){return d.jsxs("div",{className:"flex-shrink-0 border-b border-border bg-surface/40","data-testid":"cartoon-workflow-nav",children:[d.jsxs("div",{className:"flex items-center gap-2 px-3 pt-2",children:[d.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.14em] text-accent",children:"Cartoon"}),d.jsx("span",{className:"text-xs font-serif text-foreground truncate",children:e})]}),d.jsx("div",{className:"flex items-center gap-1 px-2 py-1.5 overflow-x-auto",role:"tablist",children:PM.map(s=>{const a=s.key===t;return d.jsx("button",{role:"tab","aria-selected":a,"data-testid":`nav-tab-${s.key}`,"data-active":a,onClick:()=>i(s.key),className:`flex-shrink-0 rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors ${a?"bg-accent text-white":"text-muted hover:text-foreground hover:bg-surface"}`,children:s.label},s.key)})})]})}function HM({storyName:e,authFetch:t,onSaved:i}){const[s,a]=w.useState(!0),[o,c]=w.useState(!1),[h,p]=w.useState(""),[f,_]=w.useState(""),[x,b]=w.useState(""),[v,S]=w.useState(""),[j,D]=w.useState(!1),[E,N]=w.useState("cartoon"),[I,te]=w.useState("unknown"),[q,R]=w.useState(!1),[ie,fe]=w.useState(!1),[be,B]=w.useState(null),[ne,F]=w.useState(!1),[G,Y]=w.useState(null),[U,A]=w.useState(!1),z=w.useRef(null);w.useEffect(()=>{let C=!1;return a(!0),c(!1),fe(!1),B(null),(async()=>{try{const[X,se]=await Promise.all([t(`/api/stories/${e}`),t(`/api/stories/${e}/progress`)]);if(!X.ok){C||(c(!0),a(!1));return}const le=await X.json(),K=se.ok?await se.json().catch(()=>null):null;if(C)return;p(le.title??""),_(le.description??""),b(Cu(le.genre)??""),S(le.language&&ts.find(he=>he.toLowerCase()===le.language.toLowerCase())||""),D(!!le.isNsfw),N(le.contentType==="fiction"?"fiction":"cartoon"),te((K==null?void 0:K.cover)??"unknown"),a(!1)}catch{C||(c(!0),a(!1))}})(),()=>{C=!0}},[e,t]);const $=w.useCallback(async()=>{R(!0),fe(!1),B(null);const C={title:h.trim(),description:f.trim(),genre:x,language:v,isNsfw:j};try{const X=await t(`/api/stories/${e}/publish-metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)});if(X.ok)fe(!0),i==null||i({genre:x,language:v,isNsfw:j});else{const se=await X.json().catch(()=>({}));B(se.error||"Could not save story info.")}}catch{B("Could not save story info.")}R(!1)},[e,t,h,f,x,v,j,i]),ge=w.useCallback(async C=>{var se;const X=(se=C.target.files)==null?void 0:se[0];if(z.current&&(z.current.value=""),!!X){F(!0),B(null);try{let le;try{le=await Vu(X)}catch(Le){B(Le instanceof Error?Le.message:"Could not import image");return}const K=le.type==="image/jpeg"?"jpg":"webp",he=new File([le],`cover.${K}`,{type:le.type}),_e=new FormData;_e.append("file",he);const Me=await t(`/api/stories/${e}/import-cover`,{method:"POST",body:_e});if(!Me.ok){const Le=await Me.json().catch(()=>({}));B(Le.error||"Cover import failed.");return}te("present"),Y(Le=>(Le&&URL.revokeObjectURL(Le),URL.createObjectURL(he)))}catch{B("Cover import failed.")}finally{F(!1)}}},[e,t]),T=w.useCallback(()=>{var X;const C=`Generate a cover image for this story (${h||e}) and save it as assets/cover.webp — portrait 600x900, WebP, under 1MB. Don't publish.`;(X=navigator.clipboard)==null||X.writeText(C).then(()=>{A(!0)}).catch(()=>{})},[h,e]);if(s)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"story-info-loading",children:"Loading story info…"});if(o)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load story info."});const M=I==="present"?"Cover set":I==="invalid"?"Invalid cover — re-import a WebP/JPEG under 1MB":"Missing cover",V=I==="present"?"text-green-700":I==="invalid"?"text-amber-700":"text-muted";return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"story-info-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Story Info"}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"These details appear on PlotLink when the story is published."}),d.jsxs("div",{className:"mt-4 flex flex-col gap-4 max-w-xl",children:[d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Public title"}),d.jsx("input",{type:"text",value:h,onChange:C=>{p(C.target.value),fe(!1)},"data-testid":"story-info-title",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),d.jsxs("label",{className:"flex flex-col gap-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Short description"}),d.jsx("textarea",{value:f,onChange:C=>{_(C.target.value),fe(!1)},rows:3,"data-testid":"story-info-description",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none resize-y"})]}),d.jsxs("div",{className:"flex flex-wrap gap-4",children:[d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Genre"}),d.jsxs("select",{value:x,onChange:C=>{b(C.target.value),fe(!1)},"data-testid":"story-info-genre",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[d.jsx("option",{value:"",children:"Needs metadata"}),dl.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Language"}),d.jsxs("select",{value:v,onChange:C=>{S(C.target.value),fe(!1)},"data-testid":"story-info-language",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[d.jsx("option",{value:"",children:"Needs metadata"}),ts.map(C=>d.jsx("option",{value:C,children:C},C))]})]}),d.jsxs("label",{className:"flex flex-col gap-1 min-w-[140px] flex-1",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Content type"}),d.jsx("span",{className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-surface text-muted","data-testid":"story-info-content-type",title:"Content type is locked after creation.",children:E==="cartoon"?"Cartoon · locked":"Fiction · locked"})]})]}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:"text-[11px] font-medium text-muted",children:"Cover image"}),d.jsxs("div",{className:"flex items-start gap-3",children:[G&&d.jsx("img",{src:G,alt:"Cover preview",className:"w-16 h-24 object-cover rounded border border-border"}),d.jsxs("div",{className:"flex flex-col gap-1.5",children:[d.jsx("span",{className:`text-[11px] font-medium ${V}`,"data-testid":"story-info-cover-status",children:M}),d.jsx("span",{className:"text-[10px] text-muted",children:"WebP or JPEG, max 1MB, 600×900 recommended."}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{type:"button",onClick:()=>{var C;return(C=z.current)==null?void 0:C.click()},disabled:ne,"data-testid":"story-info-import-cover",className:"rounded border border-border px-2.5 py-1 text-[11px] text-foreground hover:border-accent hover:text-accent transition-colors disabled:opacity-50",children:ne?"Importing…":"Import cover"}),d.jsx("button",{type:"button",onClick:T,"data-testid":"story-info-cover-prompt",className:"rounded border border-border px-2.5 py-1 text-[11px] text-muted hover:border-accent hover:text-accent transition-colors",children:U?"Copied!":"Ask agent for cover prompt"})]}),d.jsx("input",{ref:z,type:"file",accept:"image/*",onChange:ge,className:"hidden"})]})]})]}),d.jsxs("label",{className:"flex items-center gap-2",children:[d.jsx("input",{type:"checkbox",checked:j,onChange:C=>{D(C.target.checked),fe(!1)},"data-testid":"story-info-nsfw"}),d.jsx("span",{className:"text-xs text-foreground",children:"This story contains adult content (18+)"})]}),d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{type:"button",onClick:$,disabled:q,"data-testid":"story-info-save",className:"rounded bg-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-dim transition-colors disabled:opacity-50",children:q?"Saving…":"Save Story Info"}),ie&&d.jsx("span",{className:"text-[11px] text-green-700","data-testid":"story-info-saved",children:"Saved"}),be&&d.jsx("span",{className:"text-[11px] text-error","data-testid":"story-info-error",children:be})]})]})]})}function UM({storyName:e,authFetch:t,onOpenFile:i}){const[s,a]=w.useState(null),[o,c]=w.useState(!0);return w.useEffect(()=>{let h=!1;return(async()=>{c(!0);try{const f=await t(`/api/stories/${e}/progress`),_=f.ok?await f.json():null;h||(a(Array.isArray(_==null?void 0:_.episodes)?_.episodes:null),c(!1))}catch{h||(a(null),c(!1))}})(),()=>{h=!0}},[e,t]),o?d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"episodes-loading",children:"Loading episodes…"}):s?d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"episodes-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Episodes"}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Genesis is Episode 1; each plot file is the next episode."}),s.length===0?d.jsx("p",{className:"mt-4 text-xs text-muted italic","data-testid":"episodes-empty",children:"No episodes yet — write the Genesis to start Episode 1."}):d.jsx("ol",{className:"mt-3 flex flex-col gap-1",children:s.map(h=>d.jsx("li",{children:d.jsx("button",{onClick:()=>i(e,h.file),"data-testid":`episodes-row-${h.file}`,"data-state":h.state,className:"w-full text-left flex items-start gap-2 rounded px-2 py-1.5 hover:bg-surface",children:d.jsxs("span",{className:"min-w-0 flex-1",children:[d.jsxs("span",{className:"flex items-center gap-1.5",children:[d.jsx("span",{className:"text-xs font-medium text-foreground",children:h.label}),h.title&&d.jsxs("span",{className:"text-[11px] text-muted truncate",children:["· ",h.title]}),d.jsx("span",{className:"ml-auto text-[10px] text-muted",children:h.file})]}),d.jsx("span",{className:"block text-[11px] text-muted",children:h.summary})]})})},h.file))})]}):d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load episodes."})}function $M({storyName:e,authFetch:t,onOpenFile:i,onOpenStoryInfo:s,onPublish:a,publishingFile:o,genre:c,language:h,isNsfw:p,refreshKey:f=0}){var Ve,Et;const[_,x]=w.useState(null),[b,v]=w.useState(!0),[S,j]=w.useState(!1),[D,E]=w.useState(null),[N,I]=w.useState(null),[te,q]=w.useState(null),[R,ie]=w.useState(null),[fe,be]=w.useState(null),B=async()=>{try{const ze=await t(`/api/stories/${e}/cover-asset`),_t=ze.ok?await ze.json():null;if(!(_t!=null&&_t.found)||!_t.valid||!_t.path)return null;const Te=await t(`/api/stories/${e}/asset/${String(_t.path).replace(/^assets\//,"")}`);if(!Te.ok)return null;const Kt=await Te.blob();return new File([Kt],String(_t.path).split("/").pop()||"cover.webp",{type:_t.type||Kt.type})}catch{return null}};w.useEffect(()=>{let ze=!1;return(async()=>{v(!0),j(!1);try{const Te=await t(`/api/stories/${e}/progress`),Kt=Te.ok?await Te.json():null;if(ze)return;!Kt||!Array.isArray(Kt.episodes)?(j(!0),x(null)):x(Kt),v(!1)}catch{ze||(j(!0),x(null),v(!1))}})(),()=>{ze=!0}},[e,t,f]);const ne=((Et=(Ve=_==null?void 0:_.episodes)==null?void 0:Ve.find(ze=>!ze.published))==null?void 0:Et.file)??null,F=ne==="genesis.md",G=JSON.stringify([ne??"",f]),[Y,U]=w.useState(null);if(Y!==G&&(U(G),I(null),q(null),ie(null),be(null)),w.useEffect(()=>{if(!ne)return;let ze=!1;const _t=ne.replace(/\.md$/,"");return(async()=>{var Te;try{const Kt=[t(`/api/stories/${e}/${ne}`),t(`/api/stories/${e}/cuts/${_t}`)];F&&Kt.push(t(`/api/stories/${e}/structure.md`));const[mi,wt,et]=await Promise.all(Kt);if(ze)return;if(I(mi.ok?(await mi.json()).content??"":""),wt.ok){const Q=await wt.json();if(ze)return;q(Array.isArray(Q.cuts)?Q.cuts:[]),ie(typeof Q.title=="string"?Q.title:null)}else q(null),ie(null);be(F&&et&&et.ok?((Te=await et.json())==null?void 0:Te.content)??null:null)}catch{ze||(I(""),q(null),ie(null),be(null))}})(),()=>{ze=!0}},[ne,F,e,t,f]),b)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm","data-testid":"publish-page-loading",children:"Loading publish readiness…"});if(S||!_)return d.jsx("div",{className:"h-full flex items-center justify-center text-muted text-sm",children:"Could not load publish readiness."});const A=_.episodes.find(ze=>!ze.published);if(!A)return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsx("h2",{className:"text-base font-serif text-foreground",children:"Publish"}),d.jsx("p",{className:"mt-2 text-xs text-green-700","data-testid":"publish-all-done",children:_.episodes.length>0?"All episodes are published to PlotLink. Plan the next episode to continue.":"No episodes yet — write the Genesis (Episode 1) to begin."})]});const z=A.cuts,$=_.cover==="present",ge=[{label:"Opening text ready",status:"done"},{label:"Cut plan",status:z&&z.total>0?"done":"todo",detail:z?`${z.total} cut${z.total===1?"":"s"} planned`:"not started"},{label:"Clean images converted",status:z&&z.needClean>0&&z.withClean===z.needClean?"done":"todo",detail:z?`${z.withClean} / ${z.needClean}`:null},{label:"Cuts lettered",status:z&&z.total>0&&z.withText===z.total?"done":"todo",detail:z?`${z.withText} / ${z.total}`:null},{label:"Final images exported",status:z&&z.total>0&&z.exported===z.total?"done":"todo",detail:z?`${z.exported} / ${z.total}`:null},{label:"Final images uploaded",status:z&&z.total>0&&z.uploaded===z.total?"done":"todo",detail:z?`${z.uploaded} / ${z.total}`:null},{label:"Cover image",status:$?"done":"todo",detail:$?null:"recommended before publishing"},{label:"Publish to PlotLink",status:A.published?"done":"todo"}],T=A.state==="ready",M=A.state==="blocked",V=A.file==="genesis.md",C=!V||!!c&&!!h,X=!!o&&o===A.file,se=N!==null,le=se?Em({fileName:A.file,fileContent:N??"",storySlug:e,structureContent:fe,contentType:"cartoon",episodeTitle:R}):null,K=!!le&&Io(le,A.file),he=!V&&se&&!km({fileContent:N??"",episodeTitle:R}),_e=K||he,Me=V&&se?ym(N??""):null,Le=!!Me&&Me.blockers.length>0,He=!V&&se&&te!==null?VS(N??"",te):null,ke=He&&He.stage==="error"?He.issues:[],Je=T&&C&&(se&&(V||te!==null))&&!_e&&!Le&&!X&&!!a,at=async()=>{if(!(!Je||!a)){E(null);try{const ze=V?await B():null;await a(e,A.file,c??"",h??"",!!p,ze)}catch{E("Publish could not be started. Please try again.")}}};return d.jsxs("div",{className:"h-full overflow-y-auto px-4 py-4","data-testid":"cartoon-publish-page",children:[d.jsxs("h2",{className:"text-base font-serif text-foreground",children:["Publish ",A.label]}),d.jsx("p",{className:"mt-0.5 text-[11px] text-muted",children:"Finalize this episode: convert, letter, export, upload, then publish to PlotLink."}),d.jsx("ul",{className:"mt-3 flex flex-col gap-1.5 max-w-xl","data-testid":"publish-checklist",children:ge.map((ze,_t)=>d.jsxs("li",{className:"flex items-baseline gap-2 text-xs","data-testid":"publish-check","data-status":ze.status,children:[d.jsx("span",{className:`flex-shrink-0 ${ze.status==="done"?"text-green-700":"text-muted"}`,"aria-hidden":!0,children:ze.status==="done"?"✓":"○"}),d.jsx("span",{className:ze.status==="done"?"text-foreground":"text-muted",children:ze.label}),ze.detail&&d.jsxs("span",{className:"text-muted",children:["· ",ze.detail]})]},_t))}),le&&d.jsxs("div",{className:"mt-4 flex flex-col gap-0.5 max-w-xl","data-testid":"publish-title-preview","data-raw":K?"true":"false","data-blocked":_e?"true":"false",children:[d.jsxs("span",{className:"text-[11px] text-foreground",children:[d.jsxs("span",{className:"font-medium",children:[V?"Story title":"Episode title",":"]})," ",d.jsx("span",{className:_e?"text-error font-medium":"text-foreground",children:le})]}),K?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-raw-error",children:["This would publish as a raw filename. ",V?"Add a real “# Title” heading to genesis.md":"Set a title in the cut plan (or add a “# Title” to the episode)"," before publishing."]}):he?d.jsxs("span",{className:"text-[10px] text-error","data-testid":"publish-title-episode-required",children:["“",le,"” is a generic placeholder, not a reader-facing title, so it can’t be published. Set a real episode title in the cut plan (or add a “# Title” to the episode) — e.g. “Episode 01 — The Couple Coupon” — before publishing."]}):null]}),Me&&d.jsxs("div",{className:"mt-4 flex flex-col gap-1 rounded border border-border bg-surface/50 p-2 max-w-xl","data-testid":"cartoon-genesis-readiness","data-blocked":Le?"true":"false",children:[d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:"Story opening (Prologue)"}),d.jsx("span",{className:"text-[10px] text-muted","data-testid":"genesis-readiness-hint",children:"Genesis is the first thing readers see. Write it as the story opening/prologue, not a synopsis — set up the premise and stakes, then bridge into Episode 01."}),Me.blockers.map((ze,_t)=>d.jsx("span",{className:"text-[10px] text-error","data-testid":"genesis-readiness-blocker",children:ze},`b-${_t}`)),Me.warnings.map((ze,_t)=>d.jsx("span",{className:"text-[10px] text-amber-600","data-testid":"genesis-readiness-warning",children:ze},`w-${_t}`))]}),ke.length>0&&d.jsxs("div",{className:"mt-4 flex flex-col gap-2 rounded-xl border border-error/30 bg-error/5 px-3 py-3 max-w-xl","data-testid":"cartoon-publish-issues",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"rounded-full bg-error px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-white",children:"Before publish"}),d.jsx("span",{className:"text-xs font-medium text-foreground",children:"Finish these workflow steps"})]}),XS(ke).map(ze=>d.jsx("div",{className:"rounded-lg border border-error/15 bg-background/70 px-2.5 py-2","data-testid":`cartoon-issue-group-${ze.key}`,children:d.jsx("span",{className:"text-[11px] font-medium text-foreground",children:ze.title})},ze.key)),d.jsxs("details",{className:"text-[10px] text-muted","data-testid":"cartoon-technical-details",children:[d.jsx("summary",{className:"cursor-pointer select-none",children:"Technical details"}),d.jsx("ul",{className:"mt-1 ml-3 list-disc",children:ke.map((ze,_t)=>d.jsx("li",{className:"font-mono break-words",children:ze},_t))})]})]}),d.jsxs("div",{className:"mt-4 flex flex-col gap-2 max-w-xl",children:[!$&&d.jsx("button",{onClick:s,"data-testid":"publish-add-cover",className:"self-start rounded border border-border px-3 py-1.5 text-xs text-foreground hover:border-accent hover:text-accent transition-colors",children:"Add a cover image (Story Info)"}),V&&!C&&d.jsx("button",{onClick:s,"data-testid":"publish-set-metadata",className:"self-start rounded border border-border px-3 py-1.5 text-xs text-foreground hover:border-accent hover:text-accent transition-colors",children:"Set genre & language (Story Info)"}),!T&&d.jsxs("button",{onClick:()=>i(e,A.file),"data-testid":"publish-open-episode",className:"self-start rounded border border-accent/40 px-3 py-1.5 text-xs text-accent hover:bg-accent/5 transition-colors",children:["Open ",A.label," to finish ",M?"and fix issues":"(letter / export / upload)"]}),d.jsx("button",{onClick:at,disabled:!Je,"data-testid":"publish-cta",className:"self-start rounded bg-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-accent-dim disabled:opacity-50 transition-colors",title:Je?void 0:"Finish the remaining steps above first",children:X?"Publishing…":`Publish ${A.label} to PlotLink`}),T?C?_e||Le?d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-title-blocked-reason",children:Le?"Fix the Story opening issues above before publishing.":"Set a real reader-facing title above before publishing."}):null:d.jsx("p",{className:"text-[11px] text-amber-700","data-testid":"publish-needs-metadata",children:"Set the genre and language in Story Info before publishing."}):d.jsx("p",{className:"text-[11px] text-muted","data-testid":"publish-blocked-reason",children:M?`Not publishable yet — ${A.summary.toLowerCase()}. Open the episode to fix the flagged cuts.`:`Not ready yet — ${A.summary.toLowerCase()}.`}),D&&d.jsx("p",{className:"text-[11px] text-error","data-testid":"publish-error",children:D})]}),d.jsxs("details",{className:"mt-4 max-w-xl","data-testid":"publish-technical-details",children:[d.jsx("summary",{className:"text-[11px] text-muted cursor-pointer hover:text-foreground",children:"Technical validation details"}),d.jsxs("div",{className:"mt-1 text-[10px] text-muted space-y-0.5",children:[d.jsxs("p",{children:["Episode file: ",d.jsx("span",{className:"font-mono",children:A.file})]}),d.jsxs("p",{children:["State: ",A.state," — ",A.summary]}),d.jsx("p",{children:"Per-cut production (cut plan, clean images, lettering, export, upload) happens in the episode’s cut workspace; open it above to finish any remaining step."})]})]})]})}function FM(e,t){var s;const i=[e.plots,e.chapters].filter(Boolean);for(const a of i){let c=t!=null?a.find(p=>p.plotIndex===t||p.index===t):void 0;if(!c&&a.length===1){const p=a[0];(!(p.plotIndex!=null||p.index!=null)||t==null)&&(c=p)}const h=(s=(c==null?void 0:c.title)??(c==null?void 0:c.name))==null?void 0:s.trim();if(h)return h}}function qM(e){var o;const{fileName:t,detail:i,plotIndex:s}=e;if(!i)return{ok:!0,checked:!1};if(t==="genesis.md"){const c=(o=i.title??i.name)==null?void 0:o.trim();return c?Io(c,"genesis.md")?{ok:!1,checked:!0,publicTitle:c,reason:`PlotLink indexed the storyline title as “${c}”, a raw filename rather than the reader-facing title.`}:{ok:!0,checked:!0,publicTitle:c}:{ok:!0,checked:!1}}const a=FM(i,s);return a?Io(a,t)||Ip(a)?{ok:!1,checked:!0,publicTitle:a,reason:`PlotLink indexed the episode title as “${a}”, a generic placeholder rather than a reader-facing episode title.`}:{ok:!0,checked:!0,publicTitle:a}:{ok:!0,checked:!1}}function WM(e){return`${e.reason??"PlotLink indexed a raw/generic public title for this publish."} Published metadata is immutable on-chain and cannot be edited — the next publish must use corrected, reader-facing metadata. (The webtoon pilot stays blocked until a publish indexes a real public title.)`}const u1="plotlink-panel-ratio",GM=.6,Ey=300,If=224,Hf=6;function YM(){try{const e=localStorage.getItem(u1);if(e){const t=parseFloat(e);if(t>0&&t<1)return t}}catch{}return GM}function Ny(e,t){if(t<=0)return e;const i=Ey/t,s=1-Ey/t;return i>=s?.5:Math.min(s,Math.max(i,e))}function KM({token:e,authFetch:t}){const[i,s]=w.useState(null),[a,o]=w.useState(null),[c,h]=w.useState(null),[p,f]=w.useState(null),[_,x]=w.useState(0),[b,v]=w.useState(""),[S,j]=w.useState(null),[D,E]=w.useState(null),[N,I]=w.useState(YM),[te,q]=w.useState([]),[R,ie]=w.useState(!1),[fe,be]=w.useState(""),[B,ne]=w.useState(""),[F,G]=w.useState(""),[Y,U]=w.useState("English"),[A,z]=w.useState("normal"),[$,ge]=w.useState("claude"),[T,M]=w.useState(null),[V,C]=w.useState(!1),[X,se]=w.useState({}),[le,K]=w.useState({}),[he,_e]=w.useState(new Set),[Me,Le]=w.useState(new Set),[He,ke]=w.useState({}),[Ue,Je]=w.useState({}),[at,Ve]=w.useState({}),[Et,ze]=w.useState({}),[_t,Te]=w.useState({}),[Kt,mi]=w.useState({}),[wt,et]=w.useState(!1),[Q,xe]=w.useState(!0),je=w.useRef(new Map),$e=w.useRef(new Map),nt=w.useRef(new Map),Wt=w.useRef(new Map),ui=w.useRef(new Set),Bt=w.useRef(null),yt=w.useRef(null),Rt=w.useRef(!1);w.useEffect(()=>{t("/api/wallet").then(oe=>oe.ok?oe.json():null).then(oe=>{oe!=null&&oe.address&&E(oe.address)}).catch(()=>{})},[t]),w.useEffect(()=>{t("/api/agent/readiness").then(oe=>oe.ok?oe.json():null).then(oe=>{oe&&M(oe)}).catch(()=>{})},[t]),w.useEffect(()=>{try{localStorage.setItem(u1,String(N))}catch{}},[N]),w.useEffect(()=>{const oe=()=>{if(!yt.current)return;const O=yt.current.getBoundingClientRect().width-If-Hf;I(ce=>Ny(ce,O))};return window.addEventListener("resize",oe),oe(),()=>window.removeEventListener("resize",oe)},[]);const Qe=w.useCallback(()=>{be(""),ne(""),G(""),z("normal"),ge("claude"),ie(!0)},[]),hi=w.useCallback(async(oe,O,ce,Ee)=>{const De=fe.trim();if(!De)return;const Ne=oe==="cartoon"?"codex":Ee;try{const Pe=await t("/api/stories/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:De,description:B.trim()||void 0,language:O,genre:F||void 0,contentType:oe,agentMode:ce,agentProvider:Ne})});if(!Pe.ok)return;const We=await Pe.json();ie(!1),ke(rt=>({...rt,[We.name]:oe})),Je(rt=>({...rt,[We.name]:O})),F&&Ve(rt=>({...rt,[We.name]:F})),K(rt=>({...rt,[We.name]:Ne})),ce==="bypass"&&se(rt=>({...rt,[We.name]:!0})),s(We.name),o(null)}catch{}},[t,fe,B,F]);w.useEffect(()=>{if(te.length===0)return;const oe=setInterval(async()=>{try{const O=await t("/api/stories");if(!O.ok)return;const ce=await O.json(),Ee=new Set(ce.stories.filter(De=>De.name!=="_example").map(De=>De.name));for(const De of Ee)if(!ui.current.has(De)&&te.length>0){const Ne=te[0],Pe=je.current.get(Ne)||"fiction",We=$e.current.get(Ne)||"English",rt=nt.current.get(Ne)||"normal",Xe=Wt.current.get(Ne)||"claude";let Nt=!1;Bt.current&&(Nt=await Bt.current(Ne,De,{contentType:Pe,language:We,agentMode:rt,agentProvider:Xe}).catch(()=>!1)),Nt&&(q(jt=>jt.slice(1)),je.current.delete(Ne),$e.current.delete(Ne),nt.current.delete(Ne),Wt.current.delete(Ne),rt==="bypass"&&se(jt=>{const Gt={...jt,[De]:!0};return delete Gt[Ne],Gt}),K(jt=>{const Gt={...jt,[De]:Xe};return delete Gt[Ne],Gt}),t(`/api/stories/${De}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:Pe,language:We,agentMode:rt,agentProvider:Xe})}).catch(()=>{})),s(De),o(null)}ui.current=Ee}catch{}},3e3);return()=>clearInterval(oe)},[t,te]),w.useEffect(()=>{t("/api/stories").then(oe=>{if(oe.ok)return oe.json()}).then(oe=>{oe!=null&&oe.stories&&(ui.current=new Set(oe.stories.filter(O=>O.name!=="_example").map(O=>O.name)))}).catch(()=>{})},[t]);const H=w.useCallback((oe,O)=>{s(oe),o(O),h(null)},[]),Se=w.useRef(null),Oe=w.useCallback(async oe=>{var O,ce,Ee,De;Se.current=oe,s(oe),o(null),h(null);try{const Ne=await t(`/api/stories/${oe}`);if(Ne.ok&&Se.current===oe){const Pe=await Ne.json();if(Pe.contentType==="cartoon")return;const We=Pe.files||[],Xe=((O=We.map(Nt=>{var jt;return{file:Nt.file,num:(jt=Nt.file.match(/^plot-(\d+)\.md$/))==null?void 0:jt[1]}}).filter(Nt=>Nt.num!=null).sort((Nt,jt)=>parseInt(jt.num)-parseInt(Nt.num))[0])==null?void 0:O.file)??((ce=We.find(Nt=>Nt.file==="genesis.md"))==null?void 0:ce.file)??((Ee=We.find(Nt=>Nt.file==="structure.md"))==null?void 0:Ee.file)??((De=We[0])==null?void 0:De.file);Xe&&Se.current===oe&&o(Xe)}}catch{}},[t]),Ae=w.useCallback(oe=>{oe.preventDefault(),Rt.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const O=Ee=>{if(!Rt.current||!yt.current)return;const De=yt.current.getBoundingClientRect(),Ne=De.width-If-Hf,Pe=Ee.clientX-De.left-If;I(Ny(Pe/Ne,Ne))},ce=()=>{Rt.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",O),window.removeEventListener("mouseup",ce)};window.addEventListener("mousemove",O),window.addEventListener("mouseup",ce)},[]),Ge=w.useCallback(async(oe,O,ce,Ee,De,Ne)=>{var Xe;f(O),v("Reading file..."),j(null);let Pe=!1,We=null,rt=!1;try{const Nt=await t(`/api/stories/${oe}/${O}`);if(!Nt.ok)throw new Error("Failed to read file");const jt=await Nt.json(),Gt=He[oe];let Dt=null,ki=null;if(O==="genesis.md")try{const ei=await t(`/api/stories/${oe}/structure.md`);ei.ok&&(Dt=(await ei.json()).content??null)}catch{}else if(Gt==="cartoon"&&O.match(/^plot-\d+\.md$/))try{const ei=await t(`/api/stories/${oe}/cuts/${O.replace(/\.md$/,"")}`);ei.ok&&(ki=(await ei.json()).title??null)}catch{}const mr=Em({fileName:O,fileContent:jt.content,storySlug:oe,structureContent:Dt,contentType:Gt,episodeTitle:ki});if(Gt==="cartoon"&&Io(mr,O))return v(O==="genesis.md"?"Add a real “# Title” heading to genesis.md before publishing — it would otherwise publish as a raw filename.":"Set an episode title in the cut plan before publishing — it would otherwise publish as a raw filename."),setTimeout(()=>{f(null),v("")},6e3),!1;if(Gt==="cartoon"&&O.match(/^plot-\d+\.md$/)&&!km({fileContent:jt.content,episodeTitle:ki}))return v("Set a real episode title in the cut plan (or add a “# Title” to the episode) before publishing — a generic “Episode NN” placeholder can’t be published."),setTimeout(()=>{f(null),v("")},6e3),!1;if(Gt==="cartoon"&&O==="genesis.md"){const ei=ym(jt.content).blockers;if(ei.length>0)return v(`Genesis is the reader-facing Story opening — fix it before publishing: ${ei[0]}`),setTimeout(()=>{f(null),v("")},6e3),!1}let Jt;if(O.match(/^plot-\d+\.md$/)){if(pM(jt)){v("Already published on PlotLink — republishing would create a duplicate chapter. Open it on PlotLink instead (or use Retry Index if it isn't showing yet)."),setTimeout(()=>{f(null),v("")},6e3);return}try{const ei=await t(`/api/stories/${oe}`);if(ei.ok){const Fn=(await ei.json()).files.find(ar=>ar.file==="genesis.md"&&ar.storylineId);Jt=Fn==null?void 0:Fn.storylineId}}catch{}if(!Jt)return v("Error: Publish genesis first to create the storyline"),setTimeout(()=>{f(null),v("")},3e3),!1}v("Checking wallet balance...");try{const ei=await t("/api/publish/preflight");if(ei.ok){const Br=await ei.json();if(gM(Br))return j(xM(Br)),f(null),v(""),!1}}catch{}v("Publishing...");const qi=await t("/api/publish/file",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storyName:oe,fileName:O,title:mr,content:jt.content,genre:ce,language:Ee,isNsfw:De,storylineId:Jt,...Sy(He,oe,Jt)?{contentType:Sy(He,oe,Jt)}:{}})});if(!qi.ok){const ei=await qi.json();throw new Error(ei.error||"Publish failed")}const $n=(Xe=qi.body)==null?void 0:Xe.getReader(),gr=new TextDecoder;if($n)for(;;){const{done:ei,value:Br}=await $n.read();if(ei)break;const ar=gr.decode(Br).split(` +`).filter(Wi=>Wi.startsWith("data: "));for(const Wi of ar)try{const Ct=JSON.parse(Wi.slice(6));if(Ct.step&&v(Ct.message||Ct.step),Ct.step==="done"&&Ct.txHash){if(rt=!0,await t(`/api/stories/${oe}/${O}/publish-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({txHash:Ct.txHash,storylineId:Ct.storylineId,plotIndex:Ct.plotIndex,contentCid:Ct.contentCid,gasCost:Ct.gasCost,indexError:Ct.indexError,authorAddress:D})}),x(qn=>qn+1),Ne&&O==="genesis.md"&&Ct.storylineId){v("Uploading cover...");let qn=null;try{qn=await uM(t,Ct.storylineId,Ne)}catch{}qn||(Pe=!0)}if(Gt==="cartoon"&&Ct.storylineId)try{const qn=O!=="genesis.md",ya=`storylineId=${Ct.storylineId}`+(qn&&Ct.plotIndex!=null?`&plotIndex=${Ct.plotIndex}`:""),Lr=await t(`/api/publish/public-title?${ya}`);if(Lr.ok){const Fs=await Lr.json(),xr=qn?{plots:Fs.plotTitle!=null?[{plotIndex:Ct.plotIndex,title:Fs.plotTitle}]:[]}:{title:Fs.storylineTitle},Ei=qM({fileName:O,detail:xr,plotIndex:Ct.plotIndex});Ei.ok||(We=WM(Ei))}}catch{}}}catch{}}We&&j(We),v(Pe?"Published, but cover upload failed — set it later from Edit Story.":"Published!")}catch(Nt){const jt=Nt instanceof Error?Nt.message:"Publish failed";v(`Error: ${jt}`)}finally{setTimeout(()=>{f(null),v("")},3e3)}return rt&&!Pe},[t,He,D]),Fe=w.useCallback(oe=>{oe.startsWith("_new_")&&(q(O=>O.filter(ce=>ce!==oe)),je.current.delete(oe),$e.current.delete(oe),nt.current.delete(oe),Wt.current.delete(oe),se(O=>{if(!(oe in O))return O;const ce={...O};return delete ce[oe],ce}),K(O=>{if(!(oe in O))return O;const ce={...O};return delete ce[oe],ce}))},[]);w.useEffect(()=>{const oe=ce=>{_e(new Set(ce.filter(Xe=>Xe.hasStructure).map(Xe=>Xe.name))),Le(new Set(ce.filter(Xe=>Xe.hasGenesis).map(Xe=>Xe.name)));const Ee={},De={},Ne={},Pe={},We={},rt={};for(const Xe of ce)Ee[Xe.name]=Xe.contentType||"fiction",De[Xe.name]=Xe.language,Ne[Xe.name]=Xe.genre,Pe[Xe.name]=Xe.isNsfw,We[Xe.name]=Xe.agentProvider,Xe.title&&(rt[Xe.name]=Xe.title);ke(Ee),Je(De),Ve(Ne),ze(Pe),mi(We),Te(rt)};t("/api/stories").then(ce=>ce.ok?ce.json():null).then(ce=>{ce!=null&&ce.stories&&oe(ce.stories)}).catch(()=>{});const O=setInterval(async()=>{try{const ce=await t("/api/stories");if(ce.ok){const Ee=await ce.json();oe(Ee.stories)}}catch{}},5e3);return()=>clearInterval(O)},[t]);const dt=!!T&&T.codex.installed&&T.codex.imageGeneration==="enabled",ft=!!T&&!dt,ct=w.useCallback(async()=>{try{await navigator.clipboard.writeText("codex features enable image_generation"),C(!0),setTimeout(()=>C(!1),2e3)}catch{}},[]),Vt=w.useCallback(async()=>{if(!i||i.startsWith("_new_"))return;const oe=i;if((await t(`/api/stories/${oe}/metadata`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contentType:"cartoon",agentProvider:"codex"})})).ok){mi(ce=>({...ce,[oe]:"codex"})),K(ce=>({...ce,[oe]:"codex"}));try{const ce=await t("/api/stories");if(ce.ok){const Ee=await ce.json();if(Ee!=null&&Ee.stories){const De={};for(const Ne of Ee.stories)De[Ne.name]=Ne.agentProvider;mi(De)}}}catch{}}},[t,i]),Ci=w.useCallback(oe=>{i===oe&&(s(null),o(null))},[i]),pt=i?le[i]??Kt[i]:void 0,Fi=Of(i,He,je.current),Nn=mM(Fi,pt,i),ln=!!i&&Fi==="cartoon",Un=c==="story-info"?"story-info":c==="episodes"?"episodes":c==="publish"?"publish":a==="structure.md"?"whitepaper":a==="genesis.md"?"genesis":a&&/^plot-\d+\.md$/.test(a)?"episodes":"progress",on=w.useCallback(oe=>{const O=i;if(O)switch(oe){case"progress":h(null),o(null);break;case"story-info":h("story-info");break;case"episodes":h("episodes");break;case"whitepaper":H(O,"structure.md");break;case"genesis":H(O,"genesis.md");break;case"publish":h("publish");break}},[i,H]),xn=w.useCallback((oe,O)=>{const ce=i;if(ce)switch(oe){case"view-progress":h(null),o(null);break;case"publish":h("publish");break;case"open-cuts":case"open-lettering":case"upload":case"refresh-assets":case"generate-markdown":O&&H(ce,O);break}},[i,H]),cn=w.useCallback(oe=>{i&&(oe.genre!==void 0&&Ve(O=>({...O,[i]:oe.genre||void 0})),oe.language!==void 0&&Je(O=>({...O,[i]:oe.language||void 0})),oe.isNsfw!==void 0&&ze(O=>({...O,[i]:oe.isNsfw})))},[i]),pr=w.useCallback(oe=>{et(oe),xe(!oe)},[]),Lt=wt&&!Q;return d.jsxs("div",{ref:yt,className:"h-[calc(100vh-3.5rem)] flex","data-testid":Lt?"stories-focused-lettering-mode":"stories-default-layout",children:[!Lt&&d.jsx("div",{className:"w-56 border-r border-border flex-shrink-0",children:d.jsx(DC,{authFetch:t,selectedStory:i,selectedFile:a,onSelectFile:H,onNewStory:Qe,untitledSessions:te})}),!Lt&&d.jsx("div",{className:"min-w-0 border-r border-border",style:{flex:`${N} 0 0`},children:d.jsx(rN,{token:e,storyName:i,authFetch:t,onSelectStory:Oe,onDestroySession:Fe,onArchiveStory:Ci,confirmedStories:he,renameRef:Bt,bypassStories:X,agentProviders:le,readiness:T,contentType:Of(i,He,je.current),needsProviderRepair:Nn,onRepairProvider:Vt})}),!Lt&&d.jsx("div",{onMouseDown:Ae,className:"flex-shrink-0 flex items-center justify-center hover:bg-border/50 transition-colors",style:{width:Hf,cursor:"col-resize",background:"var(--border)"},children:d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}}),d.jsx("div",{className:"w-0.5 h-0.5 rounded-full",style:{background:"var(--text-muted)"}})]})}),d.jsxs("div",{className:"min-w-0 min-h-0 flex flex-col",style:Lt?{flex:"1 0 0"}:{flex:`${1-N} 0 0`},children:[!wt&&ln&&i&&d.jsx(IM,{storyTitle:_t[i]||i,active:Un,onSelect:on}),!wt&&ln&&i&&c!==null&&d.jsx("div",{className:"flex-shrink-0 border-b border-border","data-testid":"workflow-context-next-action",children:d.jsx(kM,{storyName:i,authFetch:t,refreshKey:_,onCoachAction:xn,onOpenStoryInfo:()=>h("story-info")})}),d.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:ln&&c==="story-info"&&i?d.jsx(HM,{storyName:i,authFetch:t,onSaved:cn}):ln&&c==="episodes"&&i?d.jsx(UM,{storyName:i,authFetch:t,onOpenFile:H}):ln&&c==="publish"&&i?d.jsx($M,{storyName:i,authFetch:t,onOpenFile:H,onOpenStoryInfo:()=>h("story-info"),onPublish:Ge,publishingFile:p,genre:at[i],language:Ue[i],isNsfw:Et[i],refreshKey:_}):i&&!a?d.jsx(NM,{storyName:i,authFetch:t,onOpenFile:H,onOpenStoryInfo:()=>h("story-info")}):d.jsx(SM,{storyName:i,fileName:a,authFetch:t,onPublish:Ge,publishingFile:p,walletAddress:D,contentType:Of(i,He,je.current)||"fiction",language:i?Ue[i]:void 0,genre:i?at[i]:void 0,isNsfw:i?Et[i]:void 0,hasGenesis:i?Me.has(i):!1,onViewProgress:()=>o(null),onOpenFile:oe=>i&&H(i,oe),onViewPublish:()=>h("publish"),focusedLetteringMode:wt,focusedLetteringWorkspaceVisible:Q,onFocusedLetteringModeChange:pr,onFocusedLetteringWorkspaceVisibleChange:xe})}),b&&d.jsx("div",{className:"shrink-0 px-3 py-1.5 bg-surface border-t border-border text-xs text-muted",children:b}),S&&d.jsxs("div",{className:"shrink-0 px-3 py-2 bg-error/10 border-t border-error/40 text-xs text-error flex items-start justify-between gap-3","data-testid":"publish-block-error",role:"alert",children:[d.jsx("span",{children:S}),d.jsx("button",{type:"button",onClick:()=>j(null),className:"shrink-0 text-error/70 hover:text-error underline","data-testid":"publish-block-error-dismiss",children:"Dismiss"})]})]}),R&&d.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(240, 235, 225, 0.9)"},children:d.jsxs("div",{className:"bg-surface border border-border rounded-lg shadow-lg p-6 max-w-sm w-full space-y-4",children:[d.jsx("h3",{className:"text-sm font-serif font-medium text-foreground text-center",children:"New Story"}),d.jsxs("label",{className:"block space-y-1",children:[d.jsxs("span",{className:"text-[10px] font-medium text-muted",children:["Title ",d.jsx("span",{className:"text-accent",children:"*"})]}),d.jsx("input",{type:"text",value:fe,onChange:oe=>be(oe.target.value),placeholder:"e.g. 신의 세포","data-testid":"new-story-title",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Short description (optional)"}),d.jsx("input",{type:"text",value:B,onChange:oe=>ne(oe.target.value),placeholder:"One line about the story","data-testid":"new-story-description",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none"})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Genre (optional)"}),d.jsxs("select",{value:F,onChange:oe=>G(oe.target.value),"data-testid":"new-story-genre",className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:[d.jsx("option",{value:"",children:"— Select later —"}),dl.map(oe=>d.jsx("option",{value:oe,children:oe},oe))]})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Language"}),d.jsx("select",{value:Y,onChange:oe=>U(oe.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none",children:ts.map(oe=>d.jsx("option",{value:oe,children:oe},oe))})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Agent mode"}),d.jsxs("select",{value:A,onChange:oe=>z(oe.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"agent-mode-select",children:[d.jsx("option",{value:"normal",children:"Normal (approve each action)"}),d.jsx("option",{value:"bypass",children:"Permissions Bypass (advanced)"})]}),A==="bypass"&&d.jsx("p",{className:"text-[10px] text-amber-700","data-testid":"agent-mode-warning",children:"Less safe: Claude can run actions without per-command approval."})]}),d.jsxs("label",{className:"block space-y-1",children:[d.jsx("span",{className:"text-[10px] font-medium text-muted",children:"Provider"}),d.jsxs("select",{value:$,onChange:oe=>ge(oe.target.value),className:"w-full px-2 py-1.5 text-xs border border-border rounded bg-transparent focus:border-accent focus:outline-none","data-testid":"agent-provider-select",children:[d.jsx("option",{value:"claude",children:"🤖 Claude (default)"}),d.jsx("option",{value:"codex",children:"🎨 Codex"})]}),d.jsx("p",{className:"text-[10px] text-muted","data-testid":"agent-provider-helper",children:$==="codex"?"Codex can generate clean cartoon images directly in the terminal.":"Claude prepares image prompts; you generate and upload clean images externally."})]}),d.jsx("p",{className:"text-xs text-muted text-center",children:"Choose a content type to create"}),!fe.trim()&&d.jsx("p",{className:"text-[10px] text-amber-700 text-center","data-testid":"new-story-title-required",children:"Enter a title to create your story."}),d.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[d.jsxs("button",{onClick:()=>hi("fiction",Y,A,$),disabled:!fe.trim(),"data-testid":"create-fiction",className:"border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Fiction"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Novels, short stories, poetry"})]}),d.jsxs("div",{className:"space-y-1",children:[d.jsxs("button",{onClick:()=>hi("cartoon",Y,A,"codex"),disabled:ft||!fe.trim(),"data-testid":"create-cartoon",className:"w-full border border-border rounded-lg p-4 hover:border-accent hover:bg-accent/5 transition-colors text-center space-y-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:bg-transparent",children:[d.jsx("p",{className:"text-sm font-serif font-medium text-foreground",children:"Cartoon"}),d.jsx("p",{className:"text-[11px] text-muted",children:"Comics, manga, webtoons"}),d.jsx("p",{className:"text-[11px] text-muted","data-testid":"cartoon-codex-note",children:"Cartoon mode requires Codex because the clean-image step needs image generation support."})]}),T&&!T.codex.installed&&d.jsxs("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-warning",children:["Codex was not detected. Install the Codex CLI and sign in (e.g."," ",d.jsx("span",{className:"font-mono",children:"npm i -g @openai/codex"})," ","then ",d.jsx("span",{className:"font-mono",children:"codex login"}),") to create cartoons."]}),Eu(T)&&d.jsx("p",{className:"text-[11px] text-amber-700 text-left","data-testid":"cartoon-codex-auth-unknown",children:Up}),T&&T.codex.installed&&!Eu(T)&&T.codex.imageGeneration!=="enabled"&&d.jsxs("div",{"data-testid":"cartoon-codex-warning",children:[d.jsx("p",{className:"text-[11px] text-amber-700 text-left",children:"Codex is installed but image generation isn't enabled. Enable it, then reopen this dialog:"}),d.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[d.jsx("code",{className:"flex-1 truncate rounded border border-border bg-surface px-1.5 py-1 text-left text-[10px] font-mono text-foreground",children:"codex features enable image_generation"}),d.jsx("button",{type:"button","data-testid":"copy-codex-enable",onClick:ct,className:"rounded border border-border px-2 py-1 text-[10px] text-muted hover:border-accent hover:text-accent transition-colors",children:V?"Copied!":"Copy"})]})]})]})]}),d.jsx("button",{onClick:()=>ie(!1),className:"w-full px-3 py-1.5 text-xs text-muted hover:text-foreground hover:bg-surface rounded text-center",children:"Cancel"})]})})]})}function VM({token:e,onComplete:t}){const[i,s]=w.useState(!1),[a,o]=w.useState(null),[c,h]=w.useState(!1),p=async()=>{s(!0),o(null);try{const f=await fetch("/api/wallet/create",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}),_=await f.json();if(!f.ok)throw new Error(_.error||"Wallet creation failed");h(!0)}catch(f){o(f instanceof Error?f.message:"Wallet creation failed")}s(!1)};return w.useEffect(()=>{p()},[]),d.jsxs("div",{className:"mx-auto max-w-sm p-6 text-center",children:[d.jsx("h2",{className:"text-accent mb-1 text-lg font-bold",children:"Wallet Setup"}),d.jsx("p",{className:"text-muted mb-6 text-xs",children:"creating your OWS wallet for on-chain publishing"}),i&&d.jsx("p",{className:"text-accent text-sm",children:"creating wallet..."}),a&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"rounded border border-red-700/30 p-3 text-xs text-red-700",children:a}),d.jsx("button",{onClick:p,className:"border-accent text-accent hover:bg-accent/10 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:"retry"})]}),c&&d.jsxs("div",{className:"space-y-4",children:[d.jsx("div",{className:"text-accent text-2xl",children:"✓"}),d.jsx("p",{className:"text-foreground text-sm font-medium",children:"wallet created"}),d.jsx("button",{onClick:t,className:"border-accent text-accent hover:bg-accent/10 w-full rounded border px-4 py-2 text-sm font-medium transition-colors",children:"continue"})]})]})}function XM({token:e,onLogout:t}){const[i,s]=w.useState("home"),[a,o]=w.useState(0),[c,h]=w.useState(null),p=w.useCallback(async(f,_)=>fetch(f,{..._,headers:{...(_==null?void 0:_.headers)||{},Authorization:`Bearer ${e}`}}),[e]);return w.useEffect(()=>{fetch("/api/health").then(f=>f.json()).then(f=>{f.version&&h(f.version)}).catch(()=>{})},[]),w.useEffect(()=>{async function f(){try{if(!(await(await p("/api/wallet")).json()).exists){s("wallet-setup");return}const b=await p("/api/stories");if(b.ok){const v=await b.json();o(v.stories.filter(S=>S.name!=="_example").length)}}catch{}}f()},[e]),d.jsxs("div",{className:"flex h-screen flex-col",children:[d.jsxs("header",{className:"border-border flex h-14 items-center justify-between border-b px-4 flex-shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-3",children:[d.jsx("button",{onClick:()=>{i!=="wallet-setup"&&s("home")},className:"flex items-center gap-2 hover:opacity-80",children:d.jsx("span",{className:"text-accent text-sm font-bold tracking-tight",children:"PlotLink OWS"})}),d.jsxs("span",{className:"text-muted text-[10px] uppercase tracking-wider",children:["writer",c?` v${c}`:""]})]}),i!=="wallet-setup"&&d.jsxs("nav",{className:"flex items-center gap-4",children:[d.jsx("button",{onClick:()=>s("stories"),className:`text-xs transition-colors ${i==="stories"?"text-accent":"text-muted hover:text-foreground"}`,children:"stories"}),d.jsx("button",{onClick:()=>s("dashboard"),className:`text-xs transition-colors ${i==="dashboard"?"text-accent":"text-muted hover:text-foreground"}`,children:"dashboard"}),d.jsx("button",{onClick:()=>s("settings"),className:`text-xs transition-colors ${i==="settings"?"text-accent":"text-muted hover:text-foreground"}`,children:"settings"}),d.jsx("button",{onClick:t,className:"text-muted hover:text-foreground text-xs transition-colors",children:"logout"})]})]}),d.jsxs("main",{className:"flex-1 min-h-0",children:[i==="home"&&d.jsxs("div",{className:"mx-auto max-w-lg space-y-6 p-8",children:[d.jsxs("div",{className:"text-center space-y-2",children:[d.jsx("h1",{className:"text-2xl font-serif text-foreground",children:"Write. Publish. Earn."}),d.jsx("p",{className:"text-muted text-sm",children:"Claude or Codex helps create your story. You publish it on-chain."})]}),d.jsxs("div",{className:"text-center space-y-3",children:[d.jsx("button",{onClick:()=>s("stories"),className:"bg-accent text-white hover:bg-accent-dim px-6 py-2.5 rounded text-sm font-medium transition-colors",children:"Start Writing"}),a>0&&d.jsxs("p",{className:"text-muted text-xs",children:[a," ",a===1?"story":"stories"," in progress"]})]}),d.jsxs("div",{className:"rounded border border-border p-4 space-y-2 text-xs text-muted",children:[d.jsx("p",{className:"font-medium text-foreground text-sm",children:"How it works"}),d.jsxs("ol",{className:"space-y-1.5 list-decimal list-inside",children:[d.jsxs("li",{children:["Open the ",d.jsx("strong",{children:"Stories"})," tab — your writing agent launches in the terminal"]}),d.jsx("li",{children:"Tell the agent your story idea — it brainstorms, outlines, and writes"}),d.jsx("li",{children:"Review the live preview as the agent creates files"}),d.jsxs("li",{children:["Click ",d.jsx("strong",{children:"Publish"})," to put your story on-chain"]}),d.jsxs("li",{children:["Earn 5% royalties on every trade at ",d.jsx("a",{href:"https://plotlink.xyz",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline",children:"plotlink.xyz"})]})]}),d.jsx("p",{className:"text-[11px] text-muted",children:"Fiction defaults to Claude; cartoon mode uses Codex for clean-image generation."})]}),d.jsx("div",{className:"text-center",children:d.jsx("a",{href:"https://github.com/realproject7/plotlink-ows#-wallet-setup",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted hover:text-accent underline transition-colors",children:"Wallet Setup Guide"})}),d.jsx(Ry,{token:e})]}),i==="stories"&&d.jsx(KM,{token:e,authFetch:p}),i==="dashboard"&&d.jsx(TC,{token:e}),i==="wallet-setup"&&d.jsx(VM,{token:e,onComplete:()=>s("home")}),i==="settings"&&d.jsx(NC,{token:e,onLogout:t})]})]})}function ZM(){const[e,t]=w.useState(()=>localStorage.getItem("ows-token")),[i,s]=w.useState(null),[a,o]=w.useState(!0);w.useEffect(()=>{fetch("/api/auth/status").then(f=>f.json()).then(f=>s(f.configured)).catch(()=>s(null))},[]),w.useEffect(()=>{if(!e){o(!1);return}fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${e}`}}).then(f=>{f.ok||(localStorage.removeItem("ows-token"),t(null))}).catch(()=>{localStorage.removeItem("ows-token"),t(null)}).finally(()=>o(!1))},[e]);const c=async f=>{try{const _=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),x=await _.json();return _.ok?(localStorage.setItem("ows-token",x.token),t(x.token),null):x.error||"Login failed"}catch{return"Cannot connect to server"}},h=async f=>{try{const _=await fetch("/api/auth/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({passphrase:f})}),x=await _.json();return _.ok?(localStorage.setItem("ows-token",x.token),t(x.token),s(!0),null):x.error||"Setup failed"}catch{return"Cannot connect to server"}},p=()=>{localStorage.removeItem("ows-token"),t(null)};return a||i===null?d.jsx("div",{className:"flex h-screen items-center justify-center",children:d.jsx("span",{className:"text-muted text-sm",children:"connecting..."})}):i?e?d.jsx(XM,{token:e,onLogout:p}):d.jsx(kC,{onLogin:c}):d.jsx(EC,{onSetup:h})}CC.createRoot(document.getElementById("root")).render(d.jsx(gC.StrictMode,{children:d.jsx(ZM,{})}));export{zp as M,No as a,US as b,UD as c,U3 as d,Eo as l,bm as s,GS as t,i4 as v}; diff --git a/app/web/dist/assets/index-MOqpTOzP.css b/app/web/dist/assets/index-Bi-xodT8.css similarity index 55% rename from app/web/dist/assets/index-MOqpTOzP.css rename to app/web/dist/assets/index-Bi-xodT8.css index b389744..18b935c 100644 --- a/app/web/dist/assets/index-MOqpTOzP.css +++ b/app/web/dist/assets/index-Bi-xodT8.css @@ -29,4 +29,4 @@ * The original design remains. The terminal itself * has been extended to include xterm CSI codes, among * other features. - */.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;-webkit-user-select:text;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-serif:ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-700:oklch(50.5% .213 27.518);--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-300:oklch(87.9% .169 91.605);--color-amber-500:oklch(76.9% .188 70.08);--color-amber-600:oklch(66.6% .179 58.318);--color-amber-700:oklch(55.5% .163 48.998);--color-amber-800:oklch(47.3% .137 46.201);--color-amber-950:oklch(27.9% .077 45.635);--color-green-50:oklch(98.2% .018 155.826);--color-green-100:oklch(96.2% .044 156.743);--color-green-300:oklch(87.1% .15 154.449);--color-green-600:oklch(62.7% .194 149.214);--color-green-700:oklch(52.7% .154 150.069);--color-green-800:oklch(44.8% .119 151.328);--color-green-950:oklch(26.6% .065 152.934);--color-white:#fff;--spacing:.25rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-xl:36rem;--container-2xl:42rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wider:.05em;--leading-tight:1.25;--leading-relaxed:1.625;--radius-md:.375rem;--radius-lg:.5rem;--radius-xl:.75rem;--aspect-video:16 / 9;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent;font-family:Inter,system-ui,-apple-system,sans-serif;line-height:1.5}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.pointer-events-none{pointer-events:none}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing) * 0)}.start{inset-inline-start:var(--spacing)}.start\!{inset-inline-start:var(--spacing)!important}.end{inset-inline-end:var(--spacing)}.-top-1\.5{top:calc(var(--spacing) * -1.5)}.top-1{top:calc(var(--spacing) * 1)}.-right-1\.5{right:calc(var(--spacing) * -1.5)}.right-0{right:calc(var(--spacing) * 0)}.right-1{right:calc(var(--spacing) * 1)}.bottom-0{bottom:calc(var(--spacing) * 0)}.z-10{z-index:10}.z-50{z-index:50}.container{width:100%}@media(min-width:40rem){.container{max-width:40rem}}@media(min-width:48rem){.container{max-width:48rem}}@media(min-width:64rem){.container{max-width:64rem}}@media(min-width:80rem){.container{max-width:80rem}}@media(min-width:96rem){.container{max-width:96rem}}.m-3{margin:calc(var(--spacing) * 3)}.-mx-1{margin-inline:calc(var(--spacing) * -1)}.mx-auto{margin-inline:auto}.prose{color:var(--tw-prose-body);max-width:65ch}.prose :where(p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where([class~=lead]):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-lead);margin-top:1.2em;margin-bottom:1.2em;font-size:1.25em;line-height:1.6}.prose :where(a):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-links);font-weight:500;text-decoration:underline}.prose :where(strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-bold);font-weight:600}.prose :where(a strong):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(blockquote strong):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(thead th strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(ol):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em;list-style-type:decimal}.prose :where(ol[type=A]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=A s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=I]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type=I s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type="1"]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:decimal}.prose :where(ul):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em;list-style-type:disc}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{color:var(--tw-prose-counters);font-weight:400}.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{color:var(--tw-prose-bullets)}.prose :where(dt):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.25em;font-weight:600}.prose :where(hr):not(:where([class~=not-prose],[class~=not-prose] *)){border-color:var(--tw-prose-hr);border-top-width:1px;margin-top:3em;margin-bottom:3em}.prose :where(blockquote):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-quotes);border-inline-start-width:.25rem;border-inline-start-color:var(--tw-prose-quote-borders);quotes:"“""”""‘""’";margin-top:1.6em;margin-bottom:1.6em;padding-inline-start:1em;font-style:italic;font-weight:500}.prose :where(blockquote p:first-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):before{content:open-quote}.prose :where(blockquote p:last-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:close-quote}.prose :where(h1):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:0;margin-bottom:.888889em;font-size:2.25em;font-weight:800;line-height:1.11111}.prose :where(h1 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:900}.prose :where(h2):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:2em;margin-bottom:1em;font-size:1.5em;font-weight:700;line-height:1.33333}.prose :where(h2 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:800}.prose :where(h3):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.6em;margin-bottom:.6em;font-size:1.25em;font-weight:600;line-height:1.6}.prose :where(h3 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:700}.prose :where(h4):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.5em;margin-bottom:.5em;font-weight:600;line-height:1.5}.prose :where(h4 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:700}.prose :where(img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(picture):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em;display:block}.prose :where(video):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(kbd):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-kbd);box-shadow:0 0 0 1px var(--tw-prose-kbd-shadows),0 3px 0 var(--tw-prose-kbd-shadows);padding-top:.1875em;padding-inline-end:.375em;padding-bottom:.1875em;border-radius:.3125rem;padding-inline-start:.375em;font-family:inherit;font-size:.875em;font-weight:500}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-code);font-size:.875em;font-weight:600}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):before,.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:"`"}.prose :where(a code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h1 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(h2 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.875em}.prose :where(h3 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.9em}.prose :where(h4 code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(blockquote code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(thead th code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(pre):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-pre-code);background-color:var(--tw-prose-pre-bg);padding-top:.857143em;padding-inline-end:1.14286em;padding-bottom:.857143em;border-radius:.375rem;margin-top:1.71429em;margin-bottom:1.71429em;padding-inline-start:1.14286em;font-size:.875em;font-weight:400;line-height:1.71429;overflow-x:auto}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)){font-weight:inherit;color:inherit;font-size:inherit;font-family:inherit;line-height:inherit;background-color:#0000;border-width:0;border-radius:0;padding:0}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):before,.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:none}.prose :where(table):not(:where([class~=not-prose],[class~=not-prose] *)){table-layout:auto;width:100%;margin-top:2em;margin-bottom:2em;font-size:.875em;line-height:1.71429}.prose :where(thead):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-th-borders)}.prose :where(thead th):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);vertical-align:bottom;padding-inline-end:.571429em;padding-bottom:.571429em;padding-inline-start:.571429em;font-weight:600}.prose :where(tbody tr):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-td-borders)}.prose :where(tbody tr:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:0}.prose :where(tbody td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:baseline}.prose :where(tfoot):not(:where([class~=not-prose],[class~=not-prose] *)){border-top-width:1px;border-top-color:var(--tw-prose-th-borders)}.prose :where(tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:top}.prose :where(th,td):not(:where([class~=not-prose],[class~=not-prose] *)){text-align:start}.prose :where(figure>*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(figcaption):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-captions);margin-top:.857143em;font-size:.875em;line-height:1.42857}.prose{--tw-prose-body:oklch(37.3% .034 259.733);--tw-prose-headings:oklch(21% .034 264.665);--tw-prose-lead:oklch(44.6% .03 256.802);--tw-prose-links:oklch(21% .034 264.665);--tw-prose-bold:oklch(21% .034 264.665);--tw-prose-counters:oklch(55.1% .027 264.364);--tw-prose-bullets:oklch(87.2% .01 258.338);--tw-prose-hr:oklch(92.8% .006 264.531);--tw-prose-quotes:oklch(21% .034 264.665);--tw-prose-quote-borders:oklch(92.8% .006 264.531);--tw-prose-captions:oklch(55.1% .027 264.364);--tw-prose-kbd:oklch(21% .034 264.665);--tw-prose-kbd-shadows:oklab(21% -.00316127 -.0338527/.1);--tw-prose-code:oklch(21% .034 264.665);--tw-prose-pre-code:oklch(92.8% .006 264.531);--tw-prose-pre-bg:oklch(27.8% .033 256.848);--tw-prose-th-borders:oklch(87.2% .01 258.338);--tw-prose-td-borders:oklch(92.8% .006 264.531);--tw-prose-invert-body:oklch(87.2% .01 258.338);--tw-prose-invert-headings:#fff;--tw-prose-invert-lead:oklch(70.7% .022 261.325);--tw-prose-invert-links:#fff;--tw-prose-invert-bold:#fff;--tw-prose-invert-counters:oklch(70.7% .022 261.325);--tw-prose-invert-bullets:oklch(44.6% .03 256.802);--tw-prose-invert-hr:oklch(37.3% .034 259.733);--tw-prose-invert-quotes:oklch(96.7% .003 264.542);--tw-prose-invert-quote-borders:oklch(37.3% .034 259.733);--tw-prose-invert-captions:oklch(70.7% .022 261.325);--tw-prose-invert-kbd:#fff;--tw-prose-invert-kbd-shadows:#ffffff1a;--tw-prose-invert-code:#fff;--tw-prose-invert-pre-code:oklch(87.2% .01 258.338);--tw-prose-invert-pre-bg:#00000080;--tw-prose-invert-th-borders:oklch(44.6% .03 256.802);--tw-prose-invert-td-borders:oklch(37.3% .034 259.733);font-size:1rem;line-height:1.75}.prose :where(picture>img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(li):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;margin-bottom:.5em}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:.375em}.prose :where(.prose>ul>li p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(.prose>ul>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ul>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(.prose>ol>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ol>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(ul ul,ul ol,ol ul,ol ol):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(dl):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where(dd):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;padding-inline-start:1.625em}.prose :where(hr+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h2+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h3+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h4+*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(thead th:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(thead th:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(tbody td,tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){padding-top:.571429em;padding-inline-end:.571429em;padding-bottom:.571429em;padding-inline-start:.571429em}.prose :where(tbody td:first-child,tfoot td:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(tbody td:last-child,tfoot td:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(figure):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(.prose>:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(.prose>:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:0}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:calc(var(--spacing) * 1)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-1\.5{margin-bottom:calc(var(--spacing) * 1.5)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.ml-0\.5{margin-left:calc(var(--spacing) * .5)}.ml-1{margin-left:calc(var(--spacing) * 1)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-3{margin-left:calc(var(--spacing) * 3)}.ml-auto{margin-left:auto}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.table{display:table}.aspect-video{aspect-ratio:var(--aspect-video)}.h-0\.5{height:calc(var(--spacing) * .5)}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-2{height:calc(var(--spacing) * 2)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-14{height:calc(var(--spacing) * 14)}.h-16{height:calc(var(--spacing) * 16)}.h-24{height:calc(var(--spacing) * 24)}.h-\[calc\(100vh-3\.5rem\)\]{height:calc(100vh - 3.5rem)}.h-full{height:100%}.h-screen{height:100vh}.max-h-72{max-height:calc(var(--spacing) * 72)}.max-h-\[32rem\]{max-height:32rem}.min-h-0{min-height:calc(var(--spacing) * 0)}.min-h-28{min-height:calc(var(--spacing) * 28)}.min-h-56{min-height:calc(var(--spacing) * 56)}.min-h-\[22rem\]{min-height:22rem}.w-0\.5{width:calc(var(--spacing) * .5)}.w-1\.5{width:calc(var(--spacing) * 1.5)}.w-2{width:calc(var(--spacing) * 2)}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-14{width:calc(var(--spacing) * 14)}.w-16{width:calc(var(--spacing) * 16)}.w-56{width:calc(var(--spacing) * 56)}.w-64{width:calc(var(--spacing) * 64)}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-\[32rem\]{max-width:32rem}.max-w-\[120px\]{max-width:120px}.max-w-lg{max-width:var(--container-lg)}.max-w-md{max-width:var(--container-md)}.max-w-none{max-width:none}.max-w-sm{max-width:var(--container-sm)}.max-w-xl{max-width:var(--container-xl)}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-\[140px\]{min-width:140px}.flex-1{flex:1}.flex-shrink-0{flex-shrink:0}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.cursor-move{cursor:move}.cursor-pointer{cursor:pointer}.cursor-se-resize{cursor:se-resize}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1.5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1.5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}.gap-x-3{column-gap:calc(var(--spacing) * 3)}.gap-y-0\.5{row-gap:calc(var(--spacing) * .5)}.gap-y-1{row-gap:calc(var(--spacing) * 1)}.self-start{align-self:flex-start}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-xl{border-radius:var(--radius-xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-accent{border-color:#8b4513}.border-accent-dim\/30{border-color:#6b34104d}.border-accent\/30{border-color:#8b45134d}.border-accent\/40{border-color:#8b451366}.border-amber-300{border-color:var(--color-amber-300)}.border-amber-500{border-color:var(--color-amber-500)}.border-amber-500\/40{border-color:#f99c0066}@supports (color:color-mix(in lab,red,red)){.border-amber-500\/40{border-color:color-mix(in oklab,var(--color-amber-500) 40%,transparent)}}.border-amber-500\/50{border-color:#f99c0080}@supports (color:color-mix(in lab,red,red)){.border-amber-500\/50{border-color:color-mix(in oklab,var(--color-amber-500) 50%,transparent)}}.border-amber-600\/30{border-color:#dd74004d}@supports (color:color-mix(in lab,red,red)){.border-amber-600\/30{border-color:color-mix(in oklab,var(--color-amber-600) 30%,transparent)}}.border-border{border-color:#d4c5b0}.border-border\/70{border-color:#d4c5b0b3}.border-border\/80{border-color:#d4c5b0cc}.border-error\/15{border-color:#cc333326}.border-error\/30{border-color:#cc33334d}.border-error\/40{border-color:#c336}.border-foreground\/40{border-color:#2c181066}.border-green-300{border-color:var(--color-green-300)}.border-green-700\/25{border-color:#00813840}@supports (color:color-mix(in lab,red,red)){.border-green-700\/25{border-color:color-mix(in oklab,var(--color-green-700) 25%,transparent)}}.border-green-700\/30{border-color:#0081384d}@supports (color:color-mix(in lab,red,red)){.border-green-700\/30{border-color:color-mix(in oklab,var(--color-green-700) 30%,transparent)}}.border-green-700\/40{border-color:#00813866}@supports (color:color-mix(in lab,red,red)){.border-green-700\/40{border-color:color-mix(in oklab,var(--color-green-700) 40%,transparent)}}.border-muted\/40{border-color:#8b735566}.border-red-700\/30{border-color:#bf000f4d}@supports (color:color-mix(in lab,red,red)){.border-red-700\/30{border-color:color-mix(in oklab,var(--color-red-700) 30%,transparent)}}.border-transparent{border-color:#0000}.bg-\[\#f4efe6\]\/85{background-color:#f4efe6d9}.bg-\[\#f8f5ef\]{background-color:#f8f5ef}.bg-accent{background-color:#8b4513}.bg-accent\/5{background-color:#8b45130d}.bg-accent\/10{background-color:#8b45131a}.bg-amber-50{background-color:var(--color-amber-50)}.bg-amber-100{background-color:var(--color-amber-100)}.bg-amber-500{background-color:var(--color-amber-500)}.bg-amber-500\/10{background-color:#f99c001a}@supports (color:color-mix(in lab,red,red)){.bg-amber-500\/10{background-color:color-mix(in oklab,var(--color-amber-500) 10%,transparent)}}.bg-amber-950\/10{background-color:#4619011a}@supports (color:color-mix(in lab,red,red)){.bg-amber-950\/10{background-color:color-mix(in oklab,var(--color-amber-950) 10%,transparent)}}.bg-background{background-color:#e8dfd0}.bg-background\/40{background-color:#e8dfd066}.bg-background\/50{background-color:#e8dfd080}.bg-background\/60{background-color:#e8dfd099}.bg-background\/70{background-color:#e8dfd0b3}.bg-error{background-color:#c33}.bg-error\/5{background-color:#cc33330d}.bg-error\/10{background-color:#cc33331a}.bg-foreground{background-color:#2c1810}.bg-green-50{background-color:var(--color-green-50)}.bg-green-100{background-color:var(--color-green-100)}.bg-green-600{background-color:var(--color-green-600)}.bg-green-600\/10{background-color:#00a5441a}@supports (color:color-mix(in lab,red,red)){.bg-green-600\/10{background-color:color-mix(in oklab,var(--color-green-600) 10%,transparent)}}.bg-green-700\/10{background-color:#0081381a}@supports (color:color-mix(in lab,red,red)){.bg-green-700\/10{background-color:color-mix(in oklab,var(--color-green-700) 10%,transparent)}}.bg-green-950\/5{background-color:#032e150d}@supports (color:color-mix(in lab,red,red)){.bg-green-950\/5{background-color:color-mix(in oklab,var(--color-green-950) 5%,transparent)}}.bg-muted\/40{background-color:#8b735566}.bg-muted\/50{background-color:#8b735580}.bg-surface{background-color:#f0ebe1}.bg-surface\/35{background-color:#f0ebe159}.bg-surface\/40{background-color:#f0ebe166}.bg-surface\/50{background-color:#f0ebe180}.bg-surface\/60{background-color:#f0ebe199}.bg-surface\/70{background-color:#f0ebe1b3}.bg-surface\/80{background-color:#f0ebe1cc}.bg-surface\/95{background-color:#f0ebe1f2}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.fill-white\/95{fill:#fffffff2}@supports (color:color-mix(in lab,red,red)){.fill-white\/95{fill:color-mix(in oklab,var(--color-white) 95%,transparent)}}.stroke-\[\#1a1a1a\]{stroke:#1a1a1a}.stroke-accent{stroke:#8b4513}.object-contain{object-fit:contain}.object-cover{object-fit:cover}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:calc(var(--spacing) * 1)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-6{padding-block:calc(var(--spacing) * 6)}.pt-1\.5{padding-top:calc(var(--spacing) * 1.5)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pr-16{padding-right:calc(var(--spacing) * 16)}.pb-1{padding-bottom:calc(var(--spacing) * 1)}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pl-3{padding-left:calc(var(--spacing) * 3)}.pl-4{padding-left:calc(var(--spacing) * 4)}.text-center{text-align:center}.text-left{text-align:left}.font-mono{font-family:var(--font-mono)}.font-sans{font-family:var(--font-sans)}.font-serif{font-family:var(--font-serif)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[9px\]{font-size:9px}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.leading-none{--tw-leading:1;line-height:1}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-\[0\.14em\]{--tw-tracking:.14em;letter-spacing:.14em}.tracking-\[0\.16em\]{--tw-tracking:.16em;letter-spacing:.16em}.tracking-\[0\.18em\]{--tw-tracking:.18em;letter-spacing:.18em}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wider{--tw-tracking:var(--tracking-wider);letter-spacing:var(--tracking-wider)}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-\[\#1a1a1a\]{color:#1a1a1a}.text-\[\#3a3a3a\]{color:#3a3a3a}.text-accent{color:#8b4513}.text-accent-dim{color:#6b3410}.text-amber-600{color:var(--color-amber-600)}.text-amber-700{color:var(--color-amber-700)}.text-amber-800{color:var(--color-amber-800)}.text-background{color:#e8dfd0}.text-error{color:#c33}.text-error\/70{color:#cc3333b3}.text-foreground{color:#2c1810}.text-green-700{color:var(--color-green-700)}.text-green-800{color:var(--color-green-800)}.text-muted{color:#8b7355}.text-muted\/70{color:#8b7355b3}.text-red-700{color:var(--color-red-700)}.text-white{color:var(--color-white)}.uppercase{text-transform:uppercase}.italic{font-style:italic}.overline{text-decoration-line:overline}.underline{text-decoration-line:underline}.opacity-90{opacity:.9}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-2{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-accent{--tw-ring-color:#8b4513}.ring-amber-500{--tw-ring-color:var(--color-amber-500)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.placeholder\:text-muted\/50::placeholder{color:#8b735580}@media(hover:hover){.hover\:border-accent:hover{border-color:#8b4513}.hover\:border-error:hover{border-color:#c33}.hover\:bg-accent-dim:hover{background-color:#6b3410}.hover\:bg-accent\/5:hover{background-color:#8b45130d}.hover\:bg-accent\/10:hover{background-color:#8b45131a}.hover\:bg-amber-500\/20:hover{background-color:#f99c0033}@supports (color:color-mix(in lab,red,red)){.hover\:bg-amber-500\/20:hover{background-color:color-mix(in oklab,var(--color-amber-500) 20%,transparent)}}.hover\:bg-border\/50:hover{background-color:#d4c5b080}.hover\:bg-error\/5:hover{background-color:#cc33330d}.hover\:bg-error\/10:hover{background-color:#cc33331a}.hover\:bg-green-700\/5:hover{background-color:#0081380d}@supports (color:color-mix(in lab,red,red)){.hover\:bg-green-700\/5:hover{background-color:color-mix(in oklab,var(--color-green-700) 5%,transparent)}}.hover\:bg-surface:hover{background-color:#f0ebe1}.hover\:text-accent:hover{color:#8b4513}.hover\:text-accent-dim:hover{color:#6b3410}.hover\:text-error:hover{color:#c33}.hover\:text-foreground:hover{color:#2c1810}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-80:hover{opacity:.8}}.focus\:border-accent:focus{border-color:#8b4513}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}@media(hover:hover){.disabled\:hover\:border-border:disabled:hover{border-color:#d4c5b0}.disabled\:hover\:bg-transparent:disabled:hover{background-color:#0000}}@media(min-width:40rem){.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}}:root{--bg:#e8dfd0;--bg-surface:#f0ebe1;--bg-shelf:#ddd3c2;--text:#2c1810;--text-muted:#8b7355;--accent:#8b4513;--accent-dim:#6b3410;--border:#d4c5b0;--error:#c33;--paper-bg:#f5f0e8}body{background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:Inter,system-ui,-apple-system,sans-serif}::selection{background:var(--accent);color:#fff}h1,h2,h3,h4{font-family:Lora,Georgia,Times New Roman,serif}.prose{--tw-prose-body:var(--text);--tw-prose-headings:var(--text);--tw-prose-links:var(--accent);--tw-prose-bold:var(--text);--tw-prose-quotes:var(--text-muted);--tw-prose-quote-borders:var(--border);--tw-prose-code:var(--text);--tw-prose-hr:var(--border)}.prose,.prose p,.prose li,.prose blockquote{font-family:Lora,Georgia,Times New Roman,serif}code,pre{font-family:Geist Mono,ui-monospace,monospace}.cartoon-awaiting-upload{border-color:var(--accent)}@supports (color:color-mix(in lab,red,red)){.cartoon-awaiting-upload{border-color:color-mix(in srgb,var(--accent) 30%,transparent)}}.cartoon-awaiting-upload{background:var(--accent)}@supports (color:color-mix(in lab,red,red)){.cartoon-awaiting-upload{background:color-mix(in srgb,var(--accent) 5%,transparent)}}.xterm .xterm-dim{opacity:1!important;color:#8b7355!important}.xterm,.xterm-viewport{border:none!important;outline:none!important}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false} + */.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;-webkit-user-select:text;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-serif:ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-700:oklch(50.5% .213 27.518);--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-300:oklch(87.9% .169 91.605);--color-amber-500:oklch(76.9% .188 70.08);--color-amber-600:oklch(66.6% .179 58.318);--color-amber-700:oklch(55.5% .163 48.998);--color-amber-800:oklch(47.3% .137 46.201);--color-amber-950:oklch(27.9% .077 45.635);--color-green-50:oklch(98.2% .018 155.826);--color-green-100:oklch(96.2% .044 156.743);--color-green-300:oklch(87.1% .15 154.449);--color-green-600:oklch(62.7% .194 149.214);--color-green-700:oklch(52.7% .154 150.069);--color-green-800:oklch(44.8% .119 151.328);--color-green-950:oklch(26.6% .065 152.934);--color-white:#fff;--spacing:.25rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-xl:36rem;--container-2xl:42rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wider:.05em;--leading-tight:1.25;--leading-relaxed:1.625;--radius-md:.375rem;--radius-lg:.5rem;--radius-xl:.75rem;--aspect-video:16 / 9;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent;font-family:Inter,system-ui,-apple-system,sans-serif;line-height:1.5}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.pointer-events-none{pointer-events:none}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing) * 0)}.start{inset-inline-start:var(--spacing)}.start\!{inset-inline-start:var(--spacing)!important}.end{inset-inline-end:var(--spacing)}.-top-1\.5{top:calc(var(--spacing) * -1.5)}.top-1{top:calc(var(--spacing) * 1)}.-right-1\.5{right:calc(var(--spacing) * -1.5)}.right-0{right:calc(var(--spacing) * 0)}.right-1{right:calc(var(--spacing) * 1)}.bottom-0{bottom:calc(var(--spacing) * 0)}.z-10{z-index:10}.z-50{z-index:50}.container{width:100%}@media(min-width:40rem){.container{max-width:40rem}}@media(min-width:48rem){.container{max-width:48rem}}@media(min-width:64rem){.container{max-width:64rem}}@media(min-width:80rem){.container{max-width:80rem}}@media(min-width:96rem){.container{max-width:96rem}}.m-3{margin:calc(var(--spacing) * 3)}.-mx-1{margin-inline:calc(var(--spacing) * -1)}.mx-auto{margin-inline:auto}.prose{color:var(--tw-prose-body);max-width:65ch}.prose :where(p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where([class~=lead]):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-lead);margin-top:1.2em;margin-bottom:1.2em;font-size:1.25em;line-height:1.6}.prose :where(a):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-links);font-weight:500;text-decoration:underline}.prose :where(strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-bold);font-weight:600}.prose :where(a strong):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(blockquote strong):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(thead th strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(ol):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em;list-style-type:decimal}.prose :where(ol[type=A]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=A s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-alpha}.prose :where(ol[type=a s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-alpha}.prose :where(ol[type=I]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type=I s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:upper-roman}.prose :where(ol[type=i s]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:lower-roman}.prose :where(ol[type="1"]):not(:where([class~=not-prose],[class~=not-prose] *)){list-style-type:decimal}.prose :where(ul):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em;padding-inline-start:1.625em;list-style-type:disc}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{color:var(--tw-prose-counters);font-weight:400}.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *))::marker{color:var(--tw-prose-bullets)}.prose :where(dt):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.25em;font-weight:600}.prose :where(hr):not(:where([class~=not-prose],[class~=not-prose] *)){border-color:var(--tw-prose-hr);border-top-width:1px;margin-top:3em;margin-bottom:3em}.prose :where(blockquote):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-quotes);border-inline-start-width:.25rem;border-inline-start-color:var(--tw-prose-quote-borders);quotes:"“""”""‘""’";margin-top:1.6em;margin-bottom:1.6em;padding-inline-start:1em;font-style:italic;font-weight:500}.prose :where(blockquote p:first-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):before{content:open-quote}.prose :where(blockquote p:last-of-type):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:close-quote}.prose :where(h1):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:0;margin-bottom:.888889em;font-size:2.25em;font-weight:800;line-height:1.11111}.prose :where(h1 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:900}.prose :where(h2):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:2em;margin-bottom:1em;font-size:1.5em;font-weight:700;line-height:1.33333}.prose :where(h2 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:800}.prose :where(h3):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.6em;margin-bottom:.6em;font-size:1.25em;font-weight:600;line-height:1.6}.prose :where(h3 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:700}.prose :where(h4):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);margin-top:1.5em;margin-bottom:.5em;font-weight:600;line-height:1.5}.prose :where(h4 strong):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-weight:700}.prose :where(img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(picture):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em;display:block}.prose :where(video):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(kbd):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-kbd);box-shadow:0 0 0 1px var(--tw-prose-kbd-shadows),0 3px 0 var(--tw-prose-kbd-shadows);padding-top:.1875em;padding-inline-end:.375em;padding-bottom:.1875em;border-radius:.3125rem;padding-inline-start:.375em;font-family:inherit;font-size:.875em;font-weight:500}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-code);font-size:.875em;font-weight:600}.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):before,.prose :where(code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:"`"}.prose :where(a code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h1 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(h2 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.875em}.prose :where(h3 code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit;font-size:.9em}.prose :where(h4 code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(blockquote code):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(thead th code):not(:where([class~=not-prose],[class~=not-prose] *)){color:inherit}.prose :where(pre):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-pre-code);background-color:var(--tw-prose-pre-bg);padding-top:.857143em;padding-inline-end:1.14286em;padding-bottom:.857143em;border-radius:.375rem;margin-top:1.71429em;margin-bottom:1.71429em;padding-inline-start:1.14286em;font-size:.875em;font-weight:400;line-height:1.71429;overflow-x:auto}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)){font-weight:inherit;color:inherit;font-size:inherit;font-family:inherit;line-height:inherit;background-color:#0000;border-width:0;border-radius:0;padding:0}.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):before,.prose :where(pre code):not(:where([class~=not-prose],[class~=not-prose] *)):after{content:none}.prose :where(table):not(:where([class~=not-prose],[class~=not-prose] *)){table-layout:auto;width:100%;margin-top:2em;margin-bottom:2em;font-size:.875em;line-height:1.71429}.prose :where(thead):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-th-borders)}.prose :where(thead th):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-headings);vertical-align:bottom;padding-inline-end:.571429em;padding-bottom:.571429em;padding-inline-start:.571429em;font-weight:600}.prose :where(tbody tr):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:1px;border-bottom-color:var(--tw-prose-td-borders)}.prose :where(tbody tr:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){border-bottom-width:0}.prose :where(tbody td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:baseline}.prose :where(tfoot):not(:where([class~=not-prose],[class~=not-prose] *)){border-top-width:1px;border-top-color:var(--tw-prose-th-borders)}.prose :where(tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){vertical-align:top}.prose :where(th,td):not(:where([class~=not-prose],[class~=not-prose] *)){text-align:start}.prose :where(figure>*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(figcaption):not(:where([class~=not-prose],[class~=not-prose] *)){color:var(--tw-prose-captions);margin-top:.857143em;font-size:.875em;line-height:1.42857}.prose{--tw-prose-body:oklch(37.3% .034 259.733);--tw-prose-headings:oklch(21% .034 264.665);--tw-prose-lead:oklch(44.6% .03 256.802);--tw-prose-links:oklch(21% .034 264.665);--tw-prose-bold:oklch(21% .034 264.665);--tw-prose-counters:oklch(55.1% .027 264.364);--tw-prose-bullets:oklch(87.2% .01 258.338);--tw-prose-hr:oklch(92.8% .006 264.531);--tw-prose-quotes:oklch(21% .034 264.665);--tw-prose-quote-borders:oklch(92.8% .006 264.531);--tw-prose-captions:oklch(55.1% .027 264.364);--tw-prose-kbd:oklch(21% .034 264.665);--tw-prose-kbd-shadows:oklab(21% -.00316127 -.0338527/.1);--tw-prose-code:oklch(21% .034 264.665);--tw-prose-pre-code:oklch(92.8% .006 264.531);--tw-prose-pre-bg:oklch(27.8% .033 256.848);--tw-prose-th-borders:oklch(87.2% .01 258.338);--tw-prose-td-borders:oklch(92.8% .006 264.531);--tw-prose-invert-body:oklch(87.2% .01 258.338);--tw-prose-invert-headings:#fff;--tw-prose-invert-lead:oklch(70.7% .022 261.325);--tw-prose-invert-links:#fff;--tw-prose-invert-bold:#fff;--tw-prose-invert-counters:oklch(70.7% .022 261.325);--tw-prose-invert-bullets:oklch(44.6% .03 256.802);--tw-prose-invert-hr:oklch(37.3% .034 259.733);--tw-prose-invert-quotes:oklch(96.7% .003 264.542);--tw-prose-invert-quote-borders:oklch(37.3% .034 259.733);--tw-prose-invert-captions:oklch(70.7% .022 261.325);--tw-prose-invert-kbd:#fff;--tw-prose-invert-kbd-shadows:#ffffff1a;--tw-prose-invert-code:#fff;--tw-prose-invert-pre-code:oklch(87.2% .01 258.338);--tw-prose-invert-pre-bg:#00000080;--tw-prose-invert-th-borders:oklch(44.6% .03 256.802);--tw-prose-invert-td-borders:oklch(37.3% .034 259.733);font-size:1rem;line-height:1.75}.prose :where(picture>img):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0;margin-bottom:0}.prose :where(li):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;margin-bottom:.5em}.prose :where(ol>li):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(ul>li):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:.375em}.prose :where(.prose>ul>li p):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(.prose>ul>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ul>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(.prose>ol>li>p:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em}.prose :where(.prose>ol>li>p:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:1.25em}.prose :where(ul ul,ul ol,ol ul,ol ol):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.75em;margin-bottom:.75em}.prose :where(dl):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:1.25em;margin-bottom:1.25em}.prose :where(dd):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:.5em;padding-inline-start:1.625em}.prose :where(hr+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h2+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h3+*):not(:where([class~=not-prose],[class~=not-prose] *)),.prose :where(h4+*):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(thead th:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(thead th:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(tbody td,tfoot td):not(:where([class~=not-prose],[class~=not-prose] *)){padding-top:.571429em;padding-inline-end:.571429em;padding-bottom:.571429em;padding-inline-start:.571429em}.prose :where(tbody td:first-child,tfoot td:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-start:0}.prose :where(tbody td:last-child,tfoot td:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){padding-inline-end:0}.prose :where(figure):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:2em;margin-bottom:2em}.prose :where(.prose>:first-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-top:0}.prose :where(.prose>:last-child):not(:where([class~=not-prose],[class~=not-prose] *)){margin-bottom:0}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:calc(var(--spacing) * 1)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-1\.5{margin-bottom:calc(var(--spacing) * 1.5)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.ml-0\.5{margin-left:calc(var(--spacing) * .5)}.ml-1{margin-left:calc(var(--spacing) * 1)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-3{margin-left:calc(var(--spacing) * 3)}.ml-auto{margin-left:auto}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.table{display:table}.aspect-video{aspect-ratio:var(--aspect-video)}.h-0\.5{height:calc(var(--spacing) * .5)}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-2{height:calc(var(--spacing) * 2)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-14{height:calc(var(--spacing) * 14)}.h-16{height:calc(var(--spacing) * 16)}.h-24{height:calc(var(--spacing) * 24)}.h-\[calc\(100vh-3\.5rem\)\]{height:calc(100vh - 3.5rem)}.h-full{height:100%}.h-screen{height:100vh}.max-h-72{max-height:calc(var(--spacing) * 72)}.min-h-0{min-height:calc(var(--spacing) * 0)}.min-h-28{min-height:calc(var(--spacing) * 28)}.min-h-56{min-height:calc(var(--spacing) * 56)}.min-h-\[22rem\]{min-height:22rem}.w-0\.5{width:calc(var(--spacing) * .5)}.w-1\.5{width:calc(var(--spacing) * 1.5)}.w-2{width:calc(var(--spacing) * 2)}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-14{width:calc(var(--spacing) * 14)}.w-16{width:calc(var(--spacing) * 16)}.w-56{width:calc(var(--spacing) * 56)}.w-64{width:calc(var(--spacing) * 64)}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-\[32rem\]{max-width:32rem}.max-w-\[120px\]{max-width:120px}.max-w-lg{max-width:var(--container-lg)}.max-w-md{max-width:var(--container-md)}.max-w-none{max-width:none}.max-w-sm{max-width:var(--container-sm)}.max-w-xl{max-width:var(--container-xl)}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-\[140px\]{min-width:140px}.flex-1{flex:1}.flex-shrink-0{flex-shrink:0}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.cursor-move{cursor:move}.cursor-pointer{cursor:pointer}.cursor-se-resize{cursor:se-resize}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1.5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1.5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}.gap-x-3{column-gap:calc(var(--spacing) * 3)}.gap-y-0\.5{row-gap:calc(var(--spacing) * .5)}.gap-y-1{row-gap:calc(var(--spacing) * 1)}.self-start{align-self:flex-start}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-xl{border-radius:var(--radius-xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-accent{border-color:#8b4513}.border-accent-dim\/30{border-color:#6b34104d}.border-accent\/30{border-color:#8b45134d}.border-accent\/40{border-color:#8b451366}.border-amber-300{border-color:var(--color-amber-300)}.border-amber-500{border-color:var(--color-amber-500)}.border-amber-500\/40{border-color:#f99c0066}@supports (color:color-mix(in lab,red,red)){.border-amber-500\/40{border-color:color-mix(in oklab,var(--color-amber-500) 40%,transparent)}}.border-amber-500\/50{border-color:#f99c0080}@supports (color:color-mix(in lab,red,red)){.border-amber-500\/50{border-color:color-mix(in oklab,var(--color-amber-500) 50%,transparent)}}.border-amber-600\/30{border-color:#dd74004d}@supports (color:color-mix(in lab,red,red)){.border-amber-600\/30{border-color:color-mix(in oklab,var(--color-amber-600) 30%,transparent)}}.border-border{border-color:#d4c5b0}.border-border\/70{border-color:#d4c5b0b3}.border-border\/80{border-color:#d4c5b0cc}.border-error\/15{border-color:#cc333326}.border-error\/30{border-color:#cc33334d}.border-error\/40{border-color:#c336}.border-foreground\/40{border-color:#2c181066}.border-green-300{border-color:var(--color-green-300)}.border-green-700\/25{border-color:#00813840}@supports (color:color-mix(in lab,red,red)){.border-green-700\/25{border-color:color-mix(in oklab,var(--color-green-700) 25%,transparent)}}.border-green-700\/30{border-color:#0081384d}@supports (color:color-mix(in lab,red,red)){.border-green-700\/30{border-color:color-mix(in oklab,var(--color-green-700) 30%,transparent)}}.border-green-700\/40{border-color:#00813866}@supports (color:color-mix(in lab,red,red)){.border-green-700\/40{border-color:color-mix(in oklab,var(--color-green-700) 40%,transparent)}}.border-muted\/40{border-color:#8b735566}.border-red-700\/30{border-color:#bf000f4d}@supports (color:color-mix(in lab,red,red)){.border-red-700\/30{border-color:color-mix(in oklab,var(--color-red-700) 30%,transparent)}}.border-transparent{border-color:#0000}.bg-\[\#f4efe6\]\/85{background-color:#f4efe6d9}.bg-\[\#f8f5ef\]{background-color:#f8f5ef}.bg-accent{background-color:#8b4513}.bg-accent\/5{background-color:#8b45130d}.bg-accent\/10{background-color:#8b45131a}.bg-amber-50{background-color:var(--color-amber-50)}.bg-amber-100{background-color:var(--color-amber-100)}.bg-amber-500{background-color:var(--color-amber-500)}.bg-amber-500\/10{background-color:#f99c001a}@supports (color:color-mix(in lab,red,red)){.bg-amber-500\/10{background-color:color-mix(in oklab,var(--color-amber-500) 10%,transparent)}}.bg-amber-950\/10{background-color:#4619011a}@supports (color:color-mix(in lab,red,red)){.bg-amber-950\/10{background-color:color-mix(in oklab,var(--color-amber-950) 10%,transparent)}}.bg-background{background-color:#e8dfd0}.bg-background\/40{background-color:#e8dfd066}.bg-background\/50{background-color:#e8dfd080}.bg-background\/60{background-color:#e8dfd099}.bg-background\/70{background-color:#e8dfd0b3}.bg-error{background-color:#c33}.bg-error\/5{background-color:#cc33330d}.bg-error\/10{background-color:#cc33331a}.bg-foreground{background-color:#2c1810}.bg-green-50{background-color:var(--color-green-50)}.bg-green-100{background-color:var(--color-green-100)}.bg-green-600{background-color:var(--color-green-600)}.bg-green-600\/10{background-color:#00a5441a}@supports (color:color-mix(in lab,red,red)){.bg-green-600\/10{background-color:color-mix(in oklab,var(--color-green-600) 10%,transparent)}}.bg-green-700\/10{background-color:#0081381a}@supports (color:color-mix(in lab,red,red)){.bg-green-700\/10{background-color:color-mix(in oklab,var(--color-green-700) 10%,transparent)}}.bg-green-950\/5{background-color:#032e150d}@supports (color:color-mix(in lab,red,red)){.bg-green-950\/5{background-color:color-mix(in oklab,var(--color-green-950) 5%,transparent)}}.bg-muted\/40{background-color:#8b735566}.bg-muted\/50{background-color:#8b735580}.bg-surface{background-color:#f0ebe1}.bg-surface\/35{background-color:#f0ebe159}.bg-surface\/40{background-color:#f0ebe166}.bg-surface\/50{background-color:#f0ebe180}.bg-surface\/60{background-color:#f0ebe199}.bg-surface\/70{background-color:#f0ebe1b3}.bg-surface\/80{background-color:#f0ebe1cc}.bg-surface\/95{background-color:#f0ebe1f2}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.fill-white\/95{fill:#fffffff2}@supports (color:color-mix(in lab,red,red)){.fill-white\/95{fill:color-mix(in oklab,var(--color-white) 95%,transparent)}}.stroke-\[\#1a1a1a\]{stroke:#1a1a1a}.stroke-accent{stroke:#8b4513}.object-contain{object-fit:contain}.object-cover{object-fit:cover}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:calc(var(--spacing) * 1)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-6{padding-block:calc(var(--spacing) * 6)}.pt-1\.5{padding-top:calc(var(--spacing) * 1.5)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pr-16{padding-right:calc(var(--spacing) * 16)}.pb-1{padding-bottom:calc(var(--spacing) * 1)}.pb-3{padding-bottom:calc(var(--spacing) * 3)}.pl-3{padding-left:calc(var(--spacing) * 3)}.pl-4{padding-left:calc(var(--spacing) * 4)}.text-center{text-align:center}.text-left{text-align:left}.font-mono{font-family:var(--font-mono)}.font-sans{font-family:var(--font-sans)}.font-serif{font-family:var(--font-serif)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[9px\]{font-size:9px}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.leading-none{--tw-leading:1;line-height:1}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-\[0\.14em\]{--tw-tracking:.14em;letter-spacing:.14em}.tracking-\[0\.16em\]{--tw-tracking:.16em;letter-spacing:.16em}.tracking-\[0\.18em\]{--tw-tracking:.18em;letter-spacing:.18em}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wider{--tw-tracking:var(--tracking-wider);letter-spacing:var(--tracking-wider)}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-\[\#1a1a1a\]{color:#1a1a1a}.text-\[\#3a3a3a\]{color:#3a3a3a}.text-accent{color:#8b4513}.text-accent-dim{color:#6b3410}.text-amber-600{color:var(--color-amber-600)}.text-amber-700{color:var(--color-amber-700)}.text-amber-800{color:var(--color-amber-800)}.text-background{color:#e8dfd0}.text-error{color:#c33}.text-error\/70{color:#cc3333b3}.text-foreground{color:#2c1810}.text-green-700{color:var(--color-green-700)}.text-green-800{color:var(--color-green-800)}.text-muted{color:#8b7355}.text-muted\/70{color:#8b7355b3}.text-red-700{color:var(--color-red-700)}.text-white{color:var(--color-white)}.uppercase{text-transform:uppercase}.italic{font-style:italic}.overline{text-decoration-line:overline}.underline{text-decoration-line:underline}.opacity-90{opacity:.9}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-2{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-accent{--tw-ring-color:#8b4513}.ring-amber-500{--tw-ring-color:var(--color-amber-500)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.placeholder\:text-muted\/50::placeholder{color:#8b735580}@media(hover:hover){.hover\:border-accent:hover{border-color:#8b4513}.hover\:border-error:hover{border-color:#c33}.hover\:bg-accent-dim:hover{background-color:#6b3410}.hover\:bg-accent\/5:hover{background-color:#8b45130d}.hover\:bg-accent\/10:hover{background-color:#8b45131a}.hover\:bg-amber-500\/20:hover{background-color:#f99c0033}@supports (color:color-mix(in lab,red,red)){.hover\:bg-amber-500\/20:hover{background-color:color-mix(in oklab,var(--color-amber-500) 20%,transparent)}}.hover\:bg-border\/50:hover{background-color:#d4c5b080}.hover\:bg-error\/5:hover{background-color:#cc33330d}.hover\:bg-error\/10:hover{background-color:#cc33331a}.hover\:bg-green-700\/5:hover{background-color:#0081380d}@supports (color:color-mix(in lab,red,red)){.hover\:bg-green-700\/5:hover{background-color:color-mix(in oklab,var(--color-green-700) 5%,transparent)}}.hover\:bg-surface:hover{background-color:#f0ebe1}.hover\:text-accent:hover{color:#8b4513}.hover\:text-accent-dim:hover{color:#6b3410}.hover\:text-error:hover{color:#c33}.hover\:text-foreground:hover{color:#2c1810}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-80:hover{opacity:.8}}.focus\:border-accent:focus{border-color:#8b4513}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}@media(hover:hover){.disabled\:hover\:border-border:disabled:hover{border-color:#d4c5b0}.disabled\:hover\:bg-transparent:disabled:hover{background-color:#0000}}@media(min-width:40rem){.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}}:root{--bg:#e8dfd0;--bg-surface:#f0ebe1;--bg-shelf:#ddd3c2;--text:#2c1810;--text-muted:#8b7355;--accent:#8b4513;--accent-dim:#6b3410;--border:#d4c5b0;--error:#c33;--paper-bg:#f5f0e8}body{background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:Inter,system-ui,-apple-system,sans-serif}::selection{background:var(--accent);color:#fff}h1,h2,h3,h4{font-family:Lora,Georgia,Times New Roman,serif}.prose{--tw-prose-body:var(--text);--tw-prose-headings:var(--text);--tw-prose-links:var(--accent);--tw-prose-bold:var(--text);--tw-prose-quotes:var(--text-muted);--tw-prose-quote-borders:var(--border);--tw-prose-code:var(--text);--tw-prose-hr:var(--border)}.prose,.prose p,.prose li,.prose blockquote{font-family:Lora,Georgia,Times New Roman,serif}code,pre{font-family:Geist Mono,ui-monospace,monospace}.cartoon-awaiting-upload{border-color:var(--accent)}@supports (color:color-mix(in lab,red,red)){.cartoon-awaiting-upload{border-color:color-mix(in srgb,var(--accent) 30%,transparent)}}.cartoon-awaiting-upload{background:var(--accent)}@supports (color:color-mix(in lab,red,red)){.cartoon-awaiting-upload{background:color-mix(in srgb,var(--accent) 5%,transparent)}}.xterm .xterm-dim{opacity:1!important;color:#8b7355!important}.xterm,.xterm-viewport{border:none!important;outline:none!important}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false} diff --git a/app/web/dist/index.html b/app/web/dist/index.html index 945db14..44e4479 100644 --- a/app/web/dist/index.html +++ b/app/web/dist/index.html @@ -7,8 +7,8 @@ - - + +