@casys/mcp-erpnext 2.5.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -145,7 +145,7 @@ Boolean requesting whether a visible border and background is provided by the ho
145
145
  - omitted: host decides border`)});P({method:E("ui/request-display-mode"),params:P({mode:So.describe("The display mode being requested.")})});var b4=P({mode:So.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),x4=Se([E("model"),E("app")]).describe("Tool visibility scope - who can access the tool.");P({resourceUri:j().optional(),visibility:pe(x4).optional().describe(`Who can access this tool. Default: ["model", "app"]
146
146
  - "model": Tool visible to and callable by the agent
147
147
  - "app": Tool callable by the app from this server only`),csp:wr().optional(),permissions:wr().optional()});P({mimeTypes:pe(j()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')});P({method:E("ui/download-file"),params:P({contents:pe(Se([wS,bS])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})});P({method:E("ui/message"),params:P({role:E("user").describe('Message role, currently only "user" is supported.'),content:pe(ba).describe("Message content blocks (text, image, etc.).")})});P({method:E("ui/notifications/sandbox-resource-ready"),params:P({html:j().describe("HTML content to load into the inner iframe."),sandbox:j().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:nm.optional().describe("CSP configuration from resource metadata."),permissions:rm.optional().describe("Sandbox permissions from resource metadata.")})});var I4=P({method:E("ui/notifications/tool-result"),params:ou.describe("Standard MCP tool execution result.")}),TS=P({toolInfo:P({id:ya.optional().describe("JSON-RPC id of the tools/call request."),tool:tm.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:c4.optional().describe("Current color theme preference."),styles:$4.optional().describe("Style configuration for theming the app."),displayMode:So.optional().describe("How the UI is currently displayed."),availableDisplayModes:pe(So).optional().describe("Display modes the host supports."),containerDimensions:Se([P({height:ye().describe("Fixed container height in pixels.")}),P({maxHeight:Se([ye(),ui()]).optional().describe("Maximum container height in pixels.")})]).and(Se([P({width:ye().describe("Fixed container width in pixels.")}),P({maxWidth:Se([ye(),ui()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
148
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:j().optional().describe("User's language and region preference in BCP 47 format."),timeZone:j().optional().describe("User's timezone in IANA format."),userAgent:j().optional().describe("Host application identifier."),platform:Se([E("web"),E("desktop"),E("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:P({touch:Oe().optional().describe("Whether the device supports touch input."),hover:Oe().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:P({top:ye().describe("Top safe area inset in pixels."),right:ye().describe("Right safe area inset in pixels."),bottom:ye().describe("Bottom safe area inset in pixels."),left:ye().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),z4=P({method:E("ui/notifications/host-context-changed"),params:TS.describe("Partial context update containing only changed fields.")});P({method:E("ui/update-model-context"),params:P({content:pe(ba).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:ze(j(),Ne().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})});P({method:E("ui/initialize"),params:P({appInfo:ru.describe("App identification (name and version)."),appCapabilities:w4.describe("Features and capabilities this app provides."),protocolVersion:j().describe("Protocol version this app supports.")})});var E4=P({protocolVersion:j().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:ru.describe("Host application identification and version."),hostCapabilities:S4.describe("Features and capabilities provided by the host."),hostContext:TS.describe("Rich context about the host environment.")}).passthrough(),j4={target:"draft-2020-12"};async function Mv(e,r){let o=e["~standard"];if(o.jsonSchema)return o.jsonSchema[r](j4);if(o.vendor==="zod"){let{z:s}=await qb(()=>Promise.resolve().then(()=>v1),void 0,import.meta.url);return s.toJSONSchema(e,{io:r})}throw Error(`Schema (vendor: ${o.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function Zv(e,r,o=""){let s=await e["~standard"].validate(r);if(s.issues){let n=s.issues.map(a=>{let u=a.path?.map(f=>typeof f=="object"?f.key:f).join(".");return u?`${u}: ${a.message}`:a.message}).join("; ");throw Error(o+n)}return s.value}class im extends a4{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(r){if(this._initializedSent)return;let o=`[ext-apps] App.${r}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(o);console.warn(`${o}. This will throw in a future release.`)}eventSchemas={toolinput:h4,toolinputpartial:v4,toolresult:I4,toolcancelled:y4,hostcontextchanged:z4};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(r){if(!im.ONE_SHOT_EVENTS.has(r)||this._everHadListener.has(r)||(this._everHadListener.add(r),!this._initializedSent))return;let o=`[ext-apps] "${String(r)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(o);console.warn(o)}setEventHandler(r,o){o&&this._assertHandlerTiming(r),super.setEventHandler(r,o)}addEventListener(r,o){this._assertHandlerTiming(r),super.addEventListener(r,o)}onEventDispatch(r,o){r==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...o})}constructor(r,o={},s={autoResize:!0}){super(s),this._appInfo=r,this._capabilities=o,this.options=s,s.allowUnsafeEval||lt({jitless:!0}),this.setRequestHandler(iu,n=>(console.log("Received ping:",n.params),{})),this.setEventHandler("hostcontextchanged",void 0)}registerCapabilities(r){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._capabilities=o4(this._capabilities,r)}registerTool(r,o,s){if(this._registeredTools[r])throw Error(`Tool ${r} is already registered`);let n=this,a=()=>{n._initializedSent&&n._capabilities.tools?.listChanged&&n.sendToolListChanged()},u=o.inputSchema!==void 0,f={title:o.title,description:o.description,inputSchema:o.inputSchema,outputSchema:o.outputSchema,annotations:o.annotations,_meta:o._meta,enabled:!0,enable(){this.enabled=!0,a()},disable(){this.enabled=!1,a()},update(h){Object.assign(this,h),a()},remove(){n._registeredTools[r]===f&&(delete n._registeredTools[r],a())},handler:async(h,g)=>{if(!f.enabled)throw Error(`Tool ${r} is disabled`);let v;if(u){let _=f.inputSchema,x=_?await Zv(_,h??{},`Invalid input for tool ${r}: `):h??{};v=await s(x,g)}else v=await s(g);return f.outputSchema&&!v.isError&&(v.structuredContent=await Zv(f.outputSchema,v.structuredContent,`Invalid output for tool ${r}: `)),v}};return this._registeredTools[r]=f,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),a(),f}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(r,o)=>{let s=this._registeredTools[r.name];if(!s)throw Error(`Tool ${r.name} not found`);return s.handler(r.arguments,o)},this.onlisttools=async(r,o)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([s,n])=>n.enabled).map(async([s,n])=>{let a={name:s,title:n.title,description:n.description,inputSchema:n.inputSchema?await Mv(n.inputSchema,"input"):{type:"object",properties:{}}};return n.outputSchema&&(a.outputSchema=await Mv(n.outputSchema,"output")),n.annotations&&(a.annotations=n.annotations),n._meta&&(a._meta=n._meta),a}))}))}async sendToolListChanged(r={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:r})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(r){this.setEventHandler("toolinput",r)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(r){this.setEventHandler("toolinputpartial",r)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(r){this.setEventHandler("toolresult",r)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(r){this.setEventHandler("toolcancelled",r)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(r){this.setEventHandler("hostcontextchanged",r)}_onteardown;get onteardown(){return this._onteardown}set onteardown(r){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,r),this._onteardown=r,this.replaceRequestHandler(k4,(o,s)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(o.params,s)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(r){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,r),this._oncalltool=r,this.replaceRequestHandler(IS,(o,s)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(o.params,s)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(r){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,r),this._onlisttools=r,this.replaceRequestHandler(xS,(o,s)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(o.params,s)})}assertCapabilityForMethod(r){switch(r){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${r})`);break}}assertRequestHandlerCapability(r){switch(r){case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${r})`);return;case"ping":case"ui/resource-teardown":return;default:throw Error(`No handler for method ${r} registered`)}}assertNotificationCapability(r){}assertTaskCapability(r){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(r){throw Error("Task handlers are not supported in MCP Apps")}async callServerTool(r,o){if(this._assertInitialized("callServerTool"),typeof r=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${r}"). Did you mean: callServerTool({ name: "${r}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:r},ou,{onprogress:()=>{},resetTimeoutOnProgress:!0,...o})}async readServerResource(r,o){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:r},SS,o)}async listServerResources(r,o){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:r},kS,o)}async createSamplingMessage(r,o){this._assertInitialized("createSamplingMessage");let s=r.tools?jS:ES;return await this.request({method:"sampling/createMessage",params:r},s,o)}sendMessage(r,o){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:r},g4,o)}sendLog(r){return this.notification({method:"notifications/message",params:r})}updateModelContext(r,o){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:r},Mp,o)}openLink(r,o){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:r},p4,o)}sendOpenLink=this.openLink;downloadFile(r,o){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:r},m4,o)}requestTeardown(r={}){return this.notification({method:"ui/notifications/request-teardown",params:r})}requestDisplayMode(r,o){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:r},b4,o)}sendSizeChanged(r){return this.notification({method:"ui/notifications/size-changed",params:r})}setupSizeChangedNotifications(){let r=!1,o=0,s=0,n=()=>{r||(r=!0,requestAnimationFrame(()=>{r=!1;let u=document.documentElement,f=u.style.height;u.style.height="max-content";let h=Math.ceil(u.getBoundingClientRect().height);u.style.height=f;let g=Math.ceil(window.innerWidth);(g!==o||h!==s)&&(o=g,s=h,this.sendSizeChanged({width:g,height:h}))}))};n();let a=new ResizeObserver(n);return a.observe(document.documentElement),a.observe(document.body),()=>a.disconnect()}async connect(r=new u4(window.parent,window.parent),o){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1,await super.connect(r);try{let s=await this.request({method:"ui/initialize",params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:l4}},E4,o);if(s===void 0)throw Error(`Server sent invalid initialize result: ${s}`);this._hostCapabilities=s.hostCapabilities,this._hostInfo=s.hostInfo,this._hostContext=s.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(s){throw this.close(),s}}}function et(e){return`var(${e})`}const D={bg:{root:et("--bg-root"),surface:et("--bg-surface"),elevated:et("--bg-elevated")},text:{primary:et("--text-primary"),secondary:et("--text-secondary"),muted:et("--text-muted"),faint:et("--text-faint")},accent:et("--accent"),accentDim:et("--accent-dim"),border:et("--border"),borderSubtle:et("--border-subtle"),success:et("--success"),successDim:et("--success-dim"),error:et("--error"),errorDim:et("--error-dim"),warning:et("--warning"),warningDim:et("--warning-dim"),info:et("--info"),infoDim:et("--info-dim")},Ct={sans:et("--font-sans"),mono:et("--font-mono")},at={card:{background:D.bg.surface,border:`1px solid ${D.border}`,borderRadius:"8px",padding:"16px"},badge:(e,r)=>({display:"inline-flex",alignItems:"center",padding:"2px 8px",fontSize:"11px",fontWeight:600,borderRadius:"4px",color:e,background:r,letterSpacing:"0.02em"}),input:{background:D.bg.elevated,border:`1px solid ${D.border}`,borderRadius:"6px",padding:"6px 12px",fontSize:"13px",color:D.text.primary,outline:"none",transition:"border-color 0.15s",width:"100%",fontFamily:Ct.sans},button:{background:D.bg.elevated,border:`1px solid ${D.border}`,borderRadius:"6px",padding:"6px 14px",fontSize:"12px",color:D.text.secondary,cursor:"pointer",transition:"all 0.15s",fontFamily:Ct.sans,whiteSpace:"nowrap"},buttonActive:{background:D.accentDim,borderColor:D.accent,color:D.accent},tableHeader:{padding:"8px 12px",textAlign:"left",fontSize:"11px",fontWeight:600,color:D.text.muted,textTransform:"uppercase",letterSpacing:"0.05em",borderBottom:`1px solid ${D.border}`,cursor:"pointer",userSelect:"none",whiteSpace:"nowrap",transition:"color 0.15s"},tableCell:{padding:"8px 12px",fontSize:"13px",borderBottom:`1px solid ${D.borderSubtle}`,color:D.text.primary},mono:{fontFamily:Ct.mono,fontSize:"12px"}};function T4(){return S.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:[S.jsx("rect",{x:"1",y:"1",width:"6",height:"6",rx:"1.5",fill:"currentColor",opacity:"0.9"}),S.jsx("rect",{x:"9",y:"1",width:"6",height:"6",rx:"1.5",fill:"currentColor",opacity:"0.6"}),S.jsx("rect",{x:"1",y:"9",width:"6",height:"6",rx:"1.5",fill:"currentColor",opacity:"0.6"}),S.jsx("rect",{x:"9",y:"9",width:"6",height:"6",rx:"1.5",fill:"currentColor",opacity:"0.35"})]})}function Ml(){const e={display:"flex",alignItems:"center",gap:7,padding:"0 14px",height:30,background:D.bg.surface,borderBottom:`1px solid ${D.border}`,flexShrink:0},r={fontFamily:Ct.sans,fontSize:11,fontWeight:700,letterSpacing:"0.08em",textTransform:"uppercase",color:D.accent},o={width:3,height:3,borderRadius:"50%",background:D.text.faint,marginLeft:2,marginRight:2,flexShrink:0},s={fontFamily:Ct.sans,fontSize:10,color:D.text.muted,letterSpacing:"0.03em"};return S.jsxs("div",{style:e,children:[S.jsx("div",{style:{color:D.accent},children:S.jsx(T4,{})}),S.jsx("span",{style:r,children:"ERPNext"}),S.jsx("div",{style:o}),S.jsx("span",{style:s,children:"gestion ERP"})]})}function P4(e){return e.error?e.board?{blockingError:null,inlineError:e.error}:{blockingError:e.error,inlineError:null}:{blockingError:null,inlineError:null}}function N4(e){let r;return e.pagination.total!==void 0?r=`${e.pagination.total} cards`:e.pagination.hasMore?r=`${e.pagination.loadedCount}+ cards loaded`:r=`${e.pagination.loadedCount} cards`,`${r} · ${e.doctype} · move tool ${e.moveToolName}`}function rd(e){let r;return e instanceof Error?r=e.message:typeof e=="string"?r=e:r="Move failed",/timeout|timed out/i.test(r)?"La mise a jour a expire, veuillez reessayer.":r}const PS={selectedCardId:null,cardDetail:null,detailLoading:!1,detailError:null};function D4(){return{board:null,loading:!0,error:null,detail:{...PS}}}function O4(e,r){switch(r.type){case"tool-input":return{...e,loading:!0,error:null};case"hydrate-board":return{board:r.board,loading:!1,error:null,detail:e.detail};case"tool-error":return{...e,loading:!1,error:r.message};case"select-card":return{...e,detail:{selectedCardId:r.cardId,cardDetail:null,detailLoading:!0,detailError:null}};case"hydrate-detail":return{...e,detail:{...e.detail,cardDetail:r.detail,detailLoading:!1,detailError:null}};case"close-detail":return{...e,detail:{...PS}};case"detail-error":return{...e,detail:{...e.detail,detailLoading:!1,detailError:r.message}};default:return e}}function C4(){const[e,r]=ce.useReducer(O4,void 0,D4);return{state:e,startLoading(){r({type:"tool-input"})},hydrateBoard(o){r({type:"hydrate-board",board:o})},setError(o){r({type:"tool-error",message:o})},selectCard(o){r({type:"select-card",cardId:o})},hydrateDetail(o){r({type:"hydrate-detail",detail:o})},closeDetail(){r({type:"close-detail"})},setDetailError(o){r({type:"detail-error",message:o})}}}function NS(e,r){const o=new Map;for(const s of r)o.set(s.columnId,(o.get(s.columnId)??0)+1);return e.columns.map(s=>({...s,count:o.get(s.id)??0}))}function Fv(e,r){const o=e.cards.map(s=>s.id===r.cardId?{...s,columnId:r.toColumn,pending:!0}:s);return{snapshot:e,board:{...e,cards:o,columns:NS(e,o)}}}function U4(e,r){const o=e.cards.map(s=>s.id!==r.cardId?s:r.serverCard?{...r.serverCard,pending:!1}:{...s,columnId:r.toColumn,pending:!1});return{...e,cards:o,columns:NS(e,o)}}function id(e,r){return e}function R4(e,r){return[...e,r]}function L4(e){const[r,...o]=e;return{nextMove:r,restQueue:o}}function A4(e,r,o){const s=e.cards.find(n=>n.id===r);return!s||s.pending||s.columnId===o?!1:e.allowedTransitions.some(n=>n.allowed&&n.fromColumn===s.columnId&&n.toColumn===o)}function M4(e,r={}){return!e.board||!e.request||e.visibilityState!=="visible"||e.dragging||e.processingMove||e.queuedMoves>0||e.refreshInFlight?!1:r.ignoreInterval?!0:e.now-e.lastRefreshStartedAt>=e.minIntervalMs}function Z4(e,r){return e?{toolName:"erpnext_kanban_get_board",arguments:e.refreshArguments}:r}const F4=920;function H4(e,r){return r>1&&e<=F4}function q4(e,r){return r<=0||e<0?0:e>=r?r-1:e}function J4(e){return e.structuredContent?JSON.stringify(e.structuredContent):e.content?.find(r=>r.type==="text")?.text??null}const Hv={success:{color:D.success,bg:D.successDim},error:{color:D.error,bg:D.errorDim},info:{color:D.info,bg:D.infoDim},default:{color:D.text.secondary,bg:D.bg.elevated}};function Ll({label:e,variant:r="default",disabled:o,loading:s,confirm:n,onClick:a}){const[u,f]=ce.useState(!1),h=ce.useRef();ce.useEffect(()=>()=>clearTimeout(h.current),[]);const g=Hv[r]??Hv.default;return S.jsx("button",{onClick:()=>{if(n&&!u){f(!0),clearTimeout(h.current),h.current=setTimeout(()=>f(!1),4e3);return}f(!1),a()},disabled:o||s,style:{...at.button,background:g.bg,color:g.color,borderColor:g.color,opacity:o||s?.5:1,fontSize:11,padding:"4px 10px"},children:s?"…":u?"Confirm?":e})}const W4=new Set(["doctype","docstatus","idx","modified_by","owner","creation","modified","_user_tags","_comments","_assign","_liked_by","_seen","__last_sync_on","lft","rgt","old_parent","is_group","is_template","depends_on_tasks","depends_on"]),V4=new Set(["name","status","workflow_state"]),B4={name:"ID",subject:"Subject",status:"Status",priority:"Priority",project:"Project",progress:"Progress (%)",description:"Description",exp_start_date:"Start date",exp_end_date:"Due date",expected_time:"Estimated (h)",actual_time:"Actual time (h)",is_milestone:"Milestone",task_weight:"Weight",total_costing_amount:"Cost",total_billing_amount:"Billing",start:"Start",duration:"Duration",title:"Title",opportunity_from:"Source type",party_name:"Party",opportunity_amount:"Amount",currency:"Currency",probability:"Probability (%)",opportunity_owner:"Owner",expected_closing:"Expected closing",transaction_date:"Created",contact_person:"Contact",source:"Source",customer:"Customer",raised_by:"Raised by",resolution_by:"SLA deadline",opening_date:"Opened",resolution_date:"Resolved",first_responded_on:"First response"},K4=new Set(["is_milestone","is_group","is_template"]),G4=new Set(["exp_start_date","exp_end_date","expected_closing","transaction_date","opening_date","resolution_date","resolution_by","first_responded_on"]),om={priority:["Low","Medium","High","Urgent"],opportunity_from:["Lead","Customer"]},Q4=new Set(["name","status","priority","subject","title","project"]),X4=new Set(["progress","is_milestone"]),DS=new Set(["description","resolution_details","notes"]),Y4=[{id:"dates",label:"Dates",fields:["exp_start_date","exp_end_date","expected_closing","transaction_date","opening_date","resolution_date","resolution_by","first_responded_on","start"]},{id:"time",label:"Time Tracking",fields:["expected_time","actual_time","duration"]},{id:"financial",label:"Financial",fields:["opportunity_amount","currency","probability","total_costing_amount","total_billing_amount","task_weight"]},{id:"people",label:"People",fields:["project","opportunity_owner","customer","party_name","contact_person","raised_by","source","opportunity_from"]}],e6={Urgent:"error",High:"error",Medium:"warning",Low:"success"};function am(e){return B4[e]??e.replace(/_/g," ").replace(/\b\w/g,r=>r.toUpperCase())}function t6(e){return DS.has(e)}function n6(e,r){return K4.has(e)?"boolean":G4.has(e)?"date":e in om?"select":t6(e)?"textarea":typeof r=="number"?"number":"text"}function r6(e){const r=Object.entries(e).filter(([O,M])=>!W4.has(O)&&M!==null&&M!==void 0&&M!==""&&typeof M!="object"),o=new Map(r),s=new Set,n=r.find(([O])=>O==="subject"||O==="title"),a=o.has("name")?String(o.get("name")):null,u=o.has("status")?String(o.get("status")):null,f=o.has("priority")?String(o.get("priority")):null,h=o.has("project")?String(o.get("project")):null,g=o.has("progress")?Number(o.get("progress")):null,v=o.has("is_milestone")?Number(o.get("is_milestone")):null;for(const O of Q4)s.add(O);for(const O of X4)s.add(O);const _=r.find(([O])=>DS.has(O)),x=_?{key:_[0],value:_[1]}:null;_&&s.add(_[0]);const I=[];for(const O of Y4){const M=[];for(const he of O.fields)o.has(he)&&!s.has(he)&&(M.push({key:he,value:o.get(he)}),s.add(he));M.length>0&&I.push({id:O.id,label:O.label,fields:M})}const U=[];for(const[O,M]of r)s.has(O)||U.push({key:O,value:M});return U.length>0&&I.push({id:"details",label:"Details",fields:U}),{titleField:n?{key:n[0],value:n[1]}:null,idValue:a,statusValue:u,priorityValue:f,projectValue:h,progressValue:g,milestoneValue:v,descriptionField:x,sections:I}}function i6({value:e,onChange:r}){const[o,s]=ce.useState(!1),n=CS(e6[e]);return o?S.jsx("select",{value:e,onChange:a=>{r(a.target.value),s(!1)},onBlur:()=>s(!1),autoFocus:!0,style:{...at.input,padding:"2px 8px",fontSize:10,fontWeight:700,width:"auto",cursor:"pointer"},children:om.priority.map(a=>S.jsx("option",{value:a,children:a},a))}):S.jsx("span",{role:"button",tabIndex:0,onClick:()=>s(!0),onKeyDown:a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),s(!0))},style:{...at.badge(n.color,n.bg),fontSize:10,padding:"2px 8px",borderRadius:3,fontWeight:700,letterSpacing:"0.03em",textTransform:"uppercase",cursor:"pointer"},title:"Click to change priority",children:e})}function o6({progressValue:e,editedFields:r,onFieldChange:o}){if(e===null)return null;const s=r.progress!==void 0?Number(r.progress):e??0;return S.jsx("div",{style:{padding:"6px 16px 8px",display:"flex",alignItems:"center",gap:10},children:S.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",gap:8},children:[S.jsx("span",{style:{fontSize:9,fontWeight:600,color:D.text.faint,textTransform:"uppercase",letterSpacing:"0.06em",flexShrink:0},children:"Progress"}),S.jsxs("div",{style:{flex:1,position:"relative",height:18,display:"flex",alignItems:"center"},children:[S.jsx("div",{style:{position:"absolute",left:0,right:0,height:4,background:D.bg.elevated,borderRadius:2},children:S.jsx("div",{style:{height:"100%",width:`${Math.min(100,Math.max(0,s))}%`,background:s>=100?D.success:D.accent,borderRadius:2,transition:"width 0.2s"}})}),S.jsx("input",{type:"range",min:0,max:100,value:s,onChange:n=>o("progress",n.target.value),style:{position:"absolute",left:0,right:0,width:"100%",height:18,opacity:0,cursor:"pointer",margin:0}})]}),S.jsxs("span",{style:{fontSize:11,fontWeight:700,fontFamily:Ct.mono,color:s>=100?D.success:D.text.primary,flexShrink:0,minWidth:32,textAlign:"right"},children:[s,"%"]})]})})}function a6({field:e,editedFields:r,onFieldChange:o}){const s=e.key in r,n=s?r[e.key]:String(e.value);return S.jsxs("div",{style:{padding:"8px 16px"},children:[S.jsx("div",{style:{fontSize:9,fontWeight:600,color:D.text.faint,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4},children:am(e.key)}),S.jsx("textarea",{value:n,onChange:a=>o(e.key,a.target.value),rows:3,style:{...at.input,resize:"vertical",borderColor:s?D.accent:D.border,background:s?D.accentDim:D.bg.elevated,lineHeight:1.5,fontSize:13}})]})}function l6({fieldKey:e,value:r,editedFields:o,onFieldChange:s}){const n=V4.has(e),a=e in o,u=a?o[e]:String(r),f=n6(e,r),h={...at.input,padding:"5px 8px",fontSize:13};function g(_){return{...h,borderColor:_?D.accent:"transparent",background:_?D.accentDim:"transparent"}}function v(){if(n)return S.jsx("span",{style:{fontSize:13,color:D.text.primary,fontFamily:typeof r=="number"?Ct.mono:Ct.sans,fontWeight:e==="name"?500:400},children:String(r)});switch(f){case"boolean":return S.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[S.jsx("input",{type:"checkbox",checked:a?u==="1":r===1,onChange:_=>s(e,_.target.checked?"1":"0"),style:{width:16,height:16,accentColor:"var(--accent)",cursor:"pointer"}}),S.jsx("span",{style:{fontSize:12,color:D.text.secondary},children:(a?u==="1":r===1)?"Yes":"No"})]});case"select":return S.jsx("select",{value:u,onChange:_=>s(e,_.target.value),style:{...h,borderColor:a?D.accent:"transparent",background:a?D.accentDim:"transparent",cursor:"pointer"},children:om[e]?.map(_=>S.jsx("option",{value:_,children:_},_))});case"date":return S.jsx("input",{type:"date",value:u,onChange:_=>s(e,_.target.value),style:g(a)});case"number":return S.jsx("input",{type:"number",value:u,onChange:_=>s(e,_.target.value),style:{...g(a),fontFamily:Ct.mono}});default:return S.jsx("input",{type:"text",value:u,onChange:_=>s(e,_.target.value),style:g(a)})}}return S.jsxs("div",{className:"detail-field-cell",style:{display:"flex",flexDirection:"column",gap:1,padding:"3px 4px"},children:[S.jsx("span",{style:{fontSize:10,fontWeight:600,color:a?D.accent:D.text.faint,textTransform:"uppercase",letterSpacing:"0.05em"},children:am(e)}),v()]})}function s6({sections:e,editedFields:r,onFieldChange:o}){return S.jsx("div",{style:{display:"flex",flexDirection:"column"},children:e.map(s=>S.jsxs("div",{style:{padding:"2px 16px 0"},children:[S.jsx("div",{style:{fontSize:9,fontWeight:700,color:D.text.faint,textTransform:"uppercase",letterSpacing:"0.08em",padding:"4px 0 2px",borderBottom:`1px solid ${D.borderSubtle}`},children:s.label}),S.jsx("div",{style:{display:"grid",gridTemplateColumns:s.fields.length>=3?"1fr 1fr 1fr":"1fr 1fr",gap:"0 12px"},children:s.fields.map((n,a)=>{const u=s.fields.length>=3?3:2,f=a===s.fields.length-1,h=s.fields.length%u===1;return S.jsx("div",{style:f&&h?{gridColumn:"1 / -1"}:void 0,children:S.jsx(l6,{fieldKey:n.key,value:n.value,editedFields:r,onFieldChange:o})},n.key)})})]},s.id))})}function u6(e){if(typeof e!="string"||!e)return[];try{const r=JSON.parse(e);return Array.isArray(r)?r.filter(o=>typeof o=="string"):[]}catch(r){return console.warn("[parseAssignees] Could not parse _assign:",r,e),[]}}function c6({assignees:e,onAssign:r,onUnassign:o,onLoadUsers:s}){const[n,a]=ce.useState(null),[u,f]=ce.useState(null),[h,g]=ce.useState(""),[v,_]=ce.useState(!1),[x,I]=ce.useState(null),[U,O]=ce.useState(null);ce.useEffect(()=>{let K=!1;return s().then(te=>{K||a(te)}).catch(te=>{K||f(te instanceof Error?te.message:"Failed to load users")}),()=>{K=!0}},[]);const M=(n??[]).filter(K=>!e.includes(K.name));async function he(){if(!(!h||v)){_(!0),O(null);try{await r(h),g("")}catch(K){O(K instanceof Error?K.message:"Assignment failed")}finally{_(!1)}}}async function xe(K){if(!(!o||x)){I(K),O(null);try{await o(K)}catch(te){O(te instanceof Error?te.message:"Unassignment failed")}finally{I(null)}}}return S.jsxs("div",{style:{padding:"8px 16px 10px",borderBottom:`1px solid ${D.borderSubtle}`,display:"flex",flexDirection:"column",gap:6},children:[S.jsx("div",{style:{fontSize:9,fontWeight:700,color:D.text.faint,textTransform:"uppercase",letterSpacing:"0.08em"},children:"Assigned to"}),S.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,alignItems:"center"},children:[e.length===0&&S.jsx("span",{style:{fontSize:11,color:D.text.faint},children:"Unassigned"}),e.map(K=>S.jsxs("span",{style:{...at.badge(D.accent,D.accentDim),fontSize:10,display:"inline-flex",alignItems:"center",gap:4},children:[K,o&&S.jsx("button",{type:"button","aria-label":`Unassign ${K}`,title:`Unassign ${K}`,onClick:()=>xe(K),disabled:x!==null,style:{background:"transparent",border:0,color:"inherit",cursor:"pointer",padding:0,fontSize:12,lineHeight:1,opacity:x===K?.5:.7},children:x===K?"…":"×"})]},K)),S.jsxs("select",{"aria-label":"Assign to user",value:h,onChange:K=>g(K.target.value),disabled:v||n===null&&!u,style:{...at.input,padding:"3px 8px",fontSize:11,width:"auto",maxWidth:220,cursor:"pointer"},children:[S.jsx("option",{value:"",children:n===null?u?"Users unavailable":"Loading users…":"Assign to…"}),M.map(K=>S.jsx("option",{value:K.name,children:K.full_name?`${K.full_name} (${K.name})`:K.name},K.name))]}),h&&S.jsx("button",{type:"button",onClick:he,disabled:v,style:{...at.button,padding:"3px 12px",fontSize:11,fontWeight:600,background:D.accent,color:"#fff",borderColor:D.accent,opacity:v?.6:1,borderRadius:5},children:v?"Assigning…":"Assign"})]}),(U??u)&&S.jsx("div",{style:{fontSize:10,color:D.error},children:U??u})]})}function d6({detail:e,board:r,onClose:o,onMove:s,onSave:n,onAssign:a,onUnassign:u,onLoadUsers:f,onNavigate:h}){const[g,v]=ce.useState({}),[_,x]=ce.useState(!1),[I,U]=ce.useState(null),O=ce.useRef(null);if(ce.useEffect(()=>{if(!e.selectedCardId)return;O.current?.focus();function ne(Ce){Ce.key==="Escape"&&o()}return document.addEventListener("keydown",ne),()=>document.removeEventListener("keydown",ne)},[e.selectedCardId,o]),ce.useEffect(()=>{v({}),U(null)},[e.selectedCardId]),!e.selectedCardId)return null;const M=e.selectedCardId,he=r.cards.find(ne=>ne.id===e.selectedCardId),xe=he?.title??e.selectedCardId,K=he?lm(r,he.columnId):[],te=Object.keys(g).length>0;function $e(ne,Ce){v(Rt=>{const yt=e.cardDetail?String(e.cardDetail[ne]??""):"";if(Ce===yt){const st={...Rt};return delete st[ne],st}return{...Rt,[ne]:Ce}}),U(null)}async function Je(){if(!(!te||!n||!e.selectedCardId)){x(!0),U(null);try{await n(r.doctype,e.selectedCardId,g),U({text:"Saved",isError:!1}),v({})}catch(ne){U({text:ne instanceof Error?ne.message:"Save failed",isError:!0})}finally{x(!1)}}}const De=he?r.columns.find(ne=>ne.id===he.columnId)?.color:void 0,we=e.cardDetail?r6(e.cardDetail):null;return S.jsx("div",{className:"kanban-detail-backdrop",onClick:ne=>{ne.target===ne.currentTarget&&o()},children:S.jsxs("div",{className:"kanban-detail-panel",role:"dialog","aria-modal":"true","aria-label":`Detail: ${xe}`,children:[De&&S.jsx("div",{"aria-hidden":"true",style:{height:3,background:De,borderRadius:"12px 12px 0 0",flexShrink:0}}),S.jsxs("div",{style:{padding:"10px 16px 8px",display:"flex",alignItems:"flex-start",gap:10,borderBottom:`1px solid ${D.border}`},children:[S.jsxs("div",{style:{flex:1,minWidth:0},children:[we?.titleField?S.jsx("input",{type:"text","aria-label":am(we.titleField.key),value:g[we.titleField.key]??String(we.titleField.value),onChange:ne=>$e(we.titleField.key,ne.target.value),style:{fontSize:15,fontWeight:700,color:D.text.primary,lineHeight:1.3,background:"transparent",border:"1px solid transparent",borderRadius:4,padding:"2px 4px",margin:"-2px -4px",width:"calc(100% + 8px)",fontFamily:Ct.sans,outline:"none",transition:"border-color 0.15s"}}):S.jsx("div",{style:{fontSize:15,fontWeight:700,color:D.text.primary,lineHeight:1.3},children:xe}),S.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:2,flexWrap:"wrap"},children:[S.jsx("span",{style:{fontFamily:Ct.mono,fontSize:11,color:D.text.faint},children:e.selectedCardId}),we?.statusValue&&S.jsx("span",{style:{...at.badge(De??D.text.muted,`${De??D.text.muted}20`),fontSize:10},children:we.statusValue}),we?.priorityValue&&S.jsx(i6,{value:g.priority??we.priorityValue,onChange:ne=>$e("priority",ne)}),we?.projectValue&&S.jsx("span",{style:{fontSize:11,color:D.text.muted},children:we.projectValue}),we?.milestoneValue!==null&&we?.milestoneValue!==void 0&&(()=>{const ne=g.is_milestone!==void 0?g.is_milestone==="1":we.milestoneValue===1;return S.jsxs("span",{role:"switch","aria-checked":ne,"aria-label":"Milestone",tabIndex:0,onClick:()=>$e("is_milestone",ne?"0":"1"),onKeyDown:Ce=>{(Ce.key==="Enter"||Ce.key===" ")&&(Ce.preventDefault(),$e("is_milestone",ne?"0":"1"))},title:ne?"Milestone (click to unset)":"Set as milestone",style:{display:"inline-flex",alignItems:"center",gap:3,cursor:"pointer",padding:"1px 6px",borderRadius:3,background:ne?D.accentDim:"transparent",border:`1px solid ${ne?D.accent:"transparent"}`,transition:"all 0.2s"},children:[S.jsx("span",{style:{fontSize:10,color:ne?D.accent:D.text.faint,transition:"color 0.2s",lineHeight:1},children:"◆"}),S.jsx("span",{style:{fontSize:9,fontWeight:600,color:ne?D.accent:D.text.faint,textTransform:"uppercase",letterSpacing:"0.04em",transition:"color 0.2s"},children:"Milestone"})]})})()]})]}),S.jsx("button",{ref:O,type:"button",onClick:o,"aria-label":"Close detail",style:{background:"transparent",border:"none",cursor:"pointer",padding:4,borderRadius:4,color:D.text.faint,fontSize:18,lineHeight:1,transition:"color 0.1s"},children:"✕"})]}),S.jsxs("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:[e.detailLoading&&S.jsx("div",{style:{padding:20,display:"flex",flexDirection:"column",gap:10},children:[1,2,3,4,5,6].map(ne=>S.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center"},children:[S.jsx("div",{className:"skeleton",style:{width:120,height:14}}),S.jsx("div",{className:"skeleton",style:{flex:1,height:14}})]},ne))}),e.detailError&&S.jsx("div",{style:{margin:16,padding:"10px 14px",background:D.errorDim,borderRadius:6,color:D.error,fontSize:12},children:e.detailError}),!e.detailLoading&&e.cardDetail&&a&&f&&S.jsx(c6,{assignees:(()=>{const ne=e.cardDetail._assign,Ce=u6(ne);return Ce.length?Ce:typeof ne=="string"&&ne?[]:he?.assignee?[he.assignee]:[]})(),onAssign:ne=>a(r.doctype,M,ne),onUnassign:u?ne=>u(r.doctype,M,ne):void 0,onLoadUsers:f}),we?.descriptionField&&S.jsx("div",{style:{borderBottom:`1px solid ${D.borderSubtle}`},children:S.jsx(a6,{field:we.descriptionField,editedFields:g,onFieldChange:$e})}),we&&we.sections.length>0&&S.jsx(s6,{sections:we.sections,editedFields:g,onFieldChange:$e}),we&&S.jsx(o6,{progressValue:we.progressValue,editedFields:g,onFieldChange:$e})]}),S.jsxs("div",{style:{borderTop:`1px solid ${D.border}`,padding:"8px 16px",display:"flex",flexWrap:"wrap",gap:6,alignItems:"center",flexShrink:0},children:[n&&e.cardDetail&&S.jsxs(S.Fragment,{children:[S.jsx("button",{type:"button",onClick:Je,disabled:!te||_,style:{...at.button,padding:"4px 12px",fontSize:11,fontWeight:600,background:te?D.accent:D.bg.elevated,color:te?"#fff":D.text.faint,borderColor:te?D.accent:D.border,opacity:_?.6:1,borderRadius:5},children:_?"Saving…":"Save"}),te&&S.jsx("button",{type:"button",onClick:()=>{v({}),U(null)},style:{...at.button,padding:"4px 10px",fontSize:11},children:"Discard"}),I&&S.jsx("span",{style:{fontSize:10,fontWeight:500,color:I.isError?D.error:D.success,padding:"1px 6px",borderRadius:3,background:I.isError?D.errorDim:D.successDim},children:I.text}),S.jsx("span",{style:{width:1,height:14,background:D.border,flexShrink:0}})]}),he&&K.length>0&&S.jsxs(S.Fragment,{children:[S.jsx("span",{style:{fontSize:10,fontWeight:600,color:D.text.faint,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Move to"}),K.map(ne=>S.jsxs("button",{type:"button",onClick:()=>{s(he,ne.columnId,ne.label),o()},style:{...at.button,padding:"4px 8px",fontSize:11,display:"inline-flex",alignItems:"center",gap:4},children:[ne.color&&S.jsx("span",{"aria-hidden":"true",style:{width:6,height:6,borderRadius:"50%",background:ne.color,flexShrink:0}}),ne.label]},ne.columnId))]}),h&&he&&K.length>0&&S.jsx("span",{style:{width:1,height:14,background:D.border,flexShrink:0}}),h&&e.selectedCardId&&S.jsxs(S.Fragment,{children:[S.jsx(Ll,{label:"Open in doclist",variant:"info",onClick:()=>h(`Show me a list view of ${r.doctype} ${e.selectedCardId}`)}),r.doctype==="Task"&&S.jsx(Ll,{label:"Timesheets",variant:"info",onClick:()=>h(`Show timesheets for task ${e.selectedCardId}`)}),r.doctype==="Opportunity"&&S.jsx(Ll,{label:"Quotations",variant:"info",onClick:()=>h(`Show quotations linked to opportunity ${e.selectedCardId}`)}),r.doctype==="Issue"&&S.jsx(Ll,{label:"Related tasks",variant:"info",onClick:()=>h(`Show tasks related to issue ${e.selectedCardId}`)})]})]})]})})}const nt=new im({name:"Kanban Viewer",version:"1.0.0"}),qv=15e3,er=1e4;function f6(){return{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0}}const Tn=J4;function Al(e){return e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:e}function lm(e,r){return e.allowedTransitions.filter(o=>o.allowed&&o.fromColumn===r&&o.toColumn!==r).map(o=>{const s=e.columns.find(n=>n.id===o.toColumn);return{columnId:o.toColumn,label:o.label??s?.label??o.toColumn,color:s?.color}})}function p6({children:e,style:r,...o}){const s=ce.useRef(null),n=ce.useRef({active:!1,startX:0,scrollLeft:0}),[a,u]=ce.useState(!1),[f,h]=ce.useState(!1),g=ce.useCallback(()=>{const O=s.current;O&&(u(O.scrollLeft>0),h(O.scrollLeft<O.scrollWidth-O.clientWidth-1))},[]);ce.useEffect(()=>{const O=s.current;if(!O)return;g();const M=new ResizeObserver(g);return M.observe(O),()=>M.disconnect()},[g]);const v=ce.useCallback(O=>{const M=s.current;M&&(n.current={active:!0,startX:O.clientX,scrollLeft:M.scrollLeft},M.style.cursor="grabbing",M.style.userSelect="none")},[]),_=ce.useCallback(O=>{if(!n.current.active)return;const M=s.current;if(!M)return;const he=O.clientX-n.current.startX;M.scrollLeft=n.current.scrollLeft-he,g()},[g]),x=ce.useCallback(()=>{n.current.active=!1;const O=s.current;O&&(O.style.cursor="grab",O.style.userSelect="")},[]);function I(){if(a&&f)return"linear-gradient(to right, transparent, black 24px, black calc(100% - 24px), transparent)";if(f)return"linear-gradient(to right, black calc(100% - 24px), transparent)";if(a)return"linear-gradient(to right, transparent, black 24px)"}const U=I();return S.jsx("div",{ref:s,style:{...r,WebkitMaskImage:U,maskImage:U},onMouseDown:v,onMouseMove:_,onMouseUp:x,onMouseLeave:x,onScroll:g,className:"drag-scroll",...o,children:e})}function m6(){return S.jsx("div",{style:{padding:20},children:S.jsx("div",{style:{display:"flex",gap:12,alignItems:"flex-start",overflowX:"auto"},children:[1,2,3].map(e=>S.jsxs("div",{style:{minWidth:240,display:"flex",flexDirection:"column",gap:8},children:[S.jsx("div",{className:"skeleton",style:{height:36,width:"100%"}}),[1,2,3].map(r=>S.jsx("div",{className:"skeleton",style:{height:72,width:"100%"}},r))]},e))})})}function g6(){return S.jsx("div",{style:{padding:"36px 20px",textAlign:"center",color:D.text.muted,fontFamily:Ct.sans,fontSize:13},children:"No kanban data available"})}function OS({message:e}){return S.jsx("div",{style:{margin:16,...at.card,borderColor:D.error,color:D.error,fontSize:13},children:e})}function CS(e){switch(e){case"error":return{color:D.error,bg:D.errorDim};case"warning":return{color:D.warning,bg:D.warningDim};case"success":return{color:D.success,bg:D.successDim};case"info":return{color:D.info,bg:D.infoDim};default:return{color:D.text.secondary,bg:D.bg.elevated}}}function h6({email:e}){const r=e.charAt(0).toUpperCase(),o=e.indexOf("@"),s=o>0?e.slice(0,o):e;return S.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[S.jsx("span",{style:{width:14,height:14,borderRadius:"50%",background:D.accent,color:"#fff",fontSize:8,fontWeight:700,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:r}),S.jsx("span",{style:{fontSize:10,color:D.text.muted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s})]})}function US({card:e,allowedTargets:r,onMove:o,onDragStart:s,onDragEnd:n,onTitleClick:a,enableDrag:u=!0}){const f=u&&!e.pending,h=e.accent??D.accent,g={background:D.bg.surface,border:`1px solid ${e.pending?D.accent:D.border}`,borderRadius:8,padding:0,display:"flex",flexDirection:"column",opacity:e.pending?.72:1,boxShadow:e.pending?`0 0 0 1px ${D.accentDim}`:"0 1px 3px rgba(0,0,0,0.06)",cursor:f?"grab":void 0,overflow:"hidden",position:"relative"},v=(e.metrics?.length??0)>0,_=(e.badges?.length??0)>0,x={fontSize:13,fontWeight:600,color:D.text.primary,lineHeight:1.35,overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical"};return S.jsxs("article",{style:g,draggable:f,onDragStart:f?I=>s(e,I):void 0,onDragEnd:f?n:void 0,className:e.pending?"animate-pulse":void 0,"aria-busy":e.pending,children:[S.jsx("div",{"aria-hidden":"true",style:{height:4,background:h,flexShrink:0,opacity:e.pending?.5:.85}}),S.jsxs("div",{style:{padding:"10px 12px 0",display:"flex",flexDirection:"column",gap:6},children:[S.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[S.jsxs("div",{style:{flex:1,minWidth:0},children:[a?S.jsx("span",{className:"kanban-card-title-link",role:"button",tabIndex:0,onClick:I=>{I.stopPropagation(),a(e)},onKeyDown:I=>{I.key==="Enter"&&a(e)},style:x,children:e.title}):S.jsx("div",{style:x,children:e.title}),e.subtitle&&S.jsx("div",{style:{fontSize:11,color:D.text.muted,marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.subtitle})]}),_&&S.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,flexShrink:0},children:e.badges?.map(I=>{const U=CS(I.tone);return S.jsx("span",{style:{...at.badge(U.color,U.bg),fontSize:10,padding:"1px 7px",borderRadius:3,fontWeight:700,letterSpacing:"0.03em",textTransform:"uppercase"},children:I.label},`${e.id}-${I.label}`)})})]}),e.description&&S.jsx("div",{style:{fontSize:11,fontStyle:"italic",color:D.text.muted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",lineHeight:1.3},children:e.description}),e.assignee&&S.jsx("div",{style:{marginTop:-2},children:S.jsx(h6,{email:e.assignee})}),v&&S.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:12,padding:"4px 0 2px",borderTop:`1px solid ${D.borderSubtle}`},children:e.metrics?.map(I=>S.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:1},children:[S.jsx("span",{style:{fontSize:9,fontWeight:600,color:D.text.faint,textTransform:"uppercase",letterSpacing:"0.06em"},children:I.label}),S.jsx("span",{style:{fontSize:13,fontWeight:700,color:D.text.primary,fontFamily:Ct.mono,letterSpacing:"-0.02em"},children:I.value})]},`${e.id}-${I.label}`))})]}),r.length>0&&S.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:0,borderTop:`1px solid ${D.borderSubtle}`,marginTop:v?0:6},children:r.map((I,U)=>S.jsxs("button",{type:"button",onClick:()=>o(e,I.columnId,I.label),disabled:e.pending,style:{flex:1,minWidth:0,padding:"7px 6px",fontSize:11,fontWeight:500,fontFamily:Ct.sans,color:D.text.muted,background:"transparent",border:"none",borderRight:U<r.length-1?`1px solid ${D.borderSubtle}`:"none",cursor:e.pending?"default":"pointer",opacity:e.pending?.5:1,transition:"color 0.12s, background 0.12s",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",outlineOffset:-2,display:"flex",alignItems:"center",justifyContent:"center",gap:5},"aria-label":`Move ${e.title} to ${I.label}`,children:[I.color&&S.jsx("span",{"aria-hidden":"true",style:{width:6,height:6,borderRadius:"50%",background:I.color,flexShrink:0}}),I.label]},`${e.id}-${I.columnId}`))})]})}function v6({column:e,cards:r,board:o,activeDropColumn:s,onMove:n,onDropCard:a,onDragStart:u,onDragEnd:f,onDragOverColumn:h,onTitleClick:g}){return S.jsxs("section",{style:{minWidth:260,maxWidth:320,display:"flex",flexDirection:"column",gap:10},onDragOver:v=>h(e.id,v),onDrop:v=>a(e.id,v),children:[S.jsxs("header",{style:{...at.card,padding:"10px 12px",display:"flex",alignItems:"center",gap:8,borderColor:s===e.id?D.accent:D.border,background:s===e.id?D.accentDim:D.bg.surface},children:[S.jsx("span",{"aria-hidden":"true",style:{width:10,height:10,borderRadius:"50%",background:e.color,flexShrink:0}}),S.jsx("span",{style:{fontSize:12,fontWeight:700,color:D.text.primary,flex:1},children:e.label}),S.jsx("span",{style:{...at.badge(e.color,`${e.color}20`)},children:e.count})]}),S.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:r.map(v=>S.jsx(US,{card:v,allowedTargets:lm(o,v.columnId),onMove:n,onDragStart:u,onDragEnd:f,onTitleClick:g},v.id))})]})}function Jv({direction:e,onClick:r}){return S.jsx("button",{type:"button",onClick:r,"aria-label":`Scroll ${e}`,style:{...at.button,padding:"6px 4px",fontSize:12,lineHeight:1,borderRadius:6,flexShrink:0,minWidth:22},children:e==="left"?"‹":"›"})}function y6({columns:e,focusIndex:r,onSelect:o}){const s=ce.useRef([]),[n,a]=ce.useState(!1),[u,f]=ce.useState(!1),h=ce.useCallback(()=>{const g=s.current[0],v=s.current[e.length-1],_=g?.parentElement;!_||!g||!v||(a(_.scrollLeft>0),f(_.scrollLeft<_.scrollWidth-_.clientWidth-1))},[e.length]);return ce.useEffect(h,[h]),ce.useEffect(()=>{const g=s.current[r];if(!g)return;const v=g.parentElement;v&&(v.scrollTo({left:g.offsetLeft-40,behavior:"smooth"}),requestAnimationFrame(h))},[r,h]),S.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,minWidth:0},children:[n&&S.jsx(Jv,{direction:"left",onClick:()=>o(Math.max(0,r-1))}),S.jsx(p6,{onScroll:h,style:{display:"flex",gap:4,overflowX:"auto",minWidth:0,flex:1,cursor:"grab"},role:"tablist","aria-label":"Kanban columns",children:e.map((g,v)=>{const _=v===r;return S.jsxs("button",{ref:x=>{s.current[v]=x},type:"button",role:"tab","aria-selected":_,"aria-controls":`kanban-panel-${g.id}`,onClick:()=>o(v),style:{...at.button,padding:"7px 14px 6px",fontSize:12,fontWeight:_?700:500,color:_?D.text.primary:D.text.muted,background:_?D.bg.surface:"transparent",borderColor:_?"transparent":D.border,borderBottomWidth:2,borderBottomColor:_?g.color:"transparent",borderRadius:_?"6px 6px 0 0":"6px",display:"flex",alignItems:"center",gap:6,whiteSpace:"nowrap",flexShrink:0},children:[S.jsx("span",{"aria-hidden":"true",style:{width:8,height:8,borderRadius:"50%",background:g.color,flexShrink:0}}),g.label,S.jsx("span",{style:{...at.badge(_?D.text.primary:D.text.muted,_?`${g.color}30`:`${D.text.muted}15`),fontSize:10},children:g.count})]},g.id)})}),u&&S.jsx(Jv,{direction:"right",onClick:()=>o(Math.min(e.length-1,r+1))})]})}function _6({board:e,inlineError:r,activeDropColumn:o,onMove:s,onDropCard:n,onDragStart:a,onDragEnd:u,onDragOverColumn:f,onTitleClick:h}){const[g,v]=ce.useState(typeof window<"u"?window.innerWidth:1200),[_,x]=ce.useState(0);ce.useEffect(()=>{function M(){v(window.innerWidth)}return window.addEventListener("resize",M),()=>window.removeEventListener("resize",M)},[]);const I=H4(g,e.columns.length),U=q4(_,e.columns.length),O=I?e.columns[U]:null;return S.jsxs("div",{style:{display:"flex",flexDirection:"column",minHeight:600,background:D.bg.root,overflowX:"hidden",width:"100%"},children:[S.jsx(Ml,{}),S.jsxs("div",{style:{padding:"14px 16px",display:"flex",flexDirection:"column",gap:14,minWidth:0},children:[S.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[S.jsx("div",{style:{fontSize:14,fontWeight:700,color:D.text.primary},children:e.title}),S.jsx("div",{style:{fontSize:11,color:D.text.muted},children:N4(e)})]}),r&&S.jsx(OS,{message:r}),I?S.jsxs(S.Fragment,{children:[S.jsx(y6,{columns:e.columns,focusIndex:U,onSelect:x}),O&&S.jsxs("div",{id:`kanban-panel-${O.id}`,role:"tabpanel","aria-label":O.label,style:{display:"flex",flexDirection:"column",gap:8,minWidth:0},children:[e.cards.filter(M=>M.columnId===O.id).map(M=>S.jsx(US,{card:M,allowedTargets:lm(e,M.columnId),onMove:s,onDragStart:a,onDragEnd:u,onTitleClick:h,enableDrag:!1},M.id)),e.cards.filter(M=>M.columnId===O.id).length===0&&S.jsxs("div",{style:{padding:"20px 12px",textAlign:"center",fontSize:12,color:D.text.muted},children:["No cards in ",O.label]})]})]}):S.jsx("div",{style:{display:"flex",gap:12,alignItems:"flex-start",overflowX:"auto",paddingBottom:8},children:e.columns.map(M=>S.jsx(v6,{column:M,board:e,cards:e.cards.filter(he=>he.columnId===M.id),activeDropColumn:o,onMove:s,onDropCard:n,onDragStart:a,onDragEnd:u,onDragOverColumn:f,onTitleClick:h},M.id))})]})]})}function Wv(e){return JSON.parse(e)}function $6(){const{state:e,hydrateBoard:r,setError:o,startLoading:s,selectCard:n,hydrateDetail:a,closeDetail:u,setDetailError:f}=C4(),[h,g]=ce.useState(""),[v,_]=ce.useState(null),x=ce.useRef([]),I=ce.useRef({}),U=ce.useRef(!1),O=ce.useRef(null),M=ce.useRef(null),he=ce.useRef(!1),xe=ce.useRef(null),K=ce.useRef(!1),te=ce.useRef(!1),$e=ce.useRef(0),Je=ce.useRef(null);function De(L){O.current=L,r(L)}function we(L){const J=Tn(L);if(!J)throw new Error("No text payload returned by tool call");return JSON.parse(J)}function ne(L){const J=Tn(L);if(!J)return"Tool call failed";try{const W=JSON.parse(J);return String(W.errorMessage??W.message??J)}catch{return J}}async function Ce(L={}){const J=O.current,W=Z4(J,xe.current);if(!M4({board:J,request:W,visibilityState:typeof document>"u"?"visible":document.visibilityState,dragging:he.current,processingMove:U.current,queuedMoves:x.current.length,refreshInFlight:K.current,now:Date.now(),lastRefreshStartedAt:$e.current,minIntervalMs:qv},L)||!W||!nt.getHostCapabilities()?.serverTools)return!1;K.current=!0,$e.current=Date.now();try{const Y=await nt.callServerTool({name:W.toolName,arguments:W.arguments},{timeout:er});if(Y.isError)return!1;const oe=Tn(Y);return oe?(De(Wv(oe)),!0):!1}catch{return!1}finally{K.current=!1}}async function Rt(){if(U.current)return;const{nextMove:L,restQueue:J}=L4(x.current);if(!L)return;if(!O.current){x.current=J;return}x.current=J,U.current=!0;const W=L.queueId??L.cardId;if(!I.current[W]){const Y=Fv(O.current,L);I.current[W]=Y.snapshot,De(Y.board)}try{if(!nt.getHostCapabilities()?.serverTools)throw new Error("Host does not support proxied server tool calls");const Y=await nt.callServerTool({name:L.moveToolName,arguments:{doctype:L.doctype,card_id:L.cardId,from_column:L.fromColumn,to_column:L.toColumn}},{timeout:er});if(Y.isError){const oe=I.current[W],le=rd(ne(Y));oe&&De(id(oe,{errorMessage:le})),o(le),g(le)}else{const oe=we(Y);if(oe.ok!==!1){if(O.current){const Ie=U4(O.current,{cardId:L.cardId,toColumn:L.toColumn,serverCard:oe.serverCard});De(Ie),te.current=!0;const Te=Ie.columns.find(mn=>mn.id===L.toColumn)?.label??L.toColumn;g(`Moved ${L.cardId} to ${Te}`)}}else{const Ie=I.current[W],Te=rd(String(oe.errorMessage??"Move failed"));Ie&&De(id(Ie,{errorMessage:Te})),o(Te),g(Te)}}}catch(Y){const oe=I.current[W],le=rd(Y);oe&&De(id(oe)),o(le),g(le)}finally{delete I.current[W],U.current=!1,x.current.length>0?Rt():te.current&&(te.current=!1,Ce({ignoreInterval:!0}))}}function yt(L,J,W){const Y=O.current;if(!Y||L.pending||L.columnId===J)return;if(!Y.allowedTransitions.find(Te=>Te.allowed&&Te.fromColumn===L.columnId&&Te.toColumn===J)){const Te=`Move to ${W} is not allowed`;o(Te),g(Te);return}const le={queueId:crypto.randomUUID(),doctype:Y.doctype,moveToolName:Y.moveToolName,cardId:L.id,fromColumn:L.columnId,toColumn:J};if(!U.current&&x.current.length===0){const Te=Fv(Y,le);I.current[le.queueId??le.cardId]=Te.snapshot,De(Te.board),g(`Moving ${L.title} to ${W}`)}else g(`${L.title} queued for ${W}`);x.current=R4(x.current,le),Rt()}ce.useEffect(()=>{nt.connect().catch(()=>{o("Failed to connect MCP App host")}),nt.ontoolinput=L=>{const J=nt.getHostContext()?.toolInfo?.tool.name;J&&L.arguments&&(xe.current={toolName:J,arguments:L.arguments}),O.current||s()},nt.ontoolresult=L=>{const J=Tn(L);if(!J){o("No kanban payload received from tool result");return}try{De(Wv(J))}catch(W){o(W instanceof Error?W.message:"Failed to parse kanban payload")}},nt.ontoolinputpartial=()=>{O.current||s()}},[]),ce.useEffect(()=>{const L=window.setInterval(()=>{Ce()},qv);function J(){Ce({ignoreInterval:!0})}function W(){document.visibilityState==="visible"&&Ce({ignoreInterval:!0})}return window.addEventListener("focus",J),document.addEventListener("visibilitychange",W),()=>{window.clearInterval(L),window.removeEventListener("focus",J),document.removeEventListener("visibilitychange",W)}},[]),ce.useEffect(()=>{O.current=e.board},[e.board]);function st(L,J){M.current=L.id,he.current=!0,J.dataTransfer.effectAllowed="move",J.dataTransfer.setData("application/json",JSON.stringify({cardId:L.id,fromColumn:L.columnId,title:L.title}))}function Lt(){M.current=null,he.current=!1,_(null)}function Kt(L,J){const W=O.current,Y=M.current;if(!W||!Y||!A4(W,Y,L)){_(null);return}J.preventDefault(),_(L)}function _t(L,J){J.preventDefault(),_(null);try{const W=J.dataTransfer.getData("application/json");if(!W||!O.current)return;const Y=JSON.parse(W),oe=O.current.cards.find(Ie=>Ie.id===Y.cardId),le=O.current.columns.find(Ie=>Ie.id===L)?.label??L;oe&&yt(oe,L,le)}catch{o("Failed to read dragged kanban card")}}function We(L){if(!O.current)return;const J=L.id;Je.current=J,n(J),(async()=>{try{const W=await nt.callServerTool({name:"erpnext_doc_get",arguments:{doctype:O.current.doctype,name:J}},{timeout:er});if(Je.current!==J)return;if(W.isError){f(ne(W));return}const Y=Tn(W);if(!Y){f("No detail payload returned");return}a(Al(JSON.parse(Y)))}catch(W){if(Je.current!==J)return;f(W instanceof Error?W.message:"Failed to fetch detail")}})()}async function B(L){try{await nt.sendMessage({role:"user",content:[{type:"text",text:L}]})}catch{}}async function de(L,J,W){if(!nt.getHostCapabilities()?.serverTools)throw new Error("Host does not support proxied server tool calls");const Y={},oe=e.detail.cardDetail;for(const[Te,mn]of Object.entries(W))if(typeof oe?.[Te]=="number"){const jr=Number(mn);Y[Te]=Number.isFinite(jr)?jr:mn}else Y[Te]=mn;const le=await nt.callServerTool({name:"erpnext_doc_update",arguments:{doctype:L,name:J,data:Y}},{timeout:er});if(le.isError)throw new Error(ne(le));const Ie=await nt.callServerTool({name:"erpnext_doc_get",arguments:{doctype:L,name:J}},{timeout:er});if(!Ie.isError){const Te=Tn(Ie);Te&&a(Al(JSON.parse(Te)))}Ce({ignoreInterval:!0})}async function Q(){if(!nt.getHostCapabilities()?.serverTools)throw new Error("Host does not support proxied server tool calls");const L=await nt.callServerTool({name:"erpnext_user_list",arguments:{limit:100}},{timeout:er});if(L.isError)throw new Error(ne(L));const J=Tn(L);if(!J)return[];let W;try{W=JSON.parse(J)}catch{throw new Error("Could not read the user list returned by the server")}return W.data??[]}async function b(L,J,W){if(!nt.getHostCapabilities()?.serverTools)throw new Error("Host does not support proxied server tool calls");const Y=await nt.callServerTool({name:"erpnext_doc_assign",arguments:{doctype:L,name:J,assign_to:W}},{timeout:er});if(Y.isError)throw new Error(ne(Y));const oe=Tn(Y);if(oe)try{const le=JSON.parse(oe),Ie=Al(le);if(!Ie._assign){const Te=le.assignment;Te?.assignees?.length&&(Ie._assign=JSON.stringify(Te.assignees))}a(Ie)}catch(le){console.warn("[handleAssignDetail] Could not hydrate the assigned doc:",le)}Ce({ignoreInterval:!0})}async function R(L,J,W){if(!nt.getHostCapabilities()?.serverTools)throw new Error("Host does not support proxied server tool calls");const Y=await nt.callServerTool({name:"erpnext_doc_unassign",arguments:{doctype:L,name:J,assign_to:W}},{timeout:er});if(Y.isError)throw new Error(ne(Y));const oe=Tn(Y);if(oe)try{const le=JSON.parse(oe),Ie=Al(le);if(!Ie._assign){const Te=le.assignment;Ie._assign=JSON.stringify((Te?.remaining??[]).map(mn=>mn.owner).filter(Boolean))}a(Ie)}catch(le){console.warn("[handleUnassignDetail] Could not hydrate the doc:",le)}Ce({ignoreInterval:!0})}if(e.loading)return S.jsxs("div",{style:{minHeight:600,background:D.bg.root},children:[S.jsx(Ml,{}),S.jsx(m6,{})]});const ve=P4(e);return ve.blockingError?S.jsxs("div",{style:{minHeight:600,background:D.bg.root},children:[S.jsx(Ml,{}),S.jsx(OS,{message:ve.blockingError})]}):e.board?S.jsxs(S.Fragment,{children:[S.jsx("div",{"aria-live":"polite",style:f6(),children:h}),S.jsx(_6,{board:e.board,inlineError:ve.inlineError,activeDropColumn:v,onMove:yt,onDropCard:_t,onDragStart:st,onDragEnd:Lt,onDragOverColumn:Kt,onTitleClick:We}),e.detail.selectedCardId&&e.board&&S.jsx(d6,{detail:e.detail,board:e.board,onClose:u,onMove:yt,onSave:de,onAssign:b,onUnassign:R,onLoadUsers:Q,onNavigate:B})]}):S.jsxs("div",{style:{minHeight:600,background:D.bg.root},children:[S.jsx(Ml,{}),S.jsx(g6,{})]})}Zb.createRoot(document.getElementById("app")).render(S.jsx($6,{}));</script>
148
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:j().optional().describe("User's language and region preference in BCP 47 format."),timeZone:j().optional().describe("User's timezone in IANA format."),userAgent:j().optional().describe("Host application identifier."),platform:Se([E("web"),E("desktop"),E("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:P({touch:Oe().optional().describe("Whether the device supports touch input."),hover:Oe().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:P({top:ye().describe("Top safe area inset in pixels."),right:ye().describe("Right safe area inset in pixels."),bottom:ye().describe("Bottom safe area inset in pixels."),left:ye().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),z4=P({method:E("ui/notifications/host-context-changed"),params:TS.describe("Partial context update containing only changed fields.")});P({method:E("ui/update-model-context"),params:P({content:pe(ba).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:ze(j(),Ne().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})});P({method:E("ui/initialize"),params:P({appInfo:ru.describe("App identification (name and version)."),appCapabilities:w4.describe("Features and capabilities this app provides."),protocolVersion:j().describe("Protocol version this app supports.")})});var E4=P({protocolVersion:j().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:ru.describe("Host application identification and version."),hostCapabilities:S4.describe("Features and capabilities provided by the host."),hostContext:TS.describe("Rich context about the host environment.")}).passthrough(),j4={target:"draft-2020-12"};async function Mv(e,r){let o=e["~standard"];if(o.jsonSchema)return o.jsonSchema[r](j4);if(o.vendor==="zod"){let{z:s}=await qb(()=>Promise.resolve().then(()=>v1),void 0,import.meta.url);return s.toJSONSchema(e,{io:r})}throw Error(`Schema (vendor: ${o.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function Zv(e,r,o=""){let s=await e["~standard"].validate(r);if(s.issues){let n=s.issues.map(a=>{let u=a.path?.map(f=>typeof f=="object"?f.key:f).join(".");return u?`${u}: ${a.message}`:a.message}).join("; ");throw Error(o+n)}return s.value}class im extends a4{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(r){if(this._initializedSent)return;let o=`[ext-apps] App.${r}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(o);console.warn(`${o}. This will throw in a future release.`)}eventSchemas={toolinput:h4,toolinputpartial:v4,toolresult:I4,toolcancelled:y4,hostcontextchanged:z4};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(r){if(!im.ONE_SHOT_EVENTS.has(r)||this._everHadListener.has(r)||(this._everHadListener.add(r),!this._initializedSent))return;let o=`[ext-apps] "${String(r)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(o);console.warn(o)}setEventHandler(r,o){o&&this._assertHandlerTiming(r),super.setEventHandler(r,o)}addEventListener(r,o){this._assertHandlerTiming(r),super.addEventListener(r,o)}onEventDispatch(r,o){r==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...o})}constructor(r,o={},s={autoResize:!0}){super(s),this._appInfo=r,this._capabilities=o,this.options=s,s.allowUnsafeEval||lt({jitless:!0}),this.setRequestHandler(iu,n=>(console.log("Received ping:",n.params),{})),this.setEventHandler("hostcontextchanged",void 0)}registerCapabilities(r){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._capabilities=o4(this._capabilities,r)}registerTool(r,o,s){if(this._registeredTools[r])throw Error(`Tool ${r} is already registered`);let n=this,a=()=>{n._initializedSent&&n._capabilities.tools?.listChanged&&n.sendToolListChanged()},u=o.inputSchema!==void 0,f={title:o.title,description:o.description,inputSchema:o.inputSchema,outputSchema:o.outputSchema,annotations:o.annotations,_meta:o._meta,enabled:!0,enable(){this.enabled=!0,a()},disable(){this.enabled=!1,a()},update(h){Object.assign(this,h),a()},remove(){n._registeredTools[r]===f&&(delete n._registeredTools[r],a())},handler:async(h,g)=>{if(!f.enabled)throw Error(`Tool ${r} is disabled`);let v;if(u){let _=f.inputSchema,x=_?await Zv(_,h??{},`Invalid input for tool ${r}: `):h??{};v=await s(x,g)}else v=await s(g);return f.outputSchema&&!v.isError&&(v.structuredContent=await Zv(f.outputSchema,v.structuredContent,`Invalid output for tool ${r}: `)),v}};return this._registeredTools[r]=f,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),a(),f}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(r,o)=>{let s=this._registeredTools[r.name];if(!s)throw Error(`Tool ${r.name} not found`);return s.handler(r.arguments,o)},this.onlisttools=async(r,o)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([s,n])=>n.enabled).map(async([s,n])=>{let a={name:s,title:n.title,description:n.description,inputSchema:n.inputSchema?await Mv(n.inputSchema,"input"):{type:"object",properties:{}}};return n.outputSchema&&(a.outputSchema=await Mv(n.outputSchema,"output")),n.annotations&&(a.annotations=n.annotations),n._meta&&(a._meta=n._meta),a}))}))}async sendToolListChanged(r={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:r})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(r){this.setEventHandler("toolinput",r)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(r){this.setEventHandler("toolinputpartial",r)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(r){this.setEventHandler("toolresult",r)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(r){this.setEventHandler("toolcancelled",r)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(r){this.setEventHandler("hostcontextchanged",r)}_onteardown;get onteardown(){return this._onteardown}set onteardown(r){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,r),this._onteardown=r,this.replaceRequestHandler(k4,(o,s)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(o.params,s)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(r){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,r),this._oncalltool=r,this.replaceRequestHandler(IS,(o,s)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(o.params,s)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(r){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,r),this._onlisttools=r,this.replaceRequestHandler(xS,(o,s)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(o.params,s)})}assertCapabilityForMethod(r){switch(r){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${r})`);break}}assertRequestHandlerCapability(r){switch(r){case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${r})`);return;case"ping":case"ui/resource-teardown":return;default:throw Error(`No handler for method ${r} registered`)}}assertNotificationCapability(r){}assertTaskCapability(r){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(r){throw Error("Task handlers are not supported in MCP Apps")}async callServerTool(r,o){if(this._assertInitialized("callServerTool"),typeof r=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${r}"). Did you mean: callServerTool({ name: "${r}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:r},ou,{onprogress:()=>{},resetTimeoutOnProgress:!0,...o})}async readServerResource(r,o){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:r},SS,o)}async listServerResources(r,o){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:r},kS,o)}async createSamplingMessage(r,o){this._assertInitialized("createSamplingMessage");let s=r.tools?jS:ES;return await this.request({method:"sampling/createMessage",params:r},s,o)}sendMessage(r,o){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:r},g4,o)}sendLog(r){return this.notification({method:"notifications/message",params:r})}updateModelContext(r,o){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:r},Mp,o)}openLink(r,o){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:r},p4,o)}sendOpenLink=this.openLink;downloadFile(r,o){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:r},m4,o)}requestTeardown(r={}){return this.notification({method:"ui/notifications/request-teardown",params:r})}requestDisplayMode(r,o){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:r},b4,o)}sendSizeChanged(r){return this.notification({method:"ui/notifications/size-changed",params:r})}setupSizeChangedNotifications(){let r=!1,o=0,s=0,n=()=>{r||(r=!0,requestAnimationFrame(()=>{r=!1;let u=document.documentElement,f=u.style.height;u.style.height="max-content";let h=Math.ceil(u.getBoundingClientRect().height);u.style.height=f;let g=Math.ceil(window.innerWidth);(g!==o||h!==s)&&(o=g,s=h,this.sendSizeChanged({width:g,height:h}))}))};n();let a=new ResizeObserver(n);return a.observe(document.documentElement),a.observe(document.body),()=>a.disconnect()}async connect(r=new u4(window.parent,window.parent),o){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1,await super.connect(r);try{let s=await this.request({method:"ui/initialize",params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:l4}},E4,o);if(s===void 0)throw Error(`Server sent invalid initialize result: ${s}`);this._hostCapabilities=s.hostCapabilities,this._hostInfo=s.hostInfo,this._hostContext=s.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(s){throw this.close(),s}}}function et(e){return`var(${e})`}const D={bg:{root:et("--bg-root"),surface:et("--bg-surface"),elevated:et("--bg-elevated")},text:{primary:et("--text-primary"),secondary:et("--text-secondary"),muted:et("--text-muted"),faint:et("--text-faint")},accent:et("--accent"),accentDim:et("--accent-dim"),border:et("--border"),borderSubtle:et("--border-subtle"),success:et("--success"),successDim:et("--success-dim"),error:et("--error"),errorDim:et("--error-dim"),warning:et("--warning"),warningDim:et("--warning-dim"),info:et("--info"),infoDim:et("--info-dim")},Ct={sans:et("--font-sans"),mono:et("--font-mono")},at={card:{background:D.bg.surface,border:`1px solid ${D.border}`,borderRadius:"8px",padding:"16px"},badge:(e,r)=>({display:"inline-flex",alignItems:"center",padding:"2px 8px",fontSize:"11px",fontWeight:600,borderRadius:"4px",color:e,background:r,letterSpacing:"0.02em"}),input:{background:D.bg.elevated,border:`1px solid ${D.border}`,borderRadius:"6px",padding:"6px 12px",fontSize:"13px",color:D.text.primary,outline:"none",transition:"border-color 0.15s",width:"100%",fontFamily:Ct.sans},button:{background:D.bg.elevated,border:`1px solid ${D.border}`,borderRadius:"6px",padding:"6px 14px",fontSize:"12px",color:D.text.secondary,cursor:"pointer",transition:"all 0.15s",fontFamily:Ct.sans,whiteSpace:"nowrap"},buttonActive:{background:D.accentDim,borderColor:D.accent,color:D.accent},tableHeader:{padding:"8px 12px",textAlign:"left",fontSize:"11px",fontWeight:600,color:D.text.muted,textTransform:"uppercase",letterSpacing:"0.05em",borderBottom:`1px solid ${D.border}`,cursor:"pointer",userSelect:"none",whiteSpace:"nowrap",transition:"color 0.15s"},tableCell:{padding:"8px 12px",fontSize:"13px",borderBottom:`1px solid ${D.borderSubtle}`,color:D.text.primary},mono:{fontFamily:Ct.mono,fontSize:"12px"}};function T4(){return S.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:[S.jsx("rect",{x:"1",y:"1",width:"6",height:"6",rx:"1.5",fill:"currentColor",opacity:"0.9"}),S.jsx("rect",{x:"9",y:"1",width:"6",height:"6",rx:"1.5",fill:"currentColor",opacity:"0.6"}),S.jsx("rect",{x:"1",y:"9",width:"6",height:"6",rx:"1.5",fill:"currentColor",opacity:"0.6"}),S.jsx("rect",{x:"9",y:"9",width:"6",height:"6",rx:"1.5",fill:"currentColor",opacity:"0.35"})]})}function Ml(){const e={display:"flex",alignItems:"center",gap:7,padding:"0 14px",height:30,background:D.bg.surface,borderBottom:`1px solid ${D.border}`,flexShrink:0},r={fontFamily:Ct.sans,fontSize:11,fontWeight:700,letterSpacing:"0.08em",textTransform:"uppercase",color:D.accent},o={width:3,height:3,borderRadius:"50%",background:D.text.faint,marginLeft:2,marginRight:2,flexShrink:0},s={fontFamily:Ct.sans,fontSize:10,color:D.text.muted,letterSpacing:"0.03em"};return S.jsxs("div",{style:e,children:[S.jsx("div",{style:{color:D.accent},children:S.jsx(T4,{})}),S.jsx("span",{style:r,children:"ERPNext"}),S.jsx("div",{style:o}),S.jsx("span",{style:s,children:"gestion ERP"})]})}function P4(e){return e.error?e.board?{blockingError:null,inlineError:e.error}:{blockingError:e.error,inlineError:null}:{blockingError:null,inlineError:null}}function N4(e){let r;return e.pagination.total!==void 0?r=`${e.pagination.total} cards`:e.pagination.hasMore?r=`${e.pagination.loadedCount}+ cards loaded`:r=`${e.pagination.loadedCount} cards`,`${r} · ${e.doctype} · move tool ${e.moveToolName}`}function rd(e){let r;return e instanceof Error?r=e.message:typeof e=="string"?r=e:r="Move failed",/timeout|timed out/i.test(r)?"La mise a jour a expire, veuillez reessayer.":r}const PS={selectedCardId:null,cardDetail:null,detailLoading:!1,detailError:null};function D4(){return{board:null,loading:!0,error:null,detail:{...PS}}}function O4(e,r){switch(r.type){case"tool-input":return{...e,loading:!0,error:null};case"hydrate-board":return{board:r.board,loading:!1,error:null,detail:e.detail};case"tool-error":return{...e,loading:!1,error:r.message};case"select-card":return{...e,detail:{selectedCardId:r.cardId,cardDetail:null,detailLoading:!0,detailError:null}};case"hydrate-detail":return{...e,detail:{...e.detail,cardDetail:r.detail,detailLoading:!1,detailError:null}};case"close-detail":return{...e,detail:{...PS}};case"detail-error":return{...e,detail:{...e.detail,detailLoading:!1,detailError:r.message}};default:return e}}function C4(){const[e,r]=ce.useReducer(O4,void 0,D4);return{state:e,startLoading(){r({type:"tool-input"})},hydrateBoard(o){r({type:"hydrate-board",board:o})},setError(o){r({type:"tool-error",message:o})},selectCard(o){r({type:"select-card",cardId:o})},hydrateDetail(o){r({type:"hydrate-detail",detail:o})},closeDetail(){r({type:"close-detail"})},setDetailError(o){r({type:"detail-error",message:o})}}}function NS(e,r){const o=new Map;for(const s of r)o.set(s.columnId,(o.get(s.columnId)??0)+1);return e.columns.map(s=>({...s,count:o.get(s.id)??0}))}function Fv(e,r){const o=e.cards.map(s=>s.id===r.cardId?{...s,columnId:r.toColumn,pending:!0}:s);return{snapshot:e,board:{...e,cards:o,columns:NS(e,o)}}}function U4(e,r){const o=e.cards.map(s=>s.id!==r.cardId?s:r.serverCard?{...r.serverCard,pending:!1}:{...s,columnId:r.toColumn,pending:!1});return{...e,cards:o,columns:NS(e,o)}}function id(e,r){return e}function R4(e,r){return[...e,r]}function L4(e){const[r,...o]=e;return{nextMove:r,restQueue:o}}function A4(e,r,o){const s=e.cards.find(n=>n.id===r);return!s||s.pending||s.columnId===o?!1:e.allowedTransitions.some(n=>n.allowed&&n.fromColumn===s.columnId&&n.toColumn===o)}function M4(e,r={}){return!e.board||!e.request||e.visibilityState!=="visible"||e.dragging||e.processingMove||e.queuedMoves>0||e.refreshInFlight?!1:r.ignoreInterval?!0:e.now-e.lastRefreshStartedAt>=e.minIntervalMs}function Z4(e,r){return e?{toolName:"erpnext_kanban_get_board",arguments:e.refreshArguments}:r}const F4=920;function H4(e,r){return r>1&&e<=F4}function q4(e,r){return r<=0||e<0?0:e>=r?r-1:e}function J4(e){return e.structuredContent?JSON.stringify(e.structuredContent):e.content?.find(r=>r.type==="text")?.text??null}const Hv={success:{color:D.success,bg:D.successDim},error:{color:D.error,bg:D.errorDim},info:{color:D.info,bg:D.infoDim},default:{color:D.text.secondary,bg:D.bg.elevated}};function Ll({label:e,variant:r="default",disabled:o,loading:s,confirm:n,onClick:a}){const[u,f]=ce.useState(!1),h=ce.useRef();ce.useEffect(()=>()=>clearTimeout(h.current),[]);const g=Hv[r]??Hv.default;return S.jsx("button",{onClick:()=>{if(n&&!u){f(!0),clearTimeout(h.current),h.current=setTimeout(()=>f(!1),4e3);return}f(!1),a()},disabled:o||s,style:{...at.button,background:g.bg,color:g.color,borderColor:g.color,opacity:o||s?.5:1,fontSize:11,padding:"4px 10px"},children:s?"…":u?"Confirm?":e})}const W4=new Set(["doctype","docstatus","idx","modified_by","owner","creation","modified","_user_tags","_comments","_assign","_liked_by","_seen","__last_sync_on","lft","rgt","old_parent","is_group","is_template","depends_on_tasks","depends_on"]),V4=new Set(["name","status","workflow_state"]),B4={name:"ID",subject:"Subject",status:"Status",priority:"Priority",project:"Project",progress:"Progress (%)",description:"Description",exp_start_date:"Start date",exp_end_date:"Due date",expected_time:"Estimated (h)",actual_time:"Actual time (h)",is_milestone:"Milestone",task_weight:"Weight",total_costing_amount:"Cost",total_billing_amount:"Billing",start:"Start",duration:"Duration",title:"Title",opportunity_from:"Source type",party_name:"Party",opportunity_amount:"Amount",currency:"Currency",probability:"Probability (%)",opportunity_owner:"Owner",expected_closing:"Expected closing",transaction_date:"Created",contact_person:"Contact",source:"Source",customer:"Customer",raised_by:"Raised by",resolution_by:"SLA deadline",opening_date:"Opened",resolution_date:"Resolved",first_responded_on:"First response"},K4=new Set(["is_milestone","is_group","is_template"]),G4=new Set(["exp_start_date","exp_end_date","expected_closing","transaction_date","opening_date","resolution_date","resolution_by","first_responded_on"]),om={priority:["Low","Medium","High","Urgent"],opportunity_from:["Lead","Customer"]},Q4=new Set(["name","status","priority","subject","title","project"]),X4=new Set(["progress","is_milestone"]),DS=new Set(["description","resolution_details","notes"]),Y4=[{id:"dates",label:"Dates",fields:["exp_start_date","exp_end_date","expected_closing","transaction_date","opening_date","resolution_date","resolution_by","first_responded_on","start"]},{id:"time",label:"Time Tracking",fields:["expected_time","actual_time","duration"]},{id:"financial",label:"Financial",fields:["opportunity_amount","currency","probability","total_costing_amount","total_billing_amount","task_weight"]},{id:"people",label:"People",fields:["project","opportunity_owner","customer","party_name","contact_person","raised_by","source","opportunity_from"]}],e6={Urgent:"error",High:"error",Medium:"warning",Low:"success"};function am(e){return B4[e]??e.replace(/_/g," ").replace(/\b\w/g,r=>r.toUpperCase())}function t6(e){return DS.has(e)}function n6(e,r){return K4.has(e)?"boolean":G4.has(e)?"date":e in om?"select":t6(e)?"textarea":typeof r=="number"?"number":"text"}function r6(e){const r=Object.entries(e).filter(([O,M])=>!W4.has(O)&&M!==null&&M!==void 0&&M!==""&&typeof M!="object"),o=new Map(r),s=new Set,n=r.find(([O])=>O==="subject"||O==="title"),a=o.has("name")?String(o.get("name")):null,u=o.has("status")?String(o.get("status")):null,f=o.has("priority")?String(o.get("priority")):null,h=o.has("project")?String(o.get("project")):null,g=o.has("progress")?Number(o.get("progress")):null,v=o.has("is_milestone")?Number(o.get("is_milestone")):null;for(const O of Q4)s.add(O);for(const O of X4)s.add(O);const _=r.find(([O])=>DS.has(O)),x=_?{key:_[0],value:_[1]}:null;_&&s.add(_[0]);const I=[];for(const O of Y4){const M=[];for(const he of O.fields)o.has(he)&&!s.has(he)&&(M.push({key:he,value:o.get(he)}),s.add(he));M.length>0&&I.push({id:O.id,label:O.label,fields:M})}const U=[];for(const[O,M]of r)s.has(O)||U.push({key:O,value:M});return U.length>0&&I.push({id:"details",label:"Details",fields:U}),{titleField:n?{key:n[0],value:n[1]}:null,idValue:a,statusValue:u,priorityValue:f,projectValue:h,progressValue:g,milestoneValue:v,descriptionField:x,sections:I}}function i6({value:e,onChange:r}){const[o,s]=ce.useState(!1),n=CS(e6[e]);return o?S.jsx("select",{value:e,onChange:a=>{r(a.target.value),s(!1)},onBlur:()=>s(!1),autoFocus:!0,style:{...at.input,padding:"2px 8px",fontSize:10,fontWeight:700,width:"auto",cursor:"pointer"},children:om.priority.map(a=>S.jsx("option",{value:a,children:a},a))}):S.jsx("span",{role:"button",tabIndex:0,onClick:()=>s(!0),onKeyDown:a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),s(!0))},style:{...at.badge(n.color,n.bg),fontSize:10,padding:"2px 8px",borderRadius:3,fontWeight:700,letterSpacing:"0.03em",textTransform:"uppercase",cursor:"pointer"},title:"Click to change priority",children:e})}function o6({progressValue:e,editedFields:r,onFieldChange:o}){if(e===null)return null;const s=r.progress!==void 0?Number(r.progress):e??0;return S.jsx("div",{style:{padding:"6px 16px 8px",display:"flex",alignItems:"center",gap:10},children:S.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",gap:8},children:[S.jsx("span",{style:{fontSize:9,fontWeight:600,color:D.text.faint,textTransform:"uppercase",letterSpacing:"0.06em",flexShrink:0},children:"Progress"}),S.jsxs("div",{style:{flex:1,position:"relative",height:18,display:"flex",alignItems:"center"},children:[S.jsx("div",{style:{position:"absolute",left:0,right:0,height:4,background:D.bg.elevated,borderRadius:2},children:S.jsx("div",{style:{height:"100%",width:`${Math.min(100,Math.max(0,s))}%`,background:s>=100?D.success:D.accent,borderRadius:2,transition:"width 0.2s"}})}),S.jsx("input",{type:"range",min:0,max:100,value:s,onChange:n=>o("progress",n.target.value),style:{position:"absolute",left:0,right:0,width:"100%",height:18,opacity:0,cursor:"pointer",margin:0}})]}),S.jsxs("span",{style:{fontSize:11,fontWeight:700,fontFamily:Ct.mono,color:s>=100?D.success:D.text.primary,flexShrink:0,minWidth:32,textAlign:"right"},children:[s,"%"]})]})})}function a6({field:e,editedFields:r,onFieldChange:o}){const s=e.key in r,n=s?r[e.key]:String(e.value);return S.jsxs("div",{style:{padding:"8px 16px"},children:[S.jsx("div",{style:{fontSize:9,fontWeight:600,color:D.text.faint,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4},children:am(e.key)}),S.jsx("textarea",{value:n,onChange:a=>o(e.key,a.target.value),rows:3,style:{...at.input,resize:"vertical",borderColor:s?D.accent:D.border,background:s?D.accentDim:D.bg.elevated,lineHeight:1.5,fontSize:13}})]})}function l6({fieldKey:e,value:r,editedFields:o,onFieldChange:s}){const n=V4.has(e),a=e in o,u=a?o[e]:String(r),f=n6(e,r),h={...at.input,padding:"5px 8px",fontSize:13};function g(_){return{...h,borderColor:_?D.accent:"transparent",background:_?D.accentDim:"transparent"}}function v(){if(n)return S.jsx("span",{style:{fontSize:13,color:D.text.primary,fontFamily:typeof r=="number"?Ct.mono:Ct.sans,fontWeight:e==="name"?500:400},children:String(r)});switch(f){case"boolean":return S.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[S.jsx("input",{type:"checkbox",checked:a?u==="1":r===1,onChange:_=>s(e,_.target.checked?"1":"0"),style:{width:16,height:16,accentColor:"var(--accent)",cursor:"pointer"}}),S.jsx("span",{style:{fontSize:12,color:D.text.secondary},children:(a?u==="1":r===1)?"Yes":"No"})]});case"select":return S.jsx("select",{value:u,onChange:_=>s(e,_.target.value),style:{...h,borderColor:a?D.accent:"transparent",background:a?D.accentDim:"transparent",cursor:"pointer"},children:om[e]?.map(_=>S.jsx("option",{value:_,children:_},_))});case"date":return S.jsx("input",{type:"date",value:u,onChange:_=>s(e,_.target.value),style:g(a)});case"number":return S.jsx("input",{type:"number",value:u,onChange:_=>s(e,_.target.value),style:{...g(a),fontFamily:Ct.mono}});default:return S.jsx("input",{type:"text",value:u,onChange:_=>s(e,_.target.value),style:g(a)})}}return S.jsxs("div",{className:"detail-field-cell",style:{display:"flex",flexDirection:"column",gap:1,padding:"3px 4px"},children:[S.jsx("span",{style:{fontSize:10,fontWeight:600,color:a?D.accent:D.text.faint,textTransform:"uppercase",letterSpacing:"0.05em"},children:am(e)}),v()]})}function s6({sections:e,editedFields:r,onFieldChange:o}){return S.jsx("div",{style:{display:"flex",flexDirection:"column"},children:e.map(s=>S.jsxs("div",{style:{padding:"2px 16px 0"},children:[S.jsx("div",{style:{fontSize:9,fontWeight:700,color:D.text.faint,textTransform:"uppercase",letterSpacing:"0.08em",padding:"4px 0 2px",borderBottom:`1px solid ${D.borderSubtle}`},children:s.label}),S.jsx("div",{style:{display:"grid",gridTemplateColumns:s.fields.length>=3?"1fr 1fr 1fr":"1fr 1fr",gap:"0 12px"},children:s.fields.map((n,a)=>{const u=s.fields.length>=3?3:2,f=a===s.fields.length-1,h=s.fields.length%u===1;return S.jsx("div",{style:f&&h?{gridColumn:"1 / -1"}:void 0,children:S.jsx(l6,{fieldKey:n.key,value:n.value,editedFields:r,onFieldChange:o})},n.key)})})]},s.id))})}function u6(e){if(typeof e!="string"||!e)return[];try{const r=JSON.parse(e);return Array.isArray(r)?r.filter(o=>typeof o=="string"):[]}catch(r){return console.warn("[parseAssignees] Could not parse _assign:",r,e),[]}}function c6({assignees:e,onAssign:r,onUnassign:o,onLoadUsers:s}){const[n,a]=ce.useState(null),[u,f]=ce.useState(null),[h,g]=ce.useState(""),[v,_]=ce.useState(!1),[x,I]=ce.useState(null),[U,O]=ce.useState(null);ce.useEffect(()=>{let K=!1;return s().then(te=>{K||a(te)}).catch(te=>{K||f(te instanceof Error?te.message:"Failed to load users")}),()=>{K=!0}},[]);const M=(n??[]).filter(K=>!e.includes(K.name));async function he(){if(!(!h||v)){_(!0),O(null);try{await r(h),g("")}catch(K){O(K instanceof Error?K.message:"Assignment failed")}finally{_(!1)}}}async function xe(K){if(!(!o||x)){I(K),O(null);try{await o(K)}catch(te){O(te instanceof Error?te.message:"Unassignment failed")}finally{I(null)}}}return S.jsxs("div",{style:{padding:"8px 16px 10px",borderBottom:`1px solid ${D.borderSubtle}`,display:"flex",flexDirection:"column",gap:6},children:[S.jsx("div",{style:{fontSize:9,fontWeight:700,color:D.text.faint,textTransform:"uppercase",letterSpacing:"0.08em"},children:"Assigned to"}),S.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,alignItems:"center"},children:[e.length===0&&S.jsx("span",{style:{fontSize:11,color:D.text.faint},children:"Unassigned"}),e.map(K=>S.jsxs("span",{style:{...at.badge(D.accent,D.accentDim),fontSize:10,display:"inline-flex",alignItems:"center",gap:4},children:[K,o&&S.jsx("button",{type:"button","aria-label":`Unassign ${K}`,title:`Unassign ${K}`,onClick:()=>xe(K),disabled:x!==null,style:{background:"transparent",border:0,color:"inherit",cursor:"pointer",padding:0,fontSize:12,lineHeight:1,opacity:x===K?.5:.7},children:x===K?"…":"×"})]},K)),S.jsxs("select",{"aria-label":"Assign to user",value:h,onChange:K=>g(K.target.value),disabled:v||n===null&&!u,style:{...at.input,padding:"3px 8px",fontSize:11,width:"auto",maxWidth:220,cursor:"pointer"},children:[S.jsx("option",{value:"",children:n===null?u?"Users unavailable":"Loading users…":"Assign to…"}),M.map(K=>S.jsx("option",{value:K.name,children:K.full_name?`${K.full_name} (${K.name})`:K.name},K.name))]}),h&&S.jsx("button",{type:"button",onClick:he,disabled:v,style:{...at.button,padding:"3px 12px",fontSize:11,fontWeight:600,background:D.accent,color:"#fff",borderColor:D.accent,opacity:v?.6:1,borderRadius:5},children:v?"Assigning…":"Assign"})]}),(U??u)&&S.jsx("div",{style:{fontSize:10,color:D.error},children:U??u})]})}function d6({detail:e,board:r,onClose:o,onMove:s,onSave:n,onAssign:a,onUnassign:u,onLoadUsers:f,onNavigate:h}){const[g,v]=ce.useState({}),[_,x]=ce.useState(!1),[I,U]=ce.useState(null),O=ce.useRef(null);if(ce.useEffect(()=>{if(!e.selectedCardId)return;O.current?.focus();function ne(Ce){Ce.key==="Escape"&&o()}return document.addEventListener("keydown",ne),()=>document.removeEventListener("keydown",ne)},[e.selectedCardId,o]),ce.useEffect(()=>{v({}),U(null)},[e.selectedCardId]),!e.selectedCardId)return null;const M=e.selectedCardId,he=r.cards.find(ne=>ne.id===e.selectedCardId),xe=he?.title??e.selectedCardId,K=he?lm(r,he.columnId):[],te=Object.keys(g).length>0;function $e(ne,Ce){v(Rt=>{const yt=e.cardDetail?String(e.cardDetail[ne]??""):"";if(Ce===yt){const st={...Rt};return delete st[ne],st}return{...Rt,[ne]:Ce}}),U(null)}async function Je(){if(!(!te||!n||!e.selectedCardId)){x(!0),U(null);try{await n(r.doctype,e.selectedCardId,g),U({text:"Saved",isError:!1}),v({})}catch(ne){U({text:ne instanceof Error?ne.message:"Save failed",isError:!0})}finally{x(!1)}}}const De=he?r.columns.find(ne=>ne.id===he.columnId)?.color:void 0,we=e.cardDetail?r6(e.cardDetail):null;return S.jsx("div",{className:"kanban-detail-backdrop",onClick:ne=>{ne.target===ne.currentTarget&&o()},children:S.jsxs("div",{className:"kanban-detail-panel",role:"dialog","aria-modal":"true","aria-label":`Detail: ${xe}`,children:[De&&S.jsx("div",{"aria-hidden":"true",style:{height:3,background:De,borderRadius:"12px 12px 0 0",flexShrink:0}}),S.jsxs("div",{style:{padding:"10px 16px 8px",display:"flex",alignItems:"flex-start",gap:10,borderBottom:`1px solid ${D.border}`},children:[S.jsxs("div",{style:{flex:1,minWidth:0},children:[we?.titleField?S.jsx("input",{type:"text","aria-label":am(we.titleField.key),value:g[we.titleField.key]??String(we.titleField.value),onChange:ne=>$e(we.titleField.key,ne.target.value),style:{fontSize:15,fontWeight:700,color:D.text.primary,lineHeight:1.3,background:"transparent",border:"1px solid transparent",borderRadius:4,padding:"2px 4px",margin:"-2px -4px",width:"calc(100% + 8px)",fontFamily:Ct.sans,outline:"none",transition:"border-color 0.15s"}}):S.jsx("div",{style:{fontSize:15,fontWeight:700,color:D.text.primary,lineHeight:1.3},children:xe}),S.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:2,flexWrap:"wrap"},children:[S.jsx("span",{style:{fontFamily:Ct.mono,fontSize:11,color:D.text.faint},children:e.selectedCardId}),we?.statusValue&&S.jsx("span",{style:{...at.badge(De??D.text.muted,`${De??D.text.muted}20`),fontSize:10},children:we.statusValue}),we?.priorityValue&&S.jsx(i6,{value:g.priority??we.priorityValue,onChange:ne=>$e("priority",ne)}),we?.projectValue&&S.jsx("span",{style:{fontSize:11,color:D.text.muted},children:we.projectValue}),we?.milestoneValue!==null&&we?.milestoneValue!==void 0&&(()=>{const ne=g.is_milestone!==void 0?g.is_milestone==="1":we.milestoneValue===1;return S.jsxs("span",{role:"switch","aria-checked":ne,"aria-label":"Milestone",tabIndex:0,onClick:()=>$e("is_milestone",ne?"0":"1"),onKeyDown:Ce=>{(Ce.key==="Enter"||Ce.key===" ")&&(Ce.preventDefault(),$e("is_milestone",ne?"0":"1"))},title:ne?"Milestone (click to unset)":"Set as milestone",style:{display:"inline-flex",alignItems:"center",gap:3,cursor:"pointer",padding:"1px 6px",borderRadius:3,background:ne?D.accentDim:"transparent",border:`1px solid ${ne?D.accent:"transparent"}`,transition:"all 0.2s"},children:[S.jsx("span",{style:{fontSize:10,color:ne?D.accent:D.text.faint,transition:"color 0.2s",lineHeight:1},children:"◆"}),S.jsx("span",{style:{fontSize:9,fontWeight:600,color:ne?D.accent:D.text.faint,textTransform:"uppercase",letterSpacing:"0.04em",transition:"color 0.2s"},children:"Milestone"})]})})()]})]}),S.jsx("button",{ref:O,type:"button",onClick:o,"aria-label":"Close detail",style:{background:"transparent",border:"none",cursor:"pointer",padding:4,borderRadius:4,color:D.text.faint,fontSize:18,lineHeight:1,transition:"color 0.1s"},children:"✕"})]}),S.jsxs("div",{style:{maxHeight:"60vh",overflowY:"auto"},children:[e.detailLoading&&S.jsx("div",{style:{padding:20,display:"flex",flexDirection:"column",gap:10},children:[1,2,3,4,5,6].map(ne=>S.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center"},children:[S.jsx("div",{className:"skeleton",style:{width:120,height:14}}),S.jsx("div",{className:"skeleton",style:{flex:1,height:14}})]},ne))}),e.detailError&&S.jsx("div",{style:{margin:16,padding:"10px 14px",background:D.errorDim,borderRadius:6,color:D.error,fontSize:12},children:e.detailError}),!e.detailLoading&&e.cardDetail&&a&&f&&S.jsx(c6,{assignees:(()=>{const ne=e.cardDetail._assign,Ce=u6(ne);return Ce.length?Ce:typeof ne=="string"&&ne?[]:he?.assignee?[he.assignee]:[]})(),onAssign:ne=>a(r.doctype,M,ne),onUnassign:u?ne=>u(r.doctype,M,ne):void 0,onLoadUsers:f}),we?.descriptionField&&S.jsx("div",{style:{borderBottom:`1px solid ${D.borderSubtle}`},children:S.jsx(a6,{field:we.descriptionField,editedFields:g,onFieldChange:$e})}),we&&we.sections.length>0&&S.jsx(s6,{sections:we.sections,editedFields:g,onFieldChange:$e}),we&&S.jsx(o6,{progressValue:we.progressValue,editedFields:g,onFieldChange:$e})]}),S.jsxs("div",{style:{borderTop:`1px solid ${D.border}`,padding:"8px 16px",display:"flex",flexWrap:"wrap",gap:6,alignItems:"center",flexShrink:0},children:[n&&e.cardDetail&&S.jsxs(S.Fragment,{children:[S.jsx("button",{type:"button",onClick:Je,disabled:!te||_,style:{...at.button,padding:"4px 12px",fontSize:11,fontWeight:600,background:te?D.accent:D.bg.elevated,color:te?"#fff":D.text.faint,borderColor:te?D.accent:D.border,opacity:_?.6:1,borderRadius:5},children:_?"Saving…":"Save"}),te&&S.jsx("button",{type:"button",onClick:()=>{v({}),U(null)},style:{...at.button,padding:"4px 10px",fontSize:11},children:"Discard"}),I&&S.jsx("span",{style:{fontSize:10,fontWeight:500,color:I.isError?D.error:D.success,padding:"1px 6px",borderRadius:3,background:I.isError?D.errorDim:D.successDim},children:I.text}),S.jsx("span",{style:{width:1,height:14,background:D.border,flexShrink:0}})]}),he&&K.length>0&&S.jsxs(S.Fragment,{children:[S.jsx("span",{style:{fontSize:10,fontWeight:600,color:D.text.faint,textTransform:"uppercase",letterSpacing:"0.06em"},children:"Move to"}),K.map(ne=>S.jsxs("button",{type:"button",onClick:()=>{s(he,ne.columnId,ne.label),o()},style:{...at.button,padding:"4px 8px",fontSize:11,display:"inline-flex",alignItems:"center",gap:4},children:[ne.color&&S.jsx("span",{"aria-hidden":"true",style:{width:6,height:6,borderRadius:"50%",background:ne.color,flexShrink:0}}),ne.label]},ne.columnId))]}),h&&he&&K.length>0&&S.jsx("span",{style:{width:1,height:14,background:D.border,flexShrink:0}}),h&&e.selectedCardId&&S.jsxs(S.Fragment,{children:[S.jsx(Ll,{label:"Open in doclist",variant:"info",onClick:()=>h(`Show me a list view of ${r.doctype} ${e.selectedCardId}`)}),r.doctype==="Task"&&S.jsx(Ll,{label:"Timesheets",variant:"info",onClick:()=>h(`Show timesheets for task ${e.selectedCardId}`)}),r.doctype==="Opportunity"&&S.jsx(Ll,{label:"Quotations",variant:"info",onClick:()=>h(`Show quotations linked to opportunity ${e.selectedCardId}`)}),r.doctype==="Issue"&&S.jsx(Ll,{label:"Related tasks",variant:"info",onClick:()=>h(`Show tasks related to issue ${e.selectedCardId}`)})]})]})]})})}const nt=new im({name:"Kanban Viewer",version:"1.0.0"}),qv=15e3,er=1e4;function f6(){return{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0}}const Tn=J4;function Al(e){return e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:e}function lm(e,r){return e.allowedTransitions.filter(o=>o.allowed&&o.fromColumn===r&&o.toColumn!==r).map(o=>{const s=e.columns.find(n=>n.id===o.toColumn);return{columnId:o.toColumn,label:o.label??s?.label??o.toColumn,color:s?.color}})}function p6({children:e,style:r,...o}){const s=ce.useRef(null),n=ce.useRef({active:!1,startX:0,scrollLeft:0}),[a,u]=ce.useState(!1),[f,h]=ce.useState(!1),g=ce.useCallback(()=>{const O=s.current;O&&(u(O.scrollLeft>0),h(O.scrollLeft<O.scrollWidth-O.clientWidth-1))},[]);ce.useEffect(()=>{const O=s.current;if(!O)return;g();const M=new ResizeObserver(g);return M.observe(O),()=>M.disconnect()},[g]);const v=ce.useCallback(O=>{const M=s.current;M&&(n.current={active:!0,startX:O.clientX,scrollLeft:M.scrollLeft},M.style.cursor="grabbing",M.style.userSelect="none")},[]),_=ce.useCallback(O=>{if(!n.current.active)return;const M=s.current;if(!M)return;const he=O.clientX-n.current.startX;M.scrollLeft=n.current.scrollLeft-he,g()},[g]),x=ce.useCallback(()=>{n.current.active=!1;const O=s.current;O&&(O.style.cursor="grab",O.style.userSelect="")},[]);function I(){if(a&&f)return"linear-gradient(to right, transparent, black 24px, black calc(100% - 24px), transparent)";if(f)return"linear-gradient(to right, black calc(100% - 24px), transparent)";if(a)return"linear-gradient(to right, transparent, black 24px)"}const U=I();return S.jsx("div",{ref:s,style:{...r,WebkitMaskImage:U,maskImage:U},onMouseDown:v,onMouseMove:_,onMouseUp:x,onMouseLeave:x,onScroll:g,className:"drag-scroll",...o,children:e})}function m6(){return S.jsx("div",{style:{padding:20},children:S.jsx("div",{style:{display:"flex",gap:12,alignItems:"flex-start",overflowX:"auto"},children:[1,2,3].map(e=>S.jsxs("div",{style:{minWidth:240,display:"flex",flexDirection:"column",gap:8},children:[S.jsx("div",{className:"skeleton",style:{height:36,width:"100%"}}),[1,2,3].map(r=>S.jsx("div",{className:"skeleton",style:{height:72,width:"100%"}},r))]},e))})})}function g6(){return S.jsx("div",{style:{padding:"36px 20px",textAlign:"center",color:D.text.muted,fontFamily:Ct.sans,fontSize:13},children:"No kanban data available"})}function OS({message:e}){return S.jsx("div",{style:{margin:16,...at.card,borderColor:D.error,color:D.error,fontSize:13},children:e})}function CS(e){switch(e){case"error":return{color:D.error,bg:D.errorDim};case"warning":return{color:D.warning,bg:D.warningDim};case"success":return{color:D.success,bg:D.successDim};case"info":return{color:D.info,bg:D.infoDim};default:return{color:D.text.secondary,bg:D.bg.elevated}}}function h6({email:e}){const r=e.charAt(0).toUpperCase(),o=e.indexOf("@"),s=o>0?e.slice(0,o):e;return S.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[S.jsx("span",{style:{width:14,height:14,borderRadius:"50%",background:D.accent,color:"#fff",fontSize:8,fontWeight:700,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:r}),S.jsx("span",{style:{fontSize:10,color:D.text.muted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s})]})}function US({card:e,allowedTargets:r,onMove:o,onDragStart:s,onDragEnd:n,onTitleClick:a,enableDrag:u=!0}){const f=u&&!e.pending,h=e.accent??D.accent,g={background:D.bg.surface,border:`1px solid ${e.pending?D.accent:D.border}`,borderRadius:8,padding:0,display:"flex",flexDirection:"column",opacity:e.pending?.72:1,boxShadow:e.pending?`0 0 0 1px ${D.accentDim}`:"0 1px 3px rgba(0,0,0,0.06)",cursor:f?"grab":void 0,overflow:"hidden",position:"relative"},v=(e.metrics?.length??0)>0,_=(e.badges?.length??0)>0,x={fontSize:13,fontWeight:600,color:D.text.primary,lineHeight:1.35,overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical"};return S.jsxs("article",{style:g,draggable:f,onDragStart:f?I=>s(e,I):void 0,onDragEnd:f?n:void 0,className:e.pending?"animate-pulse":void 0,"aria-busy":e.pending,children:[S.jsx("div",{"aria-hidden":"true",style:{height:4,background:h,flexShrink:0,opacity:e.pending?.5:.85}}),S.jsxs("div",{style:{padding:"10px 12px 0",display:"flex",flexDirection:"column",gap:6},children:[S.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[S.jsxs("div",{style:{flex:1,minWidth:0},children:[a?S.jsx("span",{className:"kanban-card-title-link",role:"button",tabIndex:0,onClick:I=>{I.stopPropagation(),a(e)},onKeyDown:I=>{I.key==="Enter"&&a(e)},style:x,children:e.title}):S.jsx("div",{style:x,children:e.title}),e.subtitle&&S.jsx("div",{style:{fontSize:11,color:D.text.muted,marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.subtitle})]}),_&&S.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,flexShrink:0},children:e.badges?.map(I=>{const U=CS(I.tone);return S.jsx("span",{style:{...at.badge(U.color,U.bg),fontSize:10,padding:"1px 7px",borderRadius:3,fontWeight:700,letterSpacing:"0.03em",textTransform:"uppercase"},children:I.label},`${e.id}-${I.label}`)})})]}),e.description&&S.jsx("div",{style:{fontSize:11,fontStyle:"italic",color:D.text.muted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",lineHeight:1.3},children:e.description}),e.assignee&&S.jsx("div",{style:{marginTop:-2},children:S.jsx(h6,{email:e.assignee})}),v&&S.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:12,padding:"4px 0 2px",borderTop:`1px solid ${D.borderSubtle}`},children:e.metrics?.map(I=>S.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:1},children:[S.jsx("span",{style:{fontSize:9,fontWeight:600,color:D.text.faint,textTransform:"uppercase",letterSpacing:"0.06em"},children:I.label}),S.jsx("span",{style:{fontSize:13,fontWeight:700,color:D.text.primary,fontFamily:Ct.mono,letterSpacing:"-0.02em"},children:I.value})]},`${e.id}-${I.label}`))})]}),r.length>0&&S.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:0,borderTop:`1px solid ${D.borderSubtle}`,marginTop:v?0:6},children:r.map((I,U)=>S.jsxs("button",{type:"button",onClick:()=>o(e,I.columnId,I.label),disabled:e.pending,style:{flex:1,minWidth:0,padding:"7px 6px",fontSize:11,fontWeight:500,fontFamily:Ct.sans,color:D.text.muted,background:"transparent",border:"none",borderRight:U<r.length-1?`1px solid ${D.borderSubtle}`:"none",cursor:e.pending?"default":"pointer",opacity:e.pending?.5:1,transition:"color 0.12s, background 0.12s",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",outlineOffset:-2,display:"flex",alignItems:"center",justifyContent:"center",gap:5},"aria-label":`Move ${e.title} to ${I.label}`,children:[I.color&&S.jsx("span",{"aria-hidden":"true",style:{width:6,height:6,borderRadius:"50%",background:I.color,flexShrink:0}}),I.label]},`${e.id}-${I.columnId}`))})]})}function v6({column:e,cards:r,board:o,activeDropColumn:s,onMove:n,onDropCard:a,onDragStart:u,onDragEnd:f,onDragOverColumn:h,onTitleClick:g}){return S.jsxs("section",{style:{minWidth:260,maxWidth:320,display:"flex",flexDirection:"column",gap:10},onDragOver:v=>h(e.id,v),onDrop:v=>a(e.id,v),children:[S.jsxs("header",{style:{...at.card,padding:"10px 12px",display:"flex",alignItems:"center",gap:8,borderColor:s===e.id?D.accent:D.border,background:s===e.id?D.accentDim:D.bg.surface},children:[S.jsx("span",{"aria-hidden":"true",style:{width:10,height:10,borderRadius:"50%",background:e.color,flexShrink:0}}),S.jsx("span",{style:{fontSize:12,fontWeight:700,color:D.text.primary,flex:1},children:e.label}),S.jsx("span",{style:{...at.badge(e.color,`${e.color}20`)},children:e.count})]}),S.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:r.map(v=>S.jsx(US,{card:v,allowedTargets:lm(o,v.columnId),onMove:n,onDragStart:u,onDragEnd:f,onTitleClick:g},v.id))})]})}function Jv({direction:e,onClick:r}){return S.jsx("button",{type:"button",onClick:r,"aria-label":`Scroll ${e}`,style:{...at.button,padding:"6px 4px",fontSize:12,lineHeight:1,borderRadius:6,flexShrink:0,minWidth:22},children:e==="left"?"‹":"›"})}function y6({columns:e,focusIndex:r,onSelect:o}){const s=ce.useRef([]),[n,a]=ce.useState(!1),[u,f]=ce.useState(!1),h=ce.useCallback(()=>{const g=s.current[0],v=s.current[e.length-1],_=g?.parentElement;!_||!g||!v||(a(_.scrollLeft>0),f(_.scrollLeft<_.scrollWidth-_.clientWidth-1))},[e.length]);return ce.useEffect(h,[h]),ce.useEffect(()=>{const g=s.current[r];if(!g)return;const v=g.parentElement;v&&(v.scrollTo({left:g.offsetLeft-40,behavior:"smooth"}),requestAnimationFrame(h))},[r,h]),S.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,minWidth:0},children:[n&&S.jsx(Jv,{direction:"left",onClick:()=>o(Math.max(0,r-1))}),S.jsx(p6,{onScroll:h,style:{display:"flex",gap:4,overflowX:"auto",minWidth:0,flex:1,cursor:"grab"},role:"tablist","aria-label":"Kanban columns",children:e.map((g,v)=>{const _=v===r;return S.jsxs("button",{ref:x=>{s.current[v]=x},type:"button",role:"tab","aria-selected":_,"aria-controls":`kanban-panel-${g.id}`,onClick:()=>o(v),style:{...at.button,padding:"7px 14px 6px",fontSize:12,fontWeight:_?700:500,color:_?D.text.primary:D.text.muted,background:_?D.bg.surface:"transparent",borderColor:_?"transparent":D.border,borderBottomWidth:2,borderBottomColor:_?g.color:"transparent",borderRadius:_?"6px 6px 0 0":"6px",display:"flex",alignItems:"center",gap:6,whiteSpace:"nowrap",flexShrink:0},children:[S.jsx("span",{"aria-hidden":"true",style:{width:8,height:8,borderRadius:"50%",background:g.color,flexShrink:0}}),g.label,S.jsx("span",{style:{...at.badge(_?D.text.primary:D.text.muted,_?`${g.color}30`:`${D.text.muted}15`),fontSize:10},children:g.count})]},g.id)})}),u&&S.jsx(Jv,{direction:"right",onClick:()=>o(Math.min(e.length-1,r+1))})]})}function _6({board:e,inlineError:r,activeDropColumn:o,onMove:s,onDropCard:n,onDragStart:a,onDragEnd:u,onDragOverColumn:f,onTitleClick:h}){const[g,v]=ce.useState(typeof window<"u"?window.innerWidth:1200),[_,x]=ce.useState(0);ce.useEffect(()=>{function M(){v(window.innerWidth)}return window.addEventListener("resize",M),()=>window.removeEventListener("resize",M)},[]);const I=H4(g,e.columns.length),U=q4(_,e.columns.length),O=I?e.columns[U]:null;return S.jsxs("div",{style:{display:"flex",flexDirection:"column",minHeight:600,background:D.bg.root,overflowX:"hidden",width:"100%"},children:[S.jsx(Ml,{}),S.jsxs("div",{style:{padding:"14px 16px",display:"flex",flexDirection:"column",gap:14,minWidth:0},children:[S.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[S.jsx("div",{style:{fontSize:14,fontWeight:700,color:D.text.primary},children:e.title}),S.jsx("div",{style:{fontSize:11,color:D.text.muted},children:N4(e)})]}),r&&S.jsx(OS,{message:r}),I?S.jsxs(S.Fragment,{children:[S.jsx(y6,{columns:e.columns,focusIndex:U,onSelect:x}),O&&S.jsxs("div",{id:`kanban-panel-${O.id}`,role:"tabpanel","aria-label":O.label,style:{display:"flex",flexDirection:"column",gap:8,minWidth:0},children:[e.cards.filter(M=>M.columnId===O.id).map(M=>S.jsx(US,{card:M,allowedTargets:lm(e,M.columnId),onMove:s,onDragStart:a,onDragEnd:u,onTitleClick:h,enableDrag:!1},M.id)),e.cards.filter(M=>M.columnId===O.id).length===0&&S.jsxs("div",{style:{padding:"20px 12px",textAlign:"center",fontSize:12,color:D.text.muted},children:["No cards in ",O.label]})]})]}):S.jsx("div",{style:{display:"flex",gap:12,alignItems:"flex-start",overflowX:"auto",paddingBottom:8},children:e.columns.map(M=>S.jsx(v6,{column:M,board:e,cards:e.cards.filter(he=>he.columnId===M.id),activeDropColumn:o,onMove:s,onDropCard:n,onDragStart:a,onDragEnd:u,onDragOverColumn:f,onTitleClick:h},M.id))})]})]})}function Wv(e){return JSON.parse(e)}function $6(){const{state:e,hydrateBoard:r,setError:o,startLoading:s,selectCard:n,hydrateDetail:a,closeDetail:u,setDetailError:f}=C4(),[h,g]=ce.useState(""),[v,_]=ce.useState(null),x=ce.useRef([]),I=ce.useRef({}),U=ce.useRef(!1),O=ce.useRef(null),M=ce.useRef(null),he=ce.useRef(!1),xe=ce.useRef(null),K=ce.useRef(!1),te=ce.useRef(!1),$e=ce.useRef(0),Je=ce.useRef(null);function De(L){O.current=L,r(L)}function we(L){const J=Tn(L);if(!J)throw new Error("No text payload returned by tool call");return JSON.parse(J)}function ne(L){const J=Tn(L);if(!J)return"Tool call failed";try{const W=JSON.parse(J);return String(W.errorMessage??W.message??J)}catch{return J}}async function Ce(L={}){const J=O.current,W=Z4(J,xe.current);if(!M4({board:J,request:W,visibilityState:typeof document>"u"?"visible":document.visibilityState,dragging:he.current,processingMove:U.current,queuedMoves:x.current.length,refreshInFlight:K.current,now:Date.now(),lastRefreshStartedAt:$e.current,minIntervalMs:qv},L)||!W||!nt.getHostCapabilities()?.serverTools)return!1;K.current=!0,$e.current=Date.now();try{const Y=await nt.callServerTool({name:W.toolName,arguments:W.arguments},{timeout:er});if(Y.isError)return!1;const oe=Tn(Y);return oe?(De(Wv(oe)),!0):!1}catch{return!1}finally{K.current=!1}}async function Rt(){if(U.current)return;const{nextMove:L,restQueue:J}=L4(x.current);if(!L)return;if(!O.current){x.current=J;return}x.current=J,U.current=!0;const W=L.queueId??L.cardId;if(!I.current[W]){const Y=Fv(O.current,L);I.current[W]=Y.snapshot,De(Y.board)}try{if(!nt.getHostCapabilities()?.serverTools)throw new Error("Host does not support proxied server tool calls");const Y=await nt.callServerTool({name:L.moveToolName,arguments:{doctype:L.doctype,card_id:L.cardId,from_column:L.fromColumn,to_column:L.toColumn}},{timeout:er});if(Y.isError){const oe=I.current[W],le=rd(ne(Y));oe&&De(id(oe,{errorMessage:le})),o(le),g(le)}else{const oe=we(Y);if(oe.ok!==!1){if(O.current){const Ie=U4(O.current,{cardId:L.cardId,toColumn:L.toColumn,serverCard:oe.serverCard});De(Ie),te.current=!0;const Te=Ie.columns.find(mn=>mn.id===L.toColumn)?.label??L.toColumn;g(`Moved ${L.cardId} to ${Te}`)}}else{const Ie=I.current[W],Te=rd(String(oe.errorMessage??"Move failed"));Ie&&De(id(Ie,{errorMessage:Te})),o(Te),g(Te)}}}catch(Y){const oe=I.current[W],le=rd(Y);oe&&De(id(oe)),o(le),g(le)}finally{delete I.current[W],U.current=!1,x.current.length>0?Rt():te.current&&(te.current=!1,Ce({ignoreInterval:!0}))}}function yt(L,J,W){const Y=O.current;if(!Y||L.pending||L.columnId===J)return;if(!Y.allowedTransitions.find(Te=>Te.allowed&&Te.fromColumn===L.columnId&&Te.toColumn===J)){const Te=`Move to ${W} is not allowed`;o(Te),g(Te);return}const le={queueId:crypto.randomUUID(),doctype:Y.doctype,moveToolName:Y.moveToolName,cardId:L.id,fromColumn:L.columnId,toColumn:J};if(!U.current&&x.current.length===0){const Te=Fv(Y,le);I.current[le.queueId??le.cardId]=Te.snapshot,De(Te.board),g(`Moving ${L.title} to ${W}`)}else g(`${L.title} queued for ${W}`);x.current=R4(x.current,le),Rt()}ce.useEffect(()=>{nt.ontoolinput=L=>{const J=nt.getHostContext()?.toolInfo?.tool.name;J&&L.arguments&&(xe.current={toolName:J,arguments:L.arguments}),O.current||s()},nt.ontoolresult=L=>{const J=Tn(L);if(!J){o("No kanban payload received from tool result");return}try{De(Wv(J))}catch(W){o(W instanceof Error?W.message:"Failed to parse kanban payload")}},nt.ontoolinputpartial=()=>{O.current||s()},nt.connect().catch(()=>{o("Failed to connect MCP App host")})},[]),ce.useEffect(()=>{const L=window.setInterval(()=>{Ce()},qv);function J(){Ce({ignoreInterval:!0})}function W(){document.visibilityState==="visible"&&Ce({ignoreInterval:!0})}return window.addEventListener("focus",J),document.addEventListener("visibilitychange",W),()=>{window.clearInterval(L),window.removeEventListener("focus",J),document.removeEventListener("visibilitychange",W)}},[]),ce.useEffect(()=>{O.current=e.board},[e.board]);function st(L,J){M.current=L.id,he.current=!0,J.dataTransfer.effectAllowed="move",J.dataTransfer.setData("application/json",JSON.stringify({cardId:L.id,fromColumn:L.columnId,title:L.title}))}function Lt(){M.current=null,he.current=!1,_(null)}function Kt(L,J){const W=O.current,Y=M.current;if(!W||!Y||!A4(W,Y,L)){_(null);return}J.preventDefault(),_(L)}function _t(L,J){J.preventDefault(),_(null);try{const W=J.dataTransfer.getData("application/json");if(!W||!O.current)return;const Y=JSON.parse(W),oe=O.current.cards.find(Ie=>Ie.id===Y.cardId),le=O.current.columns.find(Ie=>Ie.id===L)?.label??L;oe&&yt(oe,L,le)}catch{o("Failed to read dragged kanban card")}}function We(L){if(!O.current)return;const J=L.id;Je.current=J,n(J),(async()=>{try{const W=await nt.callServerTool({name:"erpnext_doc_get",arguments:{doctype:O.current.doctype,name:J}},{timeout:er});if(Je.current!==J)return;if(W.isError){f(ne(W));return}const Y=Tn(W);if(!Y){f("No detail payload returned");return}a(Al(JSON.parse(Y)))}catch(W){if(Je.current!==J)return;f(W instanceof Error?W.message:"Failed to fetch detail")}})()}async function B(L){try{await nt.sendMessage({role:"user",content:[{type:"text",text:L}]})}catch{}}async function de(L,J,W){if(!nt.getHostCapabilities()?.serverTools)throw new Error("Host does not support proxied server tool calls");const Y={},oe=e.detail.cardDetail;for(const[Te,mn]of Object.entries(W))if(typeof oe?.[Te]=="number"){const jr=Number(mn);Y[Te]=Number.isFinite(jr)?jr:mn}else Y[Te]=mn;const le=await nt.callServerTool({name:"erpnext_doc_update",arguments:{doctype:L,name:J,data:Y}},{timeout:er});if(le.isError)throw new Error(ne(le));const Ie=await nt.callServerTool({name:"erpnext_doc_get",arguments:{doctype:L,name:J}},{timeout:er});if(!Ie.isError){const Te=Tn(Ie);Te&&a(Al(JSON.parse(Te)))}Ce({ignoreInterval:!0})}async function Q(){if(!nt.getHostCapabilities()?.serverTools)throw new Error("Host does not support proxied server tool calls");const L=await nt.callServerTool({name:"erpnext_user_list",arguments:{limit:100}},{timeout:er});if(L.isError)throw new Error(ne(L));const J=Tn(L);if(!J)return[];let W;try{W=JSON.parse(J)}catch{throw new Error("Could not read the user list returned by the server")}return W.data??[]}async function b(L,J,W){if(!nt.getHostCapabilities()?.serverTools)throw new Error("Host does not support proxied server tool calls");const Y=await nt.callServerTool({name:"erpnext_doc_assign",arguments:{doctype:L,name:J,assign_to:W}},{timeout:er});if(Y.isError)throw new Error(ne(Y));const oe=Tn(Y);if(oe)try{const le=JSON.parse(oe),Ie=Al(le);if(!Ie._assign){const Te=le.assignment;Te?.assignees?.length&&(Ie._assign=JSON.stringify(Te.assignees))}a(Ie)}catch(le){console.warn("[handleAssignDetail] Could not hydrate the assigned doc:",le)}Ce({ignoreInterval:!0})}async function R(L,J,W){if(!nt.getHostCapabilities()?.serverTools)throw new Error("Host does not support proxied server tool calls");const Y=await nt.callServerTool({name:"erpnext_doc_unassign",arguments:{doctype:L,name:J,assign_to:W}},{timeout:er});if(Y.isError)throw new Error(ne(Y));const oe=Tn(Y);if(oe)try{const le=JSON.parse(oe),Ie=Al(le);if(!Ie._assign){const Te=le.assignment;Ie._assign=JSON.stringify((Te?.remaining??[]).map(mn=>mn.owner).filter(Boolean))}a(Ie)}catch(le){console.warn("[handleUnassignDetail] Could not hydrate the doc:",le)}Ce({ignoreInterval:!0})}if(e.loading)return S.jsxs("div",{style:{minHeight:600,background:D.bg.root},children:[S.jsx(Ml,{}),S.jsx(m6,{})]});const ve=P4(e);return ve.blockingError?S.jsxs("div",{style:{minHeight:600,background:D.bg.root},children:[S.jsx(Ml,{}),S.jsx(OS,{message:ve.blockingError})]}):e.board?S.jsxs(S.Fragment,{children:[S.jsx("div",{"aria-live":"polite",style:f6(),children:h}),S.jsx(_6,{board:e.board,inlineError:ve.inlineError,activeDropColumn:v,onMove:yt,onDropCard:_t,onDragStart:st,onDragEnd:Lt,onDragOverColumn:Kt,onTitleClick:We}),e.detail.selectedCardId&&e.board&&S.jsx(d6,{detail:e.detail,board:e.board,onClose:u,onMove:yt,onSave:de,onAssign:b,onUnassign:R,onLoadUsers:Q,onNavigate:B})]}):S.jsxs("div",{style:{minHeight:600,background:D.bg.root},children:[S.jsx(Ml,{}),S.jsx(g6,{})]})}Zb.createRoot(document.getElementById("app")).render(S.jsx($6,{}));</script>
149
149
  <style rel="stylesheet" crossorigin>:root{--accent: #0089ff;--accent-dim: rgba(0, 137, 255, .15);--accent-border: rgba(0, 137, 255, .3);--success: #16a34a;--success-dim: rgba(22, 163, 74, .1);--error: #dc2626;--error-dim: rgba(220, 38, 38, .1);--warning: #d97706;--warning-dim: rgba(217, 119, 6, .1);--info: #2563eb;--info-dim: rgba(37, 99, 235, .1);--radius-sm: 4px;--radius-md: 6px;--radius-lg: 8px;--font-sans: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;--font-mono: "SF Mono", "Cascadia Code", "Fira Code", monospace;--bg-root: #ffffff;--bg-surface: #f9fafb;--bg-elevated: #f3f4f6;--bg-hover: #e5e7eb;--bg-active: #d1d5db;--text-primary: #111827;--text-secondary: #4b5563;--text-muted: #6b7280;--text-faint: #9ca3af;--border: #e5e7eb;--border-subtle: #f3f4f6;--shadow-sm: 0 1px 2px rgba(0, 0, 0, .05);--shadow-md: 0 2px 8px rgba(0, 0, 0, .08)}@media(prefers-color-scheme:dark){:root{--bg-root: #08080a;--bg-surface: #111113;--bg-elevated: #18181b;--bg-hover: #1f1f23;--bg-active: #27272a;--text-primary: #e7e5e4;--text-secondary: #a8a29e;--text-muted: #78716c;--text-faint: #57534e;--border: #27272a;--border-subtle: #1f1f23;--success: #4ade80;--success-dim: rgba(74, 222, 128, .12);--error: #f87171;--error-dim: rgba(248, 113, 113, .12);--warning: #fbbf24;--warning-dim: rgba(251, 191, 36, .12);--info: #60a5fa;--info-dim: rgba(96, 165, 250, .12);--shadow-sm: 0 1px 2px rgba(0, 0, 0, .3);--shadow-md: 0 2px 8px rgba(0, 0, 0, .4)}}*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}html{border-radius:var(--radius-lg);overflow:hidden}html,body{background:var(--bg-root);color:var(--text-primary);font-family:var(--font-sans);font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}body{overflow:auto}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px}::-webkit-scrollbar-thumb:hover{background:var(--text-faint)}@keyframes pulse{0%,to{opacity:.4}50%{opacity:.15}}@keyframes shimmer{0%{background-position:-200% 0}to{background-position:200% 0}}.animate-pulse{animation:pulse 1.5s ease-in-out infinite}.skeleton{background:linear-gradient(90deg,var(--bg-elevated) 25%,var(--bg-hover) 50%,var(--bg-elevated) 75%);background-size:200% 100%;animation:shimmer 1.5s infinite;border-radius:var(--radius-sm)}.drag-scroll::-webkit-scrollbar{display:none}.drag-scroll{scrollbar-width:none}article button:hover:not(:disabled){background:var(--bg-hover)!important;color:var(--text-primary)!important}article[draggable=true]:active{cursor:grabbing;opacity:.85}.kanban-detail-backdrop{position:fixed;inset:0;z-index:100;background:#00000073;display:flex;align-items:flex-start;justify-content:center;padding:20px 12px;overflow-y:auto;backdrop-filter:blur(2px)}.kanban-detail-panel{background:var(--bg-root);border:1px solid var(--border);border-radius:10px;max-width:520px;width:100%;box-shadow:0 8px 32px #0000001f,0 2px 8px #0000000f;position:relative;display:flex;flex-direction:column}.kanban-detail-panel .detail-field-row{transition:background .1s}.kanban-detail-panel .detail-field-row:hover{background:var(--bg-surface)}.kanban-detail-panel .detail-field-cell{transition:background .1s;border-radius:4px}.kanban-detail-panel .detail-field-cell:hover{background:var(--bg-surface)}.kanban-detail-panel .detail-field-cell:hover input,.kanban-detail-panel .detail-field-cell:hover select{border-color:var(--border)!important;background:var(--bg-elevated)!important}.kanban-detail-panel select:focus{border-color:var(--accent)!important;box-shadow:0 0 0 2px var(--accent-dim);outline:none}.kanban-detail-panel input:focus{border-color:var(--accent)!important;box-shadow:0 0 0 2px var(--accent-dim);outline:none}.kanban-detail-panel textarea:focus{border-color:var(--accent)!important;box-shadow:0 0 0 2px var(--accent-dim);outline:none}@media(prefers-color-scheme:dark){.kanban-detail-backdrop{background:#000000a6}.kanban-detail-panel{box-shadow:0 8px 32px #0006,0 2px 8px #0000004d}}.kanban-card-title-link{cursor:pointer;text-decoration:none;color:inherit}.kanban-card-title-link:hover{text-decoration:underline;text-decoration-thickness:1px;text-underline-offset:2px}</style>
150
150
  </head>
151
151
  <body>
@@ -145,7 +145,7 @@ Boolean requesting whether a visible border and background is provided by the ho
145
145
  - omitted: host decides border`)});T({method:x("ui/request-display-mode"),params:T({mode:vo.describe("The display mode being requested.")})});var i4=T({mode:vo.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),o4=se([x("model"),x("app")]).describe("Tool visibility scope - who can access the tool.");T({resourceUri:I().optional(),visibility:ee(o4).optional().describe(`Who can access this tool. Default: ["model", "app"]
146
146
  - "model": Tool visible to and callable by the agent
147
147
  - "app": Tool callable by the app from this server only`),csp:hr().optional(),permissions:hr().optional()});T({mimeTypes:ee(I()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')});T({method:x("ui/download-file"),params:T({contents:ee(se([sS,cS])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})});T({method:x("ui/message"),params:T({role:x("user").describe('Message role, currently only "user" is supported.'),content:ee(ha).describe("Message content blocks (text, image, etc.).")})});T({method:x("ui/notifications/sandbox-resource-ready"),params:T({html:I().describe("HTML content to load into the inner iframe."),sandbox:I().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Bm.optional().describe("CSP configuration from resource metadata."),permissions:Km.optional().describe("Sandbox permissions from resource metadata.")})});var a4=T({method:x("ui/notifications/tool-result"),params:Qu.describe("Standard MCP tool execution result.")}),gS=T({toolInfo:T({id:da.optional().describe("JSON-RPC id of the tools/call request."),tool:Wm.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:H1.optional().describe("Current color theme preference."),styles:e4.optional().describe("Style configuration for theming the app."),displayMode:vo.optional().describe("How the UI is currently displayed."),availableDisplayModes:ee(vo).optional().describe("Display modes the host supports."),containerDimensions:se([T({height:oe().describe("Fixed container height in pixels.")}),T({maxHeight:se([oe(),ri()]).optional().describe("Maximum container height in pixels.")})]).and(se([T({width:oe().describe("Fixed container width in pixels.")}),T({maxWidth:se([oe(),ri()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
148
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:I().optional().describe("User's language and region preference in BCP 47 format."),timeZone:I().optional().describe("User's timezone in IANA format."),userAgent:I().optional().describe("Host application identifier."),platform:se([x("web"),x("desktop"),x("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:T({touch:ke().optional().describe("Whether the device supports touch input."),hover:ke().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:T({top:oe().describe("Top safe area inset in pixels."),right:oe().describe("Right safe area inset in pixels."),bottom:oe().describe("Bottom safe area inset in pixels."),left:oe().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),l4=T({method:x("ui/notifications/host-context-changed"),params:gS.describe("Partial context update containing only changed fields.")});T({method:x("ui/update-model-context"),params:T({content:ee(ha).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:pe(I(),$e().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})});T({method:x("ui/initialize"),params:T({appInfo:Ku.describe("App identification (name and version)."),appCapabilities:r4.describe("Features and capabilities this app provides."),protocolVersion:I().describe("Protocol version this app supports.")})});var u4=T({protocolVersion:I().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Ku.describe("Host application identification and version."),hostCapabilities:n4.describe("Features and capabilities provided by the host."),hostContext:gS.describe("Rich context about the host environment.")}).passthrough(),s4={target:"draft-2020-12"};async function Ph(n,i){let o=n["~standard"];if(o.jsonSchema)return o.jsonSchema[i](s4);if(o.vendor==="zod"){let{z:u}=await bb(()=>Promise.resolve().then(()=>QI),void 0,import.meta.url);return u.toJSONSchema(n,{io:i})}throw Error(`Schema (vendor: ${o.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function jh(n,i,o=""){let u=await n["~standard"].validate(i);if(u.issues){let t=u.issues.map(a=>{let c=a.path?.map(f=>typeof f=="object"?f.key:f).join(".");return c?`${c}: ${a.message}`:a.message}).join("; ");throw Error(o+t)}return u.value}class Gm extends A1{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(i){if(this._initializedSent)return;let o=`[ext-apps] App.${i}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(o);console.warn(`${o}. This will throw in a future release.`)}eventSchemas={toolinput:G1,toolinputpartial:Q1,toolresult:a4,toolcancelled:X1,hostcontextchanged:l4};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(i){if(!Gm.ONE_SHOT_EVENTS.has(i)||this._everHadListener.has(i)||(this._everHadListener.add(i),!this._initializedSent))return;let o=`[ext-apps] "${String(i)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(o);console.warn(o)}setEventHandler(i,o){o&&this._assertHandlerTiming(i),super.setEventHandler(i,o)}addEventListener(i,o){this._assertHandlerTiming(i),super.addEventListener(i,o)}onEventDispatch(i,o){i==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...o})}constructor(i,o={},u={autoResize:!0}){super(u),this._appInfo=i,this._capabilities=o,this.options=u,u.allowUnsafeEval||Ke({jitless:!0}),this.setRequestHandler(Gu,t=>(console.log("Received ping:",t.params),{})),this.setEventHandler("hostcontextchanged",void 0)}registerCapabilities(i){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._capabilities=Z1(this._capabilities,i)}registerTool(i,o,u){if(this._registeredTools[i])throw Error(`Tool ${i} is already registered`);let t=this,a=()=>{t._initializedSent&&t._capabilities.tools?.listChanged&&t.sendToolListChanged()},c=o.inputSchema!==void 0,f={title:o.title,description:o.description,inputSchema:o.inputSchema,outputSchema:o.outputSchema,annotations:o.annotations,_meta:o._meta,enabled:!0,enable(){this.enabled=!0,a()},disable(){this.enabled=!1,a()},update(v){Object.assign(this,v),a()},remove(){t._registeredTools[i]===f&&(delete t._registeredTools[i],a())},handler:async(v,g)=>{if(!f.enabled)throw Error(`Tool ${i} is disabled`);let y;if(c){let k=f.inputSchema,P=k?await jh(k,v??{},`Invalid input for tool ${i}: `):v??{};y=await u(P,g)}else y=await u(g);return f.outputSchema&&!y.isError&&(y.structuredContent=await jh(f.outputSchema,y.structuredContent,`Invalid output for tool ${i}: `)),y}};return this._registeredTools[i]=f,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),a(),f}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(i,o)=>{let u=this._registeredTools[i.name];if(!u)throw Error(`Tool ${i.name} not found`);return u.handler(i.arguments,o)},this.onlisttools=async(i,o)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([u,t])=>t.enabled).map(async([u,t])=>{let a={name:u,title:t.title,description:t.description,inputSchema:t.inputSchema?await Ph(t.inputSchema,"input"):{type:"object",properties:{}}};return t.outputSchema&&(a.outputSchema=await Ph(t.outputSchema,"output")),t.annotations&&(a.annotations=t.annotations),t._meta&&(a._meta=t._meta),a}))}))}async sendToolListChanged(i={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:i})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(i){this.setEventHandler("toolinput",i)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(i){this.setEventHandler("toolinputpartial",i)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(i){this.setEventHandler("toolresult",i)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(i){this.setEventHandler("toolcancelled",i)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(i){this.setEventHandler("hostcontextchanged",i)}_onteardown;get onteardown(){return this._onteardown}set onteardown(i){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,i),this._onteardown=i,this.replaceRequestHandler(t4,(o,u)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(o.params,u)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(i){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,i),this._oncalltool=i,this.replaceRequestHandler(fS,(o,u)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(o.params,u)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(i){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,i),this._onlisttools=i,this.replaceRequestHandler(dS,(o,u)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(o.params,u)})}assertCapabilityForMethod(i){switch(i){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${i})`);break}}assertRequestHandlerCapability(i){switch(i){case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${i})`);return;case"ping":case"ui/resource-teardown":return;default:throw Error(`No handler for method ${i} registered`)}}assertNotificationCapability(i){}assertTaskCapability(i){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(i){throw Error("Task handlers are not supported in MCP Apps")}async callServerTool(i,o){if(this._assertInitialized("callServerTool"),typeof i=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${i}"). Did you mean: callServerTool({ name: "${i}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:i},Qu,{onprogress:()=>{},resetTimeoutOnProgress:!0,...o})}async readServerResource(i,o){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:i},uS,o)}async listServerResources(i,o){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:i},lS,o)}async createSamplingMessage(i,o){this._assertInitialized("createSamplingMessage");let u=i.tools?vS:pS;return await this.request({method:"sampling/createMessage",params:i},u,o)}sendMessage(i,o){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:i},K1,o)}sendLog(i){return this.notification({method:"notifications/message",params:i})}updateModelContext(i,o){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:i},Nm,o)}openLink(i,o){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:i},W1,o)}sendOpenLink=this.openLink;downloadFile(i,o){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:i},B1,o)}requestTeardown(i={}){return this.notification({method:"ui/notifications/request-teardown",params:i})}requestDisplayMode(i,o){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:i},i4,o)}sendSizeChanged(i){return this.notification({method:"ui/notifications/size-changed",params:i})}setupSizeChangedNotifications(){let i=!1,o=0,u=0,t=()=>{i||(i=!0,requestAnimationFrame(()=>{i=!1;let c=document.documentElement,f=c.style.height;c.style.height="max-content";let v=Math.ceil(c.getBoundingClientRect().height);c.style.height=f;let g=Math.ceil(window.innerWidth);(g!==o||v!==u)&&(o=g,u=v,this.sendSizeChanged({width:g,height:v}))}))};t();let a=new ResizeObserver(t);return a.observe(document.documentElement),a.observe(document.body),()=>a.disconnect()}async connect(i=new q1(window.parent,window.parent),o){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1,await super.connect(i);try{let u=await this.request({method:"ui/initialize",params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:M1}},u4,o);if(u===void 0)throw Error(`Server sent invalid initialize result: ${u}`);this._hostCapabilities=u.hostCapabilities,this._hostInfo=u.hostInfo,this._hostContext=u.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(u){throw this.close(),u}}}function dr(n){return`var(${n})`}const Kr={bg:{surface:dr("--bg-surface")},text:{muted:dr("--text-muted"),faint:dr("--text-faint")},accent:dr("--accent"),border:dr("--border")},Jn={sans:dr("--font-sans"),mono:dr("--font-mono")};function td(n,i=2){return n.toLocaleString("en-US",{minimumFractionDigits:i,maximumFractionDigits:i})}function c4(n,i="USD"){return n.toLocaleString("en-US",{style:"currency",currency:i,minimumFractionDigits:2,maximumFractionDigits:2})}function d4(){return de.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:[de.jsx("rect",{x:"1",y:"1",width:"6",height:"6",rx:"1.5",fill:"currentColor",opacity:"0.9"}),de.jsx("rect",{x:"9",y:"1",width:"6",height:"6",rx:"1.5",fill:"currentColor",opacity:"0.6"}),de.jsx("rect",{x:"1",y:"9",width:"6",height:"6",rx:"1.5",fill:"currentColor",opacity:"0.6"}),de.jsx("rect",{x:"9",y:"9",width:"6",height:"6",rx:"1.5",fill:"currentColor",opacity:"0.35"})]})}function f4(){const n={display:"flex",alignItems:"center",gap:7,padding:"0 14px",height:30,background:Kr.bg.surface,borderBottom:`1px solid ${Kr.border}`,flexShrink:0},i={fontFamily:Jn.sans,fontSize:11,fontWeight:700,letterSpacing:"0.08em",textTransform:"uppercase",color:Kr.accent},o={width:3,height:3,borderRadius:"50%",background:Kr.text.faint,marginLeft:2,marginRight:2,flexShrink:0},u={fontFamily:Jn.sans,fontSize:10,color:Kr.text.muted,letterSpacing:"0.03em"};return de.jsxs("div",{style:n,children:[de.jsx("div",{style:{color:Kr.accent},children:de.jsx(d4,{})}),de.jsx("span",{style:i,children:"ERPNext"}),de.jsx("div",{style:o}),de.jsx("span",{style:u,children:"gestion ERP"})]})}function m4(n,i={}){return!n.request||n.visibilityState!=="visible"||n.refreshInFlight?!1:i.ignoreInterval?!0:n.now-n.lastRefreshStartedAt>=n.minIntervalMs}function Nh(n,i){return n?.refreshRequest??i}function p4(n){return n instanceof Error&&/timed? out/i.test(n.message)?"Refresh timed out":"Refresh failed"}function v4(n){return n.structuredContent?JSON.stringify(n.structuredContent):n.content?.find(i=>i.type==="text")?.text??null}const fr=new Gm({name:"KPI Viewer",version:"1.0.0"}),g4=15e3,h4=1e4;function y4({data:n,color:i}){if(n.length<2)return null;const o=60,u=24,t=2,a=Math.min(...n),f=Math.max(...n)-a||1,v=n.map((g,y)=>{const k=t+y/(n.length-1)*(o-t*2),P=t+(1-(g-a)/f)*(u-t*2);return`${k},${P}`}).join(" ");return de.jsx("svg",{width:o,height:u,viewBox:`0 0 ${o} ${u}`,style:{flexShrink:0},"aria-hidden":"true",children:de.jsx("polyline",{points:v,fill:"none",stroke:i,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function _4({delta:n,deltaLabel:i,trend:o,trendIsGood:u}){const t=o??(n>0?"up":n<0?"down":"flat"),a=t==="up"?"▲":t==="down"?"▼":"◆";let c,f;if(t==="flat")c="var(--text-muted)",f="var(--bg-hover)";else if(u===void 0)c="var(--info)",f="var(--info-dim)";else{const y=t==="up",k=u?y:!y;c=k?"var(--success)":"var(--error)",f=k?"var(--success-dim)":"var(--error-dim)"}const g=`${n>0?"+":""}${td(Math.abs(n),Math.abs(n)<10?1:0)}`;return de.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",fontSize:11,fontWeight:600,fontFamily:Jn.mono,borderRadius:4,color:c,background:f,letterSpacing:"0.02em"},children:[de.jsx("span",{style:{fontSize:8},children:a}),g,"%",i&&de.jsx("span",{style:{fontWeight:400,fontFamily:Jn.sans,opacity:.75,marginLeft:2},children:i})]})}function $4(){return de.jsx("div",{style:{padding:16},children:de.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[de.jsx("div",{className:"skeleton",style:{height:12,width:"35%"}}),de.jsx("div",{className:"skeleton",style:{height:36,width:"55%"}}),de.jsx("div",{className:"skeleton",style:{height:16,width:"40%"}})]})})}function k4({data:n,error:i,refreshing:o,onRefresh:u}){const t=n.color??"var(--accent)",a=fr.getHostCapabilities()?.serverTools;async function c(g){try{await fr.sendMessage({role:"user",content:[{type:"text",text:g}]})}catch{}}let f;if(n.formattedValue)f=n.formattedValue;else if(n.currency)f=c4(n.value,n.currency);else if(n.unit==="%")f=`${td(n.value,n.value%1===0?0:1)}%`;else{const g=n.value%1===0?0:2;f=td(n.value,g),n.unit&&(f+=` ${n.unit}`)}const v=n.color??"#60a5fa";return de.jsxs("div",{style:{fontFamily:Jn.sans,background:"var(--bg-root)",overflow:"hidden"},children:[de.jsx(f4,{}),de.jsx("div",{style:{padding:"12px 16px 14px"},children:de.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between"},children:[de.jsxs("div",{style:{flex:1,minWidth:0},children:[de.jsx("div",{style:{fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em",color:"var(--text-muted)",marginBottom:6},children:n.label}),de.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6},children:[de.jsx("button",{onClick:u,disabled:o,style:{border:"1px solid var(--border)",background:"var(--bg-elevated)",color:"var(--text-secondary)",borderRadius:6,padding:"4px 8px",fontSize:11,fontFamily:Jn.sans,cursor:o?"default":"pointer"},children:o?"Refreshing":"Refresh"}),de.jsx("div",{"aria-live":"polite",style:{fontSize:11,color:i?"var(--error)":o?"var(--text-muted)":"var(--text-faint)"},children:i??(o?"Refreshing…":"Auto-refresh on focus")})]}),de.jsx("div",{onClick:a&&n._drillDown?()=>c(n._drillDown):void 0,style:{fontSize:32,fontWeight:700,fontFamily:Jn.mono,color:t,lineHeight:1.1,marginBottom:8,cursor:a&&n._drillDown?"pointer":"default",transition:"opacity 0.15s"},onMouseEnter:g=>{n._drillDown&&(g.currentTarget.style.opacity="0.75")},onMouseLeave:g=>{g.currentTarget.style.opacity="1"},title:n._drillDown?"Click to drill down":void 0,children:f}),n.delta!==void 0&&de.jsx(_4,{delta:n.delta,deltaLabel:n.deltaLabel,trend:n.trend,trendIsGood:n.trendIsGood})]}),n.sparkline&&n.sparkline.length>=2&&de.jsx("div",{style:{paddingTop:20,paddingLeft:12,cursor:a&&n._trendDrillDown?"pointer":"default"},onClick:a&&n._trendDrillDown?()=>c(n._trendDrillDown):void 0,title:n._trendDrillDown?"Click to see trend details":void 0,children:de.jsx(y4,{data:n.sparkline,color:v})})]})})]})}function S4(){const[n,i]=sn.useState(null),[o,u]=sn.useState(!0),[t,a]=sn.useState(!1),[c,f]=sn.useState(null),v=sn.useRef(null),g=sn.useRef(null),y=sn.useRef(!1),k=sn.useRef(0);function P(B){v.current=B,g.current=Nh(B,g.current),i(B)}function j(B){const q=v4(B);if(!q)return!1;try{const Oe=JSON.parse(q);return P(Oe),f(null),u(!1),!0}catch(Oe){return console.error("Parse error:",Oe),f("Failed to parse KPI payload"),u(!1),!1}}async function Z(B={}){const q=Nh(v.current,g.current);if(!m4({request:q,visibilityState:typeof document>"u"?"visible":document.visibilityState,refreshInFlight:y.current,now:Date.now(),lastRefreshStartedAt:k.current,minIntervalMs:g4},B)||!q||!fr.getHostCapabilities()?.serverTools)return!1;y.current=!0,k.current=Date.now(),a(!0);try{const Oe=await fr.callServerTool({name:q.toolName,arguments:q.arguments},{timeout:h4});return Oe.isError?(f("Refresh failed"),!1):j(Oe)?!0:(f("Refresh returned no data"),!1)}catch(Oe){return f(p4(Oe)),!1}finally{y.current=!1,a(!1)}}return sn.useEffect(()=>{fr.connect().catch(()=>{}),fr.ontoolresult=B=>{j(B)},fr.ontoolinputpartial=()=>{v.current||u(!0)}},[]),sn.useEffect(()=>{function B(){Z({ignoreInterval:!0})}function q(){document.visibilityState==="visible"&&Z({ignoreInterval:!0})}return window.addEventListener("focus",B),document.addEventListener("visibilitychange",q),()=>{window.removeEventListener("focus",B),document.removeEventListener("visibilitychange",q)}},[]),o?de.jsx($4,{}):n?de.jsx(k4,{data:n,error:c,refreshing:t,onRefresh:()=>void Z({ignoreInterval:!0})}):de.jsx("div",{style:{padding:32,textAlign:"center",color:"var(--text-muted)",fontSize:13,fontFamily:Jn.sans},children:"No KPI data — run an analytics KPI tool"})}kb.createRoot(document.getElementById("app")).render(de.jsx(S4,{}));</script>
148
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:I().optional().describe("User's language and region preference in BCP 47 format."),timeZone:I().optional().describe("User's timezone in IANA format."),userAgent:I().optional().describe("Host application identifier."),platform:se([x("web"),x("desktop"),x("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:T({touch:ke().optional().describe("Whether the device supports touch input."),hover:ke().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:T({top:oe().describe("Top safe area inset in pixels."),right:oe().describe("Right safe area inset in pixels."),bottom:oe().describe("Bottom safe area inset in pixels."),left:oe().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),l4=T({method:x("ui/notifications/host-context-changed"),params:gS.describe("Partial context update containing only changed fields.")});T({method:x("ui/update-model-context"),params:T({content:ee(ha).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:pe(I(),$e().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})});T({method:x("ui/initialize"),params:T({appInfo:Ku.describe("App identification (name and version)."),appCapabilities:r4.describe("Features and capabilities this app provides."),protocolVersion:I().describe("Protocol version this app supports.")})});var u4=T({protocolVersion:I().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Ku.describe("Host application identification and version."),hostCapabilities:n4.describe("Features and capabilities provided by the host."),hostContext:gS.describe("Rich context about the host environment.")}).passthrough(),s4={target:"draft-2020-12"};async function Ph(n,i){let o=n["~standard"];if(o.jsonSchema)return o.jsonSchema[i](s4);if(o.vendor==="zod"){let{z:u}=await bb(()=>Promise.resolve().then(()=>QI),void 0,import.meta.url);return u.toJSONSchema(n,{io:i})}throw Error(`Schema (vendor: ${o.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function jh(n,i,o=""){let u=await n["~standard"].validate(i);if(u.issues){let t=u.issues.map(a=>{let c=a.path?.map(f=>typeof f=="object"?f.key:f).join(".");return c?`${c}: ${a.message}`:a.message}).join("; ");throw Error(o+t)}return u.value}class Gm extends A1{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(i){if(this._initializedSent)return;let o=`[ext-apps] App.${i}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(o);console.warn(`${o}. This will throw in a future release.`)}eventSchemas={toolinput:G1,toolinputpartial:Q1,toolresult:a4,toolcancelled:X1,hostcontextchanged:l4};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(i){if(!Gm.ONE_SHOT_EVENTS.has(i)||this._everHadListener.has(i)||(this._everHadListener.add(i),!this._initializedSent))return;let o=`[ext-apps] "${String(i)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(o);console.warn(o)}setEventHandler(i,o){o&&this._assertHandlerTiming(i),super.setEventHandler(i,o)}addEventListener(i,o){this._assertHandlerTiming(i),super.addEventListener(i,o)}onEventDispatch(i,o){i==="hostcontextchanged"&&(this._hostContext={...this._hostContext,...o})}constructor(i,o={},u={autoResize:!0}){super(u),this._appInfo=i,this._capabilities=o,this.options=u,u.allowUnsafeEval||Ke({jitless:!0}),this.setRequestHandler(Gu,t=>(console.log("Received ping:",t.params),{})),this.setEventHandler("hostcontextchanged",void 0)}registerCapabilities(i){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._capabilities=Z1(this._capabilities,i)}registerTool(i,o,u){if(this._registeredTools[i])throw Error(`Tool ${i} is already registered`);let t=this,a=()=>{t._initializedSent&&t._capabilities.tools?.listChanged&&t.sendToolListChanged()},c=o.inputSchema!==void 0,f={title:o.title,description:o.description,inputSchema:o.inputSchema,outputSchema:o.outputSchema,annotations:o.annotations,_meta:o._meta,enabled:!0,enable(){this.enabled=!0,a()},disable(){this.enabled=!1,a()},update(v){Object.assign(this,v),a()},remove(){t._registeredTools[i]===f&&(delete t._registeredTools[i],a())},handler:async(v,g)=>{if(!f.enabled)throw Error(`Tool ${i} is disabled`);let y;if(c){let k=f.inputSchema,P=k?await jh(k,v??{},`Invalid input for tool ${i}: `):v??{};y=await u(P,g)}else y=await u(g);return f.outputSchema&&!y.isError&&(y.structuredContent=await jh(f.outputSchema,y.structuredContent,`Invalid output for tool ${i}: `)),y}};return this._registeredTools[i]=f,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),a(),f}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(i,o)=>{let u=this._registeredTools[i.name];if(!u)throw Error(`Tool ${i.name} not found`);return u.handler(i.arguments,o)},this.onlisttools=async(i,o)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([u,t])=>t.enabled).map(async([u,t])=>{let a={name:u,title:t.title,description:t.description,inputSchema:t.inputSchema?await Ph(t.inputSchema,"input"):{type:"object",properties:{}}};return t.outputSchema&&(a.outputSchema=await Ph(t.outputSchema,"output")),t.annotations&&(a.annotations=t.annotations),t._meta&&(a._meta=t._meta),a}))}))}async sendToolListChanged(i={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:i})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(i){this.setEventHandler("toolinput",i)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(i){this.setEventHandler("toolinputpartial",i)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(i){this.setEventHandler("toolresult",i)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(i){this.setEventHandler("toolcancelled",i)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(i){this.setEventHandler("hostcontextchanged",i)}_onteardown;get onteardown(){return this._onteardown}set onteardown(i){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,i),this._onteardown=i,this.replaceRequestHandler(t4,(o,u)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(o.params,u)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(i){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,i),this._oncalltool=i,this.replaceRequestHandler(fS,(o,u)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(o.params,u)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(i){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,i),this._onlisttools=i,this.replaceRequestHandler(dS,(o,u)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(o.params,u)})}assertCapabilityForMethod(i){switch(i){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${i})`);break}}assertRequestHandlerCapability(i){switch(i){case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${i})`);return;case"ping":case"ui/resource-teardown":return;default:throw Error(`No handler for method ${i} registered`)}}assertNotificationCapability(i){}assertTaskCapability(i){throw Error("Tasks are not supported in MCP Apps")}assertTaskHandlerCapability(i){throw Error("Task handlers are not supported in MCP Apps")}async callServerTool(i,o){if(this._assertInitialized("callServerTool"),typeof i=="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${i}"). Did you mean: callServerTool({ name: "${i}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:i},Qu,{onprogress:()=>{},resetTimeoutOnProgress:!0,...o})}async readServerResource(i,o){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:i},uS,o)}async listServerResources(i,o){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:i},lS,o)}async createSamplingMessage(i,o){this._assertInitialized("createSamplingMessage");let u=i.tools?vS:pS;return await this.request({method:"sampling/createMessage",params:i},u,o)}sendMessage(i,o){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:i},K1,o)}sendLog(i){return this.notification({method:"notifications/message",params:i})}updateModelContext(i,o){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:i},Nm,o)}openLink(i,o){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:i},W1,o)}sendOpenLink=this.openLink;downloadFile(i,o){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:i},B1,o)}requestTeardown(i={}){return this.notification({method:"ui/notifications/request-teardown",params:i})}requestDisplayMode(i,o){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:i},i4,o)}sendSizeChanged(i){return this.notification({method:"ui/notifications/size-changed",params:i})}setupSizeChangedNotifications(){let i=!1,o=0,u=0,t=()=>{i||(i=!0,requestAnimationFrame(()=>{i=!1;let c=document.documentElement,f=c.style.height;c.style.height="max-content";let v=Math.ceil(c.getBoundingClientRect().height);c.style.height=f;let g=Math.ceil(window.innerWidth);(g!==o||v!==u)&&(o=g,u=v,this.sendSizeChanged({width:g,height:v}))}))};t();let a=new ResizeObserver(t);return a.observe(document.documentElement),a.observe(document.body),()=>a.disconnect()}async connect(i=new q1(window.parent,window.parent),o){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1,await super.connect(i);try{let u=await this.request({method:"ui/initialize",params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:M1}},u4,o);if(u===void 0)throw Error(`Server sent invalid initialize result: ${u}`);this._hostCapabilities=u.hostCapabilities,this._hostInfo=u.hostInfo,this._hostContext=u.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(u){throw this.close(),u}}}function dr(n){return`var(${n})`}const Kr={bg:{surface:dr("--bg-surface")},text:{muted:dr("--text-muted"),faint:dr("--text-faint")},accent:dr("--accent"),border:dr("--border")},Jn={sans:dr("--font-sans"),mono:dr("--font-mono")};function td(n,i=2){return n.toLocaleString("en-US",{minimumFractionDigits:i,maximumFractionDigits:i})}function c4(n,i="USD"){return n.toLocaleString("en-US",{style:"currency",currency:i,minimumFractionDigits:2,maximumFractionDigits:2})}function d4(){return de.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:[de.jsx("rect",{x:"1",y:"1",width:"6",height:"6",rx:"1.5",fill:"currentColor",opacity:"0.9"}),de.jsx("rect",{x:"9",y:"1",width:"6",height:"6",rx:"1.5",fill:"currentColor",opacity:"0.6"}),de.jsx("rect",{x:"1",y:"9",width:"6",height:"6",rx:"1.5",fill:"currentColor",opacity:"0.6"}),de.jsx("rect",{x:"9",y:"9",width:"6",height:"6",rx:"1.5",fill:"currentColor",opacity:"0.35"})]})}function f4(){const n={display:"flex",alignItems:"center",gap:7,padding:"0 14px",height:30,background:Kr.bg.surface,borderBottom:`1px solid ${Kr.border}`,flexShrink:0},i={fontFamily:Jn.sans,fontSize:11,fontWeight:700,letterSpacing:"0.08em",textTransform:"uppercase",color:Kr.accent},o={width:3,height:3,borderRadius:"50%",background:Kr.text.faint,marginLeft:2,marginRight:2,flexShrink:0},u={fontFamily:Jn.sans,fontSize:10,color:Kr.text.muted,letterSpacing:"0.03em"};return de.jsxs("div",{style:n,children:[de.jsx("div",{style:{color:Kr.accent},children:de.jsx(d4,{})}),de.jsx("span",{style:i,children:"ERPNext"}),de.jsx("div",{style:o}),de.jsx("span",{style:u,children:"gestion ERP"})]})}function m4(n,i={}){return!n.request||n.visibilityState!=="visible"||n.refreshInFlight?!1:i.ignoreInterval?!0:n.now-n.lastRefreshStartedAt>=n.minIntervalMs}function Nh(n,i){return n?.refreshRequest??i}function p4(n){return n instanceof Error&&/timed? out/i.test(n.message)?"Refresh timed out":"Refresh failed"}function v4(n){return n.structuredContent?JSON.stringify(n.structuredContent):n.content?.find(i=>i.type==="text")?.text??null}const fr=new Gm({name:"KPI Viewer",version:"1.0.0"}),g4=15e3,h4=1e4;function y4({data:n,color:i}){if(n.length<2)return null;const o=60,u=24,t=2,a=Math.min(...n),f=Math.max(...n)-a||1,v=n.map((g,y)=>{const k=t+y/(n.length-1)*(o-t*2),P=t+(1-(g-a)/f)*(u-t*2);return`${k},${P}`}).join(" ");return de.jsx("svg",{width:o,height:u,viewBox:`0 0 ${o} ${u}`,style:{flexShrink:0},"aria-hidden":"true",children:de.jsx("polyline",{points:v,fill:"none",stroke:i,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function _4({delta:n,deltaLabel:i,trend:o,trendIsGood:u}){const t=o??(n>0?"up":n<0?"down":"flat"),a=t==="up"?"▲":t==="down"?"▼":"◆";let c,f;if(t==="flat")c="var(--text-muted)",f="var(--bg-hover)";else if(u===void 0)c="var(--info)",f="var(--info-dim)";else{const y=t==="up",k=u?y:!y;c=k?"var(--success)":"var(--error)",f=k?"var(--success-dim)":"var(--error-dim)"}const g=`${n>0?"+":""}${td(Math.abs(n),Math.abs(n)<10?1:0)}`;return de.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",fontSize:11,fontWeight:600,fontFamily:Jn.mono,borderRadius:4,color:c,background:f,letterSpacing:"0.02em"},children:[de.jsx("span",{style:{fontSize:8},children:a}),g,"%",i&&de.jsx("span",{style:{fontWeight:400,fontFamily:Jn.sans,opacity:.75,marginLeft:2},children:i})]})}function $4(){return de.jsx("div",{style:{padding:16},children:de.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[de.jsx("div",{className:"skeleton",style:{height:12,width:"35%"}}),de.jsx("div",{className:"skeleton",style:{height:36,width:"55%"}}),de.jsx("div",{className:"skeleton",style:{height:16,width:"40%"}})]})})}function k4({data:n,error:i,refreshing:o,onRefresh:u}){const t=n.color??"var(--accent)",a=fr.getHostCapabilities()?.serverTools;async function c(g){try{await fr.sendMessage({role:"user",content:[{type:"text",text:g}]})}catch{}}let f;if(n.formattedValue)f=n.formattedValue;else if(n.currency)f=c4(n.value,n.currency);else if(n.unit==="%")f=`${td(n.value,n.value%1===0?0:1)}%`;else{const g=n.value%1===0?0:2;f=td(n.value,g),n.unit&&(f+=` ${n.unit}`)}const v=n.color??"#60a5fa";return de.jsxs("div",{style:{fontFamily:Jn.sans,background:"var(--bg-root)",overflow:"hidden"},children:[de.jsx(f4,{}),de.jsx("div",{style:{padding:"12px 16px 14px"},children:de.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between"},children:[de.jsxs("div",{style:{flex:1,minWidth:0},children:[de.jsx("div",{style:{fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em",color:"var(--text-muted)",marginBottom:6},children:n.label}),de.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6},children:[de.jsx("button",{onClick:u,disabled:o,style:{border:"1px solid var(--border)",background:"var(--bg-elevated)",color:"var(--text-secondary)",borderRadius:6,padding:"4px 8px",fontSize:11,fontFamily:Jn.sans,cursor:o?"default":"pointer"},children:o?"Refreshing":"Refresh"}),de.jsx("div",{"aria-live":"polite",style:{fontSize:11,color:i?"var(--error)":o?"var(--text-muted)":"var(--text-faint)"},children:i??(o?"Refreshing…":"Auto-refresh on focus")})]}),de.jsx("div",{onClick:a&&n._drillDown?()=>c(n._drillDown):void 0,style:{fontSize:32,fontWeight:700,fontFamily:Jn.mono,color:t,lineHeight:1.1,marginBottom:8,cursor:a&&n._drillDown?"pointer":"default",transition:"opacity 0.15s"},onMouseEnter:g=>{n._drillDown&&(g.currentTarget.style.opacity="0.75")},onMouseLeave:g=>{g.currentTarget.style.opacity="1"},title:n._drillDown?"Click to drill down":void 0,children:f}),n.delta!==void 0&&de.jsx(_4,{delta:n.delta,deltaLabel:n.deltaLabel,trend:n.trend,trendIsGood:n.trendIsGood})]}),n.sparkline&&n.sparkline.length>=2&&de.jsx("div",{style:{paddingTop:20,paddingLeft:12,cursor:a&&n._trendDrillDown?"pointer":"default"},onClick:a&&n._trendDrillDown?()=>c(n._trendDrillDown):void 0,title:n._trendDrillDown?"Click to see trend details":void 0,children:de.jsx(y4,{data:n.sparkline,color:v})})]})})]})}function S4(){const[n,i]=sn.useState(null),[o,u]=sn.useState(!0),[t,a]=sn.useState(!1),[c,f]=sn.useState(null),v=sn.useRef(null),g=sn.useRef(null),y=sn.useRef(!1),k=sn.useRef(0);function P(B){v.current=B,g.current=Nh(B,g.current),i(B)}function j(B){const q=v4(B);if(!q)return!1;try{const Oe=JSON.parse(q);return P(Oe),f(null),u(!1),!0}catch(Oe){return console.error("Parse error:",Oe),f("Failed to parse KPI payload"),u(!1),!1}}async function Z(B={}){const q=Nh(v.current,g.current);if(!m4({request:q,visibilityState:typeof document>"u"?"visible":document.visibilityState,refreshInFlight:y.current,now:Date.now(),lastRefreshStartedAt:k.current,minIntervalMs:g4},B)||!q||!fr.getHostCapabilities()?.serverTools)return!1;y.current=!0,k.current=Date.now(),a(!0);try{const Oe=await fr.callServerTool({name:q.toolName,arguments:q.arguments},{timeout:h4});return Oe.isError?(f("Refresh failed"),!1):j(Oe)?!0:(f("Refresh returned no data"),!1)}catch(Oe){return f(p4(Oe)),!1}finally{y.current=!1,a(!1)}}return sn.useEffect(()=>{fr.ontoolresult=B=>{j(B)},fr.ontoolinputpartial=()=>{v.current||u(!0)},fr.connect().catch(()=>{})},[]),sn.useEffect(()=>{function B(){Z({ignoreInterval:!0})}function q(){document.visibilityState==="visible"&&Z({ignoreInterval:!0})}return window.addEventListener("focus",B),document.addEventListener("visibilitychange",q),()=>{window.removeEventListener("focus",B),document.removeEventListener("visibilitychange",q)}},[]),o?de.jsx($4,{}):n?de.jsx(k4,{data:n,error:c,refreshing:t,onRefresh:()=>void Z({ignoreInterval:!0})}):de.jsx("div",{style:{padding:32,textAlign:"center",color:"var(--text-muted)",fontSize:13,fontFamily:Jn.sans},children:"No KPI data — run an analytics KPI tool"})}kb.createRoot(document.getElementById("app")).render(de.jsx(S4,{}));</script>
149
149
  <style rel="stylesheet" crossorigin>:root{--accent: #0089ff;--accent-dim: rgba(0, 137, 255, .15);--accent-border: rgba(0, 137, 255, .3);--success: #16a34a;--success-dim: rgba(22, 163, 74, .1);--error: #dc2626;--error-dim: rgba(220, 38, 38, .1);--warning: #d97706;--warning-dim: rgba(217, 119, 6, .1);--info: #2563eb;--info-dim: rgba(37, 99, 235, .1);--radius-sm: 4px;--radius-md: 6px;--radius-lg: 8px;--font-sans: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;--font-mono: "SF Mono", "Cascadia Code", "Fira Code", monospace;--bg-root: #ffffff;--bg-surface: #f9fafb;--bg-elevated: #f3f4f6;--bg-hover: #e5e7eb;--bg-active: #d1d5db;--text-primary: #111827;--text-secondary: #4b5563;--text-muted: #6b7280;--text-faint: #9ca3af;--border: #e5e7eb;--border-subtle: #f3f4f6;--shadow-sm: 0 1px 2px rgba(0, 0, 0, .05);--shadow-md: 0 2px 8px rgba(0, 0, 0, .08)}@media(prefers-color-scheme:dark){:root{--bg-root: #08080a;--bg-surface: #111113;--bg-elevated: #18181b;--bg-hover: #1f1f23;--bg-active: #27272a;--text-primary: #e7e5e4;--text-secondary: #a8a29e;--text-muted: #78716c;--text-faint: #57534e;--border: #27272a;--border-subtle: #1f1f23;--success: #4ade80;--success-dim: rgba(74, 222, 128, .12);--error: #f87171;--error-dim: rgba(248, 113, 113, .12);--warning: #fbbf24;--warning-dim: rgba(251, 191, 36, .12);--info: #60a5fa;--info-dim: rgba(96, 165, 250, .12);--shadow-sm: 0 1px 2px rgba(0, 0, 0, .3);--shadow-md: 0 2px 8px rgba(0, 0, 0, .4)}}*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}html{border-radius:var(--radius-lg);overflow:hidden}html,body{background:var(--bg-root);color:var(--text-primary);font-family:var(--font-sans);font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}body{overflow:auto}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px}::-webkit-scrollbar-thumb:hover{background:var(--text-faint)}@keyframes pulse{0%,to{opacity:.4}50%{opacity:.15}}@keyframes shimmer{0%{background-position:-200% 0}to{background-position:200% 0}}.animate-pulse{animation:pulse 1.5s ease-in-out infinite}.skeleton{background:linear-gradient(90deg,var(--bg-elevated) 25%,var(--bg-hover) 50%,var(--bg-elevated) 75%);background-size:200% 100%;animation:shimmer 1.5s infinite;border-radius:var(--radius-sm)}.drag-scroll::-webkit-scrollbar{display:none}.drag-scroll{scrollbar-width:none}article button:hover:not(:disabled){background:var(--bg-hover)!important;color:var(--text-primary)!important}article[draggable=true]:active{cursor:grabbing;opacity:.85}.kanban-detail-backdrop{position:fixed;inset:0;z-index:100;background:#00000073;display:flex;align-items:flex-start;justify-content:center;padding:20px 12px;overflow-y:auto;backdrop-filter:blur(2px)}.kanban-detail-panel{background:var(--bg-root);border:1px solid var(--border);border-radius:10px;max-width:520px;width:100%;box-shadow:0 8px 32px #0000001f,0 2px 8px #0000000f;position:relative;display:flex;flex-direction:column}.kanban-detail-panel .detail-field-row{transition:background .1s}.kanban-detail-panel .detail-field-row:hover{background:var(--bg-surface)}.kanban-detail-panel .detail-field-cell{transition:background .1s;border-radius:4px}.kanban-detail-panel .detail-field-cell:hover{background:var(--bg-surface)}.kanban-detail-panel .detail-field-cell:hover input,.kanban-detail-panel .detail-field-cell:hover select{border-color:var(--border)!important;background:var(--bg-elevated)!important}.kanban-detail-panel select:focus{border-color:var(--accent)!important;box-shadow:0 0 0 2px var(--accent-dim);outline:none}.kanban-detail-panel input:focus{border-color:var(--accent)!important;box-shadow:0 0 0 2px var(--accent-dim);outline:none}.kanban-detail-panel textarea:focus{border-color:var(--accent)!important;box-shadow:0 0 0 2px var(--accent-dim);outline:none}@media(prefers-color-scheme:dark){.kanban-detail-backdrop{background:#000000a6}.kanban-detail-panel{box-shadow:0 8px 32px #0006,0 2px 8px #0000004d}}.kanban-card-title-link{cursor:pointer;text-decoration:none;color:inherit}.kanban-card-title-link:hover{text-decoration:underline;text-decoration-thickness:1px;text-underline-offset:2px}</style>
150
150
  </head>
151
151
  <body>