@halcyonlabs/app 0.47.0-halcyon.607 → 0.47.0-halcyon.615

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.
@@ -1,29 +1,29 @@
1
- var ZT=Object.defineProperty;var cn=(e,t)=>{for(var n in t)ZT(e,n,{get:t[n],enumerable:!0})};var Sf=globalThis.__bbPluginRuntime;if(Sf==null||Sf.pluginSdkApp==null)throw new Error('Cannot load "@get-bb/plugin-sdk/app": this bundle must be loaded by the Moonlet app, which provides the shared plugin runtime (globalThis.__bbPluginRuntime).');var Hl=Sf.pluginSdkApp,uF="default"in Hl?Hl.default:Hl,{Markdown:H_,ThreadChat:Ef,ThreadTitle:dF,UrlLink:pF,definePluginApp:V_,experimental_BranchPicker:fF,experimental_ComposerRoot:hF,experimental_DetailRow:mF,experimental_Diff:gF,experimental_FailedVoiceRecordings:xF,experimental_FileLink:bF,experimental_Icon:pe,experimental_ImageLightbox:yF,experimental_InfoList:_F,experimental_InfoListRow:vF,experimental_InfoSection:wF,experimental_NewThreadComposer:kF,experimental_PermissionModePicker:SF,experimental_PluginIcon:EF,experimental_PluginRpcCallError:NF,experimental_PromptMentionIcon:AF,experimental_ProviderIcon:CF,experimental_ProviderModelPicker:TF,experimental_SettingsRow:Ei,experimental_SettingsSection:ct,experimental_ShortcutHint:RF,experimental_SidebarNavigationIcon:$F,experimental_SourceCode:IF,experimental_THREAD_ACTION_GROUPS:PF,experimental_THREAD_CONTEXT_SEGMENT_GROUPS:OF,experimental_THREAD_INFO_ROW_GROUPS:LF,experimental_THREAD_INFO_SECTION_GROUPS:MF,experimental_ThreadActionsContextMenu:DF,experimental_ThreadActionsMenu:FF,experimental_ThreadStatusGlyph:zF,experimental_ThreadTitleText:KF,experimental_VoiceInputButton:XF,experimental_VoiceInputTextarea:BF,experimental_VoiceRecordingBar:UF,experimental_copyToClipboard:Z_,experimental_describePromptMention:HF,experimental_promptMentionClipboardAttributes:VF,experimental_readPromptMentionClipboard:ZF,experimental_saveFile:WF,experimental_useAppPanel:W_,experimental_useArchiveEnvironmentThreads:jF,experimental_useBranches:QF,experimental_useCheckoutState:GF,experimental_useCodeTheme:YF,experimental_useComposerCommandSearch:qF,experimental_useComposerContributions:JF,experimental_useComposerMentionSearch:e4,experimental_useComposerRenderer:t4,experimental_useExperiment:n4,experimental_useFixedTabTarget:r4,experimental_usePluginId:o4,experimental_useProviders:s4,experimental_useQuestionFormHost:i4,experimental_useRpcKeyedQuery:a4,experimental_useRpcMutation:l4,experimental_useRpcQuery:c4,experimental_useRpcRefresh:u4,experimental_useSidebar:j_,experimental_useSidebarNavigation:d4,experimental_useSidebarNavigationSplit:p4,experimental_useSidebarThreadActions:f4,experimental_useSidebarThreadSplit:h4,experimental_useSidebarThreads:m4,experimental_useThreadActionRegistrations:g4,experimental_useThreadActions:x4,experimental_useThreadTitleDisplayText:b4,internal_DO_NOT_USE_Outlet:Vl,internal_DO_NOT_USE_useOutletFilled:Q_,useBbContext:G_,useBbNavigate:Ie,useComposer:Y_,useComposerView:y4,useComposers:_4,useEnvironmentProviders:v4,useRealtime:ke,useRealtimeConnectionState:q_,useRpc:J,useSdk:un,useSettings:w4,useSidebarSplitLayout:k4,useSidebarThreadDraft:S4,useSidebarThreadDraftIds:E4,useSidebarThreadRowStatus:N4,useSidebarThreadRowStatuses:A4,useSidebarThreadShortcut:C4,experimental_useSidebarThreadPullRequest:T4}=Hl;var $r={};cn($r,{Activity:()=>jT,Children:()=>Wl,Component:()=>QT,Fragment:()=>Af,Profiler:()=>GT,PureComponent:()=>YT,StrictMode:()=>qT,Suspense:()=>JT,act:()=>e2,cache:()=>t2,cacheSignal:()=>n2,captureOwnerStack:()=>r2,cloneElement:()=>Ni,createContext:()=>Cf,createElement:()=>J_,createRef:()=>o2,default:()=>WT,forwardRef:()=>Tn,isValidElement:()=>Po,lazy:()=>s2,memo:()=>i2,startTransition:()=>a2,unstable_useCacheRefresh:()=>l2,use:()=>c2,useActionState:()=>u2,useCallback:()=>q,useContext:()=>Tf,useDebugValue:()=>d2,useDeferredValue:()=>p2,useEffect:()=>K,useEffectEvent:()=>f2,useId:()=>Ai,useImperativeHandle:()=>h2,useInsertionEffect:()=>m2,useLayoutEffect:()=>ot,useMemo:()=>Lt,useOptimistic:()=>g2,useReducer:()=>x2,useRef:()=>Y,useState:()=>_,useSyncExternalStore:()=>xt,useTransition:()=>b2,version:()=>y2});var Nf=globalThis.__bbPluginRuntime;if(Nf==null||Nf.react==null)throw new Error('Cannot load "react": this bundle must be loaded by the Moonlet app, which provides the shared plugin runtime (globalThis.__bbPluginRuntime).');var Zl=Nf.react,WT="default"in Zl?Zl.default:Zl,{Activity:jT,Children:Wl,Component:QT,Fragment:Af,Profiler:GT,PureComponent:YT,StrictMode:qT,Suspense:JT,act:e2,cache:t2,cacheSignal:n2,captureOwnerStack:r2,cloneElement:Ni,createContext:Cf,createElement:J_,createRef:o2,forwardRef:Tn,isValidElement:Po,lazy:s2,memo:i2,startTransition:a2,unstable_useCacheRefresh:l2,use:c2,useActionState:u2,useCallback:q,useContext:Tf,useDebugValue:d2,useDeferredValue:p2,useEffect:K,useEffectEvent:f2,useId:Ai,useImperativeHandle:h2,useInsertionEffect:m2,useLayoutEffect:ot,useMemo:Lt,useOptimistic:g2,useReducer:x2,useRef:Y,useState:_,useSyncExternalStore:xt,useTransition:b2,version:y2}=Zl;function ev(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function _2(...e){return t=>{let n=!1,r=e.map(o=>{let s=ev(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){let s=r[o];typeof s=="function"?s():ev(e[o],null)}}}}function tv(...e){return q(_2(...e),e)}function v2(e){let t=Tn((n,r)=>{let{children:o,...s}=n,i=null,a=!1,u=[];nv(o)&&typeof jl=="function"&&(o=jl(o._payload)),Wl.forEach(o,f=>{if(N2(f)){a=!0;let h=f,g="child"in h.props?h.props.child:h.props.children;nv(g)&&typeof jl=="function"&&(g=jl(g._payload)),i=k2(h,g),u.push(i?.props?.children)}else u.push(f)}),i?i=Ni(i,void 0,u):!a&&Wl.count(o)===1&&Po(o)&&(i=o);let c=i?E2(i):void 0,d=tv(r,c);if(!i){if(o||o===0)throw new Error(a?R2(e):T2(e));return o}let p=S2(s,i.props??{});return i.type!==Af&&(p.ref=r?d:c),Ni(i,p)});return t.displayName=`${e}.Slot`,t}var Ql=v2("Slot"),w2=Symbol.for("radix.slottable");var k2=(e,t)=>{if("child"in e.props){let n=e.props.child;return Po(n)?Ni(n,void 0,e.props.children(n.props.children)):null}return Po(t)?t:null};function S2(e,t){let n={...t};for(let r in t){let o=e[r],s=t[r];/^on[A-Z]/.test(r)?o&&s?n[r]=(...a)=>{let u=s(...a);return o(...a),u}:o&&(n[r]=o):r==="style"?n[r]={...o,...s}:r==="className"&&(n[r]=[o,s].filter(Boolean).join(" "))}return{...e,...n}}function E2(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function N2(e){return Po(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===w2}var A2=Symbol.for("react.lazy");function nv(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===A2&&"_payload"in e&&C2(e._payload)}function C2(e){return typeof e=="object"&&e!==null&&"then"in e}var T2=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,R2=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,jl=$r[" use ".trim().toString()];var Rf=globalThis.__bbPluginRuntime;if(Rf==null||Rf.classVarianceAuthority==null)throw new Error('Cannot load "class-variance-authority": this bundle must be loaded by the Moonlet app, which provides the shared plugin runtime (globalThis.__bbPluginRuntime).');var Gl=Rf.classVarianceAuthority,O4="default"in Gl?Gl.default:Gl,{cva:rv,cx:L4}=Gl;var $f=globalThis.__bbPluginRuntime;if($f==null||$f.clsx==null)throw new Error('Cannot load "clsx": this bundle must be loaded by the Moonlet app, which provides the shared plugin runtime (globalThis.__bbPluginRuntime).');var Yl=$f.clsx,D4="default"in Yl?Yl.default:Yl,{clsx:ov}=Yl;var If=globalThis.__bbPluginRuntime;if(If==null||If.tailwindMerge==null)throw new Error('Cannot load "tailwind-merge": this bundle must be loaded by the Moonlet app, which provides the shared plugin runtime (globalThis.__bbPluginRuntime).');var ql=If.tailwindMerge,z4="default"in ql?ql.default:ql,{createTailwindMerge:K4,extendTailwindMerge:X4,fromTheme:B4,getDefaultConfig:U4,mergeConfigs:H4,twJoin:V4,twMerge:sv,validators:Z4}=ql;function V(...e){return sv(ov(e))}var Jl="transition-colors duration-150 hover:duration-0";var Pf=globalThis.__bbPluginRuntime;if(Pf==null||Pf.jsxRuntime==null)throw new Error('Cannot load "react/jsx-runtime": this bundle must be loaded by the Moonlet app, which provides the shared plugin runtime (globalThis.__bbPluginRuntime).');var ec=Pf.jsxRuntime,q4="default"in ec?ec.default:ec,{Fragment:he,jsx:l,jsxs:m}=ec;var $2=rv(`inline-flex cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ${Jl} focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_[data-icon-root]]:pointer-events-none [&_[data-icon-root]]:size-4 [&_[data-icon-root]]:shrink-0`,{variants:{variant:{default:"bg-foreground text-background hover:bg-foreground/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-transparent hover:bg-state-hover hover:text-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-state-hover hover:text-foreground aria-pressed:bg-state-active aria-pressed:text-foreground aria-pressed:hover:bg-state-active data-[state=open]:bg-state-active data-[state=open]:text-foreground data-[state=open]:hover:bg-state-active",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),R=Tn(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>l(r?Ql:"button",{className:V($2({variant:t,size:n,className:e})),ref:s,...o}));R.displayName="Button";function I2({route:e,busy:t,answer:n,cancel:r,expiresAt:o}){return m("div",{className:"flex flex-col gap-3 p-3 text-sm",children:[m("div",{children:[m("div",{className:"font-medium",children:[e.what==="spawn"?"Start work":e.what==="tell"?"Send a message":e.what==="relay"?"Relay a message":"Schedule a check"," ",e.what==="relay"?"to":"on"," ",l("span",{className:"font-mono",children:e.station}),e.when&&m("span",{className:"font-normal text-muted-foreground",children:[" (",e.when,")"]})]}),(e.provider||e.model)&&m("div",{className:"mt-1 text-xs",children:["Runs on ",l("span",{className:"font-mono",children:e.provider??"the project's provider"}),e.model&&m(he,{children:[" ","with ",l("span",{className:"font-mono",children:e.model})]}),e.provider==="codex"&&e.own&&" (Codex, under that machine's own Codex sign-in and settings; your moonlet's station protections don't apply)","."]}),m("div",{className:"mt-1 text-xs text-muted-foreground",children:["I\u2019m requesting this from ",e.from,".",e.what==="check"&&" The script runs as orbit on its station, outside Claude Code's sandbox, every time it's due.",e.own&&" I\u2019ll run as you on your machine, with access to your files and accounts.",e.what==="relay"&&" You set this to Ask in Settings \u2192 your moonlet \u2192 Relay. The message goes as written below, marked as relayed from your moonlet."]})]}),l("div",{className:"font-medium",children:e.title}),l("pre",{className:"max-h-72 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted p-2 font-mono text-xs",children:e.brief}),o&&m("div",{className:"text-xs text-muted-foreground",children:["Expires at ",new Date(o).toLocaleTimeString(),"."]}),m("div",{className:"flex flex-wrap gap-2",children:[l(R,{size:"sm",disabled:t,onClick:()=>n("once"),children:"Approve"}),l(R,{size:"sm",variant:"destructive",disabled:t,onClick:()=>n("deny"),children:"Decline"}),l(R,{size:"sm",variant:"ghost",disabled:t,onClick:()=>{r()},children:"Dismiss"})]})]})}var P2=e=>({"orbit-keys.service":"Password service","orbit-relay.service":"Station connection","orbit-proton-bridge.service":"Mail connection",mail:"Mail connection",gate:"Station connection",plugin:"your moonlet service",turn:"Starting work","mail-check":"Mail check",events:"Background work service"})[e]??e;function O2({switching:e,busy:t,answer:n,cancel:r,expiresAt:o}){let s=e.what==="activate";return m("div",{className:"flex flex-col gap-3 p-3 text-sm",children:[m("div",{children:[m("div",{className:"font-medium",children:["Switch ",s?"on":"off"," on the station: ",e.piece]}),m("div",{className:"mt-1 text-xs",children:[e.words,"."]})]}),l("div",{className:"text-xs",children:s&&e.recovery?"Every health check still runs. This retry may keep only the known failures below. Another failure or an interrupted switch still undoes it.":s?"I\u2019ll switch this on and check the station\u2019s health. A failed check or interrupted switch restores the previous state.":"I\u2019ll switch this off now. The effect is described above."}),e.recovery&&m("div",{className:"space-y-2 rounded-md border p-2",children:[l("p",{className:"font-medium",children:"Retry and keep this switch if the same checks still fail?"}),l("ul",{className:"list-disc pl-5",children:e.recovery.failures.map(i=>l("li",{children:P2(i)},i))}),l("p",{children:"Approve retries the same switch with the same settings and allows these known failures for this attempt. Services may remain unavailable until repaired. Other failures still undo the switch."})]}),m("div",{className:"text-xs text-muted-foreground",children:["This approves the switch described above.",o&&` Expires at ${new Date(o).toLocaleTimeString()}.`]}),m("div",{className:"flex flex-wrap gap-2",children:[l(R,{size:"sm",disabled:t,onClick:()=>n("once"),children:"Approve"}),l(R,{size:"sm",variant:"destructive",disabled:t,onClick:()=>n("deny"),children:"Decline"}),l(R,{size:"sm",variant:"ghost",disabled:t,onClick:()=>{r()},children:"Dismiss"})]})]})}function L2({login:e,offers:t,busy:n,answer:r,cancel:o,expiresAt:s}){let i=e.otp?"one-time codes":"sign-ins";return e.humanCheck?m("div",{className:"flex flex-col gap-3 p-3 text-sm",children:[m("div",{children:[l("div",{className:"font-medium",children:"Proton wants a human check before Bridge signs in"}),l("div",{className:"mt-1 text-xs text-muted-foreground",children:"It's open in Chrome on your moonlet's desktop: solve it there from the Desktop panel (Proton accepts it only from your moonlet's own computer), then press Done. Bridge's sign-in is waiting and carries on from there. The link, in case the window closed:"})]}),l("a",{className:"break-all font-mono text-xs underline",href:e.humanCheck,target:"_blank",rel:"noreferrer noopener",children:e.humanCheck}),s&&m("div",{className:"text-xs text-muted-foreground",children:["Cancelled if unanswered by ",new Date(s).toLocaleTimeString(),"."]}),m("div",{className:"flex flex-wrap gap-2",children:[l(R,{size:"sm",disabled:n,onClick:()=>r("once"),children:"Done"}),l(R,{size:"sm",variant:"destructive",disabled:n,onClick:()=>r("deny"),children:"Cancel"})]})]}):m("div",{className:"flex flex-col gap-3 p-3 text-sm",children:[l("div",{children:e.bridge?m(he,{children:[m("div",{className:"font-medium",children:["Sign Proton Mail Bridge in with ",l("span",{className:"font-mono",children:e.item})]}),l("div",{className:"mt-1 text-xs text-muted-foreground",children:"I\u2019ll sign Bridge in through the vault without seeing the password or code. Then I can read and send its mail through Bridge."})]}):m(he,{children:[m("div",{className:"font-medium",children:["Sign your moonlet in: fill ",e.otp?"the one-time code":"the username and password"," from ",l("span",{className:"font-mono",children:e.item})," ","into ",l("span",{className:"font-mono",children:e.unit}),"'s sign-in page, ",l("span",{className:"font-mono",children:e.url})]}),m("div",{className:"mt-1 text-xs text-muted-foreground",children:[e.otp?"The broker fills it into the text field that has the focus on that page; your moonlet never sees it.":"The broker fills them into that page's form (the password only into its password field) and signs in; your moonlet never sees them."," ","You can see the sign-in form in the Desktop panel."]})]})}),m("ul",{className:"list-disc space-y-0.5 pl-5 text-xs text-muted-foreground",children:[t.includes("thread")&&m("li",{children:[l("b",{children:"For this conversation"}),": ",i," for ",l("span",{className:"font-mono",children:e.name})," asked as this conversation, until Moonlet reloads your moonlet."]}),t.includes("always")&&m("li",{children:[l("b",{children:"Always"}),": ",i," for ",l("span",{className:"font-mono",children:e.name})," from any of the station's conversations, from now on. Revoke it in Settings \u2192 your moonlet."]}),s&&m("li",{children:["Expires at ",new Date(s).toLocaleTimeString(),"."]})]}),m("div",{className:"flex flex-wrap gap-2",children:[l(R,{size:"sm",disabled:n,onClick:()=>r("once"),children:"Approve"}),t.includes("thread")&&l(R,{size:"sm",variant:"secondary",disabled:n,onClick:()=>r("thread"),children:"For this conversation"}),t.includes("always")&&l(R,{size:"sm",variant:"secondary",disabled:n,onClick:()=>r("always"),children:"Always"}),l(R,{size:"sm",variant:"destructive",disabled:n,onClick:()=>r("deny"),children:"Decline"}),l(R,{size:"sm",variant:"ghost",disabled:n,onClick:()=>{o()},children:"Dismiss"})]})]})}function M2({change:e,busy:t,answer:n}){return m("div",{className:"space-y-3 p-3 text-sm",children:[m("p",{className:"font-medium",children:[e.mergeReasons?"Allow merging":e.checks?"Proceed with these checks for":"Approve change"," #",e.number," in ",e.repo,"?"]}),l("a",{className:"underline",href:`https://github.com/${e.repo}/pull/${e.number}/files/${e.head}`,target:"_blank",rel:"noreferrer noopener",children:"Read this version of the change"}),e.mergeReasons?m("p",{children:["Allow this reviewed version to be merged despite:"," ",e.mergeReasons.map(r=>({author:"the author restriction",protected_paths:"protected files",changes_requested:"a request for changes"})[r]).join(", "),". Every check must still pass, the review must match this commit, and the pull request must be ready and mergeable. This changes the default branch."]}):e.checks?m(he,{children:[l("p",{children:"Allow merging this version despite the results below. Tests may be incomplete or the change may be broken. This also approves the change, including core files. It does not install anything."}),l("a",{className:"underline",href:`https://github.com/${e.repo}/pull/${e.number}/checks`,target:"_blank",rel:"noreferrer noopener",children:"Read the check details"}),l("ul",{className:"list-disc pl-5",children:e.checks.failures.map((r,o)=>l("li",{children:r},o))}),l("p",{className:"text-xs",children:"Only these exact check runs and this version are covered. A rerun, changed result, extra check or later push needs a new decision. Repository, identity and version checks still apply."})]}):l("p",{children:"This approves this whole version, including its core files. A later push needs approval of its own. Every other merge check still applies."}),l("p",{className:"text-xs",children:"This records your approval of the change. It does not install anything."}),l("pre",{className:"whitespace-pre-wrap break-all text-xs",children:e.head}),m("div",{className:"flex gap-2",children:[l(R,{size:"sm",disabled:t,onClick:()=>n("once"),children:"Approve"}),l(R,{size:"sm",variant:"destructive",disabled:t,onClick:()=>n("deny"),children:"Decline"})]})]})}function D2({mail:e,busy:t,answer:n,cancel:r,expiresAt:o}){let s=(i,a)=>a&&m("div",{children:[m("span",{className:"text-muted-foreground",children:[i,":"]})," ",l("span",{className:"whitespace-pre-wrap break-all font-mono",children:a})]});return m("div",{className:"flex flex-col gap-3 p-3 text-sm",children:[m("div",{children:[l("div",{className:"font-medium",children:"Your moonlet wants to send this mail from its Gmail account"}),l("div",{className:"mt-1 text-xs text-muted-foreground",children:"Exactly as shown: the protected mail runner sends this message and nothing else. Sending only this one, once; a sent mail can't be taken back."})]}),m("div",{className:"flex flex-col gap-0.5 text-xs",children:[s("From",e.from),s("To",e.to),s("Cc",e.cc),s("Subject",e.subject),s("Date",e.date),s("Message-ID",e.messageId),s("In reply to",e.inReplyTo),s("References",e.references)]}),l("pre",{className:"max-h-72 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted p-2 font-mono text-xs",children:e.body}),o&&m("div",{className:"text-xs text-muted-foreground",children:["Refused if unanswered by ",new Date(o).toLocaleTimeString(),"."]}),m("div",{className:"flex flex-wrap gap-2",children:[l(R,{size:"sm",disabled:t,onClick:()=>n("once"),children:"Send"}),l(R,{size:"sm",variant:"destructive",disabled:t,onClick:()=>n("deny"),children:"Decline"}),l(R,{size:"sm",variant:"ghost",disabled:t,onClick:()=>{r()},children:"Dismiss"})]})]})}function tc({interaction:e,submit:t,cancel:n}){let r=e.payload,[o,s]=_(!1),i=u=>{s(!0),t({choice:u}).catch(()=>s(!1))};if(r.change)return l(M2,{change:r.change,busy:o,answer:i});if(r.switching)return l(O2,{switching:r.switching,busy:o,answer:i,cancel:()=>{n()},expiresAt:r.expiresAt});if(r.mail)return l(D2,{mail:r.mail,busy:o,answer:i,cancel:()=>{n()},expiresAt:r.expiresAt});if(r.route)return l(I2,{route:r.route,busy:o,answer:i,cancel:()=>{n()},expiresAt:r.expiresAt});if(r.login)return l(L2,{login:r.login,offers:r.offers,busy:o,answer:i,cancel:()=>{n()},expiresAt:r.expiresAt});let a=new Set(r.offers);return m("div",{className:"flex flex-col gap-3 p-3 text-sm",children:[m("div",{children:[m("div",{className:"font-medium",children:["I\u2019d like to ",r.level==="act"?"make a change":"look"," with ",l("span",{className:"font-mono",children:r.capability})]}),l("pre",{className:"mt-2 max-h-48 overflow-auto whitespace-pre-wrap break-all rounded-md bg-muted p-2 font-mono text-xs",children:r.command})]}),m("ul",{className:"list-disc space-y-0.5 pl-5 text-xs text-muted-foreground",children:[a.has("thread")&&m("li",{children:[l("b",{children:"For this conversation"}),": any ",l("span",{className:"font-mono",children:r.rule})," command on ",r.capability,", until Moonlet reloads your moonlet."]}),a.has("always")&&m("li",{children:[l("b",{children:"Always"}),": this exact command, from now on. Revoke it in Settings \u2192 your moonlet."]}),r.sensitive&&m("li",{children:["This command is on ",r.capability,"'s sensitive list, so it asks every time."]}),r.expiresAt&&m("li",{children:["Expires at ",new Date(r.expiresAt).toLocaleTimeString(),"."]})]}),m("div",{className:"flex flex-wrap gap-2",children:[l(R,{size:"sm",disabled:o,onClick:()=>i("once"),children:"Approve"}),a.has("thread")&&l(R,{size:"sm",variant:"secondary",disabled:o,onClick:()=>i("thread"),children:"Allow for this conversation"}),a.has("always")&&l(R,{size:"sm",variant:"secondary",disabled:o,onClick:()=>i("always"),children:"Always allow"}),l(R,{size:"sm",variant:"destructive",disabled:o,onClick:()=>i("deny"),children:"Decline"}),l(R,{size:"sm",variant:"ghost",disabled:o,onClick:()=>{n()},children:"Dismiss"})]})]})}function nc({interaction:e,submit:t,cancel:n}){let r=e.payload,[o,s]=_(!1),i=a=>{s(!0),t({hostId:a}).catch(()=>s(!1))};return m("div",{className:"flex flex-col gap-3 p-3 text-sm",children:[m("div",{children:[m("div",{className:"font-medium",children:["Which machine manages ",l("span",{className:"font-mono",children:r.station}),"?"]}),m("p",{className:"mt-1 text-xs text-muted-foreground",children:["Several machines have your moonlet's station key and this station's VM. Your moonlet reaches the station only through the one you pick, which receives its credentials when they change. Change it later with ",l("span",{className:"font-mono",children:"moonlet station manager"}),"."]})]}),m("div",{className:"flex flex-wrap gap-2",children:[r.machines.map(a=>l(R,{size:"sm",variant:"secondary",disabled:o,onClick:()=>i(a.id),children:a.name},a.id)),l(R,{size:"sm",variant:"ghost",disabled:o,onClick:()=>{n()},children:"Dismiss"})]})]})}function iv({payload:e}){let t=e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.proposal=="string"?e.proposal:"";return/^[a-f0-9]{32}$/.test(t)?l(Ci,{id:t}):l("p",{children:"The settings result is unavailable."})}function Ci({id:e}){let t=J(),[n,r]=_([]),[o,s]=_(!1);return K(()=>{let i=!0,a,u=async()=>{try{let c=e?await t.call("policy-proposals.result",{id:e}).then(d=>d?[d]:[]):await t.call("policy-proposals.history",null);i&&(r(c),s(!1))}catch{i&&s(!0)}i&&(a=setTimeout(()=>{u()},5e3))};return u(),()=>{i=!1,clearTimeout(a)}},[t,e]),!n.length&&!o?null:m("section",{className:"space-y-2 p-3 text-sm","aria-label":"Station settings results",children:[!e&&l("h2",{className:"font-medium",children:"Recent station settings requests"}),o&&l("p",{role:"alert",children:"The settings result could not be checked. Trying again."}),n.slice(0,e?1:10).map(i=>m("div",{className:"space-y-1 rounded border p-2",children:[l("p",{className:"font-medium",children:i.title}),l("p",{children:i.message})]},i.id))]})}function rc({interaction:e,submit:t}){let n=e.payload,r=J(),[o,s]=_(!1),[i,a]=_(!1),[u,c]=_(null),[d,p]=_(null),[f,h]=_([]),g=Date.now()>=n.deadline,x=!!n.restore&&f.length===0;async function b(v){if(!(o||g||v&&(n.explanation.extraConfirmation&&!i||x))){s(!0),p(null);try{await t(n.restore?{approve:v,acknowledgeRisk:i,restore:v?f:[]}:{approve:v,acknowledgeRisk:i})}catch{p("Your answer did not go through. Try again."),s(!1)}}}return m("div",{className:"space-y-3 p-3 text-sm",children:[l("p",{className:"font-medium",children:n.restore?"Approve secret use again?":"Change station permissions?"}),n.explanation.sections.map(v=>m("section",{className:"space-y-1",children:[l("h3",{className:"font-medium",children:v.heading}),v.sentences.map((w,C)=>l("p",{className:"whitespace-pre-wrap break-words",children:w},C))]},v.heading)),n.restore&&m("fieldset",{className:"space-y-2",children:[l("legend",{className:"font-medium",children:"Secret uses to approve again"}),n.restore.map(v=>m("label",{className:"flex gap-2",children:[l("input",{type:"checkbox","aria-label":`Approve ${v.id} again`,checked:f.includes(v.id),disabled:o||g,onChange:w=>h(C=>w.target.checked?[...C,v.id].sort():C.filter(y=>y!==v.id))}),m("span",{children:[l("span",{className:"whitespace-pre-wrap break-all font-mono",children:v.id}),l("span",{className:"block whitespace-pre-wrap break-words",children:v.sentence})]})]},v.id))]}),l("p",{children:"This answer covers only these settings and their application. Declining or leaving this unanswered changes nothing."}),m("p",{children:["Expires ",new Date(n.deadline).toLocaleString(),"."]}),m("details",{onToggle:v=>{v.currentTarget.open&&!u&&r.call("policy-proposals.text",{id:n.id}).then(c).catch(()=>p("The exact text could not be loaded. Try opening it again."))},children:[l("summary",{className:"cursor-pointer underline",children:"More details"}),m("p",{children:["Proposer's title: ",n.title]}),l("p",{children:"Proposer's own words (not verified):"}),l("p",{className:"whitespace-pre-wrap break-words",children:n.explanation.details.proposerWords}),n.explanation.details.unchanged.map((v,w)=>l("p",{children:v},w)),u?m("div",{className:"space-y-2",children:[l("p",{children:"Current settings"}),l("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap break-all",children:u.before}),l("p",{children:"Proposed settings"}),l("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap break-all",children:u.after}),l("p",{children:"Checked review"}),l("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap break-all",children:u.preview})]}):l("p",{children:"Loading\u2026"})]}),n.explanation.extraConfirmation&&m("label",{className:"flex gap-2",children:[l("input",{type:"checkbox",checked:i,disabled:o||g,onChange:v=>a(v.target.checked)}),"I understand the extra access described above."]}),g&&l("p",{role:"alert",children:"This request has expired. Nothing was changed."}),d&&l("p",{role:"alert",children:d}),m("div",{className:"flex gap-2",children:[l(R,{size:"sm",disabled:o||g||n.explanation.extraConfirmation&&!i||x,onClick:()=>{b(!0)},children:"Approve"}),l(R,{size:"sm",variant:"destructive",disabled:o||g,onClick:()=>{b(!1)},children:"Decline"})]})]})}var F2=/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/;function oc({url:e,label:t,size:n=64}){let r={width:n,height:n};return!e||!F2.test(e)?l("span",{role:"img","aria-label":`${t}: none`,className:"inline-block shrink-0 rounded-full border border-dashed border-border bg-muted",style:r}):l("img",{src:e,alt:t,className:"shrink-0 rounded-full border border-border bg-muted object-cover",style:r})}var z2=[{value:"approve",label:"Approve"},{value:"decline",label:"Decline"},{value:"later",label:"Later"}];function Of({id:e,beforeLabel:t="Now"}){let n=J(),[r,o]=_(null),[s,i]=_(null);return m("details",{onToggle:a=>{a.currentTarget.open&&!r&&n.call("owner-changes.details",{id:e}).then(o).catch(()=>i("The details could not be loaded. Try opening them again."))},children:[l("summary",{className:"cursor-pointer underline",children:"More details"}),s&&l("p",{role:"alert",children:s}),r&&m("div",{className:"mt-2 space-y-2",children:[r.pictures.map(a=>m("div",{className:"flex flex-col items-start gap-1",children:[l(oc,{url:a.url,label:a.label,size:96}),l("span",{className:"text-xs text-muted-foreground",children:a.label})]},a.label)),m("div",{className:"grid gap-2 md:grid-cols-2",children:[m("div",{children:[l("div",{className:"mb-1 text-xs text-muted-foreground",children:t}),l("pre",{className:"max-h-60 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted p-2 text-xs",children:r.before})]}),m("div",{children:[l("div",{className:"mb-1 text-xs text-muted-foreground",children:"After"}),l("pre",{className:"max-h-60 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted p-2 text-xs",children:r.after})]})]})]})]})}function K2({item:e,choice:t,onChoice:n,acknowledged:r,onAcknowledge:o,narrowing:s,onNarrow:i,expired:a}){let u=e.offer;return m("article",{className:"space-y-2 rounded-md border p-3","aria-disabled":a,children:[l("p",{className:"font-medium",children:e.summary}),e.explanation.sections.map(c=>m("section",{className:"space-y-1",children:[l("h4",{className:"font-medium",children:c.heading}),c.sentences.map((d,p)=>l("p",{className:"whitespace-pre-wrap break-words",children:d},p))]},c.heading)),(e.title||e.explanation.details.proposerWords)&&m("details",{children:[l("summary",{className:"cursor-pointer underline",children:"Proposer's own words (not verified)"}),e.title&&l("p",{className:"whitespace-pre-wrap break-words",children:e.title}),l("p",{className:"whitespace-pre-wrap break-words",children:e.explanation.details.proposerWords})]}),l(Of,{id:e.id}),!a&&u?.expiry&&!s.once&&m("label",{className:"block",children:["Permission ends (leave empty for no time limit)",l("input",{"aria-label":"Permission ends",className:"block rounded border p-1",type:"datetime-local",value:s.until,onChange:c=>i({...s,until:c.target.value})})]}),!a&&u?.once&&m("label",{className:"flex items-center gap-2",children:[l("input",{type:"checkbox",checked:s.once,onChange:c=>i({...s,once:c.target.checked})}),"Only this once, for the operation waiting now (no standing permission)"]}),e.explanation.extraConfirmation&&m("label",{className:"flex items-center gap-2",children:[l("input",{type:"checkbox",checked:r,disabled:a,onChange:c=>o(c.target.checked)}),"I understand the extra access described above."]}),a?l("p",{children:"This request expired before your answer; it won't be applied."}):m("fieldset",{className:"flex flex-wrap gap-3",children:[l("legend",{className:"sr-only",children:"Your answer"}),z2.map(c=>m("label",{className:"flex items-center gap-1",children:[l("input",{type:"radio",name:`choice-${e.id}`,value:c.value,checked:t===c.value,onChange:()=>n(c.value)}),c.label]},c.value))]}),m("p",{className:"text-xs text-muted-foreground",children:["Expires ",new Date(e.deadline).toLocaleString(),"."]})]})}function sc({interaction:e,submit:t,cancel:n}){let r=e.payload,[o,s]=_(()=>Object.fromEntries(r.items.map(T=>[T.id,"later"]))),[i,a]=_({}),[u,c]=_({}),[d,p]=_(!1),[f,h]=_(null),[g,x]=_(()=>Date.now());K(()=>{let T=r.items.map(S=>S.deadline).filter(S=>S>g).sort((S,$)=>S-$)[0];if(T===void 0)return;let N=setTimeout(()=>x(Date.now()),Math.min(T-g+50,2**31-1));return()=>clearTimeout(N)},[r.items,g]);let b=r.items.some(T=>o[T.id]==="approve"&&T.explanation.extraConfirmation&&!i[T.id]),v=T=>u[T]??{until:"",once:!1};function w(T){let N=T.offer;if(o[T.id]!=="approve"||!N)return;let S=v(T.id);if(N.once&&S.once)return{once:!0};if(N.expiry)return{expiresAt:S.until?Date.parse(S.until):null}}let C=r.items.some(T=>{let N=w(T)?.expiresAt;return typeof N=="number"&&(!Number.isFinite(N)||N<=Date.now())});async function y(){if(d||b||C)return;p(!0),h(null);let T=r.items.filter(N=>N.deadline>Date.now()).map(N=>{let S=w(N);return{id:N.id,planHash:N.planHash,choice:o[N.id]??"later",acknowledgeRisk:i[N.id]===!0,...S?{options:S}:{}}});try{await t({form:r.form,answers:T})}catch{h("Your answer did not go through. Try again."),p(!1)}}return m("div",{className:"space-y-3 p-3 text-sm",children:[l("p",{className:"font-medium",children:r.items.length===1?"A change your moonlet asked for":`${r.items.length} changes your moonlet asked for`}),r.items.map(T=>l(K2,{item:T,choice:o[T.id]??"later",onChoice:N=>s({...o,[T.id]:N}),acknowledged:i[T.id]===!0,onAcknowledge:N=>a({...i,[T.id]:N}),narrowing:v(T.id),onNarrow:N=>c({...u,[T.id]:N}),expired:T.deadline<=g},T.id)),l("p",{children:"Approve applies exactly what is shown. Decline is remembered for 30 days. Later keeps it for another time. Nothing changes until you send your answers."}),m("div",{className:"flex flex-wrap gap-2",children:[l(R,{size:"sm",disabled:d||b||C,onClick:()=>{y()},children:"Send answers"}),l(R,{size:"sm",variant:"ghost",disabled:d,onClick:()=>{n()},children:"Not now"})]}),b&&l("p",{children:"Tick the confirmation on each high-risk change you approve."}),C&&l("p",{children:"Choose a future end time, or leave it empty for no time limit."}),f&&l("p",{role:"alert",children:f})]})}function av(e){return e>>>0}function Ti(e){return e|0}var lv="warn",de=()=>{},Qe=()=>{},Ye=()=>{},Me=()=>{};function X2(e){if(typeof e>"u"?e=lv:lv=e,de=Qe=Ye=Me=()=>{},typeof window.console<"u")switch(e){case"debug":de=console.debug.bind(window.console);case"info":Qe=console.info.bind(window.console);case"warn":Ye=console.warn.bind(window.console);case"error":Me=console.error.bind(window.console);case"none":break;default:throw new window.Error("invalid logging type '"+e+"'")}}X2();function ic(e,t=!1){try{return decodeURIComponent(escape(e))}catch(n){if(n instanceof URIError&&t)return e;throw n}}function Gt(e){return unescape(encodeURIComponent(e))}var Oo={toBase64Table:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".split(""),base64Pad:"=",encode(e){"use strict";let t="",n=e.length,r=n%3;for(let s=0;s<n-2;s+=3)t+=this.toBase64Table[e[s]>>2],t+=this.toBase64Table[((e[s]&3)<<4)+(e[s+1]>>4)],t+=this.toBase64Table[((e[s+1]&15)<<2)+(e[s+2]>>6)],t+=this.toBase64Table[e[s+2]&63];let o=n-r;return r===2?(t+=this.toBase64Table[e[o]>>2],t+=this.toBase64Table[((e[o]&3)<<4)+(e[o+1]>>4)],t+=this.toBase64Table[(e[o+1]&15)<<2],t+=this.toBase64Table[64]):r===1&&(t+=this.toBase64Table[e[o]>>2],t+=this.toBase64Table[(e[o]&3)<<4],t+=this.toBase64Table[64],t+=this.toBase64Table[64]),t},toBinaryTable:[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,0,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1],decode(e,t=0){let n=e.indexOf("=")-t;n<0&&(n=e.length-t);let r=(n>>2)*3+Math.floor(n%4/1.5),o=new Array(r),s=0,i=0;for(let a=0,u=t;u<e.length;u++){let c=this.toBinaryTable[e.charCodeAt(u)&127],d=e.charAt(u)===this.base64Pad;if(c===-1){Me("Illegal character code "+e.charCodeAt(u)+" at position "+u);continue}i=i<<6|c,s+=6,s>=8&&(s-=8,d||(o[a++]=i>>s&255),i&=(1<<s)-1)}if(s){let a=new Error("Corrupted base64 string");throw a.name="Base64-Error",a}return o}};var Lf="ontouchstart"in document.documentElement||document.ontouchstart!==void 0||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0;window.addEventListener("touchstart",function e(){Lf=!0,window.removeEventListener("touchstart",e,!1)},!1);var Ri=10*(window.devicePixelRatio||1),cv=!1;try{let e=document.createElement("canvas");e.style.cursor='url("data:image/x-icon;base64,AAACAAEACAgAAAIAAgA4AQAAFgAAACgAAAAIAAAAEAAAAAEAIAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAAAAAAAA==") 2 2, default',e.style.cursor.indexOf("url")===0?(Qe("Data URI scheme cursor supported"),cv=!0):Ye("Data URI scheme cursor not supported")}catch(e){Me("Data URI scheme cursor test exception: "+e)}var uv=cv,B2=!0;try{let e=document.createElement("div");e.style.visibility="hidden",e.style.overflow="scroll",document.body.appendChild(e);let t=document.createElement("div");e.appendChild(t);let n=e.offsetWidth-t.offsetWidth;e.parentNode.removeChild(e),B2=n!=0}catch(e){Me("Scrollbar test exception: "+e)}var Mf=!1;async function U2(){if(!("VideoDecoder"in window))return!1;let e={codec:"avc1.42401f",codedWidth:1920,codedHeight:1080,optimizeForLatency:!0};if(!(await VideoDecoder.isConfigSupported(e)).supported)return!1;let n=new Uint8Array(Oo.decode("AAAAAWdCwBTZnpuAgICgAAADACAAAAZB4oVNAAAAAWjJYyyAAAABBgX//4HcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY0IHIzMTA4IDMxZTE5ZjkgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDIzIC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MCByZWY9NSBkZWJsb2NrPTE6MDowIGFuYWx5c2U9MHgxOjB4MTExIG1lPWhleCBzdWJtZT04IHBzeT0xIHBzeV9yZD0xLjAwOjAuMDAgbWl4ZWRfcmVmPTEgbWVfcmFuZ2U9MTYgY2hyb21hX21lPTEgdHJlbGxpcz0yIDh4OGRjdD0wIGNxbT0wIGRlYWR6b25lPTIxLDExIGZhc3RfcHNraXA9MSBjaHJvbWFfcXBfb2Zmc2V0PS0yIHRocmVhZHM9MSBsb29rYWhlYWRfdGhyZWFkcz0xIHNsaWNlZF90aHJlYWRzPTAgbnI9MCBkZWNpbWF0ZT0xIGludGVybGFjZWQ9MCBibHVyYXlfY29tcGF0PTAgY29uc3RyYWluZWRfaW50cmE9MCBiZnJhbWVzPTAgd2VpZ2h0cD0wIGtleWludD1pbmZpbml0ZSBrZXlpbnRfbWluPTI1IHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NTAgcmM9YWJyIG1idHJlZT0xIGJpdHJhdGU9NDAwIHJhdGV0b2w9MS4wIHFjb21wPTAuNjAgcXBtaW49MCBxcG1heD02OSBxcHN0ZXA9NCBpcF9yYXRpbz0xLjQwIGFxPTE6MS4wMACAAAABZYiEBrxmKAAPVccAAS044AA5DRJMnkycJk4TPw==")),r=!1,o=null,s=new VideoDecoder({output:a=>{r=!0,a.close()},error:a=>{o=a}}),i=new EncodedVideoChunk({timestamp:0,type:"key",data:n});s.configure(e),s.decode(i);try{await s.flush()}catch(a){o=a}return!(!r||o!==null)}Mf=await U2();function Jn(){return!!/mac/i.exec(navigator.platform)}function Lo(){return!!/win/i.exec(navigator.platform)}function Mo(){return!!/ipad/i.exec(navigator.platform)||!!/iphone/i.exec(navigator.platform)||!!/ipod/i.exec(navigator.platform)}function Do(e,t,n){let r=n.getBoundingClientRect(),o={x:0,y:0};return e<r.left?o.x=0:e>=r.right?o.x=r.width-1:o.x=e-r.left,t<r.top?o.y=0:t>=r.bottom?o.y=r.height-1:o.y=t-r.top,o}function Pr(e){e.stopPropagation(),e.preventDefault()}var Df=!1,pv=null;document.captureElement=null;function Ir(e){if(Df)return;let t=new e.constructor(e.type,e);Df=!0,document.captureElement?document.captureElement.dispatchEvent(t):pv.dispatchEvent(t),Df=!1,e.stopPropagation(),t.defaultPrevented&&e.preventDefault(),e.type==="mouseup"&&gv()}function fv(){let e=document.getElementById("noVNC_mouse_capture_elem");e.style.cursor=window.getComputedStyle(document.captureElement).cursor}var hv=new MutationObserver(fv);function mv(e){if(e.setCapture)e.setCapture(),document.captureElement=e;else{gv();let t=document.getElementById("noVNC_mouse_capture_elem");t===null&&(t=document.createElement("div"),t.id="noVNC_mouse_capture_elem",t.style.position="fixed",t.style.top="0px",t.style.left="0px",t.style.width="100%",t.style.height="100%",t.style.zIndex=1e4,t.style.display="none",document.body.appendChild(t),t.addEventListener("contextmenu",Ir),t.addEventListener("mousemove",Ir),t.addEventListener("mouseup",Ir)),document.captureElement=e,hv.observe(e,{attributes:!0}),fv(),t.style.display="",window.addEventListener("mousemove",Ir),window.addEventListener("mouseup",Ir)}}function gv(){if(document.releaseCapture)document.releaseCapture(),document.captureElement=null;else{if(!document.captureElement)return;pv=document.captureElement,document.captureElement=null,hv.disconnect();let e=document.getElementById("noVNC_mouse_capture_elem");e.style.display="none",window.removeEventListener("mousemove",Ir),window.removeEventListener("mouseup",Ir)}}var Or=class{constructor(){this._listeners=new Map}addEventListener(t,n){this._listeners.has(t)||this._listeners.set(t,new Set),this._listeners.get(t).add(n)}removeEventListener(t,n){this._listeners.has(t)&&this._listeners.get(t).delete(n)}dispatchEvent(t){return this._listeners.has(t.type)?(this._listeners.get(t.type).forEach(n=>n.call(this,t)),!t.defaultPrevented):!0}};var $i=class{constructor(t){if(this._drawCtx=null,this._renderQ=[],this._flushPromise=null,this._fbWidth=0,this._fbHeight=0,this._prevDrawStyle="",de(">> Display.constructor"),this._target=t,!this._target)throw new Error("Target must be set");if(typeof this._target=="string")throw new Error("target must be a DOM element");if(!this._target.getContext)throw new Error("no getContext method");this._targetCtx=this._target.getContext("2d"),this._viewportLoc={x:0,y:0,w:this._target.width,h:this._target.height},this._backbuffer=document.createElement("canvas"),this._drawCtx=this._backbuffer.getContext("2d"),this._damageBounds={left:0,top:0,right:this._backbuffer.width,bottom:this._backbuffer.height},de("User Agent: "+navigator.userAgent),de("<< Display.constructor"),this._scale=1,this._clipViewport=!1}get scale(){return this._scale}set scale(t){this._rescale(t)}get clipViewport(){return this._clipViewport}set clipViewport(t){this._clipViewport=t;let n=this._viewportLoc;this.viewportChangeSize(n.w,n.h),this.viewportChangePos(0,0)}get width(){return this._fbWidth}get height(){return this._fbHeight}viewportChangePos(t,n){let r=this._viewportLoc;t=Math.floor(t),n=Math.floor(n),this._clipViewport||(t=-r.w,n=-r.h);let o=r.x+r.w-1,s=r.y+r.h-1;t<0&&r.x+t<0&&(t=-r.x),o+t>=this._fbWidth&&(t-=o+t-this._fbWidth+1),r.y+n<0&&(n=-r.y),s+n>=this._fbHeight&&(n-=s+n-this._fbHeight+1),!(t===0&&n===0)&&(de("viewportChange deltaX: "+t+", deltaY: "+n),r.x+=t,r.y+=n,this._damage(r.x,r.y,r.w,r.h),this.flip())}viewportChangeSize(t,n){(!this._clipViewport||typeof t>"u"||typeof n>"u")&&(de("Setting viewport to full display region"),t=this._fbWidth,n=this._fbHeight),t=Math.floor(t),n=Math.floor(n),t>this._fbWidth&&(t=this._fbWidth),n>this._fbHeight&&(n=this._fbHeight);let r=this._viewportLoc;if(r.w!==t||r.h!==n){r.w=t,r.h=n;let o=this._target;o.width=t,o.height=n,this.viewportChangePos(0,0),this._damage(r.x,r.y,r.w,r.h),this.flip(),this._rescale(this._scale)}}absX(t){return this._scale===0?0:Ti(t/this._scale+this._viewportLoc.x)}absY(t){return this._scale===0?0:Ti(t/this._scale+this._viewportLoc.y)}resize(t,n){this._prevDrawStyle="",this._fbWidth=t,this._fbHeight=n;let r=this._backbuffer;if(r.width!==t||r.height!==n){let s=null;r.width>0&&r.height>0&&(s=this._drawCtx.getImageData(0,0,r.width,r.height)),r.width!==t&&(r.width=t),r.height!==n&&(r.height=n),s&&this._drawCtx.putImageData(s,0,0)}let o=this._viewportLoc;this.viewportChangeSize(o.w,o.h),this.viewportChangePos(0,0)}getImageData(){return this._drawCtx.getImageData(0,0,this.width,this.height)}toDataURL(t,n){return this._backbuffer.toDataURL(t,n)}toBlob(t,n,r){return this._backbuffer.toBlob(t,n,r)}_damage(t,n,r,o){t<this._damageBounds.left&&(this._damageBounds.left=t),n<this._damageBounds.top&&(this._damageBounds.top=n),t+r>this._damageBounds.right&&(this._damageBounds.right=t+r),n+o>this._damageBounds.bottom&&(this._damageBounds.bottom=n+o)}flip(t){if(this._renderQ.length!==0&&!t)this._renderQPush({type:"flip"});else{let n=this._damageBounds.left,r=this._damageBounds.top,o=this._damageBounds.right-n,s=this._damageBounds.bottom-r,i=n-this._viewportLoc.x,a=r-this._viewportLoc.y;i<0&&(o+=i,n-=i,i=0),a<0&&(s+=a,r-=a,a=0),i+o>this._viewportLoc.w&&(o=this._viewportLoc.w-i),a+s>this._viewportLoc.h&&(s=this._viewportLoc.h-a),o>0&&s>0&&this._targetCtx.drawImage(this._backbuffer,n,r,o,s,i,a,o,s),this._damageBounds.left=this._damageBounds.top=65535,this._damageBounds.right=this._damageBounds.bottom=0}}pending(){return this._renderQ.length>0}flush(){return this._renderQ.length===0?Promise.resolve():(this._flushPromise===null&&(this._flushPromise=new Promise(t=>{this._flushResolve=t})),this._flushPromise)}fillRect(t,n,r,o,s,i){this._renderQ.length!==0&&!i?this._renderQPush({type:"fill",x:t,y:n,width:r,height:o,color:s}):(this._setFillColor(s),this._drawCtx.fillRect(t,n,r,o),this._damage(t,n,r,o))}copyImage(t,n,r,o,s,i,a){this._renderQ.length!==0&&!a?this._renderQPush({type:"copy",oldX:t,oldY:n,x:r,y:o,width:s,height:i}):(this._drawCtx.mozImageSmoothingEnabled=!1,this._drawCtx.webkitImageSmoothingEnabled=!1,this._drawCtx.msImageSmoothingEnabled=!1,this._drawCtx.imageSmoothingEnabled=!1,this._drawCtx.drawImage(this._backbuffer,t,n,s,i,r,o,s,i),this._damage(r,o,s,i))}imageRect(t,n,r,o,s,i){if(r===0||o===0)return;let a=new Image;a.src="data: "+s+";base64,"+Oo.encode(i),this._renderQPush({type:"img",img:a,x:t,y:n,width:r,height:o})}videoFrame(t,n,r,o,s){this._renderQPush({type:"frame",frame:s,x:t,y:n,width:r,height:o})}blitImage(t,n,r,o,s,i,a){if(this._renderQ.length!==0&&!a){let u=new Uint8Array(r*o*4);u.set(new Uint8Array(s.buffer,0,u.length)),this._renderQPush({type:"blit",data:u,x:t,y:n,width:r,height:o})}else{let u=new Uint8ClampedArray(s.buffer,s.byteOffset+i,r*o*4),c=new ImageData(u,r,o);this._drawCtx.putImageData(c,t,n),this._damage(t,n,r,o)}}drawImage(t,...n){if(this._drawCtx.drawImage(t,...n),n.length<=4){let[r,o]=n;this._damage(r,o,t.width,t.height)}else{let[,,r,o,s,i]=n;this._damage(s,i,r,o)}}autoscale(t,n){let r;if(t===0||n===0)r=0;else{let o=this._viewportLoc,s=t/n;o.w/o.h>=s?r=t/o.w:r=n/o.h}this._rescale(r)}_rescale(t){this._scale=t;let n=this._viewportLoc,r=t*n.w+"px",o=t*n.h+"px";(this._target.style.width!==r||this._target.style.height!==o)&&(this._target.style.width=r,this._target.style.height=o)}_setFillColor(t){let n="rgb("+t[0]+","+t[1]+","+t[2]+")";n!==this._prevDrawStyle&&(this._drawCtx.fillStyle=n,this._prevDrawStyle=n)}_renderQPush(t){this._renderQ.push(t),this._renderQ.length===1&&this._scanRenderQ()}_resumeRenderQ(){this.removeEventListener("load",this._noVNCDisplay._resumeRenderQ),this._noVNCDisplay._scanRenderQ()}_scanRenderQ(){let t=!0;for(;t&&this._renderQ.length>0;){let n=this._renderQ[0];switch(n.type){case"flip":this.flip(!0);break;case"copy":this.copyImage(n.oldX,n.oldY,n.x,n.y,n.width,n.height,!0);break;case"fill":this.fillRect(n.x,n.y,n.width,n.height,n.color,!0);break;case"blit":this.blitImage(n.x,n.y,n.width,n.height,n.data,0,!0);break;case"img":if(n.img.complete){if(n.img.width!==n.width||n.img.height!==n.height){Me("Decoded image has incorrect dimensions. Got "+n.img.width+"x"+n.img.height+". Expected "+n.width+"x"+n.height+".");return}this.drawImage(n.img,n.x,n.y),n.img.src=""}else n.img._noVNCDisplay=this,n.img.addEventListener("load",this._resumeRenderQ),t=!1;break;case"frame":if(n.frame.ready){let r=n.frame.frame;(r.codedWidth<n.width||r.codedHeight<n.height)&&Ye("Decoded video frame does not cover its full rectangle area. Expecting at least "+n.width+"x"+n.height+" but got "+r.codedWidth+"x"+r.codedHeight);let o=0,s=0,i=n.width,a=n.height,u=n.x,c=n.y,d=i,p=a;this.drawImage(r,o,s,i,a,u,c,d,p),r.close()}else{let r=this;n.frame.promise.then(()=>{r._scanRenderQ()}),t=!1}break}t&&this._renderQ.shift()}this._renderQ.length===0&&this._flushPromise!==null&&(this._flushResolve(),this._flushPromise=null,this._flushResolve=null)}};function Xt(e,t,n,r,o){if(t.subarray&&e.subarray){e.set(t.subarray(n,n+r),o);return}for(var s=0;s<r;s++)e[o+s]=t[n+s]}var Fo=Uint8Array,bt=Uint16Array,Ii=Int32Array;function zo(e,t,n,r){for(var o=e&65535|0,s=e>>>16&65535|0,i=0;n!==0;){i=n>2e3?2e3:n,n-=i;do o=o+t[r++]|0,s=s+o|0;while(--i);o%=65521,s%=65521}return o|s<<16|0}function Ue(){for(var e,t=[],n=0;n<256;n++){e=n;for(var r=0;r<8;r++)e=e&1?3988292384^e>>>1:e>>>1;t[n]=e}return t}var Bz=Ue();var lc=30,H2=12;function Ff(e,t){var n,r,o,s,i,a,u,c,d,p,f,h,g,x,b,v,w,C,y,T,N,S,$,P,L;n=e.state,r=e.next_in,P=e.input,o=r+(e.avail_in-5),s=e.next_out,L=e.output,i=s-(t-e.avail_out),a=s+(e.avail_out-257),u=n.dmax,c=n.wsize,d=n.whave,p=n.wnext,f=n.window,h=n.hold,g=n.bits,x=n.lencode,b=n.distcode,v=(1<<n.lenbits)-1,w=(1<<n.distbits)-1;e:do{g<15&&(h+=P[r++]<<g,g+=8,h+=P[r++]<<g,g+=8),C=x[h&v];t:for(;;){if(y=C>>>24,h>>>=y,g-=y,y=C>>>16&255,y===0)L[s++]=C&65535;else if(y&16){T=C&65535,y&=15,y&&(g<y&&(h+=P[r++]<<g,g+=8),T+=h&(1<<y)-1,h>>>=y,g-=y),g<15&&(h+=P[r++]<<g,g+=8,h+=P[r++]<<g,g+=8),C=b[h&w];n:for(;;){if(y=C>>>24,h>>>=y,g-=y,y=C>>>16&255,y&16){if(N=C&65535,y&=15,g<y&&(h+=P[r++]<<g,g+=8,g<y&&(h+=P[r++]<<g,g+=8)),N+=h&(1<<y)-1,N>u){e.msg="invalid distance too far back",n.mode=lc;break e}if(h>>>=y,g-=y,y=s-i,N>y){if(y=N-y,y>d&&n.sane){e.msg="invalid distance too far back",n.mode=lc;break e}if(S=0,$=f,p===0){if(S+=c-y,y<T){T-=y;do L[s++]=f[S++];while(--y);S=s-N,$=L}}else if(p<y){if(S+=c+p-y,y-=p,y<T){T-=y;do L[s++]=f[S++];while(--y);if(S=0,p<T){y=p,T-=y;do L[s++]=f[S++];while(--y);S=s-N,$=L}}}else if(S+=p-y,y<T){T-=y;do L[s++]=f[S++];while(--y);S=s-N,$=L}for(;T>2;)L[s++]=$[S++],L[s++]=$[S++],L[s++]=$[S++],T-=3;T&&(L[s++]=$[S++],T>1&&(L[s++]=$[S++]))}else{S=s-N;do L[s++]=L[S++],L[s++]=L[S++],L[s++]=L[S++],T-=3;while(T>2);T&&(L[s++]=L[S++],T>1&&(L[s++]=L[S++]))}}else if((y&64)===0){C=b[(C&65535)+(h&(1<<y)-1)];continue n}else{e.msg="invalid distance code",n.mode=lc;break e}break}}else if((y&64)===0){C=x[(C&65535)+(h&(1<<y)-1)];continue t}else if(y&32){n.mode=H2;break e}else{e.msg="invalid literal/length code",n.mode=lc;break e}break}}while(r<o&&s<a);T=g>>3,r-=T,g-=T<<3,h&=(1<<g)-1,e.next_in=r,e.next_out=s,e.avail_in=r<o?5+(o-r):5-(r-o),e.avail_out=s<a?257+(a-s):257-(s-a),n.hold=h,n.bits=g}var Ko=15,xv=852,bv=592,yv=0,zf=1,_v=2,V2=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],Z2=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],W2=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],j2=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];function Lr(e,t,n,r,o,s,i,a){var u=a.bits,c=0,d=0,p=0,f=0,h=0,g=0,x=0,b=0,v=0,w=0,C,y,T,N,S,$=null,P=0,L,ne=new bt(Ko+1),se=new bt(Ko+1),_e=null,ie=0,Q,j,G;for(c=0;c<=Ko;c++)ne[c]=0;for(d=0;d<r;d++)ne[t[n+d]]++;for(h=u,f=Ko;f>=1&&ne[f]===0;f--);if(h>f&&(h=f),f===0)return o[s++]=1<<24|64<<16|0,o[s++]=1<<24|64<<16|0,a.bits=1,0;for(p=1;p<f&&ne[p]===0;p++);for(h<p&&(h=p),b=1,c=1;c<=Ko;c++)if(b<<=1,b-=ne[c],b<0)return-1;if(b>0&&(e===yv||f!==1))return-1;for(se[1]=0,c=1;c<Ko;c++)se[c+1]=se[c]+ne[c];for(d=0;d<r;d++)t[n+d]!==0&&(i[se[t[n+d]]++]=d);if(e===yv?($=_e=i,L=19):e===zf?($=V2,P-=257,_e=Z2,ie-=257,L=256):($=W2,_e=j2,L=-1),w=0,d=0,c=p,S=s,g=h,x=0,T=-1,v=1<<h,N=v-1,e===zf&&v>xv||e===_v&&v>bv)return 1;for(;;){Q=c-x,i[d]<L?(j=0,G=i[d]):i[d]>L?(j=_e[ie+i[d]],G=$[P+i[d]]):(j=96,G=0),C=1<<c-x,y=1<<g,p=y;do y-=C,o[S+(w>>x)+y]=Q<<24|j<<16|G|0;while(y!==0);for(C=1<<c-1;w&C;)C>>=1;if(C!==0?(w&=C-1,w+=C):w=0,d++,--ne[c]===0){if(c===f)break;c=t[n+i[d]]}if(c>h&&(w&N)!==T){for(x===0&&(x=h),S+=p,g=c-x,b=1<<g;g+x<f&&(b-=ne[g+x],!(b<=0));)g++,b<<=1;if(v+=1<<g,e===zf&&v>xv||e===_v&&v>bv)return 1;T=w&N,o[T]=h<<24|g<<16|S-s|0}}return w!==0&&(o[S+w]=c-x<<24|64<<16|0),a.bits=h,0}var Q2=0,Qv=1,Gv=2,vv=4,G2=5,cc=6,pc=0,Y2=1,q2=2,Mr=-2,J2=-3,wv=-4,eR=-5,kv=8,Yv=1,Sv=2,Ev=3,Nv=4,Av=5,Cv=6,Tv=7,Rv=8,$v=9,Iv=10,Pv=11,$n=12,Kf=13,Ov=14,Xf=15,Lv=16,Mv=17,Dv=18,Fv=19,uc=20,dc=21,zv=22,Kv=23,Xv=24,Bv=25,Uv=26,Bf=27,Hv=28,Vv=29,Ke=30,Zv=31,tR=32,nR=852,rR=592,oR=15,sR=oR;function Wv(e){return(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24)}function iR(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new bt(320),this.work=new bt(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function aR(e){var t;return!e||!e.state?Mr:(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=t.wrap&1),t.mode=Yv,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Ii(nR),t.distcode=t.distdyn=new Ii(rR),t.sane=1,t.back=-1,pc)}function Vf(e){var t;return!e||!e.state?Mr:(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,aR(e))}function lR(e,t){var n,r;return!e||!e.state||(r=e.state,t<0?(n=0,t=-t):(n=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?Mr:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,Vf(e))}function cR(e,t){var n,r;return e?(r=new iR,e.state=r,r.window=null,n=lR(e,t),n!==pc&&(e.state=null),n):Mr}function qv(e){return cR(e,sR)}var jv=!0,Uf,Hf;function uR(e){if(jv){var t;for(Uf=new Ii(512),Hf=new Ii(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(Lr(Qv,e.lens,0,288,Uf,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;Lr(Gv,e.lens,0,32,Hf,0,e.work,{bits:5}),jv=!1}e.lencode=Uf,e.lenbits=9,e.distcode=Hf,e.distbits=5}function dR(e,t,n,r){var o,s=e.state;return s.window===null&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Fo(s.wsize)),r>=s.wsize?(Xt(s.window,t,n-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):(o=s.wsize-s.wnext,o>r&&(o=r),Xt(s.window,t,n-r,o,s.wnext),r-=o,r?(Xt(s.window,t,n-r,r,0),s.wnext=r,s.whave=s.wsize):(s.wnext+=o,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=o))),0}function Jv(e,t){var n,r,o,s,i,a,u,c,d,p,f,h,g,x,b=0,v,w,C,y,T,N,S,$,P=new Fo(4),L,ne,se=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&e.avail_in!==0)return Mr;n=e.state,n.mode===$n&&(n.mode=Kf),i=e.next_out,o=e.output,u=e.avail_out,s=e.next_in,r=e.input,a=e.avail_in,c=n.hold,d=n.bits,p=a,f=u,$=pc;e:for(;;)switch(n.mode){case Yv:if(n.wrap===0){n.mode=Kf;break}for(;d<16;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if(n.wrap&2&&c===35615){n.check=0,P[0]=c&255,P[1]=c>>>8&255,n.check=Ue(n.check,P,2,0),c=0,d=0,n.mode=Sv;break}if(n.flags=0,n.head&&(n.head.done=!1),!(n.wrap&1)||(((c&255)<<8)+(c>>8))%31){e.msg="incorrect header check",n.mode=Ke;break}if((c&15)!==kv){e.msg="unknown compression method",n.mode=Ke;break}if(c>>>=4,d-=4,S=(c&15)+8,n.wbits===0)n.wbits=S;else if(S>n.wbits){e.msg="invalid window size",n.mode=Ke;break}n.dmax=1<<S,e.adler=n.check=1,n.mode=c&512?Iv:$n,c=0,d=0;break;case Sv:for(;d<16;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if(n.flags=c,(n.flags&255)!==kv){e.msg="unknown compression method",n.mode=Ke;break}if(n.flags&57344){e.msg="unknown header flags set",n.mode=Ke;break}n.head&&(n.head.text=c>>8&1),n.flags&512&&(P[0]=c&255,P[1]=c>>>8&255,n.check=Ue(n.check,P,2,0)),c=0,d=0,n.mode=Ev;case Ev:for(;d<32;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}n.head&&(n.head.time=c),n.flags&512&&(P[0]=c&255,P[1]=c>>>8&255,P[2]=c>>>16&255,P[3]=c>>>24&255,n.check=Ue(n.check,P,4,0)),c=0,d=0,n.mode=Nv;case Nv:for(;d<16;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}n.head&&(n.head.xflags=c&255,n.head.os=c>>8),n.flags&512&&(P[0]=c&255,P[1]=c>>>8&255,n.check=Ue(n.check,P,2,0)),c=0,d=0,n.mode=Av;case Av:if(n.flags&1024){for(;d<16;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}n.length=c,n.head&&(n.head.extra_len=c),n.flags&512&&(P[0]=c&255,P[1]=c>>>8&255,n.check=Ue(n.check,P,2,0)),c=0,d=0}else n.head&&(n.head.extra=null);n.mode=Cv;case Cv:if(n.flags&1024&&(h=n.length,h>a&&(h=a),h&&(n.head&&(S=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),Xt(n.head.extra,r,s,h,S)),n.flags&512&&(n.check=Ue(n.check,r,h,s)),a-=h,s+=h,n.length-=h),n.length))break e;n.length=0,n.mode=Tv;case Tv:if(n.flags&2048){if(a===0)break e;h=0;do S=r[s+h++],n.head&&S&&n.length<65536&&(n.head.name+=String.fromCharCode(S));while(S&&h<a);if(n.flags&512&&(n.check=Ue(n.check,r,h,s)),a-=h,s+=h,S)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=Rv;case Rv:if(n.flags&4096){if(a===0)break e;h=0;do S=r[s+h++],n.head&&S&&n.length<65536&&(n.head.comment+=String.fromCharCode(S));while(S&&h<a);if(n.flags&512&&(n.check=Ue(n.check,r,h,s)),a-=h,s+=h,S)break e}else n.head&&(n.head.comment=null);n.mode=$v;case $v:if(n.flags&512){for(;d<16;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if(c!==(n.check&65535)){e.msg="header crc mismatch",n.mode=Ke;break}c=0,d=0}n.head&&(n.head.hcrc=n.flags>>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=$n;break;case Iv:for(;d<32;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}e.adler=n.check=Wv(c),c=0,d=0,n.mode=Pv;case Pv:if(n.havedict===0)return e.next_out=i,e.avail_out=u,e.next_in=s,e.avail_in=a,n.hold=c,n.bits=d,q2;e.adler=n.check=1,n.mode=$n;case $n:if(t===G2||t===cc)break e;case Kf:if(n.last){c>>>=d&7,d-=d&7,n.mode=Bf;break}for(;d<3;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}switch(n.last=c&1,c>>>=1,d-=1,c&3){case 0:n.mode=Ov;break;case 1:if(uR(n),n.mode=uc,t===cc){c>>>=2,d-=2;break e}break;case 2:n.mode=Mv;break;case 3:e.msg="invalid block type",n.mode=Ke}c>>>=2,d-=2;break;case Ov:for(c>>>=d&7,d-=d&7;d<32;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if((c&65535)!==(c>>>16^65535)){e.msg="invalid stored block lengths",n.mode=Ke;break}if(n.length=c&65535,c=0,d=0,n.mode=Xf,t===cc)break e;case Xf:n.mode=Lv;case Lv:if(h=n.length,h){if(h>a&&(h=a),h>u&&(h=u),h===0)break e;Xt(o,r,s,h,i),a-=h,s+=h,u-=h,i+=h,n.length-=h;break}n.mode=$n;break;case Mv:for(;d<14;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if(n.nlen=(c&31)+257,c>>>=5,d-=5,n.ndist=(c&31)+1,c>>>=5,d-=5,n.ncode=(c&15)+4,c>>>=4,d-=4,n.nlen>286||n.ndist>30){e.msg="too many length or distance symbols",n.mode=Ke;break}n.have=0,n.mode=Dv;case Dv:for(;n.have<n.ncode;){for(;d<3;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}n.lens[se[n.have++]]=c&7,c>>>=3,d-=3}for(;n.have<19;)n.lens[se[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,L={bits:n.lenbits},$=Lr(Q2,n.lens,0,19,n.lencode,0,n.work,L),n.lenbits=L.bits,$){e.msg="invalid code lengths set",n.mode=Ke;break}n.have=0,n.mode=Fv;case Fv:for(;n.have<n.nlen+n.ndist;){for(;b=n.lencode[c&(1<<n.lenbits)-1],v=b>>>24,w=b>>>16&255,C=b&65535,!(v<=d);){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if(C<16)c>>>=v,d-=v,n.lens[n.have++]=C;else{if(C===16){for(ne=v+2;d<ne;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if(c>>>=v,d-=v,n.have===0){e.msg="invalid bit length repeat",n.mode=Ke;break}S=n.lens[n.have-1],h=3+(c&3),c>>>=2,d-=2}else if(C===17){for(ne=v+3;d<ne;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}c>>>=v,d-=v,S=0,h=3+(c&7),c>>>=3,d-=3}else{for(ne=v+7;d<ne;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}c>>>=v,d-=v,S=0,h=11+(c&127),c>>>=7,d-=7}if(n.have+h>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=Ke;break}for(;h--;)n.lens[n.have++]=S}}if(n.mode===Ke)break;if(n.lens[256]===0){e.msg="invalid code -- missing end-of-block",n.mode=Ke;break}if(n.lenbits=9,L={bits:n.lenbits},$=Lr(Qv,n.lens,0,n.nlen,n.lencode,0,n.work,L),n.lenbits=L.bits,$){e.msg="invalid literal/lengths set",n.mode=Ke;break}if(n.distbits=6,n.distcode=n.distdyn,L={bits:n.distbits},$=Lr(Gv,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,L),n.distbits=L.bits,$){e.msg="invalid distances set",n.mode=Ke;break}if(n.mode=uc,t===cc)break e;case uc:n.mode=dc;case dc:if(a>=6&&u>=258){e.next_out=i,e.avail_out=u,e.next_in=s,e.avail_in=a,n.hold=c,n.bits=d,Ff(e,f),i=e.next_out,o=e.output,u=e.avail_out,s=e.next_in,r=e.input,a=e.avail_in,c=n.hold,d=n.bits,n.mode===$n&&(n.back=-1);break}for(n.back=0;b=n.lencode[c&(1<<n.lenbits)-1],v=b>>>24,w=b>>>16&255,C=b&65535,!(v<=d);){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if(w&&(w&240)===0){for(y=v,T=w,N=C;b=n.lencode[N+((c&(1<<y+T)-1)>>y)],v=b>>>24,w=b>>>16&255,C=b&65535,!(y+v<=d);){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}c>>>=y,d-=y,n.back+=y}if(c>>>=v,d-=v,n.back+=v,n.length=C,w===0){n.mode=Uv;break}if(w&32){n.back=-1,n.mode=$n;break}if(w&64){e.msg="invalid literal/length code",n.mode=Ke;break}n.extra=w&15,n.mode=zv;case zv:if(n.extra){for(ne=n.extra;d<ne;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}n.length+=c&(1<<n.extra)-1,c>>>=n.extra,d-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=Kv;case Kv:for(;b=n.distcode[c&(1<<n.distbits)-1],v=b>>>24,w=b>>>16&255,C=b&65535,!(v<=d);){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if((w&240)===0){for(y=v,T=w,N=C;b=n.distcode[N+((c&(1<<y+T)-1)>>y)],v=b>>>24,w=b>>>16&255,C=b&65535,!(y+v<=d);){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}c>>>=y,d-=y,n.back+=y}if(c>>>=v,d-=v,n.back+=v,w&64){e.msg="invalid distance code",n.mode=Ke;break}n.offset=C,n.extra=w&15,n.mode=Xv;case Xv:if(n.extra){for(ne=n.extra;d<ne;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}n.offset+=c&(1<<n.extra)-1,c>>>=n.extra,d-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=Ke;break}n.mode=Bv;case Bv:if(u===0)break e;if(h=f-u,n.offset>h){if(h=n.offset-h,h>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=Ke;break}h>n.wnext?(h-=n.wnext,g=n.wsize-h):g=n.wnext-h,h>n.length&&(h=n.length),x=n.window}else x=o,g=i-n.offset,h=n.length;h>u&&(h=u),u-=h,n.length-=h;do o[i++]=x[g++];while(--h);n.length===0&&(n.mode=dc);break;case Uv:if(u===0)break e;o[i++]=n.length,u--,n.mode=dc;break;case Bf:if(n.wrap){for(;d<32;){if(a===0)break e;a--,c|=r[s++]<<d,d+=8}if(f-=u,e.total_out+=f,n.total+=f,f&&(e.adler=n.check=n.flags?Ue(n.check,o,f,i-f):zo(n.check,o,f,i-f)),f=u,(n.flags?c:Wv(c))!==n.check){e.msg="incorrect data check",n.mode=Ke;break}c=0,d=0}n.mode=Hv;case Hv:if(n.wrap&&n.flags){for(;d<32;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if(c!==(n.total&4294967295)){e.msg="incorrect length check",n.mode=Ke;break}c=0,d=0}n.mode=Vv;case Vv:$=Y2;break e;case Ke:$=J2;break e;case Zv:return wv;case tR:default:return Mr}return e.next_out=i,e.avail_out=u,e.next_in=s,e.avail_in=a,n.hold=c,n.bits=d,(n.wsize||f!==e.avail_out&&n.mode<Ke&&(n.mode<Bf||t!==vv))&&dR(e,e.output,e.next_out,f-e.avail_out)?(n.mode=Zv,wv):(p-=e.avail_in,f-=e.avail_out,e.total_in+=p,e.total_out+=f,n.total+=f,n.wrap&&f&&(e.adler=n.check=n.flags?Ue(n.check,o,f,e.next_out-f):zo(n.check,o,f,e.next_out-f)),e.data_type=n.bits+(n.last?64:0)+(n.mode===$n?128:0)+(n.mode===uc||n.mode===Xf?256:0),(p===0&&f===0||t===vv)&&$===pc&&($=eR),$)}function Pi(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var Yt=class{constructor(){this.strm=new Pi,this.chunkSize=1024*10*10,this.strm.output=new Uint8Array(this.chunkSize),qv(this.strm)}setInput(t){t?(this.strm.input=t,this.strm.avail_in=this.strm.input.length,this.strm.next_in=0):(this.strm.input=null,this.strm.avail_in=0,this.strm.next_in=0)}inflate(t){if(t>this.chunkSize&&(this.chunkSize=t,this.strm.output=new Uint8Array(this.chunkSize)),this.strm.next_out=0,this.strm.avail_out=t,Jv(this.strm,0)<0)throw new Error("zlib inflate failed");if(this.strm.next_out!=t)throw new Error("Incomplete zlib block");return new Uint8Array(this.strm.output.buffer,0,this.strm.next_out)}reset(){Vf(this.strm)}};var pR=4,ew=0,tw=1,fR=2;function Bo(e){for(var t=e.length;--t>=0;)e[t]=0}var hR=0,aw=1,mR=2,gR=3,xR=258,qf=29,zi=256,Li=zi+1+qf,Xo=30,Jf=19,lw=2*Li+1,Dr=15,Zf=16,bR=7,eh=256,cw=16,uw=17,dw=18,Gf=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],fc=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],yR=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],pw=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],_R=512,In=new Array((Li+2)*2);Bo(In);var Oi=new Array(Xo*2);Bo(Oi);var Mi=new Array(_R);Bo(Mi);var Di=new Array(xR-gR+1);Bo(Di);var th=new Array(qf);Bo(th);var hc=new Array(Xo);Bo(hc);function Wf(e,t,n,r,o){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=r,this.max_length=o,this.has_stree=e&&e.length}var fw,hw,mw;function jf(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function gw(e){return e<256?Mi[e]:Mi[256+(e>>>7)]}function Fi(e,t){e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255}function Nt(e,t,n){e.bi_valid>Zf-n?(e.bi_buf|=t<<e.bi_valid&65535,Fi(e,e.bi_buf),e.bi_buf=t>>Zf-e.bi_valid,e.bi_valid+=n-Zf):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=n)}function dn(e,t,n){Nt(e,n[t*2],n[t*2+1])}function xw(e,t){var n=0;do n|=e&1,e>>>=1,n<<=1;while(--t>0);return n>>>1}function vR(e){e.bi_valid===16?(Fi(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)}function wR(e,t){var n=t.dyn_tree,r=t.max_code,o=t.stat_desc.static_tree,s=t.stat_desc.has_stree,i=t.stat_desc.extra_bits,a=t.stat_desc.extra_base,u=t.stat_desc.max_length,c,d,p,f,h,g,x=0;for(f=0;f<=Dr;f++)e.bl_count[f]=0;for(n[e.heap[e.heap_max]*2+1]=0,c=e.heap_max+1;c<lw;c++)d=e.heap[c],f=n[n[d*2+1]*2+1]+1,f>u&&(f=u,x++),n[d*2+1]=f,!(d>r)&&(e.bl_count[f]++,h=0,d>=a&&(h=i[d-a]),g=n[d*2],e.opt_len+=g*(f+h),s&&(e.static_len+=g*(o[d*2+1]+h)));if(x!==0){do{for(f=u-1;e.bl_count[f]===0;)f--;e.bl_count[f]--,e.bl_count[f+1]+=2,e.bl_count[u]--,x-=2}while(x>0);for(f=u;f!==0;f--)for(d=e.bl_count[f];d!==0;)p=e.heap[--c],!(p>r)&&(n[p*2+1]!==f&&(e.opt_len+=(f-n[p*2+1])*n[p*2],n[p*2+1]=f),d--)}}function bw(e,t,n){var r=new Array(Dr+1),o=0,s,i;for(s=1;s<=Dr;s++)r[s]=o=o+n[s-1]<<1;for(i=0;i<=t;i++){var a=e[i*2+1];a!==0&&(e[i*2]=xw(r[a]++,a))}}function kR(){var e,t,n,r,o,s=new Array(Dr+1);for(n=0,r=0;r<qf-1;r++)for(th[r]=n,e=0;e<1<<Gf[r];e++)Di[n++]=r;for(Di[n-1]=r,o=0,r=0;r<16;r++)for(hc[r]=o,e=0;e<1<<fc[r];e++)Mi[o++]=r;for(o>>=7;r<Xo;r++)for(hc[r]=o<<7,e=0;e<1<<fc[r]-7;e++)Mi[256+o++]=r;for(t=0;t<=Dr;t++)s[t]=0;for(e=0;e<=143;)In[e*2+1]=8,e++,s[8]++;for(;e<=255;)In[e*2+1]=9,e++,s[9]++;for(;e<=279;)In[e*2+1]=7,e++,s[7]++;for(;e<=287;)In[e*2+1]=8,e++,s[8]++;for(bw(In,Li+1,s),e=0;e<Xo;e++)Oi[e*2+1]=5,Oi[e*2]=xw(e,5);fw=new Wf(In,Gf,zi+1,Li,Dr),hw=new Wf(Oi,fc,0,Xo,Dr),mw=new Wf(new Array(0),yR,0,Jf,bR)}function yw(e){var t;for(t=0;t<Li;t++)e.dyn_ltree[t*2]=0;for(t=0;t<Xo;t++)e.dyn_dtree[t*2]=0;for(t=0;t<Jf;t++)e.bl_tree[t*2]=0;e.dyn_ltree[eh*2]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function _w(e){e.bi_valid>8?Fi(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function SR(e,t,n,r){_w(e),r&&(Fi(e,n),Fi(e,~n)),Xt(e.pending_buf,e.window,t,n,e.pending),e.pending+=n}function nw(e,t,n,r){var o=t*2,s=n*2;return e[o]<e[s]||e[o]===e[s]&&r[t]<=r[n]}function Qf(e,t,n){for(var r=e.heap[n],o=n<<1;o<=e.heap_len&&(o<e.heap_len&&nw(t,e.heap[o+1],e.heap[o],e.depth)&&o++,!nw(t,r,e.heap[o],e.depth));)e.heap[n]=e.heap[o],n=o,o<<=1;e.heap[n]=r}function rw(e,t,n){var r,o,s=0,i,a;if(e.last_lit!==0)do r=e.pending_buf[e.d_buf+s*2]<<8|e.pending_buf[e.d_buf+s*2+1],o=e.pending_buf[e.l_buf+s],s++,r===0?dn(e,o,t):(i=Di[o],dn(e,i+zi+1,t),a=Gf[i],a!==0&&(o-=th[i],Nt(e,o,a)),r--,i=gw(r),dn(e,i,n),a=fc[i],a!==0&&(r-=hc[i],Nt(e,r,a)));while(s<e.last_lit);dn(e,eh,t)}function Yf(e,t){var n=t.dyn_tree,r=t.stat_desc.static_tree,o=t.stat_desc.has_stree,s=t.stat_desc.elems,i,a,u=-1,c;for(e.heap_len=0,e.heap_max=lw,i=0;i<s;i++)n[i*2]!==0?(e.heap[++e.heap_len]=u=i,e.depth[i]=0):n[i*2+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=u<2?++u:0,n[c*2]=1,e.depth[c]=0,e.opt_len--,o&&(e.static_len-=r[c*2+1]);for(t.max_code=u,i=e.heap_len>>1;i>=1;i--)Qf(e,n,i);c=s;do i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Qf(e,n,1),a=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=a,n[c*2]=n[i*2]+n[a*2],e.depth[c]=(e.depth[i]>=e.depth[a]?e.depth[i]:e.depth[a])+1,n[i*2+1]=n[a*2+1]=c,e.heap[1]=c++,Qf(e,n,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],wR(e,t),bw(n,u,e.bl_count)}function ow(e,t,n){var r,o=-1,s,i=t[1],a=0,u=7,c=4;for(i===0&&(u=138,c=3),t[(n+1)*2+1]=65535,r=0;r<=n;r++)s=i,i=t[(r+1)*2+1],!(++a<u&&s===i)&&(a<c?e.bl_tree[s*2]+=a:s!==0?(s!==o&&e.bl_tree[s*2]++,e.bl_tree[cw*2]++):a<=10?e.bl_tree[uw*2]++:e.bl_tree[dw*2]++,a=0,o=s,i===0?(u=138,c=3):s===i?(u=6,c=3):(u=7,c=4))}function sw(e,t,n){var r,o=-1,s,i=t[1],a=0,u=7,c=4;for(i===0&&(u=138,c=3),r=0;r<=n;r++)if(s=i,i=t[(r+1)*2+1],!(++a<u&&s===i)){if(a<c)do dn(e,s,e.bl_tree);while(--a!==0);else s!==0?(s!==o&&(dn(e,s,e.bl_tree),a--),dn(e,cw,e.bl_tree),Nt(e,a-3,2)):a<=10?(dn(e,uw,e.bl_tree),Nt(e,a-3,3)):(dn(e,dw,e.bl_tree),Nt(e,a-11,7));a=0,o=s,i===0?(u=138,c=3):s===i?(u=6,c=3):(u=7,c=4)}}function ER(e){var t;for(ow(e,e.dyn_ltree,e.l_desc.max_code),ow(e,e.dyn_dtree,e.d_desc.max_code),Yf(e,e.bl_desc),t=Jf-1;t>=3&&e.bl_tree[pw[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t}function NR(e,t,n,r){var o;for(Nt(e,t-257,5),Nt(e,n-1,5),Nt(e,r-4,4),o=0;o<r;o++)Nt(e,e.bl_tree[pw[o]*2+1],3);sw(e,e.dyn_ltree,t-1),sw(e,e.dyn_dtree,n-1)}function AR(e){var t=4093624447,n;for(n=0;n<=31;n++,t>>>=1)if(t&1&&e.dyn_ltree[n*2]!==0)return ew;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return tw;for(n=32;n<zi;n++)if(e.dyn_ltree[n*2]!==0)return tw;return ew}var iw=!1;function vw(e){iw||(kR(),iw=!0),e.l_desc=new jf(e.dyn_ltree,fw),e.d_desc=new jf(e.dyn_dtree,hw),e.bl_desc=new jf(e.bl_tree,mw),e.bi_buf=0,e.bi_valid=0,yw(e)}function nh(e,t,n,r){Nt(e,(hR<<1)+(r?1:0),3),SR(e,t,n,!0)}function ww(e){Nt(e,aw<<1,3),dn(e,eh,In),vR(e)}function kw(e,t,n,r){var o,s,i=0;e.level>0?(e.strm.data_type===fR&&(e.strm.data_type=AR(e)),Yf(e,e.l_desc),Yf(e,e.d_desc),i=ER(e),o=e.opt_len+3+7>>>3,s=e.static_len+3+7>>>3,s<=o&&(o=s)):o=s=n+5,n+4<=o&&t!==-1?nh(e,t,n,r):e.strategy===pR||s===o?(Nt(e,(aw<<1)+(r?1:0),3),rw(e,In,Oi)):(Nt(e,(mR<<1)+(r?1:0),3),NR(e,e.l_desc.max_code+1,e.d_desc.max_code+1,i+1),rw(e,e.dyn_ltree,e.dyn_dtree)),yw(e),r&&_w(e)}function Pn(e,t,n){return e.pending_buf[e.d_buf+e.last_lit*2]=t>>>8&255,e.pending_buf[e.d_buf+e.last_lit*2+1]=t&255,e.pending_buf[e.l_buf+e.last_lit]=n&255,e.last_lit++,t===0?e.dyn_ltree[n*2]++:(e.matches++,t--,e.dyn_ltree[(Di[n]+zi+1)*2]++,e.dyn_dtree[gw(t)*2]++),e.last_lit===e.lit_bufsize-1}var Sw={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"};var Xr=0,TR=1,xc=3,nr=4,Ew=5,Fr=0,Nw=1,Zo=-2;var rh=-5,ch=-1,RR=1,mc=2,$R=3,IR=4,PR=0,OR=2,bc=8,LR=9,MR=15,DR=8,FR=29,zR=256,lh=zR+1+FR,KR=30,XR=19,BR=2*lh+1,UR=15,Ae=3,tr=258,qt=tr+Ae+1,HR=32,Tw=42,Aw=69,oh=73,sh=91,ih=103,Xi=113,gc=666,qe=1,Bi=2,Kr=3,Wo=4,VR=3;function Ho(e,t){return e.msg=Sw[t],t}function Cw(e){return(e<<1)-(e>4?9:0)}function zr(e){for(var t=e.length;--t>=0;)e[t]=0}function er(e){var t=e.state,n=t.pending;n>e.avail_out&&(n=e.avail_out),n!==0&&(Xt(e.output,t.pending_buf,t.pending_out,n,e.next_out),e.next_out+=n,t.pending_out+=n,e.total_out+=n,e.avail_out-=n,t.pending-=n,t.pending===0&&(t.pending_out=0))}function st(e,t){kw(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,er(e.strm)}function Ne(e,t){e.pending_buf[e.pending++]=t}function Ki(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255}function ZR(e,t,n,r){var o=e.avail_in;return o>r&&(o=r),o===0?0:(e.avail_in-=o,Xt(t,e.input,e.next_in,o,n),e.state.wrap===1?e.adler=zo(e.adler,t,o,n):e.state.wrap===2&&(e.adler=Ue(e.adler,t,o,n)),e.next_in+=o,e.total_in+=o,o)}function Rw(e,t){var n=e.max_chain_length,r=e.strstart,o,s,i=e.prev_length,a=e.nice_match,u=e.strstart>e.w_size-qt?e.strstart-(e.w_size-qt):0,c=e.window,d=e.w_mask,p=e.prev,f=e.strstart+tr,h=c[r+i-1],g=c[r+i];e.prev_length>=e.good_match&&(n>>=2),a>e.lookahead&&(a=e.lookahead);do if(o=t,!(c[o+i]!==g||c[o+i-1]!==h||c[o]!==c[r]||c[++o]!==c[r+1])){r+=2,o++;do;while(c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&r<f);if(s=tr-(f-r),r=f-tr,s>i){if(e.match_start=t,i=s,s>=a)break;h=c[r+i-1],g=c[r+i]}}while((t=p[t&d])>u&&--n!==0);return i<=e.lookahead?i:e.lookahead}function Ui(e){var t=e.w_size,n,r,o,s,i;do{if(s=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-qt)){Xt(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,r=e.hash_size,n=r;do o=e.head[--n],e.head[n]=o>=t?o-t:0;while(--r);r=t,n=r;do o=e.prev[--n],e.prev[n]=o>=t?o-t:0;while(--r);s+=t}if(e.strm.avail_in===0)break;if(r=ZR(e.strm,e.window,e.strstart+e.lookahead,s),e.lookahead+=r,e.lookahead+e.insert>=Ae)for(i=e.strstart-e.insert,e.ins_h=e.window[i],e.ins_h=(e.ins_h<<e.hash_shift^e.window[i+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[i+Ae-1])&e.hash_mask,e.prev[i&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=i,i++,e.insert--,!(e.lookahead+e.insert<Ae)););}while(e.lookahead<qt&&e.strm.avail_in!==0)}function WR(e,t){var n=65535;for(n>e.pending_buf_size-5&&(n=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Ui(e),e.lookahead===0&&t===Xr)return qe;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var r=e.block_start+n;if((e.strstart===0||e.strstart>=r)&&(e.lookahead=e.strstart-r,e.strstart=r,st(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-qt&&(st(e,!1),e.strm.avail_out===0))return qe}return e.insert=0,t===nr?(st(e,!0),e.strm.avail_out===0?Kr:Wo):(e.strstart>e.block_start&&(st(e,!1),e.strm.avail_out===0),qe)}function ah(e,t){for(var n,r;;){if(e.lookahead<qt){if(Ui(e),e.lookahead<qt&&t===Xr)return qe;if(e.lookahead===0)break}if(n=0,e.lookahead>=Ae&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+Ae-1])&e.hash_mask,n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),n!==0&&e.strstart-n<=e.w_size-qt&&(e.match_length=Rw(e,n)),e.match_length>=Ae)if(r=Pn(e,e.strstart-e.match_start,e.match_length-Ae),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=Ae){e.match_length--;do e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+Ae-1])&e.hash_mask,n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!==0);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else r=Pn(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(st(e,!1),e.strm.avail_out===0))return qe}return e.insert=e.strstart<Ae-1?e.strstart:Ae-1,t===nr?(st(e,!0),e.strm.avail_out===0?Kr:Wo):e.last_lit&&(st(e,!1),e.strm.avail_out===0)?qe:Bi}function Uo(e,t){for(var n,r,o;;){if(e.lookahead<qt){if(Ui(e),e.lookahead<qt&&t===Xr)return qe;if(e.lookahead===0)break}if(n=0,e.lookahead>=Ae&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+Ae-1])&e.hash_mask,n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=Ae-1,n!==0&&e.prev_length<e.max_lazy_match&&e.strstart-n<=e.w_size-qt&&(e.match_length=Rw(e,n),e.match_length<=5&&(e.strategy===RR||e.match_length===Ae&&e.strstart-e.match_start>4096)&&(e.match_length=Ae-1)),e.prev_length>=Ae&&e.match_length<=e.prev_length){o=e.strstart+e.lookahead-Ae,r=Pn(e,e.strstart-1-e.prev_match,e.prev_length-Ae),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=o&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+Ae-1])&e.hash_mask,n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!==0);if(e.match_available=0,e.match_length=Ae-1,e.strstart++,r&&(st(e,!1),e.strm.avail_out===0))return qe}else if(e.match_available){if(r=Pn(e,0,e.window[e.strstart-1]),r&&st(e,!1),e.strstart++,e.lookahead--,e.strm.avail_out===0)return qe}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(r=Pn(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<Ae-1?e.strstart:Ae-1,t===nr?(st(e,!0),e.strm.avail_out===0?Kr:Wo):e.last_lit&&(st(e,!1),e.strm.avail_out===0)?qe:Bi}function jR(e,t){for(var n,r,o,s,i=e.window;;){if(e.lookahead<=tr){if(Ui(e),e.lookahead<=tr&&t===Xr)return qe;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=Ae&&e.strstart>0&&(o=e.strstart-1,r=i[o],r===i[++o]&&r===i[++o]&&r===i[++o])){s=e.strstart+tr;do;while(r===i[++o]&&r===i[++o]&&r===i[++o]&&r===i[++o]&&r===i[++o]&&r===i[++o]&&r===i[++o]&&r===i[++o]&&o<s);e.match_length=tr-(s-o),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=Ae?(n=Pn(e,1,e.match_length-Ae),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(n=Pn(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),n&&(st(e,!1),e.strm.avail_out===0))return qe}return e.insert=0,t===nr?(st(e,!0),e.strm.avail_out===0?Kr:Wo):e.last_lit&&(st(e,!1),e.strm.avail_out===0)?qe:Bi}function QR(e,t){for(var n;;){if(e.lookahead===0&&(Ui(e),e.lookahead===0)){if(t===Xr)return qe;break}if(e.match_length=0,n=Pn(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,n&&(st(e,!1),e.strm.avail_out===0))return qe}return e.insert=0,t===nr?(st(e,!0),e.strm.avail_out===0?Kr:Wo):e.last_lit&&(st(e,!1),e.strm.avail_out===0)?qe:Bi}function pn(e,t,n,r,o){this.good_length=e,this.max_lazy=t,this.nice_length=n,this.max_chain=r,this.func=o}var Vo;Vo=[new pn(0,0,0,0,WR),new pn(4,4,8,4,ah),new pn(4,5,16,8,ah),new pn(4,6,32,32,ah),new pn(4,4,16,16,Uo),new pn(8,16,32,32,Uo),new pn(8,16,128,128,Uo),new pn(8,32,128,256,Uo),new pn(32,128,258,1024,Uo),new pn(32,258,258,4096,Uo)];function GR(e){e.window_size=2*e.w_size,zr(e.head),e.max_lazy_match=Vo[e.level].max_lazy,e.good_match=Vo[e.level].good_length,e.nice_match=Vo[e.level].nice_length,e.max_chain_length=Vo[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=Ae-1,e.match_available=0,e.ins_h=0}function YR(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=bc,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new bt(BR*2),this.dyn_dtree=new bt((2*KR+1)*2),this.bl_tree=new bt((2*XR+1)*2),zr(this.dyn_ltree),zr(this.dyn_dtree),zr(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new bt(UR+1),this.heap=new bt(2*lh+1),zr(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new bt(2*lh+1),zr(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function qR(e){var t;return!e||!e.state?Ho(e,Zo):(e.total_in=e.total_out=0,e.data_type=OR,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?Tw:Xi,e.adler=t.wrap===2?0:1,t.last_flush=Xr,vw(t),Fr)}function JR(e){var t=qR(e);return t===Fr&&GR(e.state),t}function e$(e,t,n,r,o,s){if(!e)return Zo;var i=1;if(t===ch&&(t=6),r<0?(i=0,r=-r):r>15&&(i=2,r-=16),o<1||o>LR||n!==bc||r<8||r>15||t<0||t>9||s<0||s>IR)return Ho(e,Zo);r===8&&(r=9);var a=new YR;return e.state=a,a.strm=e,a.wrap=i,a.gzhead=null,a.w_bits=r,a.w_size=1<<a.w_bits,a.w_mask=a.w_size-1,a.hash_bits=o+7,a.hash_size=1<<a.hash_bits,a.hash_mask=a.hash_size-1,a.hash_shift=~~((a.hash_bits+Ae-1)/Ae),a.window=new Fo(a.w_size*2),a.head=new bt(a.hash_size),a.prev=new bt(a.w_size),a.lit_bufsize=1<<o+6,a.pending_buf_size=a.lit_bufsize*4,a.pending_buf=new Fo(a.pending_buf_size),a.d_buf=1*a.lit_bufsize,a.l_buf=3*a.lit_bufsize,a.level=t,a.strategy=s,a.method=n,JR(e)}function $w(e,t){return e$(e,t,bc,MR,DR,PR)}function uh(e,t){var n,r,o,s;if(!e||!e.state||t>Ew||t<0)return e?Ho(e,Zo):Zo;if(r=e.state,!e.output||!e.input&&e.avail_in!==0||r.status===gc&&t!==nr)return Ho(e,e.avail_out===0?rh:Zo);if(r.strm=e,n=r.last_flush,r.last_flush=t,r.status===Tw)if(r.wrap===2)e.adler=0,Ne(r,31),Ne(r,139),Ne(r,8),r.gzhead?(Ne(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),Ne(r,r.gzhead.time&255),Ne(r,r.gzhead.time>>8&255),Ne(r,r.gzhead.time>>16&255),Ne(r,r.gzhead.time>>24&255),Ne(r,r.level===9?2:r.strategy>=mc||r.level<2?4:0),Ne(r,r.gzhead.os&255),r.gzhead.extra&&r.gzhead.extra.length&&(Ne(r,r.gzhead.extra.length&255),Ne(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(e.adler=Ue(e.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=Aw):(Ne(r,0),Ne(r,0),Ne(r,0),Ne(r,0),Ne(r,0),Ne(r,r.level===9?2:r.strategy>=mc||r.level<2?4:0),Ne(r,VR),r.status=Xi);else{var i=bc+(r.w_bits-8<<4)<<8,a=-1;r.strategy>=mc||r.level<2?a=0:r.level<6?a=1:r.level===6?a=2:a=3,i|=a<<6,r.strstart!==0&&(i|=HR),i+=31-i%31,r.status=Xi,Ki(r,i),r.strstart!==0&&(Ki(r,e.adler>>>16),Ki(r,e.adler&65535)),e.adler=1}if(r.status===Aw)if(r.gzhead.extra){for(o=r.pending;r.gzindex<(r.gzhead.extra.length&65535)&&!(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>o&&(e.adler=Ue(e.adler,r.pending_buf,r.pending-o,o)),er(e),o=r.pending,r.pending===r.pending_buf_size));)Ne(r,r.gzhead.extra[r.gzindex]&255),r.gzindex++;r.gzhead.hcrc&&r.pending>o&&(e.adler=Ue(e.adler,r.pending_buf,r.pending-o,o)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=oh)}else r.status=oh;if(r.status===oh)if(r.gzhead.name){o=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>o&&(e.adler=Ue(e.adler,r.pending_buf,r.pending-o,o)),er(e),o=r.pending,r.pending===r.pending_buf_size)){s=1;break}r.gzindex<r.gzhead.name.length?s=r.gzhead.name.charCodeAt(r.gzindex++)&255:s=0,Ne(r,s)}while(s!==0);r.gzhead.hcrc&&r.pending>o&&(e.adler=Ue(e.adler,r.pending_buf,r.pending-o,o)),s===0&&(r.gzindex=0,r.status=sh)}else r.status=sh;if(r.status===sh)if(r.gzhead.comment){o=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>o&&(e.adler=Ue(e.adler,r.pending_buf,r.pending-o,o)),er(e),o=r.pending,r.pending===r.pending_buf_size)){s=1;break}r.gzindex<r.gzhead.comment.length?s=r.gzhead.comment.charCodeAt(r.gzindex++)&255:s=0,Ne(r,s)}while(s!==0);r.gzhead.hcrc&&r.pending>o&&(e.adler=Ue(e.adler,r.pending_buf,r.pending-o,o)),s===0&&(r.status=ih)}else r.status=ih;if(r.status===ih&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&er(e),r.pending+2<=r.pending_buf_size&&(Ne(r,e.adler&255),Ne(r,e.adler>>8&255),e.adler=0,r.status=Xi)):r.status=Xi),r.pending!==0){if(er(e),e.avail_out===0)return r.last_flush=-1,Fr}else if(e.avail_in===0&&Cw(t)<=Cw(n)&&t!==nr)return Ho(e,rh);if(r.status===gc&&e.avail_in!==0)return Ho(e,rh);if(e.avail_in!==0||r.lookahead!==0||t!==Xr&&r.status!==gc){var u=r.strategy===mc?QR(r,t):r.strategy===$R?jR(r,t):Vo[r.level].func(r,t);if((u===Kr||u===Wo)&&(r.status=gc),u===qe||u===Kr)return e.avail_out===0&&(r.last_flush=-1),Fr;if(u===Bi&&(t===TR?ww(r):t!==Ew&&(nh(r,0,0,!1),t===xc&&(zr(r.head),r.lookahead===0&&(r.strstart=0,r.block_start=0,r.insert=0))),er(e),e.avail_out===0))return r.last_flush=-1,Fr}return t!==nr?Fr:r.wrap<=0?Nw:(r.wrap===2?(Ne(r,e.adler&255),Ne(r,e.adler>>8&255),Ne(r,e.adler>>16&255),Ne(r,e.adler>>24&255),Ne(r,e.total_in&255),Ne(r,e.total_in>>8&255),Ne(r,e.total_in>>16&255),Ne(r,e.total_in>>24&255)):(Ki(r,e.adler>>>16),Ki(r,e.adler&65535)),er(e),r.wrap>0&&(r.wrap=-r.wrap),r.pending!==0?Fr:Nw)}var Hi=class{constructor(){this.strm=new Pi,this.chunkSize=1024*10*10,this.outputBuffer=new Uint8Array(this.chunkSize),$w(this.strm,ch)}deflate(t){this.strm.input=t,this.strm.avail_in=this.strm.input.length,this.strm.next_in=0,this.strm.output=this.outputBuffer,this.strm.avail_out=this.chunkSize,this.strm.next_out=0;let n=uh(this.strm,xc),r=new Uint8Array(this.strm.output.buffer,0,this.strm.next_out);if(n<0)throw new Error("zlib deflate failed");if(this.strm.avail_in>0){let o=[r],s=r.length;do{if(this.strm.output=new Uint8Array(this.chunkSize),this.strm.next_out=0,this.strm.avail_out=this.chunkSize,n=uh(this.strm,xc),n<0)throw new Error("zlib deflate failed");let u=new Uint8Array(this.strm.output.buffer,0,this.strm.next_out);s+=u.length,o.push(u)}while(this.strm.avail_in>0);let i=new Uint8Array(s),a=0;for(let u=0;u<o.length;u++)i.set(o[u],a),a+=o[u].length;r=i}return this.strm.input=null,this.strm.avail_in=0,this.strm.next_in=0,r}};var A={XK_VoidSymbol:16777215,XK_BackSpace:65288,XK_Tab:65289,XK_Linefeed:65290,XK_Clear:65291,XK_Return:65293,XK_Pause:65299,XK_Scroll_Lock:65300,XK_Sys_Req:65301,XK_Escape:65307,XK_Delete:65535,XK_Multi_key:65312,XK_Codeinput:65335,XK_SingleCandidate:65340,XK_MultipleCandidate:65341,XK_PreviousCandidate:65342,XK_Kanji:65313,XK_Muhenkan:65314,XK_Henkan_Mode:65315,XK_Henkan:65315,XK_Romaji:65316,XK_Hiragana:65317,XK_Katakana:65318,XK_Hiragana_Katakana:65319,XK_Zenkaku:65320,XK_Hankaku:65321,XK_Zenkaku_Hankaku:65322,XK_Touroku:65323,XK_Massyo:65324,XK_Kana_Lock:65325,XK_Kana_Shift:65326,XK_Eisu_Shift:65327,XK_Eisu_toggle:65328,XK_Kanji_Bangou:65335,XK_Zen_Koho:65341,XK_Mae_Koho:65342,XK_Home:65360,XK_Left:65361,XK_Up:65362,XK_Right:65363,XK_Down:65364,XK_Prior:65365,XK_Page_Up:65365,XK_Next:65366,XK_Page_Down:65366,XK_End:65367,XK_Begin:65368,XK_Select:65376,XK_Print:65377,XK_Execute:65378,XK_Insert:65379,XK_Undo:65381,XK_Redo:65382,XK_Menu:65383,XK_Find:65384,XK_Cancel:65385,XK_Help:65386,XK_Break:65387,XK_Mode_switch:65406,XK_script_switch:65406,XK_Num_Lock:65407,XK_KP_Space:65408,XK_KP_Tab:65417,XK_KP_Enter:65421,XK_KP_F1:65425,XK_KP_F2:65426,XK_KP_F3:65427,XK_KP_F4:65428,XK_KP_Home:65429,XK_KP_Left:65430,XK_KP_Up:65431,XK_KP_Right:65432,XK_KP_Down:65433,XK_KP_Prior:65434,XK_KP_Page_Up:65434,XK_KP_Next:65435,XK_KP_Page_Down:65435,XK_KP_End:65436,XK_KP_Begin:65437,XK_KP_Insert:65438,XK_KP_Delete:65439,XK_KP_Equal:65469,XK_KP_Multiply:65450,XK_KP_Add:65451,XK_KP_Separator:65452,XK_KP_Subtract:65453,XK_KP_Decimal:65454,XK_KP_Divide:65455,XK_KP_0:65456,XK_KP_1:65457,XK_KP_2:65458,XK_KP_3:65459,XK_KP_4:65460,XK_KP_5:65461,XK_KP_6:65462,XK_KP_7:65463,XK_KP_8:65464,XK_KP_9:65465,XK_F1:65470,XK_F2:65471,XK_F3:65472,XK_F4:65473,XK_F5:65474,XK_F6:65475,XK_F7:65476,XK_F8:65477,XK_F9:65478,XK_F10:65479,XK_F11:65480,XK_L1:65480,XK_F12:65481,XK_L2:65481,XK_F13:65482,XK_L3:65482,XK_F14:65483,XK_L4:65483,XK_F15:65484,XK_L5:65484,XK_F16:65485,XK_L6:65485,XK_F17:65486,XK_L7:65486,XK_F18:65487,XK_L8:65487,XK_F19:65488,XK_L9:65488,XK_F20:65489,XK_L10:65489,XK_F21:65490,XK_R1:65490,XK_F22:65491,XK_R2:65491,XK_F23:65492,XK_R3:65492,XK_F24:65493,XK_R4:65493,XK_F25:65494,XK_R5:65494,XK_F26:65495,XK_R6:65495,XK_F27:65496,XK_R7:65496,XK_F28:65497,XK_R8:65497,XK_F29:65498,XK_R9:65498,XK_F30:65499,XK_R10:65499,XK_F31:65500,XK_R11:65500,XK_F32:65501,XK_R12:65501,XK_F33:65502,XK_R13:65502,XK_F34:65503,XK_R14:65503,XK_F35:65504,XK_R15:65504,XK_Shift_L:65505,XK_Shift_R:65506,XK_Control_L:65507,XK_Control_R:65508,XK_Caps_Lock:65509,XK_Shift_Lock:65510,XK_Meta_L:65511,XK_Meta_R:65512,XK_Alt_L:65513,XK_Alt_R:65514,XK_Super_L:65515,XK_Super_R:65516,XK_Hyper_L:65517,XK_Hyper_R:65518,XK_ISO_Level3_Shift:65027,XK_ISO_Next_Group:65032,XK_ISO_Prev_Group:65034,XK_ISO_First_Group:65036,XK_ISO_Last_Group:65038,XK_space:32,XK_exclam:33,XK_quotedbl:34,XK_numbersign:35,XK_dollar:36,XK_percent:37,XK_ampersand:38,XK_apostrophe:39,XK_quoteright:39,XK_parenleft:40,XK_parenright:41,XK_asterisk:42,XK_plus:43,XK_comma:44,XK_minus:45,XK_period:46,XK_slash:47,XK_0:48,XK_1:49,XK_2:50,XK_3:51,XK_4:52,XK_5:53,XK_6:54,XK_7:55,XK_8:56,XK_9:57,XK_colon:58,XK_semicolon:59,XK_less:60,XK_equal:61,XK_greater:62,XK_question:63,XK_at:64,XK_A:65,XK_B:66,XK_C:67,XK_D:68,XK_E:69,XK_F:70,XK_G:71,XK_H:72,XK_I:73,XK_J:74,XK_K:75,XK_L:76,XK_M:77,XK_N:78,XK_O:79,XK_P:80,XK_Q:81,XK_R:82,XK_S:83,XK_T:84,XK_U:85,XK_V:86,XK_W:87,XK_X:88,XK_Y:89,XK_Z:90,XK_bracketleft:91,XK_backslash:92,XK_bracketright:93,XK_asciicircum:94,XK_underscore:95,XK_grave:96,XK_quoteleft:96,XK_a:97,XK_b:98,XK_c:99,XK_d:100,XK_e:101,XK_f:102,XK_g:103,XK_h:104,XK_i:105,XK_j:106,XK_k:107,XK_l:108,XK_m:109,XK_n:110,XK_o:111,XK_p:112,XK_q:113,XK_r:114,XK_s:115,XK_t:116,XK_u:117,XK_v:118,XK_w:119,XK_x:120,XK_y:121,XK_z:122,XK_braceleft:123,XK_bar:124,XK_braceright:125,XK_asciitilde:126,XK_nobreakspace:160,XK_exclamdown:161,XK_cent:162,XK_sterling:163,XK_currency:164,XK_yen:165,XK_brokenbar:166,XK_section:167,XK_diaeresis:168,XK_copyright:169,XK_ordfeminine:170,XK_guillemotleft:171,XK_notsign:172,XK_hyphen:173,XK_registered:174,XK_macron:175,XK_degree:176,XK_plusminus:177,XK_twosuperior:178,XK_threesuperior:179,XK_acute:180,XK_mu:181,XK_paragraph:182,XK_periodcentered:183,XK_cedilla:184,XK_onesuperior:185,XK_masculine:186,XK_guillemotright:187,XK_onequarter:188,XK_onehalf:189,XK_threequarters:190,XK_questiondown:191,XK_Agrave:192,XK_Aacute:193,XK_Acircumflex:194,XK_Atilde:195,XK_Adiaeresis:196,XK_Aring:197,XK_AE:198,XK_Ccedilla:199,XK_Egrave:200,XK_Eacute:201,XK_Ecircumflex:202,XK_Ediaeresis:203,XK_Igrave:204,XK_Iacute:205,XK_Icircumflex:206,XK_Idiaeresis:207,XK_ETH:208,XK_Eth:208,XK_Ntilde:209,XK_Ograve:210,XK_Oacute:211,XK_Ocircumflex:212,XK_Otilde:213,XK_Odiaeresis:214,XK_multiply:215,XK_Oslash:216,XK_Ooblique:216,XK_Ugrave:217,XK_Uacute:218,XK_Ucircumflex:219,XK_Udiaeresis:220,XK_Yacute:221,XK_THORN:222,XK_Thorn:222,XK_ssharp:223,XK_agrave:224,XK_aacute:225,XK_acircumflex:226,XK_atilde:227,XK_adiaeresis:228,XK_aring:229,XK_ae:230,XK_ccedilla:231,XK_egrave:232,XK_eacute:233,XK_ecircumflex:234,XK_ediaeresis:235,XK_igrave:236,XK_iacute:237,XK_icircumflex:238,XK_idiaeresis:239,XK_eth:240,XK_ntilde:241,XK_ograve:242,XK_oacute:243,XK_ocircumflex:244,XK_otilde:245,XK_odiaeresis:246,XK_division:247,XK_oslash:248,XK_ooblique:248,XK_ugrave:249,XK_uacute:250,XK_ucircumflex:251,XK_udiaeresis:252,XK_yacute:253,XK_thorn:254,XK_ydiaeresis:255,XK_Hangul:65329,XK_Hangul_Hanja:65332,XK_Hangul_Jeonja:65336,XF86XK_ModeLock:269025025,XF86XK_MonBrightnessUp:269025026,XF86XK_MonBrightnessDown:269025027,XF86XK_KbdLightOnOff:269025028,XF86XK_KbdBrightnessUp:269025029,XF86XK_KbdBrightnessDown:269025030,XF86XK_Standby:269025040,XF86XK_AudioLowerVolume:269025041,XF86XK_AudioMute:269025042,XF86XK_AudioRaiseVolume:269025043,XF86XK_AudioPlay:269025044,XF86XK_AudioStop:269025045,XF86XK_AudioPrev:269025046,XF86XK_AudioNext:269025047,XF86XK_HomePage:269025048,XF86XK_Mail:269025049,XF86XK_Start:269025050,XF86XK_Search:269025051,XF86XK_AudioRecord:269025052,XF86XK_Calculator:269025053,XF86XK_Memo:269025054,XF86XK_ToDoList:269025055,XF86XK_Calendar:269025056,XF86XK_PowerDown:269025057,XF86XK_ContrastAdjust:269025058,XF86XK_RockerUp:269025059,XF86XK_RockerDown:269025060,XF86XK_RockerEnter:269025061,XF86XK_Back:269025062,XF86XK_Forward:269025063,XF86XK_Stop:269025064,XF86XK_Refresh:269025065,XF86XK_PowerOff:269025066,XF86XK_WakeUp:269025067,XF86XK_Eject:269025068,XF86XK_ScreenSaver:269025069,XF86XK_WWW:269025070,XF86XK_Sleep:269025071,XF86XK_Favorites:269025072,XF86XK_AudioPause:269025073,XF86XK_AudioMedia:269025074,XF86XK_MyComputer:269025075,XF86XK_VendorHome:269025076,XF86XK_LightBulb:269025077,XF86XK_Shop:269025078,XF86XK_History:269025079,XF86XK_OpenURL:269025080,XF86XK_AddFavorite:269025081,XF86XK_HotLinks:269025082,XF86XK_BrightnessAdjust:269025083,XF86XK_Finance:269025084,XF86XK_Community:269025085,XF86XK_AudioRewind:269025086,XF86XK_BackForward:269025087,XF86XK_Launch0:269025088,XF86XK_Launch1:269025089,XF86XK_Launch2:269025090,XF86XK_Launch3:269025091,XF86XK_Launch4:269025092,XF86XK_Launch5:269025093,XF86XK_Launch6:269025094,XF86XK_Launch7:269025095,XF86XK_Launch8:269025096,XF86XK_Launch9:269025097,XF86XK_LaunchA:269025098,XF86XK_LaunchB:269025099,XF86XK_LaunchC:269025100,XF86XK_LaunchD:269025101,XF86XK_LaunchE:269025102,XF86XK_LaunchF:269025103,XF86XK_ApplicationLeft:269025104,XF86XK_ApplicationRight:269025105,XF86XK_Book:269025106,XF86XK_CD:269025107,XF86XK_Calculater:269025108,XF86XK_Clear:269025109,XF86XK_Close:269025110,XF86XK_Copy:269025111,XF86XK_Cut:269025112,XF86XK_Display:269025113,XF86XK_DOS:269025114,XF86XK_Documents:269025115,XF86XK_Excel:269025116,XF86XK_Explorer:269025117,XF86XK_Game:269025118,XF86XK_Go:269025119,XF86XK_iTouch:269025120,XF86XK_LogOff:269025121,XF86XK_Market:269025122,XF86XK_Meeting:269025123,XF86XK_MenuKB:269025125,XF86XK_MenuPB:269025126,XF86XK_MySites:269025127,XF86XK_New:269025128,XF86XK_News:269025129,XF86XK_OfficeHome:269025130,XF86XK_Open:269025131,XF86XK_Option:269025132,XF86XK_Paste:269025133,XF86XK_Phone:269025134,XF86XK_Q:269025136,XF86XK_Reply:269025138,XF86XK_Reload:269025139,XF86XK_RotateWindows:269025140,XF86XK_RotationPB:269025141,XF86XK_RotationKB:269025142,XF86XK_Save:269025143,XF86XK_ScrollUp:269025144,XF86XK_ScrollDown:269025145,XF86XK_ScrollClick:269025146,XF86XK_Send:269025147,XF86XK_Spell:269025148,XF86XK_SplitScreen:269025149,XF86XK_Support:269025150,XF86XK_TaskPane:269025151,XF86XK_Terminal:269025152,XF86XK_Tools:269025153,XF86XK_Travel:269025154,XF86XK_UserPB:269025156,XF86XK_User1KB:269025157,XF86XK_User2KB:269025158,XF86XK_Video:269025159,XF86XK_WheelButton:269025160,XF86XK_Word:269025161,XF86XK_Xfer:269025162,XF86XK_ZoomIn:269025163,XF86XK_ZoomOut:269025164,XF86XK_Away:269025165,XF86XK_Messenger:269025166,XF86XK_WebCam:269025167,XF86XK_MailForward:269025168,XF86XK_Pictures:269025169,XF86XK_Music:269025170,XF86XK_Battery:269025171,XF86XK_Bluetooth:269025172,XF86XK_WLAN:269025173,XF86XK_UWB:269025174,XF86XK_AudioForward:269025175,XF86XK_AudioRepeat:269025176,XF86XK_AudioRandomPlay:269025177,XF86XK_Subtitle:269025178,XF86XK_AudioCycleTrack:269025179,XF86XK_CycleAngle:269025180,XF86XK_FrameBack:269025181,XF86XK_FrameForward:269025182,XF86XK_Time:269025183,XF86XK_Select:269025184,XF86XK_View:269025185,XF86XK_TopMenu:269025186,XF86XK_Red:269025187,XF86XK_Green:269025188,XF86XK_Yellow:269025189,XF86XK_Blue:269025190,XF86XK_Suspend:269025191,XF86XK_Hibernate:269025192,XF86XK_TouchpadToggle:269025193,XF86XK_TouchpadOn:269025200,XF86XK_TouchpadOff:269025201,XF86XK_AudioMicMute:269025202,XF86XK_Switch_VT_1:269024769,XF86XK_Switch_VT_2:269024770,XF86XK_Switch_VT_3:269024771,XF86XK_Switch_VT_4:269024772,XF86XK_Switch_VT_5:269024773,XF86XK_Switch_VT_6:269024774,XF86XK_Switch_VT_7:269024775,XF86XK_Switch_VT_8:269024776,XF86XK_Switch_VT_9:269024777,XF86XK_Switch_VT_10:269024778,XF86XK_Switch_VT_11:269024779,XF86XK_Switch_VT_12:269024780,XF86XK_Ungrab:269024800,XF86XK_ClearGrab:269024801,XF86XK_Next_VMode:269024802,XF86XK_Prev_VMode:269024803,XF86XK_LogWindowTree:269024804,XF86XK_LogGrabInfo:269024805};var t$={256:960,257:992,258:451,259:483,260:417,261:433,262:454,263:486,264:710,265:742,266:709,267:741,268:456,269:488,270:463,271:495,272:464,273:496,274:938,275:954,278:972,279:1004,280:458,281:490,282:460,283:492,284:728,285:760,286:683,287:699,288:725,289:757,290:939,291:955,292:678,293:694,294:673,295:689,296:933,297:949,298:975,299:1007,302:967,303:999,304:681,305:697,308:684,309:700,310:979,311:1011,312:930,313:453,314:485,315:934,316:950,317:421,318:437,321:419,322:435,323:465,324:497,325:977,326:1009,327:466,328:498,330:957,331:959,332:978,333:1010,336:469,337:501,338:5052,339:5053,340:448,341:480,342:931,343:947,344:472,345:504,346:422,347:438,348:734,349:766,350:426,351:442,352:425,353:441,354:478,355:510,356:427,357:443,358:940,359:956,360:989,361:1021,362:990,363:1022,364:733,365:765,366:473,367:505,368:475,369:507,370:985,371:1017,376:5054,377:428,378:444,379:431,380:447,381:430,382:446,402:2294,466:16777681,711:439,728:418,729:511,731:434,733:445,901:1966,902:1953,904:1954,905:1955,906:1956,908:1959,910:1960,911:1963,912:1974,913:1985,914:1986,915:1987,916:1988,917:1989,918:1990,919:1991,920:1992,921:1993,922:1994,923:1995,924:1996,925:1997,926:1998,927:1999,928:2e3,929:2001,931:2002,932:2004,933:2005,934:2006,935:2007,936:2008,937:2009,938:1957,939:1961,940:1969,941:1970,942:1971,943:1972,944:1978,945:2017,946:2018,947:2019,948:2020,949:2021,950:2022,951:2023,952:2024,953:2025,954:2026,955:2027,956:2028,957:2029,958:2030,959:2031,960:2032,961:2033,962:2035,963:2034,964:2036,965:2037,966:2038,967:2039,968:2040,969:2041,970:1973,971:1977,972:1975,973:1976,974:1979,1025:1715,1026:1713,1027:1714,1028:1716,1029:1717,1030:1718,1031:1719,1032:1720,1033:1721,1034:1722,1035:1723,1036:1724,1038:1726,1039:1727,1040:1761,1041:1762,1042:1783,1043:1767,1044:1764,1045:1765,1046:1782,1047:1786,1048:1769,1049:1770,1050:1771,1051:1772,1052:1773,1053:1774,1054:1775,1055:1776,1056:1778,1057:1779,1058:1780,1059:1781,1060:1766,1061:1768,1062:1763,1063:1790,1064:1787,1065:1789,1066:1791,1067:1785,1068:1784,1069:1788,1070:1760,1071:1777,1072:1729,1073:1730,1074:1751,1075:1735,1076:1732,1077:1733,1078:1750,1079:1754,1080:1737,1081:1738,1082:1739,1083:1740,1084:1741,1085:1742,1086:1743,1087:1744,1088:1746,1089:1747,1090:1748,1091:1749,1092:1734,1093:1736,1094:1731,1095:1758,1096:1755,1097:1757,1098:1759,1099:1753,1100:1752,1101:1756,1102:1728,1103:1745,1105:1699,1106:1697,1107:1698,1108:1700,1109:1701,1110:1702,1111:1703,1112:1704,1113:1705,1114:1706,1115:1707,1116:1708,1118:1710,1119:1711,1168:1725,1169:1709,1488:3296,1489:3297,1490:3298,1491:3299,1492:3300,1493:3301,1494:3302,1495:3303,1496:3304,1497:3305,1498:3306,1499:3307,1500:3308,1501:3309,1502:3310,1503:3311,1504:3312,1505:3313,1506:3314,1507:3315,1508:3316,1509:3317,1510:3318,1511:3319,1512:3320,1513:3321,1514:3322,1548:1452,1563:1467,1567:1471,1569:1473,1570:1474,1571:1475,1572:1476,1573:1477,1574:1478,1575:1479,1576:1480,1577:1481,1578:1482,1579:1483,1580:1484,1581:1485,1582:1486,1583:1487,1584:1488,1585:1489,1586:1490,1587:1491,1588:1492,1589:1493,1590:1494,1591:1495,1592:1496,1593:1497,1594:1498,1600:1504,1601:1505,1602:1506,1603:1507,1604:1508,1605:1509,1606:1510,1607:1511,1608:1512,1609:1513,1610:1514,1611:1515,1612:1516,1613:1517,1614:1518,1615:1519,1616:1520,1617:1521,1618:1522,3585:3489,3586:3490,3587:3491,3588:3492,3589:3493,3590:3494,3591:3495,3592:3496,3593:3497,3594:3498,3595:3499,3596:3500,3597:3501,3598:3502,3599:3503,3600:3504,3601:3505,3602:3506,3603:3507,3604:3508,3605:3509,3606:3510,3607:3511,3608:3512,3609:3513,3610:3514,3611:3515,3612:3516,3613:3517,3614:3518,3615:3519,3616:3520,3617:3521,3618:3522,3619:3523,3620:3524,3621:3525,3622:3526,3623:3527,3624:3528,3625:3529,3626:3530,3627:3531,3628:3532,3629:3533,3630:3534,3631:3535,3632:3536,3633:3537,3634:3538,3635:3539,3636:3540,3637:3541,3638:3542,3639:3543,3640:3544,3641:3545,3642:3546,3647:3551,3648:3552,3649:3553,3650:3554,3651:3555,3652:3556,3653:3557,3654:3558,3655:3559,3656:3560,3657:3561,3658:3562,3659:3563,3660:3564,3661:3565,3664:3568,3665:3569,3666:3570,3667:3571,3668:3572,3669:3573,3670:3574,3671:3575,3672:3576,3673:3577,8194:2722,8195:2721,8196:2723,8197:2724,8199:2725,8200:2726,8201:2727,8202:2728,8210:2747,8211:2730,8212:2729,8213:1967,8215:3295,8216:2768,8217:2769,8218:2813,8220:2770,8221:2771,8222:2814,8224:2801,8225:2802,8226:2790,8229:2735,8230:2734,8240:2773,8242:2774,8243:2775,8248:2812,8254:1150,8361:3839,8364:8364,8453:2744,8470:1712,8471:2811,8478:2772,8482:2761,8531:2736,8532:2737,8533:2738,8534:2739,8535:2740,8536:2741,8537:2742,8538:2743,8539:2755,8540:2756,8541:2757,8542:2758,8592:2299,8593:2300,8594:2301,8595:2302,8658:2254,8660:2253,8706:2287,8711:2245,8728:3018,8730:2262,8733:2241,8734:2242,8743:2270,8744:2271,8745:2268,8746:2269,8747:2239,8756:2240,8764:2248,8771:2249,8773:16785992,8800:2237,8801:2255,8804:2236,8805:2238,8834:2266,8835:2267,8866:3068,8867:3036,8868:3010,8869:3022,8968:3027,8970:3012,8981:2810,8992:2212,8993:2213,9109:3020,9115:2219,9117:2220,9118:2221,9120:2222,9121:2215,9123:2216,9124:2217,9126:2218,9128:2223,9132:2224,9143:2209,9146:2543,9147:2544,9148:2546,9149:2547,9225:2530,9226:2533,9227:2537,9228:2531,9229:2532,9251:2732,9252:2536,9472:2211,9474:2214,9484:2210,9488:2539,9492:2541,9496:2538,9500:2548,9508:2549,9516:2551,9524:2550,9532:2542,9618:2529,9642:2791,9643:2785,9644:2779,9645:2786,9646:2783,9647:2767,9650:2792,9651:2787,9654:2781,9655:2765,9660:2793,9661:2788,9664:2780,9665:2764,9670:2528,9675:2766,9679:2782,9702:2784,9734:2789,9742:2809,9747:2762,9756:2794,9758:2795,9792:2808,9794:2807,9827:2796,9829:2798,9830:2797,9837:2806,9839:2805,10003:2803,10007:2804,10013:2777,10016:2800,10216:2748,10217:2750,12289:1188,12290:1185,12300:1186,12301:1187,12443:1246,12444:1247,12449:1191,12450:1201,12451:1192,12452:1202,12453:1193,12454:1203,12455:1194,12456:1204,12457:1195,12458:1205,12459:1206,12461:1207,12463:1208,12465:1209,12467:1210,12469:1211,12471:1212,12473:1213,12475:1214,12477:1215,12479:1216,12481:1217,12483:1199,12484:1218,12486:1219,12488:1220,12490:1221,12491:1222,12492:1223,12493:1224,12494:1225,12495:1226,12498:1227,12501:1228,12504:1229,12507:1230,12510:1231,12511:1232,12512:1233,12513:1234,12514:1235,12515:1196,12516:1236,12517:1197,12518:1237,12519:1198,12520:1238,12521:1239,12522:1240,12523:1241,12524:1242,12525:1243,12527:1244,12530:1190,12531:1245,12539:1189,12540:1200},Iw={lookup(e){if(e>=32&&e<=255)return e;let t=t$[e];return t!==void 0?t:16777216|e}};var dh={8:"Backspace",9:"Tab",10:"NumpadClear",13:"Enter",16:"ShiftLeft",17:"ControlLeft",18:"AltLeft",19:"Pause",20:"CapsLock",21:"Lang1",25:"Lang2",27:"Escape",28:"Convert",29:"NonConvert",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",41:"Select",44:"PrintScreen",45:"Insert",46:"Delete",47:"Help",48:"Digit0",49:"Digit1",50:"Digit2",51:"Digit3",52:"Digit4",53:"Digit5",54:"Digit6",55:"Digit7",56:"Digit8",57:"Digit9",91:"MetaLeft",92:"MetaRight",93:"ContextMenu",95:"Sleep",96:"Numpad0",97:"Numpad1",98:"Numpad2",99:"Numpad3",100:"Numpad4",101:"Numpad5",102:"Numpad6",103:"Numpad7",104:"Numpad8",105:"Numpad9",106:"NumpadMultiply",107:"NumpadAdd",108:"NumpadDecimal",109:"NumpadSubtract",110:"NumpadDecimal",111:"NumpadDivide",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",124:"F13",125:"F14",126:"F15",127:"F16",128:"F17",129:"F18",130:"F19",131:"F20",132:"F21",133:"F22",134:"F23",135:"F24",144:"NumLock",145:"ScrollLock",166:"BrowserBack",167:"BrowserForward",168:"BrowserRefresh",169:"BrowserStop",170:"BrowserSearch",171:"BrowserFavorites",172:"BrowserHome",173:"AudioVolumeMute",174:"AudioVolumeDown",175:"AudioVolumeUp",176:"MediaTrackNext",177:"MediaTrackPrevious",178:"MediaStop",179:"MediaPlayPause",180:"LaunchMail",181:"MediaSelect",182:"LaunchApp1",183:"LaunchApp2",225:"AltRight"};var ph={Backspace:"Backspace",AltLeft:"Alt",AltRight:"Alt",CapsLock:"CapsLock",ContextMenu:"ContextMenu",ControlLeft:"Control",ControlRight:"Control",Enter:"Enter",MetaLeft:"Meta",MetaRight:"Meta",ShiftLeft:"Shift",ShiftRight:"Shift",Tab:"Tab",Delete:"Delete",End:"End",Help:"Help",Home:"Home",Insert:"Insert",PageDown:"PageDown",PageUp:"PageUp",ArrowDown:"ArrowDown",ArrowLeft:"ArrowLeft",ArrowRight:"ArrowRight",ArrowUp:"ArrowUp",NumLock:"NumLock",NumpadBackspace:"Backspace",NumpadClear:"Clear",Escape:"Escape",F1:"F1",F2:"F2",F3:"F3",F4:"F4",F5:"F5",F6:"F6",F7:"F7",F8:"F8",F9:"F9",F10:"F10",F11:"F11",F12:"F12",F13:"F13",F14:"F14",F15:"F15",F16:"F16",F17:"F17",F18:"F18",F19:"F19",F20:"F20",F21:"F21",F22:"F22",F23:"F23",F24:"F24",F25:"F25",F26:"F26",F27:"F27",F28:"F28",F29:"F29",F30:"F30",F31:"F31",F32:"F32",F33:"F33",F34:"F34",F35:"F35",PrintScreen:"PrintScreen",ScrollLock:"ScrollLock",Pause:"Pause",BrowserBack:"BrowserBack",BrowserFavorites:"BrowserFavorites",BrowserForward:"BrowserForward",BrowserHome:"BrowserHome",BrowserRefresh:"BrowserRefresh",BrowserSearch:"BrowserSearch",BrowserStop:"BrowserStop",Eject:"Eject",LaunchApp1:"LaunchMyComputer",LaunchApp2:"LaunchCalendar",LaunchMail:"LaunchMail",MediaPlayPause:"MediaPlay",MediaStop:"MediaStop",MediaTrackNext:"MediaTrackNext",MediaTrackPrevious:"MediaTrackPrevious",Power:"Power",Sleep:"Sleep",AudioVolumeDown:"AudioVolumeDown",AudioVolumeMute:"AudioVolumeMute",AudioVolumeUp:"AudioVolumeUp",WakeUp:"WakeUp"};var Br={};function X(e,t){if(t===void 0)throw new Error('Undefined keysym for key "'+e+'"');if(e in Br)throw new Error('Duplicate entry for key "'+e+'"');Br[e]=[t,t,t,t]}function yc(e,t,n){if(t===void 0)throw new Error('Undefined keysym for key "'+e+'"');if(n===void 0)throw new Error('Undefined keysym for key "'+e+'"');if(e in Br)throw new Error('Duplicate entry for key "'+e+'"');Br[e]=[t,t,n,t]}function Ce(e,t,n){if(t===void 0)throw new Error('Undefined keysym for key "'+e+'"');if(n===void 0)throw new Error('Undefined keysym for key "'+e+'"');if(e in Br)throw new Error('Duplicate entry for key "'+e+'"');Br[e]=[t,t,t,n]}yc("Alt",A.XK_Alt_L,A.XK_Alt_R);X("AltGraph",A.XK_ISO_Level3_Shift);X("CapsLock",A.XK_Caps_Lock);yc("Control",A.XK_Control_L,A.XK_Control_R);yc("Meta",A.XK_Super_L,A.XK_Super_R);X("NumLock",A.XK_Num_Lock);X("ScrollLock",A.XK_Scroll_Lock);yc("Shift",A.XK_Shift_L,A.XK_Shift_R);Ce("Enter",A.XK_Return,A.XK_KP_Enter);X("Tab",A.XK_Tab);Ce(" ",A.XK_space,A.XK_KP_Space);Ce("ArrowDown",A.XK_Down,A.XK_KP_Down);Ce("ArrowLeft",A.XK_Left,A.XK_KP_Left);Ce("ArrowRight",A.XK_Right,A.XK_KP_Right);Ce("ArrowUp",A.XK_Up,A.XK_KP_Up);Ce("End",A.XK_End,A.XK_KP_End);Ce("Home",A.XK_Home,A.XK_KP_Home);Ce("PageDown",A.XK_Next,A.XK_KP_Next);Ce("PageUp",A.XK_Prior,A.XK_KP_Prior);X("Backspace",A.XK_BackSpace);Ce("Clear",A.XK_Clear,A.XK_KP_Begin);X("Copy",A.XF86XK_Copy);X("Cut",A.XF86XK_Cut);Ce("Delete",A.XK_Delete,A.XK_KP_Delete);Ce("Insert",A.XK_Insert,A.XK_KP_Insert);X("Paste",A.XF86XK_Paste);X("Redo",A.XK_Redo);X("Undo",A.XK_Undo);X("Cancel",A.XK_Cancel);X("ContextMenu",A.XK_Menu);X("Escape",A.XK_Escape);X("Execute",A.XK_Execute);X("Find",A.XK_Find);X("Help",A.XK_Help);X("Pause",A.XK_Pause);X("Select",A.XK_Select);X("ZoomIn",A.XF86XK_ZoomIn);X("ZoomOut",A.XF86XK_ZoomOut);X("BrightnessDown",A.XF86XK_MonBrightnessDown);X("BrightnessUp",A.XF86XK_MonBrightnessUp);X("Eject",A.XF86XK_Eject);X("LogOff",A.XF86XK_LogOff);X("Power",A.XF86XK_PowerOff);X("PowerOff",A.XF86XK_PowerDown);X("PrintScreen",A.XK_Print);X("Hibernate",A.XF86XK_Hibernate);X("Standby",A.XF86XK_Standby);X("WakeUp",A.XF86XK_WakeUp);X("AllCandidates",A.XK_MultipleCandidate);X("Alphanumeric",A.XK_Eisu_toggle);X("CodeInput",A.XK_Codeinput);X("Compose",A.XK_Multi_key);X("Convert",A.XK_Henkan);X("GroupFirst",A.XK_ISO_First_Group);X("GroupLast",A.XK_ISO_Last_Group);X("GroupNext",A.XK_ISO_Next_Group);X("GroupPrevious",A.XK_ISO_Prev_Group);X("NonConvert",A.XK_Muhenkan);X("PreviousCandidate",A.XK_PreviousCandidate);X("SingleCandidate",A.XK_SingleCandidate);X("HangulMode",A.XK_Hangul);X("HanjaMode",A.XK_Hangul_Hanja);X("JunjaMode",A.XK_Hangul_Jeonja);X("Eisu",A.XK_Eisu_toggle);X("Hankaku",A.XK_Hankaku);X("Hiragana",A.XK_Hiragana);X("HiraganaKatakana",A.XK_Hiragana_Katakana);X("KanaMode",A.XK_Kana_Shift);X("KanjiMode",A.XK_Kanji);X("Katakana",A.XK_Katakana);X("Romaji",A.XK_Romaji);X("Zenkaku",A.XK_Zenkaku);X("ZenkakuHankaku",A.XK_Zenkaku_Hankaku);X("F1",A.XK_F1);X("F2",A.XK_F2);X("F3",A.XK_F3);X("F4",A.XK_F4);X("F5",A.XK_F5);X("F6",A.XK_F6);X("F7",A.XK_F7);X("F8",A.XK_F8);X("F9",A.XK_F9);X("F10",A.XK_F10);X("F11",A.XK_F11);X("F12",A.XK_F12);X("F13",A.XK_F13);X("F14",A.XK_F14);X("F15",A.XK_F15);X("F16",A.XK_F16);X("F17",A.XK_F17);X("F18",A.XK_F18);X("F19",A.XK_F19);X("F20",A.XK_F20);X("F21",A.XK_F21);X("F22",A.XK_F22);X("F23",A.XK_F23);X("F24",A.XK_F24);X("F25",A.XK_F25);X("F26",A.XK_F26);X("F27",A.XK_F27);X("F28",A.XK_F28);X("F29",A.XK_F29);X("F30",A.XK_F30);X("F31",A.XK_F31);X("F32",A.XK_F32);X("F33",A.XK_F33);X("F34",A.XK_F34);X("F35",A.XK_F35);X("Close",A.XF86XK_Close);X("MailForward",A.XF86XK_MailForward);X("MailReply",A.XF86XK_Reply);X("MailSend",A.XF86XK_Send);X("MediaFastForward",A.XF86XK_AudioForward);X("MediaPause",A.XF86XK_AudioPause);X("MediaPlay",A.XF86XK_AudioPlay);X("MediaRecord",A.XF86XK_AudioRecord);X("MediaRewind",A.XF86XK_AudioRewind);X("MediaStop",A.XF86XK_AudioStop);X("MediaTrackNext",A.XF86XK_AudioNext);X("MediaTrackPrevious",A.XF86XK_AudioPrev);X("New",A.XF86XK_New);X("Open",A.XF86XK_Open);X("Print",A.XK_Print);X("Save",A.XF86XK_Save);X("SpellCheck",A.XF86XK_Spell);X("AudioVolumeDown",A.XF86XK_AudioLowerVolume);X("AudioVolumeUp",A.XF86XK_AudioRaiseVolume);X("AudioVolumeMute",A.XF86XK_AudioMute);X("MicrophoneVolumeMute",A.XF86XK_AudioMicMute);X("LaunchApplication1",A.XF86XK_MyComputer);X("LaunchApplication2",A.XF86XK_Calculator);X("LaunchCalendar",A.XF86XK_Calendar);X("LaunchMail",A.XF86XK_Mail);X("LaunchMediaPlayer",A.XF86XK_AudioMedia);X("LaunchMusicPlayer",A.XF86XK_Music);X("LaunchPhone",A.XF86XK_Phone);X("LaunchScreenSaver",A.XF86XK_ScreenSaver);X("LaunchSpreadsheet",A.XF86XK_Excel);X("LaunchWebBrowser",A.XF86XK_WWW);X("LaunchWebCam",A.XF86XK_WebCam);X("LaunchWordProcessor",A.XF86XK_Word);X("BrowserBack",A.XF86XK_Back);X("BrowserFavorites",A.XF86XK_Favorites);X("BrowserForward",A.XF86XK_Forward);X("BrowserHome",A.XF86XK_HomePage);X("BrowserRefresh",A.XF86XK_Refresh);X("BrowserSearch",A.XF86XK_Search);X("BrowserStop",A.XF86XK_Stop);X("Dimmer",A.XF86XK_BrightnessAdjust);X("MediaAudioTrack",A.XF86XK_AudioCycleTrack);X("RandomToggle",A.XF86XK_AudioRandomPlay);X("SplitScreenToggle",A.XF86XK_SplitScreen);X("Subtitle",A.XF86XK_Subtitle);X("VideoModeNext",A.XF86XK_Next_VMode);Ce("=",A.XK_equal,A.XK_KP_Equal);Ce("+",A.XK_plus,A.XK_KP_Add);Ce("-",A.XK_minus,A.XK_KP_Subtract);Ce("*",A.XK_asterisk,A.XK_KP_Multiply);Ce("/",A.XK_slash,A.XK_KP_Divide);Ce(".",A.XK_period,A.XK_KP_Decimal);Ce(",",A.XK_comma,A.XK_KP_Separator);Ce("0",A.XK_0,A.XK_KP_0);Ce("1",A.XK_1,A.XK_KP_1);Ce("2",A.XK_2,A.XK_KP_2);Ce("3",A.XK_3,A.XK_KP_3);Ce("4",A.XK_4,A.XK_KP_4);Ce("5",A.XK_5,A.XK_KP_5);Ce("6",A.XK_6,A.XK_KP_6);Ce("7",A.XK_7,A.XK_KP_7);Ce("8",A.XK_8,A.XK_KP_8);Ce("9",A.XK_9,A.XK_KP_9);var fh=Br;function jo(e){if(e.code){switch(e.code){case"OSLeft":return"MetaLeft";case"OSRight":return"MetaRight"}return e.code}if(e.keyCode in dh){let t=dh[e.keyCode];if(Jn()&&t==="ContextMenu"&&(t="MetaRight"),e.location===2)switch(t){case"ShiftLeft":return"ShiftRight";case"ControlLeft":return"ControlRight";case"AltLeft":return"AltRight"}if(e.location===3)switch(t){case"Delete":return"NumpadDecimal";case"Insert":return"Numpad0";case"End":return"Numpad1";case"ArrowDown":return"Numpad2";case"PageDown":return"Numpad3";case"ArrowLeft":return"Numpad4";case"ArrowRight":return"Numpad6";case"Home":return"Numpad7";case"ArrowUp":return"Numpad8";case"PageUp":return"Numpad9";case"Enter":return"NumpadEnter"}return t}return"Unidentified"}function n$(e){if(e.key!==void 0&&e.key!=="Unidentified"){switch(e.key){case"OS":return"Meta";case"LaunchMyComputer":return"LaunchApplication1";case"LaunchCalculator":return"LaunchApplication2"}switch(e.key){case"UIKeyInputUpArrow":return"ArrowUp";case"UIKeyInputDownArrow":return"ArrowDown";case"UIKeyInputLeftArrow":return"ArrowLeft";case"UIKeyInputRightArrow":return"ArrowRight";case"UIKeyInputEscape":return"Escape"}return e.key==="\0"&&e.code==="NumpadDecimal"?"Delete":e.key}let t=jo(e);return t in ph?ph[t]:e.charCode?String.fromCharCode(e.charCode):"Unidentified"}function Pw(e){let t=n$(e);if(t==="Unidentified")return null;if(t in fh){let r=e.location;if(t==="Meta"&&r===0&&(r=2),t==="Clear"&&r===3&&jo(e)==="NumLock"&&(r=0),(r===void 0||r>3)&&(r=0),t==="Meta"){let o=jo(e);if(o==="AltLeft")return A.XK_Meta_L;if(o==="AltRight")return A.XK_Meta_R}if(t==="Clear"&&jo(e)==="NumLock")return A.XK_Num_Lock;if(Lo())switch(t){case"Zenkaku":case"Hankaku":return A.XK_Zenkaku_Hankaku;case"Romaji":case"KanaMode":return A.XK_Romaji}return fh[t][r]}if(t.length!==1)return null;let n=t.charCodeAt();return n?Iw.lookup(n):null}var Vi=class{constructor(t){this._target=t||null,this._keyDownList={},this._altGrArmed=!1,this._eventHandlers={keyup:this._handleKeyUp.bind(this),keydown:this._handleKeyDown.bind(this),blur:this._allKeysUp.bind(this)},this.onkeyevent=()=>{}}_sendKeyEvent(t,n,r,o=null,s=null){if(r)this._keyDownList[n]=t;else{if(!(n in this._keyDownList))return;delete this._keyDownList[n]}de("onkeyevent "+(r?"down":"up")+", keysym: "+t,", code: "+n+", numlock: "+o+", capslock: "+s),this.onkeyevent(t,n,r,o,s)}_getKeyCode(t){let n=jo(t);if(n!=="Unidentified")return n;if(t.keyCode&&t.keyCode!==229)return"Platform"+t.keyCode;if(t.keyIdentifier){if(t.keyIdentifier.substr(0,2)!=="U+")return t.keyIdentifier;let r=parseInt(t.keyIdentifier.substr(2),16);return"Platform"+String.fromCharCode(r).toUpperCase().charCodeAt()}return"Unidentified"}_handleKeyDown(t){let n=this._getKeyCode(t),r=Pw(t),o=t.getModifierState("NumLock"),s=t.getModifierState("CapsLock");if((Jn()||Mo())&&(o=null),this._altGrArmed&&(this._altGrArmed=!1,clearTimeout(this._altGrTimeout),n==="AltRight"&&t.timeStamp-this._altGrCtrlTime<50?r=A.XK_ISO_Level3_Shift:this._sendKeyEvent(A.XK_Control_L,"ControlLeft",!0,o,s)),n==="Unidentified"){r&&(this._sendKeyEvent(r,n,!0,o,s),this._sendKeyEvent(r,n,!1,o,s)),Pr(t);return}if(Jn()||Mo())switch(r){case A.XK_Super_L:r=A.XK_Alt_L;break;case A.XK_Super_R:r=A.XK_Super_L;break;case A.XK_Alt_L:r=A.XK_Mode_switch;break;case A.XK_Alt_R:r=A.XK_ISO_Level3_Shift;break}if(n in this._keyDownList&&(r=this._keyDownList[n]),(Jn()||Mo())&&t.metaKey&&n!=="MetaLeft"&&n!=="MetaRight"){this._sendKeyEvent(r,n,!0,o,s),this._sendKeyEvent(r,n,!1,o,s),Pr(t);return}if((Jn()||Mo())&&n==="CapsLock"){this._sendKeyEvent(A.XK_Caps_Lock,"CapsLock",!0,o,s),this._sendKeyEvent(A.XK_Caps_Lock,"CapsLock",!1,o,s),Pr(t);return}let i=[A.XK_Zenkaku_Hankaku,A.XK_Eisu_toggle,A.XK_Katakana,A.XK_Hiragana,A.XK_Romaji];if(Lo()&&i.includes(r)){this._sendKeyEvent(r,n,!0,o,s),this._sendKeyEvent(r,n,!1,o,s),Pr(t);return}if(Pr(t),n==="ControlLeft"&&Lo()&&!("ControlLeft"in this._keyDownList)){this._altGrArmed=!0,this._altGrTimeout=setTimeout(this._interruptAltGrSequence.bind(this),100),this._altGrCtrlTime=t.timeStamp;return}this._sendKeyEvent(r,n,!0,o,s)}_handleKeyUp(t){Pr(t);let n=this._getKeyCode(t);if(this._interruptAltGrSequence(),(Jn()||Mo())&&n==="CapsLock"){this._sendKeyEvent(A.XK_Caps_Lock,"CapsLock",!0),this._sendKeyEvent(A.XK_Caps_Lock,"CapsLock",!1);return}this._sendKeyEvent(this._keyDownList[n],n,!1),Lo()&&(n==="ShiftLeft"||n==="ShiftRight")&&("ShiftRight"in this._keyDownList&&this._sendKeyEvent(this._keyDownList.ShiftRight,"ShiftRight",!1),"ShiftLeft"in this._keyDownList&&this._sendKeyEvent(this._keyDownList.ShiftLeft,"ShiftLeft",!1))}_interruptAltGrSequence(){this._altGrArmed&&(this._altGrArmed=!1,clearTimeout(this._altGrTimeout),this._sendKeyEvent(A.XK_Control_L,"ControlLeft",!0))}_allKeysUp(){de(">> Keyboard.allKeysUp"),this._interruptAltGrSequence();for(let t in this._keyDownList)this._sendKeyEvent(this._keyDownList[t],t,!1);de("<< Keyboard.allKeysUp")}grab(){this._target.addEventListener("keydown",this._eventHandlers.keydown),this._target.addEventListener("keyup",this._eventHandlers.keyup),window.addEventListener("blur",this._eventHandlers.blur)}ungrab(){this._target.removeEventListener("keydown",this._eventHandlers.keydown),this._target.removeEventListener("keyup",this._eventHandlers.keyup),window.removeEventListener("blur",this._eventHandlers.blur),this._allKeysUp()}};var Zi=class{constructor(){this._target=null,this._state=127,this._tracked=[],this._ignored=[],this._waitingRelease=!1,this._releaseStart=0,this._longpressTimeoutId=null,this._twoTouchTimeoutId=null,this._boundEventHandler=this._eventHandler.bind(this)}attach(t){this.detach(),this._target=t,this._target.addEventListener("touchstart",this._boundEventHandler),this._target.addEventListener("touchmove",this._boundEventHandler),this._target.addEventListener("touchend",this._boundEventHandler),this._target.addEventListener("touchcancel",this._boundEventHandler)}detach(){this._target&&(this._stopLongpressTimeout(),this._stopTwoTouchTimeout(),this._target.removeEventListener("touchstart",this._boundEventHandler),this._target.removeEventListener("touchmove",this._boundEventHandler),this._target.removeEventListener("touchend",this._boundEventHandler),this._target.removeEventListener("touchcancel",this._boundEventHandler),this._target=null)}_eventHandler(t){let n;switch(t.stopPropagation(),t.preventDefault(),t.type){case"touchstart":n=this._touchStart;break;case"touchmove":n=this._touchMove;break;case"touchend":case"touchcancel":n=this._touchEnd;break}for(let r=0;r<t.changedTouches.length;r++){let o=t.changedTouches[r];n.call(this,o.identifier,o.clientX,o.clientY)}}_touchStart(t,n,r){if(this._hasDetectedGesture()||this._state===0){this._ignored.push(t);return}if(this._tracked.length>0&&Date.now()-this._tracked[0].started>250){this._state=0,this._ignored.push(t);return}if(this._waitingRelease){this._state=0,this._ignored.push(t);return}switch(this._tracked.push({id:t,started:Date.now(),active:!0,firstX:n,firstY:r,lastX:n,lastY:r,angle:0}),this._tracked.length){case 1:this._startLongpressTimeout();break;case 2:this._state&=-26,this._stopLongpressTimeout();break;case 3:this._state&=-99;break;default:this._state=0}}_touchMove(t,n,r){let o=this._tracked.find(a=>a.id===t);if(o===void 0)return;o.lastX=n,o.lastY=r;let s=n-o.firstX,i=r-o.firstY;if((o.firstX!==o.lastX||o.firstY!==o.lastY)&&(o.angle=Math.atan2(i,s)*180/Math.PI),!this._hasDetectedGesture()){if(Math.hypot(s,i)<50)return;if(this._state&=-24,this._stopLongpressTimeout(),this._tracked.length!==1&&(this._state&=-9),this._tracked.length!==2&&(this._state&=-97),this._tracked.length===2){let a=this._tracked.find(c=>c.id!==t);if(Math.hypot(a.firstX-a.lastX,a.firstY-a.lastY)>50){let c=Math.abs(o.angle-a.angle);c=Math.abs((c+180)%360-180),c>90?this._state&=-33:this._state&=-65,this._isTwoTouchTimeoutRunning()&&this._stopTwoTouchTimeout()}else this._isTwoTouchTimeoutRunning()||this._startTwoTouchTimeout()}if(!this._hasDetectedGesture())return;this._pushEvent("gesturestart")}this._pushEvent("gesturemove")}_touchEnd(t,n,r){if(this._ignored.indexOf(t)!==-1){this._ignored.splice(this._ignored.indexOf(t),1),this._ignored.length===0&&this._tracked.length===0&&(this._state=127,this._waitingRelease=!1);return}if(!this._hasDetectedGesture()&&this._isTwoTouchTimeoutRunning()&&(this._stopTwoTouchTimeout(),this._state=0),!this._hasDetectedGesture()&&(this._state&=-105,this._state&=-17,this._stopLongpressTimeout(),!this._waitingRelease))switch(this._releaseStart=Date.now(),this._waitingRelease=!0,this._tracked.length){case 1:this._state&=-7;break;case 2:this._state&=-6;break}if(this._waitingRelease){Date.now()-this._releaseStart>250&&(this._state=0),this._tracked.some(s=>Date.now()-s.started>1e3)&&(this._state=0);let o=this._tracked.find(s=>s.id===t);if(o.active=!1,this._hasDetectedGesture())this._pushEvent("gesturestart");else if(this._state!==0)return}this._hasDetectedGesture()&&this._pushEvent("gestureend");for(let o=0;o<this._tracked.length;o++)this._tracked[o].active&&this._ignored.push(this._tracked[o].id);this._tracked=[],this._state=0,this._ignored.indexOf(t)!==-1&&this._ignored.splice(this._ignored.indexOf(t),1),this._ignored.length===0&&(this._state=127,this._waitingRelease=!1)}_hasDetectedGesture(){return!(this._state===0||this._state&this._state-1||this._state&7&&this._tracked.some(t=>t.active))}_startLongpressTimeout(){this._stopLongpressTimeout(),this._longpressTimeoutId=setTimeout(()=>this._longpressTimeout(),1e3)}_stopLongpressTimeout(){clearTimeout(this._longpressTimeoutId),this._longpressTimeoutId=null}_longpressTimeout(){if(this._hasDetectedGesture())throw new Error("A longpress gesture failed, conflict with a different gesture");this._state=16,this._pushEvent("gesturestart")}_startTwoTouchTimeout(){this._stopTwoTouchTimeout(),this._twoTouchTimeoutId=setTimeout(()=>this._twoTouchTimeout(),50)}_stopTwoTouchTimeout(){clearTimeout(this._twoTouchTimeoutId),this._twoTouchTimeoutId=null}_isTwoTouchTimeoutRunning(){return this._twoTouchTimeoutId!==null}_twoTouchTimeout(){if(this._tracked.length===0)throw new Error("A pinch or two drag gesture failed, no tracked touches");let t=this._getAverageMovement(),n=Math.abs(t.x),r=Math.abs(t.y),o=this._getAverageDistance(),s=Math.abs(Math.hypot(o.first.x,o.first.y)-Math.hypot(o.last.x,o.last.y));r<s&&n<s?this._state=64:this._state=32,this._pushEvent("gesturestart"),this._pushEvent("gesturemove")}_pushEvent(t){let n={type:this._stateToGesture(this._state)},r=this._getPosition(),o=r.last;switch(t==="gesturestart"&&(o=r.first),this._state){case 32:case 64:o=r.first;break}if(n.clientX=o.x,n.clientY=o.y,this._state===64){let i=this._getAverageDistance();t==="gesturestart"?(n.magnitudeX=i.first.x,n.magnitudeY=i.first.y):(n.magnitudeX=i.last.x,n.magnitudeY=i.last.y)}else if(this._state===32)if(t==="gesturestart")n.magnitudeX=0,n.magnitudeY=0;else{let i=this._getAverageMovement();n.magnitudeX=i.x,n.magnitudeY=i.y}let s=new CustomEvent(t,{detail:n});this._target.dispatchEvent(s)}_stateToGesture(t){switch(t){case 1:return"onetap";case 2:return"twotap";case 4:return"threetap";case 8:return"drag";case 16:return"longpress";case 32:return"twodrag";case 64:return"pinch"}throw new Error("Unknown gesture state: "+t)}_getPosition(){if(this._tracked.length===0)throw new Error("Failed to get gesture position, no tracked touches");let t=this._tracked.length,n=0,r=0,o=0,s=0;for(let i=0;i<this._tracked.length;i++)n+=this._tracked[i].firstX,r+=this._tracked[i].firstY,o+=this._tracked[i].lastX,s+=this._tracked[i].lastY;return{first:{x:n/t,y:r/t},last:{x:o/t,y:s/t}}}_getAverageMovement(){if(this._tracked.length===0)throw new Error("Failed to get gesture movement, no tracked touches");let t,n;t=n=0;let r=this._tracked.length;for(let o=0;o<this._tracked.length;o++)t+=this._tracked[o].lastX-this._tracked[o].firstX,n+=this._tracked[o].lastY-this._tracked[o].firstY;return{x:t/r,y:n/r}}_getAverageDistance(){if(this._tracked.length===0)throw new Error("Failed to get gesture distance, no tracked touches");let t=this._tracked[0],n=this._tracked[this._tracked.length-1],r=Math.abs(n.firstX-t.firstX),o=Math.abs(n.firstY-t.firstY),s=Math.abs(n.lastX-t.lastX),i=Math.abs(n.lastY-t.lastY);return{first:{x:r,y:o},last:{x:s,y:i}}}};var Wi=!uv||Lf,ji=class{constructor(){this._target=null,this._canvas=document.createElement("canvas"),Wi&&(this._canvas.style.position="fixed",this._canvas.style.zIndex="65535",this._canvas.style.pointerEvents="none",this._canvas.style.userSelect="none",this._canvas.style.WebkitUserSelect="none",this._canvas.style.visibility="hidden"),this._position={x:0,y:0},this._hotSpot={x:0,y:0},this._eventHandlers={mouseover:this._handleMouseOver.bind(this),mouseleave:this._handleMouseLeave.bind(this),mousemove:this._handleMouseMove.bind(this),mouseup:this._handleMouseUp.bind(this)}}attach(t){if(this._target&&this.detach(),this._target=t,Wi){document.body.appendChild(this._canvas);let n={capture:!0,passive:!0};this._target.addEventListener("mouseover",this._eventHandlers.mouseover,n),this._target.addEventListener("mouseleave",this._eventHandlers.mouseleave,n),this._target.addEventListener("mousemove",this._eventHandlers.mousemove,n),this._target.addEventListener("mouseup",this._eventHandlers.mouseup,n)}this.clear()}detach(){if(this._target){if(Wi){let t={capture:!0,passive:!0};this._target.removeEventListener("mouseover",this._eventHandlers.mouseover,t),this._target.removeEventListener("mouseleave",this._eventHandlers.mouseleave,t),this._target.removeEventListener("mousemove",this._eventHandlers.mousemove,t),this._target.removeEventListener("mouseup",this._eventHandlers.mouseup,t),document.contains(this._canvas)&&document.body.removeChild(this._canvas)}this._target=null}}change(t,n,r,o,s){if(o===0||s===0){this.clear();return}this._position.x=this._position.x+this._hotSpot.x-n,this._position.y=this._position.y+this._hotSpot.y-r,this._hotSpot.x=n,this._hotSpot.y=r;let i=this._canvas.getContext("2d");this._canvas.width=o,this._canvas.height=s;let a=new ImageData(new Uint8ClampedArray(t),o,s);if(i.clearRect(0,0,o,s),i.putImageData(a,0,0),Wi)this._updatePosition();else{let u=this._canvas.toDataURL();this._target.style.cursor="url("+u+")"+n+" "+r+", default"}}clear(){this._target.style.cursor="none",this._canvas.width=0,this._canvas.height=0,this._position.x=this._position.x+this._hotSpot.x,this._position.y=this._position.y+this._hotSpot.y,this._hotSpot.x=0,this._hotSpot.y=0}move(t,n){if(!Wi)return;window.visualViewport?(this._position.x=t+window.visualViewport.offsetLeft,this._position.y=n+window.visualViewport.offsetTop):(this._position.x=t,this._position.y=n),this._updatePosition();let r=document.elementFromPoint(t,n);this._updateVisibility(r)}_handleMouseOver(t){this._handleMouseMove(t)}_handleMouseLeave(t){this._updateVisibility(t.relatedTarget)}_handleMouseMove(t){this._updateVisibility(t.target),this._position.x=t.clientX-this._hotSpot.x,this._position.y=t.clientY-this._hotSpot.y,this._updatePosition()}_handleMouseUp(t){let n=document.elementFromPoint(t.clientX,t.clientY);this._updateVisibility(n),this._captureIsActive()&&window.setTimeout(()=>{this._target&&(n=document.elementFromPoint(t.clientX,t.clientY),this._updateVisibility(n))},0)}_showCursor(){this._canvas.style.visibility==="hidden"&&(this._canvas.style.visibility="")}_hideCursor(){this._canvas.style.visibility!=="hidden"&&(this._canvas.style.visibility="hidden")}_shouldShowCursor(t){return t?t===this._target?!0:!(!this._target.contains(t)||window.getComputedStyle(t).cursor!=="none"):!1}_updateVisibility(t){this._captureIsActive()&&(t=document.captureElement),this._shouldShowCursor(t)?this._showCursor():this._hideCursor()}_updatePosition(){this._canvas.style.left=this._position.x+"px",this._canvas.style.top=this._position.y+"px"}_captureIsActive(){return document.captureElement&&document.documentElement.contains(document.captureElement)}};var hh=40*1024*1024,_c={CONNECTING:"connecting",OPEN:"open",CLOSING:"closing",CLOSED:"closed"},vc={CONNECTING:[WebSocket.CONNECTING,_c.CONNECTING],OPEN:[WebSocket.OPEN,_c.OPEN],CLOSING:[WebSocket.CLOSING,_c.CLOSING],CLOSED:[WebSocket.CLOSED,_c.CLOSED]},Ow=["send","close","binaryType","onerror","onmessage","onopen","protocol","readyState"],Qi=class{constructor(){this._websocket=null,this._rQi=0,this._rQlen=0,this._rQbufferSize=1024*1024*4,this._rQ=null,this._sQbufferSize=1024*10,this._sQlen=0,this._sQ=null,this._eventHandlers={message:()=>{},open:()=>{},close:()=>{},error:()=>{}}}get readyState(){let t;return this._websocket===null?"unused":(t=this._websocket.readyState,vc.CONNECTING.includes(t)?"connecting":vc.OPEN.includes(t)?"open":vc.CLOSING.includes(t)?"closing":vc.CLOSED.includes(t)?"closed":"unknown")}rQpeek8(){return this._rQ[this._rQi]}rQskipBytes(t){this._rQi+=t}rQshift8(){return this._rQshift(1)}rQshift16(){return this._rQshift(2)}rQshift32(){return this._rQshift(4)}_rQshift(t){let n=0;for(let r=t-1;r>=0;r--)n+=this._rQ[this._rQi++]<<r*8;return n>>>0}rQlen(){return this._rQlen-this._rQi}rQshiftStr(t){let n="";for(let r=0;r<t;r+=4096){let o=this.rQshiftBytes(Math.min(4096,t-r),!1);n+=String.fromCharCode.apply(null,o)}return n}rQshiftBytes(t,n=!0){return this._rQi+=t,n?this._rQ.slice(this._rQi-t,this._rQi):this._rQ.subarray(this._rQi-t,this._rQi)}rQshiftTo(t,n){t.set(new Uint8Array(this._rQ.buffer,this._rQi,n)),this._rQi+=n}rQpeekBytes(t,n=!0){return n?this._rQ.slice(this._rQi,this._rQi+t):this._rQ.subarray(this._rQi,this._rQi+t)}rQwait(t,n,r){if(this._rQlen-this._rQi<n){if(r){if(this._rQi<r)throw new Error("rQwait cannot backup "+r+" bytes");this._rQi-=r}return!0}return!1}sQpush8(t){this._sQensureSpace(1),this._sQ[this._sQlen++]=t}sQpush16(t){this._sQensureSpace(2),this._sQ[this._sQlen++]=t>>8&255,this._sQ[this._sQlen++]=t>>0&255}sQpush32(t){this._sQensureSpace(4),this._sQ[this._sQlen++]=t>>24&255,this._sQ[this._sQlen++]=t>>16&255,this._sQ[this._sQlen++]=t>>8&255,this._sQ[this._sQlen++]=t>>0&255}sQpushString(t){let n=t.split("").map(r=>r.charCodeAt(0));this.sQpushBytes(new Uint8Array(n))}sQpushBytes(t){for(let n=0;n<t.length;){this._sQensureSpace(1);let r=this._sQbufferSize-this._sQlen;r>t.length-n&&(r=t.length-n),this._sQ.set(t.subarray(n,n+r),this._sQlen),this._sQlen+=r,n+=r}}flush(){this._sQlen>0&&this.readyState==="open"&&(this._websocket.send(new Uint8Array(this._sQ.buffer,0,this._sQlen)),this._sQlen=0)}_sQensureSpace(t){this._sQbufferSize-this._sQlen<t&&this.flush()}off(t){this._eventHandlers[t]=()=>{}}on(t,n){this._eventHandlers[t]=n}_allocateBuffers(){this._rQ=new Uint8Array(this._rQbufferSize),this._sQ=new Uint8Array(this._sQbufferSize)}init(){this._allocateBuffers(),this._rQi=0,this._websocket=null}open(t,n){this.attach(new WebSocket(t,n))}attach(t){this.init();let n=[...Object.keys(t),...Object.getOwnPropertyNames(Object.getPrototypeOf(t))];for(let r=0;r<Ow.length;r++){let o=Ow[r];if(n.indexOf(o)<0)throw new Error("Raw channel missing property: "+o)}this._websocket=t,this._websocket.binaryType="arraybuffer",this._websocket.onmessage=this._recvMessage.bind(this),this._websocket.onopen=()=>{de(">> WebSock.onopen"),this._websocket.protocol&&Qe("Server choose sub-protocol: "+this._websocket.protocol),this._eventHandlers.open(),de("<< WebSock.onopen")},this._websocket.onclose=r=>{de(">> WebSock.onclose"),this._eventHandlers.close(r),de("<< WebSock.onclose")},this._websocket.onerror=r=>{de(">> WebSock.onerror: "+r),this._eventHandlers.error(r),de("<< WebSock.onerror: "+r)}}close(){this._websocket&&((this.readyState==="connecting"||this.readyState==="open")&&(Qe("Closing WebSocket connection"),this._websocket.close()),this._websocket.onmessage=()=>{})}_expandCompactRQ(t){let n=(this._rQlen-this._rQi+t)*8,r=this._rQbufferSize<n;if(r&&(this._rQbufferSize=Math.max(this._rQbufferSize*2,n)),this._rQbufferSize>hh&&(this._rQbufferSize=hh,this._rQbufferSize-(this._rQlen-this._rQi)<t))throw new Error("Receive queue buffer exceeded "+hh+" bytes, and the new message could not fit");if(r){let o=this._rQ.buffer;this._rQ=new Uint8Array(this._rQbufferSize),this._rQ.set(new Uint8Array(o,this._rQi,this._rQlen-this._rQi))}else this._rQ.copyWithin(0,this._rQi,this._rQlen);this._rQlen=this._rQlen-this._rQi,this._rQi=0}_recvMessage(t){this._rQlen==this._rQi&&(this._rQlen=0,this._rQi=0);let n=new Uint8Array(t.data);n.length>this._rQbufferSize-this._rQlen&&this._expandCompactRQ(n.length),this._rQ.set(n,this._rQlen),this._rQlen+=n.length,this._rQlen-this._rQi>0?this._eventHandlers.message():de("Ignoring empty message")}};var Lw={Again:57349,AltLeft:56,AltRight:57400,ArrowDown:57424,ArrowLeft:57419,ArrowRight:57421,ArrowUp:57416,AudioVolumeDown:57390,AudioVolumeMute:57376,AudioVolumeUp:57392,Backquote:41,Backslash:43,Backspace:14,BracketLeft:26,BracketRight:27,BrowserBack:57450,BrowserFavorites:57446,BrowserForward:57449,BrowserHome:57394,BrowserRefresh:57447,BrowserSearch:57445,BrowserStop:57448,CapsLock:58,Comma:51,ContextMenu:57437,ControlLeft:29,ControlRight:57373,Convert:121,Copy:57464,Cut:57404,Delete:57427,Digit0:11,Digit1:2,Digit2:3,Digit3:4,Digit4:5,Digit5:6,Digit6:7,Digit7:8,Digit8:9,Digit9:10,Eject:57469,End:57423,Enter:28,Equal:13,Escape:1,F1:59,F10:68,F11:87,F12:88,F13:93,F14:94,F15:95,F16:85,F17:57347,F18:57463,F19:57348,F2:60,F20:90,F21:116,F22:57465,F23:109,F24:111,F3:61,F4:62,F5:63,F6:64,F7:65,F8:66,F9:67,Find:57409,Help:57461,Hiragana:119,Home:57415,Insert:57426,IntlBackslash:86,IntlRo:115,IntlYen:125,KanaMode:112,Katakana:120,KeyA:30,KeyB:48,KeyC:46,KeyD:32,KeyE:18,KeyF:33,KeyG:34,KeyH:35,KeyI:23,KeyJ:36,KeyK:37,KeyL:38,KeyM:50,KeyN:49,KeyO:24,KeyP:25,KeyQ:16,KeyR:19,KeyS:31,KeyT:20,KeyU:22,KeyV:47,KeyW:17,KeyX:45,KeyY:21,KeyZ:44,Lang1:114,Lang2:113,Lang3:120,Lang4:119,Lang5:118,LaunchApp1:57451,LaunchApp2:57377,LaunchMail:57452,MediaPlayPause:57378,MediaSelect:57453,MediaStop:57380,MediaTrackNext:57369,MediaTrackPrevious:57360,MetaLeft:57435,MetaRight:57436,Minus:12,NonConvert:123,NumLock:69,Numpad0:82,Numpad1:79,Numpad2:80,Numpad3:81,Numpad4:75,Numpad5:76,Numpad6:77,Numpad7:71,Numpad8:72,Numpad9:73,NumpadAdd:78,NumpadComma:126,NumpadDecimal:83,NumpadDivide:57397,NumpadEnter:57372,NumpadEqual:89,NumpadMultiply:55,NumpadParenLeft:57462,NumpadParenRight:57467,NumpadSubtract:74,Open:100,PageDown:57425,PageUp:57417,Paste:101,Pause:57414,Period:52,Power:57438,PrintScreen:84,Props:57350,Quote:40,ScrollLock:70,Semicolon:39,ShiftLeft:42,ShiftRight:54,Slash:53,Sleep:57439,Space:57,Suspend:57381,Tab:15,Undo:57351,WakeUp:57443};var ge={encodingRaw:0,encodingCopyRect:1,encodingRRE:2,encodingHextile:5,encodingZlib:6,encodingTight:7,encodingZRLE:16,encodingTightPNG:-260,encodingJPEG:21,encodingH264:50,pseudoEncodingQualityLevel9:-23,pseudoEncodingQualityLevel0:-32,pseudoEncodingDesktopSize:-223,pseudoEncodingLastRect:-224,pseudoEncodingCursor:-239,pseudoEncodingQEMUExtendedKeyEvent:-258,pseudoEncodingQEMULedEvent:-261,pseudoEncodingDesktopName:-307,pseudoEncodingExtendedDesktopSize:-308,pseudoEncodingXvp:-309,pseudoEncodingFence:-312,pseudoEncodingContinuousUpdates:-313,pseudoEncodingExtendedMouseButtons:-316,pseudoEncodingCompressLevel9:-247,pseudoEncodingCompressLevel0:-256,pseudoEncodingVMwareCursor:1464686180,pseudoEncodingExtendedClipboard:3231835598};var wc=class e{constructor(){this._key=null}get algorithm(){return{name:"AES-ECB"}}static async importKey(t,n,r,o){let s=new e;return await s._importKey(t,r,o),s}async _importKey(t,n,r){this._key=await window.crypto.subtle.importKey("raw",t,{name:"AES-CBC"},n,r)}async encrypt(t,n){let r=new Uint8Array(n);if(r.length%16!==0||this._key===null)return null;let o=r.length/16;for(let s=0;s<o;s++){let i=new Uint8Array(await window.crypto.subtle.encrypt({name:"AES-CBC",iv:new Uint8Array(16)},this._key,r.slice(s*16,s*16+16))).slice(0,16);r.set(i,s*16)}return r}},kc=class e{constructor(){this._rawKey=null,this._ctrKey=null,this._cbcKey=null,this._zeroBlock=new Uint8Array(16),this._prefixBlock0=this._zeroBlock,this._prefixBlock1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]),this._prefixBlock2=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2])}get algorithm(){return{name:"AES-EAX"}}async _encryptBlock(t){let n=await window.crypto.subtle.encrypt({name:"AES-CBC",iv:this._zeroBlock},this._cbcKey,t);return new Uint8Array(n).slice(0,16)}async _initCMAC(){let t=await this._encryptBlock(this._zeroBlock),n=new Uint8Array(16),r=t[0]>>>6;for(let s=0;s<15;s++)n[s]=t[s+1]>>6|t[s]<<2,t[s]=t[s+1]>>7|t[s]<<1;let o=[0,135,14,137];n[14]^=r>>>1,n[15]=t[15]<<2^o[r],t[15]=t[15]<<1^o[r>>1],this._k1=t,this._k2=n}async _encryptCTR(t,n){let r=await window.crypto.subtle.encrypt({name:"AES-CTR",counter:n,length:128},this._ctrKey,t);return new Uint8Array(r)}async _decryptCTR(t,n){let r=await window.crypto.subtle.decrypt({name:"AES-CTR",counter:n,length:128},this._ctrKey,t);return new Uint8Array(r)}async _computeCMAC(t,n){if(n.length!==16)return null;let r=Math.floor(t.length/16),o=Math.ceil(t.length/16),s=t.length-r*16,i=new Uint8Array((o+1)*16);if(i.set(n),i.set(t,16),s===0)for(let c=0;c<16;c++)i[r*16+c]^=this._k1[c];else{i[(r+1)*16+s]=128;for(let c=0;c<16;c++)i[(r+1)*16+c]^=this._k2[c]}let a=await window.crypto.subtle.encrypt({name:"AES-CBC",iv:this._zeroBlock},this._cbcKey,i);return a=new Uint8Array(a),a.slice(a.length-32,a.length-16)}static async importKey(t,n,r,o){let s=new e;return await s._importKey(t),s}async _importKey(t){this._rawKey=t,this._ctrKey=await window.crypto.subtle.importKey("raw",t,{name:"AES-CTR"},!1,["encrypt","decrypt"]),this._cbcKey=await window.crypto.subtle.importKey("raw",t,{name:"AES-CBC"},!1,["encrypt"]),await this._initCMAC()}async encrypt(t,n){let r=t.additionalData,o=t.iv,s=await this._computeCMAC(o,this._prefixBlock0),i=await this._encryptCTR(n,s),a=await this._computeCMAC(r,this._prefixBlock1),u=await this._computeCMAC(i,this._prefixBlock2);for(let d=0;d<16;d++)u[d]^=s[d]^a[d];let c=new Uint8Array(16+i.length);return c.set(i),c.set(u,i.length),c}async decrypt(t,n){let r=n.slice(0,n.length-16),o=t.additionalData,s=t.iv,i=n.slice(n.length-16),a=await this._computeCMAC(s,this._prefixBlock0),u=await this._computeCMAC(o,this._prefixBlock1),c=await this._computeCMAC(r,this._prefixBlock2);for(let p=0;p<16;p++)c[p]^=a[p]^u[p];if(c.length!==i.length)return null;for(let p=0;p<i.length;p++)if(c[p]!==i[p])return null;return await this._decryptCTR(r,a)}};var Mw=[13,16,10,23,0,4,2,27,14,5,20,9,22,18,11,3,25,7,15,6,26,19,12,1,40,51,30,36,46,54,29,39,50,44,32,47,43,48,38,55,33,52,45,41,49,35,28,31],o$=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],E=0,M,D,B,F,z,U;M=65536;D=1<<24;B=M|D;F=4;z=1024;U=F|z;var Dw=[B|z,E|E,M|E,B|U,B|F,M|U,E|F,M|E,E|z,B|z,B|U,E|z,D|U,B|F,D|E,E|F,E|U,D|z,D|z,M|z,M|z,B|E,B|E,D|U,M|F,D|F,D|F,M|F,E|E,E|U,M|U,D|E,M|E,B|U,E|F,B|E,B|z,D|E,D|E,E|z,B|F,M|E,M|z,D|F,E|z,E|F,D|U,M|U,B|U,M|F,B|E,D|U,D|F,E|U,M|U,B|z,E|U,D|z,D|z,E|E,M|F,M|z,E|E,B|F];M=1<<20;D=1<<31;B=M|D;F=32;z=32768;U=F|z;var Fw=[B|U,D|z,E|z,M|U,M|E,E|F,B|F,D|U,D|F,B|U,B|z,D|E,D|z,M|E,E|F,B|F,M|z,M|F,D|U,E|E,D|E,E|z,M|U,B|E,M|F,D|F,E|E,M|z,E|U,B|z,B|E,E|U,E|E,M|U,B|F,M|E,D|U,B|E,B|z,E|z,B|E,D|z,E|F,B|U,M|U,E|F,E|z,D|E,E|U,B|z,M|E,D|F,M|F,D|U,D|F,M|F,M|z,E|E,D|z,E|U,D|E,B|F,B|U,M|z];M=1<<17;D=1<<27;B=M|D;F=8;z=512;U=F|z;var zw=[E|U,B|z,E|E,B|F,D|z,E|E,M|U,D|z,M|F,D|F,D|F,M|E,B|U,M|F,B|E,E|U,D|E,E|F,B|z,E|z,M|z,B|E,B|F,M|U,D|U,M|z,M|E,D|U,E|F,B|U,E|z,D|E,B|z,D|E,M|F,E|U,M|E,B|z,D|z,E|E,E|z,M|F,B|U,D|z,D|F,E|z,E|E,B|F,D|U,M|E,D|E,B|U,E|F,M|U,M|z,D|F,B|E,D|U,E|U,B|E,M|U,E|F,B|F,M|z];M=8192;D=1<<23;B=M|D;F=1;z=128;U=F|z;var Kw=[B|F,M|U,M|U,E|z,B|z,D|U,D|F,M|F,E|E,B|E,B|E,B|U,E|U,E|E,D|z,D|F,E|F,M|E,D|E,B|F,E|z,D|E,M|F,M|z,D|U,E|F,M|z,D|z,M|E,B|z,B|U,E|U,D|z,D|F,B|E,B|U,E|U,E|E,E|E,B|E,M|z,D|z,D|U,E|F,B|F,M|U,M|U,E|z,B|U,E|U,E|F,M|E,D|F,M|F,B|z,D|U,M|F,M|z,D|E,B|F,E|z,D|E,M|E,B|z];M=1<<25;D=1<<30;B=M|D;F=256;z=1<<19;U=F|z;var Xw=[E|F,M|U,M|z,B|F,E|z,E|F,D|E,M|z,D|U,E|z,M|F,D|U,B|F,B|z,E|U,D|E,M|E,D|z,D|z,E|E,D|F,B|U,B|U,M|F,B|z,D|F,E|E,B|E,M|U,M|E,B|E,E|U,E|z,B|F,E|F,M|E,D|E,M|z,B|F,D|U,M|F,D|E,B|z,M|U,D|U,E|F,M|E,B|z,B|U,E|U,B|E,B|U,M|z,E|E,D|z,B|E,E|U,M|F,D|F,E|z,E|E,D|z,M|U,D|F];M=1<<22;D=1<<29;B=M|D;F=16;z=16384;U=F|z;var Bw=[D|F,B|E,E|z,B|U,B|E,E|F,B|U,M|E,D|z,M|U,M|E,D|F,M|F,D|z,D|E,E|U,E|E,M|F,D|U,E|z,M|z,D|U,E|F,B|F,B|F,E|E,M|U,B|z,E|U,M|z,B|z,D|E,D|z,E|F,B|F,M|z,B|U,M|E,E|U,D|F,M|E,D|z,D|E,E|U,D|F,B|U,M|z,B|E,M|U,B|z,E|E,B|F,E|F,E|z,B|E,M|U,E|z,M|F,D|U,E|E,B|z,D|E,M|F,D|U];M=1<<21;D=1<<26;B=M|D;F=2;z=2048;U=F|z;var Uw=[M|E,B|F,D|U,E|E,E|z,D|U,M|U,B|z,B|U,M|E,E|E,D|F,E|F,D|E,B|F,E|U,D|z,M|U,M|F,D|z,D|F,B|E,B|z,M|F,B|E,E|z,E|U,B|U,M|z,E|F,D|E,M|z,D|E,M|z,M|E,D|U,D|U,B|F,B|F,E|F,M|F,D|E,D|z,M|E,B|z,E|U,M|U,B|z,E|U,D|F,B|U,B|E,M|z,E|E,E|F,B|U,E|E,M|U,B|E,E|z,D|F,D|z,E|z,M|F];M=1<<18;D=1<<28;B=M|D;F=64;z=4096;U=F|z;var Hw=[D|U,E|z,M|E,B|U,D|E,D|U,E|F,D|E,M|F,B|E,B|U,M|z,B|z,M|U,E|z,E|F,B|E,D|F,D|z,E|U,M|z,M|F,B|F,B|z,E|U,E|E,E|E,B|F,D|F,D|z,M|U,M|E,M|U,M|E,B|z,E|z,E|F,B|F,E|z,M|U,D|z,E|F,D|F,B|E,B|F,D|E,M|E,D|U,E|E,B|U,M|F,D|F,B|E,D|z,D|U,E|E,B|U,M|z,M|z,E|U,E|U,M|F,D|E,B|z],Sc=class{constructor(t){this.keys=[];let n=[],r=[],o=[];for(let s=0,i=56;s<56;++s,i-=8){i+=i<-5?65:i<-3?31:i<-1?63:i===27?35:0;let a=i&7;n[s]=(t[i>>>3]&1<<a)!==0?1:0}for(let s=0;s<16;++s){let i=s<<1,a=i+1;o[i]=o[a]=0;for(let u=28;u<59;u+=28)for(let c=u-28;c<u;++c){let d=c+o$[s];r[c]=d<u?n[d]:n[d-28]}for(let u=0;u<24;++u)r[Mw[u]]!==0&&(o[i]|=1<<23-u),r[Mw[u+24]]!==0&&(o[a]|=1<<23-u)}for(let s=0,i=0,a=0;s<16;++s){let u=o[i++],c=o[i++];this.keys[a]=(u&16515072)<<6,this.keys[a]|=(u&4032)<<10,this.keys[a]|=(c&16515072)>>>10,this.keys[a]|=(c&4032)>>>6,++a,this.keys[a]=(u&258048)<<12,this.keys[a]|=(u&63)<<16,this.keys[a]|=(c&258048)>>>4,this.keys[a]|=c&63,++a}}enc8(t){let n=t.slice(),r=0,o,s,i;o=n[r++]<<24|n[r++]<<16|n[r++]<<8|n[r++],s=n[r++]<<24|n[r++]<<16|n[r++]<<8|n[r++],i=(o>>>4^s)&252645135,s^=i,o^=i<<4,i=(o>>>16^s)&65535,s^=i,o^=i<<16,i=(s>>>2^o)&858993459,o^=i,s^=i<<2,i=(s>>>8^o)&16711935,o^=i,s^=i<<8,s=s<<1|s>>>31&1,i=(o^s)&2863311530,o^=i,s^=i,o=o<<1|o>>>31&1;for(let a=0,u=0;a<8;++a){i=s<<28|s>>>4,i^=this.keys[u++];let c=Uw[i&63];c|=Xw[i>>>8&63],c|=zw[i>>>16&63],c|=Dw[i>>>24&63],i=s^this.keys[u++],c|=Hw[i&63],c|=Bw[i>>>8&63],c|=Kw[i>>>16&63],c|=Fw[i>>>24&63],o^=c,i=o<<28|o>>>4,i^=this.keys[u++],c=Uw[i&63],c|=Xw[i>>>8&63],c|=zw[i>>>16&63],c|=Dw[i>>>24&63],i=o^this.keys[u++],c|=Hw[i&63],c|=Bw[i>>>8&63],c|=Kw[i>>>16&63],c|=Fw[i>>>24&63],s^=c}for(s=s<<31|s>>>1,i=(o^s)&2863311530,o^=i,s^=i,o=o<<31|o>>>1,i=(o>>>8^s)&16711935,s^=i,o^=i<<8,i=(o>>>2^s)&858993459,s^=i,o^=i<<2,i=(s>>>16^o)&65535,o^=i,s^=i<<16,i=(s>>>4^o)&252645135,o^=i,s^=i<<4,i=[s,o],r=0;r<8;r++)n[r]=(i[r>>>2]>>>8*(3-r%4))%256,n[r]<0&&(n[r]+=256);return n}},Ec=class e{constructor(){this._cipher=null}get algorithm(){return{name:"DES-ECB"}}static importKey(t,n,r,o){let s=new e;return s._importKey(t),s}_importKey(t,n,r){this._cipher=new Sc(t)}encrypt(t,n){let r=new Uint8Array(n);if(r.length%8!==0||this._cipher===null)return null;let o=r.length/8;for(let s=0;s<o;s++)r.set(this._cipher.enc8(r.slice(s*8,s*8+8)),s*8);return r}},Nc=class e{constructor(){this._cipher=null}get algorithm(){return{name:"DES-CBC"}}static importKey(t,n,r,o){let s=new e;return s._importKey(t),s}_importKey(t){this._cipher=new Sc(t)}encrypt(t,n){let r=new Uint8Array(n),o=new Uint8Array(t.iv);if(r.length%8!==0||this._cipher===null)return null;let s=r.length/8;for(let i=0;i<s;i++){for(let a=0;a<8;a++)o[a]^=n[i*8+a];o=this._cipher.enc8(o),r.set(o,i*8)}return r}};function Qo(e,t,n){let r=1n;for(e=e%n;t>0n;)(t&1n)===1n&&(r=r*e%n),t=t>>1n,e=e*e%n;return r}function Go(e,t=0){let n=e.toString(16);t===0&&(t=Math.ceil(n.length/2)),n=n.padStart(t*2,"0");let r=n.length/2,o=new Uint8Array(r);for(let s=0;s<r;s++)o[s]=parseInt(n.slice(s*2,s*2+2),16);return o}function Mt(e){let t="0x";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return BigInt(t)}var Ac=class e{constructor(){this._keyLength=0,this._keyBytes=0,this._n=null,this._e=null,this._d=null,this._nBigInt=null,this._eBigInt=null,this._dBigInt=null,this._extractable=!1}get algorithm(){return{name:"RSA-PKCS1-v1_5"}}_base64urlDecode(t){return t=t.replace(/-/g,"+").replace(/_/g,"/"),t=t.padEnd(Math.ceil(t.length/4)*4,"="),Oo.decode(t)}_padArray(t,n){let r=new Uint8Array(n);return r.set(t,n-t.length),r}static async generateKey(t,n,r){let o=new e;return await o._generateKey(t,n),{privateKey:o}}async _generateKey(t,n){this._keyLength=t.modulusLength,this._keyBytes=Math.ceil(this._keyLength/8);let r=await window.crypto.subtle.generateKey({name:"RSA-OAEP",modulusLength:t.modulusLength,publicExponent:t.publicExponent,hash:{name:"SHA-256"}},!0,["encrypt","decrypt"]),o=await window.crypto.subtle.exportKey("jwk",r.privateKey);this._n=this._padArray(this._base64urlDecode(o.n),this._keyBytes),this._nBigInt=Mt(this._n),this._e=this._padArray(this._base64urlDecode(o.e),this._keyBytes),this._eBigInt=Mt(this._e),this._d=this._padArray(this._base64urlDecode(o.d),this._keyBytes),this._dBigInt=Mt(this._d),this._extractable=n}static async importKey(t,n,r,o){if(o.length!==1||o[0]!=="encrypt")throw new Error("only support importing RSA public key");let s=new e;return await s._importKey(t,r),s}async _importKey(t,n){let r=t.n,o=t.e;if(r.length!==o.length)throw new Error("the sizes of modulus and public exponent do not match");this._keyBytes=r.length,this._keyLength=this._keyBytes*8,this._n=new Uint8Array(this._keyBytes),this._e=new Uint8Array(this._keyBytes),this._n.set(r),this._e.set(o),this._nBigInt=Mt(this._n),this._eBigInt=Mt(this._e),this._extractable=n}async encrypt(t,n){if(n.length>this._keyBytes-11)return null;let r=new Uint8Array(this._keyBytes-n.length-3);window.crypto.getRandomValues(r);for(let a=0;a<r.length;a++)r[a]=Math.floor(r[a]*254/255+1);let o=new Uint8Array(this._keyBytes);o[1]=2,o.set(r,2),o.set(n,r.length+3);let s=Mt(o),i=Qo(s,this._eBigInt,this._nBigInt);return Go(i,this._keyBytes)}async decrypt(t,n){if(n.length!==this._keyBytes)return null;let r=Mt(n),o=Qo(r,this._dBigInt,this._nBigInt),s=Go(o,this._keyBytes);if(s[0]!==0||s[1]!==2)return null;let i=2;for(;i<s.length&&s[i]!==0;i++);return i===s.length?null:s.slice(i+1,s.length)}async exportKey(){if(!this._extractable)throw new Error("key is not extractable");return{n:this._n,e:this._e,d:this._d}}};var mh=class{constructor(t){this._key=t}get algorithm(){return{name:"DH"}}exportKey(){return this._key}},Cc=class e{constructor(){this._g=null,this._p=null,this._gBigInt=null,this._pBigInt=null,this._privateKey=null}get algorithm(){return{name:"DH"}}static generateKey(t,n){let r=new e;return r._generateKey(t),{privateKey:r,publicKey:new mh(r._publicKey)}}_generateKey(t){let n=t.g,r=t.p;this._keyBytes=r.length,this._gBigInt=Mt(n),this._pBigInt=Mt(r),this._privateKey=window.crypto.getRandomValues(new Uint8Array(this._keyBytes)),this._privateKeyBigInt=Mt(this._privateKey),this._publicKey=Go(Qo(this._gBigInt,this._privateKeyBigInt,this._pBigInt),this._keyBytes)}deriveBits(t,n){let r=Math.ceil(n/8),o=new Uint8Array(t.public),s=r>this._keyBytes?r:this._keyBytes,i=Qo(Mt(o),this._privateKeyBigInt,this._pBigInt);return Go(i,s).slice(0,s)}};async function Vw(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return s$(a$(l$(i$(t),8*t.length)))}function s$(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function i$(e){let t=Array(e.length>>2);for(let n=0;n<t.length;n++)t[n]=0;for(let n=0;n<8*e.length;n+=8)t[n>>5]|=(255&e.charCodeAt(n/8))<<n%32;return t}function a$(e){let t="";for(let n=0;n<32*e.length;n+=8)t+=String.fromCharCode(e[n>>5]>>>n%32&255);return t}function l$(e,t){e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;let n=1732584193,r=-271733879,o=-1732584194,s=271733878;for(let i=0;i<e.length;i+=16){let a=n,u=r,c=o,d=s;r=ft(r=ft(r=ft(r=ft(r=pt(r=pt(r=pt(r=pt(r=dt(r=dt(r=dt(r=dt(r=ut(r=ut(r=ut(r=ut(r,o=ut(o,s=ut(s,n=ut(n,r,o,s,e[i+0],7,-680876936),r,o,e[i+1],12,-389564586),n,r,e[i+2],17,606105819),s,n,e[i+3],22,-1044525330),o=ut(o,s=ut(s,n=ut(n,r,o,s,e[i+4],7,-176418897),r,o,e[i+5],12,1200080426),n,r,e[i+6],17,-1473231341),s,n,e[i+7],22,-45705983),o=ut(o,s=ut(s,n=ut(n,r,o,s,e[i+8],7,1770035416),r,o,e[i+9],12,-1958414417),n,r,e[i+10],17,-42063),s,n,e[i+11],22,-1990404162),o=ut(o,s=ut(s,n=ut(n,r,o,s,e[i+12],7,1804603682),r,o,e[i+13],12,-40341101),n,r,e[i+14],17,-1502002290),s,n,e[i+15],22,1236535329),o=dt(o,s=dt(s,n=dt(n,r,o,s,e[i+1],5,-165796510),r,o,e[i+6],9,-1069501632),n,r,e[i+11],14,643717713),s,n,e[i+0],20,-373897302),o=dt(o,s=dt(s,n=dt(n,r,o,s,e[i+5],5,-701558691),r,o,e[i+10],9,38016083),n,r,e[i+15],14,-660478335),s,n,e[i+4],20,-405537848),o=dt(o,s=dt(s,n=dt(n,r,o,s,e[i+9],5,568446438),r,o,e[i+14],9,-1019803690),n,r,e[i+3],14,-187363961),s,n,e[i+8],20,1163531501),o=dt(o,s=dt(s,n=dt(n,r,o,s,e[i+13],5,-1444681467),r,o,e[i+2],9,-51403784),n,r,e[i+7],14,1735328473),s,n,e[i+12],20,-1926607734),o=pt(o,s=pt(s,n=pt(n,r,o,s,e[i+5],4,-378558),r,o,e[i+8],11,-2022574463),n,r,e[i+11],16,1839030562),s,n,e[i+14],23,-35309556),o=pt(o,s=pt(s,n=pt(n,r,o,s,e[i+1],4,-1530992060),r,o,e[i+4],11,1272893353),n,r,e[i+7],16,-155497632),s,n,e[i+10],23,-1094730640),o=pt(o,s=pt(s,n=pt(n,r,o,s,e[i+13],4,681279174),r,o,e[i+0],11,-358537222),n,r,e[i+3],16,-722521979),s,n,e[i+6],23,76029189),o=pt(o,s=pt(s,n=pt(n,r,o,s,e[i+9],4,-640364487),r,o,e[i+12],11,-421815835),n,r,e[i+15],16,530742520),s,n,e[i+2],23,-995338651),o=ft(o,s=ft(s,n=ft(n,r,o,s,e[i+0],6,-198630844),r,o,e[i+7],10,1126891415),n,r,e[i+14],15,-1416354905),s,n,e[i+5],21,-57434055),o=ft(o,s=ft(s,n=ft(n,r,o,s,e[i+12],6,1700485571),r,o,e[i+3],10,-1894986606),n,r,e[i+10],15,-1051523),s,n,e[i+1],21,-2054922799),o=ft(o,s=ft(s,n=ft(n,r,o,s,e[i+8],6,1873313359),r,o,e[i+15],10,-30611744),n,r,e[i+6],15,-1560198380),s,n,e[i+13],21,1309151649),o=ft(o,s=ft(s,n=ft(n,r,o,s,e[i+4],6,-145523070),r,o,e[i+11],10,-1120210379),n,r,e[i+2],15,718787259),s,n,e[i+9],21,-343485551),n=rr(n,a),r=rr(r,u),o=rr(o,c),s=rr(s,d)}return Array(n,r,o,s)}function Tc(e,t,n,r,o,s){return rr(c$(rr(rr(t,e),rr(r,s)),o),n)}function ut(e,t,n,r,o,s,i){return Tc(t&n|~t&r,e,t,o,s,i)}function dt(e,t,n,r,o,s,i){return Tc(t&r|n&~r,e,t,o,s,i)}function pt(e,t,n,r,o,s,i){return Tc(t^n^r,e,t,o,s,i)}function ft(e,t,n,r,o,s,i){return Tc(n^(t|~r),e,t,o,s,i)}function rr(e,t){let n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function c$(e,t){return e<<t|e>>>32-t}var gh=class{constructor(){this._algorithms={"AES-ECB":wc,"AES-EAX":kc,"DES-ECB":Ec,"DES-CBC":Nc,"RSA-PKCS1-v1_5":Ac,DH:Cc,MD5:Vw}}encrypt(t,n,r){if(n.algorithm.name!==t.name)throw new Error("algorithm does not match");if(typeof n.encrypt!="function")throw new Error("key does not support encryption");return n.encrypt(t,r)}decrypt(t,n,r){if(n.algorithm.name!==t.name)throw new Error("algorithm does not match");if(typeof n.decrypt!="function")throw new Error("key does not support encryption");return n.decrypt(t,r)}importKey(t,n,r,o,s){if(t!=="raw")throw new Error("key format is not supported");let i=this._algorithms[r.name];if(typeof i>"u"||typeof i.importKey!="function")throw new Error("algorithm is not supported");return i.importKey(n,r,o,s)}generateKey(t,n,r){let o=this._algorithms[t.name];if(typeof o>"u"||typeof o.generateKey!="function")throw new Error("algorithm is not supported");return o.generateKey(t,n,r)}exportKey(t,n){if(t!=="raw")throw new Error("key format is not supported");if(typeof n.exportKey!="function")throw new Error("key does not support exportKey");return n.exportKey()}digest(t,n){let r=this._algorithms[t];if(typeof r!="function")throw new Error("algorithm is not supported");return r(n)}deriveBits(t,n,r){if(n.algorithm.name!==t.name)throw new Error("algorithm does not match");if(typeof n.deriveBits!="function")throw new Error("key does not support deriveBits");return n.deriveBits(t,r)}},Xe=new gh;var Rc=class{constructor(){this._cipher=null,this._counter=new Uint8Array(16)}async setKey(t){this._cipher=await Xe.importKey("raw",t,{name:"AES-EAX"},!1,["encrypt, decrypt"])}async makeMessage(t){let n=new Uint8Array([(t.length&65280)>>>8,t.length&255]),r=await Xe.encrypt({name:"AES-EAX",iv:this._counter,additionalData:n},this._cipher,t);for(let s=0;s<16&&this._counter[s]++===255;s++);let o=new Uint8Array(t.length+2+16);return o.set(n),o.set(r,2),o}async receiveMessage(t,n){let r=new Uint8Array([(t&65280)>>>8,t&255]),o=await Xe.decrypt({name:"AES-EAX",iv:this._counter,additionalData:r},this._cipher,n);for(let s=0;s<16&&this._counter[s]++===255;s++);return o}},Gi=class extends Or{constructor(t,n){super(),this._hasStarted=!1,this._checkSock=null,this._checkCredentials=null,this._approveServerResolve=null,this._sockReject=null,this._credentialsReject=null,this._approveServerReject=null,this._sock=t,this._getCredentials=n}_waitSockAsync(t){return new Promise((n,r)=>{let o=()=>!this._sock.rQwait("RA2",t);o()?n():(this._checkSock=()=>{o()&&(n(),this._checkSock=null,this._sockReject=null)},this._sockReject=r)})}_waitApproveKeyAsync(){return new Promise((t,n)=>{this._approveServerResolve=t,this._approveServerReject=n})}_waitCredentialsAsync(t){let n=()=>t===1&&this._getCredentials().username!==void 0&&this._getCredentials().password!==void 0?!0:t===2&&this._getCredentials().password!==void 0;return new Promise((r,o)=>{n()?r():(this._checkCredentials=()=>{n()&&(r(),this._checkCredentials=null,this._credentialsReject=null)},this._credentialsReject=o)})}checkInternalEvents(){this._checkSock!==null&&this._checkSock(),this._checkCredentials!==null&&this._checkCredentials()}approveServer(){this._approveServerResolve!==null&&(this._approveServerResolve(),this._approveServerResolve=null)}disconnect(){this._sockReject!==null&&(this._sockReject(new Error("disconnect normally")),this._sockReject=null),this._credentialsReject!==null&&(this._credentialsReject(new Error("disconnect normally")),this._credentialsReject=null),this._approveServerReject!==null&&(this._approveServerReject(new Error("disconnect normally")),this._approveServerReject=null)}async negotiateRA2neAuthAsync(){this._hasStarted=!0,await this._waitSockAsync(4);let t=this._sock.rQpeekBytes(4),n=this._sock.rQshift32();if(n<1024)throw new Error("RA2: server public key is too short: "+n);if(n>8192)throw new Error("RA2: server public key is too long: "+n);let r=Math.ceil(n/8);await this._waitSockAsync(r*2);let o=this._sock.rQshiftBytes(r),s=this._sock.rQshiftBytes(r),i=await Xe.importKey("raw",{n:o,e:s},{name:"RSA-PKCS1-v1_5"},!1,["encrypt"]),a=new Uint8Array(4+r*2);a.set(t),a.set(o,4),a.set(s,4+r);let u=this._waitApproveKeyAsync();this.dispatchEvent(new CustomEvent("serververification",{detail:{type:"RSA",publickey:a}})),await u;let c=2048,d=Math.ceil(c/8),p=(await Xe.generateKey({name:"RSA-PKCS1-v1_5",modulusLength:c,publicExponent:new Uint8Array([1,0,1])},!0,["encrypt"])).privateKey,f=await Xe.exportKey("raw",p),h=f.n,g=f.e,x=new Uint8Array(4+d*2);x[0]=(c&4278190080)>>>24,x[1]=(c&16711680)>>>16,x[2]=(c&65280)>>>8,x[3]=c&255,x.set(h,4),x.set(g,4+d),this._sock.sQpushBytes(x),this._sock.flush();let b=new Uint8Array(16);window.crypto.getRandomValues(b);let v=await Xe.encrypt({name:"RSA-PKCS1-v1_5"},i,b),w=new Uint8Array(2+r);if(w[0]=(r&65280)>>>8,w[1]=r&255,w.set(v,2),this._sock.sQpushBytes(w),this._sock.flush(),await this._waitSockAsync(2),this._sock.rQshift16()!==d)throw new Error("RA2: wrong encrypted message length");let C=this._sock.rQshiftBytes(d),y=await Xe.decrypt({name:"RSA-PKCS1-v1_5"},p,C);if(y===null||y.length!==16)throw new Error("RA2: corrupted server encrypted random");let T=new Uint8Array(32),N=new Uint8Array(32);T.set(y),T.set(b,16),N.set(b),N.set(y,16),T=await window.crypto.subtle.digest("SHA-1",T),T=new Uint8Array(T).slice(0,16),N=await window.crypto.subtle.digest("SHA-1",N),N=new Uint8Array(N).slice(0,16);let S=new Rc;await S.setKey(T);let $=new Rc;await $.setKey(N);let P=new Uint8Array(8+r*2+d*2),L=new Uint8Array(8+r*2+d*2);if(P.set(a),P.set(x,4+r*2),L.set(x),L.set(a,4+d*2),P=await window.crypto.subtle.digest("SHA-1",P),L=await window.crypto.subtle.digest("SHA-1",L),P=new Uint8Array(P),L=new Uint8Array(L),this._sock.sQpushBytes(await S.makeMessage(L)),this._sock.flush(),await this._waitSockAsync(38),this._sock.rQshift16()!==20)throw new Error("RA2: wrong server hash");let ne=await $.receiveMessage(20,this._sock.rQshiftBytes(36));if(ne===null)throw new Error("RA2: failed to authenticate the message");for(let G=0;G<20;G++)if(ne[G]!==P[G])throw new Error("RA2: wrong server hash");if(await this._waitSockAsync(19),this._sock.rQshift16()!==1)throw new Error("RA2: wrong subtype");let se=await $.receiveMessage(1,this._sock.rQshiftBytes(17));if(se===null)throw new Error("RA2: failed to authenticate the message");se=se[0];let _e=this._waitCredentialsAsync(se);if(se===1)(this._getCredentials().username===void 0||this._getCredentials().password===void 0)&&this.dispatchEvent(new CustomEvent("credentialsrequired",{detail:{types:["username","password"]}}));else if(se===2)this._getCredentials().password===void 0&&this.dispatchEvent(new CustomEvent("credentialsrequired",{detail:{types:["password"]}}));else throw new Error("RA2: wrong subtype");await _e;let ie;se===1?ie=Gt(this._getCredentials().username).slice(0,255):ie="";let Q=Gt(this._getCredentials().password).slice(0,255),j=new Uint8Array(ie.length+Q.length+2);j[0]=ie.length,j[ie.length+1]=Q.length;for(let G=0;G<ie.length;G++)j[G+1]=ie.charCodeAt(G);for(let G=0;G<Q.length;G++)j[ie.length+2+G]=Q.charCodeAt(G);this._sock.sQpushBytes(await S.makeMessage(j)),this._sock.flush()}get hasStarted(){return this._hasStarted}set hasStarted(t){this._hasStarted=t}};var Yi=class{constructor(){this._lines=0}decodeRect(t,n,r,o,s,i,a){if(r===0||o===0)return!0;this._lines===0&&(this._lines=o);let u=a==8?1:4,c=r*u;for(;this._lines>0;){if(s.rQwait("RAW",c))return!1;let d=n+(o-this._lines),p=s.rQshiftBytes(c,!1);if(a==8){let f=new Uint8Array(r*4);for(let h=0;h<r;h++)f[h*4+0]=(p[h]>>0&3)*255/3,f[h*4+1]=(p[h]>>2&3)*255/3,f[h*4+2]=(p[h]>>4&3)*255/3,f[h*4+3]=255;p=f}for(let f=0;f<r;f++)p[f*4+3]=255;i.blitImage(t,d,r,1,p,0),this._lines--}return!0}};var qi=class{decodeRect(t,n,r,o,s,i,a){if(s.rQwait("COPYRECT",4))return!1;let u=s.rQshift16(),c=s.rQshift16();return r===0||o===0||i.copyImage(u,c,t,n,r,o),!0}};var Ji=class{constructor(){this._subrects=0}decodeRect(t,n,r,o,s,i,a){if(this._subrects===0){if(s.rQwait("RRE",8))return!1;this._subrects=s.rQshift32();let u=s.rQshiftBytes(4);i.fillRect(t,n,r,o,u)}for(;this._subrects>0;){if(s.rQwait("RRE",12))return!1;let u=s.rQshiftBytes(4),c=s.rQshift16(),d=s.rQshift16(),p=s.rQshift16(),f=s.rQshift16();i.fillRect(t+c,n+d,p,f,u),this._subrects--}return!0}};var ea=class{constructor(){this._tiles=0,this._lastsubencoding=0,this._tileBuffer=new Uint8Array(256*4)}decodeRect(t,n,r,o,s,i,a){for(this._tiles===0&&(this._tilesX=Math.ceil(r/16),this._tilesY=Math.ceil(o/16),this._totalTiles=this._tilesX*this._tilesY,this._tiles=this._totalTiles);this._tiles>0;){let u=1;if(s.rQwait("HEXTILE",u))return!1;let c=s.rQpeek8();if(c>30)throw new Error("Illegal hextile subencoding (subencoding: "+c+")");let d=this._totalTiles-this._tiles,p=d%this._tilesX,f=Math.floor(d/this._tilesX),h=t+p*16,g=n+f*16,x=Math.min(16,t+r-h),b=Math.min(16,n+o-g);if(c&1)u+=x*b*4;else if(c&2&&(u+=4),c&4&&(u+=4),c&8){if(u++,s.rQwait("HEXTILE",u))return!1;let v=s.rQpeekBytes(u).at(-1);c&16?u+=v*6:u+=v*2}if(s.rQwait("HEXTILE",u))return!1;if(s.rQshift8(),c===0)this._lastsubencoding&1?de(" Ignoring blank after RAW"):i.fillRect(h,g,x,b,this._background);else if(c&1){let v=x*b,w=s.rQshiftBytes(v*4,!1);for(let C=0;C<v;C++)w[C*4+3]=255;i.blitImage(h,g,x,b,w,0)}else{if(c&2&&(this._background=new Uint8Array(s.rQshiftBytes(4))),c&4&&(this._foreground=new Uint8Array(s.rQshiftBytes(4))),this._startTile(h,g,x,b,this._background),c&8){let v=s.rQshift8();for(let w=0;w<v;w++){let C;c&16?C=s.rQshiftBytes(4):C=this._foreground;let y=s.rQshift8(),T=y>>4,N=y&15,S=s.rQshift8(),$=(S>>4)+1,P=(S&15)+1;this._subTile(T,N,$,P,C)}}this._finishTile(i)}this._lastsubencoding=c,this._tiles--}return!0}_startTile(t,n,r,o,s){this._tileX=t,this._tileY=n,this._tileW=r,this._tileH=o;let i=s[0],a=s[1],u=s[2],c=this._tileBuffer;for(let d=0;d<r*o*4;d+=4)c[d]=i,c[d+1]=a,c[d+2]=u,c[d+3]=255}_subTile(t,n,r,o,s){let i=s[0],a=s[1],u=s[2],c=t+r,d=n+o,p=this._tileBuffer,f=this._tileW;for(let h=n;h<d;h++)for(let g=t;g<c;g++){let x=(g+h*f)*4;p[x]=i,p[x+1]=a,p[x+2]=u,p[x+3]=255}}_finishTile(t){t.blitImage(this._tileX,this._tileY,this._tileW,this._tileH,this._tileBuffer,0)}};var ta=class{constructor(){this._zlib=new Yt,this._length=0}decodeRect(t,n,r,o,s,i,a){if(r===0||o===0)return!0;if(this._length===0){if(s.rQwait("ZLIB",4))return!1;this._length=s.rQshift32()}if(s.rQwait("ZLIB",this._length))return!1;let u=new Uint8Array(s.rQshiftBytes(this._length,!1));this._length=0,this._zlib.setInput(u),u=this._zlib.inflate(r*o*4),this._zlib.setInput(null);for(let c=0;c<r*o;c++)u[c*4+3]=255;return i.blitImage(t,n,r,o,u,0),!0}};var Ur=class{constructor(){this._ctl=null,this._filter=null,this._numColors=0,this._palette=new Uint8Array(1024),this._len=0,this._zlibs=[];for(let t=0;t<4;t++)this._zlibs[t]=new Yt}decodeRect(t,n,r,o,s,i,a){if(this._ctl===null){if(s.rQwait("TIGHT compression-control",1))return!1;this._ctl=s.rQshift8();for(let c=0;c<4;c++)this._ctl>>c&1&&(this._zlibs[c].reset(),Qe("Reset zlib stream "+c));this._ctl=this._ctl>>4}let u;if(this._ctl===8)u=this._fillRect(t,n,r,o,s,i,a);else if(this._ctl===9)u=this._jpegRect(t,n,r,o,s,i,a);else if(this._ctl===10)u=this._pngRect(t,n,r,o,s,i,a);else if((this._ctl&8)==0)u=this._basicRect(this._ctl,t,n,r,o,s,i,a);else throw new Error("Illegal tight compression received (ctl: "+this._ctl+")");return u&&(this._ctl=null),u}_fillRect(t,n,r,o,s,i,a){if(s.rQwait("TIGHT",3))return!1;let u=s.rQshiftBytes(3);return i.fillRect(t,n,r,o,u,!1),!0}_jpegRect(t,n,r,o,s,i,a){let u=this._readData(s);return u===null?!1:(i.imageRect(t,n,r,o,"image/jpeg",u),!0)}_pngRect(t,n,r,o,s,i,a){throw new Error("PNG received in standard Tight rect")}_basicRect(t,n,r,o,s,i,a,u){if(this._filter===null)if(t&4){if(i.rQwait("TIGHT",1))return!1;this._filter=i.rQshift8()}else this._filter=0;let c=t&3,d;switch(this._filter){case 0:d=this._copyFilter(c,n,r,o,s,i,a,u);break;case 1:d=this._paletteFilter(c,n,r,o,s,i,a,u);break;case 2:d=this._gradientFilter(c,n,r,o,s,i,a,u);break;default:throw new Error("Illegal tight filter received (ctl: "+this._filter+")")}return d&&(this._filter=null),d}_copyFilter(t,n,r,o,s,i,a,u){let c=o*s*3,d;if(c===0)return!0;if(c<12){if(i.rQwait("TIGHT",c))return!1;d=i.rQshiftBytes(c)}else{if(d=this._readData(i),d===null)return!1;this._zlibs[t].setInput(d),d=this._zlibs[t].inflate(c),this._zlibs[t].setInput(null)}let p=new Uint8Array(o*s*4);for(let f=0,h=0;f<o*s*4;f+=4,h+=3)p[f]=d[h],p[f+1]=d[h+1],p[f+2]=d[h+2],p[f+3]=255;return a.blitImage(n,r,o,s,p,0,!1),!0}_paletteFilter(t,n,r,o,s,i,a,u){if(this._numColors===0){if(i.rQwait("TIGHT palette",1))return!1;let h=i.rQpeek8()+1,g=h*3;if(i.rQwait("TIGHT palette",1+g))return!1;this._numColors=h,i.rQskipBytes(1),i.rQshiftTo(this._palette,g)}let c=this._numColors<=2?1:8,p=Math.floor((o*c+7)/8)*s,f;if(p===0)return!0;if(p<12){if(i.rQwait("TIGHT",p))return!1;f=i.rQshiftBytes(p)}else{if(f=this._readData(i),f===null)return!1;this._zlibs[t].setInput(f),f=this._zlibs[t].inflate(p),this._zlibs[t].setInput(null)}return this._numColors==2?this._monoRect(n,r,o,s,f,this._palette,a):this._paletteRect(n,r,o,s,f,this._palette,a),this._numColors=0,!0}_monoRect(t,n,r,o,s,i,a){let u=this._getScratchBuffer(r*o*4),c=Math.floor((r+7)/8),d=Math.floor(r/8);for(let p=0;p<o;p++){let f,h,g;for(g=0;g<d;g++)for(let x=7;x>=0;x--)f=(p*r+g*8+7-x)*4,h=(s[p*c+g]>>x&1)*3,u[f]=i[h],u[f+1]=i[h+1],u[f+2]=i[h+2],u[f+3]=255;for(let x=7;x>=8-r%8;x--)f=(p*r+g*8+7-x)*4,h=(s[p*c+g]>>x&1)*3,u[f]=i[h],u[f+1]=i[h+1],u[f+2]=i[h+2],u[f+3]=255}a.blitImage(t,n,r,o,u,0,!1)}_paletteRect(t,n,r,o,s,i,a){let u=this._getScratchBuffer(r*o*4),c=r*o*4;for(let d=0,p=0;d<c;d+=4,p++){let f=s[p]*3;u[d]=i[f],u[d+1]=i[f+1],u[d+2]=i[f+2],u[d+3]=255}a.blitImage(t,n,r,o,u,0,!1)}_gradientFilter(t,n,r,o,s,i,a,u){let c=o*s*3,d;if(c===0)return!0;if(c<12){if(i.rQwait("TIGHT",c))return!1;d=i.rQshiftBytes(c)}else{if(d=this._readData(i),d===null)return!1;this._zlibs[t].setInput(d),d=this._zlibs[t].inflate(c),this._zlibs[t].setInput(null)}let p=new Uint8Array(4*o*s),f=0,h=0,g=new Uint8Array(3);for(let w=0;w<o;w++){for(let C=0;C<3;C++){let y=g[C],T=d[h++]+y;p[f++]=T,g[C]=T}p[f++]=255}let x=0,b=new Uint8Array(3),v=new Uint8Array(3);for(let w=1;w<s;w++){g.fill(0),v.fill(0);for(let C=0;C<o;C++){for(let y=0;y<3;y++){b[y]=p[x++];let T=g[y]+b[y]-v[y];T<0?T=0:T>255&&(T=255);let N=d[h++]+T;p[f++]=N,v[y]=b[y],g[y]=N}p[f++]=255,x++}}return a.blitImage(n,r,o,s,p,0,!1),!0}_readData(t){if(this._len===0){if(t.rQwait("TIGHT",3))return null;let r;r=t.rQshift8(),this._len=r&127,r&128&&(r=t.rQshift8(),this._len|=(r&127)<<7,r&128&&(r=t.rQshift8(),this._len|=r<<14))}if(t.rQwait("TIGHT",this._len))return null;let n=t.rQshiftBytes(this._len,!1);return this._len=0,n}_getScratchBuffer(t){return(!this._scratchBuffer||this._scratchBuffer.length<t)&&(this._scratchBuffer=new Uint8Array(t)),this._scratchBuffer}};var na=class extends Ur{_pngRect(t,n,r,o,s,i,a){let u=this._readData(s);return u===null?!1:(i.imageRect(t,n,r,o,"image/png",u),!0)}_basicRect(t,n,r,o,s,i,a,u){throw new Error("BasicCompression received in TightPNG rect")}};var $c=64,Ic=64,ra=class{constructor(){this._length=0,this._inflator=new Yt,this._pixelBuffer=new Uint8Array($c*Ic*4),this._tileBuffer=new Uint8Array($c*Ic*4)}decodeRect(t,n,r,o,s,i,a){if(this._length===0){if(s.rQwait("ZLib data length",4))return!1;this._length=s.rQshift32()}if(s.rQwait("Zlib data",this._length))return!1;let u=s.rQshiftBytes(this._length,!1);this._inflator.setInput(u);for(let c=n;c<n+o;c+=Ic){let d=Math.min(Ic,n+o-c);for(let p=t;p<t+r;p+=$c){let f=Math.min($c,t+r-p),h=f*d,g=this._inflator.inflate(1)[0];if(g===0){let x=this._readPixels(h);i.blitImage(p,c,f,d,x,0,!1)}else if(g===1){let x=this._readPixels(1);i.fillRect(p,c,f,d,[x[0],x[1],x[2]])}else if(g>=2&&g<=16){let x=this._decodePaletteTile(g,h,f,d);i.blitImage(p,c,f,d,x,0,!1)}else if(g===128){let x=this._decodeRLETile(h);i.blitImage(p,c,f,d,x,0,!1)}else if(g>=130&&g<=255){let x=this._decodeRLEPaletteTile(g-128,h);i.blitImage(p,c,f,d,x,0,!1)}else throw new Error("Unknown subencoding: "+g)}}return this._length=0,!0}_getBitsPerPixelInPalette(t){if(t<=2)return 1;if(t<=4)return 2;if(t<=16)return 4}_readPixels(t){let n=this._pixelBuffer,r=this._inflator.inflate(3*t);for(let o=0,s=0;o<t*4;o+=4,s+=3)n[o]=r[s],n[o+1]=r[s+1],n[o+2]=r[s+2],n[o+3]=255;return n}_decodePaletteTile(t,n,r,o){let s=this._tileBuffer,i=this._readPixels(t),a=this._getBitsPerPixelInPalette(t),u=(1<<a)-1,c=0,d=this._inflator.inflate(1)[0];for(let p=0;p<o;p++){let f=8-a;for(let h=0;h<r;h++){f<0&&(f=8-a,d=this._inflator.inflate(1)[0]);let g=d>>f&u;s[c]=i[g*4],s[c+1]=i[g*4+1],s[c+2]=i[g*4+2],s[c+3]=i[g*4+3],c+=4,f-=a}f<8-a&&p<o-1&&(d=this._inflator.inflate(1)[0])}return s}_decodeRLETile(t){let n=this._tileBuffer,r=0;for(;r<t;){let o=this._readPixels(1),s=this._readRLELength();for(let i=0;i<s;i++)n[r*4]=o[0],n[r*4+1]=o[1],n[r*4+2]=o[2],n[r*4+3]=o[3],r++}return n}_decodeRLEPaletteTile(t,n){let r=this._tileBuffer,o=this._readPixels(t),s=0;for(;s<n;){let i=this._inflator.inflate(1)[0],a=1;if(i>=128&&(i-=128,a=this._readRLELength()),i>t)throw new Error("Too big index in palette: "+i+", palette size: "+t);if(s+a>n)throw new Error("Too big rle length in palette mode: "+a+", allowed length is: "+(n-s));for(let u=0;u<a;u++)r[s*4]=o[i*4],r[s*4+1]=o[i*4+1],r[s*4+2]=o[i*4+2],r[s*4+3]=o[i*4+3],s++}return r}_readRLELength(){let t=0,n=0;do n=this._inflator.inflate(1)[0],t+=n;while(n===255);return t+1}};var oa=class{constructor(){this._cachedQuantTables=[],this._cachedHuffmanTables=[],this._segments=[]}decodeRect(t,n,r,o,s,i,a){for(;;){let h=this._readSegment(s);if(h===null)return!1;if(this._segments.push(h),h[1]===217)break}let u=[],c=[];for(let h of this._segments){let g=h[1];g===196?u.push(h):g===219&&c.push(h)}let d=this._segments.findIndex(h=>h[1]==192||h[1]==194);if(d==-1)throw new Error("Illegal JPEG image without SOF");c.length===0&&this._segments.splice(d+1,0,...this._cachedQuantTables),u.length===0&&this._segments.splice(d+1,0,...this._cachedHuffmanTables);let p=0;for(let h of this._segments)p+=h.length;let f=new Uint8Array(p);p=0;for(let h of this._segments)f.set(h,p),p+=h.length;return i.imageRect(t,n,r,o,"image/jpeg",f),u.length!==0&&(this._cachedHuffmanTables=u),c.length!==0&&(this._cachedQuantTables=c),this._segments=[],!0}_readSegment(t){if(t.rQwait("JPEG",2))return null;let n=t.rQshift8();if(n!=255)throw new Error("Illegal JPEG marker received (byte: "+n+")");let r=t.rQshift8();if(r>=208&&r<=217||r==1)return new Uint8Array([n,r]);if(t.rQwait("JPEG",2,2))return null;let o=t.rQshift16();if(o<2)throw new Error("Illegal JPEG length received (length: "+o+")");if(t.rQwait("JPEG",o-2,4))return null;let s=0;if(r===218){if(t.rQwait("JPEG",o-2+2,4))return null;let a=t.rQlen(),u=t.rQpeekBytes(a,!1);for(;;){let c=u.indexOf(255,o-2+s);if(c===-1||c===a-1)return t.rQwait("JPEG",1/0,4),null;if(u.at(c+1)===0||u.at(c+1)>=208&&u.at(c+1)<=215){s=c+2-(o-2);continue}s=c-(o-2);break}}let i=new Uint8Array(2+o+s);return i[0]=n,i[1]=r,i[2]=o>>8,i[3]=o,i.set(t.rQshiftBytes(o-2+s,!1),4),i}};var xh=class{constructor(t){this._data=t,this._index=0,this.profileIdc=null,this.constraintSet=null,this.levelIdc=null}_getStartSequenceLen(t){let n=this._data;return n[t+0]==0&&n[t+1]==0&&n[t+2]==0&&n[t+3]==1?4:n[t+0]==0&&n[t+1]==0&&n[t+2]==1?3:0}_indexOfNextNalUnit(t){let n=this._data;for(let r=t;r<n.length;++r)if(this._getStartSequenceLen(r)!=0)return r;return-1}_parseSps(t){this.profileIdc=this._data[t],this.constraintSet=this._data[t+1],this.levelIdc=this._data[t+2]}_parseNalUnit(t){let n=this._data[t];if(n&128)throw new Error("H264 parsing sanity check failed, forbidden zero bit is set");let r=n&31;switch(r){case 1:return{slice:!0};case 5:return{slice:!0,key:!0};case 6:return{};case 7:return this._parseSps(t+1),{};case 8:return{};default:Ye("Unhandled unit type: ",r);break}return{}}parse(){let t=this._index,n=!1;for(;this._index<this._data.length;){let r=this._getStartSequenceLen(this._index);if(r==0)throw new Error("Invalid start sequence in bit stream");let{slice:o,key:s}=this._parseNalUnit(this._index+r),i=this._indexOfNextNalUnit(this._index+r);if(i==-1?this._index=this._data.length:this._index=i,s&&(n=!0),o)break}return t===this._index?null:{frame:this._data.subarray(t,this._index),key:n}}},bh=class{constructor(t,n){this.lastUsed=0,this._width=t,this._height=n,this._profileIdc=null,this._constraintSet=null,this._levelIdc=null,this._decoder=null,this._pendingFrames=[]}_handleFrame(t){let n=this._pendingFrames.shift();if(n===void 0)throw new Error("Pending frame queue empty when receiving frame from decoder");if(n.timestamp!=t.timestamp)throw new Error("Video frame timestamp mismatch. Expected "+t.timestamp+" but but got "+n.timestamp);n.frame=t,n.ready=!0,n.resolve(),n.keep||t.close()}_handleError(t){throw new Error("Failed to decode frame: "+t.message)}_configureDecoder(t,n,r){(this._decoder===null||this._decoder.state==="closed")&&(this._decoder=new VideoDecoder({output:s=>this._handleFrame(s),error:s=>this._handleError(s)}));let o="avc1."+t.toString(16).padStart(2,"0")+n.toString(16).padStart(2,"0")+r.toString(16).padStart(2,"0");this._decoder.configure({codec:o,codedWidth:this._width,codedHeight:this._height,optimizeForLatency:!0})}_preparePendingFrame(t){let n={timestamp:t,promise:null,resolve:null,frame:null,ready:!1,keep:!1};return n.promise=new Promise(r=>{n.resolve=r}),this._pendingFrames.push(n),n}decode(t){let n=new xh(t),r=null,o=Math.round(window.performance.now()*1e3);for(;;){let s=n.parse();if(s===null)break;if(n.profileIdc!==null&&(self._profileIdc=n.profileIdc,self._constraintSet=n.constraintSet,self._levelIdc=n.levelIdc),this._decoder===null||this._decoder.state!=="configured"){if(!s.key){Ye("Missing key frame. Can't decode until one arrives");continue}if(self._profileIdc===null){Ye("Cannot config decoder. Have not received SPS and PPS yet.");continue}this._configureDecoder(self._profileIdc,self._constraintSet,self._levelIdc)}r=this._preparePendingFrame(o);let i=new EncodedVideoChunk({timestamp:o,type:s.key?"key":"delta",data:s.frame});try{this._decoder.decode(i)}catch(a){Ye("Failed to decode:",a)}}return r!==null&&(r.keep=!0),r}},sa=class{constructor(){this._tick=0,this._contexts={}}_contextId(t,n,r,o){return[t,n,r,o].join(",")}_findOldestContextId(){let t=Number.MAX_VALUE,n;for(let[r,o]of Object.entries(this._contexts))o.lastUsed<t&&(t=o.lastUsed,n=r);return n}_createContext(t,n,r,o){if(Object.keys(this._contexts).length>=64){let a=this._findOldestContextId();delete this._contexts[a]}let i=new bh(r,o);return this._contexts[this._contextId(t,n,r,o)]=i,i}_getContext(t,n,r,o){let s=this._contexts[this._contextId(t,n,r,o)];return s!==void 0?s:this._createContext(t,n,r,o)}_resetContext(t,n,r,o){delete this._contexts[this._contextId(t,n,r,o)]}_resetAllContexts(){this._contexts={}}decodeRect(t,n,r,o,s,i,a){if(s.rQwait("h264 header",8))return!1;let d=s.rQshift32(),p=s.rQshift32();if(s.rQwait("h264 payload",d,8))return!1;p&2?this._resetAllContexts():p&1&&this._resetContext(t,n,r,o);let f=this._getContext(t,n,r,o);if(f.lastUsed=this._tick++,d!==0){let h=s.rQshiftBytes(d,!1),g=f.decode(h);g!==null&&i.videoFrame(t,n,r,o,g)}return!0}};var u$=3,d$="rgb(40, 40, 40)",Zw=17,Ww=50,jw=19,ia=75,or=50,p$=1e3,f$=50,Qw=1,Pc=2,Gw=6,Yw=16,yh=19,qw=22,Jw=30,ek=113,tk=129,nk=256,fn=1;var rk=1<<24,Oc=1<<25,ok=1<<26,aa=1<<27,Lc=1<<28,yt=class e extends Or{constructor(t,n,r){if(!t)throw new Error("Must specify target");if(!n)throw new Error("Must specify URL, WebSocket or RTCDataChannel");window.isSecureContext||Me("noVNC requires a secure context (TLS). Expect crashes!"),super(),this._target=t,typeof n=="string"?this._url=n:(this._url=null,this._rawChannel=n),r=r||{},this._rfbCredentials=r.credentials||{},this._shared="shared"in r?!!r.shared:!0,this._repeaterID=r.repeaterID||"",this._wsProtocols=r.wsProtocols||[],this._rfbConnectionState="",this._rfbInitState="",this._rfbAuthScheme=-1,this._rfbCleanDisconnect=!0,this._rfbRSAAESAuthenticationState=null,this._rfbVersion=0,this._rfbMaxVersion=3.8,this._rfbTightVNC=!1,this._rfbVeNCryptState=0,this._rfbXvpVer=0,this._fbWidth=0,this._fbHeight=0,this._fbName="",this._capabilities={power:!1},this._supportsFence=!1,this._supportsContinuousUpdates=!1,this._enabledContinuousUpdates=!1,this._supportsSetDesktopSize=!1,this._screenID=0,this._screenFlags=0,this._pendingRemoteResize=!1,this._lastResize=0,this._qemuExtKeyEventSupported=!1,this._extendedPointerEventSupported=!1,this._clipboardText=null,this._clipboardServerCapabilitiesActions={},this._clipboardServerCapabilitiesFormats={},this._sock=null,this._display=null,this._flushing=!1,this._keyboard=null,this._gestures=null,this._resizeObserver=null,this._disconnTimer=null,this._resizeTimeout=null,this._mouseMoveTimer=null,this._decoders={},this._FBU={rects:0,x:0,y:0,width:0,height:0,encoding:null},this._mousePos={},this._mouseButtonMask=0,this._mouseLastMoveTime=0,this._viewportDragging=!1,this._viewportDragPos={},this._viewportHasMoved=!1,this._accumulatedWheelDeltaX=0,this._accumulatedWheelDeltaY=0,this._gestureLastTapTime=null,this._gestureFirstDoubleTapEv=null,this._gestureLastMagnitudeX=0,this._gestureLastMagnitudeY=0,this._eventHandlers={focusCanvas:this._focusCanvas.bind(this),handleResize:this._handleResize.bind(this),handleMouse:this._handleMouse.bind(this),handleWheel:this._handleWheel.bind(this),handleGesture:this._handleGesture.bind(this),handleRSAAESCredentialsRequired:this._handleRSAAESCredentialsRequired.bind(this),handleRSAAESServerVerification:this._handleRSAAESServerVerification.bind(this)},de(">> RFB.constructor"),this._screen=document.createElement("div"),this._screen.style.display="flex",this._screen.style.width="100%",this._screen.style.height="100%",this._screen.style.overflow="auto",this._screen.style.background=d$,this._canvas=document.createElement("canvas"),this._canvas.style.margin="auto",this._canvas.style.outline="none",this._canvas.width=0,this._canvas.height=0,this._canvas.tabIndex=-1,this._screen.appendChild(this._canvas),this._cursor=new ji,this._cursorImage=e.cursors.none,this._decoders[ge.encodingRaw]=new Yi,this._decoders[ge.encodingCopyRect]=new qi,this._decoders[ge.encodingRRE]=new Ji,this._decoders[ge.encodingHextile]=new ea,this._decoders[ge.encodingZlib]=new ta,this._decoders[ge.encodingTight]=new Ur,this._decoders[ge.encodingTightPNG]=new na,this._decoders[ge.encodingZRLE]=new ra,this._decoders[ge.encodingJPEG]=new oa,this._decoders[ge.encodingH264]=new sa;try{this._display=new $i(this._canvas)}catch(o){throw Me("Display exception: "+o),o}this._keyboard=new Vi(this._canvas),this._keyboard.onkeyevent=this._handleKeyEvent.bind(this),this._remoteCapsLock=null,this._remoteNumLock=null,this._gestures=new Zi,this._sock=new Qi,this._sock.on("open",this._socketOpen.bind(this)),this._sock.on("close",this._socketClose.bind(this)),this._sock.on("message",this._handleMessage.bind(this)),this._sock.on("error",this._socketError.bind(this)),this._expectedClientWidth=null,this._expectedClientHeight=null,this._resizeObserver=new ResizeObserver(this._eventHandlers.handleResize),this._updateConnectionState("connecting"),de("<< RFB.constructor"),this.dragViewport=!1,this.focusOnClick=!0,this._viewOnly=!1,this._clipViewport=!1,this._clippingViewport=!1,this._scaleViewport=!1,this._resizeSession=!1,this._showDotCursor=!1,this._qualityLevel=6,this._compressionLevel=2}get viewOnly(){return this._viewOnly}set viewOnly(t){this._viewOnly=t,(this._rfbConnectionState==="connecting"||this._rfbConnectionState==="connected")&&(t?this._keyboard.ungrab():this._keyboard.grab())}get capabilities(){return this._capabilities}get clippingViewport(){return this._clippingViewport}_setClippingViewport(t){t!==this._clippingViewport&&(this._clippingViewport=t,this.dispatchEvent(new CustomEvent("clippingviewport",{detail:this._clippingViewport})))}get touchButton(){return 0}set touchButton(t){Ye("Using old API!")}get clipViewport(){return this._clipViewport}set clipViewport(t){this._clipViewport=t,this._updateClip()}get scaleViewport(){return this._scaleViewport}set scaleViewport(t){this._scaleViewport=t,t&&this._clipViewport&&this._updateClip(),this._updateScale(),!t&&this._clipViewport&&this._updateClip()}get resizeSession(){return this._resizeSession}set resizeSession(t){this._resizeSession=t,t&&this._requestRemoteResize()}get showDotCursor(){return this._showDotCursor}set showDotCursor(t){this._showDotCursor=t,this._refreshCursor()}get background(){return this._screen.style.background}set background(t){this._screen.style.background=t}get qualityLevel(){return this._qualityLevel}set qualityLevel(t){if(!Number.isInteger(t)||t<0||t>9){Me("qualityLevel must be an integer between 0 and 9");return}this._qualityLevel!==t&&(this._qualityLevel=t,this._rfbConnectionState==="connected"&&this._sendEncodings())}get compressionLevel(){return this._compressionLevel}set compressionLevel(t){if(!Number.isInteger(t)||t<0||t>9){Me("compressionLevel must be an integer between 0 and 9");return}this._compressionLevel!==t&&(this._compressionLevel=t,this._rfbConnectionState==="connected"&&this._sendEncodings())}disconnect(){this._updateConnectionState("disconnecting"),this._sock.off("error"),this._sock.off("message"),this._sock.off("open"),this._rfbRSAAESAuthenticationState!==null&&this._rfbRSAAESAuthenticationState.disconnect()}approveServer(){this._rfbRSAAESAuthenticationState!==null&&this._rfbRSAAESAuthenticationState.approveServer()}sendCredentials(t){this._rfbCredentials=t,this._resumeAuthentication()}sendCtrlAltDel(){this._rfbConnectionState!=="connected"||this._viewOnly||(Qe("Sending Ctrl-Alt-Del"),this.sendKey(A.XK_Control_L,"ControlLeft",!0),this.sendKey(A.XK_Alt_L,"AltLeft",!0),this.sendKey(A.XK_Delete,"Delete",!0),this.sendKey(A.XK_Delete,"Delete",!1),this.sendKey(A.XK_Alt_L,"AltLeft",!1),this.sendKey(A.XK_Control_L,"ControlLeft",!1))}machineShutdown(){this._xvpOp(1,2)}machineReboot(){this._xvpOp(1,3)}machineReset(){this._xvpOp(1,4)}sendKey(t,n,r){if(this._rfbConnectionState!=="connected"||this._viewOnly)return;if(r===void 0){this.sendKey(t,n,!0),this.sendKey(t,n,!1);return}let o=Lw[n];if(this._qemuExtKeyEventSupported&&o)t=t||0,Qe("Sending key ("+(r?"down":"up")+"): keysym "+t+", scancode "+o),e.messages.QEMUExtendedKeyEvent(this._sock,t,r,o);else{if(!t)return;Qe("Sending keysym ("+(r?"down":"up")+"): "+t),e.messages.keyEvent(this._sock,t,r?1:0)}}focus(t){this._canvas.focus(t)}blur(){this._canvas.blur()}clipboardPasteFrom(t){if(!(this._rfbConnectionState!=="connected"||this._viewOnly))if(this._clipboardServerCapabilitiesFormats[fn]&&this._clipboardServerCapabilitiesActions[aa])this._clipboardText=t,e.messages.extendedClipboardNotify(this._sock,[fn]);else{let n,r,o;n=0;for(let s of t)n++;o=new Uint8Array(n),r=0;for(let s of t){let i=s.codePointAt(0);i>255&&(i=63),o[r++]=i}e.messages.clientCutText(this._sock,o)}}getImageData(){return this._display.getImageData()}toDataURL(t,n){return this._display.toDataURL(t,n)}toBlob(t,n,r){return this._display.toBlob(t,n,r)}_connect(){if(de(">> RFB.connect"),this._url)Qe(`connecting to ${this._url}`),this._sock.open(this._url,this._wsProtocols);else{if(Qe(`attaching ${this._rawChannel} to Websock`),this._sock.attach(this._rawChannel),this._sock.readyState==="closed")throw Error("Cannot use already closed WebSocket/RTCDataChannel");this._sock.readyState==="open"&&this._socketOpen()}this._target.appendChild(this._screen),this._gestures.attach(this._canvas),this._cursor.attach(this._canvas),this._refreshCursor(),this._resizeObserver.observe(this._screen),this._canvas.addEventListener("mousedown",this._eventHandlers.focusCanvas),this._canvas.addEventListener("touchstart",this._eventHandlers.focusCanvas),this._canvas.addEventListener("mousedown",this._eventHandlers.handleMouse),this._canvas.addEventListener("mouseup",this._eventHandlers.handleMouse),this._canvas.addEventListener("mousemove",this._eventHandlers.handleMouse),this._canvas.addEventListener("click",this._eventHandlers.handleMouse),this._canvas.addEventListener("contextmenu",this._eventHandlers.handleMouse),this._canvas.addEventListener("wheel",this._eventHandlers.handleWheel),this._canvas.addEventListener("gesturestart",this._eventHandlers.handleGesture),this._canvas.addEventListener("gesturemove",this._eventHandlers.handleGesture),this._canvas.addEventListener("gestureend",this._eventHandlers.handleGesture),de("<< RFB.connect")}_disconnect(){de(">> RFB.disconnect"),this._cursor.detach(),this._canvas.removeEventListener("gesturestart",this._eventHandlers.handleGesture),this._canvas.removeEventListener("gesturemove",this._eventHandlers.handleGesture),this._canvas.removeEventListener("gestureend",this._eventHandlers.handleGesture),this._canvas.removeEventListener("wheel",this._eventHandlers.handleWheel),this._canvas.removeEventListener("mousedown",this._eventHandlers.handleMouse),this._canvas.removeEventListener("mouseup",this._eventHandlers.handleMouse),this._canvas.removeEventListener("mousemove",this._eventHandlers.handleMouse),this._canvas.removeEventListener("click",this._eventHandlers.handleMouse),this._canvas.removeEventListener("contextmenu",this._eventHandlers.handleMouse),this._canvas.removeEventListener("mousedown",this._eventHandlers.focusCanvas),this._canvas.removeEventListener("touchstart",this._eventHandlers.focusCanvas),this._resizeObserver.disconnect(),this._keyboard.ungrab(),this._gestures.detach(),this._sock.close();try{this._target.removeChild(this._screen)}catch(t){if(t.name!=="NotFoundError")throw t}clearTimeout(this._resizeTimeout),clearTimeout(this._mouseMoveTimer),de("<< RFB.disconnect")}_socketOpen(){this._rfbConnectionState==="connecting"&&this._rfbInitState===""?(this._rfbInitState="ProtocolVersion",de("Starting VNC handshake")):this._fail("Unexpected server connection while "+this._rfbConnectionState)}_socketClose(t){de("WebSocket on-close event");let n="";switch(t.code&&(n="(code: "+t.code,t.reason&&(n+=", reason: "+t.reason),n+=")"),this._rfbConnectionState){case"connecting":this._fail("Connection closed "+n);break;case"connected":this._updateConnectionState("disconnecting"),this._updateConnectionState("disconnected");break;case"disconnecting":this._updateConnectionState("disconnected");break;case"disconnected":this._fail("Unexpected server disconnect when already disconnected "+n);break;default:this._fail("Unexpected server disconnect before connecting "+n);break}this._sock.off("close"),this._rawChannel=null}_socketError(t){Ye("WebSocket on-error event")}_focusCanvas(t){this.focusOnClick&&this.focus({preventScroll:!0})}_setDesktopName(t){this._fbName=t,this.dispatchEvent(new CustomEvent("desktopname",{detail:{name:this._fbName}}))}_saveExpectedClientSize(){this._expectedClientWidth=this._screen.clientWidth,this._expectedClientHeight=this._screen.clientHeight}_currentClientSize(){return[this._screen.clientWidth,this._screen.clientHeight]}_clientHasExpectedSize(){let[t,n]=this._currentClientSize();return t==this._expectedClientWidth&&n==this._expectedClientHeight}_handleResize(){this._clientHasExpectedSize()||(window.requestAnimationFrame(()=>{this._updateClip(),this._updateScale(),this._saveExpectedClientSize()}),this._requestRemoteResize())}_updateClip(){let t=this._display.clipViewport,n=this._clipViewport;if(this._scaleViewport&&(n=!1),t!==n&&(this._display.clipViewport=n),n){let r=this._screenSize();this._display.viewportChangeSize(r.w,r.h),this._fixScrollbars(),this._setClippingViewport(r.w<this._display.width||r.h<this._display.height)}else this._setClippingViewport(!1);t!==n&&this._saveExpectedClientSize()}_updateScale(){if(!this._scaleViewport)this._display.scale=1;else{let t=this._screenSize();this._display.autoscale(t.w,t.h)}this._fixScrollbars()}_requestRemoteResize(){if(!this._resizeSession||this._viewOnly||!this._supportsSetDesktopSize||this._pendingRemoteResize)return;if(Date.now()-this._lastResize<100){clearTimeout(this._resizeTimeout),this._resizeTimeout=setTimeout(this._requestRemoteResize.bind(this),100-(Date.now()-this._lastResize));return}this._resizeTimeout=null;let t=this._screenSize();t.w===this._fbWidth&&t.h===this._fbHeight||(this._pendingRemoteResize=!0,this._lastResize=Date.now(),e.messages.setDesktopSize(this._sock,Math.floor(t.w),Math.floor(t.h),this._screenID,this._screenFlags),de("Requested new desktop size: "+t.w+"x"+t.h))}_screenSize(){let t=this._screen.getBoundingClientRect();return{w:t.width,h:t.height}}_fixScrollbars(){let t=this._screen.style.overflow;this._screen.style.overflow="hidden",this._screen.getBoundingClientRect(),this._screen.style.overflow=t}_updateConnectionState(t){let n=this._rfbConnectionState;if(t===n){de("Already in state '"+t+"', ignoring");return}if(n==="disconnected"){Me("Tried changing state of a disconnected RFB object");return}switch(t){case"connected":if(n!=="connecting"){Me("Bad transition to connected state, previous connection state: "+n);return}break;case"disconnected":if(n!=="disconnecting"){Me("Bad transition to disconnected state, previous connection state: "+n);return}break;case"connecting":if(n!==""){Me("Bad transition to connecting state, previous connection state: "+n);return}break;case"disconnecting":if(n!=="connected"&&n!=="connecting"){Me("Bad transition to disconnecting state, previous connection state: "+n);return}break;default:Me("Unknown connection state: "+t);return}switch(this._rfbConnectionState=t,de("New state '"+t+"', was '"+n+"'."),this._disconnTimer&&t!=="disconnecting"&&(de("Clearing disconnect timer"),clearTimeout(this._disconnTimer),this._disconnTimer=null,this._sock.off("close")),t){case"connecting":this._connect();break;case"connected":this.dispatchEvent(new CustomEvent("connect",{detail:{}}));break;case"disconnecting":this._disconnect(),this._disconnTimer=setTimeout(()=>{Me("Disconnection timed out."),this._updateConnectionState("disconnected")},u$*1e3);break;case"disconnected":this.dispatchEvent(new CustomEvent("disconnect",{detail:{clean:this._rfbCleanDisconnect}}));break}}_fail(t){switch(this._rfbConnectionState){case"disconnecting":Me("Failed when disconnecting: "+t);break;case"connected":Me("Failed while connected: "+t);break;case"connecting":Me("Failed when connecting: "+t);break;default:Me("RFB failure: "+t);break}return this._rfbCleanDisconnect=!1,this._updateConnectionState("disconnecting"),this._updateConnectionState("disconnected"),!1}_setCapability(t,n){this._capabilities[t]=n,this.dispatchEvent(new CustomEvent("capabilities",{detail:{capabilities:this._capabilities}}))}_handleMessage(){if(this._sock.rQwait("message",1)){Ye("handleMessage called on an empty receive queue");return}switch(this._rfbConnectionState){case"disconnected":Me("Got data while disconnected");break;case"connected":for(;!(this._flushing||!this._normalMsg()||this._sock.rQwait("message",1)););break;case"connecting":for(;this._rfbConnectionState==="connecting"&&this._initMsg(););break;default:Me("Got data while in an invalid state");break}}_handleKeyEvent(t,n,r,o,s){n=="CapsLock"&&r&&(this._remoteCapsLock=null),this._remoteCapsLock!==null&&s!==null&&this._remoteCapsLock!==s&&r&&(de("Fixing remote caps lock"),this.sendKey(A.XK_Caps_Lock,"CapsLock",!0),this.sendKey(A.XK_Caps_Lock,"CapsLock",!1),this._remoteCapsLock=null),n=="NumLock"&&r&&(this._remoteNumLock=null),this._remoteNumLock!==null&&o!==null&&this._remoteNumLock!==o&&r&&(de("Fixing remote num lock"),this.sendKey(A.XK_Num_Lock,"NumLock",!0),this.sendKey(A.XK_Num_Lock,"NumLock",!1),this._remoteNumLock=null),this.sendKey(t,n,r)}static _convertButtonMask(t){let n={0:1,1:4,2:2,3:128,4:256},r=0;for(let o=0;o<5;o++)t&1<<o&&(r|=n[o]);return r}_handleMouse(t){if(t.type==="click"&&t.target!==this._canvas||(t.stopPropagation(),t.preventDefault(),t.type==="click"||t.type==="contextmenu"))return;let n=Do(t.clientX,t.clientY,this._canvas),r=e._convertButtonMask(t.buttons),o=t.type=="mousedown";switch(t.type){case"mousedown":case"mouseup":if(this.dragViewport)if(o&&!this._viewportDragging){this._viewportDragging=!0,this._viewportDragPos={x:n.x,y:n.y},this._viewportHasMoved=!1,this._flushMouseMoveTimer(n.x,n.y),this._mouseButtonMask=r;break}else{if(this._viewportDragging=!1,this._viewportHasMoved){this._mouseButtonMask=r;break}this._sendMouse(n.x,n.y,this._mouseButtonMask)}o&&mv(this._canvas),this._handleMouseButton(n.x,n.y,r);break;case"mousemove":if(this._viewportDragging){let s=this._viewportDragPos.x-n.x,i=this._viewportDragPos.y-n.y;(this._viewportHasMoved||Math.abs(s)>Ri||Math.abs(i)>Ri)&&(this._viewportHasMoved=!0,this._viewportDragPos={x:n.x,y:n.y},this._display.viewportChangePos(s,i));break}this._handleMouseMove(n.x,n.y);break}}_handleMouseButton(t,n,r){this._flushMouseMoveTimer(t,n),this._mouseButtonMask=r,this._sendMouse(t,n,this._mouseButtonMask)}_handleMouseMove(t,n){if(this._mousePos={x:t,y:n},this._mouseMoveTimer==null){let r=Date.now()-this._mouseLastMoveTime;r>Zw?(this._sendMouse(t,n,this._mouseButtonMask),this._mouseLastMoveTime=Date.now()):this._mouseMoveTimer=setTimeout(()=>{this._handleDelayedMouseMove()},Zw-r)}}_handleDelayedMouseMove(){this._mouseMoveTimer=null,this._sendMouse(this._mousePos.x,this._mousePos.y,this._mouseButtonMask),this._mouseLastMoveTime=Date.now()}_sendMouse(t,n,r){if(this._rfbConnectionState!=="connected"||this._viewOnly)return;if(r&32768)throw new Error("Illegal mouse button mask (mask: "+r+")");let o=r&32640;this._extendedPointerEventSupported&&o?e.messages.extendedPointerEvent(this._sock,this._display.absX(t),this._display.absY(n),r):e.messages.pointerEvent(this._sock,this._display.absX(t),this._display.absY(n),r)}_handleWheel(t){if(this._rfbConnectionState!=="connected"||this._viewOnly)return;t.stopPropagation(),t.preventDefault();let n=Do(t.clientX,t.clientY,this._canvas),r=e._convertButtonMask(t.buttons),o=t.deltaX,s=t.deltaY;t.deltaMode!==0&&(o*=jw,s*=jw),this._accumulatedWheelDeltaX+=o,this._accumulatedWheelDeltaY+=s,Math.abs(this._accumulatedWheelDeltaX)>=Ww&&(this._accumulatedWheelDeltaX<0?(this._handleMouseButton(n.x,n.y,r|32),this._handleMouseButton(n.x,n.y,r)):this._accumulatedWheelDeltaX>0&&(this._handleMouseButton(n.x,n.y,r|64),this._handleMouseButton(n.x,n.y,r)),this._accumulatedWheelDeltaX=0),Math.abs(this._accumulatedWheelDeltaY)>=Ww&&(this._accumulatedWheelDeltaY<0?(this._handleMouseButton(n.x,n.y,r|8),this._handleMouseButton(n.x,n.y,r)):this._accumulatedWheelDeltaY>0&&(this._handleMouseButton(n.x,n.y,r|16),this._handleMouseButton(n.x,n.y,r)),this._accumulatedWheelDeltaY=0)}_fakeMouseMove(t,n,r){this._handleMouseMove(n,r),this._cursor.move(t.detail.clientX,t.detail.clientY)}_handleTapEvent(t,n){let r=Do(t.detail.clientX,t.detail.clientY,this._canvas);if(this._gestureLastTapTime!==null&&Date.now()-this._gestureLastTapTime<p$&&this._gestureFirstDoubleTapEv.detail.type===t.detail.type){let o=this._gestureFirstDoubleTapEv.detail.clientX-t.detail.clientX,s=this._gestureFirstDoubleTapEv.detail.clientY-t.detail.clientY;Math.hypot(o,s)<f$?r=Do(this._gestureFirstDoubleTapEv.detail.clientX,this._gestureFirstDoubleTapEv.detail.clientY,this._canvas):this._gestureFirstDoubleTapEv=t}else this._gestureFirstDoubleTapEv=t;this._gestureLastTapTime=Date.now(),this._fakeMouseMove(this._gestureFirstDoubleTapEv,r.x,r.y),this._handleMouseButton(r.x,r.y,n),this._handleMouseButton(r.x,r.y,0)}_handleGesture(t){let n,r=Do(t.detail.clientX,t.detail.clientY,this._canvas);switch(t.type){case"gesturestart":switch(t.detail.type){case"onetap":this._handleTapEvent(t,1);break;case"twotap":this._handleTapEvent(t,4);break;case"threetap":this._handleTapEvent(t,2);break;case"drag":this.dragViewport?(this._viewportHasMoved=!1,this._viewportDragging=!0,this._viewportDragPos={x:r.x,y:r.y}):(this._fakeMouseMove(t,r.x,r.y),this._handleMouseButton(r.x,r.y,1));break;case"longpress":this.dragViewport?(this._viewportHasMoved=!1,this._viewportDragPos={x:r.x,y:r.y}):(this._fakeMouseMove(t,r.x,r.y),this._handleMouseButton(r.x,r.y,4));break;case"twodrag":this._gestureLastMagnitudeX=t.detail.magnitudeX,this._gestureLastMagnitudeY=t.detail.magnitudeY,this._fakeMouseMove(t,r.x,r.y);break;case"pinch":this._gestureLastMagnitudeX=Math.hypot(t.detail.magnitudeX,t.detail.magnitudeY),this._fakeMouseMove(t,r.x,r.y);break}break;case"gesturemove":switch(t.detail.type){case"onetap":case"twotap":case"threetap":break;case"drag":case"longpress":if(this.dragViewport){this._viewportDragging=!0;let o=this._viewportDragPos.x-r.x,s=this._viewportDragPos.y-r.y;(this._viewportHasMoved||Math.abs(o)>Ri||Math.abs(s)>Ri)&&(this._viewportHasMoved=!0,this._viewportDragPos={x:r.x,y:r.y},this._display.viewportChangePos(o,s))}else this._fakeMouseMove(t,r.x,r.y);break;case"twodrag":for(this._fakeMouseMove(t,r.x,r.y);t.detail.magnitudeY-this._gestureLastMagnitudeY>or;)this._handleMouseButton(r.x,r.y,8),this._handleMouseButton(r.x,r.y,0),this._gestureLastMagnitudeY+=or;for(;t.detail.magnitudeY-this._gestureLastMagnitudeY<-or;)this._handleMouseButton(r.x,r.y,16),this._handleMouseButton(r.x,r.y,0),this._gestureLastMagnitudeY-=or;for(;t.detail.magnitudeX-this._gestureLastMagnitudeX>or;)this._handleMouseButton(r.x,r.y,32),this._handleMouseButton(r.x,r.y,0),this._gestureLastMagnitudeX+=or;for(;t.detail.magnitudeX-this._gestureLastMagnitudeX<-or;)this._handleMouseButton(r.x,r.y,64),this._handleMouseButton(r.x,r.y,0),this._gestureLastMagnitudeX-=or;break;case"pinch":if(this._fakeMouseMove(t,r.x,r.y),n=Math.hypot(t.detail.magnitudeX,t.detail.magnitudeY),Math.abs(n-this._gestureLastMagnitudeX)>ia){for(this._handleKeyEvent(A.XK_Control_L,"ControlLeft",!0);n-this._gestureLastMagnitudeX>ia;)this._handleMouseButton(r.x,r.y,8),this._handleMouseButton(r.x,r.y,0),this._gestureLastMagnitudeX+=ia;for(;n-this._gestureLastMagnitudeX<-ia;)this._handleMouseButton(r.x,r.y,16),this._handleMouseButton(r.x,r.y,0),this._gestureLastMagnitudeX-=ia}this._handleKeyEvent(A.XK_Control_L,"ControlLeft",!1);break}break;case"gestureend":switch(t.detail.type){case"onetap":case"twotap":case"threetap":case"pinch":case"twodrag":break;case"drag":this.dragViewport?this._viewportDragging=!1:(this._fakeMouseMove(t,r.x,r.y),this._handleMouseButton(r.x,r.y,0));break;case"longpress":if(this._viewportHasMoved)break;this.dragViewport&&!this._viewportHasMoved?(this._fakeMouseMove(t,r.x,r.y),this._handleMouseButton(r.x,r.y,4),this._handleMouseButton(r.x,r.y,0),this._viewportDragging=!1):(this._fakeMouseMove(t,r.x,r.y),this._handleMouseButton(r.x,r.y,0));break}break}}_flushMouseMoveTimer(t,n){this._mouseMoveTimer!==null&&(clearTimeout(this._mouseMoveTimer),this._mouseMoveTimer=null,this._sendMouse(t,n,this._mouseButtonMask))}_negotiateProtocolVersion(){if(this._sock.rQwait("version",12))return!1;let t=this._sock.rQshiftStr(12).substr(4,7);Qe("Server ProtocolVersion: "+t);let n=0;switch(t){case"000.000":n=1;break;case"003.003":case"003.006":this._rfbVersion=3.3;break;case"003.007":this._rfbVersion=3.7;break;case"003.008":case"003.889":case"004.000":case"004.001":case"005.000":this._rfbVersion=3.8;break;default:return this._fail("Invalid server version "+t)}if(n){let o="ID:"+this._repeaterID;for(;o.length<250;)o+="\0";return this._sock.sQpushString(o),this._sock.flush(),!0}this._rfbVersion>this._rfbMaxVersion&&(this._rfbVersion=this._rfbMaxVersion);let r="00"+parseInt(this._rfbVersion,10)+".00"+this._rfbVersion*10%10;this._sock.sQpushString("RFB "+r+`
2
- `),this._sock.flush(),de("Sent ProtocolVersion: "+r),this._rfbInitState="Security"}_isSupportedSecurityType(t){return[Qw,Pc,Gw,Yw,yh,qw,Jw,ek,nk].includes(t)}_negotiateSecurity(){if(this._rfbVersion>=3.7){let t=this._sock.rQshift8();if(this._sock.rQwait("security type",t,1))return!1;if(t===0)return this._rfbInitState="SecurityReason",this._securityContext="no security types",this._securityStatus=1,!0;let n=this._sock.rQshiftBytes(t);de("Server security types: "+n),this._rfbAuthScheme=-1;for(let r of n)if(this._isSupportedSecurityType(r)){this._rfbAuthScheme=r;break}if(this._rfbAuthScheme===-1)return this._fail("Unsupported security types (types: "+n+")");this._sock.sQpush8(this._rfbAuthScheme),this._sock.flush()}else{if(this._sock.rQwait("security scheme",4))return!1;if(this._rfbAuthScheme=this._sock.rQshift32(),this._rfbAuthScheme==0)return this._rfbInitState="SecurityReason",this._securityContext="authentication scheme",this._securityStatus=1,!0}return this._rfbInitState="Authentication",de("Authenticating using scheme: "+this._rfbAuthScheme),!0}_handleSecurityReason(){if(this._sock.rQwait("reason length",4))return!1;let t=this._sock.rQshift32(),n="";if(t>0){if(this._sock.rQwait("reason",t,4))return!1;n=this._sock.rQshiftStr(t)}return n!==""?(this.dispatchEvent(new CustomEvent("securityfailure",{detail:{status:this._securityStatus,reason:n}})),this._fail("Security negotiation failed on "+this._securityContext+" (reason: "+n+")")):(this.dispatchEvent(new CustomEvent("securityfailure",{detail:{status:this._securityStatus}})),this._fail("Security negotiation failed on "+this._securityContext))}_negotiateXvpAuth(){return this._rfbCredentials.username===void 0||this._rfbCredentials.password===void 0||this._rfbCredentials.target===void 0?(this.dispatchEvent(new CustomEvent("credentialsrequired",{detail:{types:["username","password","target"]}})),!1):(this._sock.sQpush8(this._rfbCredentials.username.length),this._sock.sQpush8(this._rfbCredentials.target.length),this._sock.sQpushString(this._rfbCredentials.username),this._sock.sQpushString(this._rfbCredentials.target),this._sock.flush(),this._rfbAuthScheme=Pc,this._negotiateAuthentication())}_negotiateVeNCryptAuth(){if(this._rfbVeNCryptState==0){if(this._sock.rQwait("vencrypt version",2))return!1;let t=this._sock.rQshift8(),n=this._sock.rQshift8();if(!(t==0&&n==2))return this._fail("Unsupported VeNCrypt version "+t+"."+n);this._sock.sQpush8(0),this._sock.sQpush8(2),this._sock.flush(),this._rfbVeNCryptState=1}if(this._rfbVeNCryptState==1){if(this._sock.rQwait("vencrypt ack",1))return!1;let t=this._sock.rQshift8();if(t!=0)return this._fail("VeNCrypt failure "+t);this._rfbVeNCryptState=2}if(this._rfbVeNCryptState==2){if(this._sock.rQwait("vencrypt subtypes length",1))return!1;let t=this._sock.rQshift8();if(t<1)return this._fail("VeNCrypt subtypes empty");this._rfbVeNCryptSubtypesLength=t,this._rfbVeNCryptState=3}if(this._rfbVeNCryptState==3){if(this._sock.rQwait("vencrypt subtypes",4*this._rfbVeNCryptSubtypesLength))return!1;let t=[];for(let n=0;n<this._rfbVeNCryptSubtypesLength;n++)t.push(this._sock.rQshift32());this._rfbAuthScheme=-1;for(let n of t)if(n!==yh&&this._isSupportedSecurityType(n)){this._rfbAuthScheme=n;break}return this._rfbAuthScheme===-1?this._fail("Unsupported security types (types: "+t+")"):(this._sock.sQpush32(this._rfbAuthScheme),this._sock.flush(),this._rfbVeNCryptState=4,!0)}}_negotiatePlainAuth(){if(this._rfbCredentials.username===void 0||this._rfbCredentials.password===void 0)return this.dispatchEvent(new CustomEvent("credentialsrequired",{detail:{types:["username","password"]}})),!1;let t=Gt(this._rfbCredentials.username),n=Gt(this._rfbCredentials.password);return this._sock.sQpush32(t.length),this._sock.sQpush32(n.length),this._sock.sQpushString(t),this._sock.sQpushString(n),this._sock.flush(),this._rfbInitState="SecurityResult",!0}_negotiateStdVNCAuth(){if(this._sock.rQwait("auth challenge",16))return!1;if(this._rfbCredentials.password===void 0)return this.dispatchEvent(new CustomEvent("credentialsrequired",{detail:{types:["password"]}})),!1;let t=Array.prototype.slice.call(this._sock.rQshiftBytes(16)),n=e.genDES(this._rfbCredentials.password,t);return this._sock.sQpushBytes(n),this._sock.flush(),this._rfbInitState="SecurityResult",!0}_negotiateARDAuth(){if(this._rfbCredentials.username===void 0||this._rfbCredentials.password===void 0)return this.dispatchEvent(new CustomEvent("credentialsrequired",{detail:{types:["username","password"]}})),!1;if(this._rfbCredentials.ardPublicKey!=null&&this._rfbCredentials.ardCredentials!=null)return this._sock.sQpushBytes(this._rfbCredentials.ardCredentials),this._sock.sQpushBytes(this._rfbCredentials.ardPublicKey),this._sock.flush(),this._rfbCredentials.ardCredentials=null,this._rfbCredentials.ardPublicKey=null,this._rfbInitState="SecurityResult",!0;if(this._sock.rQwait("read ard",4))return!1;let t=this._sock.rQshiftBytes(2),n=this._sock.rQshift16();if(this._sock.rQwait("read ard keylength",n*2,4))return!1;let r=this._sock.rQshiftBytes(n),o=this._sock.rQshiftBytes(n),s=Xe.generateKey({name:"DH",g:t,p:r},!1,["deriveBits"]);return this._negotiateARDAuthAsync(n,o,s),!1}async _negotiateARDAuthAsync(t,n,r){let o=Xe.exportKey("raw",r.publicKey),s=Xe.deriveBits({name:"DH",public:n},r.privateKey,t*8),i=Gt(this._rfbCredentials.username).substring(0,63),a=Gt(this._rfbCredentials.password).substring(0,63),u=window.crypto.getRandomValues(new Uint8Array(128));for(let f=0;f<i.length;f++)u[f]=i.charCodeAt(f);u[i.length]=0;for(let f=0;f<a.length;f++)u[64+f]=a.charCodeAt(f);u[64+a.length]=0;let c=await Xe.digest("MD5",s),d=await Xe.importKey("raw",c,{name:"AES-ECB"},!1,["encrypt"]),p=await Xe.encrypt({name:"AES-ECB"},d,u);this._rfbCredentials.ardCredentials=p,this._rfbCredentials.ardPublicKey=o,this._resumeAuthentication()}_negotiateTightUnixAuth(){return this._rfbCredentials.username===void 0||this._rfbCredentials.password===void 0?(this.dispatchEvent(new CustomEvent("credentialsrequired",{detail:{types:["username","password"]}})),!1):(this._sock.sQpush32(this._rfbCredentials.username.length),this._sock.sQpush32(this._rfbCredentials.password.length),this._sock.sQpushString(this._rfbCredentials.username),this._sock.sQpushString(this._rfbCredentials.password),this._sock.flush(),this._rfbInitState="SecurityResult",!0)}_negotiateTightTunnels(t){let n={0:{vendor:"TGHT",signature:"NOTUNNEL"}},r={};for(let o=0;o<t;o++){let s=this._sock.rQshift32(),i=this._sock.rQshiftStr(4),a=this._sock.rQshiftStr(8);r[s]={vendor:i,signature:a}}return de("Server Tight tunnel types: "+r),r[1]&&r[1].vendor==="SICR"&&r[1].signature==="SCHANNEL"&&(de("Detected Siemens server. Assuming NOTUNNEL support."),r[0]={vendor:"TGHT",signature:"NOTUNNEL"}),r[0]?r[0].vendor!=n[0].vendor||r[0].signature!=n[0].signature?this._fail("Client's tunnel type had the incorrect vendor or signature"):(de("Selected tunnel type: "+n[0]),this._sock.sQpush32(0),this._sock.flush(),!1):this._fail("Server wanted tunnels, but doesn't support the notunnel type")}_negotiateTightAuth(){if(!this._rfbTightVNC){if(this._sock.rQwait("num tunnels",4))return!1;let o=this._sock.rQshift32();if(o>0&&this._sock.rQwait("tunnel capabilities",16*o,4))return!1;if(this._rfbTightVNC=!0,o>0)return this._negotiateTightTunnels(o),!1}if(this._sock.rQwait("sub auth count",4))return!1;let t=this._sock.rQshift32();if(t===0)return this._rfbInitState="SecurityResult",!0;if(this._sock.rQwait("sub auth capabilities",16*t,4))return!1;let n={STDVNOAUTH__:1,STDVVNCAUTH_:2,TGHTULGNAUTH:129},r=[];for(let o=0;o<t;o++){this._sock.rQshift32();let s=this._sock.rQshiftStr(12);r.push(s)}de("Server Tight authentication types: "+r);for(let o in n)if(r.indexOf(o)!=-1)switch(this._sock.sQpush32(n[o]),this._sock.flush(),de("Selected authentication type: "+o),o){case"STDVNOAUTH__":return this._rfbInitState="SecurityResult",!0;case"STDVVNCAUTH_":return this._rfbAuthScheme=Pc,!0;case"TGHTULGNAUTH":return this._rfbAuthScheme=tk,!0;default:return this._fail("Unsupported tiny auth scheme (scheme: "+o+")")}return this._fail("No supported sub-auth types!")}_handleRSAAESCredentialsRequired(t){this.dispatchEvent(t)}_handleRSAAESServerVerification(t){this.dispatchEvent(t)}_negotiateRA2neAuth(){return this._rfbRSAAESAuthenticationState===null&&(this._rfbRSAAESAuthenticationState=new Gi(this._sock,()=>this._rfbCredentials),this._rfbRSAAESAuthenticationState.addEventListener("serververification",this._eventHandlers.handleRSAAESServerVerification),this._rfbRSAAESAuthenticationState.addEventListener("credentialsrequired",this._eventHandlers.handleRSAAESCredentialsRequired)),this._rfbRSAAESAuthenticationState.checkInternalEvents(),this._rfbRSAAESAuthenticationState.hasStarted||this._rfbRSAAESAuthenticationState.negotiateRA2neAuthAsync().catch(t=>{t.message!=="disconnect normally"&&this._fail(t.message)}).then(()=>(this._rfbInitState="SecurityResult",!0)).finally(()=>{this._rfbRSAAESAuthenticationState.removeEventListener("serververification",this._eventHandlers.handleRSAAESServerVerification),this._rfbRSAAESAuthenticationState.removeEventListener("credentialsrequired",this._eventHandlers.handleRSAAESCredentialsRequired),this._rfbRSAAESAuthenticationState=null}),!1}_negotiateMSLogonIIAuth(){if(this._sock.rQwait("mslogonii dh param",24))return!1;if(this._rfbCredentials.username===void 0||this._rfbCredentials.password===void 0)return this.dispatchEvent(new CustomEvent("credentialsrequired",{detail:{types:["username","password"]}})),!1;let t=this._sock.rQshiftBytes(8),n=this._sock.rQshiftBytes(8),r=this._sock.rQshiftBytes(8),o=Xe.generateKey({name:"DH",g:t,p:n},!0,["deriveBits"]),s=Xe.exportKey("raw",o.publicKey),i=Xe.deriveBits({name:"DH",public:r},o.privateKey,64),a=Xe.importKey("raw",i,{name:"DES-CBC"},!1,["encrypt"]),u=Gt(this._rfbCredentials.username).substring(0,255),c=Gt(this._rfbCredentials.password).substring(0,63),d=new Uint8Array(256),p=new Uint8Array(64);window.crypto.getRandomValues(d),window.crypto.getRandomValues(p);for(let f=0;f<u.length;f++)d[f]=u.charCodeAt(f);d[u.length]=0;for(let f=0;f<c.length;f++)p[f]=c.charCodeAt(f);return p[c.length]=0,d=Xe.encrypt({name:"DES-CBC",iv:i},a,d),p=Xe.encrypt({name:"DES-CBC",iv:i},a,p),this._sock.sQpushBytes(s),this._sock.sQpushBytes(d),this._sock.sQpushBytes(p),this._sock.flush(),this._rfbInitState="SecurityResult",!0}_negotiateAuthentication(){switch(this._rfbAuthScheme){case Qw:return this._rfbVersion>=3.8?this._rfbInitState="SecurityResult":this._rfbInitState="ClientInitialisation",!0;case qw:return this._negotiateXvpAuth();case Jw:return this._negotiateARDAuth();case Pc:return this._negotiateStdVNCAuth();case Yw:return this._negotiateTightAuth();case yh:return this._negotiateVeNCryptAuth();case nk:return this._negotiatePlainAuth();case tk:return this._negotiateTightUnixAuth();case Gw:return this._negotiateRA2neAuth();case ek:return this._negotiateMSLogonIIAuth();default:return this._fail("Unsupported auth scheme (scheme: "+this._rfbAuthScheme+")")}}_handleSecurityResult(){if(this._sock.rQwait("VNC auth response ",4))return!1;let t=this._sock.rQshift32();return t===0?(this._rfbInitState="ClientInitialisation",de("Authentication OK"),!0):this._rfbVersion>=3.8?(this._rfbInitState="SecurityReason",this._securityContext="security result",this._securityStatus=t,!0):(this.dispatchEvent(new CustomEvent("securityfailure",{detail:{status:t}})),this._fail("Security handshake failed"))}_negotiateServerInit(){if(this._sock.rQwait("server initialization",24))return!1;let t=this._sock.rQshift16(),n=this._sock.rQshift16(),r=this._sock.rQshift8(),o=this._sock.rQshift8(),s=this._sock.rQshift8(),i=this._sock.rQshift8(),a=this._sock.rQshift16(),u=this._sock.rQshift16(),c=this._sock.rQshift16(),d=this._sock.rQshift8(),p=this._sock.rQshift8(),f=this._sock.rQshift8();this._sock.rQskipBytes(3);let h=this._sock.rQshift32();if(this._sock.rQwait("server init name",h,24))return!1;let g=this._sock.rQshiftStr(h);if(g=ic(g,!0),this._rfbTightVNC){if(this._sock.rQwait("TightVNC extended server init header",8,24+h))return!1;let x=this._sock.rQshift16(),b=this._sock.rQshift16(),v=this._sock.rQshift16();this._sock.rQskipBytes(2);let w=(x+b+v)*16;if(this._sock.rQwait("TightVNC extended server init header",w,32+h))return!1;this._sock.rQskipBytes(16*x),this._sock.rQskipBytes(16*b),this._sock.rQskipBytes(16*v)}return Qe("Screen: "+t+"x"+n+", bpp: "+r+", depth: "+o+", bigEndian: "+s+", trueColor: "+i+", redMax: "+a+", greenMax: "+u+", blueMax: "+c+", redShift: "+d+", greenShift: "+p+", blueShift: "+f),this._setDesktopName(g),this._resize(t,n),this._viewOnly||this._keyboard.grab(),this._fbDepth=24,this._fbName==="Intel(r) AMT KVM"&&(Ye("Intel AMT KVM only supports 8/16 bit depths. Using low color mode."),this._fbDepth=8),e.messages.pixelFormat(this._sock,this._fbDepth,!0),this._sendEncodings(),e.messages.fbUpdateRequest(this._sock,!1,0,0,this._fbWidth,this._fbHeight),this._updateConnectionState("connected"),!0}_sendEncodings(){let t=[];t.push(ge.encodingCopyRect),this._fbDepth==24&&(Mf&&t.push(ge.encodingH264),t.push(ge.encodingTight),t.push(ge.encodingTightPNG),t.push(ge.encodingZRLE),t.push(ge.encodingJPEG),t.push(ge.encodingHextile),t.push(ge.encodingRRE),t.push(ge.encodingZlib)),t.push(ge.encodingRaw),t.push(ge.pseudoEncodingQualityLevel0+this._qualityLevel),t.push(ge.pseudoEncodingCompressLevel0+this._compressionLevel),t.push(ge.pseudoEncodingDesktopSize),t.push(ge.pseudoEncodingLastRect),t.push(ge.pseudoEncodingQEMUExtendedKeyEvent),t.push(ge.pseudoEncodingQEMULedEvent),t.push(ge.pseudoEncodingExtendedDesktopSize),t.push(ge.pseudoEncodingXvp),t.push(ge.pseudoEncodingFence),t.push(ge.pseudoEncodingContinuousUpdates),t.push(ge.pseudoEncodingDesktopName),t.push(ge.pseudoEncodingExtendedClipboard),t.push(ge.pseudoEncodingExtendedMouseButtons),this._fbDepth==24&&(t.push(ge.pseudoEncodingVMwareCursor),t.push(ge.pseudoEncodingCursor)),e.messages.clientEncodings(this._sock,t)}_initMsg(){switch(this._rfbInitState){case"ProtocolVersion":return this._negotiateProtocolVersion();case"Security":return this._negotiateSecurity();case"Authentication":return this._negotiateAuthentication();case"SecurityResult":return this._handleSecurityResult();case"SecurityReason":return this._handleSecurityReason();case"ClientInitialisation":return this._sock.sQpush8(this._shared?1:0),this._sock.flush(),this._rfbInitState="ServerInitialisation",!0;case"ServerInitialisation":return this._negotiateServerInit();default:return this._fail("Unknown init state (state: "+this._rfbInitState+")")}}_resumeAuthentication(){setTimeout(this._initMsg.bind(this),0)}_handleSetColourMapMsg(){return de("SetColorMapEntries"),this._fail("Unexpected SetColorMapEntries message")}_handleServerCutText(){if(de("ServerCutText"),this._sock.rQwait("ServerCutText header",7,1))return!1;this._sock.rQskipBytes(3);let t=this._sock.rQshift32();if(t=Ti(t),this._sock.rQwait("ServerCutText content",Math.abs(t),8))return!1;if(t>=0){let n=this._sock.rQshiftStr(t);if(this._viewOnly)return!0;this.dispatchEvent(new CustomEvent("clipboard",{detail:{text:n}}))}else{t=Math.abs(t);let n=this._sock.rQshift32(),r=n&65535,o=n&4278190080;if(!!(o&rk)){this._clipboardServerCapabilitiesFormats={},this._clipboardServerCapabilitiesActions={};for(let a=0;a<=15;a++){let u=1<<a;r&u&&(this._clipboardServerCapabilitiesFormats[u]=!0,this._sock.rQshift32())}for(let a=24;a<=31;a++){let u=1<<a;this._clipboardServerCapabilitiesActions[u]=!!(o&u)}let i=[rk,Oc,ok,aa,Lc];e.messages.extendedClipboardCaps(this._sock,i,{extendedClipboardFormatText:0})}else if(o===Oc){if(this._viewOnly)return!0;this._clipboardText!=null&&this._clipboardServerCapabilitiesActions[Lc]&&r&fn&&e.messages.extendedClipboardProvide(this._sock,[fn],[this._clipboardText])}else if(o===ok){if(this._viewOnly)return!0;this._clipboardServerCapabilitiesActions[aa]&&(this._clipboardText!=null?e.messages.extendedClipboardNotify(this._sock,[fn]):e.messages.extendedClipboardNotify(this._sock,[]))}else if(o===aa){if(this._viewOnly)return!0;this._clipboardServerCapabilitiesActions[Oc]&&r&fn&&e.messages.extendedClipboardRequest(this._sock,[fn])}else if(o===Lc){if(this._viewOnly||!(r&fn))return!0;this._clipboardText=null;let i=this._sock.rQshiftBytes(t-4),a=new Yt,u=null;a.setInput(i);for(let c=0;c<=15;c++){let d=1<<c;if(r&d){let p=0,f=a.inflate(4);p|=f[0]<<24,p|=f[1]<<16,p|=f[2]<<8,p|=f[3];let h=a.inflate(p);d===fn&&(u=h)}}if(a.setInput(null),u!==null){let c="";for(let d=0;d<u.length;d++)c+=String.fromCharCode(u[d]);u=c,u=ic(u),u.length>0&&u.charAt(u.length-1)==="\0"&&(u=u.slice(0,-1)),u=u.replaceAll(`\r
1
+ var GT=Object.defineProperty;var un=(e,t)=>{for(var n in t)GT(e,n,{get:t[n],enumerable:!0})};var Nf=globalThis.__bbPluginRuntime;if(Nf==null||Nf.pluginSdkApp==null)throw new Error('Cannot load "@get-bb/plugin-sdk/app": this bundle must be loaded by the Moonlet app, which provides the shared plugin runtime (globalThis.__bbPluginRuntime).');var Vl=Nf.pluginSdkApp,hF="default"in Vl?Vl.default:Vl,{Markdown:Z_,ThreadChat:Af,ThreadTitle:mF,UrlLink:gF,definePluginApp:W_,experimental_BranchPicker:xF,experimental_ComposerRoot:bF,experimental_DetailRow:yF,experimental_Diff:_F,experimental_FailedVoiceRecordings:vF,experimental_FileLink:wF,experimental_Icon:pe,experimental_ImageLightbox:kF,experimental_InfoList:SF,experimental_InfoListRow:EF,experimental_InfoSection:NF,experimental_NewThreadComposer:AF,experimental_PermissionModePicker:CF,experimental_PluginIcon:TF,experimental_PluginRpcCallError:RF,experimental_PromptMentionIcon:$F,experimental_ProviderIcon:IF,experimental_ProviderModelPicker:PF,experimental_SettingsRow:Ni,experimental_SettingsSection:ct,experimental_ShortcutHint:OF,experimental_SidebarNavigationIcon:LF,experimental_SourceCode:MF,experimental_THREAD_ACTION_GROUPS:DF,experimental_THREAD_CONTEXT_SEGMENT_GROUPS:FF,experimental_THREAD_INFO_ROW_GROUPS:zF,experimental_THREAD_INFO_SECTION_GROUPS:KF,experimental_ThreadActionsContextMenu:XF,experimental_ThreadActionsMenu:BF,experimental_ThreadStatusGlyph:UF,experimental_ThreadTitleText:HF,experimental_VoiceInputButton:VF,experimental_VoiceInputTextarea:ZF,experimental_VoiceRecordingBar:WF,experimental_copyToClipboard:j_,experimental_describePromptMention:jF,experimental_promptMentionClipboardAttributes:QF,experimental_readPromptMentionClipboard:GF,experimental_saveFile:YF,experimental_useAppPanel:Q_,experimental_useArchiveEnvironmentThreads:qF,experimental_useBranches:JF,experimental_useCheckoutState:e4,experimental_useCodeTheme:t4,experimental_useComposerCommandSearch:n4,experimental_useComposerContributions:r4,experimental_useComposerMentionSearch:o4,experimental_useComposerRenderer:s4,experimental_useExperiment:i4,experimental_useFixedTabTarget:a4,experimental_usePluginId:l4,experimental_useProviders:c4,experimental_useQuestionFormHost:u4,experimental_useRpcKeyedQuery:d4,experimental_useRpcMutation:p4,experimental_useRpcQuery:f4,experimental_useRpcRefresh:h4,experimental_useSidebar:G_,experimental_useSidebarNavigation:m4,experimental_useSidebarNavigationSplit:g4,experimental_useSidebarThreadActions:x4,experimental_useSidebarThreadSplit:b4,experimental_useSidebarThreads:y4,experimental_useThreadActionRegistrations:_4,experimental_useThreadActions:v4,experimental_useThreadTitleDisplayText:w4,internal_DO_NOT_USE_Outlet:Zl,internal_DO_NOT_USE_useOutletFilled:Y_,useBbContext:q_,useBbNavigate:Ie,useComposer:J_,useComposerView:k4,useComposers:S4,useEnvironmentProviders:E4,useRealtime:ke,useRealtimeConnectionState:ev,useRpc:J,useSdk:dn,useSettings:N4,useSidebarSplitLayout:A4,useSidebarThreadDraft:C4,useSidebarThreadDraftIds:T4,useSidebarThreadRowStatus:R4,useSidebarThreadRowStatuses:$4,useSidebarThreadShortcut:I4,experimental_useSidebarThreadPullRequest:P4}=Vl;var Ir={};un(Ir,{Activity:()=>qT,Children:()=>jl,Component:()=>JT,Fragment:()=>Tf,Profiler:()=>e2,PureComponent:()=>t2,StrictMode:()=>n2,Suspense:()=>r2,act:()=>o2,cache:()=>s2,cacheSignal:()=>i2,captureOwnerStack:()=>a2,cloneElement:()=>Ai,createContext:()=>Rf,createElement:()=>tv,createRef:()=>l2,default:()=>YT,forwardRef:()=>Rn,isValidElement:()=>Oo,lazy:()=>c2,memo:()=>u2,startTransition:()=>d2,unstable_useCacheRefresh:()=>p2,use:()=>f2,useActionState:()=>h2,useCallback:()=>q,useContext:()=>$f,useDebugValue:()=>m2,useDeferredValue:()=>g2,useEffect:()=>M,useEffectEvent:()=>x2,useId:()=>Ci,useImperativeHandle:()=>b2,useInsertionEffect:()=>y2,useLayoutEffect:()=>Ye,useMemo:()=>Lt,useOptimistic:()=>_2,useReducer:()=>v2,useRef:()=>G,useState:()=>v,useSyncExternalStore:()=>xt,useTransition:()=>w2,version:()=>k2});var Cf=globalThis.__bbPluginRuntime;if(Cf==null||Cf.react==null)throw new Error('Cannot load "react": this bundle must be loaded by the Moonlet app, which provides the shared plugin runtime (globalThis.__bbPluginRuntime).');var Wl=Cf.react,YT="default"in Wl?Wl.default:Wl,{Activity:qT,Children:jl,Component:JT,Fragment:Tf,Profiler:e2,PureComponent:t2,StrictMode:n2,Suspense:r2,act:o2,cache:s2,cacheSignal:i2,captureOwnerStack:a2,cloneElement:Ai,createContext:Rf,createElement:tv,createRef:l2,forwardRef:Rn,isValidElement:Oo,lazy:c2,memo:u2,startTransition:d2,unstable_useCacheRefresh:p2,use:f2,useActionState:h2,useCallback:q,useContext:$f,useDebugValue:m2,useDeferredValue:g2,useEffect:M,useEffectEvent:x2,useId:Ci,useImperativeHandle:b2,useInsertionEffect:y2,useLayoutEffect:Ye,useMemo:Lt,useOptimistic:_2,useReducer:v2,useRef:G,useState:v,useSyncExternalStore:xt,useTransition:w2,version:k2}=Wl;function nv(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function S2(...e){return t=>{let n=!1,r=e.map(o=>{let s=nv(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){let s=r[o];typeof s=="function"?s():nv(e[o],null)}}}}function rv(...e){return q(S2(...e),e)}function E2(e){let t=Rn((n,r)=>{let{children:o,...s}=n,i=null,a=!1,u=[];ov(o)&&typeof Ql=="function"&&(o=Ql(o._payload)),jl.forEach(o,f=>{if(R2(f)){a=!0;let h=f,g="child"in h.props?h.props.child:h.props.children;ov(g)&&typeof Ql=="function"&&(g=Ql(g._payload)),i=A2(h,g),u.push(i?.props?.children)}else u.push(f)}),i?i=Ai(i,void 0,u):!a&&jl.count(o)===1&&Oo(o)&&(i=o);let c=i?T2(i):void 0,d=rv(r,c);if(!i){if(o||o===0)throw new Error(a?O2(e):P2(e));return o}let p=C2(s,i.props??{});return i.type!==Tf&&(p.ref=r?d:c),Ai(i,p)});return t.displayName=`${e}.Slot`,t}var Gl=E2("Slot"),N2=Symbol.for("radix.slottable");var A2=(e,t)=>{if("child"in e.props){let n=e.props.child;return Oo(n)?Ai(n,void 0,e.props.children(n.props.children)):null}return Oo(t)?t:null};function C2(e,t){let n={...t};for(let r in t){let o=e[r],s=t[r];/^on[A-Z]/.test(r)?o&&s?n[r]=(...a)=>{let u=s(...a);return o(...a),u}:o&&(n[r]=o):r==="style"?n[r]={...o,...s}:r==="className"&&(n[r]=[o,s].filter(Boolean).join(" "))}return{...e,...n}}function T2(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function R2(e){return Oo(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===N2}var $2=Symbol.for("react.lazy");function ov(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===$2&&"_payload"in e&&I2(e._payload)}function I2(e){return typeof e=="object"&&e!==null&&"then"in e}var P2=e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,O2=e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,Ql=Ir[" use ".trim().toString()];var If=globalThis.__bbPluginRuntime;if(If==null||If.classVarianceAuthority==null)throw new Error('Cannot load "class-variance-authority": this bundle must be loaded by the Moonlet app, which provides the shared plugin runtime (globalThis.__bbPluginRuntime).');var Yl=If.classVarianceAuthority,F4="default"in Yl?Yl.default:Yl,{cva:sv,cx:z4}=Yl;var Pf=globalThis.__bbPluginRuntime;if(Pf==null||Pf.clsx==null)throw new Error('Cannot load "clsx": this bundle must be loaded by the Moonlet app, which provides the shared plugin runtime (globalThis.__bbPluginRuntime).');var ql=Pf.clsx,X4="default"in ql?ql.default:ql,{clsx:iv}=ql;var Of=globalThis.__bbPluginRuntime;if(Of==null||Of.tailwindMerge==null)throw new Error('Cannot load "tailwind-merge": this bundle must be loaded by the Moonlet app, which provides the shared plugin runtime (globalThis.__bbPluginRuntime).');var Jl=Of.tailwindMerge,U4="default"in Jl?Jl.default:Jl,{createTailwindMerge:H4,extendTailwindMerge:V4,fromTheme:Z4,getDefaultConfig:W4,mergeConfigs:j4,twJoin:Q4,twMerge:av,validators:G4}=Jl;function V(...e){return av(iv(e))}var ec="transition-colors duration-150 hover:duration-0";var Lf=globalThis.__bbPluginRuntime;if(Lf==null||Lf.jsxRuntime==null)throw new Error('Cannot load "react/jsx-runtime": this bundle must be loaded by the Moonlet app, which provides the shared plugin runtime (globalThis.__bbPluginRuntime).');var tc=Lf.jsxRuntime,nz="default"in tc?tc.default:tc,{Fragment:he,jsx:l,jsxs:m}=tc;var L2=sv(`inline-flex cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ${ec} focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_[data-icon-root]]:pointer-events-none [&_[data-icon-root]]:size-4 [&_[data-icon-root]]:shrink-0`,{variants:{variant:{default:"bg-foreground text-background hover:bg-foreground/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-transparent hover:bg-state-hover hover:text-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-state-hover hover:text-foreground aria-pressed:bg-state-active aria-pressed:text-foreground aria-pressed:hover:bg-state-active data-[state=open]:bg-state-active data-[state=open]:text-foreground data-[state=open]:hover:bg-state-active",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),R=Rn(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>l(r?Gl:"button",{className:V(L2({variant:t,size:n,className:e})),ref:s,...o}));R.displayName="Button";function M2({route:e,busy:t,answer:n,cancel:r,expiresAt:o}){return m("div",{className:"flex flex-col gap-3 p-3 text-sm",children:[m("div",{children:[m("div",{className:"font-medium",children:[e.what==="spawn"?"Start work":e.what==="tell"?"Send a message":e.what==="relay"?"Relay a message":"Schedule a check"," ",e.what==="relay"?"to":"on"," ",l("span",{className:"font-mono",children:e.station}),e.when&&m("span",{className:"font-normal text-muted-foreground",children:[" (",e.when,")"]})]}),(e.provider||e.model)&&m("div",{className:"mt-1 text-xs",children:["Runs on ",l("span",{className:"font-mono",children:e.provider??"the project's provider"}),e.model&&m(he,{children:[" ","with ",l("span",{className:"font-mono",children:e.model})]}),e.provider==="codex"&&e.own&&" (Codex, under that machine's own Codex sign-in and settings; your moonlet's station protections don't apply)","."]}),m("div",{className:"mt-1 text-xs text-muted-foreground",children:["I\u2019m requesting this from ",e.from,".",e.what==="check"&&" The script runs as orbit on its station, outside Claude Code's sandbox, every time it's due.",e.own&&" I\u2019ll run as you on your machine, with access to your files and accounts.",e.what==="relay"&&" You set this to Ask in Settings \u2192 your moonlet \u2192 Relay. The message goes as written below, marked as relayed from your moonlet."]})]}),l("div",{className:"font-medium",children:e.title}),l("pre",{className:"max-h-72 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted p-2 font-mono text-xs",children:e.brief}),o&&m("div",{className:"text-xs text-muted-foreground",children:["Expires at ",new Date(o).toLocaleTimeString(),"."]}),m("div",{className:"flex flex-wrap gap-2",children:[l(R,{size:"sm",disabled:t,onClick:()=>n("once"),children:"Approve"}),l(R,{size:"sm",variant:"destructive",disabled:t,onClick:()=>n("deny"),children:"Decline"}),l(R,{size:"sm",variant:"ghost",disabled:t,onClick:()=>{r()},children:"Dismiss"})]})]})}var D2=e=>({"orbit-keys.service":"Password service","orbit-relay.service":"Station connection","orbit-proton-bridge.service":"Mail connection",mail:"Mail connection",gate:"Station connection",plugin:"your moonlet service",turn:"Starting work","mail-check":"Mail check",events:"Background work service"})[e]??e;function F2({switching:e,busy:t,answer:n,cancel:r,expiresAt:o}){let s=e.what==="activate";return m("div",{className:"flex flex-col gap-3 p-3 text-sm",children:[m("div",{children:[m("div",{className:"font-medium",children:["Switch ",s?"on":"off"," on the station: ",e.piece]}),m("div",{className:"mt-1 text-xs",children:[e.words,"."]})]}),l("div",{className:"text-xs",children:s&&e.recovery?"Every health check still runs. This retry may keep only the known failures below. Another failure or an interrupted switch still undoes it.":s?"I\u2019ll switch this on and check the station\u2019s health. A failed check or interrupted switch restores the previous state.":"I\u2019ll switch this off now. The effect is described above."}),e.recovery&&m("div",{className:"space-y-2 rounded-md border p-2",children:[l("p",{className:"font-medium",children:"Retry and keep this switch if the same checks still fail?"}),l("ul",{className:"list-disc pl-5",children:e.recovery.failures.map(i=>l("li",{children:D2(i)},i))}),l("p",{children:"Approve retries the same switch with the same settings and allows these known failures for this attempt. Services may remain unavailable until repaired. Other failures still undo the switch."})]}),m("div",{className:"text-xs text-muted-foreground",children:["This approves the switch described above.",o&&` Expires at ${new Date(o).toLocaleTimeString()}.`]}),m("div",{className:"flex flex-wrap gap-2",children:[l(R,{size:"sm",disabled:t,onClick:()=>n("once"),children:"Approve"}),l(R,{size:"sm",variant:"destructive",disabled:t,onClick:()=>n("deny"),children:"Decline"}),l(R,{size:"sm",variant:"ghost",disabled:t,onClick:()=>{r()},children:"Dismiss"})]})]})}function z2({login:e,offers:t,busy:n,answer:r,cancel:o,expiresAt:s}){let i=e.otp?"one-time codes":"sign-ins";return e.humanCheck?m("div",{className:"flex flex-col gap-3 p-3 text-sm",children:[m("div",{children:[l("div",{className:"font-medium",children:"Proton wants a human check before Bridge signs in"}),l("div",{className:"mt-1 text-xs text-muted-foreground",children:"It's open in Chrome on your moonlet's desktop: solve it there from the Desktop panel (Proton accepts it only from your moonlet's own computer), then press Done. Bridge's sign-in is waiting and carries on from there. The link, in case the window closed:"})]}),l("a",{className:"break-all font-mono text-xs underline",href:e.humanCheck,target:"_blank",rel:"noreferrer noopener",children:e.humanCheck}),s&&m("div",{className:"text-xs text-muted-foreground",children:["Cancelled if unanswered by ",new Date(s).toLocaleTimeString(),"."]}),m("div",{className:"flex flex-wrap gap-2",children:[l(R,{size:"sm",disabled:n,onClick:()=>r("once"),children:"Done"}),l(R,{size:"sm",variant:"destructive",disabled:n,onClick:()=>r("deny"),children:"Cancel"})]})]}):m("div",{className:"flex flex-col gap-3 p-3 text-sm",children:[l("div",{children:e.bridge?m(he,{children:[m("div",{className:"font-medium",children:["Sign Proton Mail Bridge in with ",l("span",{className:"font-mono",children:e.item})]}),l("div",{className:"mt-1 text-xs text-muted-foreground",children:"I\u2019ll sign Bridge in through the vault without seeing the password or code. Then I can read and send its mail through Bridge."})]}):m(he,{children:[m("div",{className:"font-medium",children:["Sign your moonlet in: fill ",e.otp?"the one-time code":"the username and password"," from ",l("span",{className:"font-mono",children:e.item})," ","into ",l("span",{className:"font-mono",children:e.unit}),"'s sign-in page, ",l("span",{className:"font-mono",children:e.url})]}),m("div",{className:"mt-1 text-xs text-muted-foreground",children:[e.otp?"The broker fills it into the text field that has the focus on that page; your moonlet never sees it.":"The broker fills them into that page's form (the password only into its password field) and signs in; your moonlet never sees them."," ","You can see the sign-in form in the Desktop panel."]})]})}),m("ul",{className:"list-disc space-y-0.5 pl-5 text-xs text-muted-foreground",children:[t.includes("thread")&&m("li",{children:[l("b",{children:"For this conversation"}),": ",i," for ",l("span",{className:"font-mono",children:e.name})," asked as this conversation, until Moonlet reloads your moonlet."]}),t.includes("always")&&m("li",{children:[l("b",{children:"Always"}),": ",i," for ",l("span",{className:"font-mono",children:e.name})," from any of the station's conversations, from now on. Revoke it in Settings \u2192 your moonlet."]}),s&&m("li",{children:["Expires at ",new Date(s).toLocaleTimeString(),"."]})]}),m("div",{className:"flex flex-wrap gap-2",children:[l(R,{size:"sm",disabled:n,onClick:()=>r("once"),children:"Approve"}),t.includes("thread")&&l(R,{size:"sm",variant:"secondary",disabled:n,onClick:()=>r("thread"),children:"For this conversation"}),t.includes("always")&&l(R,{size:"sm",variant:"secondary",disabled:n,onClick:()=>r("always"),children:"Always"}),l(R,{size:"sm",variant:"destructive",disabled:n,onClick:()=>r("deny"),children:"Decline"}),l(R,{size:"sm",variant:"ghost",disabled:n,onClick:()=>{o()},children:"Dismiss"})]})]})}function K2({change:e,busy:t,answer:n}){return m("div",{className:"space-y-3 p-3 text-sm",children:[m("p",{className:"font-medium",children:[e.mergeReasons?"Allow merging":e.checks?"Proceed with these checks for":"Approve change"," #",e.number," in ",e.repo,"?"]}),l("a",{className:"underline",href:`https://github.com/${e.repo}/pull/${e.number}/files/${e.head}`,target:"_blank",rel:"noreferrer noopener",children:"Read this version of the change"}),e.mergeReasons?m("p",{children:["Allow this reviewed version to be merged despite:"," ",e.mergeReasons.map(r=>({author:"the author restriction",protected_paths:"protected files",changes_requested:"a request for changes"})[r]).join(", "),". Every check must still pass, the review must match this commit, and the pull request must be ready and mergeable. This changes the default branch."]}):e.checks?m(he,{children:[l("p",{children:"Allow merging this version despite the results below. Tests may be incomplete or the change may be broken. This also approves the change, including core files. It does not install anything."}),l("a",{className:"underline",href:`https://github.com/${e.repo}/pull/${e.number}/checks`,target:"_blank",rel:"noreferrer noopener",children:"Read the check details"}),l("ul",{className:"list-disc pl-5",children:e.checks.failures.map((r,o)=>l("li",{children:r},o))}),l("p",{className:"text-xs",children:"Only these exact check runs and this version are covered. A rerun, changed result, extra check or later push needs a new decision. Repository, identity and version checks still apply."})]}):l("p",{children:"This approves this whole version, including its core files. A later push needs approval of its own. Every other merge check still applies."}),l("p",{className:"text-xs",children:"This records your approval of the change. It does not install anything."}),l("pre",{className:"whitespace-pre-wrap break-all text-xs",children:e.head}),m("div",{className:"flex gap-2",children:[l(R,{size:"sm",disabled:t,onClick:()=>n("once"),children:"Approve"}),l(R,{size:"sm",variant:"destructive",disabled:t,onClick:()=>n("deny"),children:"Decline"})]})]})}function X2({mail:e,busy:t,answer:n,cancel:r,expiresAt:o}){let s=(i,a)=>a&&m("div",{children:[m("span",{className:"text-muted-foreground",children:[i,":"]})," ",l("span",{className:"whitespace-pre-wrap break-all font-mono",children:a})]});return m("div",{className:"flex flex-col gap-3 p-3 text-sm",children:[m("div",{children:[l("div",{className:"font-medium",children:"Your moonlet wants to send this mail from its Gmail account"}),l("div",{className:"mt-1 text-xs text-muted-foreground",children:"Exactly as shown: the protected mail runner sends this message and nothing else. Sending only this one, once; a sent mail can't be taken back."})]}),m("div",{className:"flex flex-col gap-0.5 text-xs",children:[s("From",e.from),s("To",e.to),s("Cc",e.cc),s("Subject",e.subject),s("Date",e.date),s("Message-ID",e.messageId),s("In reply to",e.inReplyTo),s("References",e.references)]}),l("pre",{className:"max-h-72 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted p-2 font-mono text-xs",children:e.body}),o&&m("div",{className:"text-xs text-muted-foreground",children:["Refused if unanswered by ",new Date(o).toLocaleTimeString(),"."]}),m("div",{className:"flex flex-wrap gap-2",children:[l(R,{size:"sm",disabled:t,onClick:()=>n("once"),children:"Send"}),l(R,{size:"sm",variant:"destructive",disabled:t,onClick:()=>n("deny"),children:"Decline"}),l(R,{size:"sm",variant:"ghost",disabled:t,onClick:()=>{r()},children:"Dismiss"})]})]})}function nc({interaction:e,submit:t,cancel:n}){let r=e.payload,[o,s]=v(!1),i=u=>{s(!0),t({choice:u}).catch(()=>s(!1))};if(r.change)return l(K2,{change:r.change,busy:o,answer:i});if(r.switching)return l(F2,{switching:r.switching,busy:o,answer:i,cancel:()=>{n()},expiresAt:r.expiresAt});if(r.mail)return l(X2,{mail:r.mail,busy:o,answer:i,cancel:()=>{n()},expiresAt:r.expiresAt});if(r.route)return l(M2,{route:r.route,busy:o,answer:i,cancel:()=>{n()},expiresAt:r.expiresAt});if(r.login)return l(z2,{login:r.login,offers:r.offers,busy:o,answer:i,cancel:()=>{n()},expiresAt:r.expiresAt});let a=new Set(r.offers);return m("div",{className:"flex flex-col gap-3 p-3 text-sm",children:[m("div",{children:[m("div",{className:"font-medium",children:["I\u2019d like to ",r.level==="act"?"make a change":"look"," with ",l("span",{className:"font-mono",children:r.capability})]}),l("pre",{className:"mt-2 max-h-48 overflow-auto whitespace-pre-wrap break-all rounded-md bg-muted p-2 font-mono text-xs",children:r.command})]}),m("ul",{className:"list-disc space-y-0.5 pl-5 text-xs text-muted-foreground",children:[a.has("thread")&&m("li",{children:[l("b",{children:"For this conversation"}),": any ",l("span",{className:"font-mono",children:r.rule})," command on ",r.capability,", until Moonlet reloads your moonlet."]}),a.has("always")&&m("li",{children:[l("b",{children:"Always"}),": this exact command, from now on. Revoke it in Settings \u2192 your moonlet."]}),r.sensitive&&m("li",{children:["This command is on ",r.capability,"'s sensitive list, so it asks every time."]}),r.expiresAt&&m("li",{children:["Expires at ",new Date(r.expiresAt).toLocaleTimeString(),"."]})]}),m("div",{className:"flex flex-wrap gap-2",children:[l(R,{size:"sm",disabled:o,onClick:()=>i("once"),children:"Approve"}),a.has("thread")&&l(R,{size:"sm",variant:"secondary",disabled:o,onClick:()=>i("thread"),children:"Allow for this conversation"}),a.has("always")&&l(R,{size:"sm",variant:"secondary",disabled:o,onClick:()=>i("always"),children:"Always allow"}),l(R,{size:"sm",variant:"destructive",disabled:o,onClick:()=>i("deny"),children:"Decline"}),l(R,{size:"sm",variant:"ghost",disabled:o,onClick:()=>{n()},children:"Dismiss"})]})]})}function rc({interaction:e,submit:t,cancel:n}){let r=e.payload,[o,s]=v(!1),i=a=>{s(!0),t({hostId:a}).catch(()=>s(!1))};return m("div",{className:"flex flex-col gap-3 p-3 text-sm",children:[m("div",{children:[m("div",{className:"font-medium",children:["Which machine manages ",l("span",{className:"font-mono",children:r.station}),"?"]}),m("p",{className:"mt-1 text-xs text-muted-foreground",children:["Several machines have your moonlet's station key and this station's VM. Your moonlet reaches the station only through the one you pick, which receives its credentials when they change. Change it later with ",l("span",{className:"font-mono",children:"moonlet station manager"}),"."]})]}),m("div",{className:"flex flex-wrap gap-2",children:[r.machines.map(a=>l(R,{size:"sm",variant:"secondary",disabled:o,onClick:()=>i(a.id),children:a.name},a.id)),l(R,{size:"sm",variant:"ghost",disabled:o,onClick:()=>{n()},children:"Dismiss"})]})]})}function lv({payload:e}){let t=e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.proposal=="string"?e.proposal:"";return/^[a-f0-9]{32}$/.test(t)?l(Ti,{id:t}):l("p",{children:"The settings result is unavailable."})}function Ti({id:e}){let t=J(),[n,r]=v([]),[o,s]=v(!1);return M(()=>{let i=!0,a,u=async()=>{try{let c=e?await t.call("policy-proposals.result",{id:e}).then(d=>d?[d]:[]):await t.call("policy-proposals.history",null);i&&(r(c),s(!1))}catch{i&&s(!0)}i&&(a=setTimeout(()=>{u()},5e3))};return u(),()=>{i=!1,clearTimeout(a)}},[t,e]),!n.length&&!o?null:m("section",{className:"space-y-2 p-3 text-sm","aria-label":"Station settings results",children:[!e&&l("h2",{className:"font-medium",children:"Recent station settings requests"}),o&&l("p",{role:"alert",children:"The settings result could not be checked. Trying again."}),n.slice(0,e?1:10).map(i=>m("div",{className:"space-y-1 rounded border p-2",children:[l("p",{className:"font-medium",children:i.title}),l("p",{children:i.message})]},i.id))]})}function oc({interaction:e,submit:t}){let n=e.payload,r=J(),[o,s]=v(!1),[i,a]=v(!1),[u,c]=v(null),[d,p]=v(null),[f,h]=v([]),g=Date.now()>=n.deadline,x=!!n.restore&&f.length===0;async function b(_){if(!(o||g||_&&(n.explanation.extraConfirmation&&!i||x))){s(!0),p(null);try{await t(n.restore?{approve:_,acknowledgeRisk:i,restore:_?f:[]}:{approve:_,acknowledgeRisk:i})}catch{p("Your answer did not go through. Try again."),s(!1)}}}return m("div",{className:"space-y-3 p-3 text-sm",children:[l("p",{className:"font-medium",children:n.restore?"Approve secret use again?":"Change station permissions?"}),n.explanation.sections.map(_=>m("section",{className:"space-y-1",children:[l("h3",{className:"font-medium",children:_.heading}),_.sentences.map((w,T)=>l("p",{className:"whitespace-pre-wrap break-words",children:w},T))]},_.heading)),n.restore&&m("fieldset",{className:"space-y-2",children:[l("legend",{className:"font-medium",children:"Secret uses to approve again"}),n.restore.map(_=>m("label",{className:"flex gap-2",children:[l("input",{type:"checkbox","aria-label":`Approve ${_.id} again`,checked:f.includes(_.id),disabled:o||g,onChange:w=>h(T=>w.target.checked?[...T,_.id].sort():T.filter(y=>y!==_.id))}),m("span",{children:[l("span",{className:"whitespace-pre-wrap break-all font-mono",children:_.id}),l("span",{className:"block whitespace-pre-wrap break-words",children:_.sentence})]})]},_.id))]}),l("p",{children:"This answer covers only these settings and their application. Declining or leaving this unanswered changes nothing."}),m("p",{children:["Expires ",new Date(n.deadline).toLocaleString(),"."]}),m("details",{onToggle:_=>{_.currentTarget.open&&!u&&r.call("policy-proposals.text",{id:n.id}).then(c).catch(()=>p("The exact text could not be loaded. Try opening it again."))},children:[l("summary",{className:"cursor-pointer underline",children:"More details"}),m("p",{children:["Proposer's title: ",n.title]}),l("p",{children:"Proposer's own words (not verified):"}),l("p",{className:"whitespace-pre-wrap break-words",children:n.explanation.details.proposerWords}),n.explanation.details.unchanged.map((_,w)=>l("p",{children:_},w)),u?m("div",{className:"space-y-2",children:[l("p",{children:"Current settings"}),l("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap break-all",children:u.before}),l("p",{children:"Proposed settings"}),l("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap break-all",children:u.after}),l("p",{children:"Checked review"}),l("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap break-all",children:u.preview})]}):l("p",{children:"Loading\u2026"})]}),n.explanation.extraConfirmation&&m("label",{className:"flex gap-2",children:[l("input",{type:"checkbox",checked:i,disabled:o||g,onChange:_=>a(_.target.checked)}),"I understand the extra access described above."]}),g&&l("p",{role:"alert",children:"This request has expired. Nothing was changed."}),d&&l("p",{role:"alert",children:d}),m("div",{className:"flex gap-2",children:[l(R,{size:"sm",disabled:o||g||n.explanation.extraConfirmation&&!i||x,onClick:()=>{b(!0)},children:"Approve"}),l(R,{size:"sm",variant:"destructive",disabled:o||g,onClick:()=>{b(!1)},children:"Decline"})]})]})}var B2=/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/;function sc({url:e,label:t,size:n=64}){let r={width:n,height:n};return!e||!B2.test(e)?l("span",{role:"img","aria-label":`${t}: none`,className:"inline-block shrink-0 rounded-full border border-dashed border-border bg-muted",style:r}):l("img",{src:e,alt:t,className:"shrink-0 rounded-full border border-border bg-muted object-cover",style:r})}var U2=[{value:"approve",label:"Approve"},{value:"decline",label:"Decline"},{value:"later",label:"Later"}];function Mf({id:e,beforeLabel:t="Now"}){let n=J(),[r,o]=v(null),[s,i]=v(null);return m("details",{onToggle:a=>{a.currentTarget.open&&!r&&n.call("owner-changes.details",{id:e}).then(o).catch(()=>i("The details could not be loaded. Try opening them again."))},children:[l("summary",{className:"cursor-pointer underline",children:"More details"}),s&&l("p",{role:"alert",children:s}),r&&m("div",{className:"mt-2 space-y-2",children:[r.pictures.map(a=>m("div",{className:"flex flex-col items-start gap-1",children:[l(sc,{url:a.url,label:a.label,size:96}),l("span",{className:"text-xs text-muted-foreground",children:a.label})]},a.label)),m("div",{className:"grid gap-2 md:grid-cols-2",children:[m("div",{children:[l("div",{className:"mb-1 text-xs text-muted-foreground",children:t}),l("pre",{className:"max-h-60 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted p-2 text-xs",children:r.before})]}),m("div",{children:[l("div",{className:"mb-1 text-xs text-muted-foreground",children:"After"}),l("pre",{className:"max-h-60 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted p-2 text-xs",children:r.after})]})]})]})]})}function H2({item:e,choice:t,onChoice:n,acknowledged:r,onAcknowledge:o,narrowing:s,onNarrow:i,expired:a}){let u=e.offer;return m("article",{className:"space-y-2 rounded-md border p-3","aria-disabled":a,children:[l("p",{className:"font-medium",children:e.summary}),e.explanation.sections.map(c=>m("section",{className:"space-y-1",children:[l("h4",{className:"font-medium",children:c.heading}),c.sentences.map((d,p)=>l("p",{className:"whitespace-pre-wrap break-words",children:d},p))]},c.heading)),(e.title||e.explanation.details.proposerWords)&&m("details",{children:[l("summary",{className:"cursor-pointer underline",children:"Proposer's own words (not verified)"}),e.title&&l("p",{className:"whitespace-pre-wrap break-words",children:e.title}),l("p",{className:"whitespace-pre-wrap break-words",children:e.explanation.details.proposerWords})]}),l(Mf,{id:e.id}),!a&&u?.expiry&&!s.once&&m("label",{className:"block",children:["Permission ends (leave empty for no time limit)",l("input",{"aria-label":"Permission ends",className:"block rounded border p-1",type:"datetime-local",value:s.until,onChange:c=>i({...s,until:c.target.value})})]}),!a&&u?.once&&m("label",{className:"flex items-center gap-2",children:[l("input",{type:"checkbox",checked:s.once,onChange:c=>i({...s,once:c.target.checked})}),"Only this once, for the operation waiting now (no standing permission)"]}),e.explanation.extraConfirmation&&m("label",{className:"flex items-center gap-2",children:[l("input",{type:"checkbox",checked:r,disabled:a,onChange:c=>o(c.target.checked)}),"I understand the extra access described above."]}),a?l("p",{children:"This request expired before your answer; it won't be applied."}):m("fieldset",{className:"flex flex-wrap gap-3",children:[l("legend",{className:"sr-only",children:"Your answer"}),U2.map(c=>m("label",{className:"flex items-center gap-1",children:[l("input",{type:"radio",name:`choice-${e.id}`,value:c.value,checked:t===c.value,onChange:()=>n(c.value)}),c.label]},c.value))]}),m("p",{className:"text-xs text-muted-foreground",children:["Expires ",new Date(e.deadline).toLocaleString(),"."]})]})}function ic({interaction:e,submit:t,cancel:n}){let r=e.payload,[o,s]=v(()=>Object.fromEntries(r.items.map(E=>[E.id,"later"]))),[i,a]=v({}),[u,c]=v({}),[d,p]=v(!1),[f,h]=v(null),[g,x]=v(()=>Date.now());M(()=>{let E=r.items.map(N=>N.deadline).filter(N=>N>g).sort((N,$)=>N-$)[0];if(E===void 0)return;let k=setTimeout(()=>x(Date.now()),Math.min(E-g+50,2**31-1));return()=>clearTimeout(k)},[r.items,g]);let b=r.items.some(E=>o[E.id]==="approve"&&E.explanation.extraConfirmation&&!i[E.id]),_=E=>u[E]??{until:"",once:!1};function w(E){let k=E.offer;if(o[E.id]!=="approve"||!k)return;let N=_(E.id);if(k.once&&N.once)return{once:!0};if(k.expiry)return{expiresAt:N.until?Date.parse(N.until):null}}let T=r.items.some(E=>{let k=w(E)?.expiresAt;return typeof k=="number"&&(!Number.isFinite(k)||k<=Date.now())});async function y(){if(d||b||T)return;p(!0),h(null);let E=r.items.filter(k=>k.deadline>Date.now()).map(k=>{let N=w(k);return{id:k.id,planHash:k.planHash,choice:o[k.id]??"later",acknowledgeRisk:i[k.id]===!0,...N?{options:N}:{}}});try{await t({form:r.form,answers:E})}catch{h("Your answer did not go through. Try again."),p(!1)}}return m("div",{className:"space-y-3 p-3 text-sm",children:[l("p",{className:"font-medium",children:r.items.length===1?"A change your moonlet asked for":`${r.items.length} changes your moonlet asked for`}),r.items.map(E=>l(H2,{item:E,choice:o[E.id]??"later",onChoice:k=>s({...o,[E.id]:k}),acknowledged:i[E.id]===!0,onAcknowledge:k=>a({...i,[E.id]:k}),narrowing:_(E.id),onNarrow:k=>c({...u,[E.id]:k}),expired:E.deadline<=g},E.id)),l("p",{children:"Approve applies exactly what is shown. Decline is remembered for 30 days. Later keeps it for another time. Nothing changes until you send your answers."}),m("div",{className:"flex flex-wrap gap-2",children:[l(R,{size:"sm",disabled:d||b||T,onClick:()=>{y()},children:"Send answers"}),l(R,{size:"sm",variant:"ghost",disabled:d,onClick:()=>{n()},children:"Not now"})]}),b&&l("p",{children:"Tick the confirmation on each high-risk change you approve."}),T&&l("p",{children:"Choose a future end time, or leave it empty for no time limit."}),f&&l("p",{role:"alert",children:f})]})}function cv(e){return e>>>0}function Ri(e){return e|0}var uv="warn",de=()=>{},Qe=()=>{},qe=()=>{},Me=()=>{};function V2(e){if(typeof e>"u"?e=uv:uv=e,de=Qe=qe=Me=()=>{},typeof window.console<"u")switch(e){case"debug":de=console.debug.bind(window.console);case"info":Qe=console.info.bind(window.console);case"warn":qe=console.warn.bind(window.console);case"error":Me=console.error.bind(window.console);case"none":break;default:throw new window.Error("invalid logging type '"+e+"'")}}V2();function ac(e,t=!1){try{return decodeURIComponent(escape(e))}catch(n){if(n instanceof URIError&&t)return e;throw n}}function Gt(e){return unescape(encodeURIComponent(e))}var Lo={toBase64Table:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".split(""),base64Pad:"=",encode(e){"use strict";let t="",n=e.length,r=n%3;for(let s=0;s<n-2;s+=3)t+=this.toBase64Table[e[s]>>2],t+=this.toBase64Table[((e[s]&3)<<4)+(e[s+1]>>4)],t+=this.toBase64Table[((e[s+1]&15)<<2)+(e[s+2]>>6)],t+=this.toBase64Table[e[s+2]&63];let o=n-r;return r===2?(t+=this.toBase64Table[e[o]>>2],t+=this.toBase64Table[((e[o]&3)<<4)+(e[o+1]>>4)],t+=this.toBase64Table[(e[o+1]&15)<<2],t+=this.toBase64Table[64]):r===1&&(t+=this.toBase64Table[e[o]>>2],t+=this.toBase64Table[(e[o]&3)<<4],t+=this.toBase64Table[64],t+=this.toBase64Table[64]),t},toBinaryTable:[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,0,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1],decode(e,t=0){let n=e.indexOf("=")-t;n<0&&(n=e.length-t);let r=(n>>2)*3+Math.floor(n%4/1.5),o=new Array(r),s=0,i=0;for(let a=0,u=t;u<e.length;u++){let c=this.toBinaryTable[e.charCodeAt(u)&127],d=e.charAt(u)===this.base64Pad;if(c===-1){Me("Illegal character code "+e.charCodeAt(u)+" at position "+u);continue}i=i<<6|c,s+=6,s>=8&&(s-=8,d||(o[a++]=i>>s&255),i&=(1<<s)-1)}if(s){let a=new Error("Corrupted base64 string");throw a.name="Base64-Error",a}return o}};var Df="ontouchstart"in document.documentElement||document.ontouchstart!==void 0||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0;window.addEventListener("touchstart",function e(){Df=!0,window.removeEventListener("touchstart",e,!1)},!1);var $i=10*(window.devicePixelRatio||1),dv=!1;try{let e=document.createElement("canvas");e.style.cursor='url("data:image/x-icon;base64,AAACAAEACAgAAAIAAgA4AQAAFgAAACgAAAAIAAAAEAAAAAEAIAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAAAAAAAA==") 2 2, default',e.style.cursor.indexOf("url")===0?(Qe("Data URI scheme cursor supported"),dv=!0):qe("Data URI scheme cursor not supported")}catch(e){Me("Data URI scheme cursor test exception: "+e)}var pv=dv,Z2=!0;try{let e=document.createElement("div");e.style.visibility="hidden",e.style.overflow="scroll",document.body.appendChild(e);let t=document.createElement("div");e.appendChild(t);let n=e.offsetWidth-t.offsetWidth;e.parentNode.removeChild(e),Z2=n!=0}catch(e){Me("Scrollbar test exception: "+e)}var Ff=!1;async function W2(){if(!("VideoDecoder"in window))return!1;let e={codec:"avc1.42401f",codedWidth:1920,codedHeight:1080,optimizeForLatency:!0};if(!(await VideoDecoder.isConfigSupported(e)).supported)return!1;let n=new Uint8Array(Lo.decode("AAAAAWdCwBTZnpuAgICgAAADACAAAAZB4oVNAAAAAWjJYyyAAAABBgX//4HcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTY0IHIzMTA4IDMxZTE5ZjkgLSBILjI2NC9NUEVHLTQgQVZDIGNvZGVjIC0gQ29weWxlZnQgMjAwMy0yMDIzIC0gaHR0cDovL3d3dy52aWRlb2xhbi5vcmcveDI2NC5odG1sIC0gb3B0aW9uczogY2FiYWM9MCByZWY9NSBkZWJsb2NrPTE6MDowIGFuYWx5c2U9MHgxOjB4MTExIG1lPWhleCBzdWJtZT04IHBzeT0xIHBzeV9yZD0xLjAwOjAuMDAgbWl4ZWRfcmVmPTEgbWVfcmFuZ2U9MTYgY2hyb21hX21lPTEgdHJlbGxpcz0yIDh4OGRjdD0wIGNxbT0wIGRlYWR6b25lPTIxLDExIGZhc3RfcHNraXA9MSBjaHJvbWFfcXBfb2Zmc2V0PS0yIHRocmVhZHM9MSBsb29rYWhlYWRfdGhyZWFkcz0xIHNsaWNlZF90aHJlYWRzPTAgbnI9MCBkZWNpbWF0ZT0xIGludGVybGFjZWQ9MCBibHVyYXlfY29tcGF0PTAgY29uc3RyYWluZWRfaW50cmE9MCBiZnJhbWVzPTAgd2VpZ2h0cD0wIGtleWludD1pbmZpbml0ZSBrZXlpbnRfbWluPTI1IHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NTAgcmM9YWJyIG1idHJlZT0xIGJpdHJhdGU9NDAwIHJhdGV0b2w9MS4wIHFjb21wPTAuNjAgcXBtaW49MCBxcG1heD02OSBxcHN0ZXA9NCBpcF9yYXRpbz0xLjQwIGFxPTE6MS4wMACAAAABZYiEBrxmKAAPVccAAS044AA5DRJMnkycJk4TPw==")),r=!1,o=null,s=new VideoDecoder({output:a=>{r=!0,a.close()},error:a=>{o=a}}),i=new EncodedVideoChunk({timestamp:0,type:"key",data:n});s.configure(e),s.decode(i);try{await s.flush()}catch(a){o=a}return!(!r||o!==null)}Ff=await W2();function er(){return!!/mac/i.exec(navigator.platform)}function Mo(){return!!/win/i.exec(navigator.platform)}function Do(){return!!/ipad/i.exec(navigator.platform)||!!/iphone/i.exec(navigator.platform)||!!/ipod/i.exec(navigator.platform)}function Fo(e,t,n){let r=n.getBoundingClientRect(),o={x:0,y:0};return e<r.left?o.x=0:e>=r.right?o.x=r.width-1:o.x=e-r.left,t<r.top?o.y=0:t>=r.bottom?o.y=r.height-1:o.y=t-r.top,o}function Or(e){e.stopPropagation(),e.preventDefault()}var zf=!1,hv=null;document.captureElement=null;function Pr(e){if(zf)return;let t=new e.constructor(e.type,e);zf=!0,document.captureElement?document.captureElement.dispatchEvent(t):hv.dispatchEvent(t),zf=!1,e.stopPropagation(),t.defaultPrevented&&e.preventDefault(),e.type==="mouseup"&&bv()}function mv(){let e=document.getElementById("noVNC_mouse_capture_elem");e.style.cursor=window.getComputedStyle(document.captureElement).cursor}var gv=new MutationObserver(mv);function xv(e){if(e.setCapture)e.setCapture(),document.captureElement=e;else{bv();let t=document.getElementById("noVNC_mouse_capture_elem");t===null&&(t=document.createElement("div"),t.id="noVNC_mouse_capture_elem",t.style.position="fixed",t.style.top="0px",t.style.left="0px",t.style.width="100%",t.style.height="100%",t.style.zIndex=1e4,t.style.display="none",document.body.appendChild(t),t.addEventListener("contextmenu",Pr),t.addEventListener("mousemove",Pr),t.addEventListener("mouseup",Pr)),document.captureElement=e,gv.observe(e,{attributes:!0}),mv(),t.style.display="",window.addEventListener("mousemove",Pr),window.addEventListener("mouseup",Pr)}}function bv(){if(document.releaseCapture)document.releaseCapture(),document.captureElement=null;else{if(!document.captureElement)return;hv=document.captureElement,document.captureElement=null,gv.disconnect();let e=document.getElementById("noVNC_mouse_capture_elem");e.style.display="none",window.removeEventListener("mousemove",Pr),window.removeEventListener("mouseup",Pr)}}var Lr=class{constructor(){this._listeners=new Map}addEventListener(t,n){this._listeners.has(t)||this._listeners.set(t,new Set),this._listeners.get(t).add(n)}removeEventListener(t,n){this._listeners.has(t)&&this._listeners.get(t).delete(n)}dispatchEvent(t){return this._listeners.has(t.type)?(this._listeners.get(t.type).forEach(n=>n.call(this,t)),!t.defaultPrevented):!0}};var Ii=class{constructor(t){if(this._drawCtx=null,this._renderQ=[],this._flushPromise=null,this._fbWidth=0,this._fbHeight=0,this._prevDrawStyle="",de(">> Display.constructor"),this._target=t,!this._target)throw new Error("Target must be set");if(typeof this._target=="string")throw new Error("target must be a DOM element");if(!this._target.getContext)throw new Error("no getContext method");this._targetCtx=this._target.getContext("2d"),this._viewportLoc={x:0,y:0,w:this._target.width,h:this._target.height},this._backbuffer=document.createElement("canvas"),this._drawCtx=this._backbuffer.getContext("2d"),this._damageBounds={left:0,top:0,right:this._backbuffer.width,bottom:this._backbuffer.height},de("User Agent: "+navigator.userAgent),de("<< Display.constructor"),this._scale=1,this._clipViewport=!1}get scale(){return this._scale}set scale(t){this._rescale(t)}get clipViewport(){return this._clipViewport}set clipViewport(t){this._clipViewport=t;let n=this._viewportLoc;this.viewportChangeSize(n.w,n.h),this.viewportChangePos(0,0)}get width(){return this._fbWidth}get height(){return this._fbHeight}viewportChangePos(t,n){let r=this._viewportLoc;t=Math.floor(t),n=Math.floor(n),this._clipViewport||(t=-r.w,n=-r.h);let o=r.x+r.w-1,s=r.y+r.h-1;t<0&&r.x+t<0&&(t=-r.x),o+t>=this._fbWidth&&(t-=o+t-this._fbWidth+1),r.y+n<0&&(n=-r.y),s+n>=this._fbHeight&&(n-=s+n-this._fbHeight+1),!(t===0&&n===0)&&(de("viewportChange deltaX: "+t+", deltaY: "+n),r.x+=t,r.y+=n,this._damage(r.x,r.y,r.w,r.h),this.flip())}viewportChangeSize(t,n){(!this._clipViewport||typeof t>"u"||typeof n>"u")&&(de("Setting viewport to full display region"),t=this._fbWidth,n=this._fbHeight),t=Math.floor(t),n=Math.floor(n),t>this._fbWidth&&(t=this._fbWidth),n>this._fbHeight&&(n=this._fbHeight);let r=this._viewportLoc;if(r.w!==t||r.h!==n){r.w=t,r.h=n;let o=this._target;o.width=t,o.height=n,this.viewportChangePos(0,0),this._damage(r.x,r.y,r.w,r.h),this.flip(),this._rescale(this._scale)}}absX(t){return this._scale===0?0:Ri(t/this._scale+this._viewportLoc.x)}absY(t){return this._scale===0?0:Ri(t/this._scale+this._viewportLoc.y)}resize(t,n){this._prevDrawStyle="",this._fbWidth=t,this._fbHeight=n;let r=this._backbuffer;if(r.width!==t||r.height!==n){let s=null;r.width>0&&r.height>0&&(s=this._drawCtx.getImageData(0,0,r.width,r.height)),r.width!==t&&(r.width=t),r.height!==n&&(r.height=n),s&&this._drawCtx.putImageData(s,0,0)}let o=this._viewportLoc;this.viewportChangeSize(o.w,o.h),this.viewportChangePos(0,0)}getImageData(){return this._drawCtx.getImageData(0,0,this.width,this.height)}toDataURL(t,n){return this._backbuffer.toDataURL(t,n)}toBlob(t,n,r){return this._backbuffer.toBlob(t,n,r)}_damage(t,n,r,o){t<this._damageBounds.left&&(this._damageBounds.left=t),n<this._damageBounds.top&&(this._damageBounds.top=n),t+r>this._damageBounds.right&&(this._damageBounds.right=t+r),n+o>this._damageBounds.bottom&&(this._damageBounds.bottom=n+o)}flip(t){if(this._renderQ.length!==0&&!t)this._renderQPush({type:"flip"});else{let n=this._damageBounds.left,r=this._damageBounds.top,o=this._damageBounds.right-n,s=this._damageBounds.bottom-r,i=n-this._viewportLoc.x,a=r-this._viewportLoc.y;i<0&&(o+=i,n-=i,i=0),a<0&&(s+=a,r-=a,a=0),i+o>this._viewportLoc.w&&(o=this._viewportLoc.w-i),a+s>this._viewportLoc.h&&(s=this._viewportLoc.h-a),o>0&&s>0&&this._targetCtx.drawImage(this._backbuffer,n,r,o,s,i,a,o,s),this._damageBounds.left=this._damageBounds.top=65535,this._damageBounds.right=this._damageBounds.bottom=0}}pending(){return this._renderQ.length>0}flush(){return this._renderQ.length===0?Promise.resolve():(this._flushPromise===null&&(this._flushPromise=new Promise(t=>{this._flushResolve=t})),this._flushPromise)}fillRect(t,n,r,o,s,i){this._renderQ.length!==0&&!i?this._renderQPush({type:"fill",x:t,y:n,width:r,height:o,color:s}):(this._setFillColor(s),this._drawCtx.fillRect(t,n,r,o),this._damage(t,n,r,o))}copyImage(t,n,r,o,s,i,a){this._renderQ.length!==0&&!a?this._renderQPush({type:"copy",oldX:t,oldY:n,x:r,y:o,width:s,height:i}):(this._drawCtx.mozImageSmoothingEnabled=!1,this._drawCtx.webkitImageSmoothingEnabled=!1,this._drawCtx.msImageSmoothingEnabled=!1,this._drawCtx.imageSmoothingEnabled=!1,this._drawCtx.drawImage(this._backbuffer,t,n,s,i,r,o,s,i),this._damage(r,o,s,i))}imageRect(t,n,r,o,s,i){if(r===0||o===0)return;let a=new Image;a.src="data: "+s+";base64,"+Lo.encode(i),this._renderQPush({type:"img",img:a,x:t,y:n,width:r,height:o})}videoFrame(t,n,r,o,s){this._renderQPush({type:"frame",frame:s,x:t,y:n,width:r,height:o})}blitImage(t,n,r,o,s,i,a){if(this._renderQ.length!==0&&!a){let u=new Uint8Array(r*o*4);u.set(new Uint8Array(s.buffer,0,u.length)),this._renderQPush({type:"blit",data:u,x:t,y:n,width:r,height:o})}else{let u=new Uint8ClampedArray(s.buffer,s.byteOffset+i,r*o*4),c=new ImageData(u,r,o);this._drawCtx.putImageData(c,t,n),this._damage(t,n,r,o)}}drawImage(t,...n){if(this._drawCtx.drawImage(t,...n),n.length<=4){let[r,o]=n;this._damage(r,o,t.width,t.height)}else{let[,,r,o,s,i]=n;this._damage(s,i,r,o)}}autoscale(t,n){let r;if(t===0||n===0)r=0;else{let o=this._viewportLoc,s=t/n;o.w/o.h>=s?r=t/o.w:r=n/o.h}this._rescale(r)}_rescale(t){this._scale=t;let n=this._viewportLoc,r=t*n.w+"px",o=t*n.h+"px";(this._target.style.width!==r||this._target.style.height!==o)&&(this._target.style.width=r,this._target.style.height=o)}_setFillColor(t){let n="rgb("+t[0]+","+t[1]+","+t[2]+")";n!==this._prevDrawStyle&&(this._drawCtx.fillStyle=n,this._prevDrawStyle=n)}_renderQPush(t){this._renderQ.push(t),this._renderQ.length===1&&this._scanRenderQ()}_resumeRenderQ(){this.removeEventListener("load",this._noVNCDisplay._resumeRenderQ),this._noVNCDisplay._scanRenderQ()}_scanRenderQ(){let t=!0;for(;t&&this._renderQ.length>0;){let n=this._renderQ[0];switch(n.type){case"flip":this.flip(!0);break;case"copy":this.copyImage(n.oldX,n.oldY,n.x,n.y,n.width,n.height,!0);break;case"fill":this.fillRect(n.x,n.y,n.width,n.height,n.color,!0);break;case"blit":this.blitImage(n.x,n.y,n.width,n.height,n.data,0,!0);break;case"img":if(n.img.complete){if(n.img.width!==n.width||n.img.height!==n.height){Me("Decoded image has incorrect dimensions. Got "+n.img.width+"x"+n.img.height+". Expected "+n.width+"x"+n.height+".");return}this.drawImage(n.img,n.x,n.y),n.img.src=""}else n.img._noVNCDisplay=this,n.img.addEventListener("load",this._resumeRenderQ),t=!1;break;case"frame":if(n.frame.ready){let r=n.frame.frame;(r.codedWidth<n.width||r.codedHeight<n.height)&&qe("Decoded video frame does not cover its full rectangle area. Expecting at least "+n.width+"x"+n.height+" but got "+r.codedWidth+"x"+r.codedHeight);let o=0,s=0,i=n.width,a=n.height,u=n.x,c=n.y,d=i,p=a;this.drawImage(r,o,s,i,a,u,c,d,p),r.close()}else{let r=this;n.frame.promise.then(()=>{r._scanRenderQ()}),t=!1}break}t&&this._renderQ.shift()}this._renderQ.length===0&&this._flushPromise!==null&&(this._flushResolve(),this._flushPromise=null,this._flushResolve=null)}};function Xt(e,t,n,r,o){if(t.subarray&&e.subarray){e.set(t.subarray(n,n+r),o);return}for(var s=0;s<r;s++)e[o+s]=t[n+s]}var zo=Uint8Array,bt=Uint16Array,Pi=Int32Array;function Ko(e,t,n,r){for(var o=e&65535|0,s=e>>>16&65535|0,i=0;n!==0;){i=n>2e3?2e3:n,n-=i;do o=o+t[r++]|0,s=s+o|0;while(--i);o%=65521,s%=65521}return o|s<<16|0}function Ue(){for(var e,t=[],n=0;n<256;n++){e=n;for(var r=0;r<8;r++)e=e&1?3988292384^e>>>1:e>>>1;t[n]=e}return t}var Zz=Ue();var cc=30,j2=12;function Kf(e,t){var n,r,o,s,i,a,u,c,d,p,f,h,g,x,b,_,w,T,y,E,k,N,$,P,L;n=e.state,r=e.next_in,P=e.input,o=r+(e.avail_in-5),s=e.next_out,L=e.output,i=s-(t-e.avail_out),a=s+(e.avail_out-257),u=n.dmax,c=n.wsize,d=n.whave,p=n.wnext,f=n.window,h=n.hold,g=n.bits,x=n.lencode,b=n.distcode,_=(1<<n.lenbits)-1,w=(1<<n.distbits)-1;e:do{g<15&&(h+=P[r++]<<g,g+=8,h+=P[r++]<<g,g+=8),T=x[h&_];t:for(;;){if(y=T>>>24,h>>>=y,g-=y,y=T>>>16&255,y===0)L[s++]=T&65535;else if(y&16){E=T&65535,y&=15,y&&(g<y&&(h+=P[r++]<<g,g+=8),E+=h&(1<<y)-1,h>>>=y,g-=y),g<15&&(h+=P[r++]<<g,g+=8,h+=P[r++]<<g,g+=8),T=b[h&w];n:for(;;){if(y=T>>>24,h>>>=y,g-=y,y=T>>>16&255,y&16){if(k=T&65535,y&=15,g<y&&(h+=P[r++]<<g,g+=8,g<y&&(h+=P[r++]<<g,g+=8)),k+=h&(1<<y)-1,k>u){e.msg="invalid distance too far back",n.mode=cc;break e}if(h>>>=y,g-=y,y=s-i,k>y){if(y=k-y,y>d&&n.sane){e.msg="invalid distance too far back",n.mode=cc;break e}if(N=0,$=f,p===0){if(N+=c-y,y<E){E-=y;do L[s++]=f[N++];while(--y);N=s-k,$=L}}else if(p<y){if(N+=c+p-y,y-=p,y<E){E-=y;do L[s++]=f[N++];while(--y);if(N=0,p<E){y=p,E-=y;do L[s++]=f[N++];while(--y);N=s-k,$=L}}}else if(N+=p-y,y<E){E-=y;do L[s++]=f[N++];while(--y);N=s-k,$=L}for(;E>2;)L[s++]=$[N++],L[s++]=$[N++],L[s++]=$[N++],E-=3;E&&(L[s++]=$[N++],E>1&&(L[s++]=$[N++]))}else{N=s-k;do L[s++]=L[N++],L[s++]=L[N++],L[s++]=L[N++],E-=3;while(E>2);E&&(L[s++]=L[N++],E>1&&(L[s++]=L[N++]))}}else if((y&64)===0){T=b[(T&65535)+(h&(1<<y)-1)];continue n}else{e.msg="invalid distance code",n.mode=cc;break e}break}}else if((y&64)===0){T=x[(T&65535)+(h&(1<<y)-1)];continue t}else if(y&32){n.mode=j2;break e}else{e.msg="invalid literal/length code",n.mode=cc;break e}break}}while(r<o&&s<a);E=g>>3,r-=E,g-=E<<3,h&=(1<<g)-1,e.next_in=r,e.next_out=s,e.avail_in=r<o?5+(o-r):5-(r-o),e.avail_out=s<a?257+(a-s):257-(s-a),n.hold=h,n.bits=g}var Xo=15,yv=852,_v=592,vv=0,Xf=1,wv=2,Q2=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],G2=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],Y2=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],q2=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];function Mr(e,t,n,r,o,s,i,a){var u=a.bits,c=0,d=0,p=0,f=0,h=0,g=0,x=0,b=0,_=0,w=0,T,y,E,k,N,$=null,P=0,L,ne=new bt(Xo+1),se=new bt(Xo+1),_e=null,ie=0,Q,j,Y;for(c=0;c<=Xo;c++)ne[c]=0;for(d=0;d<r;d++)ne[t[n+d]]++;for(h=u,f=Xo;f>=1&&ne[f]===0;f--);if(h>f&&(h=f),f===0)return o[s++]=1<<24|64<<16|0,o[s++]=1<<24|64<<16|0,a.bits=1,0;for(p=1;p<f&&ne[p]===0;p++);for(h<p&&(h=p),b=1,c=1;c<=Xo;c++)if(b<<=1,b-=ne[c],b<0)return-1;if(b>0&&(e===vv||f!==1))return-1;for(se[1]=0,c=1;c<Xo;c++)se[c+1]=se[c]+ne[c];for(d=0;d<r;d++)t[n+d]!==0&&(i[se[t[n+d]]++]=d);if(e===vv?($=_e=i,L=19):e===Xf?($=Q2,P-=257,_e=G2,ie-=257,L=256):($=Y2,_e=q2,L=-1),w=0,d=0,c=p,N=s,g=h,x=0,E=-1,_=1<<h,k=_-1,e===Xf&&_>yv||e===wv&&_>_v)return 1;for(;;){Q=c-x,i[d]<L?(j=0,Y=i[d]):i[d]>L?(j=_e[ie+i[d]],Y=$[P+i[d]]):(j=96,Y=0),T=1<<c-x,y=1<<g,p=y;do y-=T,o[N+(w>>x)+y]=Q<<24|j<<16|Y|0;while(y!==0);for(T=1<<c-1;w&T;)T>>=1;if(T!==0?(w&=T-1,w+=T):w=0,d++,--ne[c]===0){if(c===f)break;c=t[n+i[d]]}if(c>h&&(w&k)!==E){for(x===0&&(x=h),N+=p,g=c-x,b=1<<g;g+x<f&&(b-=ne[g+x],!(b<=0));)g++,b<<=1;if(_+=1<<g,e===Xf&&_>yv||e===wv&&_>_v)return 1;E=w&k,o[E]=h<<24|g<<16|N-s|0}}return w!==0&&(o[N+w]=c-x<<24|64<<16|0),a.bits=h,0}var J2=0,Yv=1,qv=2,kv=4,eR=5,uc=6,fc=0,tR=1,nR=2,Dr=-2,rR=-3,Sv=-4,oR=-5,Ev=8,Jv=1,Nv=2,Av=3,Cv=4,Tv=5,Rv=6,$v=7,Iv=8,Pv=9,Ov=10,Lv=11,In=12,Bf=13,Mv=14,Uf=15,Dv=16,Fv=17,zv=18,Kv=19,dc=20,pc=21,Xv=22,Bv=23,Uv=24,Hv=25,Vv=26,Hf=27,Zv=28,Wv=29,Ke=30,jv=31,sR=32,iR=852,aR=592,lR=15,cR=lR;function Qv(e){return(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24)}function uR(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new bt(320),this.work=new bt(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function dR(e){var t;return!e||!e.state?Dr:(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=t.wrap&1),t.mode=Jv,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Pi(iR),t.distcode=t.distdyn=new Pi(aR),t.sane=1,t.back=-1,fc)}function Wf(e){var t;return!e||!e.state?Dr:(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,dR(e))}function pR(e,t){var n,r;return!e||!e.state||(r=e.state,t<0?(n=0,t=-t):(n=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?Dr:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,Wf(e))}function fR(e,t){var n,r;return e?(r=new uR,e.state=r,r.window=null,n=pR(e,t),n!==fc&&(e.state=null),n):Dr}function ew(e){return fR(e,cR)}var Gv=!0,Vf,Zf;function hR(e){if(Gv){var t;for(Vf=new Pi(512),Zf=new Pi(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(Mr(Yv,e.lens,0,288,Vf,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;Mr(qv,e.lens,0,32,Zf,0,e.work,{bits:5}),Gv=!1}e.lencode=Vf,e.lenbits=9,e.distcode=Zf,e.distbits=5}function mR(e,t,n,r){var o,s=e.state;return s.window===null&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new zo(s.wsize)),r>=s.wsize?(Xt(s.window,t,n-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):(o=s.wsize-s.wnext,o>r&&(o=r),Xt(s.window,t,n-r,o,s.wnext),r-=o,r?(Xt(s.window,t,n-r,r,0),s.wnext=r,s.whave=s.wsize):(s.wnext+=o,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=o))),0}function tw(e,t){var n,r,o,s,i,a,u,c,d,p,f,h,g,x,b=0,_,w,T,y,E,k,N,$,P=new zo(4),L,ne,se=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&e.avail_in!==0)return Dr;n=e.state,n.mode===In&&(n.mode=Bf),i=e.next_out,o=e.output,u=e.avail_out,s=e.next_in,r=e.input,a=e.avail_in,c=n.hold,d=n.bits,p=a,f=u,$=fc;e:for(;;)switch(n.mode){case Jv:if(n.wrap===0){n.mode=Bf;break}for(;d<16;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if(n.wrap&2&&c===35615){n.check=0,P[0]=c&255,P[1]=c>>>8&255,n.check=Ue(n.check,P,2,0),c=0,d=0,n.mode=Nv;break}if(n.flags=0,n.head&&(n.head.done=!1),!(n.wrap&1)||(((c&255)<<8)+(c>>8))%31){e.msg="incorrect header check",n.mode=Ke;break}if((c&15)!==Ev){e.msg="unknown compression method",n.mode=Ke;break}if(c>>>=4,d-=4,N=(c&15)+8,n.wbits===0)n.wbits=N;else if(N>n.wbits){e.msg="invalid window size",n.mode=Ke;break}n.dmax=1<<N,e.adler=n.check=1,n.mode=c&512?Ov:In,c=0,d=0;break;case Nv:for(;d<16;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if(n.flags=c,(n.flags&255)!==Ev){e.msg="unknown compression method",n.mode=Ke;break}if(n.flags&57344){e.msg="unknown header flags set",n.mode=Ke;break}n.head&&(n.head.text=c>>8&1),n.flags&512&&(P[0]=c&255,P[1]=c>>>8&255,n.check=Ue(n.check,P,2,0)),c=0,d=0,n.mode=Av;case Av:for(;d<32;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}n.head&&(n.head.time=c),n.flags&512&&(P[0]=c&255,P[1]=c>>>8&255,P[2]=c>>>16&255,P[3]=c>>>24&255,n.check=Ue(n.check,P,4,0)),c=0,d=0,n.mode=Cv;case Cv:for(;d<16;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}n.head&&(n.head.xflags=c&255,n.head.os=c>>8),n.flags&512&&(P[0]=c&255,P[1]=c>>>8&255,n.check=Ue(n.check,P,2,0)),c=0,d=0,n.mode=Tv;case Tv:if(n.flags&1024){for(;d<16;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}n.length=c,n.head&&(n.head.extra_len=c),n.flags&512&&(P[0]=c&255,P[1]=c>>>8&255,n.check=Ue(n.check,P,2,0)),c=0,d=0}else n.head&&(n.head.extra=null);n.mode=Rv;case Rv:if(n.flags&1024&&(h=n.length,h>a&&(h=a),h&&(n.head&&(N=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),Xt(n.head.extra,r,s,h,N)),n.flags&512&&(n.check=Ue(n.check,r,h,s)),a-=h,s+=h,n.length-=h),n.length))break e;n.length=0,n.mode=$v;case $v:if(n.flags&2048){if(a===0)break e;h=0;do N=r[s+h++],n.head&&N&&n.length<65536&&(n.head.name+=String.fromCharCode(N));while(N&&h<a);if(n.flags&512&&(n.check=Ue(n.check,r,h,s)),a-=h,s+=h,N)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=Iv;case Iv:if(n.flags&4096){if(a===0)break e;h=0;do N=r[s+h++],n.head&&N&&n.length<65536&&(n.head.comment+=String.fromCharCode(N));while(N&&h<a);if(n.flags&512&&(n.check=Ue(n.check,r,h,s)),a-=h,s+=h,N)break e}else n.head&&(n.head.comment=null);n.mode=Pv;case Pv:if(n.flags&512){for(;d<16;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if(c!==(n.check&65535)){e.msg="header crc mismatch",n.mode=Ke;break}c=0,d=0}n.head&&(n.head.hcrc=n.flags>>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=In;break;case Ov:for(;d<32;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}e.adler=n.check=Qv(c),c=0,d=0,n.mode=Lv;case Lv:if(n.havedict===0)return e.next_out=i,e.avail_out=u,e.next_in=s,e.avail_in=a,n.hold=c,n.bits=d,nR;e.adler=n.check=1,n.mode=In;case In:if(t===eR||t===uc)break e;case Bf:if(n.last){c>>>=d&7,d-=d&7,n.mode=Hf;break}for(;d<3;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}switch(n.last=c&1,c>>>=1,d-=1,c&3){case 0:n.mode=Mv;break;case 1:if(hR(n),n.mode=dc,t===uc){c>>>=2,d-=2;break e}break;case 2:n.mode=Fv;break;case 3:e.msg="invalid block type",n.mode=Ke}c>>>=2,d-=2;break;case Mv:for(c>>>=d&7,d-=d&7;d<32;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if((c&65535)!==(c>>>16^65535)){e.msg="invalid stored block lengths",n.mode=Ke;break}if(n.length=c&65535,c=0,d=0,n.mode=Uf,t===uc)break e;case Uf:n.mode=Dv;case Dv:if(h=n.length,h){if(h>a&&(h=a),h>u&&(h=u),h===0)break e;Xt(o,r,s,h,i),a-=h,s+=h,u-=h,i+=h,n.length-=h;break}n.mode=In;break;case Fv:for(;d<14;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if(n.nlen=(c&31)+257,c>>>=5,d-=5,n.ndist=(c&31)+1,c>>>=5,d-=5,n.ncode=(c&15)+4,c>>>=4,d-=4,n.nlen>286||n.ndist>30){e.msg="too many length or distance symbols",n.mode=Ke;break}n.have=0,n.mode=zv;case zv:for(;n.have<n.ncode;){for(;d<3;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}n.lens[se[n.have++]]=c&7,c>>>=3,d-=3}for(;n.have<19;)n.lens[se[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,L={bits:n.lenbits},$=Mr(J2,n.lens,0,19,n.lencode,0,n.work,L),n.lenbits=L.bits,$){e.msg="invalid code lengths set",n.mode=Ke;break}n.have=0,n.mode=Kv;case Kv:for(;n.have<n.nlen+n.ndist;){for(;b=n.lencode[c&(1<<n.lenbits)-1],_=b>>>24,w=b>>>16&255,T=b&65535,!(_<=d);){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if(T<16)c>>>=_,d-=_,n.lens[n.have++]=T;else{if(T===16){for(ne=_+2;d<ne;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if(c>>>=_,d-=_,n.have===0){e.msg="invalid bit length repeat",n.mode=Ke;break}N=n.lens[n.have-1],h=3+(c&3),c>>>=2,d-=2}else if(T===17){for(ne=_+3;d<ne;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}c>>>=_,d-=_,N=0,h=3+(c&7),c>>>=3,d-=3}else{for(ne=_+7;d<ne;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}c>>>=_,d-=_,N=0,h=11+(c&127),c>>>=7,d-=7}if(n.have+h>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=Ke;break}for(;h--;)n.lens[n.have++]=N}}if(n.mode===Ke)break;if(n.lens[256]===0){e.msg="invalid code -- missing end-of-block",n.mode=Ke;break}if(n.lenbits=9,L={bits:n.lenbits},$=Mr(Yv,n.lens,0,n.nlen,n.lencode,0,n.work,L),n.lenbits=L.bits,$){e.msg="invalid literal/lengths set",n.mode=Ke;break}if(n.distbits=6,n.distcode=n.distdyn,L={bits:n.distbits},$=Mr(qv,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,L),n.distbits=L.bits,$){e.msg="invalid distances set",n.mode=Ke;break}if(n.mode=dc,t===uc)break e;case dc:n.mode=pc;case pc:if(a>=6&&u>=258){e.next_out=i,e.avail_out=u,e.next_in=s,e.avail_in=a,n.hold=c,n.bits=d,Kf(e,f),i=e.next_out,o=e.output,u=e.avail_out,s=e.next_in,r=e.input,a=e.avail_in,c=n.hold,d=n.bits,n.mode===In&&(n.back=-1);break}for(n.back=0;b=n.lencode[c&(1<<n.lenbits)-1],_=b>>>24,w=b>>>16&255,T=b&65535,!(_<=d);){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if(w&&(w&240)===0){for(y=_,E=w,k=T;b=n.lencode[k+((c&(1<<y+E)-1)>>y)],_=b>>>24,w=b>>>16&255,T=b&65535,!(y+_<=d);){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}c>>>=y,d-=y,n.back+=y}if(c>>>=_,d-=_,n.back+=_,n.length=T,w===0){n.mode=Vv;break}if(w&32){n.back=-1,n.mode=In;break}if(w&64){e.msg="invalid literal/length code",n.mode=Ke;break}n.extra=w&15,n.mode=Xv;case Xv:if(n.extra){for(ne=n.extra;d<ne;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}n.length+=c&(1<<n.extra)-1,c>>>=n.extra,d-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=Bv;case Bv:for(;b=n.distcode[c&(1<<n.distbits)-1],_=b>>>24,w=b>>>16&255,T=b&65535,!(_<=d);){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if((w&240)===0){for(y=_,E=w,k=T;b=n.distcode[k+((c&(1<<y+E)-1)>>y)],_=b>>>24,w=b>>>16&255,T=b&65535,!(y+_<=d);){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}c>>>=y,d-=y,n.back+=y}if(c>>>=_,d-=_,n.back+=_,w&64){e.msg="invalid distance code",n.mode=Ke;break}n.offset=T,n.extra=w&15,n.mode=Uv;case Uv:if(n.extra){for(ne=n.extra;d<ne;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}n.offset+=c&(1<<n.extra)-1,c>>>=n.extra,d-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=Ke;break}n.mode=Hv;case Hv:if(u===0)break e;if(h=f-u,n.offset>h){if(h=n.offset-h,h>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=Ke;break}h>n.wnext?(h-=n.wnext,g=n.wsize-h):g=n.wnext-h,h>n.length&&(h=n.length),x=n.window}else x=o,g=i-n.offset,h=n.length;h>u&&(h=u),u-=h,n.length-=h;do o[i++]=x[g++];while(--h);n.length===0&&(n.mode=pc);break;case Vv:if(u===0)break e;o[i++]=n.length,u--,n.mode=pc;break;case Hf:if(n.wrap){for(;d<32;){if(a===0)break e;a--,c|=r[s++]<<d,d+=8}if(f-=u,e.total_out+=f,n.total+=f,f&&(e.adler=n.check=n.flags?Ue(n.check,o,f,i-f):Ko(n.check,o,f,i-f)),f=u,(n.flags?c:Qv(c))!==n.check){e.msg="incorrect data check",n.mode=Ke;break}c=0,d=0}n.mode=Zv;case Zv:if(n.wrap&&n.flags){for(;d<32;){if(a===0)break e;a--,c+=r[s++]<<d,d+=8}if(c!==(n.total&4294967295)){e.msg="incorrect length check",n.mode=Ke;break}c=0,d=0}n.mode=Wv;case Wv:$=tR;break e;case Ke:$=rR;break e;case jv:return Sv;case sR:default:return Dr}return e.next_out=i,e.avail_out=u,e.next_in=s,e.avail_in=a,n.hold=c,n.bits=d,(n.wsize||f!==e.avail_out&&n.mode<Ke&&(n.mode<Hf||t!==kv))&&mR(e,e.output,e.next_out,f-e.avail_out)?(n.mode=jv,Sv):(p-=e.avail_in,f-=e.avail_out,e.total_in+=p,e.total_out+=f,n.total+=f,n.wrap&&f&&(e.adler=n.check=n.flags?Ue(n.check,o,f,e.next_out-f):Ko(n.check,o,f,e.next_out-f)),e.data_type=n.bits+(n.last?64:0)+(n.mode===In?128:0)+(n.mode===dc||n.mode===Uf?256:0),(p===0&&f===0||t===kv)&&$===fc&&($=oR),$)}function Oi(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var Yt=class{constructor(){this.strm=new Oi,this.chunkSize=1024*10*10,this.strm.output=new Uint8Array(this.chunkSize),ew(this.strm)}setInput(t){t?(this.strm.input=t,this.strm.avail_in=this.strm.input.length,this.strm.next_in=0):(this.strm.input=null,this.strm.avail_in=0,this.strm.next_in=0)}inflate(t){if(t>this.chunkSize&&(this.chunkSize=t,this.strm.output=new Uint8Array(this.chunkSize)),this.strm.next_out=0,this.strm.avail_out=t,tw(this.strm,0)<0)throw new Error("zlib inflate failed");if(this.strm.next_out!=t)throw new Error("Incomplete zlib block");return new Uint8Array(this.strm.output.buffer,0,this.strm.next_out)}reset(){Wf(this.strm)}};var gR=4,nw=0,rw=1,xR=2;function Uo(e){for(var t=e.length;--t>=0;)e[t]=0}var bR=0,cw=1,yR=2,_R=3,vR=258,eh=29,Ki=256,Mi=Ki+1+eh,Bo=30,th=19,uw=2*Mi+1,Fr=15,jf=16,wR=7,nh=256,dw=16,pw=17,fw=18,qf=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],hc=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],kR=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],hw=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],SR=512,Pn=new Array((Mi+2)*2);Uo(Pn);var Li=new Array(Bo*2);Uo(Li);var Di=new Array(SR);Uo(Di);var Fi=new Array(vR-_R+1);Uo(Fi);var rh=new Array(eh);Uo(rh);var mc=new Array(Bo);Uo(mc);function Qf(e,t,n,r,o){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=r,this.max_length=o,this.has_stree=e&&e.length}var mw,gw,xw;function Gf(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function bw(e){return e<256?Di[e]:Di[256+(e>>>7)]}function zi(e,t){e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255}function Nt(e,t,n){e.bi_valid>jf-n?(e.bi_buf|=t<<e.bi_valid&65535,zi(e,e.bi_buf),e.bi_buf=t>>jf-e.bi_valid,e.bi_valid+=n-jf):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=n)}function pn(e,t,n){Nt(e,n[t*2],n[t*2+1])}function yw(e,t){var n=0;do n|=e&1,e>>>=1,n<<=1;while(--t>0);return n>>>1}function ER(e){e.bi_valid===16?(zi(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)}function NR(e,t){var n=t.dyn_tree,r=t.max_code,o=t.stat_desc.static_tree,s=t.stat_desc.has_stree,i=t.stat_desc.extra_bits,a=t.stat_desc.extra_base,u=t.stat_desc.max_length,c,d,p,f,h,g,x=0;for(f=0;f<=Fr;f++)e.bl_count[f]=0;for(n[e.heap[e.heap_max]*2+1]=0,c=e.heap_max+1;c<uw;c++)d=e.heap[c],f=n[n[d*2+1]*2+1]+1,f>u&&(f=u,x++),n[d*2+1]=f,!(d>r)&&(e.bl_count[f]++,h=0,d>=a&&(h=i[d-a]),g=n[d*2],e.opt_len+=g*(f+h),s&&(e.static_len+=g*(o[d*2+1]+h)));if(x!==0){do{for(f=u-1;e.bl_count[f]===0;)f--;e.bl_count[f]--,e.bl_count[f+1]+=2,e.bl_count[u]--,x-=2}while(x>0);for(f=u;f!==0;f--)for(d=e.bl_count[f];d!==0;)p=e.heap[--c],!(p>r)&&(n[p*2+1]!==f&&(e.opt_len+=(f-n[p*2+1])*n[p*2],n[p*2+1]=f),d--)}}function _w(e,t,n){var r=new Array(Fr+1),o=0,s,i;for(s=1;s<=Fr;s++)r[s]=o=o+n[s-1]<<1;for(i=0;i<=t;i++){var a=e[i*2+1];a!==0&&(e[i*2]=yw(r[a]++,a))}}function AR(){var e,t,n,r,o,s=new Array(Fr+1);for(n=0,r=0;r<eh-1;r++)for(rh[r]=n,e=0;e<1<<qf[r];e++)Fi[n++]=r;for(Fi[n-1]=r,o=0,r=0;r<16;r++)for(mc[r]=o,e=0;e<1<<hc[r];e++)Di[o++]=r;for(o>>=7;r<Bo;r++)for(mc[r]=o<<7,e=0;e<1<<hc[r]-7;e++)Di[256+o++]=r;for(t=0;t<=Fr;t++)s[t]=0;for(e=0;e<=143;)Pn[e*2+1]=8,e++,s[8]++;for(;e<=255;)Pn[e*2+1]=9,e++,s[9]++;for(;e<=279;)Pn[e*2+1]=7,e++,s[7]++;for(;e<=287;)Pn[e*2+1]=8,e++,s[8]++;for(_w(Pn,Mi+1,s),e=0;e<Bo;e++)Li[e*2+1]=5,Li[e*2]=yw(e,5);mw=new Qf(Pn,qf,Ki+1,Mi,Fr),gw=new Qf(Li,hc,0,Bo,Fr),xw=new Qf(new Array(0),kR,0,th,wR)}function vw(e){var t;for(t=0;t<Mi;t++)e.dyn_ltree[t*2]=0;for(t=0;t<Bo;t++)e.dyn_dtree[t*2]=0;for(t=0;t<th;t++)e.bl_tree[t*2]=0;e.dyn_ltree[nh*2]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function ww(e){e.bi_valid>8?zi(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function CR(e,t,n,r){ww(e),r&&(zi(e,n),zi(e,~n)),Xt(e.pending_buf,e.window,t,n,e.pending),e.pending+=n}function ow(e,t,n,r){var o=t*2,s=n*2;return e[o]<e[s]||e[o]===e[s]&&r[t]<=r[n]}function Yf(e,t,n){for(var r=e.heap[n],o=n<<1;o<=e.heap_len&&(o<e.heap_len&&ow(t,e.heap[o+1],e.heap[o],e.depth)&&o++,!ow(t,r,e.heap[o],e.depth));)e.heap[n]=e.heap[o],n=o,o<<=1;e.heap[n]=r}function sw(e,t,n){var r,o,s=0,i,a;if(e.last_lit!==0)do r=e.pending_buf[e.d_buf+s*2]<<8|e.pending_buf[e.d_buf+s*2+1],o=e.pending_buf[e.l_buf+s],s++,r===0?pn(e,o,t):(i=Fi[o],pn(e,i+Ki+1,t),a=qf[i],a!==0&&(o-=rh[i],Nt(e,o,a)),r--,i=bw(r),pn(e,i,n),a=hc[i],a!==0&&(r-=mc[i],Nt(e,r,a)));while(s<e.last_lit);pn(e,nh,t)}function Jf(e,t){var n=t.dyn_tree,r=t.stat_desc.static_tree,o=t.stat_desc.has_stree,s=t.stat_desc.elems,i,a,u=-1,c;for(e.heap_len=0,e.heap_max=uw,i=0;i<s;i++)n[i*2]!==0?(e.heap[++e.heap_len]=u=i,e.depth[i]=0):n[i*2+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=u<2?++u:0,n[c*2]=1,e.depth[c]=0,e.opt_len--,o&&(e.static_len-=r[c*2+1]);for(t.max_code=u,i=e.heap_len>>1;i>=1;i--)Yf(e,n,i);c=s;do i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Yf(e,n,1),a=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=a,n[c*2]=n[i*2]+n[a*2],e.depth[c]=(e.depth[i]>=e.depth[a]?e.depth[i]:e.depth[a])+1,n[i*2+1]=n[a*2+1]=c,e.heap[1]=c++,Yf(e,n,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],NR(e,t),_w(n,u,e.bl_count)}function iw(e,t,n){var r,o=-1,s,i=t[1],a=0,u=7,c=4;for(i===0&&(u=138,c=3),t[(n+1)*2+1]=65535,r=0;r<=n;r++)s=i,i=t[(r+1)*2+1],!(++a<u&&s===i)&&(a<c?e.bl_tree[s*2]+=a:s!==0?(s!==o&&e.bl_tree[s*2]++,e.bl_tree[dw*2]++):a<=10?e.bl_tree[pw*2]++:e.bl_tree[fw*2]++,a=0,o=s,i===0?(u=138,c=3):s===i?(u=6,c=3):(u=7,c=4))}function aw(e,t,n){var r,o=-1,s,i=t[1],a=0,u=7,c=4;for(i===0&&(u=138,c=3),r=0;r<=n;r++)if(s=i,i=t[(r+1)*2+1],!(++a<u&&s===i)){if(a<c)do pn(e,s,e.bl_tree);while(--a!==0);else s!==0?(s!==o&&(pn(e,s,e.bl_tree),a--),pn(e,dw,e.bl_tree),Nt(e,a-3,2)):a<=10?(pn(e,pw,e.bl_tree),Nt(e,a-3,3)):(pn(e,fw,e.bl_tree),Nt(e,a-11,7));a=0,o=s,i===0?(u=138,c=3):s===i?(u=6,c=3):(u=7,c=4)}}function TR(e){var t;for(iw(e,e.dyn_ltree,e.l_desc.max_code),iw(e,e.dyn_dtree,e.d_desc.max_code),Jf(e,e.bl_desc),t=th-1;t>=3&&e.bl_tree[hw[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t}function RR(e,t,n,r){var o;for(Nt(e,t-257,5),Nt(e,n-1,5),Nt(e,r-4,4),o=0;o<r;o++)Nt(e,e.bl_tree[hw[o]*2+1],3);aw(e,e.dyn_ltree,t-1),aw(e,e.dyn_dtree,n-1)}function $R(e){var t=4093624447,n;for(n=0;n<=31;n++,t>>>=1)if(t&1&&e.dyn_ltree[n*2]!==0)return nw;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return rw;for(n=32;n<Ki;n++)if(e.dyn_ltree[n*2]!==0)return rw;return nw}var lw=!1;function kw(e){lw||(AR(),lw=!0),e.l_desc=new Gf(e.dyn_ltree,mw),e.d_desc=new Gf(e.dyn_dtree,gw),e.bl_desc=new Gf(e.bl_tree,xw),e.bi_buf=0,e.bi_valid=0,vw(e)}function oh(e,t,n,r){Nt(e,(bR<<1)+(r?1:0),3),CR(e,t,n,!0)}function Sw(e){Nt(e,cw<<1,3),pn(e,nh,Pn),ER(e)}function Ew(e,t,n,r){var o,s,i=0;e.level>0?(e.strm.data_type===xR&&(e.strm.data_type=$R(e)),Jf(e,e.l_desc),Jf(e,e.d_desc),i=TR(e),o=e.opt_len+3+7>>>3,s=e.static_len+3+7>>>3,s<=o&&(o=s)):o=s=n+5,n+4<=o&&t!==-1?oh(e,t,n,r):e.strategy===gR||s===o?(Nt(e,(cw<<1)+(r?1:0),3),sw(e,Pn,Li)):(Nt(e,(yR<<1)+(r?1:0),3),RR(e,e.l_desc.max_code+1,e.d_desc.max_code+1,i+1),sw(e,e.dyn_ltree,e.dyn_dtree)),vw(e),r&&ww(e)}function On(e,t,n){return e.pending_buf[e.d_buf+e.last_lit*2]=t>>>8&255,e.pending_buf[e.d_buf+e.last_lit*2+1]=t&255,e.pending_buf[e.l_buf+e.last_lit]=n&255,e.last_lit++,t===0?e.dyn_ltree[n*2]++:(e.matches++,t--,e.dyn_ltree[(Fi[n]+Ki+1)*2]++,e.dyn_dtree[bw(t)*2]++),e.last_lit===e.lit_bufsize-1}var Nw={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"};var Br=0,PR=1,bc=3,rr=4,Aw=5,zr=0,Cw=1,Wo=-2;var sh=-5,dh=-1,OR=1,gc=2,LR=3,MR=4,DR=0,FR=2,yc=8,zR=9,KR=15,XR=8,BR=29,UR=256,uh=UR+1+BR,HR=30,VR=19,ZR=2*uh+1,WR=15,Ae=3,nr=258,qt=nr+Ae+1,jR=32,$w=42,Tw=69,ih=73,ah=91,lh=103,Bi=113,xc=666,Je=1,Ui=2,Xr=3,jo=4,QR=3;function Vo(e,t){return e.msg=Nw[t],t}function Rw(e){return(e<<1)-(e>4?9:0)}function Kr(e){for(var t=e.length;--t>=0;)e[t]=0}function tr(e){var t=e.state,n=t.pending;n>e.avail_out&&(n=e.avail_out),n!==0&&(Xt(e.output,t.pending_buf,t.pending_out,n,e.next_out),e.next_out+=n,t.pending_out+=n,e.total_out+=n,e.avail_out-=n,t.pending-=n,t.pending===0&&(t.pending_out=0))}function st(e,t){Ew(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,tr(e.strm)}function Ne(e,t){e.pending_buf[e.pending++]=t}function Xi(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255}function GR(e,t,n,r){var o=e.avail_in;return o>r&&(o=r),o===0?0:(e.avail_in-=o,Xt(t,e.input,e.next_in,o,n),e.state.wrap===1?e.adler=Ko(e.adler,t,o,n):e.state.wrap===2&&(e.adler=Ue(e.adler,t,o,n)),e.next_in+=o,e.total_in+=o,o)}function Iw(e,t){var n=e.max_chain_length,r=e.strstart,o,s,i=e.prev_length,a=e.nice_match,u=e.strstart>e.w_size-qt?e.strstart-(e.w_size-qt):0,c=e.window,d=e.w_mask,p=e.prev,f=e.strstart+nr,h=c[r+i-1],g=c[r+i];e.prev_length>=e.good_match&&(n>>=2),a>e.lookahead&&(a=e.lookahead);do if(o=t,!(c[o+i]!==g||c[o+i-1]!==h||c[o]!==c[r]||c[++o]!==c[r+1])){r+=2,o++;do;while(c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&c[++r]===c[++o]&&r<f);if(s=nr-(f-r),r=f-nr,s>i){if(e.match_start=t,i=s,s>=a)break;h=c[r+i-1],g=c[r+i]}}while((t=p[t&d])>u&&--n!==0);return i<=e.lookahead?i:e.lookahead}function Hi(e){var t=e.w_size,n,r,o,s,i;do{if(s=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-qt)){Xt(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,r=e.hash_size,n=r;do o=e.head[--n],e.head[n]=o>=t?o-t:0;while(--r);r=t,n=r;do o=e.prev[--n],e.prev[n]=o>=t?o-t:0;while(--r);s+=t}if(e.strm.avail_in===0)break;if(r=GR(e.strm,e.window,e.strstart+e.lookahead,s),e.lookahead+=r,e.lookahead+e.insert>=Ae)for(i=e.strstart-e.insert,e.ins_h=e.window[i],e.ins_h=(e.ins_h<<e.hash_shift^e.window[i+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[i+Ae-1])&e.hash_mask,e.prev[i&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=i,i++,e.insert--,!(e.lookahead+e.insert<Ae)););}while(e.lookahead<qt&&e.strm.avail_in!==0)}function YR(e,t){var n=65535;for(n>e.pending_buf_size-5&&(n=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Hi(e),e.lookahead===0&&t===Br)return Je;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var r=e.block_start+n;if((e.strstart===0||e.strstart>=r)&&(e.lookahead=e.strstart-r,e.strstart=r,st(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-qt&&(st(e,!1),e.strm.avail_out===0))return Je}return e.insert=0,t===rr?(st(e,!0),e.strm.avail_out===0?Xr:jo):(e.strstart>e.block_start&&(st(e,!1),e.strm.avail_out===0),Je)}function ch(e,t){for(var n,r;;){if(e.lookahead<qt){if(Hi(e),e.lookahead<qt&&t===Br)return Je;if(e.lookahead===0)break}if(n=0,e.lookahead>=Ae&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+Ae-1])&e.hash_mask,n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),n!==0&&e.strstart-n<=e.w_size-qt&&(e.match_length=Iw(e,n)),e.match_length>=Ae)if(r=On(e,e.strstart-e.match_start,e.match_length-Ae),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=Ae){e.match_length--;do e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+Ae-1])&e.hash_mask,n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!==0);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else r=On(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(st(e,!1),e.strm.avail_out===0))return Je}return e.insert=e.strstart<Ae-1?e.strstart:Ae-1,t===rr?(st(e,!0),e.strm.avail_out===0?Xr:jo):e.last_lit&&(st(e,!1),e.strm.avail_out===0)?Je:Ui}function Ho(e,t){for(var n,r,o;;){if(e.lookahead<qt){if(Hi(e),e.lookahead<qt&&t===Br)return Je;if(e.lookahead===0)break}if(n=0,e.lookahead>=Ae&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+Ae-1])&e.hash_mask,n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=Ae-1,n!==0&&e.prev_length<e.max_lazy_match&&e.strstart-n<=e.w_size-qt&&(e.match_length=Iw(e,n),e.match_length<=5&&(e.strategy===OR||e.match_length===Ae&&e.strstart-e.match_start>4096)&&(e.match_length=Ae-1)),e.prev_length>=Ae&&e.match_length<=e.prev_length){o=e.strstart+e.lookahead-Ae,r=On(e,e.strstart-1-e.prev_match,e.prev_length-Ae),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=o&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+Ae-1])&e.hash_mask,n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!==0);if(e.match_available=0,e.match_length=Ae-1,e.strstart++,r&&(st(e,!1),e.strm.avail_out===0))return Je}else if(e.match_available){if(r=On(e,0,e.window[e.strstart-1]),r&&st(e,!1),e.strstart++,e.lookahead--,e.strm.avail_out===0)return Je}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(r=On(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<Ae-1?e.strstart:Ae-1,t===rr?(st(e,!0),e.strm.avail_out===0?Xr:jo):e.last_lit&&(st(e,!1),e.strm.avail_out===0)?Je:Ui}function qR(e,t){for(var n,r,o,s,i=e.window;;){if(e.lookahead<=nr){if(Hi(e),e.lookahead<=nr&&t===Br)return Je;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=Ae&&e.strstart>0&&(o=e.strstart-1,r=i[o],r===i[++o]&&r===i[++o]&&r===i[++o])){s=e.strstart+nr;do;while(r===i[++o]&&r===i[++o]&&r===i[++o]&&r===i[++o]&&r===i[++o]&&r===i[++o]&&r===i[++o]&&r===i[++o]&&o<s);e.match_length=nr-(s-o),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=Ae?(n=On(e,1,e.match_length-Ae),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(n=On(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),n&&(st(e,!1),e.strm.avail_out===0))return Je}return e.insert=0,t===rr?(st(e,!0),e.strm.avail_out===0?Xr:jo):e.last_lit&&(st(e,!1),e.strm.avail_out===0)?Je:Ui}function JR(e,t){for(var n;;){if(e.lookahead===0&&(Hi(e),e.lookahead===0)){if(t===Br)return Je;break}if(e.match_length=0,n=On(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,n&&(st(e,!1),e.strm.avail_out===0))return Je}return e.insert=0,t===rr?(st(e,!0),e.strm.avail_out===0?Xr:jo):e.last_lit&&(st(e,!1),e.strm.avail_out===0)?Je:Ui}function fn(e,t,n,r,o){this.good_length=e,this.max_lazy=t,this.nice_length=n,this.max_chain=r,this.func=o}var Zo;Zo=[new fn(0,0,0,0,YR),new fn(4,4,8,4,ch),new fn(4,5,16,8,ch),new fn(4,6,32,32,ch),new fn(4,4,16,16,Ho),new fn(8,16,32,32,Ho),new fn(8,16,128,128,Ho),new fn(8,32,128,256,Ho),new fn(32,128,258,1024,Ho),new fn(32,258,258,4096,Ho)];function e$(e){e.window_size=2*e.w_size,Kr(e.head),e.max_lazy_match=Zo[e.level].max_lazy,e.good_match=Zo[e.level].good_length,e.nice_match=Zo[e.level].nice_length,e.max_chain_length=Zo[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=Ae-1,e.match_available=0,e.ins_h=0}function t$(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=yc,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new bt(ZR*2),this.dyn_dtree=new bt((2*HR+1)*2),this.bl_tree=new bt((2*VR+1)*2),Kr(this.dyn_ltree),Kr(this.dyn_dtree),Kr(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new bt(WR+1),this.heap=new bt(2*uh+1),Kr(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new bt(2*uh+1),Kr(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function n$(e){var t;return!e||!e.state?Vo(e,Wo):(e.total_in=e.total_out=0,e.data_type=FR,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?$w:Bi,e.adler=t.wrap===2?0:1,t.last_flush=Br,kw(t),zr)}function r$(e){var t=n$(e);return t===zr&&e$(e.state),t}function o$(e,t,n,r,o,s){if(!e)return Wo;var i=1;if(t===dh&&(t=6),r<0?(i=0,r=-r):r>15&&(i=2,r-=16),o<1||o>zR||n!==yc||r<8||r>15||t<0||t>9||s<0||s>MR)return Vo(e,Wo);r===8&&(r=9);var a=new t$;return e.state=a,a.strm=e,a.wrap=i,a.gzhead=null,a.w_bits=r,a.w_size=1<<a.w_bits,a.w_mask=a.w_size-1,a.hash_bits=o+7,a.hash_size=1<<a.hash_bits,a.hash_mask=a.hash_size-1,a.hash_shift=~~((a.hash_bits+Ae-1)/Ae),a.window=new zo(a.w_size*2),a.head=new bt(a.hash_size),a.prev=new bt(a.w_size),a.lit_bufsize=1<<o+6,a.pending_buf_size=a.lit_bufsize*4,a.pending_buf=new zo(a.pending_buf_size),a.d_buf=1*a.lit_bufsize,a.l_buf=3*a.lit_bufsize,a.level=t,a.strategy=s,a.method=n,r$(e)}function Pw(e,t){return o$(e,t,yc,KR,XR,DR)}function ph(e,t){var n,r,o,s;if(!e||!e.state||t>Aw||t<0)return e?Vo(e,Wo):Wo;if(r=e.state,!e.output||!e.input&&e.avail_in!==0||r.status===xc&&t!==rr)return Vo(e,e.avail_out===0?sh:Wo);if(r.strm=e,n=r.last_flush,r.last_flush=t,r.status===$w)if(r.wrap===2)e.adler=0,Ne(r,31),Ne(r,139),Ne(r,8),r.gzhead?(Ne(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),Ne(r,r.gzhead.time&255),Ne(r,r.gzhead.time>>8&255),Ne(r,r.gzhead.time>>16&255),Ne(r,r.gzhead.time>>24&255),Ne(r,r.level===9?2:r.strategy>=gc||r.level<2?4:0),Ne(r,r.gzhead.os&255),r.gzhead.extra&&r.gzhead.extra.length&&(Ne(r,r.gzhead.extra.length&255),Ne(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(e.adler=Ue(e.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=Tw):(Ne(r,0),Ne(r,0),Ne(r,0),Ne(r,0),Ne(r,0),Ne(r,r.level===9?2:r.strategy>=gc||r.level<2?4:0),Ne(r,QR),r.status=Bi);else{var i=yc+(r.w_bits-8<<4)<<8,a=-1;r.strategy>=gc||r.level<2?a=0:r.level<6?a=1:r.level===6?a=2:a=3,i|=a<<6,r.strstart!==0&&(i|=jR),i+=31-i%31,r.status=Bi,Xi(r,i),r.strstart!==0&&(Xi(r,e.adler>>>16),Xi(r,e.adler&65535)),e.adler=1}if(r.status===Tw)if(r.gzhead.extra){for(o=r.pending;r.gzindex<(r.gzhead.extra.length&65535)&&!(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>o&&(e.adler=Ue(e.adler,r.pending_buf,r.pending-o,o)),tr(e),o=r.pending,r.pending===r.pending_buf_size));)Ne(r,r.gzhead.extra[r.gzindex]&255),r.gzindex++;r.gzhead.hcrc&&r.pending>o&&(e.adler=Ue(e.adler,r.pending_buf,r.pending-o,o)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=ih)}else r.status=ih;if(r.status===ih)if(r.gzhead.name){o=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>o&&(e.adler=Ue(e.adler,r.pending_buf,r.pending-o,o)),tr(e),o=r.pending,r.pending===r.pending_buf_size)){s=1;break}r.gzindex<r.gzhead.name.length?s=r.gzhead.name.charCodeAt(r.gzindex++)&255:s=0,Ne(r,s)}while(s!==0);r.gzhead.hcrc&&r.pending>o&&(e.adler=Ue(e.adler,r.pending_buf,r.pending-o,o)),s===0&&(r.gzindex=0,r.status=ah)}else r.status=ah;if(r.status===ah)if(r.gzhead.comment){o=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>o&&(e.adler=Ue(e.adler,r.pending_buf,r.pending-o,o)),tr(e),o=r.pending,r.pending===r.pending_buf_size)){s=1;break}r.gzindex<r.gzhead.comment.length?s=r.gzhead.comment.charCodeAt(r.gzindex++)&255:s=0,Ne(r,s)}while(s!==0);r.gzhead.hcrc&&r.pending>o&&(e.adler=Ue(e.adler,r.pending_buf,r.pending-o,o)),s===0&&(r.status=lh)}else r.status=lh;if(r.status===lh&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&tr(e),r.pending+2<=r.pending_buf_size&&(Ne(r,e.adler&255),Ne(r,e.adler>>8&255),e.adler=0,r.status=Bi)):r.status=Bi),r.pending!==0){if(tr(e),e.avail_out===0)return r.last_flush=-1,zr}else if(e.avail_in===0&&Rw(t)<=Rw(n)&&t!==rr)return Vo(e,sh);if(r.status===xc&&e.avail_in!==0)return Vo(e,sh);if(e.avail_in!==0||r.lookahead!==0||t!==Br&&r.status!==xc){var u=r.strategy===gc?JR(r,t):r.strategy===LR?qR(r,t):Zo[r.level].func(r,t);if((u===Xr||u===jo)&&(r.status=xc),u===Je||u===Xr)return e.avail_out===0&&(r.last_flush=-1),zr;if(u===Ui&&(t===PR?Sw(r):t!==Aw&&(oh(r,0,0,!1),t===bc&&(Kr(r.head),r.lookahead===0&&(r.strstart=0,r.block_start=0,r.insert=0))),tr(e),e.avail_out===0))return r.last_flush=-1,zr}return t!==rr?zr:r.wrap<=0?Cw:(r.wrap===2?(Ne(r,e.adler&255),Ne(r,e.adler>>8&255),Ne(r,e.adler>>16&255),Ne(r,e.adler>>24&255),Ne(r,e.total_in&255),Ne(r,e.total_in>>8&255),Ne(r,e.total_in>>16&255),Ne(r,e.total_in>>24&255)):(Xi(r,e.adler>>>16),Xi(r,e.adler&65535)),tr(e),r.wrap>0&&(r.wrap=-r.wrap),r.pending!==0?zr:Cw)}var Vi=class{constructor(){this.strm=new Oi,this.chunkSize=1024*10*10,this.outputBuffer=new Uint8Array(this.chunkSize),Pw(this.strm,dh)}deflate(t){this.strm.input=t,this.strm.avail_in=this.strm.input.length,this.strm.next_in=0,this.strm.output=this.outputBuffer,this.strm.avail_out=this.chunkSize,this.strm.next_out=0;let n=ph(this.strm,bc),r=new Uint8Array(this.strm.output.buffer,0,this.strm.next_out);if(n<0)throw new Error("zlib deflate failed");if(this.strm.avail_in>0){let o=[r],s=r.length;do{if(this.strm.output=new Uint8Array(this.chunkSize),this.strm.next_out=0,this.strm.avail_out=this.chunkSize,n=ph(this.strm,bc),n<0)throw new Error("zlib deflate failed");let u=new Uint8Array(this.strm.output.buffer,0,this.strm.next_out);s+=u.length,o.push(u)}while(this.strm.avail_in>0);let i=new Uint8Array(s),a=0;for(let u=0;u<o.length;u++)i.set(o[u],a),a+=o[u].length;r=i}return this.strm.input=null,this.strm.avail_in=0,this.strm.next_in=0,r}};var C={XK_VoidSymbol:16777215,XK_BackSpace:65288,XK_Tab:65289,XK_Linefeed:65290,XK_Clear:65291,XK_Return:65293,XK_Pause:65299,XK_Scroll_Lock:65300,XK_Sys_Req:65301,XK_Escape:65307,XK_Delete:65535,XK_Multi_key:65312,XK_Codeinput:65335,XK_SingleCandidate:65340,XK_MultipleCandidate:65341,XK_PreviousCandidate:65342,XK_Kanji:65313,XK_Muhenkan:65314,XK_Henkan_Mode:65315,XK_Henkan:65315,XK_Romaji:65316,XK_Hiragana:65317,XK_Katakana:65318,XK_Hiragana_Katakana:65319,XK_Zenkaku:65320,XK_Hankaku:65321,XK_Zenkaku_Hankaku:65322,XK_Touroku:65323,XK_Massyo:65324,XK_Kana_Lock:65325,XK_Kana_Shift:65326,XK_Eisu_Shift:65327,XK_Eisu_toggle:65328,XK_Kanji_Bangou:65335,XK_Zen_Koho:65341,XK_Mae_Koho:65342,XK_Home:65360,XK_Left:65361,XK_Up:65362,XK_Right:65363,XK_Down:65364,XK_Prior:65365,XK_Page_Up:65365,XK_Next:65366,XK_Page_Down:65366,XK_End:65367,XK_Begin:65368,XK_Select:65376,XK_Print:65377,XK_Execute:65378,XK_Insert:65379,XK_Undo:65381,XK_Redo:65382,XK_Menu:65383,XK_Find:65384,XK_Cancel:65385,XK_Help:65386,XK_Break:65387,XK_Mode_switch:65406,XK_script_switch:65406,XK_Num_Lock:65407,XK_KP_Space:65408,XK_KP_Tab:65417,XK_KP_Enter:65421,XK_KP_F1:65425,XK_KP_F2:65426,XK_KP_F3:65427,XK_KP_F4:65428,XK_KP_Home:65429,XK_KP_Left:65430,XK_KP_Up:65431,XK_KP_Right:65432,XK_KP_Down:65433,XK_KP_Prior:65434,XK_KP_Page_Up:65434,XK_KP_Next:65435,XK_KP_Page_Down:65435,XK_KP_End:65436,XK_KP_Begin:65437,XK_KP_Insert:65438,XK_KP_Delete:65439,XK_KP_Equal:65469,XK_KP_Multiply:65450,XK_KP_Add:65451,XK_KP_Separator:65452,XK_KP_Subtract:65453,XK_KP_Decimal:65454,XK_KP_Divide:65455,XK_KP_0:65456,XK_KP_1:65457,XK_KP_2:65458,XK_KP_3:65459,XK_KP_4:65460,XK_KP_5:65461,XK_KP_6:65462,XK_KP_7:65463,XK_KP_8:65464,XK_KP_9:65465,XK_F1:65470,XK_F2:65471,XK_F3:65472,XK_F4:65473,XK_F5:65474,XK_F6:65475,XK_F7:65476,XK_F8:65477,XK_F9:65478,XK_F10:65479,XK_F11:65480,XK_L1:65480,XK_F12:65481,XK_L2:65481,XK_F13:65482,XK_L3:65482,XK_F14:65483,XK_L4:65483,XK_F15:65484,XK_L5:65484,XK_F16:65485,XK_L6:65485,XK_F17:65486,XK_L7:65486,XK_F18:65487,XK_L8:65487,XK_F19:65488,XK_L9:65488,XK_F20:65489,XK_L10:65489,XK_F21:65490,XK_R1:65490,XK_F22:65491,XK_R2:65491,XK_F23:65492,XK_R3:65492,XK_F24:65493,XK_R4:65493,XK_F25:65494,XK_R5:65494,XK_F26:65495,XK_R6:65495,XK_F27:65496,XK_R7:65496,XK_F28:65497,XK_R8:65497,XK_F29:65498,XK_R9:65498,XK_F30:65499,XK_R10:65499,XK_F31:65500,XK_R11:65500,XK_F32:65501,XK_R12:65501,XK_F33:65502,XK_R13:65502,XK_F34:65503,XK_R14:65503,XK_F35:65504,XK_R15:65504,XK_Shift_L:65505,XK_Shift_R:65506,XK_Control_L:65507,XK_Control_R:65508,XK_Caps_Lock:65509,XK_Shift_Lock:65510,XK_Meta_L:65511,XK_Meta_R:65512,XK_Alt_L:65513,XK_Alt_R:65514,XK_Super_L:65515,XK_Super_R:65516,XK_Hyper_L:65517,XK_Hyper_R:65518,XK_ISO_Level3_Shift:65027,XK_ISO_Next_Group:65032,XK_ISO_Prev_Group:65034,XK_ISO_First_Group:65036,XK_ISO_Last_Group:65038,XK_space:32,XK_exclam:33,XK_quotedbl:34,XK_numbersign:35,XK_dollar:36,XK_percent:37,XK_ampersand:38,XK_apostrophe:39,XK_quoteright:39,XK_parenleft:40,XK_parenright:41,XK_asterisk:42,XK_plus:43,XK_comma:44,XK_minus:45,XK_period:46,XK_slash:47,XK_0:48,XK_1:49,XK_2:50,XK_3:51,XK_4:52,XK_5:53,XK_6:54,XK_7:55,XK_8:56,XK_9:57,XK_colon:58,XK_semicolon:59,XK_less:60,XK_equal:61,XK_greater:62,XK_question:63,XK_at:64,XK_A:65,XK_B:66,XK_C:67,XK_D:68,XK_E:69,XK_F:70,XK_G:71,XK_H:72,XK_I:73,XK_J:74,XK_K:75,XK_L:76,XK_M:77,XK_N:78,XK_O:79,XK_P:80,XK_Q:81,XK_R:82,XK_S:83,XK_T:84,XK_U:85,XK_V:86,XK_W:87,XK_X:88,XK_Y:89,XK_Z:90,XK_bracketleft:91,XK_backslash:92,XK_bracketright:93,XK_asciicircum:94,XK_underscore:95,XK_grave:96,XK_quoteleft:96,XK_a:97,XK_b:98,XK_c:99,XK_d:100,XK_e:101,XK_f:102,XK_g:103,XK_h:104,XK_i:105,XK_j:106,XK_k:107,XK_l:108,XK_m:109,XK_n:110,XK_o:111,XK_p:112,XK_q:113,XK_r:114,XK_s:115,XK_t:116,XK_u:117,XK_v:118,XK_w:119,XK_x:120,XK_y:121,XK_z:122,XK_braceleft:123,XK_bar:124,XK_braceright:125,XK_asciitilde:126,XK_nobreakspace:160,XK_exclamdown:161,XK_cent:162,XK_sterling:163,XK_currency:164,XK_yen:165,XK_brokenbar:166,XK_section:167,XK_diaeresis:168,XK_copyright:169,XK_ordfeminine:170,XK_guillemotleft:171,XK_notsign:172,XK_hyphen:173,XK_registered:174,XK_macron:175,XK_degree:176,XK_plusminus:177,XK_twosuperior:178,XK_threesuperior:179,XK_acute:180,XK_mu:181,XK_paragraph:182,XK_periodcentered:183,XK_cedilla:184,XK_onesuperior:185,XK_masculine:186,XK_guillemotright:187,XK_onequarter:188,XK_onehalf:189,XK_threequarters:190,XK_questiondown:191,XK_Agrave:192,XK_Aacute:193,XK_Acircumflex:194,XK_Atilde:195,XK_Adiaeresis:196,XK_Aring:197,XK_AE:198,XK_Ccedilla:199,XK_Egrave:200,XK_Eacute:201,XK_Ecircumflex:202,XK_Ediaeresis:203,XK_Igrave:204,XK_Iacute:205,XK_Icircumflex:206,XK_Idiaeresis:207,XK_ETH:208,XK_Eth:208,XK_Ntilde:209,XK_Ograve:210,XK_Oacute:211,XK_Ocircumflex:212,XK_Otilde:213,XK_Odiaeresis:214,XK_multiply:215,XK_Oslash:216,XK_Ooblique:216,XK_Ugrave:217,XK_Uacute:218,XK_Ucircumflex:219,XK_Udiaeresis:220,XK_Yacute:221,XK_THORN:222,XK_Thorn:222,XK_ssharp:223,XK_agrave:224,XK_aacute:225,XK_acircumflex:226,XK_atilde:227,XK_adiaeresis:228,XK_aring:229,XK_ae:230,XK_ccedilla:231,XK_egrave:232,XK_eacute:233,XK_ecircumflex:234,XK_ediaeresis:235,XK_igrave:236,XK_iacute:237,XK_icircumflex:238,XK_idiaeresis:239,XK_eth:240,XK_ntilde:241,XK_ograve:242,XK_oacute:243,XK_ocircumflex:244,XK_otilde:245,XK_odiaeresis:246,XK_division:247,XK_oslash:248,XK_ooblique:248,XK_ugrave:249,XK_uacute:250,XK_ucircumflex:251,XK_udiaeresis:252,XK_yacute:253,XK_thorn:254,XK_ydiaeresis:255,XK_Hangul:65329,XK_Hangul_Hanja:65332,XK_Hangul_Jeonja:65336,XF86XK_ModeLock:269025025,XF86XK_MonBrightnessUp:269025026,XF86XK_MonBrightnessDown:269025027,XF86XK_KbdLightOnOff:269025028,XF86XK_KbdBrightnessUp:269025029,XF86XK_KbdBrightnessDown:269025030,XF86XK_Standby:269025040,XF86XK_AudioLowerVolume:269025041,XF86XK_AudioMute:269025042,XF86XK_AudioRaiseVolume:269025043,XF86XK_AudioPlay:269025044,XF86XK_AudioStop:269025045,XF86XK_AudioPrev:269025046,XF86XK_AudioNext:269025047,XF86XK_HomePage:269025048,XF86XK_Mail:269025049,XF86XK_Start:269025050,XF86XK_Search:269025051,XF86XK_AudioRecord:269025052,XF86XK_Calculator:269025053,XF86XK_Memo:269025054,XF86XK_ToDoList:269025055,XF86XK_Calendar:269025056,XF86XK_PowerDown:269025057,XF86XK_ContrastAdjust:269025058,XF86XK_RockerUp:269025059,XF86XK_RockerDown:269025060,XF86XK_RockerEnter:269025061,XF86XK_Back:269025062,XF86XK_Forward:269025063,XF86XK_Stop:269025064,XF86XK_Refresh:269025065,XF86XK_PowerOff:269025066,XF86XK_WakeUp:269025067,XF86XK_Eject:269025068,XF86XK_ScreenSaver:269025069,XF86XK_WWW:269025070,XF86XK_Sleep:269025071,XF86XK_Favorites:269025072,XF86XK_AudioPause:269025073,XF86XK_AudioMedia:269025074,XF86XK_MyComputer:269025075,XF86XK_VendorHome:269025076,XF86XK_LightBulb:269025077,XF86XK_Shop:269025078,XF86XK_History:269025079,XF86XK_OpenURL:269025080,XF86XK_AddFavorite:269025081,XF86XK_HotLinks:269025082,XF86XK_BrightnessAdjust:269025083,XF86XK_Finance:269025084,XF86XK_Community:269025085,XF86XK_AudioRewind:269025086,XF86XK_BackForward:269025087,XF86XK_Launch0:269025088,XF86XK_Launch1:269025089,XF86XK_Launch2:269025090,XF86XK_Launch3:269025091,XF86XK_Launch4:269025092,XF86XK_Launch5:269025093,XF86XK_Launch6:269025094,XF86XK_Launch7:269025095,XF86XK_Launch8:269025096,XF86XK_Launch9:269025097,XF86XK_LaunchA:269025098,XF86XK_LaunchB:269025099,XF86XK_LaunchC:269025100,XF86XK_LaunchD:269025101,XF86XK_LaunchE:269025102,XF86XK_LaunchF:269025103,XF86XK_ApplicationLeft:269025104,XF86XK_ApplicationRight:269025105,XF86XK_Book:269025106,XF86XK_CD:269025107,XF86XK_Calculater:269025108,XF86XK_Clear:269025109,XF86XK_Close:269025110,XF86XK_Copy:269025111,XF86XK_Cut:269025112,XF86XK_Display:269025113,XF86XK_DOS:269025114,XF86XK_Documents:269025115,XF86XK_Excel:269025116,XF86XK_Explorer:269025117,XF86XK_Game:269025118,XF86XK_Go:269025119,XF86XK_iTouch:269025120,XF86XK_LogOff:269025121,XF86XK_Market:269025122,XF86XK_Meeting:269025123,XF86XK_MenuKB:269025125,XF86XK_MenuPB:269025126,XF86XK_MySites:269025127,XF86XK_New:269025128,XF86XK_News:269025129,XF86XK_OfficeHome:269025130,XF86XK_Open:269025131,XF86XK_Option:269025132,XF86XK_Paste:269025133,XF86XK_Phone:269025134,XF86XK_Q:269025136,XF86XK_Reply:269025138,XF86XK_Reload:269025139,XF86XK_RotateWindows:269025140,XF86XK_RotationPB:269025141,XF86XK_RotationKB:269025142,XF86XK_Save:269025143,XF86XK_ScrollUp:269025144,XF86XK_ScrollDown:269025145,XF86XK_ScrollClick:269025146,XF86XK_Send:269025147,XF86XK_Spell:269025148,XF86XK_SplitScreen:269025149,XF86XK_Support:269025150,XF86XK_TaskPane:269025151,XF86XK_Terminal:269025152,XF86XK_Tools:269025153,XF86XK_Travel:269025154,XF86XK_UserPB:269025156,XF86XK_User1KB:269025157,XF86XK_User2KB:269025158,XF86XK_Video:269025159,XF86XK_WheelButton:269025160,XF86XK_Word:269025161,XF86XK_Xfer:269025162,XF86XK_ZoomIn:269025163,XF86XK_ZoomOut:269025164,XF86XK_Away:269025165,XF86XK_Messenger:269025166,XF86XK_WebCam:269025167,XF86XK_MailForward:269025168,XF86XK_Pictures:269025169,XF86XK_Music:269025170,XF86XK_Battery:269025171,XF86XK_Bluetooth:269025172,XF86XK_WLAN:269025173,XF86XK_UWB:269025174,XF86XK_AudioForward:269025175,XF86XK_AudioRepeat:269025176,XF86XK_AudioRandomPlay:269025177,XF86XK_Subtitle:269025178,XF86XK_AudioCycleTrack:269025179,XF86XK_CycleAngle:269025180,XF86XK_FrameBack:269025181,XF86XK_FrameForward:269025182,XF86XK_Time:269025183,XF86XK_Select:269025184,XF86XK_View:269025185,XF86XK_TopMenu:269025186,XF86XK_Red:269025187,XF86XK_Green:269025188,XF86XK_Yellow:269025189,XF86XK_Blue:269025190,XF86XK_Suspend:269025191,XF86XK_Hibernate:269025192,XF86XK_TouchpadToggle:269025193,XF86XK_TouchpadOn:269025200,XF86XK_TouchpadOff:269025201,XF86XK_AudioMicMute:269025202,XF86XK_Switch_VT_1:269024769,XF86XK_Switch_VT_2:269024770,XF86XK_Switch_VT_3:269024771,XF86XK_Switch_VT_4:269024772,XF86XK_Switch_VT_5:269024773,XF86XK_Switch_VT_6:269024774,XF86XK_Switch_VT_7:269024775,XF86XK_Switch_VT_8:269024776,XF86XK_Switch_VT_9:269024777,XF86XK_Switch_VT_10:269024778,XF86XK_Switch_VT_11:269024779,XF86XK_Switch_VT_12:269024780,XF86XK_Ungrab:269024800,XF86XK_ClearGrab:269024801,XF86XK_Next_VMode:269024802,XF86XK_Prev_VMode:269024803,XF86XK_LogWindowTree:269024804,XF86XK_LogGrabInfo:269024805};var s$={256:960,257:992,258:451,259:483,260:417,261:433,262:454,263:486,264:710,265:742,266:709,267:741,268:456,269:488,270:463,271:495,272:464,273:496,274:938,275:954,278:972,279:1004,280:458,281:490,282:460,283:492,284:728,285:760,286:683,287:699,288:725,289:757,290:939,291:955,292:678,293:694,294:673,295:689,296:933,297:949,298:975,299:1007,302:967,303:999,304:681,305:697,308:684,309:700,310:979,311:1011,312:930,313:453,314:485,315:934,316:950,317:421,318:437,321:419,322:435,323:465,324:497,325:977,326:1009,327:466,328:498,330:957,331:959,332:978,333:1010,336:469,337:501,338:5052,339:5053,340:448,341:480,342:931,343:947,344:472,345:504,346:422,347:438,348:734,349:766,350:426,351:442,352:425,353:441,354:478,355:510,356:427,357:443,358:940,359:956,360:989,361:1021,362:990,363:1022,364:733,365:765,366:473,367:505,368:475,369:507,370:985,371:1017,376:5054,377:428,378:444,379:431,380:447,381:430,382:446,402:2294,466:16777681,711:439,728:418,729:511,731:434,733:445,901:1966,902:1953,904:1954,905:1955,906:1956,908:1959,910:1960,911:1963,912:1974,913:1985,914:1986,915:1987,916:1988,917:1989,918:1990,919:1991,920:1992,921:1993,922:1994,923:1995,924:1996,925:1997,926:1998,927:1999,928:2e3,929:2001,931:2002,932:2004,933:2005,934:2006,935:2007,936:2008,937:2009,938:1957,939:1961,940:1969,941:1970,942:1971,943:1972,944:1978,945:2017,946:2018,947:2019,948:2020,949:2021,950:2022,951:2023,952:2024,953:2025,954:2026,955:2027,956:2028,957:2029,958:2030,959:2031,960:2032,961:2033,962:2035,963:2034,964:2036,965:2037,966:2038,967:2039,968:2040,969:2041,970:1973,971:1977,972:1975,973:1976,974:1979,1025:1715,1026:1713,1027:1714,1028:1716,1029:1717,1030:1718,1031:1719,1032:1720,1033:1721,1034:1722,1035:1723,1036:1724,1038:1726,1039:1727,1040:1761,1041:1762,1042:1783,1043:1767,1044:1764,1045:1765,1046:1782,1047:1786,1048:1769,1049:1770,1050:1771,1051:1772,1052:1773,1053:1774,1054:1775,1055:1776,1056:1778,1057:1779,1058:1780,1059:1781,1060:1766,1061:1768,1062:1763,1063:1790,1064:1787,1065:1789,1066:1791,1067:1785,1068:1784,1069:1788,1070:1760,1071:1777,1072:1729,1073:1730,1074:1751,1075:1735,1076:1732,1077:1733,1078:1750,1079:1754,1080:1737,1081:1738,1082:1739,1083:1740,1084:1741,1085:1742,1086:1743,1087:1744,1088:1746,1089:1747,1090:1748,1091:1749,1092:1734,1093:1736,1094:1731,1095:1758,1096:1755,1097:1757,1098:1759,1099:1753,1100:1752,1101:1756,1102:1728,1103:1745,1105:1699,1106:1697,1107:1698,1108:1700,1109:1701,1110:1702,1111:1703,1112:1704,1113:1705,1114:1706,1115:1707,1116:1708,1118:1710,1119:1711,1168:1725,1169:1709,1488:3296,1489:3297,1490:3298,1491:3299,1492:3300,1493:3301,1494:3302,1495:3303,1496:3304,1497:3305,1498:3306,1499:3307,1500:3308,1501:3309,1502:3310,1503:3311,1504:3312,1505:3313,1506:3314,1507:3315,1508:3316,1509:3317,1510:3318,1511:3319,1512:3320,1513:3321,1514:3322,1548:1452,1563:1467,1567:1471,1569:1473,1570:1474,1571:1475,1572:1476,1573:1477,1574:1478,1575:1479,1576:1480,1577:1481,1578:1482,1579:1483,1580:1484,1581:1485,1582:1486,1583:1487,1584:1488,1585:1489,1586:1490,1587:1491,1588:1492,1589:1493,1590:1494,1591:1495,1592:1496,1593:1497,1594:1498,1600:1504,1601:1505,1602:1506,1603:1507,1604:1508,1605:1509,1606:1510,1607:1511,1608:1512,1609:1513,1610:1514,1611:1515,1612:1516,1613:1517,1614:1518,1615:1519,1616:1520,1617:1521,1618:1522,3585:3489,3586:3490,3587:3491,3588:3492,3589:3493,3590:3494,3591:3495,3592:3496,3593:3497,3594:3498,3595:3499,3596:3500,3597:3501,3598:3502,3599:3503,3600:3504,3601:3505,3602:3506,3603:3507,3604:3508,3605:3509,3606:3510,3607:3511,3608:3512,3609:3513,3610:3514,3611:3515,3612:3516,3613:3517,3614:3518,3615:3519,3616:3520,3617:3521,3618:3522,3619:3523,3620:3524,3621:3525,3622:3526,3623:3527,3624:3528,3625:3529,3626:3530,3627:3531,3628:3532,3629:3533,3630:3534,3631:3535,3632:3536,3633:3537,3634:3538,3635:3539,3636:3540,3637:3541,3638:3542,3639:3543,3640:3544,3641:3545,3642:3546,3647:3551,3648:3552,3649:3553,3650:3554,3651:3555,3652:3556,3653:3557,3654:3558,3655:3559,3656:3560,3657:3561,3658:3562,3659:3563,3660:3564,3661:3565,3664:3568,3665:3569,3666:3570,3667:3571,3668:3572,3669:3573,3670:3574,3671:3575,3672:3576,3673:3577,8194:2722,8195:2721,8196:2723,8197:2724,8199:2725,8200:2726,8201:2727,8202:2728,8210:2747,8211:2730,8212:2729,8213:1967,8215:3295,8216:2768,8217:2769,8218:2813,8220:2770,8221:2771,8222:2814,8224:2801,8225:2802,8226:2790,8229:2735,8230:2734,8240:2773,8242:2774,8243:2775,8248:2812,8254:1150,8361:3839,8364:8364,8453:2744,8470:1712,8471:2811,8478:2772,8482:2761,8531:2736,8532:2737,8533:2738,8534:2739,8535:2740,8536:2741,8537:2742,8538:2743,8539:2755,8540:2756,8541:2757,8542:2758,8592:2299,8593:2300,8594:2301,8595:2302,8658:2254,8660:2253,8706:2287,8711:2245,8728:3018,8730:2262,8733:2241,8734:2242,8743:2270,8744:2271,8745:2268,8746:2269,8747:2239,8756:2240,8764:2248,8771:2249,8773:16785992,8800:2237,8801:2255,8804:2236,8805:2238,8834:2266,8835:2267,8866:3068,8867:3036,8868:3010,8869:3022,8968:3027,8970:3012,8981:2810,8992:2212,8993:2213,9109:3020,9115:2219,9117:2220,9118:2221,9120:2222,9121:2215,9123:2216,9124:2217,9126:2218,9128:2223,9132:2224,9143:2209,9146:2543,9147:2544,9148:2546,9149:2547,9225:2530,9226:2533,9227:2537,9228:2531,9229:2532,9251:2732,9252:2536,9472:2211,9474:2214,9484:2210,9488:2539,9492:2541,9496:2538,9500:2548,9508:2549,9516:2551,9524:2550,9532:2542,9618:2529,9642:2791,9643:2785,9644:2779,9645:2786,9646:2783,9647:2767,9650:2792,9651:2787,9654:2781,9655:2765,9660:2793,9661:2788,9664:2780,9665:2764,9670:2528,9675:2766,9679:2782,9702:2784,9734:2789,9742:2809,9747:2762,9756:2794,9758:2795,9792:2808,9794:2807,9827:2796,9829:2798,9830:2797,9837:2806,9839:2805,10003:2803,10007:2804,10013:2777,10016:2800,10216:2748,10217:2750,12289:1188,12290:1185,12300:1186,12301:1187,12443:1246,12444:1247,12449:1191,12450:1201,12451:1192,12452:1202,12453:1193,12454:1203,12455:1194,12456:1204,12457:1195,12458:1205,12459:1206,12461:1207,12463:1208,12465:1209,12467:1210,12469:1211,12471:1212,12473:1213,12475:1214,12477:1215,12479:1216,12481:1217,12483:1199,12484:1218,12486:1219,12488:1220,12490:1221,12491:1222,12492:1223,12493:1224,12494:1225,12495:1226,12498:1227,12501:1228,12504:1229,12507:1230,12510:1231,12511:1232,12512:1233,12513:1234,12514:1235,12515:1196,12516:1236,12517:1197,12518:1237,12519:1198,12520:1238,12521:1239,12522:1240,12523:1241,12524:1242,12525:1243,12527:1244,12530:1190,12531:1245,12539:1189,12540:1200},Ow={lookup(e){if(e>=32&&e<=255)return e;let t=s$[e];return t!==void 0?t:16777216|e}};var fh={8:"Backspace",9:"Tab",10:"NumpadClear",13:"Enter",16:"ShiftLeft",17:"ControlLeft",18:"AltLeft",19:"Pause",20:"CapsLock",21:"Lang1",25:"Lang2",27:"Escape",28:"Convert",29:"NonConvert",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",41:"Select",44:"PrintScreen",45:"Insert",46:"Delete",47:"Help",48:"Digit0",49:"Digit1",50:"Digit2",51:"Digit3",52:"Digit4",53:"Digit5",54:"Digit6",55:"Digit7",56:"Digit8",57:"Digit9",91:"MetaLeft",92:"MetaRight",93:"ContextMenu",95:"Sleep",96:"Numpad0",97:"Numpad1",98:"Numpad2",99:"Numpad3",100:"Numpad4",101:"Numpad5",102:"Numpad6",103:"Numpad7",104:"Numpad8",105:"Numpad9",106:"NumpadMultiply",107:"NumpadAdd",108:"NumpadDecimal",109:"NumpadSubtract",110:"NumpadDecimal",111:"NumpadDivide",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",124:"F13",125:"F14",126:"F15",127:"F16",128:"F17",129:"F18",130:"F19",131:"F20",132:"F21",133:"F22",134:"F23",135:"F24",144:"NumLock",145:"ScrollLock",166:"BrowserBack",167:"BrowserForward",168:"BrowserRefresh",169:"BrowserStop",170:"BrowserSearch",171:"BrowserFavorites",172:"BrowserHome",173:"AudioVolumeMute",174:"AudioVolumeDown",175:"AudioVolumeUp",176:"MediaTrackNext",177:"MediaTrackPrevious",178:"MediaStop",179:"MediaPlayPause",180:"LaunchMail",181:"MediaSelect",182:"LaunchApp1",183:"LaunchApp2",225:"AltRight"};var hh={Backspace:"Backspace",AltLeft:"Alt",AltRight:"Alt",CapsLock:"CapsLock",ContextMenu:"ContextMenu",ControlLeft:"Control",ControlRight:"Control",Enter:"Enter",MetaLeft:"Meta",MetaRight:"Meta",ShiftLeft:"Shift",ShiftRight:"Shift",Tab:"Tab",Delete:"Delete",End:"End",Help:"Help",Home:"Home",Insert:"Insert",PageDown:"PageDown",PageUp:"PageUp",ArrowDown:"ArrowDown",ArrowLeft:"ArrowLeft",ArrowRight:"ArrowRight",ArrowUp:"ArrowUp",NumLock:"NumLock",NumpadBackspace:"Backspace",NumpadClear:"Clear",Escape:"Escape",F1:"F1",F2:"F2",F3:"F3",F4:"F4",F5:"F5",F6:"F6",F7:"F7",F8:"F8",F9:"F9",F10:"F10",F11:"F11",F12:"F12",F13:"F13",F14:"F14",F15:"F15",F16:"F16",F17:"F17",F18:"F18",F19:"F19",F20:"F20",F21:"F21",F22:"F22",F23:"F23",F24:"F24",F25:"F25",F26:"F26",F27:"F27",F28:"F28",F29:"F29",F30:"F30",F31:"F31",F32:"F32",F33:"F33",F34:"F34",F35:"F35",PrintScreen:"PrintScreen",ScrollLock:"ScrollLock",Pause:"Pause",BrowserBack:"BrowserBack",BrowserFavorites:"BrowserFavorites",BrowserForward:"BrowserForward",BrowserHome:"BrowserHome",BrowserRefresh:"BrowserRefresh",BrowserSearch:"BrowserSearch",BrowserStop:"BrowserStop",Eject:"Eject",LaunchApp1:"LaunchMyComputer",LaunchApp2:"LaunchCalendar",LaunchMail:"LaunchMail",MediaPlayPause:"MediaPlay",MediaStop:"MediaStop",MediaTrackNext:"MediaTrackNext",MediaTrackPrevious:"MediaTrackPrevious",Power:"Power",Sleep:"Sleep",AudioVolumeDown:"AudioVolumeDown",AudioVolumeMute:"AudioVolumeMute",AudioVolumeUp:"AudioVolumeUp",WakeUp:"WakeUp"};var Ur={};function X(e,t){if(t===void 0)throw new Error('Undefined keysym for key "'+e+'"');if(e in Ur)throw new Error('Duplicate entry for key "'+e+'"');Ur[e]=[t,t,t,t]}function _c(e,t,n){if(t===void 0)throw new Error('Undefined keysym for key "'+e+'"');if(n===void 0)throw new Error('Undefined keysym for key "'+e+'"');if(e in Ur)throw new Error('Duplicate entry for key "'+e+'"');Ur[e]=[t,t,n,t]}function Ce(e,t,n){if(t===void 0)throw new Error('Undefined keysym for key "'+e+'"');if(n===void 0)throw new Error('Undefined keysym for key "'+e+'"');if(e in Ur)throw new Error('Duplicate entry for key "'+e+'"');Ur[e]=[t,t,t,n]}_c("Alt",C.XK_Alt_L,C.XK_Alt_R);X("AltGraph",C.XK_ISO_Level3_Shift);X("CapsLock",C.XK_Caps_Lock);_c("Control",C.XK_Control_L,C.XK_Control_R);_c("Meta",C.XK_Super_L,C.XK_Super_R);X("NumLock",C.XK_Num_Lock);X("ScrollLock",C.XK_Scroll_Lock);_c("Shift",C.XK_Shift_L,C.XK_Shift_R);Ce("Enter",C.XK_Return,C.XK_KP_Enter);X("Tab",C.XK_Tab);Ce(" ",C.XK_space,C.XK_KP_Space);Ce("ArrowDown",C.XK_Down,C.XK_KP_Down);Ce("ArrowLeft",C.XK_Left,C.XK_KP_Left);Ce("ArrowRight",C.XK_Right,C.XK_KP_Right);Ce("ArrowUp",C.XK_Up,C.XK_KP_Up);Ce("End",C.XK_End,C.XK_KP_End);Ce("Home",C.XK_Home,C.XK_KP_Home);Ce("PageDown",C.XK_Next,C.XK_KP_Next);Ce("PageUp",C.XK_Prior,C.XK_KP_Prior);X("Backspace",C.XK_BackSpace);Ce("Clear",C.XK_Clear,C.XK_KP_Begin);X("Copy",C.XF86XK_Copy);X("Cut",C.XF86XK_Cut);Ce("Delete",C.XK_Delete,C.XK_KP_Delete);Ce("Insert",C.XK_Insert,C.XK_KP_Insert);X("Paste",C.XF86XK_Paste);X("Redo",C.XK_Redo);X("Undo",C.XK_Undo);X("Cancel",C.XK_Cancel);X("ContextMenu",C.XK_Menu);X("Escape",C.XK_Escape);X("Execute",C.XK_Execute);X("Find",C.XK_Find);X("Help",C.XK_Help);X("Pause",C.XK_Pause);X("Select",C.XK_Select);X("ZoomIn",C.XF86XK_ZoomIn);X("ZoomOut",C.XF86XK_ZoomOut);X("BrightnessDown",C.XF86XK_MonBrightnessDown);X("BrightnessUp",C.XF86XK_MonBrightnessUp);X("Eject",C.XF86XK_Eject);X("LogOff",C.XF86XK_LogOff);X("Power",C.XF86XK_PowerOff);X("PowerOff",C.XF86XK_PowerDown);X("PrintScreen",C.XK_Print);X("Hibernate",C.XF86XK_Hibernate);X("Standby",C.XF86XK_Standby);X("WakeUp",C.XF86XK_WakeUp);X("AllCandidates",C.XK_MultipleCandidate);X("Alphanumeric",C.XK_Eisu_toggle);X("CodeInput",C.XK_Codeinput);X("Compose",C.XK_Multi_key);X("Convert",C.XK_Henkan);X("GroupFirst",C.XK_ISO_First_Group);X("GroupLast",C.XK_ISO_Last_Group);X("GroupNext",C.XK_ISO_Next_Group);X("GroupPrevious",C.XK_ISO_Prev_Group);X("NonConvert",C.XK_Muhenkan);X("PreviousCandidate",C.XK_PreviousCandidate);X("SingleCandidate",C.XK_SingleCandidate);X("HangulMode",C.XK_Hangul);X("HanjaMode",C.XK_Hangul_Hanja);X("JunjaMode",C.XK_Hangul_Jeonja);X("Eisu",C.XK_Eisu_toggle);X("Hankaku",C.XK_Hankaku);X("Hiragana",C.XK_Hiragana);X("HiraganaKatakana",C.XK_Hiragana_Katakana);X("KanaMode",C.XK_Kana_Shift);X("KanjiMode",C.XK_Kanji);X("Katakana",C.XK_Katakana);X("Romaji",C.XK_Romaji);X("Zenkaku",C.XK_Zenkaku);X("ZenkakuHankaku",C.XK_Zenkaku_Hankaku);X("F1",C.XK_F1);X("F2",C.XK_F2);X("F3",C.XK_F3);X("F4",C.XK_F4);X("F5",C.XK_F5);X("F6",C.XK_F6);X("F7",C.XK_F7);X("F8",C.XK_F8);X("F9",C.XK_F9);X("F10",C.XK_F10);X("F11",C.XK_F11);X("F12",C.XK_F12);X("F13",C.XK_F13);X("F14",C.XK_F14);X("F15",C.XK_F15);X("F16",C.XK_F16);X("F17",C.XK_F17);X("F18",C.XK_F18);X("F19",C.XK_F19);X("F20",C.XK_F20);X("F21",C.XK_F21);X("F22",C.XK_F22);X("F23",C.XK_F23);X("F24",C.XK_F24);X("F25",C.XK_F25);X("F26",C.XK_F26);X("F27",C.XK_F27);X("F28",C.XK_F28);X("F29",C.XK_F29);X("F30",C.XK_F30);X("F31",C.XK_F31);X("F32",C.XK_F32);X("F33",C.XK_F33);X("F34",C.XK_F34);X("F35",C.XK_F35);X("Close",C.XF86XK_Close);X("MailForward",C.XF86XK_MailForward);X("MailReply",C.XF86XK_Reply);X("MailSend",C.XF86XK_Send);X("MediaFastForward",C.XF86XK_AudioForward);X("MediaPause",C.XF86XK_AudioPause);X("MediaPlay",C.XF86XK_AudioPlay);X("MediaRecord",C.XF86XK_AudioRecord);X("MediaRewind",C.XF86XK_AudioRewind);X("MediaStop",C.XF86XK_AudioStop);X("MediaTrackNext",C.XF86XK_AudioNext);X("MediaTrackPrevious",C.XF86XK_AudioPrev);X("New",C.XF86XK_New);X("Open",C.XF86XK_Open);X("Print",C.XK_Print);X("Save",C.XF86XK_Save);X("SpellCheck",C.XF86XK_Spell);X("AudioVolumeDown",C.XF86XK_AudioLowerVolume);X("AudioVolumeUp",C.XF86XK_AudioRaiseVolume);X("AudioVolumeMute",C.XF86XK_AudioMute);X("MicrophoneVolumeMute",C.XF86XK_AudioMicMute);X("LaunchApplication1",C.XF86XK_MyComputer);X("LaunchApplication2",C.XF86XK_Calculator);X("LaunchCalendar",C.XF86XK_Calendar);X("LaunchMail",C.XF86XK_Mail);X("LaunchMediaPlayer",C.XF86XK_AudioMedia);X("LaunchMusicPlayer",C.XF86XK_Music);X("LaunchPhone",C.XF86XK_Phone);X("LaunchScreenSaver",C.XF86XK_ScreenSaver);X("LaunchSpreadsheet",C.XF86XK_Excel);X("LaunchWebBrowser",C.XF86XK_WWW);X("LaunchWebCam",C.XF86XK_WebCam);X("LaunchWordProcessor",C.XF86XK_Word);X("BrowserBack",C.XF86XK_Back);X("BrowserFavorites",C.XF86XK_Favorites);X("BrowserForward",C.XF86XK_Forward);X("BrowserHome",C.XF86XK_HomePage);X("BrowserRefresh",C.XF86XK_Refresh);X("BrowserSearch",C.XF86XK_Search);X("BrowserStop",C.XF86XK_Stop);X("Dimmer",C.XF86XK_BrightnessAdjust);X("MediaAudioTrack",C.XF86XK_AudioCycleTrack);X("RandomToggle",C.XF86XK_AudioRandomPlay);X("SplitScreenToggle",C.XF86XK_SplitScreen);X("Subtitle",C.XF86XK_Subtitle);X("VideoModeNext",C.XF86XK_Next_VMode);Ce("=",C.XK_equal,C.XK_KP_Equal);Ce("+",C.XK_plus,C.XK_KP_Add);Ce("-",C.XK_minus,C.XK_KP_Subtract);Ce("*",C.XK_asterisk,C.XK_KP_Multiply);Ce("/",C.XK_slash,C.XK_KP_Divide);Ce(".",C.XK_period,C.XK_KP_Decimal);Ce(",",C.XK_comma,C.XK_KP_Separator);Ce("0",C.XK_0,C.XK_KP_0);Ce("1",C.XK_1,C.XK_KP_1);Ce("2",C.XK_2,C.XK_KP_2);Ce("3",C.XK_3,C.XK_KP_3);Ce("4",C.XK_4,C.XK_KP_4);Ce("5",C.XK_5,C.XK_KP_5);Ce("6",C.XK_6,C.XK_KP_6);Ce("7",C.XK_7,C.XK_KP_7);Ce("8",C.XK_8,C.XK_KP_8);Ce("9",C.XK_9,C.XK_KP_9);var mh=Ur;function Qo(e){if(e.code){switch(e.code){case"OSLeft":return"MetaLeft";case"OSRight":return"MetaRight"}return e.code}if(e.keyCode in fh){let t=fh[e.keyCode];if(er()&&t==="ContextMenu"&&(t="MetaRight"),e.location===2)switch(t){case"ShiftLeft":return"ShiftRight";case"ControlLeft":return"ControlRight";case"AltLeft":return"AltRight"}if(e.location===3)switch(t){case"Delete":return"NumpadDecimal";case"Insert":return"Numpad0";case"End":return"Numpad1";case"ArrowDown":return"Numpad2";case"PageDown":return"Numpad3";case"ArrowLeft":return"Numpad4";case"ArrowRight":return"Numpad6";case"Home":return"Numpad7";case"ArrowUp":return"Numpad8";case"PageUp":return"Numpad9";case"Enter":return"NumpadEnter"}return t}return"Unidentified"}function i$(e){if(e.key!==void 0&&e.key!=="Unidentified"){switch(e.key){case"OS":return"Meta";case"LaunchMyComputer":return"LaunchApplication1";case"LaunchCalculator":return"LaunchApplication2"}switch(e.key){case"UIKeyInputUpArrow":return"ArrowUp";case"UIKeyInputDownArrow":return"ArrowDown";case"UIKeyInputLeftArrow":return"ArrowLeft";case"UIKeyInputRightArrow":return"ArrowRight";case"UIKeyInputEscape":return"Escape"}return e.key==="\0"&&e.code==="NumpadDecimal"?"Delete":e.key}let t=Qo(e);return t in hh?hh[t]:e.charCode?String.fromCharCode(e.charCode):"Unidentified"}function Lw(e){let t=i$(e);if(t==="Unidentified")return null;if(t in mh){let r=e.location;if(t==="Meta"&&r===0&&(r=2),t==="Clear"&&r===3&&Qo(e)==="NumLock"&&(r=0),(r===void 0||r>3)&&(r=0),t==="Meta"){let o=Qo(e);if(o==="AltLeft")return C.XK_Meta_L;if(o==="AltRight")return C.XK_Meta_R}if(t==="Clear"&&Qo(e)==="NumLock")return C.XK_Num_Lock;if(Mo())switch(t){case"Zenkaku":case"Hankaku":return C.XK_Zenkaku_Hankaku;case"Romaji":case"KanaMode":return C.XK_Romaji}return mh[t][r]}if(t.length!==1)return null;let n=t.charCodeAt();return n?Ow.lookup(n):null}var Zi=class{constructor(t){this._target=t||null,this._keyDownList={},this._altGrArmed=!1,this._eventHandlers={keyup:this._handleKeyUp.bind(this),keydown:this._handleKeyDown.bind(this),blur:this._allKeysUp.bind(this)},this.onkeyevent=()=>{}}_sendKeyEvent(t,n,r,o=null,s=null){if(r)this._keyDownList[n]=t;else{if(!(n in this._keyDownList))return;delete this._keyDownList[n]}de("onkeyevent "+(r?"down":"up")+", keysym: "+t,", code: "+n+", numlock: "+o+", capslock: "+s),this.onkeyevent(t,n,r,o,s)}_getKeyCode(t){let n=Qo(t);if(n!=="Unidentified")return n;if(t.keyCode&&t.keyCode!==229)return"Platform"+t.keyCode;if(t.keyIdentifier){if(t.keyIdentifier.substr(0,2)!=="U+")return t.keyIdentifier;let r=parseInt(t.keyIdentifier.substr(2),16);return"Platform"+String.fromCharCode(r).toUpperCase().charCodeAt()}return"Unidentified"}_handleKeyDown(t){let n=this._getKeyCode(t),r=Lw(t),o=t.getModifierState("NumLock"),s=t.getModifierState("CapsLock");if((er()||Do())&&(o=null),this._altGrArmed&&(this._altGrArmed=!1,clearTimeout(this._altGrTimeout),n==="AltRight"&&t.timeStamp-this._altGrCtrlTime<50?r=C.XK_ISO_Level3_Shift:this._sendKeyEvent(C.XK_Control_L,"ControlLeft",!0,o,s)),n==="Unidentified"){r&&(this._sendKeyEvent(r,n,!0,o,s),this._sendKeyEvent(r,n,!1,o,s)),Or(t);return}if(er()||Do())switch(r){case C.XK_Super_L:r=C.XK_Alt_L;break;case C.XK_Super_R:r=C.XK_Super_L;break;case C.XK_Alt_L:r=C.XK_Mode_switch;break;case C.XK_Alt_R:r=C.XK_ISO_Level3_Shift;break}if(n in this._keyDownList&&(r=this._keyDownList[n]),(er()||Do())&&t.metaKey&&n!=="MetaLeft"&&n!=="MetaRight"){this._sendKeyEvent(r,n,!0,o,s),this._sendKeyEvent(r,n,!1,o,s),Or(t);return}if((er()||Do())&&n==="CapsLock"){this._sendKeyEvent(C.XK_Caps_Lock,"CapsLock",!0,o,s),this._sendKeyEvent(C.XK_Caps_Lock,"CapsLock",!1,o,s),Or(t);return}let i=[C.XK_Zenkaku_Hankaku,C.XK_Eisu_toggle,C.XK_Katakana,C.XK_Hiragana,C.XK_Romaji];if(Mo()&&i.includes(r)){this._sendKeyEvent(r,n,!0,o,s),this._sendKeyEvent(r,n,!1,o,s),Or(t);return}if(Or(t),n==="ControlLeft"&&Mo()&&!("ControlLeft"in this._keyDownList)){this._altGrArmed=!0,this._altGrTimeout=setTimeout(this._interruptAltGrSequence.bind(this),100),this._altGrCtrlTime=t.timeStamp;return}this._sendKeyEvent(r,n,!0,o,s)}_handleKeyUp(t){Or(t);let n=this._getKeyCode(t);if(this._interruptAltGrSequence(),(er()||Do())&&n==="CapsLock"){this._sendKeyEvent(C.XK_Caps_Lock,"CapsLock",!0),this._sendKeyEvent(C.XK_Caps_Lock,"CapsLock",!1);return}this._sendKeyEvent(this._keyDownList[n],n,!1),Mo()&&(n==="ShiftLeft"||n==="ShiftRight")&&("ShiftRight"in this._keyDownList&&this._sendKeyEvent(this._keyDownList.ShiftRight,"ShiftRight",!1),"ShiftLeft"in this._keyDownList&&this._sendKeyEvent(this._keyDownList.ShiftLeft,"ShiftLeft",!1))}_interruptAltGrSequence(){this._altGrArmed&&(this._altGrArmed=!1,clearTimeout(this._altGrTimeout),this._sendKeyEvent(C.XK_Control_L,"ControlLeft",!0))}_allKeysUp(){de(">> Keyboard.allKeysUp"),this._interruptAltGrSequence();for(let t in this._keyDownList)this._sendKeyEvent(this._keyDownList[t],t,!1);de("<< Keyboard.allKeysUp")}grab(){this._target.addEventListener("keydown",this._eventHandlers.keydown),this._target.addEventListener("keyup",this._eventHandlers.keyup),window.addEventListener("blur",this._eventHandlers.blur)}ungrab(){this._target.removeEventListener("keydown",this._eventHandlers.keydown),this._target.removeEventListener("keyup",this._eventHandlers.keyup),window.removeEventListener("blur",this._eventHandlers.blur),this._allKeysUp()}};var Wi=class{constructor(){this._target=null,this._state=127,this._tracked=[],this._ignored=[],this._waitingRelease=!1,this._releaseStart=0,this._longpressTimeoutId=null,this._twoTouchTimeoutId=null,this._boundEventHandler=this._eventHandler.bind(this)}attach(t){this.detach(),this._target=t,this._target.addEventListener("touchstart",this._boundEventHandler),this._target.addEventListener("touchmove",this._boundEventHandler),this._target.addEventListener("touchend",this._boundEventHandler),this._target.addEventListener("touchcancel",this._boundEventHandler)}detach(){this._target&&(this._stopLongpressTimeout(),this._stopTwoTouchTimeout(),this._target.removeEventListener("touchstart",this._boundEventHandler),this._target.removeEventListener("touchmove",this._boundEventHandler),this._target.removeEventListener("touchend",this._boundEventHandler),this._target.removeEventListener("touchcancel",this._boundEventHandler),this._target=null)}_eventHandler(t){let n;switch(t.stopPropagation(),t.preventDefault(),t.type){case"touchstart":n=this._touchStart;break;case"touchmove":n=this._touchMove;break;case"touchend":case"touchcancel":n=this._touchEnd;break}for(let r=0;r<t.changedTouches.length;r++){let o=t.changedTouches[r];n.call(this,o.identifier,o.clientX,o.clientY)}}_touchStart(t,n,r){if(this._hasDetectedGesture()||this._state===0){this._ignored.push(t);return}if(this._tracked.length>0&&Date.now()-this._tracked[0].started>250){this._state=0,this._ignored.push(t);return}if(this._waitingRelease){this._state=0,this._ignored.push(t);return}switch(this._tracked.push({id:t,started:Date.now(),active:!0,firstX:n,firstY:r,lastX:n,lastY:r,angle:0}),this._tracked.length){case 1:this._startLongpressTimeout();break;case 2:this._state&=-26,this._stopLongpressTimeout();break;case 3:this._state&=-99;break;default:this._state=0}}_touchMove(t,n,r){let o=this._tracked.find(a=>a.id===t);if(o===void 0)return;o.lastX=n,o.lastY=r;let s=n-o.firstX,i=r-o.firstY;if((o.firstX!==o.lastX||o.firstY!==o.lastY)&&(o.angle=Math.atan2(i,s)*180/Math.PI),!this._hasDetectedGesture()){if(Math.hypot(s,i)<50)return;if(this._state&=-24,this._stopLongpressTimeout(),this._tracked.length!==1&&(this._state&=-9),this._tracked.length!==2&&(this._state&=-97),this._tracked.length===2){let a=this._tracked.find(c=>c.id!==t);if(Math.hypot(a.firstX-a.lastX,a.firstY-a.lastY)>50){let c=Math.abs(o.angle-a.angle);c=Math.abs((c+180)%360-180),c>90?this._state&=-33:this._state&=-65,this._isTwoTouchTimeoutRunning()&&this._stopTwoTouchTimeout()}else this._isTwoTouchTimeoutRunning()||this._startTwoTouchTimeout()}if(!this._hasDetectedGesture())return;this._pushEvent("gesturestart")}this._pushEvent("gesturemove")}_touchEnd(t,n,r){if(this._ignored.indexOf(t)!==-1){this._ignored.splice(this._ignored.indexOf(t),1),this._ignored.length===0&&this._tracked.length===0&&(this._state=127,this._waitingRelease=!1);return}if(!this._hasDetectedGesture()&&this._isTwoTouchTimeoutRunning()&&(this._stopTwoTouchTimeout(),this._state=0),!this._hasDetectedGesture()&&(this._state&=-105,this._state&=-17,this._stopLongpressTimeout(),!this._waitingRelease))switch(this._releaseStart=Date.now(),this._waitingRelease=!0,this._tracked.length){case 1:this._state&=-7;break;case 2:this._state&=-6;break}if(this._waitingRelease){Date.now()-this._releaseStart>250&&(this._state=0),this._tracked.some(s=>Date.now()-s.started>1e3)&&(this._state=0);let o=this._tracked.find(s=>s.id===t);if(o.active=!1,this._hasDetectedGesture())this._pushEvent("gesturestart");else if(this._state!==0)return}this._hasDetectedGesture()&&this._pushEvent("gestureend");for(let o=0;o<this._tracked.length;o++)this._tracked[o].active&&this._ignored.push(this._tracked[o].id);this._tracked=[],this._state=0,this._ignored.indexOf(t)!==-1&&this._ignored.splice(this._ignored.indexOf(t),1),this._ignored.length===0&&(this._state=127,this._waitingRelease=!1)}_hasDetectedGesture(){return!(this._state===0||this._state&this._state-1||this._state&7&&this._tracked.some(t=>t.active))}_startLongpressTimeout(){this._stopLongpressTimeout(),this._longpressTimeoutId=setTimeout(()=>this._longpressTimeout(),1e3)}_stopLongpressTimeout(){clearTimeout(this._longpressTimeoutId),this._longpressTimeoutId=null}_longpressTimeout(){if(this._hasDetectedGesture())throw new Error("A longpress gesture failed, conflict with a different gesture");this._state=16,this._pushEvent("gesturestart")}_startTwoTouchTimeout(){this._stopTwoTouchTimeout(),this._twoTouchTimeoutId=setTimeout(()=>this._twoTouchTimeout(),50)}_stopTwoTouchTimeout(){clearTimeout(this._twoTouchTimeoutId),this._twoTouchTimeoutId=null}_isTwoTouchTimeoutRunning(){return this._twoTouchTimeoutId!==null}_twoTouchTimeout(){if(this._tracked.length===0)throw new Error("A pinch or two drag gesture failed, no tracked touches");let t=this._getAverageMovement(),n=Math.abs(t.x),r=Math.abs(t.y),o=this._getAverageDistance(),s=Math.abs(Math.hypot(o.first.x,o.first.y)-Math.hypot(o.last.x,o.last.y));r<s&&n<s?this._state=64:this._state=32,this._pushEvent("gesturestart"),this._pushEvent("gesturemove")}_pushEvent(t){let n={type:this._stateToGesture(this._state)},r=this._getPosition(),o=r.last;switch(t==="gesturestart"&&(o=r.first),this._state){case 32:case 64:o=r.first;break}if(n.clientX=o.x,n.clientY=o.y,this._state===64){let i=this._getAverageDistance();t==="gesturestart"?(n.magnitudeX=i.first.x,n.magnitudeY=i.first.y):(n.magnitudeX=i.last.x,n.magnitudeY=i.last.y)}else if(this._state===32)if(t==="gesturestart")n.magnitudeX=0,n.magnitudeY=0;else{let i=this._getAverageMovement();n.magnitudeX=i.x,n.magnitudeY=i.y}let s=new CustomEvent(t,{detail:n});this._target.dispatchEvent(s)}_stateToGesture(t){switch(t){case 1:return"onetap";case 2:return"twotap";case 4:return"threetap";case 8:return"drag";case 16:return"longpress";case 32:return"twodrag";case 64:return"pinch"}throw new Error("Unknown gesture state: "+t)}_getPosition(){if(this._tracked.length===0)throw new Error("Failed to get gesture position, no tracked touches");let t=this._tracked.length,n=0,r=0,o=0,s=0;for(let i=0;i<this._tracked.length;i++)n+=this._tracked[i].firstX,r+=this._tracked[i].firstY,o+=this._tracked[i].lastX,s+=this._tracked[i].lastY;return{first:{x:n/t,y:r/t},last:{x:o/t,y:s/t}}}_getAverageMovement(){if(this._tracked.length===0)throw new Error("Failed to get gesture movement, no tracked touches");let t,n;t=n=0;let r=this._tracked.length;for(let o=0;o<this._tracked.length;o++)t+=this._tracked[o].lastX-this._tracked[o].firstX,n+=this._tracked[o].lastY-this._tracked[o].firstY;return{x:t/r,y:n/r}}_getAverageDistance(){if(this._tracked.length===0)throw new Error("Failed to get gesture distance, no tracked touches");let t=this._tracked[0],n=this._tracked[this._tracked.length-1],r=Math.abs(n.firstX-t.firstX),o=Math.abs(n.firstY-t.firstY),s=Math.abs(n.lastX-t.lastX),i=Math.abs(n.lastY-t.lastY);return{first:{x:r,y:o},last:{x:s,y:i}}}};var ji=!pv||Df,Qi=class{constructor(){this._target=null,this._canvas=document.createElement("canvas"),ji&&(this._canvas.style.position="fixed",this._canvas.style.zIndex="65535",this._canvas.style.pointerEvents="none",this._canvas.style.userSelect="none",this._canvas.style.WebkitUserSelect="none",this._canvas.style.visibility="hidden"),this._position={x:0,y:0},this._hotSpot={x:0,y:0},this._eventHandlers={mouseover:this._handleMouseOver.bind(this),mouseleave:this._handleMouseLeave.bind(this),mousemove:this._handleMouseMove.bind(this),mouseup:this._handleMouseUp.bind(this)}}attach(t){if(this._target&&this.detach(),this._target=t,ji){document.body.appendChild(this._canvas);let n={capture:!0,passive:!0};this._target.addEventListener("mouseover",this._eventHandlers.mouseover,n),this._target.addEventListener("mouseleave",this._eventHandlers.mouseleave,n),this._target.addEventListener("mousemove",this._eventHandlers.mousemove,n),this._target.addEventListener("mouseup",this._eventHandlers.mouseup,n)}this.clear()}detach(){if(this._target){if(ji){let t={capture:!0,passive:!0};this._target.removeEventListener("mouseover",this._eventHandlers.mouseover,t),this._target.removeEventListener("mouseleave",this._eventHandlers.mouseleave,t),this._target.removeEventListener("mousemove",this._eventHandlers.mousemove,t),this._target.removeEventListener("mouseup",this._eventHandlers.mouseup,t),document.contains(this._canvas)&&document.body.removeChild(this._canvas)}this._target=null}}change(t,n,r,o,s){if(o===0||s===0){this.clear();return}this._position.x=this._position.x+this._hotSpot.x-n,this._position.y=this._position.y+this._hotSpot.y-r,this._hotSpot.x=n,this._hotSpot.y=r;let i=this._canvas.getContext("2d");this._canvas.width=o,this._canvas.height=s;let a=new ImageData(new Uint8ClampedArray(t),o,s);if(i.clearRect(0,0,o,s),i.putImageData(a,0,0),ji)this._updatePosition();else{let u=this._canvas.toDataURL();this._target.style.cursor="url("+u+")"+n+" "+r+", default"}}clear(){this._target.style.cursor="none",this._canvas.width=0,this._canvas.height=0,this._position.x=this._position.x+this._hotSpot.x,this._position.y=this._position.y+this._hotSpot.y,this._hotSpot.x=0,this._hotSpot.y=0}move(t,n){if(!ji)return;window.visualViewport?(this._position.x=t+window.visualViewport.offsetLeft,this._position.y=n+window.visualViewport.offsetTop):(this._position.x=t,this._position.y=n),this._updatePosition();let r=document.elementFromPoint(t,n);this._updateVisibility(r)}_handleMouseOver(t){this._handleMouseMove(t)}_handleMouseLeave(t){this._updateVisibility(t.relatedTarget)}_handleMouseMove(t){this._updateVisibility(t.target),this._position.x=t.clientX-this._hotSpot.x,this._position.y=t.clientY-this._hotSpot.y,this._updatePosition()}_handleMouseUp(t){let n=document.elementFromPoint(t.clientX,t.clientY);this._updateVisibility(n),this._captureIsActive()&&window.setTimeout(()=>{this._target&&(n=document.elementFromPoint(t.clientX,t.clientY),this._updateVisibility(n))},0)}_showCursor(){this._canvas.style.visibility==="hidden"&&(this._canvas.style.visibility="")}_hideCursor(){this._canvas.style.visibility!=="hidden"&&(this._canvas.style.visibility="hidden")}_shouldShowCursor(t){return t?t===this._target?!0:!(!this._target.contains(t)||window.getComputedStyle(t).cursor!=="none"):!1}_updateVisibility(t){this._captureIsActive()&&(t=document.captureElement),this._shouldShowCursor(t)?this._showCursor():this._hideCursor()}_updatePosition(){this._canvas.style.left=this._position.x+"px",this._canvas.style.top=this._position.y+"px"}_captureIsActive(){return document.captureElement&&document.documentElement.contains(document.captureElement)}};var gh=40*1024*1024,vc={CONNECTING:"connecting",OPEN:"open",CLOSING:"closing",CLOSED:"closed"},wc={CONNECTING:[WebSocket.CONNECTING,vc.CONNECTING],OPEN:[WebSocket.OPEN,vc.OPEN],CLOSING:[WebSocket.CLOSING,vc.CLOSING],CLOSED:[WebSocket.CLOSED,vc.CLOSED]},Mw=["send","close","binaryType","onerror","onmessage","onopen","protocol","readyState"],Gi=class{constructor(){this._websocket=null,this._rQi=0,this._rQlen=0,this._rQbufferSize=1024*1024*4,this._rQ=null,this._sQbufferSize=1024*10,this._sQlen=0,this._sQ=null,this._eventHandlers={message:()=>{},open:()=>{},close:()=>{},error:()=>{}}}get readyState(){let t;return this._websocket===null?"unused":(t=this._websocket.readyState,wc.CONNECTING.includes(t)?"connecting":wc.OPEN.includes(t)?"open":wc.CLOSING.includes(t)?"closing":wc.CLOSED.includes(t)?"closed":"unknown")}rQpeek8(){return this._rQ[this._rQi]}rQskipBytes(t){this._rQi+=t}rQshift8(){return this._rQshift(1)}rQshift16(){return this._rQshift(2)}rQshift32(){return this._rQshift(4)}_rQshift(t){let n=0;for(let r=t-1;r>=0;r--)n+=this._rQ[this._rQi++]<<r*8;return n>>>0}rQlen(){return this._rQlen-this._rQi}rQshiftStr(t){let n="";for(let r=0;r<t;r+=4096){let o=this.rQshiftBytes(Math.min(4096,t-r),!1);n+=String.fromCharCode.apply(null,o)}return n}rQshiftBytes(t,n=!0){return this._rQi+=t,n?this._rQ.slice(this._rQi-t,this._rQi):this._rQ.subarray(this._rQi-t,this._rQi)}rQshiftTo(t,n){t.set(new Uint8Array(this._rQ.buffer,this._rQi,n)),this._rQi+=n}rQpeekBytes(t,n=!0){return n?this._rQ.slice(this._rQi,this._rQi+t):this._rQ.subarray(this._rQi,this._rQi+t)}rQwait(t,n,r){if(this._rQlen-this._rQi<n){if(r){if(this._rQi<r)throw new Error("rQwait cannot backup "+r+" bytes");this._rQi-=r}return!0}return!1}sQpush8(t){this._sQensureSpace(1),this._sQ[this._sQlen++]=t}sQpush16(t){this._sQensureSpace(2),this._sQ[this._sQlen++]=t>>8&255,this._sQ[this._sQlen++]=t>>0&255}sQpush32(t){this._sQensureSpace(4),this._sQ[this._sQlen++]=t>>24&255,this._sQ[this._sQlen++]=t>>16&255,this._sQ[this._sQlen++]=t>>8&255,this._sQ[this._sQlen++]=t>>0&255}sQpushString(t){let n=t.split("").map(r=>r.charCodeAt(0));this.sQpushBytes(new Uint8Array(n))}sQpushBytes(t){for(let n=0;n<t.length;){this._sQensureSpace(1);let r=this._sQbufferSize-this._sQlen;r>t.length-n&&(r=t.length-n),this._sQ.set(t.subarray(n,n+r),this._sQlen),this._sQlen+=r,n+=r}}flush(){this._sQlen>0&&this.readyState==="open"&&(this._websocket.send(new Uint8Array(this._sQ.buffer,0,this._sQlen)),this._sQlen=0)}_sQensureSpace(t){this._sQbufferSize-this._sQlen<t&&this.flush()}off(t){this._eventHandlers[t]=()=>{}}on(t,n){this._eventHandlers[t]=n}_allocateBuffers(){this._rQ=new Uint8Array(this._rQbufferSize),this._sQ=new Uint8Array(this._sQbufferSize)}init(){this._allocateBuffers(),this._rQi=0,this._websocket=null}open(t,n){this.attach(new WebSocket(t,n))}attach(t){this.init();let n=[...Object.keys(t),...Object.getOwnPropertyNames(Object.getPrototypeOf(t))];for(let r=0;r<Mw.length;r++){let o=Mw[r];if(n.indexOf(o)<0)throw new Error("Raw channel missing property: "+o)}this._websocket=t,this._websocket.binaryType="arraybuffer",this._websocket.onmessage=this._recvMessage.bind(this),this._websocket.onopen=()=>{de(">> WebSock.onopen"),this._websocket.protocol&&Qe("Server choose sub-protocol: "+this._websocket.protocol),this._eventHandlers.open(),de("<< WebSock.onopen")},this._websocket.onclose=r=>{de(">> WebSock.onclose"),this._eventHandlers.close(r),de("<< WebSock.onclose")},this._websocket.onerror=r=>{de(">> WebSock.onerror: "+r),this._eventHandlers.error(r),de("<< WebSock.onerror: "+r)}}close(){this._websocket&&((this.readyState==="connecting"||this.readyState==="open")&&(Qe("Closing WebSocket connection"),this._websocket.close()),this._websocket.onmessage=()=>{})}_expandCompactRQ(t){let n=(this._rQlen-this._rQi+t)*8,r=this._rQbufferSize<n;if(r&&(this._rQbufferSize=Math.max(this._rQbufferSize*2,n)),this._rQbufferSize>gh&&(this._rQbufferSize=gh,this._rQbufferSize-(this._rQlen-this._rQi)<t))throw new Error("Receive queue buffer exceeded "+gh+" bytes, and the new message could not fit");if(r){let o=this._rQ.buffer;this._rQ=new Uint8Array(this._rQbufferSize),this._rQ.set(new Uint8Array(o,this._rQi,this._rQlen-this._rQi))}else this._rQ.copyWithin(0,this._rQi,this._rQlen);this._rQlen=this._rQlen-this._rQi,this._rQi=0}_recvMessage(t){this._rQlen==this._rQi&&(this._rQlen=0,this._rQi=0);let n=new Uint8Array(t.data);n.length>this._rQbufferSize-this._rQlen&&this._expandCompactRQ(n.length),this._rQ.set(n,this._rQlen),this._rQlen+=n.length,this._rQlen-this._rQi>0?this._eventHandlers.message():de("Ignoring empty message")}};var Dw={Again:57349,AltLeft:56,AltRight:57400,ArrowDown:57424,ArrowLeft:57419,ArrowRight:57421,ArrowUp:57416,AudioVolumeDown:57390,AudioVolumeMute:57376,AudioVolumeUp:57392,Backquote:41,Backslash:43,Backspace:14,BracketLeft:26,BracketRight:27,BrowserBack:57450,BrowserFavorites:57446,BrowserForward:57449,BrowserHome:57394,BrowserRefresh:57447,BrowserSearch:57445,BrowserStop:57448,CapsLock:58,Comma:51,ContextMenu:57437,ControlLeft:29,ControlRight:57373,Convert:121,Copy:57464,Cut:57404,Delete:57427,Digit0:11,Digit1:2,Digit2:3,Digit3:4,Digit4:5,Digit5:6,Digit6:7,Digit7:8,Digit8:9,Digit9:10,Eject:57469,End:57423,Enter:28,Equal:13,Escape:1,F1:59,F10:68,F11:87,F12:88,F13:93,F14:94,F15:95,F16:85,F17:57347,F18:57463,F19:57348,F2:60,F20:90,F21:116,F22:57465,F23:109,F24:111,F3:61,F4:62,F5:63,F6:64,F7:65,F8:66,F9:67,Find:57409,Help:57461,Hiragana:119,Home:57415,Insert:57426,IntlBackslash:86,IntlRo:115,IntlYen:125,KanaMode:112,Katakana:120,KeyA:30,KeyB:48,KeyC:46,KeyD:32,KeyE:18,KeyF:33,KeyG:34,KeyH:35,KeyI:23,KeyJ:36,KeyK:37,KeyL:38,KeyM:50,KeyN:49,KeyO:24,KeyP:25,KeyQ:16,KeyR:19,KeyS:31,KeyT:20,KeyU:22,KeyV:47,KeyW:17,KeyX:45,KeyY:21,KeyZ:44,Lang1:114,Lang2:113,Lang3:120,Lang4:119,Lang5:118,LaunchApp1:57451,LaunchApp2:57377,LaunchMail:57452,MediaPlayPause:57378,MediaSelect:57453,MediaStop:57380,MediaTrackNext:57369,MediaTrackPrevious:57360,MetaLeft:57435,MetaRight:57436,Minus:12,NonConvert:123,NumLock:69,Numpad0:82,Numpad1:79,Numpad2:80,Numpad3:81,Numpad4:75,Numpad5:76,Numpad6:77,Numpad7:71,Numpad8:72,Numpad9:73,NumpadAdd:78,NumpadComma:126,NumpadDecimal:83,NumpadDivide:57397,NumpadEnter:57372,NumpadEqual:89,NumpadMultiply:55,NumpadParenLeft:57462,NumpadParenRight:57467,NumpadSubtract:74,Open:100,PageDown:57425,PageUp:57417,Paste:101,Pause:57414,Period:52,Power:57438,PrintScreen:84,Props:57350,Quote:40,ScrollLock:70,Semicolon:39,ShiftLeft:42,ShiftRight:54,Slash:53,Sleep:57439,Space:57,Suspend:57381,Tab:15,Undo:57351,WakeUp:57443};var ge={encodingRaw:0,encodingCopyRect:1,encodingRRE:2,encodingHextile:5,encodingZlib:6,encodingTight:7,encodingZRLE:16,encodingTightPNG:-260,encodingJPEG:21,encodingH264:50,pseudoEncodingQualityLevel9:-23,pseudoEncodingQualityLevel0:-32,pseudoEncodingDesktopSize:-223,pseudoEncodingLastRect:-224,pseudoEncodingCursor:-239,pseudoEncodingQEMUExtendedKeyEvent:-258,pseudoEncodingQEMULedEvent:-261,pseudoEncodingDesktopName:-307,pseudoEncodingExtendedDesktopSize:-308,pseudoEncodingXvp:-309,pseudoEncodingFence:-312,pseudoEncodingContinuousUpdates:-313,pseudoEncodingExtendedMouseButtons:-316,pseudoEncodingCompressLevel9:-247,pseudoEncodingCompressLevel0:-256,pseudoEncodingVMwareCursor:1464686180,pseudoEncodingExtendedClipboard:3231835598};var kc=class e{constructor(){this._key=null}get algorithm(){return{name:"AES-ECB"}}static async importKey(t,n,r,o){let s=new e;return await s._importKey(t,r,o),s}async _importKey(t,n,r){this._key=await window.crypto.subtle.importKey("raw",t,{name:"AES-CBC"},n,r)}async encrypt(t,n){let r=new Uint8Array(n);if(r.length%16!==0||this._key===null)return null;let o=r.length/16;for(let s=0;s<o;s++){let i=new Uint8Array(await window.crypto.subtle.encrypt({name:"AES-CBC",iv:new Uint8Array(16)},this._key,r.slice(s*16,s*16+16))).slice(0,16);r.set(i,s*16)}return r}},Sc=class e{constructor(){this._rawKey=null,this._ctrKey=null,this._cbcKey=null,this._zeroBlock=new Uint8Array(16),this._prefixBlock0=this._zeroBlock,this._prefixBlock1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]),this._prefixBlock2=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2])}get algorithm(){return{name:"AES-EAX"}}async _encryptBlock(t){let n=await window.crypto.subtle.encrypt({name:"AES-CBC",iv:this._zeroBlock},this._cbcKey,t);return new Uint8Array(n).slice(0,16)}async _initCMAC(){let t=await this._encryptBlock(this._zeroBlock),n=new Uint8Array(16),r=t[0]>>>6;for(let s=0;s<15;s++)n[s]=t[s+1]>>6|t[s]<<2,t[s]=t[s+1]>>7|t[s]<<1;let o=[0,135,14,137];n[14]^=r>>>1,n[15]=t[15]<<2^o[r],t[15]=t[15]<<1^o[r>>1],this._k1=t,this._k2=n}async _encryptCTR(t,n){let r=await window.crypto.subtle.encrypt({name:"AES-CTR",counter:n,length:128},this._ctrKey,t);return new Uint8Array(r)}async _decryptCTR(t,n){let r=await window.crypto.subtle.decrypt({name:"AES-CTR",counter:n,length:128},this._ctrKey,t);return new Uint8Array(r)}async _computeCMAC(t,n){if(n.length!==16)return null;let r=Math.floor(t.length/16),o=Math.ceil(t.length/16),s=t.length-r*16,i=new Uint8Array((o+1)*16);if(i.set(n),i.set(t,16),s===0)for(let c=0;c<16;c++)i[r*16+c]^=this._k1[c];else{i[(r+1)*16+s]=128;for(let c=0;c<16;c++)i[(r+1)*16+c]^=this._k2[c]}let a=await window.crypto.subtle.encrypt({name:"AES-CBC",iv:this._zeroBlock},this._cbcKey,i);return a=new Uint8Array(a),a.slice(a.length-32,a.length-16)}static async importKey(t,n,r,o){let s=new e;return await s._importKey(t),s}async _importKey(t){this._rawKey=t,this._ctrKey=await window.crypto.subtle.importKey("raw",t,{name:"AES-CTR"},!1,["encrypt","decrypt"]),this._cbcKey=await window.crypto.subtle.importKey("raw",t,{name:"AES-CBC"},!1,["encrypt"]),await this._initCMAC()}async encrypt(t,n){let r=t.additionalData,o=t.iv,s=await this._computeCMAC(o,this._prefixBlock0),i=await this._encryptCTR(n,s),a=await this._computeCMAC(r,this._prefixBlock1),u=await this._computeCMAC(i,this._prefixBlock2);for(let d=0;d<16;d++)u[d]^=s[d]^a[d];let c=new Uint8Array(16+i.length);return c.set(i),c.set(u,i.length),c}async decrypt(t,n){let r=n.slice(0,n.length-16),o=t.additionalData,s=t.iv,i=n.slice(n.length-16),a=await this._computeCMAC(s,this._prefixBlock0),u=await this._computeCMAC(o,this._prefixBlock1),c=await this._computeCMAC(r,this._prefixBlock2);for(let p=0;p<16;p++)c[p]^=a[p]^u[p];if(c.length!==i.length)return null;for(let p=0;p<i.length;p++)if(c[p]!==i[p])return null;return await this._decryptCTR(r,a)}};var Fw=[13,16,10,23,0,4,2,27,14,5,20,9,22,18,11,3,25,7,15,6,26,19,12,1,40,51,30,36,46,54,29,39,50,44,32,47,43,48,38,55,33,52,45,41,49,35,28,31],l$=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],A=0,D,F,B,z,K,U;D=65536;F=1<<24;B=D|F;z=4;K=1024;U=z|K;var zw=[B|K,A|A,D|A,B|U,B|z,D|U,A|z,D|A,A|K,B|K,B|U,A|K,F|U,B|z,F|A,A|z,A|U,F|K,F|K,D|K,D|K,B|A,B|A,F|U,D|z,F|z,F|z,D|z,A|A,A|U,D|U,F|A,D|A,B|U,A|z,B|A,B|K,F|A,F|A,A|K,B|z,D|A,D|K,F|z,A|K,A|z,F|U,D|U,B|U,D|z,B|A,F|U,F|z,A|U,D|U,B|K,A|U,F|K,F|K,A|A,D|z,D|K,A|A,B|z];D=1<<20;F=1<<31;B=D|F;z=32;K=32768;U=z|K;var Kw=[B|U,F|K,A|K,D|U,D|A,A|z,B|z,F|U,F|z,B|U,B|K,F|A,F|K,D|A,A|z,B|z,D|K,D|z,F|U,A|A,F|A,A|K,D|U,B|A,D|z,F|z,A|A,D|K,A|U,B|K,B|A,A|U,A|A,D|U,B|z,D|A,F|U,B|A,B|K,A|K,B|A,F|K,A|z,B|U,D|U,A|z,A|K,F|A,A|U,B|K,D|A,F|z,D|z,F|U,F|z,D|z,D|K,A|A,F|K,A|U,F|A,B|z,B|U,D|K];D=1<<17;F=1<<27;B=D|F;z=8;K=512;U=z|K;var Xw=[A|U,B|K,A|A,B|z,F|K,A|A,D|U,F|K,D|z,F|z,F|z,D|A,B|U,D|z,B|A,A|U,F|A,A|z,B|K,A|K,D|K,B|A,B|z,D|U,F|U,D|K,D|A,F|U,A|z,B|U,A|K,F|A,B|K,F|A,D|z,A|U,D|A,B|K,F|K,A|A,A|K,D|z,B|U,F|K,F|z,A|K,A|A,B|z,F|U,D|A,F|A,B|U,A|z,D|U,D|K,F|z,B|A,F|U,A|U,B|A,D|U,A|z,B|z,D|K];D=8192;F=1<<23;B=D|F;z=1;K=128;U=z|K;var Bw=[B|z,D|U,D|U,A|K,B|K,F|U,F|z,D|z,A|A,B|A,B|A,B|U,A|U,A|A,F|K,F|z,A|z,D|A,F|A,B|z,A|K,F|A,D|z,D|K,F|U,A|z,D|K,F|K,D|A,B|K,B|U,A|U,F|K,F|z,B|A,B|U,A|U,A|A,A|A,B|A,D|K,F|K,F|U,A|z,B|z,D|U,D|U,A|K,B|U,A|U,A|z,D|A,F|z,D|z,B|K,F|U,D|z,D|K,F|A,B|z,A|K,F|A,D|A,B|K];D=1<<25;F=1<<30;B=D|F;z=256;K=1<<19;U=z|K;var Uw=[A|z,D|U,D|K,B|z,A|K,A|z,F|A,D|K,F|U,A|K,D|z,F|U,B|z,B|K,A|U,F|A,D|A,F|K,F|K,A|A,F|z,B|U,B|U,D|z,B|K,F|z,A|A,B|A,D|U,D|A,B|A,A|U,A|K,B|z,A|z,D|A,F|A,D|K,B|z,F|U,D|z,F|A,B|K,D|U,F|U,A|z,D|A,B|K,B|U,A|U,B|A,B|U,D|K,A|A,F|K,B|A,A|U,D|z,F|z,A|K,A|A,F|K,D|U,F|z];D=1<<22;F=1<<29;B=D|F;z=16;K=16384;U=z|K;var Hw=[F|z,B|A,A|K,B|U,B|A,A|z,B|U,D|A,F|K,D|U,D|A,F|z,D|z,F|K,F|A,A|U,A|A,D|z,F|U,A|K,D|K,F|U,A|z,B|z,B|z,A|A,D|U,B|K,A|U,D|K,B|K,F|A,F|K,A|z,B|z,D|K,B|U,D|A,A|U,F|z,D|A,F|K,F|A,A|U,F|z,B|U,D|K,B|A,D|U,B|K,A|A,B|z,A|z,A|K,B|A,D|U,A|K,D|z,F|U,A|A,B|K,F|A,D|z,F|U];D=1<<21;F=1<<26;B=D|F;z=2;K=2048;U=z|K;var Vw=[D|A,B|z,F|U,A|A,A|K,F|U,D|U,B|K,B|U,D|A,A|A,F|z,A|z,F|A,B|z,A|U,F|K,D|U,D|z,F|K,F|z,B|A,B|K,D|z,B|A,A|K,A|U,B|U,D|K,A|z,F|A,D|K,F|A,D|K,D|A,F|U,F|U,B|z,B|z,A|z,D|z,F|A,F|K,D|A,B|K,A|U,D|U,B|K,A|U,F|z,B|U,B|A,D|K,A|A,A|z,B|U,A|A,D|U,B|A,A|K,F|z,F|K,A|K,D|z];D=1<<18;F=1<<28;B=D|F;z=64;K=4096;U=z|K;var Zw=[F|U,A|K,D|A,B|U,F|A,F|U,A|z,F|A,D|z,B|A,B|U,D|K,B|K,D|U,A|K,A|z,B|A,F|z,F|K,A|U,D|K,D|z,B|z,B|K,A|U,A|A,A|A,B|z,F|z,F|K,D|U,D|A,D|U,D|A,B|K,A|K,A|z,B|z,A|K,D|U,F|K,A|z,F|z,B|A,B|z,F|A,D|A,F|U,A|A,B|U,D|z,F|z,B|A,F|K,F|U,A|A,B|U,D|K,D|K,A|U,A|U,D|z,F|A,B|K],Ec=class{constructor(t){this.keys=[];let n=[],r=[],o=[];for(let s=0,i=56;s<56;++s,i-=8){i+=i<-5?65:i<-3?31:i<-1?63:i===27?35:0;let a=i&7;n[s]=(t[i>>>3]&1<<a)!==0?1:0}for(let s=0;s<16;++s){let i=s<<1,a=i+1;o[i]=o[a]=0;for(let u=28;u<59;u+=28)for(let c=u-28;c<u;++c){let d=c+l$[s];r[c]=d<u?n[d]:n[d-28]}for(let u=0;u<24;++u)r[Fw[u]]!==0&&(o[i]|=1<<23-u),r[Fw[u+24]]!==0&&(o[a]|=1<<23-u)}for(let s=0,i=0,a=0;s<16;++s){let u=o[i++],c=o[i++];this.keys[a]=(u&16515072)<<6,this.keys[a]|=(u&4032)<<10,this.keys[a]|=(c&16515072)>>>10,this.keys[a]|=(c&4032)>>>6,++a,this.keys[a]=(u&258048)<<12,this.keys[a]|=(u&63)<<16,this.keys[a]|=(c&258048)>>>4,this.keys[a]|=c&63,++a}}enc8(t){let n=t.slice(),r=0,o,s,i;o=n[r++]<<24|n[r++]<<16|n[r++]<<8|n[r++],s=n[r++]<<24|n[r++]<<16|n[r++]<<8|n[r++],i=(o>>>4^s)&252645135,s^=i,o^=i<<4,i=(o>>>16^s)&65535,s^=i,o^=i<<16,i=(s>>>2^o)&858993459,o^=i,s^=i<<2,i=(s>>>8^o)&16711935,o^=i,s^=i<<8,s=s<<1|s>>>31&1,i=(o^s)&2863311530,o^=i,s^=i,o=o<<1|o>>>31&1;for(let a=0,u=0;a<8;++a){i=s<<28|s>>>4,i^=this.keys[u++];let c=Vw[i&63];c|=Uw[i>>>8&63],c|=Xw[i>>>16&63],c|=zw[i>>>24&63],i=s^this.keys[u++],c|=Zw[i&63],c|=Hw[i>>>8&63],c|=Bw[i>>>16&63],c|=Kw[i>>>24&63],o^=c,i=o<<28|o>>>4,i^=this.keys[u++],c=Vw[i&63],c|=Uw[i>>>8&63],c|=Xw[i>>>16&63],c|=zw[i>>>24&63],i=o^this.keys[u++],c|=Zw[i&63],c|=Hw[i>>>8&63],c|=Bw[i>>>16&63],c|=Kw[i>>>24&63],s^=c}for(s=s<<31|s>>>1,i=(o^s)&2863311530,o^=i,s^=i,o=o<<31|o>>>1,i=(o>>>8^s)&16711935,s^=i,o^=i<<8,i=(o>>>2^s)&858993459,s^=i,o^=i<<2,i=(s>>>16^o)&65535,o^=i,s^=i<<16,i=(s>>>4^o)&252645135,o^=i,s^=i<<4,i=[s,o],r=0;r<8;r++)n[r]=(i[r>>>2]>>>8*(3-r%4))%256,n[r]<0&&(n[r]+=256);return n}},Nc=class e{constructor(){this._cipher=null}get algorithm(){return{name:"DES-ECB"}}static importKey(t,n,r,o){let s=new e;return s._importKey(t),s}_importKey(t,n,r){this._cipher=new Ec(t)}encrypt(t,n){let r=new Uint8Array(n);if(r.length%8!==0||this._cipher===null)return null;let o=r.length/8;for(let s=0;s<o;s++)r.set(this._cipher.enc8(r.slice(s*8,s*8+8)),s*8);return r}},Ac=class e{constructor(){this._cipher=null}get algorithm(){return{name:"DES-CBC"}}static importKey(t,n,r,o){let s=new e;return s._importKey(t),s}_importKey(t){this._cipher=new Ec(t)}encrypt(t,n){let r=new Uint8Array(n),o=new Uint8Array(t.iv);if(r.length%8!==0||this._cipher===null)return null;let s=r.length/8;for(let i=0;i<s;i++){for(let a=0;a<8;a++)o[a]^=n[i*8+a];o=this._cipher.enc8(o),r.set(o,i*8)}return r}};function Go(e,t,n){let r=1n;for(e=e%n;t>0n;)(t&1n)===1n&&(r=r*e%n),t=t>>1n,e=e*e%n;return r}function Yo(e,t=0){let n=e.toString(16);t===0&&(t=Math.ceil(n.length/2)),n=n.padStart(t*2,"0");let r=n.length/2,o=new Uint8Array(r);for(let s=0;s<r;s++)o[s]=parseInt(n.slice(s*2,s*2+2),16);return o}function Mt(e){let t="0x";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return BigInt(t)}var Cc=class e{constructor(){this._keyLength=0,this._keyBytes=0,this._n=null,this._e=null,this._d=null,this._nBigInt=null,this._eBigInt=null,this._dBigInt=null,this._extractable=!1}get algorithm(){return{name:"RSA-PKCS1-v1_5"}}_base64urlDecode(t){return t=t.replace(/-/g,"+").replace(/_/g,"/"),t=t.padEnd(Math.ceil(t.length/4)*4,"="),Lo.decode(t)}_padArray(t,n){let r=new Uint8Array(n);return r.set(t,n-t.length),r}static async generateKey(t,n,r){let o=new e;return await o._generateKey(t,n),{privateKey:o}}async _generateKey(t,n){this._keyLength=t.modulusLength,this._keyBytes=Math.ceil(this._keyLength/8);let r=await window.crypto.subtle.generateKey({name:"RSA-OAEP",modulusLength:t.modulusLength,publicExponent:t.publicExponent,hash:{name:"SHA-256"}},!0,["encrypt","decrypt"]),o=await window.crypto.subtle.exportKey("jwk",r.privateKey);this._n=this._padArray(this._base64urlDecode(o.n),this._keyBytes),this._nBigInt=Mt(this._n),this._e=this._padArray(this._base64urlDecode(o.e),this._keyBytes),this._eBigInt=Mt(this._e),this._d=this._padArray(this._base64urlDecode(o.d),this._keyBytes),this._dBigInt=Mt(this._d),this._extractable=n}static async importKey(t,n,r,o){if(o.length!==1||o[0]!=="encrypt")throw new Error("only support importing RSA public key");let s=new e;return await s._importKey(t,r),s}async _importKey(t,n){let r=t.n,o=t.e;if(r.length!==o.length)throw new Error("the sizes of modulus and public exponent do not match");this._keyBytes=r.length,this._keyLength=this._keyBytes*8,this._n=new Uint8Array(this._keyBytes),this._e=new Uint8Array(this._keyBytes),this._n.set(r),this._e.set(o),this._nBigInt=Mt(this._n),this._eBigInt=Mt(this._e),this._extractable=n}async encrypt(t,n){if(n.length>this._keyBytes-11)return null;let r=new Uint8Array(this._keyBytes-n.length-3);window.crypto.getRandomValues(r);for(let a=0;a<r.length;a++)r[a]=Math.floor(r[a]*254/255+1);let o=new Uint8Array(this._keyBytes);o[1]=2,o.set(r,2),o.set(n,r.length+3);let s=Mt(o),i=Go(s,this._eBigInt,this._nBigInt);return Yo(i,this._keyBytes)}async decrypt(t,n){if(n.length!==this._keyBytes)return null;let r=Mt(n),o=Go(r,this._dBigInt,this._nBigInt),s=Yo(o,this._keyBytes);if(s[0]!==0||s[1]!==2)return null;let i=2;for(;i<s.length&&s[i]!==0;i++);return i===s.length?null:s.slice(i+1,s.length)}async exportKey(){if(!this._extractable)throw new Error("key is not extractable");return{n:this._n,e:this._e,d:this._d}}};var xh=class{constructor(t){this._key=t}get algorithm(){return{name:"DH"}}exportKey(){return this._key}},Tc=class e{constructor(){this._g=null,this._p=null,this._gBigInt=null,this._pBigInt=null,this._privateKey=null}get algorithm(){return{name:"DH"}}static generateKey(t,n){let r=new e;return r._generateKey(t),{privateKey:r,publicKey:new xh(r._publicKey)}}_generateKey(t){let n=t.g,r=t.p;this._keyBytes=r.length,this._gBigInt=Mt(n),this._pBigInt=Mt(r),this._privateKey=window.crypto.getRandomValues(new Uint8Array(this._keyBytes)),this._privateKeyBigInt=Mt(this._privateKey),this._publicKey=Yo(Go(this._gBigInt,this._privateKeyBigInt,this._pBigInt),this._keyBytes)}deriveBits(t,n){let r=Math.ceil(n/8),o=new Uint8Array(t.public),s=r>this._keyBytes?r:this._keyBytes,i=Go(Mt(o),this._privateKeyBigInt,this._pBigInt);return Yo(i,s).slice(0,s)}};async function Ww(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return c$(d$(p$(u$(t),8*t.length)))}function c$(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function u$(e){let t=Array(e.length>>2);for(let n=0;n<t.length;n++)t[n]=0;for(let n=0;n<8*e.length;n+=8)t[n>>5]|=(255&e.charCodeAt(n/8))<<n%32;return t}function d$(e){let t="";for(let n=0;n<32*e.length;n+=8)t+=String.fromCharCode(e[n>>5]>>>n%32&255);return t}function p$(e,t){e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;let n=1732584193,r=-271733879,o=-1732584194,s=271733878;for(let i=0;i<e.length;i+=16){let a=n,u=r,c=o,d=s;r=ft(r=ft(r=ft(r=ft(r=pt(r=pt(r=pt(r=pt(r=dt(r=dt(r=dt(r=dt(r=ut(r=ut(r=ut(r=ut(r,o=ut(o,s=ut(s,n=ut(n,r,o,s,e[i+0],7,-680876936),r,o,e[i+1],12,-389564586),n,r,e[i+2],17,606105819),s,n,e[i+3],22,-1044525330),o=ut(o,s=ut(s,n=ut(n,r,o,s,e[i+4],7,-176418897),r,o,e[i+5],12,1200080426),n,r,e[i+6],17,-1473231341),s,n,e[i+7],22,-45705983),o=ut(o,s=ut(s,n=ut(n,r,o,s,e[i+8],7,1770035416),r,o,e[i+9],12,-1958414417),n,r,e[i+10],17,-42063),s,n,e[i+11],22,-1990404162),o=ut(o,s=ut(s,n=ut(n,r,o,s,e[i+12],7,1804603682),r,o,e[i+13],12,-40341101),n,r,e[i+14],17,-1502002290),s,n,e[i+15],22,1236535329),o=dt(o,s=dt(s,n=dt(n,r,o,s,e[i+1],5,-165796510),r,o,e[i+6],9,-1069501632),n,r,e[i+11],14,643717713),s,n,e[i+0],20,-373897302),o=dt(o,s=dt(s,n=dt(n,r,o,s,e[i+5],5,-701558691),r,o,e[i+10],9,38016083),n,r,e[i+15],14,-660478335),s,n,e[i+4],20,-405537848),o=dt(o,s=dt(s,n=dt(n,r,o,s,e[i+9],5,568446438),r,o,e[i+14],9,-1019803690),n,r,e[i+3],14,-187363961),s,n,e[i+8],20,1163531501),o=dt(o,s=dt(s,n=dt(n,r,o,s,e[i+13],5,-1444681467),r,o,e[i+2],9,-51403784),n,r,e[i+7],14,1735328473),s,n,e[i+12],20,-1926607734),o=pt(o,s=pt(s,n=pt(n,r,o,s,e[i+5],4,-378558),r,o,e[i+8],11,-2022574463),n,r,e[i+11],16,1839030562),s,n,e[i+14],23,-35309556),o=pt(o,s=pt(s,n=pt(n,r,o,s,e[i+1],4,-1530992060),r,o,e[i+4],11,1272893353),n,r,e[i+7],16,-155497632),s,n,e[i+10],23,-1094730640),o=pt(o,s=pt(s,n=pt(n,r,o,s,e[i+13],4,681279174),r,o,e[i+0],11,-358537222),n,r,e[i+3],16,-722521979),s,n,e[i+6],23,76029189),o=pt(o,s=pt(s,n=pt(n,r,o,s,e[i+9],4,-640364487),r,o,e[i+12],11,-421815835),n,r,e[i+15],16,530742520),s,n,e[i+2],23,-995338651),o=ft(o,s=ft(s,n=ft(n,r,o,s,e[i+0],6,-198630844),r,o,e[i+7],10,1126891415),n,r,e[i+14],15,-1416354905),s,n,e[i+5],21,-57434055),o=ft(o,s=ft(s,n=ft(n,r,o,s,e[i+12],6,1700485571),r,o,e[i+3],10,-1894986606),n,r,e[i+10],15,-1051523),s,n,e[i+1],21,-2054922799),o=ft(o,s=ft(s,n=ft(n,r,o,s,e[i+8],6,1873313359),r,o,e[i+15],10,-30611744),n,r,e[i+6],15,-1560198380),s,n,e[i+13],21,1309151649),o=ft(o,s=ft(s,n=ft(n,r,o,s,e[i+4],6,-145523070),r,o,e[i+11],10,-1120210379),n,r,e[i+2],15,718787259),s,n,e[i+9],21,-343485551),n=or(n,a),r=or(r,u),o=or(o,c),s=or(s,d)}return Array(n,r,o,s)}function Rc(e,t,n,r,o,s){return or(f$(or(or(t,e),or(r,s)),o),n)}function ut(e,t,n,r,o,s,i){return Rc(t&n|~t&r,e,t,o,s,i)}function dt(e,t,n,r,o,s,i){return Rc(t&r|n&~r,e,t,o,s,i)}function pt(e,t,n,r,o,s,i){return Rc(t^n^r,e,t,o,s,i)}function ft(e,t,n,r,o,s,i){return Rc(n^(t|~r),e,t,o,s,i)}function or(e,t){let n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function f$(e,t){return e<<t|e>>>32-t}var bh=class{constructor(){this._algorithms={"AES-ECB":kc,"AES-EAX":Sc,"DES-ECB":Nc,"DES-CBC":Ac,"RSA-PKCS1-v1_5":Cc,DH:Tc,MD5:Ww}}encrypt(t,n,r){if(n.algorithm.name!==t.name)throw new Error("algorithm does not match");if(typeof n.encrypt!="function")throw new Error("key does not support encryption");return n.encrypt(t,r)}decrypt(t,n,r){if(n.algorithm.name!==t.name)throw new Error("algorithm does not match");if(typeof n.decrypt!="function")throw new Error("key does not support encryption");return n.decrypt(t,r)}importKey(t,n,r,o,s){if(t!=="raw")throw new Error("key format is not supported");let i=this._algorithms[r.name];if(typeof i>"u"||typeof i.importKey!="function")throw new Error("algorithm is not supported");return i.importKey(n,r,o,s)}generateKey(t,n,r){let o=this._algorithms[t.name];if(typeof o>"u"||typeof o.generateKey!="function")throw new Error("algorithm is not supported");return o.generateKey(t,n,r)}exportKey(t,n){if(t!=="raw")throw new Error("key format is not supported");if(typeof n.exportKey!="function")throw new Error("key does not support exportKey");return n.exportKey()}digest(t,n){let r=this._algorithms[t];if(typeof r!="function")throw new Error("algorithm is not supported");return r(n)}deriveBits(t,n,r){if(n.algorithm.name!==t.name)throw new Error("algorithm does not match");if(typeof n.deriveBits!="function")throw new Error("key does not support deriveBits");return n.deriveBits(t,r)}},Xe=new bh;var $c=class{constructor(){this._cipher=null,this._counter=new Uint8Array(16)}async setKey(t){this._cipher=await Xe.importKey("raw",t,{name:"AES-EAX"},!1,["encrypt, decrypt"])}async makeMessage(t){let n=new Uint8Array([(t.length&65280)>>>8,t.length&255]),r=await Xe.encrypt({name:"AES-EAX",iv:this._counter,additionalData:n},this._cipher,t);for(let s=0;s<16&&this._counter[s]++===255;s++);let o=new Uint8Array(t.length+2+16);return o.set(n),o.set(r,2),o}async receiveMessage(t,n){let r=new Uint8Array([(t&65280)>>>8,t&255]),o=await Xe.decrypt({name:"AES-EAX",iv:this._counter,additionalData:r},this._cipher,n);for(let s=0;s<16&&this._counter[s]++===255;s++);return o}},Yi=class extends Lr{constructor(t,n){super(),this._hasStarted=!1,this._checkSock=null,this._checkCredentials=null,this._approveServerResolve=null,this._sockReject=null,this._credentialsReject=null,this._approveServerReject=null,this._sock=t,this._getCredentials=n}_waitSockAsync(t){return new Promise((n,r)=>{let o=()=>!this._sock.rQwait("RA2",t);o()?n():(this._checkSock=()=>{o()&&(n(),this._checkSock=null,this._sockReject=null)},this._sockReject=r)})}_waitApproveKeyAsync(){return new Promise((t,n)=>{this._approveServerResolve=t,this._approveServerReject=n})}_waitCredentialsAsync(t){let n=()=>t===1&&this._getCredentials().username!==void 0&&this._getCredentials().password!==void 0?!0:t===2&&this._getCredentials().password!==void 0;return new Promise((r,o)=>{n()?r():(this._checkCredentials=()=>{n()&&(r(),this._checkCredentials=null,this._credentialsReject=null)},this._credentialsReject=o)})}checkInternalEvents(){this._checkSock!==null&&this._checkSock(),this._checkCredentials!==null&&this._checkCredentials()}approveServer(){this._approveServerResolve!==null&&(this._approveServerResolve(),this._approveServerResolve=null)}disconnect(){this._sockReject!==null&&(this._sockReject(new Error("disconnect normally")),this._sockReject=null),this._credentialsReject!==null&&(this._credentialsReject(new Error("disconnect normally")),this._credentialsReject=null),this._approveServerReject!==null&&(this._approveServerReject(new Error("disconnect normally")),this._approveServerReject=null)}async negotiateRA2neAuthAsync(){this._hasStarted=!0,await this._waitSockAsync(4);let t=this._sock.rQpeekBytes(4),n=this._sock.rQshift32();if(n<1024)throw new Error("RA2: server public key is too short: "+n);if(n>8192)throw new Error("RA2: server public key is too long: "+n);let r=Math.ceil(n/8);await this._waitSockAsync(r*2);let o=this._sock.rQshiftBytes(r),s=this._sock.rQshiftBytes(r),i=await Xe.importKey("raw",{n:o,e:s},{name:"RSA-PKCS1-v1_5"},!1,["encrypt"]),a=new Uint8Array(4+r*2);a.set(t),a.set(o,4),a.set(s,4+r);let u=this._waitApproveKeyAsync();this.dispatchEvent(new CustomEvent("serververification",{detail:{type:"RSA",publickey:a}})),await u;let c=2048,d=Math.ceil(c/8),p=(await Xe.generateKey({name:"RSA-PKCS1-v1_5",modulusLength:c,publicExponent:new Uint8Array([1,0,1])},!0,["encrypt"])).privateKey,f=await Xe.exportKey("raw",p),h=f.n,g=f.e,x=new Uint8Array(4+d*2);x[0]=(c&4278190080)>>>24,x[1]=(c&16711680)>>>16,x[2]=(c&65280)>>>8,x[3]=c&255,x.set(h,4),x.set(g,4+d),this._sock.sQpushBytes(x),this._sock.flush();let b=new Uint8Array(16);window.crypto.getRandomValues(b);let _=await Xe.encrypt({name:"RSA-PKCS1-v1_5"},i,b),w=new Uint8Array(2+r);if(w[0]=(r&65280)>>>8,w[1]=r&255,w.set(_,2),this._sock.sQpushBytes(w),this._sock.flush(),await this._waitSockAsync(2),this._sock.rQshift16()!==d)throw new Error("RA2: wrong encrypted message length");let T=this._sock.rQshiftBytes(d),y=await Xe.decrypt({name:"RSA-PKCS1-v1_5"},p,T);if(y===null||y.length!==16)throw new Error("RA2: corrupted server encrypted random");let E=new Uint8Array(32),k=new Uint8Array(32);E.set(y),E.set(b,16),k.set(b),k.set(y,16),E=await window.crypto.subtle.digest("SHA-1",E),E=new Uint8Array(E).slice(0,16),k=await window.crypto.subtle.digest("SHA-1",k),k=new Uint8Array(k).slice(0,16);let N=new $c;await N.setKey(E);let $=new $c;await $.setKey(k);let P=new Uint8Array(8+r*2+d*2),L=new Uint8Array(8+r*2+d*2);if(P.set(a),P.set(x,4+r*2),L.set(x),L.set(a,4+d*2),P=await window.crypto.subtle.digest("SHA-1",P),L=await window.crypto.subtle.digest("SHA-1",L),P=new Uint8Array(P),L=new Uint8Array(L),this._sock.sQpushBytes(await N.makeMessage(L)),this._sock.flush(),await this._waitSockAsync(38),this._sock.rQshift16()!==20)throw new Error("RA2: wrong server hash");let ne=await $.receiveMessage(20,this._sock.rQshiftBytes(36));if(ne===null)throw new Error("RA2: failed to authenticate the message");for(let Y=0;Y<20;Y++)if(ne[Y]!==P[Y])throw new Error("RA2: wrong server hash");if(await this._waitSockAsync(19),this._sock.rQshift16()!==1)throw new Error("RA2: wrong subtype");let se=await $.receiveMessage(1,this._sock.rQshiftBytes(17));if(se===null)throw new Error("RA2: failed to authenticate the message");se=se[0];let _e=this._waitCredentialsAsync(se);if(se===1)(this._getCredentials().username===void 0||this._getCredentials().password===void 0)&&this.dispatchEvent(new CustomEvent("credentialsrequired",{detail:{types:["username","password"]}}));else if(se===2)this._getCredentials().password===void 0&&this.dispatchEvent(new CustomEvent("credentialsrequired",{detail:{types:["password"]}}));else throw new Error("RA2: wrong subtype");await _e;let ie;se===1?ie=Gt(this._getCredentials().username).slice(0,255):ie="";let Q=Gt(this._getCredentials().password).slice(0,255),j=new Uint8Array(ie.length+Q.length+2);j[0]=ie.length,j[ie.length+1]=Q.length;for(let Y=0;Y<ie.length;Y++)j[Y+1]=ie.charCodeAt(Y);for(let Y=0;Y<Q.length;Y++)j[ie.length+2+Y]=Q.charCodeAt(Y);this._sock.sQpushBytes(await N.makeMessage(j)),this._sock.flush()}get hasStarted(){return this._hasStarted}set hasStarted(t){this._hasStarted=t}};var qi=class{constructor(){this._lines=0}decodeRect(t,n,r,o,s,i,a){if(r===0||o===0)return!0;this._lines===0&&(this._lines=o);let u=a==8?1:4,c=r*u;for(;this._lines>0;){if(s.rQwait("RAW",c))return!1;let d=n+(o-this._lines),p=s.rQshiftBytes(c,!1);if(a==8){let f=new Uint8Array(r*4);for(let h=0;h<r;h++)f[h*4+0]=(p[h]>>0&3)*255/3,f[h*4+1]=(p[h]>>2&3)*255/3,f[h*4+2]=(p[h]>>4&3)*255/3,f[h*4+3]=255;p=f}for(let f=0;f<r;f++)p[f*4+3]=255;i.blitImage(t,d,r,1,p,0),this._lines--}return!0}};var Ji=class{decodeRect(t,n,r,o,s,i,a){if(s.rQwait("COPYRECT",4))return!1;let u=s.rQshift16(),c=s.rQshift16();return r===0||o===0||i.copyImage(u,c,t,n,r,o),!0}};var ea=class{constructor(){this._subrects=0}decodeRect(t,n,r,o,s,i,a){if(this._subrects===0){if(s.rQwait("RRE",8))return!1;this._subrects=s.rQshift32();let u=s.rQshiftBytes(4);i.fillRect(t,n,r,o,u)}for(;this._subrects>0;){if(s.rQwait("RRE",12))return!1;let u=s.rQshiftBytes(4),c=s.rQshift16(),d=s.rQshift16(),p=s.rQshift16(),f=s.rQshift16();i.fillRect(t+c,n+d,p,f,u),this._subrects--}return!0}};var ta=class{constructor(){this._tiles=0,this._lastsubencoding=0,this._tileBuffer=new Uint8Array(256*4)}decodeRect(t,n,r,o,s,i,a){for(this._tiles===0&&(this._tilesX=Math.ceil(r/16),this._tilesY=Math.ceil(o/16),this._totalTiles=this._tilesX*this._tilesY,this._tiles=this._totalTiles);this._tiles>0;){let u=1;if(s.rQwait("HEXTILE",u))return!1;let c=s.rQpeek8();if(c>30)throw new Error("Illegal hextile subencoding (subencoding: "+c+")");let d=this._totalTiles-this._tiles,p=d%this._tilesX,f=Math.floor(d/this._tilesX),h=t+p*16,g=n+f*16,x=Math.min(16,t+r-h),b=Math.min(16,n+o-g);if(c&1)u+=x*b*4;else if(c&2&&(u+=4),c&4&&(u+=4),c&8){if(u++,s.rQwait("HEXTILE",u))return!1;let _=s.rQpeekBytes(u).at(-1);c&16?u+=_*6:u+=_*2}if(s.rQwait("HEXTILE",u))return!1;if(s.rQshift8(),c===0)this._lastsubencoding&1?de(" Ignoring blank after RAW"):i.fillRect(h,g,x,b,this._background);else if(c&1){let _=x*b,w=s.rQshiftBytes(_*4,!1);for(let T=0;T<_;T++)w[T*4+3]=255;i.blitImage(h,g,x,b,w,0)}else{if(c&2&&(this._background=new Uint8Array(s.rQshiftBytes(4))),c&4&&(this._foreground=new Uint8Array(s.rQshiftBytes(4))),this._startTile(h,g,x,b,this._background),c&8){let _=s.rQshift8();for(let w=0;w<_;w++){let T;c&16?T=s.rQshiftBytes(4):T=this._foreground;let y=s.rQshift8(),E=y>>4,k=y&15,N=s.rQshift8(),$=(N>>4)+1,P=(N&15)+1;this._subTile(E,k,$,P,T)}}this._finishTile(i)}this._lastsubencoding=c,this._tiles--}return!0}_startTile(t,n,r,o,s){this._tileX=t,this._tileY=n,this._tileW=r,this._tileH=o;let i=s[0],a=s[1],u=s[2],c=this._tileBuffer;for(let d=0;d<r*o*4;d+=4)c[d]=i,c[d+1]=a,c[d+2]=u,c[d+3]=255}_subTile(t,n,r,o,s){let i=s[0],a=s[1],u=s[2],c=t+r,d=n+o,p=this._tileBuffer,f=this._tileW;for(let h=n;h<d;h++)for(let g=t;g<c;g++){let x=(g+h*f)*4;p[x]=i,p[x+1]=a,p[x+2]=u,p[x+3]=255}}_finishTile(t){t.blitImage(this._tileX,this._tileY,this._tileW,this._tileH,this._tileBuffer,0)}};var na=class{constructor(){this._zlib=new Yt,this._length=0}decodeRect(t,n,r,o,s,i,a){if(r===0||o===0)return!0;if(this._length===0){if(s.rQwait("ZLIB",4))return!1;this._length=s.rQshift32()}if(s.rQwait("ZLIB",this._length))return!1;let u=new Uint8Array(s.rQshiftBytes(this._length,!1));this._length=0,this._zlib.setInput(u),u=this._zlib.inflate(r*o*4),this._zlib.setInput(null);for(let c=0;c<r*o;c++)u[c*4+3]=255;return i.blitImage(t,n,r,o,u,0),!0}};var Hr=class{constructor(){this._ctl=null,this._filter=null,this._numColors=0,this._palette=new Uint8Array(1024),this._len=0,this._zlibs=[];for(let t=0;t<4;t++)this._zlibs[t]=new Yt}decodeRect(t,n,r,o,s,i,a){if(this._ctl===null){if(s.rQwait("TIGHT compression-control",1))return!1;this._ctl=s.rQshift8();for(let c=0;c<4;c++)this._ctl>>c&1&&(this._zlibs[c].reset(),Qe("Reset zlib stream "+c));this._ctl=this._ctl>>4}let u;if(this._ctl===8)u=this._fillRect(t,n,r,o,s,i,a);else if(this._ctl===9)u=this._jpegRect(t,n,r,o,s,i,a);else if(this._ctl===10)u=this._pngRect(t,n,r,o,s,i,a);else if((this._ctl&8)==0)u=this._basicRect(this._ctl,t,n,r,o,s,i,a);else throw new Error("Illegal tight compression received (ctl: "+this._ctl+")");return u&&(this._ctl=null),u}_fillRect(t,n,r,o,s,i,a){if(s.rQwait("TIGHT",3))return!1;let u=s.rQshiftBytes(3);return i.fillRect(t,n,r,o,u,!1),!0}_jpegRect(t,n,r,o,s,i,a){let u=this._readData(s);return u===null?!1:(i.imageRect(t,n,r,o,"image/jpeg",u),!0)}_pngRect(t,n,r,o,s,i,a){throw new Error("PNG received in standard Tight rect")}_basicRect(t,n,r,o,s,i,a,u){if(this._filter===null)if(t&4){if(i.rQwait("TIGHT",1))return!1;this._filter=i.rQshift8()}else this._filter=0;let c=t&3,d;switch(this._filter){case 0:d=this._copyFilter(c,n,r,o,s,i,a,u);break;case 1:d=this._paletteFilter(c,n,r,o,s,i,a,u);break;case 2:d=this._gradientFilter(c,n,r,o,s,i,a,u);break;default:throw new Error("Illegal tight filter received (ctl: "+this._filter+")")}return d&&(this._filter=null),d}_copyFilter(t,n,r,o,s,i,a,u){let c=o*s*3,d;if(c===0)return!0;if(c<12){if(i.rQwait("TIGHT",c))return!1;d=i.rQshiftBytes(c)}else{if(d=this._readData(i),d===null)return!1;this._zlibs[t].setInput(d),d=this._zlibs[t].inflate(c),this._zlibs[t].setInput(null)}let p=new Uint8Array(o*s*4);for(let f=0,h=0;f<o*s*4;f+=4,h+=3)p[f]=d[h],p[f+1]=d[h+1],p[f+2]=d[h+2],p[f+3]=255;return a.blitImage(n,r,o,s,p,0,!1),!0}_paletteFilter(t,n,r,o,s,i,a,u){if(this._numColors===0){if(i.rQwait("TIGHT palette",1))return!1;let h=i.rQpeek8()+1,g=h*3;if(i.rQwait("TIGHT palette",1+g))return!1;this._numColors=h,i.rQskipBytes(1),i.rQshiftTo(this._palette,g)}let c=this._numColors<=2?1:8,p=Math.floor((o*c+7)/8)*s,f;if(p===0)return!0;if(p<12){if(i.rQwait("TIGHT",p))return!1;f=i.rQshiftBytes(p)}else{if(f=this._readData(i),f===null)return!1;this._zlibs[t].setInput(f),f=this._zlibs[t].inflate(p),this._zlibs[t].setInput(null)}return this._numColors==2?this._monoRect(n,r,o,s,f,this._palette,a):this._paletteRect(n,r,o,s,f,this._palette,a),this._numColors=0,!0}_monoRect(t,n,r,o,s,i,a){let u=this._getScratchBuffer(r*o*4),c=Math.floor((r+7)/8),d=Math.floor(r/8);for(let p=0;p<o;p++){let f,h,g;for(g=0;g<d;g++)for(let x=7;x>=0;x--)f=(p*r+g*8+7-x)*4,h=(s[p*c+g]>>x&1)*3,u[f]=i[h],u[f+1]=i[h+1],u[f+2]=i[h+2],u[f+3]=255;for(let x=7;x>=8-r%8;x--)f=(p*r+g*8+7-x)*4,h=(s[p*c+g]>>x&1)*3,u[f]=i[h],u[f+1]=i[h+1],u[f+2]=i[h+2],u[f+3]=255}a.blitImage(t,n,r,o,u,0,!1)}_paletteRect(t,n,r,o,s,i,a){let u=this._getScratchBuffer(r*o*4),c=r*o*4;for(let d=0,p=0;d<c;d+=4,p++){let f=s[p]*3;u[d]=i[f],u[d+1]=i[f+1],u[d+2]=i[f+2],u[d+3]=255}a.blitImage(t,n,r,o,u,0,!1)}_gradientFilter(t,n,r,o,s,i,a,u){let c=o*s*3,d;if(c===0)return!0;if(c<12){if(i.rQwait("TIGHT",c))return!1;d=i.rQshiftBytes(c)}else{if(d=this._readData(i),d===null)return!1;this._zlibs[t].setInput(d),d=this._zlibs[t].inflate(c),this._zlibs[t].setInput(null)}let p=new Uint8Array(4*o*s),f=0,h=0,g=new Uint8Array(3);for(let w=0;w<o;w++){for(let T=0;T<3;T++){let y=g[T],E=d[h++]+y;p[f++]=E,g[T]=E}p[f++]=255}let x=0,b=new Uint8Array(3),_=new Uint8Array(3);for(let w=1;w<s;w++){g.fill(0),_.fill(0);for(let T=0;T<o;T++){for(let y=0;y<3;y++){b[y]=p[x++];let E=g[y]+b[y]-_[y];E<0?E=0:E>255&&(E=255);let k=d[h++]+E;p[f++]=k,_[y]=b[y],g[y]=k}p[f++]=255,x++}}return a.blitImage(n,r,o,s,p,0,!1),!0}_readData(t){if(this._len===0){if(t.rQwait("TIGHT",3))return null;let r;r=t.rQshift8(),this._len=r&127,r&128&&(r=t.rQshift8(),this._len|=(r&127)<<7,r&128&&(r=t.rQshift8(),this._len|=r<<14))}if(t.rQwait("TIGHT",this._len))return null;let n=t.rQshiftBytes(this._len,!1);return this._len=0,n}_getScratchBuffer(t){return(!this._scratchBuffer||this._scratchBuffer.length<t)&&(this._scratchBuffer=new Uint8Array(t)),this._scratchBuffer}};var ra=class extends Hr{_pngRect(t,n,r,o,s,i,a){let u=this._readData(s);return u===null?!1:(i.imageRect(t,n,r,o,"image/png",u),!0)}_basicRect(t,n,r,o,s,i,a,u){throw new Error("BasicCompression received in TightPNG rect")}};var Ic=64,Pc=64,oa=class{constructor(){this._length=0,this._inflator=new Yt,this._pixelBuffer=new Uint8Array(Ic*Pc*4),this._tileBuffer=new Uint8Array(Ic*Pc*4)}decodeRect(t,n,r,o,s,i,a){if(this._length===0){if(s.rQwait("ZLib data length",4))return!1;this._length=s.rQshift32()}if(s.rQwait("Zlib data",this._length))return!1;let u=s.rQshiftBytes(this._length,!1);this._inflator.setInput(u);for(let c=n;c<n+o;c+=Pc){let d=Math.min(Pc,n+o-c);for(let p=t;p<t+r;p+=Ic){let f=Math.min(Ic,t+r-p),h=f*d,g=this._inflator.inflate(1)[0];if(g===0){let x=this._readPixels(h);i.blitImage(p,c,f,d,x,0,!1)}else if(g===1){let x=this._readPixels(1);i.fillRect(p,c,f,d,[x[0],x[1],x[2]])}else if(g>=2&&g<=16){let x=this._decodePaletteTile(g,h,f,d);i.blitImage(p,c,f,d,x,0,!1)}else if(g===128){let x=this._decodeRLETile(h);i.blitImage(p,c,f,d,x,0,!1)}else if(g>=130&&g<=255){let x=this._decodeRLEPaletteTile(g-128,h);i.blitImage(p,c,f,d,x,0,!1)}else throw new Error("Unknown subencoding: "+g)}}return this._length=0,!0}_getBitsPerPixelInPalette(t){if(t<=2)return 1;if(t<=4)return 2;if(t<=16)return 4}_readPixels(t){let n=this._pixelBuffer,r=this._inflator.inflate(3*t);for(let o=0,s=0;o<t*4;o+=4,s+=3)n[o]=r[s],n[o+1]=r[s+1],n[o+2]=r[s+2],n[o+3]=255;return n}_decodePaletteTile(t,n,r,o){let s=this._tileBuffer,i=this._readPixels(t),a=this._getBitsPerPixelInPalette(t),u=(1<<a)-1,c=0,d=this._inflator.inflate(1)[0];for(let p=0;p<o;p++){let f=8-a;for(let h=0;h<r;h++){f<0&&(f=8-a,d=this._inflator.inflate(1)[0]);let g=d>>f&u;s[c]=i[g*4],s[c+1]=i[g*4+1],s[c+2]=i[g*4+2],s[c+3]=i[g*4+3],c+=4,f-=a}f<8-a&&p<o-1&&(d=this._inflator.inflate(1)[0])}return s}_decodeRLETile(t){let n=this._tileBuffer,r=0;for(;r<t;){let o=this._readPixels(1),s=this._readRLELength();for(let i=0;i<s;i++)n[r*4]=o[0],n[r*4+1]=o[1],n[r*4+2]=o[2],n[r*4+3]=o[3],r++}return n}_decodeRLEPaletteTile(t,n){let r=this._tileBuffer,o=this._readPixels(t),s=0;for(;s<n;){let i=this._inflator.inflate(1)[0],a=1;if(i>=128&&(i-=128,a=this._readRLELength()),i>t)throw new Error("Too big index in palette: "+i+", palette size: "+t);if(s+a>n)throw new Error("Too big rle length in palette mode: "+a+", allowed length is: "+(n-s));for(let u=0;u<a;u++)r[s*4]=o[i*4],r[s*4+1]=o[i*4+1],r[s*4+2]=o[i*4+2],r[s*4+3]=o[i*4+3],s++}return r}_readRLELength(){let t=0,n=0;do n=this._inflator.inflate(1)[0],t+=n;while(n===255);return t+1}};var sa=class{constructor(){this._cachedQuantTables=[],this._cachedHuffmanTables=[],this._segments=[]}decodeRect(t,n,r,o,s,i,a){for(;;){let h=this._readSegment(s);if(h===null)return!1;if(this._segments.push(h),h[1]===217)break}let u=[],c=[];for(let h of this._segments){let g=h[1];g===196?u.push(h):g===219&&c.push(h)}let d=this._segments.findIndex(h=>h[1]==192||h[1]==194);if(d==-1)throw new Error("Illegal JPEG image without SOF");c.length===0&&this._segments.splice(d+1,0,...this._cachedQuantTables),u.length===0&&this._segments.splice(d+1,0,...this._cachedHuffmanTables);let p=0;for(let h of this._segments)p+=h.length;let f=new Uint8Array(p);p=0;for(let h of this._segments)f.set(h,p),p+=h.length;return i.imageRect(t,n,r,o,"image/jpeg",f),u.length!==0&&(this._cachedHuffmanTables=u),c.length!==0&&(this._cachedQuantTables=c),this._segments=[],!0}_readSegment(t){if(t.rQwait("JPEG",2))return null;let n=t.rQshift8();if(n!=255)throw new Error("Illegal JPEG marker received (byte: "+n+")");let r=t.rQshift8();if(r>=208&&r<=217||r==1)return new Uint8Array([n,r]);if(t.rQwait("JPEG",2,2))return null;let o=t.rQshift16();if(o<2)throw new Error("Illegal JPEG length received (length: "+o+")");if(t.rQwait("JPEG",o-2,4))return null;let s=0;if(r===218){if(t.rQwait("JPEG",o-2+2,4))return null;let a=t.rQlen(),u=t.rQpeekBytes(a,!1);for(;;){let c=u.indexOf(255,o-2+s);if(c===-1||c===a-1)return t.rQwait("JPEG",1/0,4),null;if(u.at(c+1)===0||u.at(c+1)>=208&&u.at(c+1)<=215){s=c+2-(o-2);continue}s=c-(o-2);break}}let i=new Uint8Array(2+o+s);return i[0]=n,i[1]=r,i[2]=o>>8,i[3]=o,i.set(t.rQshiftBytes(o-2+s,!1),4),i}};var yh=class{constructor(t){this._data=t,this._index=0,this.profileIdc=null,this.constraintSet=null,this.levelIdc=null}_getStartSequenceLen(t){let n=this._data;return n[t+0]==0&&n[t+1]==0&&n[t+2]==0&&n[t+3]==1?4:n[t+0]==0&&n[t+1]==0&&n[t+2]==1?3:0}_indexOfNextNalUnit(t){let n=this._data;for(let r=t;r<n.length;++r)if(this._getStartSequenceLen(r)!=0)return r;return-1}_parseSps(t){this.profileIdc=this._data[t],this.constraintSet=this._data[t+1],this.levelIdc=this._data[t+2]}_parseNalUnit(t){let n=this._data[t];if(n&128)throw new Error("H264 parsing sanity check failed, forbidden zero bit is set");let r=n&31;switch(r){case 1:return{slice:!0};case 5:return{slice:!0,key:!0};case 6:return{};case 7:return this._parseSps(t+1),{};case 8:return{};default:qe("Unhandled unit type: ",r);break}return{}}parse(){let t=this._index,n=!1;for(;this._index<this._data.length;){let r=this._getStartSequenceLen(this._index);if(r==0)throw new Error("Invalid start sequence in bit stream");let{slice:o,key:s}=this._parseNalUnit(this._index+r),i=this._indexOfNextNalUnit(this._index+r);if(i==-1?this._index=this._data.length:this._index=i,s&&(n=!0),o)break}return t===this._index?null:{frame:this._data.subarray(t,this._index),key:n}}},_h=class{constructor(t,n){this.lastUsed=0,this._width=t,this._height=n,this._profileIdc=null,this._constraintSet=null,this._levelIdc=null,this._decoder=null,this._pendingFrames=[]}_handleFrame(t){let n=this._pendingFrames.shift();if(n===void 0)throw new Error("Pending frame queue empty when receiving frame from decoder");if(n.timestamp!=t.timestamp)throw new Error("Video frame timestamp mismatch. Expected "+t.timestamp+" but but got "+n.timestamp);n.frame=t,n.ready=!0,n.resolve(),n.keep||t.close()}_handleError(t){throw new Error("Failed to decode frame: "+t.message)}_configureDecoder(t,n,r){(this._decoder===null||this._decoder.state==="closed")&&(this._decoder=new VideoDecoder({output:s=>this._handleFrame(s),error:s=>this._handleError(s)}));let o="avc1."+t.toString(16).padStart(2,"0")+n.toString(16).padStart(2,"0")+r.toString(16).padStart(2,"0");this._decoder.configure({codec:o,codedWidth:this._width,codedHeight:this._height,optimizeForLatency:!0})}_preparePendingFrame(t){let n={timestamp:t,promise:null,resolve:null,frame:null,ready:!1,keep:!1};return n.promise=new Promise(r=>{n.resolve=r}),this._pendingFrames.push(n),n}decode(t){let n=new yh(t),r=null,o=Math.round(window.performance.now()*1e3);for(;;){let s=n.parse();if(s===null)break;if(n.profileIdc!==null&&(self._profileIdc=n.profileIdc,self._constraintSet=n.constraintSet,self._levelIdc=n.levelIdc),this._decoder===null||this._decoder.state!=="configured"){if(!s.key){qe("Missing key frame. Can't decode until one arrives");continue}if(self._profileIdc===null){qe("Cannot config decoder. Have not received SPS and PPS yet.");continue}this._configureDecoder(self._profileIdc,self._constraintSet,self._levelIdc)}r=this._preparePendingFrame(o);let i=new EncodedVideoChunk({timestamp:o,type:s.key?"key":"delta",data:s.frame});try{this._decoder.decode(i)}catch(a){qe("Failed to decode:",a)}}return r!==null&&(r.keep=!0),r}},ia=class{constructor(){this._tick=0,this._contexts={}}_contextId(t,n,r,o){return[t,n,r,o].join(",")}_findOldestContextId(){let t=Number.MAX_VALUE,n;for(let[r,o]of Object.entries(this._contexts))o.lastUsed<t&&(t=o.lastUsed,n=r);return n}_createContext(t,n,r,o){if(Object.keys(this._contexts).length>=64){let a=this._findOldestContextId();delete this._contexts[a]}let i=new _h(r,o);return this._contexts[this._contextId(t,n,r,o)]=i,i}_getContext(t,n,r,o){let s=this._contexts[this._contextId(t,n,r,o)];return s!==void 0?s:this._createContext(t,n,r,o)}_resetContext(t,n,r,o){delete this._contexts[this._contextId(t,n,r,o)]}_resetAllContexts(){this._contexts={}}decodeRect(t,n,r,o,s,i,a){if(s.rQwait("h264 header",8))return!1;let d=s.rQshift32(),p=s.rQshift32();if(s.rQwait("h264 payload",d,8))return!1;p&2?this._resetAllContexts():p&1&&this._resetContext(t,n,r,o);let f=this._getContext(t,n,r,o);if(f.lastUsed=this._tick++,d!==0){let h=s.rQshiftBytes(d,!1),g=f.decode(h);g!==null&&i.videoFrame(t,n,r,o,g)}return!0}};var h$=3,m$="rgb(40, 40, 40)",jw=17,Qw=50,Gw=19,aa=75,sr=50,g$=1e3,x$=50,Yw=1,Oc=2,qw=6,Jw=16,vh=19,ek=22,tk=30,nk=113,rk=129,ok=256,hn=1;var sk=1<<24,Lc=1<<25,ik=1<<26,la=1<<27,Mc=1<<28,yt=class e extends Lr{constructor(t,n,r){if(!t)throw new Error("Must specify target");if(!n)throw new Error("Must specify URL, WebSocket or RTCDataChannel");window.isSecureContext||Me("noVNC requires a secure context (TLS). Expect crashes!"),super(),this._target=t,typeof n=="string"?this._url=n:(this._url=null,this._rawChannel=n),r=r||{},this._rfbCredentials=r.credentials||{},this._shared="shared"in r?!!r.shared:!0,this._repeaterID=r.repeaterID||"",this._wsProtocols=r.wsProtocols||[],this._rfbConnectionState="",this._rfbInitState="",this._rfbAuthScheme=-1,this._rfbCleanDisconnect=!0,this._rfbRSAAESAuthenticationState=null,this._rfbVersion=0,this._rfbMaxVersion=3.8,this._rfbTightVNC=!1,this._rfbVeNCryptState=0,this._rfbXvpVer=0,this._fbWidth=0,this._fbHeight=0,this._fbName="",this._capabilities={power:!1},this._supportsFence=!1,this._supportsContinuousUpdates=!1,this._enabledContinuousUpdates=!1,this._supportsSetDesktopSize=!1,this._screenID=0,this._screenFlags=0,this._pendingRemoteResize=!1,this._lastResize=0,this._qemuExtKeyEventSupported=!1,this._extendedPointerEventSupported=!1,this._clipboardText=null,this._clipboardServerCapabilitiesActions={},this._clipboardServerCapabilitiesFormats={},this._sock=null,this._display=null,this._flushing=!1,this._keyboard=null,this._gestures=null,this._resizeObserver=null,this._disconnTimer=null,this._resizeTimeout=null,this._mouseMoveTimer=null,this._decoders={},this._FBU={rects:0,x:0,y:0,width:0,height:0,encoding:null},this._mousePos={},this._mouseButtonMask=0,this._mouseLastMoveTime=0,this._viewportDragging=!1,this._viewportDragPos={},this._viewportHasMoved=!1,this._accumulatedWheelDeltaX=0,this._accumulatedWheelDeltaY=0,this._gestureLastTapTime=null,this._gestureFirstDoubleTapEv=null,this._gestureLastMagnitudeX=0,this._gestureLastMagnitudeY=0,this._eventHandlers={focusCanvas:this._focusCanvas.bind(this),handleResize:this._handleResize.bind(this),handleMouse:this._handleMouse.bind(this),handleWheel:this._handleWheel.bind(this),handleGesture:this._handleGesture.bind(this),handleRSAAESCredentialsRequired:this._handleRSAAESCredentialsRequired.bind(this),handleRSAAESServerVerification:this._handleRSAAESServerVerification.bind(this)},de(">> RFB.constructor"),this._screen=document.createElement("div"),this._screen.style.display="flex",this._screen.style.width="100%",this._screen.style.height="100%",this._screen.style.overflow="auto",this._screen.style.background=m$,this._canvas=document.createElement("canvas"),this._canvas.style.margin="auto",this._canvas.style.outline="none",this._canvas.width=0,this._canvas.height=0,this._canvas.tabIndex=-1,this._screen.appendChild(this._canvas),this._cursor=new Qi,this._cursorImage=e.cursors.none,this._decoders[ge.encodingRaw]=new qi,this._decoders[ge.encodingCopyRect]=new Ji,this._decoders[ge.encodingRRE]=new ea,this._decoders[ge.encodingHextile]=new ta,this._decoders[ge.encodingZlib]=new na,this._decoders[ge.encodingTight]=new Hr,this._decoders[ge.encodingTightPNG]=new ra,this._decoders[ge.encodingZRLE]=new oa,this._decoders[ge.encodingJPEG]=new sa,this._decoders[ge.encodingH264]=new ia;try{this._display=new Ii(this._canvas)}catch(o){throw Me("Display exception: "+o),o}this._keyboard=new Zi(this._canvas),this._keyboard.onkeyevent=this._handleKeyEvent.bind(this),this._remoteCapsLock=null,this._remoteNumLock=null,this._gestures=new Wi,this._sock=new Gi,this._sock.on("open",this._socketOpen.bind(this)),this._sock.on("close",this._socketClose.bind(this)),this._sock.on("message",this._handleMessage.bind(this)),this._sock.on("error",this._socketError.bind(this)),this._expectedClientWidth=null,this._expectedClientHeight=null,this._resizeObserver=new ResizeObserver(this._eventHandlers.handleResize),this._updateConnectionState("connecting"),de("<< RFB.constructor"),this.dragViewport=!1,this.focusOnClick=!0,this._viewOnly=!1,this._clipViewport=!1,this._clippingViewport=!1,this._scaleViewport=!1,this._resizeSession=!1,this._showDotCursor=!1,this._qualityLevel=6,this._compressionLevel=2}get viewOnly(){return this._viewOnly}set viewOnly(t){this._viewOnly=t,(this._rfbConnectionState==="connecting"||this._rfbConnectionState==="connected")&&(t?this._keyboard.ungrab():this._keyboard.grab())}get capabilities(){return this._capabilities}get clippingViewport(){return this._clippingViewport}_setClippingViewport(t){t!==this._clippingViewport&&(this._clippingViewport=t,this.dispatchEvent(new CustomEvent("clippingviewport",{detail:this._clippingViewport})))}get touchButton(){return 0}set touchButton(t){qe("Using old API!")}get clipViewport(){return this._clipViewport}set clipViewport(t){this._clipViewport=t,this._updateClip()}get scaleViewport(){return this._scaleViewport}set scaleViewport(t){this._scaleViewport=t,t&&this._clipViewport&&this._updateClip(),this._updateScale(),!t&&this._clipViewport&&this._updateClip()}get resizeSession(){return this._resizeSession}set resizeSession(t){this._resizeSession=t,t&&this._requestRemoteResize()}get showDotCursor(){return this._showDotCursor}set showDotCursor(t){this._showDotCursor=t,this._refreshCursor()}get background(){return this._screen.style.background}set background(t){this._screen.style.background=t}get qualityLevel(){return this._qualityLevel}set qualityLevel(t){if(!Number.isInteger(t)||t<0||t>9){Me("qualityLevel must be an integer between 0 and 9");return}this._qualityLevel!==t&&(this._qualityLevel=t,this._rfbConnectionState==="connected"&&this._sendEncodings())}get compressionLevel(){return this._compressionLevel}set compressionLevel(t){if(!Number.isInteger(t)||t<0||t>9){Me("compressionLevel must be an integer between 0 and 9");return}this._compressionLevel!==t&&(this._compressionLevel=t,this._rfbConnectionState==="connected"&&this._sendEncodings())}disconnect(){this._updateConnectionState("disconnecting"),this._sock.off("error"),this._sock.off("message"),this._sock.off("open"),this._rfbRSAAESAuthenticationState!==null&&this._rfbRSAAESAuthenticationState.disconnect()}approveServer(){this._rfbRSAAESAuthenticationState!==null&&this._rfbRSAAESAuthenticationState.approveServer()}sendCredentials(t){this._rfbCredentials=t,this._resumeAuthentication()}sendCtrlAltDel(){this._rfbConnectionState!=="connected"||this._viewOnly||(Qe("Sending Ctrl-Alt-Del"),this.sendKey(C.XK_Control_L,"ControlLeft",!0),this.sendKey(C.XK_Alt_L,"AltLeft",!0),this.sendKey(C.XK_Delete,"Delete",!0),this.sendKey(C.XK_Delete,"Delete",!1),this.sendKey(C.XK_Alt_L,"AltLeft",!1),this.sendKey(C.XK_Control_L,"ControlLeft",!1))}machineShutdown(){this._xvpOp(1,2)}machineReboot(){this._xvpOp(1,3)}machineReset(){this._xvpOp(1,4)}sendKey(t,n,r){if(this._rfbConnectionState!=="connected"||this._viewOnly)return;if(r===void 0){this.sendKey(t,n,!0),this.sendKey(t,n,!1);return}let o=Dw[n];if(this._qemuExtKeyEventSupported&&o)t=t||0,Qe("Sending key ("+(r?"down":"up")+"): keysym "+t+", scancode "+o),e.messages.QEMUExtendedKeyEvent(this._sock,t,r,o);else{if(!t)return;Qe("Sending keysym ("+(r?"down":"up")+"): "+t),e.messages.keyEvent(this._sock,t,r?1:0)}}focus(t){this._canvas.focus(t)}blur(){this._canvas.blur()}clipboardPasteFrom(t){if(!(this._rfbConnectionState!=="connected"||this._viewOnly))if(this._clipboardServerCapabilitiesFormats[hn]&&this._clipboardServerCapabilitiesActions[la])this._clipboardText=t,e.messages.extendedClipboardNotify(this._sock,[hn]);else{let n,r,o;n=0;for(let s of t)n++;o=new Uint8Array(n),r=0;for(let s of t){let i=s.codePointAt(0);i>255&&(i=63),o[r++]=i}e.messages.clientCutText(this._sock,o)}}getImageData(){return this._display.getImageData()}toDataURL(t,n){return this._display.toDataURL(t,n)}toBlob(t,n,r){return this._display.toBlob(t,n,r)}_connect(){if(de(">> RFB.connect"),this._url)Qe(`connecting to ${this._url}`),this._sock.open(this._url,this._wsProtocols);else{if(Qe(`attaching ${this._rawChannel} to Websock`),this._sock.attach(this._rawChannel),this._sock.readyState==="closed")throw Error("Cannot use already closed WebSocket/RTCDataChannel");this._sock.readyState==="open"&&this._socketOpen()}this._target.appendChild(this._screen),this._gestures.attach(this._canvas),this._cursor.attach(this._canvas),this._refreshCursor(),this._resizeObserver.observe(this._screen),this._canvas.addEventListener("mousedown",this._eventHandlers.focusCanvas),this._canvas.addEventListener("touchstart",this._eventHandlers.focusCanvas),this._canvas.addEventListener("mousedown",this._eventHandlers.handleMouse),this._canvas.addEventListener("mouseup",this._eventHandlers.handleMouse),this._canvas.addEventListener("mousemove",this._eventHandlers.handleMouse),this._canvas.addEventListener("click",this._eventHandlers.handleMouse),this._canvas.addEventListener("contextmenu",this._eventHandlers.handleMouse),this._canvas.addEventListener("wheel",this._eventHandlers.handleWheel),this._canvas.addEventListener("gesturestart",this._eventHandlers.handleGesture),this._canvas.addEventListener("gesturemove",this._eventHandlers.handleGesture),this._canvas.addEventListener("gestureend",this._eventHandlers.handleGesture),de("<< RFB.connect")}_disconnect(){de(">> RFB.disconnect"),this._cursor.detach(),this._canvas.removeEventListener("gesturestart",this._eventHandlers.handleGesture),this._canvas.removeEventListener("gesturemove",this._eventHandlers.handleGesture),this._canvas.removeEventListener("gestureend",this._eventHandlers.handleGesture),this._canvas.removeEventListener("wheel",this._eventHandlers.handleWheel),this._canvas.removeEventListener("mousedown",this._eventHandlers.handleMouse),this._canvas.removeEventListener("mouseup",this._eventHandlers.handleMouse),this._canvas.removeEventListener("mousemove",this._eventHandlers.handleMouse),this._canvas.removeEventListener("click",this._eventHandlers.handleMouse),this._canvas.removeEventListener("contextmenu",this._eventHandlers.handleMouse),this._canvas.removeEventListener("mousedown",this._eventHandlers.focusCanvas),this._canvas.removeEventListener("touchstart",this._eventHandlers.focusCanvas),this._resizeObserver.disconnect(),this._keyboard.ungrab(),this._gestures.detach(),this._sock.close();try{this._target.removeChild(this._screen)}catch(t){if(t.name!=="NotFoundError")throw t}clearTimeout(this._resizeTimeout),clearTimeout(this._mouseMoveTimer),de("<< RFB.disconnect")}_socketOpen(){this._rfbConnectionState==="connecting"&&this._rfbInitState===""?(this._rfbInitState="ProtocolVersion",de("Starting VNC handshake")):this._fail("Unexpected server connection while "+this._rfbConnectionState)}_socketClose(t){de("WebSocket on-close event");let n="";switch(t.code&&(n="(code: "+t.code,t.reason&&(n+=", reason: "+t.reason),n+=")"),this._rfbConnectionState){case"connecting":this._fail("Connection closed "+n);break;case"connected":this._updateConnectionState("disconnecting"),this._updateConnectionState("disconnected");break;case"disconnecting":this._updateConnectionState("disconnected");break;case"disconnected":this._fail("Unexpected server disconnect when already disconnected "+n);break;default:this._fail("Unexpected server disconnect before connecting "+n);break}this._sock.off("close"),this._rawChannel=null}_socketError(t){qe("WebSocket on-error event")}_focusCanvas(t){this.focusOnClick&&this.focus({preventScroll:!0})}_setDesktopName(t){this._fbName=t,this.dispatchEvent(new CustomEvent("desktopname",{detail:{name:this._fbName}}))}_saveExpectedClientSize(){this._expectedClientWidth=this._screen.clientWidth,this._expectedClientHeight=this._screen.clientHeight}_currentClientSize(){return[this._screen.clientWidth,this._screen.clientHeight]}_clientHasExpectedSize(){let[t,n]=this._currentClientSize();return t==this._expectedClientWidth&&n==this._expectedClientHeight}_handleResize(){this._clientHasExpectedSize()||(window.requestAnimationFrame(()=>{this._updateClip(),this._updateScale(),this._saveExpectedClientSize()}),this._requestRemoteResize())}_updateClip(){let t=this._display.clipViewport,n=this._clipViewport;if(this._scaleViewport&&(n=!1),t!==n&&(this._display.clipViewport=n),n){let r=this._screenSize();this._display.viewportChangeSize(r.w,r.h),this._fixScrollbars(),this._setClippingViewport(r.w<this._display.width||r.h<this._display.height)}else this._setClippingViewport(!1);t!==n&&this._saveExpectedClientSize()}_updateScale(){if(!this._scaleViewport)this._display.scale=1;else{let t=this._screenSize();this._display.autoscale(t.w,t.h)}this._fixScrollbars()}_requestRemoteResize(){if(!this._resizeSession||this._viewOnly||!this._supportsSetDesktopSize||this._pendingRemoteResize)return;if(Date.now()-this._lastResize<100){clearTimeout(this._resizeTimeout),this._resizeTimeout=setTimeout(this._requestRemoteResize.bind(this),100-(Date.now()-this._lastResize));return}this._resizeTimeout=null;let t=this._screenSize();t.w===this._fbWidth&&t.h===this._fbHeight||(this._pendingRemoteResize=!0,this._lastResize=Date.now(),e.messages.setDesktopSize(this._sock,Math.floor(t.w),Math.floor(t.h),this._screenID,this._screenFlags),de("Requested new desktop size: "+t.w+"x"+t.h))}_screenSize(){let t=this._screen.getBoundingClientRect();return{w:t.width,h:t.height}}_fixScrollbars(){let t=this._screen.style.overflow;this._screen.style.overflow="hidden",this._screen.getBoundingClientRect(),this._screen.style.overflow=t}_updateConnectionState(t){let n=this._rfbConnectionState;if(t===n){de("Already in state '"+t+"', ignoring");return}if(n==="disconnected"){Me("Tried changing state of a disconnected RFB object");return}switch(t){case"connected":if(n!=="connecting"){Me("Bad transition to connected state, previous connection state: "+n);return}break;case"disconnected":if(n!=="disconnecting"){Me("Bad transition to disconnected state, previous connection state: "+n);return}break;case"connecting":if(n!==""){Me("Bad transition to connecting state, previous connection state: "+n);return}break;case"disconnecting":if(n!=="connected"&&n!=="connecting"){Me("Bad transition to disconnecting state, previous connection state: "+n);return}break;default:Me("Unknown connection state: "+t);return}switch(this._rfbConnectionState=t,de("New state '"+t+"', was '"+n+"'."),this._disconnTimer&&t!=="disconnecting"&&(de("Clearing disconnect timer"),clearTimeout(this._disconnTimer),this._disconnTimer=null,this._sock.off("close")),t){case"connecting":this._connect();break;case"connected":this.dispatchEvent(new CustomEvent("connect",{detail:{}}));break;case"disconnecting":this._disconnect(),this._disconnTimer=setTimeout(()=>{Me("Disconnection timed out."),this._updateConnectionState("disconnected")},h$*1e3);break;case"disconnected":this.dispatchEvent(new CustomEvent("disconnect",{detail:{clean:this._rfbCleanDisconnect}}));break}}_fail(t){switch(this._rfbConnectionState){case"disconnecting":Me("Failed when disconnecting: "+t);break;case"connected":Me("Failed while connected: "+t);break;case"connecting":Me("Failed when connecting: "+t);break;default:Me("RFB failure: "+t);break}return this._rfbCleanDisconnect=!1,this._updateConnectionState("disconnecting"),this._updateConnectionState("disconnected"),!1}_setCapability(t,n){this._capabilities[t]=n,this.dispatchEvent(new CustomEvent("capabilities",{detail:{capabilities:this._capabilities}}))}_handleMessage(){if(this._sock.rQwait("message",1)){qe("handleMessage called on an empty receive queue");return}switch(this._rfbConnectionState){case"disconnected":Me("Got data while disconnected");break;case"connected":for(;!(this._flushing||!this._normalMsg()||this._sock.rQwait("message",1)););break;case"connecting":for(;this._rfbConnectionState==="connecting"&&this._initMsg(););break;default:Me("Got data while in an invalid state");break}}_handleKeyEvent(t,n,r,o,s){n=="CapsLock"&&r&&(this._remoteCapsLock=null),this._remoteCapsLock!==null&&s!==null&&this._remoteCapsLock!==s&&r&&(de("Fixing remote caps lock"),this.sendKey(C.XK_Caps_Lock,"CapsLock",!0),this.sendKey(C.XK_Caps_Lock,"CapsLock",!1),this._remoteCapsLock=null),n=="NumLock"&&r&&(this._remoteNumLock=null),this._remoteNumLock!==null&&o!==null&&this._remoteNumLock!==o&&r&&(de("Fixing remote num lock"),this.sendKey(C.XK_Num_Lock,"NumLock",!0),this.sendKey(C.XK_Num_Lock,"NumLock",!1),this._remoteNumLock=null),this.sendKey(t,n,r)}static _convertButtonMask(t){let n={0:1,1:4,2:2,3:128,4:256},r=0;for(let o=0;o<5;o++)t&1<<o&&(r|=n[o]);return r}_handleMouse(t){if(t.type==="click"&&t.target!==this._canvas||(t.stopPropagation(),t.preventDefault(),t.type==="click"||t.type==="contextmenu"))return;let n=Fo(t.clientX,t.clientY,this._canvas),r=e._convertButtonMask(t.buttons),o=t.type=="mousedown";switch(t.type){case"mousedown":case"mouseup":if(this.dragViewport)if(o&&!this._viewportDragging){this._viewportDragging=!0,this._viewportDragPos={x:n.x,y:n.y},this._viewportHasMoved=!1,this._flushMouseMoveTimer(n.x,n.y),this._mouseButtonMask=r;break}else{if(this._viewportDragging=!1,this._viewportHasMoved){this._mouseButtonMask=r;break}this._sendMouse(n.x,n.y,this._mouseButtonMask)}o&&xv(this._canvas),this._handleMouseButton(n.x,n.y,r);break;case"mousemove":if(this._viewportDragging){let s=this._viewportDragPos.x-n.x,i=this._viewportDragPos.y-n.y;(this._viewportHasMoved||Math.abs(s)>$i||Math.abs(i)>$i)&&(this._viewportHasMoved=!0,this._viewportDragPos={x:n.x,y:n.y},this._display.viewportChangePos(s,i));break}this._handleMouseMove(n.x,n.y);break}}_handleMouseButton(t,n,r){this._flushMouseMoveTimer(t,n),this._mouseButtonMask=r,this._sendMouse(t,n,this._mouseButtonMask)}_handleMouseMove(t,n){if(this._mousePos={x:t,y:n},this._mouseMoveTimer==null){let r=Date.now()-this._mouseLastMoveTime;r>jw?(this._sendMouse(t,n,this._mouseButtonMask),this._mouseLastMoveTime=Date.now()):this._mouseMoveTimer=setTimeout(()=>{this._handleDelayedMouseMove()},jw-r)}}_handleDelayedMouseMove(){this._mouseMoveTimer=null,this._sendMouse(this._mousePos.x,this._mousePos.y,this._mouseButtonMask),this._mouseLastMoveTime=Date.now()}_sendMouse(t,n,r){if(this._rfbConnectionState!=="connected"||this._viewOnly)return;if(r&32768)throw new Error("Illegal mouse button mask (mask: "+r+")");let o=r&32640;this._extendedPointerEventSupported&&o?e.messages.extendedPointerEvent(this._sock,this._display.absX(t),this._display.absY(n),r):e.messages.pointerEvent(this._sock,this._display.absX(t),this._display.absY(n),r)}_handleWheel(t){if(this._rfbConnectionState!=="connected"||this._viewOnly)return;t.stopPropagation(),t.preventDefault();let n=Fo(t.clientX,t.clientY,this._canvas),r=e._convertButtonMask(t.buttons),o=t.deltaX,s=t.deltaY;t.deltaMode!==0&&(o*=Gw,s*=Gw),this._accumulatedWheelDeltaX+=o,this._accumulatedWheelDeltaY+=s,Math.abs(this._accumulatedWheelDeltaX)>=Qw&&(this._accumulatedWheelDeltaX<0?(this._handleMouseButton(n.x,n.y,r|32),this._handleMouseButton(n.x,n.y,r)):this._accumulatedWheelDeltaX>0&&(this._handleMouseButton(n.x,n.y,r|64),this._handleMouseButton(n.x,n.y,r)),this._accumulatedWheelDeltaX=0),Math.abs(this._accumulatedWheelDeltaY)>=Qw&&(this._accumulatedWheelDeltaY<0?(this._handleMouseButton(n.x,n.y,r|8),this._handleMouseButton(n.x,n.y,r)):this._accumulatedWheelDeltaY>0&&(this._handleMouseButton(n.x,n.y,r|16),this._handleMouseButton(n.x,n.y,r)),this._accumulatedWheelDeltaY=0)}_fakeMouseMove(t,n,r){this._handleMouseMove(n,r),this._cursor.move(t.detail.clientX,t.detail.clientY)}_handleTapEvent(t,n){let r=Fo(t.detail.clientX,t.detail.clientY,this._canvas);if(this._gestureLastTapTime!==null&&Date.now()-this._gestureLastTapTime<g$&&this._gestureFirstDoubleTapEv.detail.type===t.detail.type){let o=this._gestureFirstDoubleTapEv.detail.clientX-t.detail.clientX,s=this._gestureFirstDoubleTapEv.detail.clientY-t.detail.clientY;Math.hypot(o,s)<x$?r=Fo(this._gestureFirstDoubleTapEv.detail.clientX,this._gestureFirstDoubleTapEv.detail.clientY,this._canvas):this._gestureFirstDoubleTapEv=t}else this._gestureFirstDoubleTapEv=t;this._gestureLastTapTime=Date.now(),this._fakeMouseMove(this._gestureFirstDoubleTapEv,r.x,r.y),this._handleMouseButton(r.x,r.y,n),this._handleMouseButton(r.x,r.y,0)}_handleGesture(t){let n,r=Fo(t.detail.clientX,t.detail.clientY,this._canvas);switch(t.type){case"gesturestart":switch(t.detail.type){case"onetap":this._handleTapEvent(t,1);break;case"twotap":this._handleTapEvent(t,4);break;case"threetap":this._handleTapEvent(t,2);break;case"drag":this.dragViewport?(this._viewportHasMoved=!1,this._viewportDragging=!0,this._viewportDragPos={x:r.x,y:r.y}):(this._fakeMouseMove(t,r.x,r.y),this._handleMouseButton(r.x,r.y,1));break;case"longpress":this.dragViewport?(this._viewportHasMoved=!1,this._viewportDragPos={x:r.x,y:r.y}):(this._fakeMouseMove(t,r.x,r.y),this._handleMouseButton(r.x,r.y,4));break;case"twodrag":this._gestureLastMagnitudeX=t.detail.magnitudeX,this._gestureLastMagnitudeY=t.detail.magnitudeY,this._fakeMouseMove(t,r.x,r.y);break;case"pinch":this._gestureLastMagnitudeX=Math.hypot(t.detail.magnitudeX,t.detail.magnitudeY),this._fakeMouseMove(t,r.x,r.y);break}break;case"gesturemove":switch(t.detail.type){case"onetap":case"twotap":case"threetap":break;case"drag":case"longpress":if(this.dragViewport){this._viewportDragging=!0;let o=this._viewportDragPos.x-r.x,s=this._viewportDragPos.y-r.y;(this._viewportHasMoved||Math.abs(o)>$i||Math.abs(s)>$i)&&(this._viewportHasMoved=!0,this._viewportDragPos={x:r.x,y:r.y},this._display.viewportChangePos(o,s))}else this._fakeMouseMove(t,r.x,r.y);break;case"twodrag":for(this._fakeMouseMove(t,r.x,r.y);t.detail.magnitudeY-this._gestureLastMagnitudeY>sr;)this._handleMouseButton(r.x,r.y,8),this._handleMouseButton(r.x,r.y,0),this._gestureLastMagnitudeY+=sr;for(;t.detail.magnitudeY-this._gestureLastMagnitudeY<-sr;)this._handleMouseButton(r.x,r.y,16),this._handleMouseButton(r.x,r.y,0),this._gestureLastMagnitudeY-=sr;for(;t.detail.magnitudeX-this._gestureLastMagnitudeX>sr;)this._handleMouseButton(r.x,r.y,32),this._handleMouseButton(r.x,r.y,0),this._gestureLastMagnitudeX+=sr;for(;t.detail.magnitudeX-this._gestureLastMagnitudeX<-sr;)this._handleMouseButton(r.x,r.y,64),this._handleMouseButton(r.x,r.y,0),this._gestureLastMagnitudeX-=sr;break;case"pinch":if(this._fakeMouseMove(t,r.x,r.y),n=Math.hypot(t.detail.magnitudeX,t.detail.magnitudeY),Math.abs(n-this._gestureLastMagnitudeX)>aa){for(this._handleKeyEvent(C.XK_Control_L,"ControlLeft",!0);n-this._gestureLastMagnitudeX>aa;)this._handleMouseButton(r.x,r.y,8),this._handleMouseButton(r.x,r.y,0),this._gestureLastMagnitudeX+=aa;for(;n-this._gestureLastMagnitudeX<-aa;)this._handleMouseButton(r.x,r.y,16),this._handleMouseButton(r.x,r.y,0),this._gestureLastMagnitudeX-=aa}this._handleKeyEvent(C.XK_Control_L,"ControlLeft",!1);break}break;case"gestureend":switch(t.detail.type){case"onetap":case"twotap":case"threetap":case"pinch":case"twodrag":break;case"drag":this.dragViewport?this._viewportDragging=!1:(this._fakeMouseMove(t,r.x,r.y),this._handleMouseButton(r.x,r.y,0));break;case"longpress":if(this._viewportHasMoved)break;this.dragViewport&&!this._viewportHasMoved?(this._fakeMouseMove(t,r.x,r.y),this._handleMouseButton(r.x,r.y,4),this._handleMouseButton(r.x,r.y,0),this._viewportDragging=!1):(this._fakeMouseMove(t,r.x,r.y),this._handleMouseButton(r.x,r.y,0));break}break}}_flushMouseMoveTimer(t,n){this._mouseMoveTimer!==null&&(clearTimeout(this._mouseMoveTimer),this._mouseMoveTimer=null,this._sendMouse(t,n,this._mouseButtonMask))}_negotiateProtocolVersion(){if(this._sock.rQwait("version",12))return!1;let t=this._sock.rQshiftStr(12).substr(4,7);Qe("Server ProtocolVersion: "+t);let n=0;switch(t){case"000.000":n=1;break;case"003.003":case"003.006":this._rfbVersion=3.3;break;case"003.007":this._rfbVersion=3.7;break;case"003.008":case"003.889":case"004.000":case"004.001":case"005.000":this._rfbVersion=3.8;break;default:return this._fail("Invalid server version "+t)}if(n){let o="ID:"+this._repeaterID;for(;o.length<250;)o+="\0";return this._sock.sQpushString(o),this._sock.flush(),!0}this._rfbVersion>this._rfbMaxVersion&&(this._rfbVersion=this._rfbMaxVersion);let r="00"+parseInt(this._rfbVersion,10)+".00"+this._rfbVersion*10%10;this._sock.sQpushString("RFB "+r+`
2
+ `),this._sock.flush(),de("Sent ProtocolVersion: "+r),this._rfbInitState="Security"}_isSupportedSecurityType(t){return[Yw,Oc,qw,Jw,vh,ek,tk,nk,ok].includes(t)}_negotiateSecurity(){if(this._rfbVersion>=3.7){let t=this._sock.rQshift8();if(this._sock.rQwait("security type",t,1))return!1;if(t===0)return this._rfbInitState="SecurityReason",this._securityContext="no security types",this._securityStatus=1,!0;let n=this._sock.rQshiftBytes(t);de("Server security types: "+n),this._rfbAuthScheme=-1;for(let r of n)if(this._isSupportedSecurityType(r)){this._rfbAuthScheme=r;break}if(this._rfbAuthScheme===-1)return this._fail("Unsupported security types (types: "+n+")");this._sock.sQpush8(this._rfbAuthScheme),this._sock.flush()}else{if(this._sock.rQwait("security scheme",4))return!1;if(this._rfbAuthScheme=this._sock.rQshift32(),this._rfbAuthScheme==0)return this._rfbInitState="SecurityReason",this._securityContext="authentication scheme",this._securityStatus=1,!0}return this._rfbInitState="Authentication",de("Authenticating using scheme: "+this._rfbAuthScheme),!0}_handleSecurityReason(){if(this._sock.rQwait("reason length",4))return!1;let t=this._sock.rQshift32(),n="";if(t>0){if(this._sock.rQwait("reason",t,4))return!1;n=this._sock.rQshiftStr(t)}return n!==""?(this.dispatchEvent(new CustomEvent("securityfailure",{detail:{status:this._securityStatus,reason:n}})),this._fail("Security negotiation failed on "+this._securityContext+" (reason: "+n+")")):(this.dispatchEvent(new CustomEvent("securityfailure",{detail:{status:this._securityStatus}})),this._fail("Security negotiation failed on "+this._securityContext))}_negotiateXvpAuth(){return this._rfbCredentials.username===void 0||this._rfbCredentials.password===void 0||this._rfbCredentials.target===void 0?(this.dispatchEvent(new CustomEvent("credentialsrequired",{detail:{types:["username","password","target"]}})),!1):(this._sock.sQpush8(this._rfbCredentials.username.length),this._sock.sQpush8(this._rfbCredentials.target.length),this._sock.sQpushString(this._rfbCredentials.username),this._sock.sQpushString(this._rfbCredentials.target),this._sock.flush(),this._rfbAuthScheme=Oc,this._negotiateAuthentication())}_negotiateVeNCryptAuth(){if(this._rfbVeNCryptState==0){if(this._sock.rQwait("vencrypt version",2))return!1;let t=this._sock.rQshift8(),n=this._sock.rQshift8();if(!(t==0&&n==2))return this._fail("Unsupported VeNCrypt version "+t+"."+n);this._sock.sQpush8(0),this._sock.sQpush8(2),this._sock.flush(),this._rfbVeNCryptState=1}if(this._rfbVeNCryptState==1){if(this._sock.rQwait("vencrypt ack",1))return!1;let t=this._sock.rQshift8();if(t!=0)return this._fail("VeNCrypt failure "+t);this._rfbVeNCryptState=2}if(this._rfbVeNCryptState==2){if(this._sock.rQwait("vencrypt subtypes length",1))return!1;let t=this._sock.rQshift8();if(t<1)return this._fail("VeNCrypt subtypes empty");this._rfbVeNCryptSubtypesLength=t,this._rfbVeNCryptState=3}if(this._rfbVeNCryptState==3){if(this._sock.rQwait("vencrypt subtypes",4*this._rfbVeNCryptSubtypesLength))return!1;let t=[];for(let n=0;n<this._rfbVeNCryptSubtypesLength;n++)t.push(this._sock.rQshift32());this._rfbAuthScheme=-1;for(let n of t)if(n!==vh&&this._isSupportedSecurityType(n)){this._rfbAuthScheme=n;break}return this._rfbAuthScheme===-1?this._fail("Unsupported security types (types: "+t+")"):(this._sock.sQpush32(this._rfbAuthScheme),this._sock.flush(),this._rfbVeNCryptState=4,!0)}}_negotiatePlainAuth(){if(this._rfbCredentials.username===void 0||this._rfbCredentials.password===void 0)return this.dispatchEvent(new CustomEvent("credentialsrequired",{detail:{types:["username","password"]}})),!1;let t=Gt(this._rfbCredentials.username),n=Gt(this._rfbCredentials.password);return this._sock.sQpush32(t.length),this._sock.sQpush32(n.length),this._sock.sQpushString(t),this._sock.sQpushString(n),this._sock.flush(),this._rfbInitState="SecurityResult",!0}_negotiateStdVNCAuth(){if(this._sock.rQwait("auth challenge",16))return!1;if(this._rfbCredentials.password===void 0)return this.dispatchEvent(new CustomEvent("credentialsrequired",{detail:{types:["password"]}})),!1;let t=Array.prototype.slice.call(this._sock.rQshiftBytes(16)),n=e.genDES(this._rfbCredentials.password,t);return this._sock.sQpushBytes(n),this._sock.flush(),this._rfbInitState="SecurityResult",!0}_negotiateARDAuth(){if(this._rfbCredentials.username===void 0||this._rfbCredentials.password===void 0)return this.dispatchEvent(new CustomEvent("credentialsrequired",{detail:{types:["username","password"]}})),!1;if(this._rfbCredentials.ardPublicKey!=null&&this._rfbCredentials.ardCredentials!=null)return this._sock.sQpushBytes(this._rfbCredentials.ardCredentials),this._sock.sQpushBytes(this._rfbCredentials.ardPublicKey),this._sock.flush(),this._rfbCredentials.ardCredentials=null,this._rfbCredentials.ardPublicKey=null,this._rfbInitState="SecurityResult",!0;if(this._sock.rQwait("read ard",4))return!1;let t=this._sock.rQshiftBytes(2),n=this._sock.rQshift16();if(this._sock.rQwait("read ard keylength",n*2,4))return!1;let r=this._sock.rQshiftBytes(n),o=this._sock.rQshiftBytes(n),s=Xe.generateKey({name:"DH",g:t,p:r},!1,["deriveBits"]);return this._negotiateARDAuthAsync(n,o,s),!1}async _negotiateARDAuthAsync(t,n,r){let o=Xe.exportKey("raw",r.publicKey),s=Xe.deriveBits({name:"DH",public:n},r.privateKey,t*8),i=Gt(this._rfbCredentials.username).substring(0,63),a=Gt(this._rfbCredentials.password).substring(0,63),u=window.crypto.getRandomValues(new Uint8Array(128));for(let f=0;f<i.length;f++)u[f]=i.charCodeAt(f);u[i.length]=0;for(let f=0;f<a.length;f++)u[64+f]=a.charCodeAt(f);u[64+a.length]=0;let c=await Xe.digest("MD5",s),d=await Xe.importKey("raw",c,{name:"AES-ECB"},!1,["encrypt"]),p=await Xe.encrypt({name:"AES-ECB"},d,u);this._rfbCredentials.ardCredentials=p,this._rfbCredentials.ardPublicKey=o,this._resumeAuthentication()}_negotiateTightUnixAuth(){return this._rfbCredentials.username===void 0||this._rfbCredentials.password===void 0?(this.dispatchEvent(new CustomEvent("credentialsrequired",{detail:{types:["username","password"]}})),!1):(this._sock.sQpush32(this._rfbCredentials.username.length),this._sock.sQpush32(this._rfbCredentials.password.length),this._sock.sQpushString(this._rfbCredentials.username),this._sock.sQpushString(this._rfbCredentials.password),this._sock.flush(),this._rfbInitState="SecurityResult",!0)}_negotiateTightTunnels(t){let n={0:{vendor:"TGHT",signature:"NOTUNNEL"}},r={};for(let o=0;o<t;o++){let s=this._sock.rQshift32(),i=this._sock.rQshiftStr(4),a=this._sock.rQshiftStr(8);r[s]={vendor:i,signature:a}}return de("Server Tight tunnel types: "+r),r[1]&&r[1].vendor==="SICR"&&r[1].signature==="SCHANNEL"&&(de("Detected Siemens server. Assuming NOTUNNEL support."),r[0]={vendor:"TGHT",signature:"NOTUNNEL"}),r[0]?r[0].vendor!=n[0].vendor||r[0].signature!=n[0].signature?this._fail("Client's tunnel type had the incorrect vendor or signature"):(de("Selected tunnel type: "+n[0]),this._sock.sQpush32(0),this._sock.flush(),!1):this._fail("Server wanted tunnels, but doesn't support the notunnel type")}_negotiateTightAuth(){if(!this._rfbTightVNC){if(this._sock.rQwait("num tunnels",4))return!1;let o=this._sock.rQshift32();if(o>0&&this._sock.rQwait("tunnel capabilities",16*o,4))return!1;if(this._rfbTightVNC=!0,o>0)return this._negotiateTightTunnels(o),!1}if(this._sock.rQwait("sub auth count",4))return!1;let t=this._sock.rQshift32();if(t===0)return this._rfbInitState="SecurityResult",!0;if(this._sock.rQwait("sub auth capabilities",16*t,4))return!1;let n={STDVNOAUTH__:1,STDVVNCAUTH_:2,TGHTULGNAUTH:129},r=[];for(let o=0;o<t;o++){this._sock.rQshift32();let s=this._sock.rQshiftStr(12);r.push(s)}de("Server Tight authentication types: "+r);for(let o in n)if(r.indexOf(o)!=-1)switch(this._sock.sQpush32(n[o]),this._sock.flush(),de("Selected authentication type: "+o),o){case"STDVNOAUTH__":return this._rfbInitState="SecurityResult",!0;case"STDVVNCAUTH_":return this._rfbAuthScheme=Oc,!0;case"TGHTULGNAUTH":return this._rfbAuthScheme=rk,!0;default:return this._fail("Unsupported tiny auth scheme (scheme: "+o+")")}return this._fail("No supported sub-auth types!")}_handleRSAAESCredentialsRequired(t){this.dispatchEvent(t)}_handleRSAAESServerVerification(t){this.dispatchEvent(t)}_negotiateRA2neAuth(){return this._rfbRSAAESAuthenticationState===null&&(this._rfbRSAAESAuthenticationState=new Yi(this._sock,()=>this._rfbCredentials),this._rfbRSAAESAuthenticationState.addEventListener("serververification",this._eventHandlers.handleRSAAESServerVerification),this._rfbRSAAESAuthenticationState.addEventListener("credentialsrequired",this._eventHandlers.handleRSAAESCredentialsRequired)),this._rfbRSAAESAuthenticationState.checkInternalEvents(),this._rfbRSAAESAuthenticationState.hasStarted||this._rfbRSAAESAuthenticationState.negotiateRA2neAuthAsync().catch(t=>{t.message!=="disconnect normally"&&this._fail(t.message)}).then(()=>(this._rfbInitState="SecurityResult",!0)).finally(()=>{this._rfbRSAAESAuthenticationState.removeEventListener("serververification",this._eventHandlers.handleRSAAESServerVerification),this._rfbRSAAESAuthenticationState.removeEventListener("credentialsrequired",this._eventHandlers.handleRSAAESCredentialsRequired),this._rfbRSAAESAuthenticationState=null}),!1}_negotiateMSLogonIIAuth(){if(this._sock.rQwait("mslogonii dh param",24))return!1;if(this._rfbCredentials.username===void 0||this._rfbCredentials.password===void 0)return this.dispatchEvent(new CustomEvent("credentialsrequired",{detail:{types:["username","password"]}})),!1;let t=this._sock.rQshiftBytes(8),n=this._sock.rQshiftBytes(8),r=this._sock.rQshiftBytes(8),o=Xe.generateKey({name:"DH",g:t,p:n},!0,["deriveBits"]),s=Xe.exportKey("raw",o.publicKey),i=Xe.deriveBits({name:"DH",public:r},o.privateKey,64),a=Xe.importKey("raw",i,{name:"DES-CBC"},!1,["encrypt"]),u=Gt(this._rfbCredentials.username).substring(0,255),c=Gt(this._rfbCredentials.password).substring(0,63),d=new Uint8Array(256),p=new Uint8Array(64);window.crypto.getRandomValues(d),window.crypto.getRandomValues(p);for(let f=0;f<u.length;f++)d[f]=u.charCodeAt(f);d[u.length]=0;for(let f=0;f<c.length;f++)p[f]=c.charCodeAt(f);return p[c.length]=0,d=Xe.encrypt({name:"DES-CBC",iv:i},a,d),p=Xe.encrypt({name:"DES-CBC",iv:i},a,p),this._sock.sQpushBytes(s),this._sock.sQpushBytes(d),this._sock.sQpushBytes(p),this._sock.flush(),this._rfbInitState="SecurityResult",!0}_negotiateAuthentication(){switch(this._rfbAuthScheme){case Yw:return this._rfbVersion>=3.8?this._rfbInitState="SecurityResult":this._rfbInitState="ClientInitialisation",!0;case ek:return this._negotiateXvpAuth();case tk:return this._negotiateARDAuth();case Oc:return this._negotiateStdVNCAuth();case Jw:return this._negotiateTightAuth();case vh:return this._negotiateVeNCryptAuth();case ok:return this._negotiatePlainAuth();case rk:return this._negotiateTightUnixAuth();case qw:return this._negotiateRA2neAuth();case nk:return this._negotiateMSLogonIIAuth();default:return this._fail("Unsupported auth scheme (scheme: "+this._rfbAuthScheme+")")}}_handleSecurityResult(){if(this._sock.rQwait("VNC auth response ",4))return!1;let t=this._sock.rQshift32();return t===0?(this._rfbInitState="ClientInitialisation",de("Authentication OK"),!0):this._rfbVersion>=3.8?(this._rfbInitState="SecurityReason",this._securityContext="security result",this._securityStatus=t,!0):(this.dispatchEvent(new CustomEvent("securityfailure",{detail:{status:t}})),this._fail("Security handshake failed"))}_negotiateServerInit(){if(this._sock.rQwait("server initialization",24))return!1;let t=this._sock.rQshift16(),n=this._sock.rQshift16(),r=this._sock.rQshift8(),o=this._sock.rQshift8(),s=this._sock.rQshift8(),i=this._sock.rQshift8(),a=this._sock.rQshift16(),u=this._sock.rQshift16(),c=this._sock.rQshift16(),d=this._sock.rQshift8(),p=this._sock.rQshift8(),f=this._sock.rQshift8();this._sock.rQskipBytes(3);let h=this._sock.rQshift32();if(this._sock.rQwait("server init name",h,24))return!1;let g=this._sock.rQshiftStr(h);if(g=ac(g,!0),this._rfbTightVNC){if(this._sock.rQwait("TightVNC extended server init header",8,24+h))return!1;let x=this._sock.rQshift16(),b=this._sock.rQshift16(),_=this._sock.rQshift16();this._sock.rQskipBytes(2);let w=(x+b+_)*16;if(this._sock.rQwait("TightVNC extended server init header",w,32+h))return!1;this._sock.rQskipBytes(16*x),this._sock.rQskipBytes(16*b),this._sock.rQskipBytes(16*_)}return Qe("Screen: "+t+"x"+n+", bpp: "+r+", depth: "+o+", bigEndian: "+s+", trueColor: "+i+", redMax: "+a+", greenMax: "+u+", blueMax: "+c+", redShift: "+d+", greenShift: "+p+", blueShift: "+f),this._setDesktopName(g),this._resize(t,n),this._viewOnly||this._keyboard.grab(),this._fbDepth=24,this._fbName==="Intel(r) AMT KVM"&&(qe("Intel AMT KVM only supports 8/16 bit depths. Using low color mode."),this._fbDepth=8),e.messages.pixelFormat(this._sock,this._fbDepth,!0),this._sendEncodings(),e.messages.fbUpdateRequest(this._sock,!1,0,0,this._fbWidth,this._fbHeight),this._updateConnectionState("connected"),!0}_sendEncodings(){let t=[];t.push(ge.encodingCopyRect),this._fbDepth==24&&(Ff&&t.push(ge.encodingH264),t.push(ge.encodingTight),t.push(ge.encodingTightPNG),t.push(ge.encodingZRLE),t.push(ge.encodingJPEG),t.push(ge.encodingHextile),t.push(ge.encodingRRE),t.push(ge.encodingZlib)),t.push(ge.encodingRaw),t.push(ge.pseudoEncodingQualityLevel0+this._qualityLevel),t.push(ge.pseudoEncodingCompressLevel0+this._compressionLevel),t.push(ge.pseudoEncodingDesktopSize),t.push(ge.pseudoEncodingLastRect),t.push(ge.pseudoEncodingQEMUExtendedKeyEvent),t.push(ge.pseudoEncodingQEMULedEvent),t.push(ge.pseudoEncodingExtendedDesktopSize),t.push(ge.pseudoEncodingXvp),t.push(ge.pseudoEncodingFence),t.push(ge.pseudoEncodingContinuousUpdates),t.push(ge.pseudoEncodingDesktopName),t.push(ge.pseudoEncodingExtendedClipboard),t.push(ge.pseudoEncodingExtendedMouseButtons),this._fbDepth==24&&(t.push(ge.pseudoEncodingVMwareCursor),t.push(ge.pseudoEncodingCursor)),e.messages.clientEncodings(this._sock,t)}_initMsg(){switch(this._rfbInitState){case"ProtocolVersion":return this._negotiateProtocolVersion();case"Security":return this._negotiateSecurity();case"Authentication":return this._negotiateAuthentication();case"SecurityResult":return this._handleSecurityResult();case"SecurityReason":return this._handleSecurityReason();case"ClientInitialisation":return this._sock.sQpush8(this._shared?1:0),this._sock.flush(),this._rfbInitState="ServerInitialisation",!0;case"ServerInitialisation":return this._negotiateServerInit();default:return this._fail("Unknown init state (state: "+this._rfbInitState+")")}}_resumeAuthentication(){setTimeout(this._initMsg.bind(this),0)}_handleSetColourMapMsg(){return de("SetColorMapEntries"),this._fail("Unexpected SetColorMapEntries message")}_handleServerCutText(){if(de("ServerCutText"),this._sock.rQwait("ServerCutText header",7,1))return!1;this._sock.rQskipBytes(3);let t=this._sock.rQshift32();if(t=Ri(t),this._sock.rQwait("ServerCutText content",Math.abs(t),8))return!1;if(t>=0){let n=this._sock.rQshiftStr(t);if(this._viewOnly)return!0;this.dispatchEvent(new CustomEvent("clipboard",{detail:{text:n}}))}else{t=Math.abs(t);let n=this._sock.rQshift32(),r=n&65535,o=n&4278190080;if(!!(o&sk)){this._clipboardServerCapabilitiesFormats={},this._clipboardServerCapabilitiesActions={};for(let a=0;a<=15;a++){let u=1<<a;r&u&&(this._clipboardServerCapabilitiesFormats[u]=!0,this._sock.rQshift32())}for(let a=24;a<=31;a++){let u=1<<a;this._clipboardServerCapabilitiesActions[u]=!!(o&u)}let i=[sk,Lc,ik,la,Mc];e.messages.extendedClipboardCaps(this._sock,i,{extendedClipboardFormatText:0})}else if(o===Lc){if(this._viewOnly)return!0;this._clipboardText!=null&&this._clipboardServerCapabilitiesActions[Mc]&&r&hn&&e.messages.extendedClipboardProvide(this._sock,[hn],[this._clipboardText])}else if(o===ik){if(this._viewOnly)return!0;this._clipboardServerCapabilitiesActions[la]&&(this._clipboardText!=null?e.messages.extendedClipboardNotify(this._sock,[hn]):e.messages.extendedClipboardNotify(this._sock,[]))}else if(o===la){if(this._viewOnly)return!0;this._clipboardServerCapabilitiesActions[Lc]&&r&hn&&e.messages.extendedClipboardRequest(this._sock,[hn])}else if(o===Mc){if(this._viewOnly||!(r&hn))return!0;this._clipboardText=null;let i=this._sock.rQshiftBytes(t-4),a=new Yt,u=null;a.setInput(i);for(let c=0;c<=15;c++){let d=1<<c;if(r&d){let p=0,f=a.inflate(4);p|=f[0]<<24,p|=f[1]<<16,p|=f[2]<<8,p|=f[3];let h=a.inflate(p);d===hn&&(u=h)}}if(a.setInput(null),u!==null){let c="";for(let d=0;d<u.length;d++)c+=String.fromCharCode(u[d]);u=c,u=ac(u),u.length>0&&u.charAt(u.length-1)==="\0"&&(u=u.slice(0,-1)),u=u.replaceAll(`\r
3
3
  `,`
4
- `),this.dispatchEvent(new CustomEvent("clipboard",{detail:{text:u}}))}}else return this._fail("Unexpected action in extended clipboard message: "+o)}return!0}_handleServerFenceMsg(){if(this._sock.rQwait("ServerFence header",8,1))return!1;this._sock.rQskipBytes(3);let t=this._sock.rQshift32(),n=this._sock.rQshift8();if(this._sock.rQwait("ServerFence payload",n,9))return!1;n>64&&(Ye("Bad payload length ("+n+") in fence response"),n=64);let r=this._sock.rQshiftStr(n);return this._supportsFence=!0,t&1<<31?(t&=3,e.messages.clientFence(this._sock,t,r),!0):this._fail("Unexpected fence response")}_handleXvpMsg(){if(this._sock.rQwait("XVP version and message",3,1))return!1;this._sock.rQskipBytes(1);let t=this._sock.rQshift8(),n=this._sock.rQshift8();switch(n){case 0:Me("XVP operation failed");break;case 1:this._rfbXvpVer=t,Qe("XVP extensions enabled (version "+this._rfbXvpVer+")"),this._setCapability("power",!0);break;default:this._fail("Illegal server XVP message (msg: "+n+")");break}return!0}_normalMsg(){let t;this._FBU.rects>0?t=0:t=this._sock.rQshift8();let n,r;switch(t){case 0:return r=this._framebufferUpdate(),r&&!this._enabledContinuousUpdates&&e.messages.fbUpdateRequest(this._sock,!0,0,0,this._fbWidth,this._fbHeight),r;case 1:return this._handleSetColourMapMsg();case 2:return de("Bell"),this.dispatchEvent(new CustomEvent("bell",{detail:{}})),!0;case 3:return this._handleServerCutText();case 150:return n=!this._supportsContinuousUpdates,this._supportsContinuousUpdates=!0,this._enabledContinuousUpdates=!1,n&&(this._enabledContinuousUpdates=!0,this._updateContinuousUpdates(),Qe("Enabling continuous updates.")),!0;case 248:return this._handleServerFenceMsg();case 250:return this._handleXvpMsg();default:return this._fail("Unexpected server message (type "+t+")"),de("sock.rQpeekBytes(30): "+this._sock.rQpeekBytes(30)),!0}}_framebufferUpdate(){if(this._FBU.rects===0){if(this._sock.rQwait("FBU header",3,1))return!1;if(this._sock.rQskipBytes(1),this._FBU.rects=this._sock.rQshift16(),this._display.pending())return this._flushing=!0,this._display.flush().then(()=>{this._flushing=!1,this._sock.rQwait("message",1)||this._handleMessage()}),!1}for(;this._FBU.rects>0;){if(this._FBU.encoding===null){if(this._sock.rQwait("rect header",12))return!1;this._FBU.x=this._sock.rQshift16(),this._FBU.y=this._sock.rQshift16(),this._FBU.width=this._sock.rQshift16(),this._FBU.height=this._sock.rQshift16(),this._FBU.encoding=this._sock.rQshift32(),this._FBU.encoding>>=0}if(!this._handleRect())return!1;this._FBU.rects--,this._FBU.encoding=null}return this._display.flip(),!0}_handleRect(){switch(this._FBU.encoding){case ge.pseudoEncodingLastRect:return this._FBU.rects=1,!0;case ge.pseudoEncodingVMwareCursor:return this._handleVMwareCursor();case ge.pseudoEncodingCursor:return this._handleCursor();case ge.pseudoEncodingQEMUExtendedKeyEvent:return this._qemuExtKeyEventSupported=!0,!0;case ge.pseudoEncodingDesktopName:return this._handleDesktopName();case ge.pseudoEncodingDesktopSize:return this._resize(this._FBU.width,this._FBU.height),!0;case ge.pseudoEncodingExtendedDesktopSize:return this._handleExtendedDesktopSize();case ge.pseudoEncodingExtendedMouseButtons:return this._extendedPointerEventSupported=!0,!0;case ge.pseudoEncodingQEMULedEvent:return this._handleLedEvent();default:return this._handleDataRect()}}_handleVMwareCursor(){let t=this._FBU.x,n=this._FBU.y,r=this._FBU.width,o=this._FBU.height;if(this._sock.rQwait("VMware cursor encoding",1))return!1;let s=this._sock.rQshift8();this._sock.rQshift8();let i,a=4;if(s==0){if(i=new Array(r*o*a),this._sock.rQwait("VMware cursor classic encoding",r*o*a*2,2))return!1;let c=new Array(r*o);for(let p=0;p<r*o;p++)c[p]=this._sock.rQshift32();let d=new Array(r*o);for(let p=0;p<r*o;p++)d[p]=this._sock.rQshift32();for(let p=0;p<r*o;p++)if(c[p]==0){let f=d[p],h=f>>8&255,g=f>>16&255,x=f>>24&255;i[p*a]=h,i[p*a+1]=g,i[p*a+2]=x,i[p*a+3]=255}else(c[p]&-256)==-256?d[p]==0?(i[p*a]=0,i[p*a+1]=0,i[p*a+2]=0,i[p*a+3]=0):(d[p]&-256,i[p*a]=0,i[p*a+1]=0,i[p*a+2]=0,i[p*a+3]=255):(i[p*a]=0,i[p*a+1]=0,i[p*a+2]=0,i[p*a+3]=255)}else if(s==1){if(this._sock.rQwait("VMware cursor alpha encoding",r*o*4,2))return!1;i=new Array(r*o*a);for(let u=0;u<r*o;u++){let c=this._sock.rQshift32();i[u*4]=c>>24&255,i[u*4+1]=c>>16&255,i[u*4+2]=c>>8&255,i[u*4+3]=c&255}}else return Ye("The given cursor type is not supported: "+s+" given."),!1;return this._updateCursor(i,t,n,r,o),!0}_handleCursor(){let t=this._FBU.x,n=this._FBU.y,r=this._FBU.width,o=this._FBU.height,s=r*o*4,i=Math.ceil(r/8)*o,a=s+i;if(this._sock.rQwait("cursor encoding",a))return!1;let u=this._sock.rQshiftBytes(s),c=this._sock.rQshiftBytes(i),d=new Uint8Array(r*o*4),p=0;for(let f=0;f<o;f++)for(let h=0;h<r;h++){let g=f*Math.ceil(r/8)+Math.floor(h/8),x=c[g]<<h%8&128?255:0;d[p]=u[p+2],d[p+1]=u[p+1],d[p+2]=u[p],d[p+3]=x,p+=4}return this._updateCursor(d,t,n,r,o),!0}_handleDesktopName(){if(this._sock.rQwait("DesktopName",4))return!1;let t=this._sock.rQshift32();if(this._sock.rQwait("DesktopName",t,4))return!1;let n=this._sock.rQshiftStr(t);return n=ic(n,!0),this._setDesktopName(n),!0}_handleLedEvent(){if(this._sock.rQwait("LED status",1))return!1;let t=this._sock.rQshift8(),n=!!(t&2),r=!!(t&4);return this._remoteCapsLock=r,this._remoteNumLock=n,!0}_handleExtendedDesktopSize(){if(this._sock.rQwait("ExtendedDesktopSize",4))return!1;let t=this._sock.rQpeek8(),n=4+t*16;if(this._sock.rQwait("ExtendedDesktopSize",n))return!1;let r=!this._supportsSetDesktopSize;this._supportsSetDesktopSize=!0,this._sock.rQskipBytes(1),this._sock.rQskipBytes(3);for(let o=0;o<t;o+=1)o===0?(this._screenID=this._sock.rQshift32(),this._sock.rQskipBytes(2),this._sock.rQskipBytes(2),this._sock.rQskipBytes(2),this._sock.rQskipBytes(2),this._screenFlags=this._sock.rQshift32()):this._sock.rQskipBytes(16);if(this._FBU.x===1&&(this._pendingRemoteResize=!1),this._FBU.x===1&&this._FBU.y!==0){let o="";switch(this._FBU.y){case 1:o="Resize is administratively prohibited";break;case 2:o="Out of resources";break;case 3:o="Invalid screen layout";break;default:o="Unknown reason";break}Ye("Server did not accept the resize request: "+o)}else this._resize(this._FBU.width,this._FBU.height);return r&&this._requestRemoteResize(),this._FBU.x===1&&this._FBU.y===0&&this._requestRemoteResize(),!0}_handleDataRect(){let t=this._decoders[this._FBU.encoding];if(!t)return this._fail("Unsupported encoding (encoding: "+this._FBU.encoding+")"),!1;try{return t.decodeRect(this._FBU.x,this._FBU.y,this._FBU.width,this._FBU.height,this._sock,this._display,this._fbDepth)}catch(n){return this._fail("Error decoding rect: "+n),!1}}_updateContinuousUpdates(){this._enabledContinuousUpdates&&e.messages.enableContinuousUpdates(this._sock,!0,0,0,this._fbWidth,this._fbHeight)}_resize(t,n){this._fbWidth=t,this._fbHeight=n,this._display.resize(this._fbWidth,this._fbHeight),this._updateClip(),this._updateScale(),this._updateContinuousUpdates(),this._saveExpectedClientSize()}_xvpOp(t,n){this._rfbXvpVer<t||(Qe("Sending XVP operation "+n+" (version "+t+")"),e.messages.xvpOp(this._sock,t,n))}_updateCursor(t,n,r,o,s){this._cursorImage={rgbaPixels:t,hotx:n,hoty:r,w:o,h:s},this._refreshCursor()}_shouldShowDotCursor(){if(!this._showDotCursor)return!1;for(let t=3;t<this._cursorImage.rgbaPixels.length;t+=4)if(this._cursorImage.rgbaPixels[t])return!1;return!0}_refreshCursor(){if(this._rfbConnectionState!=="connecting"&&this._rfbConnectionState!=="connected")return;let t=this._shouldShowDotCursor()?e.cursors.dot:this._cursorImage;this._cursor.change(t.rgbaPixels,t.hotx,t.hoty,t.w,t.h)}static genDES(t,n){let r=t.split("").map(s=>s.charCodeAt(0)),o=Xe.importKey("raw",r,{name:"DES-ECB"},!1,["encrypt"]);return Xe.encrypt({name:"DES-ECB"},o,n)}};yt.messages={keyEvent(e,t,n){e.sQpush8(4),e.sQpush8(n),e.sQpush16(0),e.sQpush32(t),e.flush()},QEMUExtendedKeyEvent(e,t,n,r){function o(i){let a=r>>8,u=r&255;return a===224&&u<127?u|128:i}e.sQpush8(255),e.sQpush8(0),e.sQpush16(n),e.sQpush32(t);let s=o(r);e.sQpush32(s),e.flush()},pointerEvent(e,t,n,r){e.sQpush8(5),r=r&127,e.sQpush8(r),e.sQpush16(t),e.sQpush16(n),e.flush()},extendedPointerEvent(e,t,n,r){e.sQpush8(5);let o=r>>7&255;if(o&252)throw new Error("Invalid mouse button mask: "+r);let s=r&127;s|=128,e.sQpush8(s),e.sQpush16(t),e.sQpush16(n),e.sQpush8(o),e.flush()},_buildExtendedClipboardFlags(e,t){let n=new Uint8Array(4),r=0,o=0;for(let s=0;s<e.length;s++)o|=e[s];for(let s=0;s<t.length;s++)r|=t[s];return n[0]=o>>24,n[1]=0,n[2]=0,n[3]=r,n},extendedClipboardProvide(e,t,n){let r=new Hi,o=[];for(let a=0;a<t.length;a++){if(t[a]!=fn)throw new Error("Unsupported extended clipboard format for Provide message.");n[a]=n[a].replace(/\r\n|\r|\n/gm,`\r
5
- `);let u=Gt(n[a]+"\0");o.push(u.length>>24&255,u.length>>16&255,u.length>>8&255,u.length&255);for(let c=0;c<u.length;c++)o.push(u.charCodeAt(c))}let s=r.deflate(new Uint8Array(o)),i=new Uint8Array(4+s.length);i.set(yt.messages._buildExtendedClipboardFlags([Lc],t)),i.set(s,4),yt.messages.clientCutText(e,i,!0)},extendedClipboardNotify(e,t){let n=yt.messages._buildExtendedClipboardFlags([aa],t);yt.messages.clientCutText(e,n,!0)},extendedClipboardRequest(e,t){let n=yt.messages._buildExtendedClipboardFlags([Oc],t);yt.messages.clientCutText(e,n,!0)},extendedClipboardCaps(e,t,n){let r=Object.keys(n),o=new Uint8Array(4+4*r.length);r.map(i=>parseInt(i)),r.sort((i,a)=>i-a),o.set(yt.messages._buildExtendedClipboardFlags(t,[]));let s=4;for(let i=0;i<r.length;i++)o[s]=n[r[i]]>>24,o[s+1]=n[r[i]]>>16,o[s+2]=n[r[i]]>>8,o[s+3]=n[r[i]]>>0,s+=4,o[3]|=1<<r[i];yt.messages.clientCutText(e,o,!0)},clientCutText(e,t,n=!1){e.sQpush8(6),e.sQpush8(0),e.sQpush8(0),e.sQpush8(0);let r;n?r=av(-t.length):r=t.length,e.sQpush32(r),e.sQpushBytes(t),e.flush()},setDesktopSize(e,t,n,r,o){e.sQpush8(251),e.sQpush8(0),e.sQpush16(t),e.sQpush16(n),e.sQpush8(1),e.sQpush8(0),e.sQpush32(r),e.sQpush16(0),e.sQpush16(0),e.sQpush16(t),e.sQpush16(n),e.sQpush32(o),e.flush()},clientFence(e,t,n){e.sQpush8(248),e.sQpush8(0),e.sQpush8(0),e.sQpush8(0),e.sQpush32(t),e.sQpush8(n.length),e.sQpushString(n),e.flush()},enableContinuousUpdates(e,t,n,r,o,s){e.sQpush8(150),e.sQpush8(t),e.sQpush16(n),e.sQpush16(r),e.sQpush16(o),e.sQpush16(s),e.flush()},pixelFormat(e,t,n){let r;t>16?r=32:t>8?r=16:r=8;let o=Math.floor(t/3);e.sQpush8(0),e.sQpush8(0),e.sQpush8(0),e.sQpush8(0),e.sQpush8(r),e.sQpush8(t),e.sQpush8(0),e.sQpush8(n?1:0),e.sQpush16((1<<o)-1),e.sQpush16((1<<o)-1),e.sQpush16((1<<o)-1),e.sQpush8(o*0),e.sQpush8(o*1),e.sQpush8(o*2),e.sQpush8(0),e.sQpush8(0),e.sQpush8(0),e.flush()},clientEncodings(e,t){e.sQpush8(2),e.sQpush8(0),e.sQpush16(t.length);for(let n=0;n<t.length;n++)e.sQpush32(t[n]);e.flush()},fbUpdateRequest(e,t,n,r,o,s){typeof n>"u"&&(n=0),typeof r>"u"&&(r=0),e.sQpush8(3),e.sQpush8(t?1:0),e.sQpush16(n),e.sQpush16(r),e.sQpush16(o),e.sQpush16(s),e.flush()},xvpOp(e,t,n){e.sQpush8(250),e.sQpush8(0),e.sQpush8(t),e.sQpush8(n),e.flush()}};yt.cursors={none:{rgbaPixels:new Uint8Array,w:0,h:0,hotx:0,hoty:0},dot:{rgbaPixels:new Uint8Array([255,255,255,255,0,0,0,255,255,255,255,255,0,0,0,255,0,0,0,0,0,0,0,255,255,255,255,255,0,0,0,255,255,255,255,255]),w:3,h:3,hotx:1,hoty:1}};var At="home",_h="desktop",vh="notifications",ik="main-chat",wh="notifications";var h$=/^thr_[a-z0-9]+$/;function kh(e){return e.experimental_messageSeq}function m$(e,t){let n=Math.floor(Math.max(0,t-e)/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Sh(e,t){let n=e.replies===1?"1 reply":`${e.replies} replies`;return e.replies===0?"Thread started":`${n} \xB7 last ${m$(e.lastActivityAt,t)}`}var hn={kind:"main"},ak="thread",lk="full";function Mc(e){if(e.kind==="main")return"";let t=`${ak}/${e.threadId}`;return e.kind==="full"?`${t}/${lk}`:t}function ck(e){let[t,n,r,...o]=e.split("/");return t!==ak||n===void 0||!h$.test(n)||o.length>0?hn:r===void 0?{kind:"beside",threadId:n}:r===lk?{kind:"full",threadId:n}:hn}function uk(e,t){return Mc(e)===Mc(t)}function Eh(e){return e.kind==="main"?null:e.threadId}function Dc(e){return e.kind==="full"?{kind:"beside",threadId:e.threadId}:hn}function dk(e,t,n){return{kind:n||e.kind==="full"?"full":"beside",threadId:t}}function pk(e,t){return e.kind==="main"?"open":t.kind==="main"?"close":e.threadId!==t.threadId&&e.kind===t.kind?"swap":t.kind==="full"?"full":"unfull"}var sk={needs:0,working:1,waiting:1,starting:1,finished:2},Fc={needs:"Needs you",working:"Working",waiting:"Waiting",starting:"Starting",finished:"Finished"};function On(e,t){return t.has(e.threadId)?"needs":e.running?"working":e.waiting?"waiting":e.starting?"starting":"finished"}function fk(e,t){return e.filter(n=>!n.done).sort((n,r)=>sk[On(n,t)]-sk[On(r,t)]||r.lastActivityAt-n.lastActivityAt)}function hk(e,t,n){let r=new Set(t.map(c=>c.threadId)),o=new Set([...r].filter(c=>n.has(c))),s={open:r,needs:o};if(e===null)return{clearOverride:!1,seen:s};let i=[...r].some(c=>!e.open.has(c)),a=[...o].some(c=>!e.needs.has(c));return{clearOverride:e.open.size>0&&r.size===0||i||a,seen:s}}function mk(e,t,n){let r=[null,...t],o=Math.max(0,r.indexOf(Eh(e)));return r[(o+n+r.length)%r.length]??null}var g$=e=>e.replace(/^Thread: /,"");function la(e,t){let n=t.get(e.threadId);return(n===void 0?"":g$(n))||e.rootPreview.trim()||"A message"}function gk(e,t){let n=e.outcomes.at(-1),o=(!e.running&&e.waiting?e.waiting:!e.running&&e.starting?"starting":null)??(n?`\u21B3 ${n.text}`:Sh(e,t));return e.project?`${e.project.split("/").at(-1)} \xB7 ${o}`:o}var zc=null;function xk(e){return zc=e,()=>{zc===e&&(zc=null)}}function Yo(){return zc}var bk="moonlet-chat-motion",mn="data-moonlet-vt",Xc="data-moonlet-vt-device";var yk="cubic-bezier(.2, .8, .2, 1)",sr="var(--moonlet-lamp, oklch(0.72 0.14 78))",x$=`
4
+ `),this.dispatchEvent(new CustomEvent("clipboard",{detail:{text:u}}))}}else return this._fail("Unexpected action in extended clipboard message: "+o)}return!0}_handleServerFenceMsg(){if(this._sock.rQwait("ServerFence header",8,1))return!1;this._sock.rQskipBytes(3);let t=this._sock.rQshift32(),n=this._sock.rQshift8();if(this._sock.rQwait("ServerFence payload",n,9))return!1;n>64&&(qe("Bad payload length ("+n+") in fence response"),n=64);let r=this._sock.rQshiftStr(n);return this._supportsFence=!0,t&1<<31?(t&=3,e.messages.clientFence(this._sock,t,r),!0):this._fail("Unexpected fence response")}_handleXvpMsg(){if(this._sock.rQwait("XVP version and message",3,1))return!1;this._sock.rQskipBytes(1);let t=this._sock.rQshift8(),n=this._sock.rQshift8();switch(n){case 0:Me("XVP operation failed");break;case 1:this._rfbXvpVer=t,Qe("XVP extensions enabled (version "+this._rfbXvpVer+")"),this._setCapability("power",!0);break;default:this._fail("Illegal server XVP message (msg: "+n+")");break}return!0}_normalMsg(){let t;this._FBU.rects>0?t=0:t=this._sock.rQshift8();let n,r;switch(t){case 0:return r=this._framebufferUpdate(),r&&!this._enabledContinuousUpdates&&e.messages.fbUpdateRequest(this._sock,!0,0,0,this._fbWidth,this._fbHeight),r;case 1:return this._handleSetColourMapMsg();case 2:return de("Bell"),this.dispatchEvent(new CustomEvent("bell",{detail:{}})),!0;case 3:return this._handleServerCutText();case 150:return n=!this._supportsContinuousUpdates,this._supportsContinuousUpdates=!0,this._enabledContinuousUpdates=!1,n&&(this._enabledContinuousUpdates=!0,this._updateContinuousUpdates(),Qe("Enabling continuous updates.")),!0;case 248:return this._handleServerFenceMsg();case 250:return this._handleXvpMsg();default:return this._fail("Unexpected server message (type "+t+")"),de("sock.rQpeekBytes(30): "+this._sock.rQpeekBytes(30)),!0}}_framebufferUpdate(){if(this._FBU.rects===0){if(this._sock.rQwait("FBU header",3,1))return!1;if(this._sock.rQskipBytes(1),this._FBU.rects=this._sock.rQshift16(),this._display.pending())return this._flushing=!0,this._display.flush().then(()=>{this._flushing=!1,this._sock.rQwait("message",1)||this._handleMessage()}),!1}for(;this._FBU.rects>0;){if(this._FBU.encoding===null){if(this._sock.rQwait("rect header",12))return!1;this._FBU.x=this._sock.rQshift16(),this._FBU.y=this._sock.rQshift16(),this._FBU.width=this._sock.rQshift16(),this._FBU.height=this._sock.rQshift16(),this._FBU.encoding=this._sock.rQshift32(),this._FBU.encoding>>=0}if(!this._handleRect())return!1;this._FBU.rects--,this._FBU.encoding=null}return this._display.flip(),!0}_handleRect(){switch(this._FBU.encoding){case ge.pseudoEncodingLastRect:return this._FBU.rects=1,!0;case ge.pseudoEncodingVMwareCursor:return this._handleVMwareCursor();case ge.pseudoEncodingCursor:return this._handleCursor();case ge.pseudoEncodingQEMUExtendedKeyEvent:return this._qemuExtKeyEventSupported=!0,!0;case ge.pseudoEncodingDesktopName:return this._handleDesktopName();case ge.pseudoEncodingDesktopSize:return this._resize(this._FBU.width,this._FBU.height),!0;case ge.pseudoEncodingExtendedDesktopSize:return this._handleExtendedDesktopSize();case ge.pseudoEncodingExtendedMouseButtons:return this._extendedPointerEventSupported=!0,!0;case ge.pseudoEncodingQEMULedEvent:return this._handleLedEvent();default:return this._handleDataRect()}}_handleVMwareCursor(){let t=this._FBU.x,n=this._FBU.y,r=this._FBU.width,o=this._FBU.height;if(this._sock.rQwait("VMware cursor encoding",1))return!1;let s=this._sock.rQshift8();this._sock.rQshift8();let i,a=4;if(s==0){if(i=new Array(r*o*a),this._sock.rQwait("VMware cursor classic encoding",r*o*a*2,2))return!1;let c=new Array(r*o);for(let p=0;p<r*o;p++)c[p]=this._sock.rQshift32();let d=new Array(r*o);for(let p=0;p<r*o;p++)d[p]=this._sock.rQshift32();for(let p=0;p<r*o;p++)if(c[p]==0){let f=d[p],h=f>>8&255,g=f>>16&255,x=f>>24&255;i[p*a]=h,i[p*a+1]=g,i[p*a+2]=x,i[p*a+3]=255}else(c[p]&-256)==-256?d[p]==0?(i[p*a]=0,i[p*a+1]=0,i[p*a+2]=0,i[p*a+3]=0):(d[p]&-256,i[p*a]=0,i[p*a+1]=0,i[p*a+2]=0,i[p*a+3]=255):(i[p*a]=0,i[p*a+1]=0,i[p*a+2]=0,i[p*a+3]=255)}else if(s==1){if(this._sock.rQwait("VMware cursor alpha encoding",r*o*4,2))return!1;i=new Array(r*o*a);for(let u=0;u<r*o;u++){let c=this._sock.rQshift32();i[u*4]=c>>24&255,i[u*4+1]=c>>16&255,i[u*4+2]=c>>8&255,i[u*4+3]=c&255}}else return qe("The given cursor type is not supported: "+s+" given."),!1;return this._updateCursor(i,t,n,r,o),!0}_handleCursor(){let t=this._FBU.x,n=this._FBU.y,r=this._FBU.width,o=this._FBU.height,s=r*o*4,i=Math.ceil(r/8)*o,a=s+i;if(this._sock.rQwait("cursor encoding",a))return!1;let u=this._sock.rQshiftBytes(s),c=this._sock.rQshiftBytes(i),d=new Uint8Array(r*o*4),p=0;for(let f=0;f<o;f++)for(let h=0;h<r;h++){let g=f*Math.ceil(r/8)+Math.floor(h/8),x=c[g]<<h%8&128?255:0;d[p]=u[p+2],d[p+1]=u[p+1],d[p+2]=u[p],d[p+3]=x,p+=4}return this._updateCursor(d,t,n,r,o),!0}_handleDesktopName(){if(this._sock.rQwait("DesktopName",4))return!1;let t=this._sock.rQshift32();if(this._sock.rQwait("DesktopName",t,4))return!1;let n=this._sock.rQshiftStr(t);return n=ac(n,!0),this._setDesktopName(n),!0}_handleLedEvent(){if(this._sock.rQwait("LED status",1))return!1;let t=this._sock.rQshift8(),n=!!(t&2),r=!!(t&4);return this._remoteCapsLock=r,this._remoteNumLock=n,!0}_handleExtendedDesktopSize(){if(this._sock.rQwait("ExtendedDesktopSize",4))return!1;let t=this._sock.rQpeek8(),n=4+t*16;if(this._sock.rQwait("ExtendedDesktopSize",n))return!1;let r=!this._supportsSetDesktopSize;this._supportsSetDesktopSize=!0,this._sock.rQskipBytes(1),this._sock.rQskipBytes(3);for(let o=0;o<t;o+=1)o===0?(this._screenID=this._sock.rQshift32(),this._sock.rQskipBytes(2),this._sock.rQskipBytes(2),this._sock.rQskipBytes(2),this._sock.rQskipBytes(2),this._screenFlags=this._sock.rQshift32()):this._sock.rQskipBytes(16);if(this._FBU.x===1&&(this._pendingRemoteResize=!1),this._FBU.x===1&&this._FBU.y!==0){let o="";switch(this._FBU.y){case 1:o="Resize is administratively prohibited";break;case 2:o="Out of resources";break;case 3:o="Invalid screen layout";break;default:o="Unknown reason";break}qe("Server did not accept the resize request: "+o)}else this._resize(this._FBU.width,this._FBU.height);return r&&this._requestRemoteResize(),this._FBU.x===1&&this._FBU.y===0&&this._requestRemoteResize(),!0}_handleDataRect(){let t=this._decoders[this._FBU.encoding];if(!t)return this._fail("Unsupported encoding (encoding: "+this._FBU.encoding+")"),!1;try{return t.decodeRect(this._FBU.x,this._FBU.y,this._FBU.width,this._FBU.height,this._sock,this._display,this._fbDepth)}catch(n){return this._fail("Error decoding rect: "+n),!1}}_updateContinuousUpdates(){this._enabledContinuousUpdates&&e.messages.enableContinuousUpdates(this._sock,!0,0,0,this._fbWidth,this._fbHeight)}_resize(t,n){this._fbWidth=t,this._fbHeight=n,this._display.resize(this._fbWidth,this._fbHeight),this._updateClip(),this._updateScale(),this._updateContinuousUpdates(),this._saveExpectedClientSize()}_xvpOp(t,n){this._rfbXvpVer<t||(Qe("Sending XVP operation "+n+" (version "+t+")"),e.messages.xvpOp(this._sock,t,n))}_updateCursor(t,n,r,o,s){this._cursorImage={rgbaPixels:t,hotx:n,hoty:r,w:o,h:s},this._refreshCursor()}_shouldShowDotCursor(){if(!this._showDotCursor)return!1;for(let t=3;t<this._cursorImage.rgbaPixels.length;t+=4)if(this._cursorImage.rgbaPixels[t])return!1;return!0}_refreshCursor(){if(this._rfbConnectionState!=="connecting"&&this._rfbConnectionState!=="connected")return;let t=this._shouldShowDotCursor()?e.cursors.dot:this._cursorImage;this._cursor.change(t.rgbaPixels,t.hotx,t.hoty,t.w,t.h)}static genDES(t,n){let r=t.split("").map(s=>s.charCodeAt(0)),o=Xe.importKey("raw",r,{name:"DES-ECB"},!1,["encrypt"]);return Xe.encrypt({name:"DES-ECB"},o,n)}};yt.messages={keyEvent(e,t,n){e.sQpush8(4),e.sQpush8(n),e.sQpush16(0),e.sQpush32(t),e.flush()},QEMUExtendedKeyEvent(e,t,n,r){function o(i){let a=r>>8,u=r&255;return a===224&&u<127?u|128:i}e.sQpush8(255),e.sQpush8(0),e.sQpush16(n),e.sQpush32(t);let s=o(r);e.sQpush32(s),e.flush()},pointerEvent(e,t,n,r){e.sQpush8(5),r=r&127,e.sQpush8(r),e.sQpush16(t),e.sQpush16(n),e.flush()},extendedPointerEvent(e,t,n,r){e.sQpush8(5);let o=r>>7&255;if(o&252)throw new Error("Invalid mouse button mask: "+r);let s=r&127;s|=128,e.sQpush8(s),e.sQpush16(t),e.sQpush16(n),e.sQpush8(o),e.flush()},_buildExtendedClipboardFlags(e,t){let n=new Uint8Array(4),r=0,o=0;for(let s=0;s<e.length;s++)o|=e[s];for(let s=0;s<t.length;s++)r|=t[s];return n[0]=o>>24,n[1]=0,n[2]=0,n[3]=r,n},extendedClipboardProvide(e,t,n){let r=new Vi,o=[];for(let a=0;a<t.length;a++){if(t[a]!=hn)throw new Error("Unsupported extended clipboard format for Provide message.");n[a]=n[a].replace(/\r\n|\r|\n/gm,`\r
5
+ `);let u=Gt(n[a]+"\0");o.push(u.length>>24&255,u.length>>16&255,u.length>>8&255,u.length&255);for(let c=0;c<u.length;c++)o.push(u.charCodeAt(c))}let s=r.deflate(new Uint8Array(o)),i=new Uint8Array(4+s.length);i.set(yt.messages._buildExtendedClipboardFlags([Mc],t)),i.set(s,4),yt.messages.clientCutText(e,i,!0)},extendedClipboardNotify(e,t){let n=yt.messages._buildExtendedClipboardFlags([la],t);yt.messages.clientCutText(e,n,!0)},extendedClipboardRequest(e,t){let n=yt.messages._buildExtendedClipboardFlags([Lc],t);yt.messages.clientCutText(e,n,!0)},extendedClipboardCaps(e,t,n){let r=Object.keys(n),o=new Uint8Array(4+4*r.length);r.map(i=>parseInt(i)),r.sort((i,a)=>i-a),o.set(yt.messages._buildExtendedClipboardFlags(t,[]));let s=4;for(let i=0;i<r.length;i++)o[s]=n[r[i]]>>24,o[s+1]=n[r[i]]>>16,o[s+2]=n[r[i]]>>8,o[s+3]=n[r[i]]>>0,s+=4,o[3]|=1<<r[i];yt.messages.clientCutText(e,o,!0)},clientCutText(e,t,n=!1){e.sQpush8(6),e.sQpush8(0),e.sQpush8(0),e.sQpush8(0);let r;n?r=cv(-t.length):r=t.length,e.sQpush32(r),e.sQpushBytes(t),e.flush()},setDesktopSize(e,t,n,r,o){e.sQpush8(251),e.sQpush8(0),e.sQpush16(t),e.sQpush16(n),e.sQpush8(1),e.sQpush8(0),e.sQpush32(r),e.sQpush16(0),e.sQpush16(0),e.sQpush16(t),e.sQpush16(n),e.sQpush32(o),e.flush()},clientFence(e,t,n){e.sQpush8(248),e.sQpush8(0),e.sQpush8(0),e.sQpush8(0),e.sQpush32(t),e.sQpush8(n.length),e.sQpushString(n),e.flush()},enableContinuousUpdates(e,t,n,r,o,s){e.sQpush8(150),e.sQpush8(t),e.sQpush16(n),e.sQpush16(r),e.sQpush16(o),e.sQpush16(s),e.flush()},pixelFormat(e,t,n){let r;t>16?r=32:t>8?r=16:r=8;let o=Math.floor(t/3);e.sQpush8(0),e.sQpush8(0),e.sQpush8(0),e.sQpush8(0),e.sQpush8(r),e.sQpush8(t),e.sQpush8(0),e.sQpush8(n?1:0),e.sQpush16((1<<o)-1),e.sQpush16((1<<o)-1),e.sQpush16((1<<o)-1),e.sQpush8(o*0),e.sQpush8(o*1),e.sQpush8(o*2),e.sQpush8(0),e.sQpush8(0),e.sQpush8(0),e.flush()},clientEncodings(e,t){e.sQpush8(2),e.sQpush8(0),e.sQpush16(t.length);for(let n=0;n<t.length;n++)e.sQpush32(t[n]);e.flush()},fbUpdateRequest(e,t,n,r,o,s){typeof n>"u"&&(n=0),typeof r>"u"&&(r=0),e.sQpush8(3),e.sQpush8(t?1:0),e.sQpush16(n),e.sQpush16(r),e.sQpush16(o),e.sQpush16(s),e.flush()},xvpOp(e,t,n){e.sQpush8(250),e.sQpush8(0),e.sQpush8(t),e.sQpush8(n),e.flush()}};yt.cursors={none:{rgbaPixels:new Uint8Array,w:0,h:0,hotx:0,hoty:0},dot:{rgbaPixels:new Uint8Array([255,255,255,255,0,0,0,255,255,255,255,255,0,0,0,255,0,0,0,0,0,0,0,255,255,255,255,255,0,0,0,255,255,255,255,255]),w:3,h:3,hotx:1,hoty:1}};var At="home",wh="desktop",kh="notifications",lk="main-chat",Sh="notifications";var b$=/^thr_[a-z0-9]+$/;function Eh(e){return e.experimental_messageSeq}function y$(e,t){let n=Math.floor(Math.max(0,t-e)/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Nh(e,t){let n=e.replies===1?"1 reply":`${e.replies} replies`;return e.replies===0?"Thread started":`${n} \xB7 last ${y$(e.lastActivityAt,t)}`}var mn={kind:"main"},ck="thread",uk="full";function Dc(e){if(e.kind==="main")return"";let t=`${ck}/${e.threadId}`;return e.kind==="full"?`${t}/${uk}`:t}function dk(e){let[t,n,r,...o]=e.split("/");return t!==ck||n===void 0||!b$.test(n)||o.length>0?mn:r===void 0?{kind:"beside",threadId:n}:r===uk?{kind:"full",threadId:n}:mn}function pk(e,t){return Dc(e)===Dc(t)}function Ah(e){return e.kind==="main"?null:e.threadId}function Fc(e){return e.kind==="full"?{kind:"beside",threadId:e.threadId}:mn}function fk(e,t,n){return{kind:n||e.kind==="full"?"full":"beside",threadId:t}}function hk(e,t){return e.kind==="main"?"open":t.kind==="main"?"close":e.threadId!==t.threadId&&e.kind===t.kind?"swap":t.kind==="full"?"full":"unfull"}var ak={needs:0,working:1,waiting:1,starting:1,finished:2},zc={needs:"Needs you",working:"Working",waiting:"Waiting",starting:"Starting",finished:"Finished"};function Ln(e,t){return t.has(e.threadId)?"needs":e.running?"working":e.waiting?"waiting":e.starting?"starting":"finished"}function mk(e,t){return e.filter(n=>!n.done).sort((n,r)=>ak[Ln(n,t)]-ak[Ln(r,t)]||r.lastActivityAt-n.lastActivityAt)}function gk(e,t,n){let r=new Set(t.map(c=>c.threadId)),o=new Set([...r].filter(c=>n.has(c))),s={open:r,needs:o};if(e===null)return{clearOverride:!1,seen:s};let i=[...r].some(c=>!e.open.has(c)),a=[...o].some(c=>!e.needs.has(c));return{clearOverride:e.open.size>0&&r.size===0||i||a,seen:s}}function xk(e,t,n){let r=[null,...t],o=Math.max(0,r.indexOf(Ah(e)));return r[(o+n+r.length)%r.length]??null}var _$=e=>e.replace(/^Thread: /,"");function ca(e,t){let n=t.get(e.threadId);return(n===void 0?"":_$(n))||e.rootPreview.trim()||"A message"}function bk(e,t){let n=e.outcomes.at(-1),o=(!e.running&&e.waiting?e.waiting:!e.running&&e.starting?"starting":null)??(n?`\u21B3 ${n.text}`:Nh(e,t));return e.project?`${e.project.split("/").at(-1)} \xB7 ${o}`:o}var Kc=null;function yk(e){return Kc=e,()=>{Kc===e&&(Kc=null)}}function qo(){return Kc}var _k="moonlet-chat-motion",gn="data-moonlet-vt",Bc="data-moonlet-vt-device";var vk="cubic-bezier(.2, .8, .2, 1)",ir="var(--moonlet-lamp, oklch(0.72 0.14 78))",v$=`
6
6
  [data-moonlet-pane="rail"] { view-transition-name: moonlet-rail; }
7
7
  [data-moonlet-pane="main"] { view-transition-name: moonlet-main; }
8
8
  [data-moonlet-pane="thread"] { view-transition-name: moonlet-thread; }
9
9
  ::view-transition-group(moonlet-rail), ::view-transition-group(moonlet-main), ::view-transition-group(moonlet-thread) {
10
- overflow: clip; animation-duration: 210ms; animation-timing-function: ${yk};
10
+ overflow: clip; animation-duration: 210ms; animation-timing-function: ${vk};
11
11
  }
12
12
  ::view-transition-old(moonlet-rail), ::view-transition-new(moonlet-rail),
13
13
  ::view-transition-old(moonlet-main), ::view-transition-new(moonlet-main),
14
14
  ::view-transition-old(moonlet-thread), ::view-transition-new(moonlet-thread) {
15
- height: 100%; object-fit: none; object-position: left top; animation-duration: 210ms; animation-timing-function: ${yk};
15
+ height: 100%; object-fit: none; object-position: left top; animation-duration: 210ms; animation-timing-function: ${vk};
16
16
  }
17
- html[${mn}="open"]::view-transition-new(moonlet-thread) { animation-name: moonlet-in-right; }
18
- html[${mn}="close"]::view-transition-old(moonlet-thread) { animation-name: moonlet-out-right; }
19
- html[${mn}="full"]::view-transition-old(moonlet-main) { animation-name: moonlet-out-left; }
20
- html[${mn}="unfull"]::view-transition-new(moonlet-main) { animation-name: moonlet-in-left; }
21
- html[${mn}="swap"]::view-transition-old(moonlet-thread) { animation-name: moonlet-fade-out; animation-duration: 120ms; }
22
- html[${mn}="swap"]::view-transition-new(moonlet-thread) { animation-name: moonlet-swap-in; }
17
+ html[${gn}="open"]::view-transition-new(moonlet-thread) { animation-name: moonlet-in-right; }
18
+ html[${gn}="close"]::view-transition-old(moonlet-thread) { animation-name: moonlet-out-right; }
19
+ html[${gn}="full"]::view-transition-old(moonlet-main) { animation-name: moonlet-out-left; }
20
+ html[${gn}="unfull"]::view-transition-new(moonlet-main) { animation-name: moonlet-in-left; }
21
+ html[${gn}="swap"]::view-transition-old(moonlet-thread) { animation-name: moonlet-fade-out; animation-duration: 120ms; }
22
+ html[${gn}="swap"]::view-transition-new(moonlet-thread) { animation-name: moonlet-swap-in; }
23
23
  ::view-transition-new(moonlet-rail):only-child { animation-name: moonlet-in-left; }
24
24
  ::view-transition-old(moonlet-rail):only-child { animation-name: moonlet-out-left; }
25
- html[${Xc}="phone"][${mn}="open"]::view-transition-new(moonlet-thread) { animation-name: moonlet-in-up; }
26
- html[${Xc}="phone"][${mn}="close"]::view-transition-old(moonlet-thread) { animation-name: moonlet-out-down; }
25
+ html[${Bc}="phone"][${gn}="open"]::view-transition-new(moonlet-thread) { animation-name: moonlet-in-up; }
26
+ html[${Bc}="phone"][${gn}="close"]::view-transition-old(moonlet-thread) { animation-name: moonlet-out-down; }
27
27
  @keyframes moonlet-in-right { from { transform: translateX(36px); opacity: 0; } }
28
28
  @keyframes moonlet-out-right { to { transform: translateX(36px); opacity: 0; } }
29
29
  @keyframes moonlet-in-left { from { transform: translateX(-28px); opacity: 0; } }
@@ -32,45 +32,45 @@ html[${Xc}="phone"][${mn}="close"]::view-transition-old(moonlet-thread) { animat
32
32
  @keyframes moonlet-out-down { to { transform: translateY(60px); opacity: 0; } }
33
33
  @keyframes moonlet-fade-out { to { opacity: 0; } }
34
34
  @keyframes moonlet-swap-in { from { transform: translateY(8px); opacity: 0; } }
35
- `;function _k(e){if(e.getElementById(bk))return()=>{};let t=e.createElement("style");return t.id=bk,t.textContent=x$,e.head.append(t),()=>t.remove()}var Kc=null;function vk(e,t,n,r){let o=null,s=()=>o??=r(),i=e.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!0;if(!e.startViewTransition||i||e.visibilityState!=="visible"){s();return}Kc?.skipTransition();let a=e.documentElement;a.setAttribute(mn,t),a.setAttribute(Xc,n?"phone":"desktop");let u=e.startViewTransition(s);Kc=u,u.updateCallbackDone.catch(()=>{s()}),u.ready.catch(()=>{}),u.finished.catch(()=>{}).finally(()=>{Kc===u&&(Kc=null,a.removeAttribute(mn),a.removeAttribute(Xc))})}function Bc({orbitThread:e,threadId:t,done:n}){let r=J(),[o,s]=_(!1),[i,a]=_(null),u=async()=>{s(!0),a(null);try{await r.call("threads.done",{orbitThread:e,threadId:t})}catch(c){a(c instanceof Error?c.message:"Couldn't save Done. Try again.")}finally{s(!1)}};return m("div",{className:"flex shrink-0 flex-col items-end gap-1",children:[l("button",{type:"button",disabled:o||n,onClick:()=>{u()},"aria-label":"Mark as Done",className:"rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-state-hover hover:text-foreground disabled:opacity-50",children:o?"Saving\u2026":n?"\u2713 Done":"Done"}),i?l("span",{role:"alert",className:"max-w-48 text-xs text-destructive",children:i}):null]})}var Nh="moonlet-threads-list";function Ah({size:e=16}){return l("svg",{width:e,height:e,viewBox:"0 0 20 20","aria-hidden":"true",className:"shrink-0",children:l("circle",{cx:"10",cy:"10",r:"9",fill:sr})})}function Uc({mark:e,size:t=16}){return l("svg",{width:t,height:t,viewBox:"0 0 18 18","aria-hidden":"true","data-mark":e,className:"shrink-0",children:e==="needs"?m(he,{children:[l("circle",{cx:"9",cy:"9",r:"6.5",fill:"none",stroke:sr,strokeWidth:"2.3"}),l("circle",{cx:"9",cy:"9",r:"2.6",fill:sr})]}):e==="working"?m(he,{children:[l("circle",{cx:"9",cy:"9",r:"6.5",fill:"none",stroke:"var(--border)",strokeWidth:"2.3"}),l("g",{className:"origin-center animate-spin motion-reduce:animate-none [animation-duration:1.6s]",children:l("circle",{cx:"9",cy:"9",r:"6.5",fill:"none",stroke:sr,strokeWidth:"2.3",strokeDasharray:"12 41",strokeLinecap:"round"})})]}):e==="waiting"?l("path",{d:"M5.5 3h7M5.5 15h7M6.6 3c0 3.4 4.8 3.6 4.8 6s-4.8 2.6-4.8 6M11.4 3c0 3.4-4.8 3.6-4.8 6s4.8 2.6 4.8 6",fill:"none",stroke:sr,strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"}):e==="starting"?l("circle",{cx:"9",cy:"9",r:"6.5",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeDasharray:"2.6 2.6",className:"text-muted-foreground"}):m("g",{className:"text-muted-foreground",children:[l("circle",{cx:"9",cy:"9",r:"6.5",fill:"none",stroke:"currentColor",strokeWidth:"2"}),l("path",{d:"M6 9.2l2 2 4-4.4",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})]})})}var wk="flex w-full min-w-0 items-start gap-2.5 rounded-lg px-2.5 py-2 text-left text-sm text-foreground transition-colors hover:bg-state-hover aria-[current=true]:bg-state-active";function kk({orbit:e,listed:t,names:n,needsYou:r,unread:o,view:s,mainUnread:i,now:a,onMain:u,onThread:c}){let d=t.filter(h=>On(h,r)==="working").length,p=t.filter(h=>On(h,r)==="waiting").length,f=[d>0?`${d} working`:null,p>0?`${p} waiting`:null].filter(h=>h!==null).join(" \xB7 ");return l("nav",{id:Nh,"aria-label":"Threads","data-moonlet-pane":"rail",className:"flex min-h-0 min-w-0 flex-col overflow-hidden border-r border-border bg-sidebar",children:m("div",{className:"flex w-64 flex-1 flex-col gap-0.5 overflow-y-auto px-2 py-2.5",children:[m("button",{type:"button",onClick:u,"aria-current":s.kind!=="full",className:V(wk,"items-center"),children:[l(Ah,{size:18}),m("span",{className:"flex min-w-0 flex-1 flex-col",children:[l("span",{className:"truncate font-semibold",children:"Moonlet"}),l("span",{className:"truncate text-xs text-muted-foreground",children:"Main conversation"})]}),i?l("span",{className:"rounded-full px-1.5 text-xs font-semibold text-foreground",style:{background:sr},children:"New"}):null]}),m("div",{className:"flex items-baseline justify-between px-2.5 pb-1 pt-3 text-xs font-semibold text-muted-foreground",children:[l("span",{children:"Threads"}),f?l("span",{children:f}):null]}),t.map(h=>{let g=la(h,n),x=On(h,r),b=s.kind!=="main"&&s.threadId===h.threadId;return m("div",{className:"group relative min-w-0",children:[m("button",{type:"button",title:"Click to open, Shift-click for full screen",onClick:v=>c(h,v.shiftKey),"aria-current":b,className:V(wk,"pr-16"),children:[l("span",{className:"mt-0.5",children:l(Uc,{mark:x})}),m("span",{className:"flex min-w-0 flex-1 flex-col",children:[l("span",{className:V("truncate",o.has(h.threadId)?"font-bold":"font-medium"),children:g}),l("span",{className:"truncate text-xs text-muted-foreground",children:x==="needs"?Fc.needs:gk(h,a)})]}),b&&s.kind==="beside"?l("span",{className:"self-center text-xs text-muted-foreground",children:"beside"}):null]}),l("div",{className:"absolute right-1 top-1 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",children:l(Bc,{orbitThread:e,threadId:h.threadId,done:h.done})})]},h.threadId)})]})})}function Sk({listed:e,names:t,needsYou:n,view:r,onThread:o}){return e.length===0?null:l("nav",{"aria-label":"Threads",className:"flex shrink-0 gap-1.5 overflow-x-auto border-b border-border px-3 py-2 [scrollbar-width:none]",children:e.map(s=>{let i=On(s,n),a=r.kind!=="main"&&r.threadId===s.threadId;return m("button",{type:"button",onClick:()=>o(s,!1),"aria-current":a,className:V("inline-flex h-8 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border border-border bg-background pl-2 pr-3 text-sm aria-[current=true]:ring-1 aria-[current=true]:ring-foreground",i==="needs"&&"font-semibold"),style:i==="needs"?{borderColor:sr}:void 0,children:[l(Uc,{mark:i,size:14}),la(s,t),i==="needs"?" needs you":""]},s.threadId)})})}var ca=["display","visibility","opacity","content-visibility","all"],b$=e=>new Set(Array.from(e.matchAll(/var\(\s*(--[\w-]+)/g),t=>t[1]));function Ch(e){let t=new Set,n=new Map;for(let r=0;r<e.length;r++){let o=e.item(r);if(!ca.includes(o)&&!o.startsWith("--"))continue;let s=b$(e.getPropertyValue(o));if(o.startsWith("--"))s.size&&n.set(o,s);else for(let i of s)t.add(i)}return{roots:t,edges:n}}function Ek(e){return"style"in e?e.style:null}var Hc=class{nodes=new WeakMap;roots=new Map;references=new Map;edges=new Map;sheets=new Map;rules=new Map;animations=new Map;unknownSheets=new Set;unknown=!1;used=null;classes=null;classAttribute=!1;document;constructor(t){this.document=t,this.invalidateSheets(new Set(t.querySelectorAll('style,link[rel="stylesheet"]')))}count(t,n,r){let o=t.get(n)??0,s=o+r;s?t.set(n,s):t.delete(n),(!o||!s)&&(this.used=this.classes=null)}apply(t,n){for(let r of t.roots)this.count(this.roots,r,n),this.count(this.references,r,n);for(let[r,o]of t.edges){let s=this.edges.get(r);s||this.edges.set(r,s=new Map);for(let i of o)this.count(s,i,n),this.count(this.references,i,n);s.size||this.edges.delete(r)}}retain(t){for(let n of t){let r=this.nodes.get(n);if(r)r.users++;else{let o=Ch(Ek(n)??this.document.createElement("div").style);this.nodes.set(n,{users:1,value:o}),this.apply(o,1)}}}release(t){for(let n of t){let r=this.nodes.get(n);r&&!--r.users&&(this.apply(r.value,-1),this.nodes.delete(n))}t.clear()}parseSheet(t){let n={values:[],rules:[],animations:new Map,unknown:!1},r=new Set,o=(i,a)=>{for(let u of i){if("style"in u){let c=u.style;n.values.push(Ch(c));let d=Array.from({length:c.length},(p,f)=>c.item(f));if("selectorText"in u&&/\.|\[\s*class\b/.test(String(u.selectorText))&&n.rules.push({selector:String(u.selectorText),properties:d}),a)for(let p of d)n.animations.get(a).add(p)}if("styleSheet"in u&&u.styleSheet&&s(u.styleSheet),"cssRules"in u){let c="name"in u?String(u.name):a;c&&!n.animations.has(c)&&n.animations.set(c,new Set),o(u.cssRules,c)}}},s=i=>{r.has(i)||(r.add(i),o(i.cssRules))};try{"sheet"in t&&t.sheet?s(t.sheet):n.unknown=!0}catch{n.unknown=!0}return n}invalidateSheets(t){for(let r of t){let o=this.sheets.get(r),s=r.isConnected?this.parseSheet(r):null;for(let i of s?.values??[])this.apply(i,1);for(let i of o?.values??[])this.apply(i,-1);JSON.stringify(o?.rules??[])!==JSON.stringify(s?.rules??[])&&(this.classes=null),s?.rules.length?this.rules.set(r,s.rules):this.rules.delete(r),s?.animations.size?this.animations.set(r,s.animations):this.animations.delete(r),s?.unknown?this.unknownSheets.add(r):this.unknownSheets.delete(r),s?this.sheets.set(r,s):this.sheets.delete(r)}let n=!!this.unknownSheets.size;this.unknown!==n&&(this.classes=null),this.unknown=n,this.prepare()}prepare(){if(!this.used){this.used=new Set(this.roots.keys());for(let t of this.used)for(let n of this.edges.get(t)?.keys()??[])this.used.add(n)}if(!this.classes){this.classes=new Set,this.classAttribute=!1;for(let t of this.rules.values())for(let n of t)if(n.properties.some(r=>ca.includes(r)||this.used.has(r))){/\[\s*class\b/.test(n.selector)&&(this.classAttribute=!0);for(let r of n.selector.matchAll(/\.((?:\\(?:[0-9a-fA-F]{1,6}\s?|.)|[\w-])+)/g))this.classes.add(r[1].replace(/\\([0-9a-fA-F]{1,6})\s?|\\(.)/g,(o,s,i)=>{if(!s)return i;let a=Number.parseInt(s,16);return a>0&&a<=1114111&&!(a>=55296&&a<=57343)?String.fromCodePoint(a):"\uFFFD"}))}}}affects(t){let n=t.target,r=t.attributeName,o=n.getAttribute(r);if(t.oldValue===o)return!1;if(r!=="style"&&r!=="class")return!0;if(r==="class"){if(this.prepare(),this.unknown||this.classAttribute)return!0;let c=new Set((t.oldValue??"").split(/\s+/)),d=new Set((o??"").split(/\s+/));return[...c,...d].some(p=>c.has(p)!==d.has(p)&&this.classes.has(p))}let s=Ek(n);if(!s)return!1;let i=this.nodes.get(n);if(i){let c=Ch(s);this.apply(c,1),this.apply(i.value,-1),i.value=c}let a=this.document.createElement("div").style;if(a.cssText=t.oldValue??"",ca.some(c=>a.getPropertyValue(c)!==s.getPropertyValue(c)||a.getPropertyPriority(c)!==s.getPropertyPriority(c)))return!0;let u=new Set([...Array.from({length:a.length},(c,d)=>a.item(d)),...Array.from({length:s.length},(c,d)=>s.item(d))]);for(let c of u)if(!(!c.startsWith("--")||!this.references.has(c)&&!this.unknown)&&(a.getPropertyValue(c)!==s.getPropertyValue(c)||a.getPropertyPriority(c)!==s.getPropertyPriority(c))&&(this.prepare(),this.unknown||this.used.has(c)))return!0;return!1}property(t){return ca.includes(t)?!0:t.startsWith("--")?(this.prepare(),this.unknown||this.used.has(t)):!1}animation(t){if(this.prepare(),this.unknown)return!0;let n=!1;for(let r of this.animations.values()){let o=r.get(t);if(o&&(n=!0,[...o].some(s=>ca.includes(s)||this.used.has(s))))return!0}return!n}};var ma="data-orbit-chat",Ln="data-orbit-avatar-start",Tk="data-orbit-author",Jo="data-orbit-reply-column",y$="#thread-detail-timeline-panel",Vc=`:is(${y$}, [${ma}])`,qo='[data-timeline-row-list="top-level"] > [data-timeline-items]',ua="[data-timeline-row-id]",Th="[data-message-column]",da='style,link[rel="stylesheet"]';function es(e){return e?.size??0}function pa(e){return e?.boundaries??0}function ts(e){e.size=1+es(e.left)+es(e.right),e.boundaries=+(e.kind!=="skip")+pa(e.left)+pa(e.right),e.left&&(e.left.parent=e),e.right&&(e.right.parent=e)}function fa(e,t){return e?t?e.priority<t.priority?(e.right=fa(e.right,t),ts(e),e):(t.left=fa(e,t.left),ts(t),t):e:t}function ha(e,t){if(!e)return[null,null];if(es(e.left)>=t){let[o,s]=ha(e.left,t);return e.left=s,ts(e),e.parent=null,o&&(o.parent=null),[o,e]}let[n,r]=ha(e.right,t-es(e.left)-1);return e.right=n,ts(e),e.parent=null,r&&(r.parent=null),[e,r]}function Nk(e){let t=es(e.left);for(let n=e,r=e.parent;r;n=r,r=r.parent)r.right===n&&(t+=es(r.left)+1);return t}function gn(e){return e.nodeType===1}function _$(e,t){let n=e.ownerDocument.defaultView;if(!n)return!1;let r=o=>{let s=t.get(o);return s||(s=n.getComputedStyle(o),t.set(o,s)),s};if(["hidden","collapse"].includes(r(e).visibility))return!1;for(let o=e;o;o=o.parentElement){if(o.hasAttribute("hidden")||o.getAttribute("aria-hidden")==="true")return!1;let s=r(o);if(s.display==="none"||s.opacity==="0"||s.getPropertyValue("content-visibility")==="hidden"||o.parentElement?.localName==="details"&&!o.parentElement.hasAttribute("open")&&o.localName!=="summary")return!1}return!0}var Ak=()=>({rows:new Map,global:""});function Ck(e,t){try{if(!("sheet"in e)||!e.sheet)return null;let n=new Map,r=[],o=new Set,s=(a,u)=>{for(let c of a){if("styleSheet"in c&&c.styleSheet&&i(c.styleSheet,u+c.cssText),"cssRules"in c&&s(c.cssRules,u+c.cssText.slice(0,c.cssText.indexOf("{"))),!("style"in c))continue;let d=c.style,p=Array.from({length:d.length},(x,b)=>d.item(b)).filter(t);if(!p.length)continue;let f="selectorText"in c?String(c.selectorText):"",h=JSON.stringify([u,f,p.map(x=>[x,d.getPropertyValue(x),d.getPropertyPriority(x)])]),g=new Set;for(let x of f.split(",")){let b=x.match(/\[data-timeline-row-id\s*=\s*("(?:[^"\\]|\\.)*")\s*\]/);if(!b){g.clear();break}let v=JSON.parse(b[1]);if(typeof v!="string"){g.clear();break}g.add(v)}if(!g.size)r.push(h);else for(let x of g)n.set(x,(n.get(x)??"")+h)}},i=(a,u)=>{o.has(a)||(o.add(a),s(a.cssRules,u))};return i(e.sheet,JSON.stringify([e.getAttribute("media"),e.getAttribute("disabled")])),{rows:n,global:r.join(`
36
- `)}}catch{return null}}var Rh=class{entries=new Map;lists=new Set;ids=new Map;pendingChildren=new Set;dirty=new Set;pendingStyles=new Set;relocatedStyles=new Set;sheets=new Map;observers=[];cancel=null;structureDirty=!1;roots=new Map;sequence=0;visibility;scope;name;layoutChanged;constructor(t,n,r=()=>{}){let o=t.nodeType===9?t:t.ownerDocument;this.visibility=new Hc(o),this.scope=t,this.name=n,this.layoutChanged=r;for(let s of t.querySelectorAll(`${Vc} ${qo}`))this.addList(s);for(let s of o.querySelectorAll(da))this.sheets.set(s,Ck(s,i=>this.visibility.property(i)));this.flush()}addList(t){if(this.lists.has(t)||t.closest(ua)||this.scope.nodeType!==9&&t.closest(Vc)!==this.scope)return;this.lists.add(t),this.structureDirty=!0;let n=null;for(let r of t.children){let o=this.create(r,t);o.list=t,o.previous=n,o.next=null,n&&(n.next=o),this.entries.set(r,o),this.insert(o),this.dirty.add(o),n=o}}create(t,n){return{node:t,list:n,previous:null,next:null,kind:"skip",id:null,column:null,markedColumn:null,header:null,left:null,right:null,parent:null,size:1,boundaries:0,priority:Math.imul(++this.sequence,2654435761)>>>0,visibilityNodes:new Set}}insert(t){let[n,r]=ha(this.roots.get(t.list)??null,t.previous?Nk(t.previous)+1:0),o=fa(fa(n,t),r);o&&(o.parent=null),this.roots.set(t.list,o)}remove(t){let[n,r]=ha(this.roots.get(t.list)??null,Nk(t)),[,o]=ha(r,1),s=fa(n,o);s&&(s.parent=null),this.roots.set(t.list,s),t.left=t.right=t.parent=null,ts(t)}unindex(t){if(t.id===null)return;let n=this.ids.get(t.id);n?.delete(t),n?.size||this.ids.delete(t.id)}forget(t){this.entries.delete(t.node),this.visibility.release(t.visibilityNodes),this.unindex(t),t.node.removeAttribute(Ln),t.markedColumn?.removeAttribute(Jo),t.header?.remove()}read(t,n){let r=t.node.getAttribute("data-timeline-row-id");if(t.id!==r&&(this.unindex(t),t.id=r,r!==null)){let u=this.ids.get(r);u||this.ids.set(r,u=new Set),u.add(t)}let o=t.visibilityNodes,s=new Set;t.visibilityNodes=s,t.column=null,t.kind=t.node.hasAttribute("data-timeline-window-spacer")?"gap":"skip";let i=r?.includes(":assistant:")?"reply":r?.includes(":user")?"owner":null;if(i===null){this.visibility.release(o);return}for(let u of t.node.querySelectorAll(Th))if(u.closest(ua)===t.node){for(let c=u;c;c=c.parentElement)s.add(c);if(t.column??=u,_$(u,n)){t.column=u,t.kind=i;break}}let a=new Set;for(let u of s)o.delete(u)||a.add(u);this.visibility.release(o),this.visibility.retain(a)}boundary(t,n){let r=n==="previous"?"left":"right",o=n==="previous"?"right":"left",s=i=>{let a=i;for(;;)if(pa(a[o]))a=a[o];else{if(a.kind!=="skip")return a;a=a[r]}};if(pa(t[r]))return s(t[r]);for(let i=t,a=t.parent;a;i=a,a=a.parent)if(a[o]===i){if(a.kind!=="skip")return a;if(pa(a[r]))return s(a[r])}return null}render(t){let n=t.kind==="reply"&&this.boundary(t,"previous")?.kind!=="reply",r=n?t.column:null;if(t.node.hasAttribute(Ln)!==n&&t.node.toggleAttribute(Ln,n),t.markedColumn!==r&&(t.markedColumn?.removeAttribute(Jo),r?.setAttribute(Jo,""),t.markedColumn=r),t.header&&(t.header.parentElement!==r||!this.name)&&(t.header.remove(),t.header=null),!r||!this.name||t.header)return;let o=r.ownerDocument.createElement("div");o.setAttribute(Tk,""),o.className="mb-1 min-w-0 text-sm font-medium text-foreground",o.style.overflowWrap="anywhere",o.textContent=this.name,r.prepend(o),t.header=o}flush=()=>{this.cancel=null;let t=new Set;for(let s of this.lists)if(!this.scope.contains(s)||!s.matches(qo)){this.lists.delete(s),this.roots.delete(s);for(let i of this.entries.values())i.list===s&&this.forget(i);this.layoutChanged()}let n=new Map;for(let s of this.pendingChildren){let i=this.entries.get(s);if(i){if(i.kind!=="skip"){let a=this.boundary(i,"next");a&&t.add(a)}this.remove(i),i.previous&&(i.previous.next=i.next),i.next&&(i.next.previous=i.previous),!s.parentElement||!this.lists.has(s.parentElement)?this.forget(i):(n.set(s,i),this.entries.delete(s))}}for(let s of this.pendingChildren){let i=s.parentElement;if(!i||!this.lists.has(i))continue;let a=n.get(s);a||(a=this.create(s,i)),this.entries.set(s,a),a.list=i;let u=s.previousElementSibling;for(;u&&!this.entries.has(u);)u=u.previousElementSibling;let c=s.nextElementSibling;for(;c&&!this.entries.has(c);)c=c.nextElementSibling;a.previous=u?this.entries.get(u):null,a.next=c?this.entries.get(c):null,a.previous&&(a.previous.next=a),a.next&&(a.next.previous=a),this.insert(a),this.dirty.add(a)}this.pendingChildren.clear(),this.pendingStyles.size&&this.visibility.invalidateSheets(this.pendingStyles);for(let s of this.pendingStyles){let i=this.sheets.has(s)?this.sheets.get(s):Ak(),a=s.isConnected?Ck(s,c=>this.visibility.property(c)):Ak();s.isConnected?this.sheets.set(s,a):this.sheets.delete(s);let u=this.relocatedStyles.has(s);if(i===null||a===null||i.global!==a.global||u&&a.global!=="")for(let c of this.entries.values())this.dirty.add(c);else for(let c of new Set([...i.rows.keys(),...a.rows.keys()]))if(u||i.rows.get(c)!==a.rows.get(c))for(let d of this.ids.get(c)??[])this.dirty.add(d)}this.pendingStyles.clear(),this.relocatedStyles.clear();let r=new Map,o=[];for(let s of this.dirty){if(!this.entries.has(s.node))continue;let i=s.kind;this.read(s,r);for(let a=s;a;a=a.parent)ts(a);t.add(s),(i!=="skip"||s.kind!=="skip")&&o.push(s)}this.dirty.clear();for(let s of o){let i=this.boundary(s,"next");i&&t.add(i)}for(let s of t)this.entries.has(s.node)&&this.render(s);this.structureDirty&&(this.structureDirty=!1,this.layoutChanged())};schedule(){if(this.cancel)return;let n=(this.scope.nodeType===9?this.scope:this.scope.ownerDocument).defaultView;if(n?.requestAnimationFrame){let r=n.requestAnimationFrame(this.flush);this.cancel=()=>n.cancelAnimationFrame(r)}else{let r=setTimeout(this.flush,16);this.cancel=()=>clearTimeout(r)}}styles(t,n){let r=gn(t.target)?t.target:t.target.parentElement;r?.matches(da)&&r!==n&&this.pendingStyles.add(r);for(let o of[...t.addedNodes,...t.removedNodes])if(gn(o)&&(o.matches(da)&&o!==n&&(this.pendingStyles.add(o),o.isConnected&&this.sheets.has(o)&&this.relocatedStyles.add(o)),o.firstElementChild))for(let s of o.querySelectorAll(da))s!==n&&(this.pendingStyles.add(s),s.isConnected&&this.sheets.has(s)&&this.relocatedStyles.add(s))}receive=(t,n)=>{for(let r of t){if(this.styles(r,n),r.type==="characterData"||!gn(r.target)||!this.scope.contains(r.target))continue;let o=r.target;if(r.type==="attributes"&&!this.visibility.affects(r))continue;let s=this.entries.get(o)??this.entries.get(o.closest(ua));if(r.type==="attributes")if(s)(o===s.node||o===s.column||o.contains(s.column)||r.attributeName==="data-message-column")&&this.dirty.add(s);else for(let i of o.querySelectorAll(ua)){let a=this.entries.get(i);a&&this.dirty.add(a)}else if(this.lists.has(o))for(let i of[...r.addedNodes,...r.removedNodes])gn(i)&&this.pendingChildren.add(i);else if(!s?.column?.contains(o)){if(s)for(let i of[...r.addedNodes,...r.removedNodes])gn(i)&&(i.contains(s.column)||i.matches(Th)||i.firstElementChild&&i.querySelector(Th))&&this.dirty.add(s);for(let i of r.removedNodes)if(gn(i))for(let a of this.lists)i.contains(a)&&(this.structureDirty=!0);for(let i of r.addedNodes)if(gn(i)&&(i.hasAttribute("data-timeline-items")&&i.matches(qo)&&this.addList(i),i.firstElementChild))for(let a of i.querySelectorAll(`${Vc} ${qo}`))this.addList(a)}if(r.type==="attributes"&&["data-timeline-items","data-timeline-row-list","data-timeline-virtual-spacer"].includes(r.attributeName??"")){o.matches(qo)&&this.addList(o);for(let i of o.querySelectorAll(`${Vc} ${qo}`))this.addList(i);this.layoutChanged()}}(this.structureDirty||this.dirty.size||this.pendingChildren.size||this.pendingStyles.size)&&this.schedule()};observe(t){let n=this.scope,r=n.nodeType===9?n:n.ownerDocument,o=r.defaultView,s=new o.MutationObserver(p=>this.receive(p,t));s.observe(n,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["class","style","hidden","aria-hidden","open","data-message-column","data-timeline-row-id","data-timeline-items","data-timeline-row-list","data-timeline-virtual-spacer"]});let i=new o.MutationObserver(p=>{for(let f of p)n.contains(f.target)||this.styles(f,t);this.pendingStyles.size&&this.schedule()});i.observe(r.head,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["media","disabled","href"]}),i.observe(r.body,{subtree:!0,childList:!0,characterData:!0});let a=new o.MutationObserver(p=>{if(p.some(f=>this.visibility.affects(f))){for(let f of this.entries.values())this.dirty.add(f);this.schedule()}});for(let p=gn(n)?n.parentElement:null;p;p=p.parentElement)a.observe(p,{attributes:!0,attributeOldValue:!0,attributeFilter:["class","style","hidden","aria-hidden","open"]});this.observers.push(s,i,a);let u=p=>{gn(p.target)&&p.target.matches(da)&&(this.pendingStyles.add(p.target),this.schedule())},c=p=>{if(p.type.startsWith("transition")&&"propertyName"in p&&!["opacity","visibility","display","content-visibility"].includes(String(p.propertyName))||p.type.startsWith("animation")&&"animationName"in p&&!this.visibility.animation(String(p.animationName)))return;let f=p.target;if(!(!f||!gn(f))){if(n.contains(f)){let h=this.entries.get(f)??this.entries.get(f.closest(ua));if(h)h.column&&f.contains(h.column)&&this.dirty.add(h);else for(let g of this.entries.values())f.contains(g.node)&&this.dirty.add(g)}else if(f.contains(n))for(let h of this.entries.values())this.dirty.add(h);this.dirty.size&&this.schedule()}},d=["transitionend","transitioncancel","animationend","animationcancel"];for(let p of d)r.addEventListener(p,c,!0);return r.addEventListener("load",u,!0),()=>{r.removeEventListener("load",u,!0);for(let p of d)r.removeEventListener(p,c,!0);for(let p of this.observers)p.disconnect();this.cancel?.();for(let p of this.entries.values())this.forget(p);this.entries.clear(),this.roots.clear(),this.lists.clear(),this.dirty.clear(),this.pendingChildren.clear(),this.pendingStyles.clear(),this.relocatedStyles.clear(),this.sheets.clear()}}};function Rk(e,t,n,r){return new Rh(e,t,r).observe(n)}var Wc="data-orbit-avatar",Ih="--orbit-avatar-image",v$="orbit-chat-avatar",Lh="#thread-detail-timeline-panel",w$="thread-pane",Ph=`:is(${Lh}, [${ma}])`,k$=`${Ph} [data-timeline-row-list="top-level"]`,Hr=`:is(:root[${Wc}] ${Lh}, [${ma}][${Wc}]) [data-timeline-row-list="top-level"]`,rs="[data-timeline-row-id]",ir="[data-timeline-items]",$k=`${k$} > ${ir} > ${rs}`,Oh='[data-timeline-row-id*=":user"]',Zc='[data-timeline-row-id*=":assistant:"]',ns=48,Ik=960,S$=ns+14,E$=ns+10,N$=`
37
- ${Hr} > ${ir} > ${rs}:not(${Oh}) {
35
+ `;function wk(e){if(e.getElementById(_k))return()=>{};let t=e.createElement("style");return t.id=_k,t.textContent=v$,e.head.append(t),()=>t.remove()}var Xc=null;function kk(e,t,n,r){let o=null,s=()=>o??=r(),i=e.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!0;if(!e.startViewTransition||i||e.visibilityState!=="visible"){s();return}Xc?.skipTransition();let a=e.documentElement;a.setAttribute(gn,t),a.setAttribute(Bc,n?"phone":"desktop");let u=e.startViewTransition(s);Xc=u,u.updateCallbackDone.catch(()=>{s()}),u.ready.catch(()=>{}),u.finished.catch(()=>{}).finally(()=>{Xc===u&&(Xc=null,a.removeAttribute(gn),a.removeAttribute(Bc))})}function Uc({orbitThread:e,threadId:t,done:n}){let r=J(),[o,s]=v(!1),[i,a]=v(null),u=async()=>{s(!0),a(null);try{await r.call("threads.done",{orbitThread:e,threadId:t})}catch(c){a(c instanceof Error?c.message:"Couldn't save Done. Try again.")}finally{s(!1)}};return m("div",{className:"flex shrink-0 flex-col items-end gap-1",children:[l("button",{type:"button",disabled:o||n,onClick:()=>{u()},"aria-label":"Mark as Done",className:"rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-state-hover hover:text-foreground disabled:opacity-50",children:o?"Saving\u2026":n?"\u2713 Done":"Done"}),i?l("span",{role:"alert",className:"max-w-48 text-xs text-destructive",children:i}):null]})}var Ch="moonlet-threads-list";function Th({size:e=16}){return l("svg",{width:e,height:e,viewBox:"0 0 20 20","aria-hidden":"true",className:"shrink-0",children:l("circle",{cx:"10",cy:"10",r:"9",fill:ir})})}function Hc({mark:e,size:t=16}){return l("svg",{width:t,height:t,viewBox:"0 0 18 18","aria-hidden":"true","data-mark":e,className:"shrink-0",children:e==="needs"?m(he,{children:[l("circle",{cx:"9",cy:"9",r:"6.5",fill:"none",stroke:ir,strokeWidth:"2.3"}),l("circle",{cx:"9",cy:"9",r:"2.6",fill:ir})]}):e==="working"?m(he,{children:[l("circle",{cx:"9",cy:"9",r:"6.5",fill:"none",stroke:"var(--border)",strokeWidth:"2.3"}),l("g",{className:"origin-center animate-spin motion-reduce:animate-none [animation-duration:1.6s]",children:l("circle",{cx:"9",cy:"9",r:"6.5",fill:"none",stroke:ir,strokeWidth:"2.3",strokeDasharray:"12 41",strokeLinecap:"round"})})]}):e==="waiting"?l("path",{d:"M5.5 3h7M5.5 15h7M6.6 3c0 3.4 4.8 3.6 4.8 6s-4.8 2.6-4.8 6M11.4 3c0 3.4-4.8 3.6-4.8 6s4.8 2.6 4.8 6",fill:"none",stroke:ir,strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"}):e==="starting"?l("circle",{cx:"9",cy:"9",r:"6.5",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeDasharray:"2.6 2.6",className:"text-muted-foreground"}):m("g",{className:"text-muted-foreground",children:[l("circle",{cx:"9",cy:"9",r:"6.5",fill:"none",stroke:"currentColor",strokeWidth:"2"}),l("path",{d:"M6 9.2l2 2 4-4.4",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})]})})}var Sk="flex w-full min-w-0 items-start gap-2.5 rounded-lg px-2.5 py-2 text-left text-sm text-foreground transition-colors hover:bg-state-hover aria-[current=true]:bg-state-active";function Ek({orbit:e,listed:t,names:n,needsYou:r,unread:o,view:s,mainUnread:i,now:a,onMain:u,onThread:c}){let d=t.filter(h=>Ln(h,r)==="working").length,p=t.filter(h=>Ln(h,r)==="waiting").length,f=[d>0?`${d} working`:null,p>0?`${p} waiting`:null].filter(h=>h!==null).join(" \xB7 ");return l("nav",{id:Ch,"aria-label":"Threads","data-moonlet-pane":"rail",className:"flex min-h-0 min-w-0 flex-col overflow-hidden border-r border-border bg-sidebar",children:m("div",{className:"flex min-w-0 flex-1 flex-col gap-0.5 overflow-y-auto px-2 py-2.5",children:[m("button",{type:"button",onClick:u,"aria-current":s.kind!=="full",className:V(Sk,"items-center"),children:[l(Th,{size:18}),m("span",{className:"flex min-w-0 flex-1 flex-col",children:[l("span",{className:"truncate font-semibold",children:"Moonlet"}),l("span",{className:"truncate text-xs text-muted-foreground",children:"Main conversation"})]}),i?l("span",{className:"rounded-full px-1.5 text-xs font-semibold text-foreground",style:{background:ir},children:"New"}):null]}),m("div",{className:"flex items-baseline justify-between px-2.5 pb-1 pt-3 text-xs font-semibold text-muted-foreground",children:[l("span",{children:"Threads"}),f?l("span",{children:f}):null]}),t.map(h=>{let g=ca(h,n),x=Ln(h,r),b=s.kind!=="main"&&s.threadId===h.threadId;return m("div",{className:"group relative min-w-0",children:[m("button",{type:"button",title:"Click to open, Shift-click for full screen",onClick:_=>c(h,_.shiftKey),"aria-current":b,className:V(Sk,"pr-16"),children:[l("span",{className:"mt-0.5",children:l(Hc,{mark:x})}),m("span",{className:"flex min-w-0 flex-1 flex-col",children:[l("span",{className:V("truncate",o.has(h.threadId)?"font-bold":"font-medium"),children:g}),l("span",{className:"truncate text-xs text-muted-foreground",children:x==="needs"?zc.needs:bk(h,a)})]}),b&&s.kind==="beside"?l("span",{className:"self-center text-xs text-muted-foreground",children:"beside"}):null]}),l("div",{className:"absolute right-1 top-1 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100",children:l(Uc,{orbitThread:e,threadId:h.threadId,done:h.done})})]},h.threadId)})]})})}function Nk({listed:e,names:t,needsYou:n,view:r,onThread:o}){return e.length===0?null:l("nav",{"aria-label":"Threads",className:"flex shrink-0 gap-1.5 overflow-x-auto border-b border-border px-3 py-2 [scrollbar-width:none]",children:e.map(s=>{let i=Ln(s,n),a=r.kind!=="main"&&r.threadId===s.threadId;return m("button",{type:"button",onClick:()=>o(s,!1),"aria-current":a,className:V("inline-flex h-8 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border border-border bg-background pl-2 pr-3 text-sm aria-[current=true]:ring-1 aria-[current=true]:ring-foreground",i==="needs"&&"font-semibold"),style:i==="needs"?{borderColor:ir}:void 0,children:[l(Hc,{mark:i,size:14}),ca(s,t),i==="needs"?" needs you":""]},s.threadId)})})}var ua=["display","visibility","opacity","content-visibility","all"],w$=e=>new Set(Array.from(e.matchAll(/var\(\s*(--[\w-]+)/g),t=>t[1]));function Rh(e){let t=new Set,n=new Map;for(let r=0;r<e.length;r++){let o=e.item(r);if(!ua.includes(o)&&!o.startsWith("--"))continue;let s=w$(e.getPropertyValue(o));if(o.startsWith("--"))s.size&&n.set(o,s);else for(let i of s)t.add(i)}return{roots:t,edges:n}}function Ak(e){return"style"in e?e.style:null}var Vc=class{nodes=new WeakMap;roots=new Map;references=new Map;edges=new Map;sheets=new Map;rules=new Map;animations=new Map;unknownSheets=new Set;unknown=!1;used=null;classes=null;classAttribute=!1;document;constructor(t){this.document=t,this.invalidateSheets(new Set(t.querySelectorAll('style,link[rel="stylesheet"]')))}count(t,n,r){let o=t.get(n)??0,s=o+r;s?t.set(n,s):t.delete(n),(!o||!s)&&(this.used=this.classes=null)}apply(t,n){for(let r of t.roots)this.count(this.roots,r,n),this.count(this.references,r,n);for(let[r,o]of t.edges){let s=this.edges.get(r);s||this.edges.set(r,s=new Map);for(let i of o)this.count(s,i,n),this.count(this.references,i,n);s.size||this.edges.delete(r)}}retain(t){for(let n of t){let r=this.nodes.get(n);if(r)r.users++;else{let o=Rh(Ak(n)??this.document.createElement("div").style);this.nodes.set(n,{users:1,value:o}),this.apply(o,1)}}}release(t){for(let n of t){let r=this.nodes.get(n);r&&!--r.users&&(this.apply(r.value,-1),this.nodes.delete(n))}t.clear()}parseSheet(t){let n={values:[],rules:[],animations:new Map,unknown:!1},r=new Set,o=(i,a)=>{for(let u of i){if("style"in u){let c=u.style;n.values.push(Rh(c));let d=Array.from({length:c.length},(p,f)=>c.item(f));if("selectorText"in u&&/\.|\[\s*class\b/.test(String(u.selectorText))&&n.rules.push({selector:String(u.selectorText),properties:d}),a)for(let p of d)n.animations.get(a).add(p)}if("styleSheet"in u&&u.styleSheet&&s(u.styleSheet),"cssRules"in u){let c="name"in u?String(u.name):a;c&&!n.animations.has(c)&&n.animations.set(c,new Set),o(u.cssRules,c)}}},s=i=>{r.has(i)||(r.add(i),o(i.cssRules))};try{"sheet"in t&&t.sheet?s(t.sheet):n.unknown=!0}catch{n.unknown=!0}return n}invalidateSheets(t){for(let r of t){let o=this.sheets.get(r),s=r.isConnected?this.parseSheet(r):null;for(let i of s?.values??[])this.apply(i,1);for(let i of o?.values??[])this.apply(i,-1);JSON.stringify(o?.rules??[])!==JSON.stringify(s?.rules??[])&&(this.classes=null),s?.rules.length?this.rules.set(r,s.rules):this.rules.delete(r),s?.animations.size?this.animations.set(r,s.animations):this.animations.delete(r),s?.unknown?this.unknownSheets.add(r):this.unknownSheets.delete(r),s?this.sheets.set(r,s):this.sheets.delete(r)}let n=!!this.unknownSheets.size;this.unknown!==n&&(this.classes=null),this.unknown=n,this.prepare()}prepare(){if(!this.used){this.used=new Set(this.roots.keys());for(let t of this.used)for(let n of this.edges.get(t)?.keys()??[])this.used.add(n)}if(!this.classes){this.classes=new Set,this.classAttribute=!1;for(let t of this.rules.values())for(let n of t)if(n.properties.some(r=>ua.includes(r)||this.used.has(r))){/\[\s*class\b/.test(n.selector)&&(this.classAttribute=!0);for(let r of n.selector.matchAll(/\.((?:\\(?:[0-9a-fA-F]{1,6}\s?|.)|[\w-])+)/g))this.classes.add(r[1].replace(/\\([0-9a-fA-F]{1,6})\s?|\\(.)/g,(o,s,i)=>{if(!s)return i;let a=Number.parseInt(s,16);return a>0&&a<=1114111&&!(a>=55296&&a<=57343)?String.fromCodePoint(a):"\uFFFD"}))}}}affects(t){let n=t.target,r=t.attributeName,o=n.getAttribute(r);if(t.oldValue===o)return!1;if(r!=="style"&&r!=="class")return!0;if(r==="class"){if(this.prepare(),this.unknown||this.classAttribute)return!0;let c=new Set((t.oldValue??"").split(/\s+/)),d=new Set((o??"").split(/\s+/));return[...c,...d].some(p=>c.has(p)!==d.has(p)&&this.classes.has(p))}let s=Ak(n);if(!s)return!1;let i=this.nodes.get(n);if(i){let c=Rh(s);this.apply(c,1),this.apply(i.value,-1),i.value=c}let a=this.document.createElement("div").style;if(a.cssText=t.oldValue??"",ua.some(c=>a.getPropertyValue(c)!==s.getPropertyValue(c)||a.getPropertyPriority(c)!==s.getPropertyPriority(c)))return!0;let u=new Set([...Array.from({length:a.length},(c,d)=>a.item(d)),...Array.from({length:s.length},(c,d)=>s.item(d))]);for(let c of u)if(!(!c.startsWith("--")||!this.references.has(c)&&!this.unknown)&&(a.getPropertyValue(c)!==s.getPropertyValue(c)||a.getPropertyPriority(c)!==s.getPropertyPriority(c))&&(this.prepare(),this.unknown||this.used.has(c)))return!0;return!1}property(t){return ua.includes(t)?!0:t.startsWith("--")?(this.prepare(),this.unknown||this.used.has(t)):!1}animation(t){if(this.prepare(),this.unknown)return!0;let n=!1;for(let r of this.animations.values()){let o=r.get(t);if(o&&(n=!0,[...o].some(s=>ua.includes(s)||this.used.has(s))))return!0}return!n}};var ga="data-orbit-chat",Mn="data-orbit-avatar-start",$k="data-orbit-author",es="data-orbit-reply-column",k$="#thread-detail-timeline-panel",Zc=`:is(${k$}, [${ga}])`,Jo='[data-timeline-row-list="top-level"] > [data-timeline-items]',da="[data-timeline-row-id]",$h="[data-message-column]",pa='style,link[rel="stylesheet"]';function ts(e){return e?.size??0}function fa(e){return e?.boundaries??0}function ns(e){e.size=1+ts(e.left)+ts(e.right),e.boundaries=+(e.kind!=="skip")+fa(e.left)+fa(e.right),e.left&&(e.left.parent=e),e.right&&(e.right.parent=e)}function ha(e,t){return e?t?e.priority<t.priority?(e.right=ha(e.right,t),ns(e),e):(t.left=ha(e,t.left),ns(t),t):e:t}function ma(e,t){if(!e)return[null,null];if(ts(e.left)>=t){let[o,s]=ma(e.left,t);return e.left=s,ns(e),e.parent=null,o&&(o.parent=null),[o,e]}let[n,r]=ma(e.right,t-ts(e.left)-1);return e.right=n,ns(e),e.parent=null,r&&(r.parent=null),[e,r]}function Ck(e){let t=ts(e.left);for(let n=e,r=e.parent;r;n=r,r=r.parent)r.right===n&&(t+=ts(r.left)+1);return t}function xn(e){return e.nodeType===1}function S$(e,t){let n=e.ownerDocument.defaultView;if(!n)return!1;let r=o=>{let s=t.get(o);return s||(s=n.getComputedStyle(o),t.set(o,s)),s};if(["hidden","collapse"].includes(r(e).visibility))return!1;for(let o=e;o;o=o.parentElement){if(o.hasAttribute("hidden")||o.getAttribute("aria-hidden")==="true")return!1;let s=r(o);if(s.display==="none"||s.opacity==="0"||s.getPropertyValue("content-visibility")==="hidden"||o.parentElement?.localName==="details"&&!o.parentElement.hasAttribute("open")&&o.localName!=="summary")return!1}return!0}var Tk=()=>({rows:new Map,global:""});function Rk(e,t){try{if(!("sheet"in e)||!e.sheet)return null;let n=new Map,r=[],o=new Set,s=(a,u)=>{for(let c of a){if("styleSheet"in c&&c.styleSheet&&i(c.styleSheet,u+c.cssText),"cssRules"in c&&s(c.cssRules,u+c.cssText.slice(0,c.cssText.indexOf("{"))),!("style"in c))continue;let d=c.style,p=Array.from({length:d.length},(x,b)=>d.item(b)).filter(t);if(!p.length)continue;let f="selectorText"in c?String(c.selectorText):"",h=JSON.stringify([u,f,p.map(x=>[x,d.getPropertyValue(x),d.getPropertyPriority(x)])]),g=new Set;for(let x of f.split(",")){let b=x.match(/\[data-timeline-row-id\s*=\s*("(?:[^"\\]|\\.)*")\s*\]/);if(!b){g.clear();break}let _=JSON.parse(b[1]);if(typeof _!="string"){g.clear();break}g.add(_)}if(!g.size)r.push(h);else for(let x of g)n.set(x,(n.get(x)??"")+h)}},i=(a,u)=>{o.has(a)||(o.add(a),s(a.cssRules,u))};return i(e.sheet,JSON.stringify([e.getAttribute("media"),e.getAttribute("disabled")])),{rows:n,global:r.join(`
36
+ `)}}catch{return null}}var Ih=class{entries=new Map;lists=new Set;ids=new Map;pendingChildren=new Set;dirty=new Set;pendingStyles=new Set;relocatedStyles=new Set;sheets=new Map;observers=[];cancel=null;structureDirty=!1;roots=new Map;sequence=0;visibility;scope;name;layoutChanged;constructor(t,n,r=()=>{}){let o=t.nodeType===9?t:t.ownerDocument;this.visibility=new Vc(o),this.scope=t,this.name=n,this.layoutChanged=r;for(let s of t.querySelectorAll(`${Zc} ${Jo}`))this.addList(s);for(let s of o.querySelectorAll(pa))this.sheets.set(s,Rk(s,i=>this.visibility.property(i)));this.flush()}addList(t){if(this.lists.has(t)||t.closest(da)||this.scope.nodeType!==9&&t.closest(Zc)!==this.scope)return;this.lists.add(t),this.structureDirty=!0;let n=null;for(let r of t.children){let o=this.create(r,t);o.list=t,o.previous=n,o.next=null,n&&(n.next=o),this.entries.set(r,o),this.insert(o),this.dirty.add(o),n=o}}create(t,n){return{node:t,list:n,previous:null,next:null,kind:"skip",id:null,column:null,markedColumn:null,header:null,left:null,right:null,parent:null,size:1,boundaries:0,priority:Math.imul(++this.sequence,2654435761)>>>0,visibilityNodes:new Set}}insert(t){let[n,r]=ma(this.roots.get(t.list)??null,t.previous?Ck(t.previous)+1:0),o=ha(ha(n,t),r);o&&(o.parent=null),this.roots.set(t.list,o)}remove(t){let[n,r]=ma(this.roots.get(t.list)??null,Ck(t)),[,o]=ma(r,1),s=ha(n,o);s&&(s.parent=null),this.roots.set(t.list,s),t.left=t.right=t.parent=null,ns(t)}unindex(t){if(t.id===null)return;let n=this.ids.get(t.id);n?.delete(t),n?.size||this.ids.delete(t.id)}forget(t){this.entries.delete(t.node),this.visibility.release(t.visibilityNodes),this.unindex(t),t.node.removeAttribute(Mn),t.markedColumn?.removeAttribute(es),t.header?.remove()}read(t,n){let r=t.node.getAttribute("data-timeline-row-id");if(t.id!==r&&(this.unindex(t),t.id=r,r!==null)){let u=this.ids.get(r);u||this.ids.set(r,u=new Set),u.add(t)}let o=t.visibilityNodes,s=new Set;t.visibilityNodes=s,t.column=null,t.kind=t.node.hasAttribute("data-timeline-window-spacer")?"gap":"skip";let i=r?.includes(":assistant:")?"reply":r?.includes(":user")?"owner":null;if(i===null){this.visibility.release(o);return}for(let u of t.node.querySelectorAll($h))if(u.closest(da)===t.node){for(let c=u;c;c=c.parentElement)s.add(c);if(t.column??=u,S$(u,n)){t.column=u,t.kind=i;break}}let a=new Set;for(let u of s)o.delete(u)||a.add(u);this.visibility.release(o),this.visibility.retain(a)}boundary(t,n){let r=n==="previous"?"left":"right",o=n==="previous"?"right":"left",s=i=>{let a=i;for(;;)if(fa(a[o]))a=a[o];else{if(a.kind!=="skip")return a;a=a[r]}};if(fa(t[r]))return s(t[r]);for(let i=t,a=t.parent;a;i=a,a=a.parent)if(a[o]===i){if(a.kind!=="skip")return a;if(fa(a[r]))return s(a[r])}return null}render(t){let n=t.kind==="reply"&&this.boundary(t,"previous")?.kind!=="reply",r=n?t.column:null;if(t.node.hasAttribute(Mn)!==n&&t.node.toggleAttribute(Mn,n),t.markedColumn!==r&&(t.markedColumn?.removeAttribute(es),r?.setAttribute(es,""),t.markedColumn=r),t.header&&(t.header.parentElement!==r||!this.name)&&(t.header.remove(),t.header=null),!r||!this.name||t.header)return;let o=r.ownerDocument.createElement("div");o.setAttribute($k,""),o.className="mb-1 min-w-0 text-sm font-medium text-foreground",o.style.overflowWrap="anywhere",o.textContent=this.name,r.prepend(o),t.header=o}flush=()=>{this.cancel=null;let t=new Set;for(let s of this.lists)if(!this.scope.contains(s)||!s.matches(Jo)){this.lists.delete(s),this.roots.delete(s);for(let i of this.entries.values())i.list===s&&this.forget(i);this.layoutChanged()}let n=new Map;for(let s of this.pendingChildren){let i=this.entries.get(s);if(i){if(i.kind!=="skip"){let a=this.boundary(i,"next");a&&t.add(a)}this.remove(i),i.previous&&(i.previous.next=i.next),i.next&&(i.next.previous=i.previous),!s.parentElement||!this.lists.has(s.parentElement)?this.forget(i):(n.set(s,i),this.entries.delete(s))}}for(let s of this.pendingChildren){let i=s.parentElement;if(!i||!this.lists.has(i))continue;let a=n.get(s);a||(a=this.create(s,i)),this.entries.set(s,a),a.list=i;let u=s.previousElementSibling;for(;u&&!this.entries.has(u);)u=u.previousElementSibling;let c=s.nextElementSibling;for(;c&&!this.entries.has(c);)c=c.nextElementSibling;a.previous=u?this.entries.get(u):null,a.next=c?this.entries.get(c):null,a.previous&&(a.previous.next=a),a.next&&(a.next.previous=a),this.insert(a),this.dirty.add(a)}this.pendingChildren.clear(),this.pendingStyles.size&&this.visibility.invalidateSheets(this.pendingStyles);for(let s of this.pendingStyles){let i=this.sheets.has(s)?this.sheets.get(s):Tk(),a=s.isConnected?Rk(s,c=>this.visibility.property(c)):Tk();s.isConnected?this.sheets.set(s,a):this.sheets.delete(s);let u=this.relocatedStyles.has(s);if(i===null||a===null||i.global!==a.global||u&&a.global!=="")for(let c of this.entries.values())this.dirty.add(c);else for(let c of new Set([...i.rows.keys(),...a.rows.keys()]))if(u||i.rows.get(c)!==a.rows.get(c))for(let d of this.ids.get(c)??[])this.dirty.add(d)}this.pendingStyles.clear(),this.relocatedStyles.clear();let r=new Map,o=[];for(let s of this.dirty){if(!this.entries.has(s.node))continue;let i=s.kind;this.read(s,r);for(let a=s;a;a=a.parent)ns(a);t.add(s),(i!=="skip"||s.kind!=="skip")&&o.push(s)}this.dirty.clear();for(let s of o){let i=this.boundary(s,"next");i&&t.add(i)}for(let s of t)this.entries.has(s.node)&&this.render(s);this.structureDirty&&(this.structureDirty=!1,this.layoutChanged())};schedule(){if(this.cancel)return;let n=(this.scope.nodeType===9?this.scope:this.scope.ownerDocument).defaultView;if(n?.requestAnimationFrame){let r=n.requestAnimationFrame(this.flush);this.cancel=()=>n.cancelAnimationFrame(r)}else{let r=setTimeout(this.flush,16);this.cancel=()=>clearTimeout(r)}}styles(t,n){let r=xn(t.target)?t.target:t.target.parentElement;r?.matches(pa)&&r!==n&&this.pendingStyles.add(r);for(let o of[...t.addedNodes,...t.removedNodes])if(xn(o)&&(o.matches(pa)&&o!==n&&(this.pendingStyles.add(o),o.isConnected&&this.sheets.has(o)&&this.relocatedStyles.add(o)),o.firstElementChild))for(let s of o.querySelectorAll(pa))s!==n&&(this.pendingStyles.add(s),s.isConnected&&this.sheets.has(s)&&this.relocatedStyles.add(s))}receive=(t,n)=>{for(let r of t){if(this.styles(r,n),r.type==="characterData"||!xn(r.target)||!this.scope.contains(r.target))continue;let o=r.target;if(r.type==="attributes"&&!this.visibility.affects(r))continue;let s=this.entries.get(o)??this.entries.get(o.closest(da));if(r.type==="attributes")if(s)(o===s.node||o===s.column||o.contains(s.column)||r.attributeName==="data-message-column")&&this.dirty.add(s);else for(let i of o.querySelectorAll(da)){let a=this.entries.get(i);a&&this.dirty.add(a)}else if(this.lists.has(o))for(let i of[...r.addedNodes,...r.removedNodes])xn(i)&&this.pendingChildren.add(i);else if(!s?.column?.contains(o)){if(s)for(let i of[...r.addedNodes,...r.removedNodes])xn(i)&&(i.contains(s.column)||i.matches($h)||i.firstElementChild&&i.querySelector($h))&&this.dirty.add(s);for(let i of r.removedNodes)if(xn(i))for(let a of this.lists)i.contains(a)&&(this.structureDirty=!0);for(let i of r.addedNodes)if(xn(i)&&(i.hasAttribute("data-timeline-items")&&i.matches(Jo)&&this.addList(i),i.firstElementChild))for(let a of i.querySelectorAll(`${Zc} ${Jo}`))this.addList(a)}if(r.type==="attributes"&&["data-timeline-items","data-timeline-row-list","data-timeline-virtual-spacer"].includes(r.attributeName??"")){o.matches(Jo)&&this.addList(o);for(let i of o.querySelectorAll(`${Zc} ${Jo}`))this.addList(i);this.layoutChanged()}}(this.structureDirty||this.dirty.size||this.pendingChildren.size||this.pendingStyles.size)&&this.schedule()};observe(t){let n=this.scope,r=n.nodeType===9?n:n.ownerDocument,o=r.defaultView,s=new o.MutationObserver(p=>this.receive(p,t));s.observe(n,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["class","style","hidden","aria-hidden","open","data-message-column","data-timeline-row-id","data-timeline-items","data-timeline-row-list","data-timeline-virtual-spacer"]});let i=new o.MutationObserver(p=>{for(let f of p)n.contains(f.target)||this.styles(f,t);this.pendingStyles.size&&this.schedule()});i.observe(r.head,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["media","disabled","href"]}),i.observe(r.body,{subtree:!0,childList:!0,characterData:!0});let a=new o.MutationObserver(p=>{if(p.some(f=>this.visibility.affects(f))){for(let f of this.entries.values())this.dirty.add(f);this.schedule()}});for(let p=xn(n)?n.parentElement:null;p;p=p.parentElement)a.observe(p,{attributes:!0,attributeOldValue:!0,attributeFilter:["class","style","hidden","aria-hidden","open"]});this.observers.push(s,i,a);let u=p=>{xn(p.target)&&p.target.matches(pa)&&(this.pendingStyles.add(p.target),this.schedule())},c=p=>{if(p.type.startsWith("transition")&&"propertyName"in p&&!["opacity","visibility","display","content-visibility"].includes(String(p.propertyName))||p.type.startsWith("animation")&&"animationName"in p&&!this.visibility.animation(String(p.animationName)))return;let f=p.target;if(!(!f||!xn(f))){if(n.contains(f)){let h=this.entries.get(f)??this.entries.get(f.closest(da));if(h)h.column&&f.contains(h.column)&&this.dirty.add(h);else for(let g of this.entries.values())f.contains(g.node)&&this.dirty.add(g)}else if(f.contains(n))for(let h of this.entries.values())this.dirty.add(h);this.dirty.size&&this.schedule()}},d=["transitionend","transitioncancel","animationend","animationcancel"];for(let p of d)r.addEventListener(p,c,!0);return r.addEventListener("load",u,!0),()=>{r.removeEventListener("load",u,!0);for(let p of d)r.removeEventListener(p,c,!0);for(let p of this.observers)p.disconnect();this.cancel?.();for(let p of this.entries.values())this.forget(p);this.entries.clear(),this.roots.clear(),this.lists.clear(),this.dirty.clear(),this.pendingChildren.clear(),this.pendingStyles.clear(),this.relocatedStyles.clear(),this.sheets.clear()}}};function Ik(e,t,n,r){return new Ih(e,t,r).observe(n)}var jc="data-orbit-avatar",Oh="--orbit-avatar-image",E$="orbit-chat-avatar",Dh="#thread-detail-timeline-panel",N$="thread-pane",Lh=`:is(${Dh}, [${ga}])`,A$=`${Lh} [data-timeline-row-list="top-level"]`,Vr=`:is(:root[${jc}] ${Dh}, [${ga}][${jc}]) [data-timeline-row-list="top-level"]`,os="[data-timeline-row-id]",ar="[data-timeline-items]",Pk=`${A$} > ${ar} > ${os}`,Mh='[data-timeline-row-id*=":user"]',Wc='[data-timeline-row-id*=":assistant:"]',rs=48,Ok=960,C$=rs+14,T$=rs+10,R$=`
37
+ ${Vr} > ${ar} > ${os}:not(${Mh}) {
38
38
  position: relative;
39
- --orbit-avatar-gutter: ${S$}px;
39
+ --orbit-avatar-gutter: ${C$}px;
40
40
  padding-inline-start: var(--orbit-avatar-gutter);
41
41
  }
42
- ${Hr} > ${ir} > ${Zc}[${Ln}] [${Jo}]::before {
42
+ ${Vr} > ${ar} > ${Wc}[${Mn}] [${es}]::before {
43
43
  content: "";
44
44
  position: absolute;
45
45
  inset-inline-start: calc(-1 * var(--orbit-avatar-gutter));
46
46
  top: 0;
47
- width: ${ns}px;
48
- height: ${ns}px;
47
+ width: ${rs}px;
48
+ height: ${rs}px;
49
49
  border-radius: 9999px;
50
- background: var(${Ih}) center / cover no-repeat, color-mix(in oklch, var(--ink, currentColor) 6%, var(--canvas, transparent));
50
+ background: var(${Oh}) center / cover no-repeat, color-mix(in oklch, var(--ink, currentColor) 6%, var(--canvas, transparent));
51
51
  box-shadow: 0 0 0 1px color-mix(in oklch, var(--ink, currentColor) 14%, transparent);
52
52
  pointer-events: none;
53
53
  }
54
- ${Hr} > ${ir} > ${Zc}[${Ln}] {
55
- min-height: ${ns}px;
54
+ ${Vr} > ${ar} > ${Wc}[${Mn}] {
55
+ min-height: ${rs}px;
56
56
  }
57
- ${Hr} > ${ir} > ${Zc}[${Ln}] [${Jo}] {
57
+ ${Vr} > ${ar} > ${Wc}[${Mn}] [${es}] {
58
58
  position: relative;
59
- min-height: ${ns}px;
59
+ min-height: ${rs}px;
60
60
  }
61
- @container ${w$} (max-width: 480px) {
62
- ${Hr} > ${ir} > ${rs}:not(${Oh}) {
63
- --orbit-avatar-gutter: ${E$}px;
61
+ @container ${N$} (max-width: 480px) {
62
+ ${Vr} > ${ar} > ${os}:not(${Mh}) {
63
+ --orbit-avatar-gutter: ${T$}px;
64
64
  }
65
65
  }
66
- `,nK={gutter:`${Hr} > ${ir} > ${rs}:not(${Oh})`,avatar:`${Hr} > ${ir} > ${Zc}[${Ln}]`};function A$(e){return!e||!/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/.test(e)?null:`url("${e}")`}function Pk(e,t,n=null,r){let o=A$(t);if(!o&&!n)return()=>{};let s=()=>r??e.querySelector(Lh),i=r??e.documentElement,a=e.createElement("style");a.id=v$,a.textContent=N$,e.head.append(a),o&&(i.style.setProperty(Ih,o),i.setAttribute(Wc,""));let u=e.defaultView,c=u?new u.Image:null,d=C=>console.warn(`[Moonlet avatar] ${C}`);c&&o&&(c.onerror=()=>d("The saved avatar could not be loaded. Check the page image policy and the saved picture."),c.src=t);let p=!1,f=null,h=null,g=null,x=()=>{if(!h)return;let C=h.querySelector(`${Ph} ${rs}`),y=h.querySelector($k);C&&!y&&!p&&f===null&&(f=setTimeout(()=>{f=null,h?.querySelector(`${Ph} ${rs}`)&&!h.querySelector($k)&&(p=!0,d("Chat rows no longer match Moonlet's avatar layout. Update the chat avatar selectors for this Moonlet version."))},2e3))},b=()=>{let C=s();C!==h&&(g?.(),h=C,g=h?Rk(h,n,a,x):null,x())};b();let v=C=>{let y=C.effectiveDirective;(y==="img-src"||y==="style-src-elem"||y==="style-src-attr")&&d("The page policy blocked an image or style while the chat avatar was active. Check the browser policy report.")};e.addEventListener("securitypolicyviolation",v),a.sheet||d("The avatar stylesheet was not applied. Check the page style policy.");let w=new(u?.MutationObserver??MutationObserver)(()=>{h?.isConnected||b()});return r||w.observe(e.body,{childList:!0,subtree:!0}),()=>{w.disconnect(),e.removeEventListener("securitypolicyviolation",v),g?.(),f!==null&&clearTimeout(f),c&&(c.onerror=null),a.remove(),i.removeAttribute(Wc),i.style.removeProperty(Ih)}}var ga="data-orbit-chat-width",C$="orbit-chat-width",Ok="#thread-detail-timeline-panel > div > [data-thread-window]",Lk=["> div > div > [data-page-scroll-viewport] > div > .max-w-\\[760px\\]","> div > div > [data-page-scroll-viewport] > div > [data-scroll-footer] > div > .max-w-\\[760px\\]"],T$=Lk.map(e=>`${Ok}[${ga}] ${e}`).join(`,
67
- `),R$=`${T$} { max-width: ${Ik}px; }`,$h=new WeakSet;function Mk(e,t){if(!t)return()=>{};let n=e.createElement("style");n.id=C$,n.textContent=R$,e.head.append(n);let r=null,o=null,s=()=>{let c=e.querySelector(Ok);c!==r&&(r?.removeAttribute(ga),r=c);let d=!!(r&&Lk.every(p=>r.querySelector(`:scope ${p}`)));return r?.hasAttribute(ga)!==d&&r?.toggleAttribute(ga,d),d},i=()=>{s()?(o!==null&&clearTimeout(o),o=null):!$h.has(e)&&o===null&&(o=setTimeout(()=>{o=null,!s()&&!$h.has(e)&&($h.add(e),console.warn(`[Moonlet chat width] The chat column no longer matches this Moonlet version. The ${Ik}px width could not be applied. Update the column selector in chat-avatar-style.ts.`))},2e3))};i();let a=e.defaultView,u=new(a?.MutationObserver??MutationObserver)(i);return u.observe(e.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","data-page-scroll-viewport","data-thread-window"]}),()=>{u.disconnect(),o!==null&&clearTimeout(o),r?.removeAttribute(ga),n.remove()}}function jc({threadId:e,container:t}={}){let n=G_(),r=e??n.threadId,o=J(),[s,i]=_({threadId:null,url:null,isOrbitThread:!1,name:null}),a=s.threadId===r?s.url:null,u=q_(),[c,d]=_(0),p=q(()=>d(g=>g+1),[]);ke("config",p),K(()=>{if(!r){i({threadId:null,url:null,isOrbitThread:!1,name:null});return}let g=!0;return o.call("avatar.forThread",{threadId:r}).then(x=>{g&&i({threadId:r,url:x.url,isOrbitThread:x.isOrbitThread,name:x.name})},()=>{g&&(i({threadId:r,url:null,isOrbitThread:!1,name:null}),console.warn("[Moonlet avatar] Could not read the avatar for this conversation. It will be checked again after reconnecting or saving preferences."))}),()=>{g=!1}},[o,r,c,u]);let f=s.threadId===r?s.name:null,h=s.threadId===r&&s.isOrbitThread;return ot(()=>{if(t===null)return;let g=Pk(document,a,f,t),x=Mk(document,h&&t===void 0);return()=>{g(),x()}},[r,a,f,h,t]),null}var $$=new Set(["title-changed","interactions-changed","read-state-changed","status-changed"]),Dk=new Set;function Fk(e){let t=un(),[n,r]=_(new Map),[o,s]=_(Dk),[i,a]=_(Dk),[u,c]=_(0),d=Lt(()=>e?.map(h=>h.threadId)??[],[e]),p=q(()=>c(h=>h+1),[]);K(()=>{let h=t.subscribe({event:"thread:changed",callback:x=>{x.changes.some(b=>$$.has(b))&&(!x.id||d.includes(x.id))&&p()}}),g=t.subscribe({event:"realtime:connection",callback:x=>{x.state==="connected"&&p()}});return()=>{h(),g()}},[t,d,p]),K(()=>{let h=new AbortController,g=!0;return(async()=>{let x=new Map,b=new Set,v=new Set;try{for(let w=0;w<d.length;w+=200){if(!g)return;let C=await t.threads.list({threadIds:d.slice(w,w+200),includeHidden:!0,limit:200,signal:h.signal});for(let y of C)y.title&&x.set(y.id,y.title),y.hasPendingInteraction&&b.add(y.id),(y.lastReadAt??0)<y.latestAttentionAt&&v.add(y.id)}if(!g)return;r(x),s(b),a(v)}catch{g&&r(w=>new Map(d.flatMap(C=>{let y=w.get(C);return y===void 0?[]:[[C,y]]})))}})(),()=>{g=!1,h.abort()}},[t,d,u]);let f=q((h,g)=>{r(x=>new Map(x).set(h,g)),p()},[p]);return{names:n,saved:f,needsYou:o,unread:i}}function zk({threadId:e,title:t,onSaved:n}){let r=un(),[o,s]=_(!1),[i,a]=_(t),[u,c]=_(!1),[d,p]=_(null),f=Y(null),h=Y(null),g=Y(!1),x=Y(!0),b=Y(!1);K(()=>(x.current=!0,()=>{x.current=!1}),[]),K(()=>{o?(f.current?.focus(),f.current?.select()):b.current&&(b.current=!1,h.current?.focus())},[o]);let v=()=>{b.current=!0,s(!1),p(null)},w=async()=>{let C=i.trim();if(!(g.current||!C)){g.current=!0,c(!0),p(null);try{await r.threads.update({threadId:e,title:C}),x.current&&(n(e,C),v())}catch(y){x.current&&p(y instanceof Error?y.message:"Couldn't save the title. Try again.")}finally{g.current=!1,x.current&&c(!1)}}};return o?m("form",{className:"flex min-w-0 flex-1 flex-col gap-1",onSubmit:C=>{C.preventDefault(),w()},onKeyDown:C=>{C.key==="Escape"&&!g.current&&(C.preventDefault(),v())},children:[m("div",{className:"flex min-w-0 items-center gap-2",children:[l("input",{ref:f,"aria-label":"Title",className:"min-w-0 flex-1 rounded-md border border-border bg-background px-2 py-1 text-sm",value:i,disabled:u,onChange:C=>a(C.target.value)}),l("button",{type:"submit",disabled:u||!i.trim(),"aria-busy":u,className:"rounded-md px-2 py-1 text-xs disabled:opacity-50",children:u?"Saving\u2026":"Save title"}),l("button",{type:"button",disabled:u,className:"rounded-md px-2 py-1 text-xs disabled:opacity-50",onClick:v,children:"Cancel"})]}),d?l("span",{role:"alert",className:"text-xs text-destructive",children:d}):null]}):m("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[l("span",{className:"truncate text-sm font-medium",children:t}),l("button",{ref:h,type:"button","aria-label":"Rename",className:"shrink-0 rounded-md px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{a(t),s(!0)},children:"Rename"})]})}var Kk={light:"#f6cf79",gold:"#e2b04d",deep:"#c2871f",crater:"#d9a035","crater-shadow":"#b47a1c","crater-rim":"#ffe08f",shade:"#303d77",rim:"#425090","shade-crater":"#2c3766",ink:"#222940",shine:"#f5f8fd"},Xk=[["gold","M32 4A28 28 0 0 0 32 60A15 28 0 0 0 32 4Z"],["light","M7.75 46A28 28 0 0 1 30.05 4.07A33.76 33.76 0 0 0 7.75 46Z"],["deep","M32 4A14 28 0 0 1 32 60A8.8 28 0 0 0 32 4Z"],["crater","M18.11 19.84A2.8 4.3 -138.81 1 0 13.89 16.16A2.8 4.3 -138.81 1 0 18.11 19.84Z"],["crater-shadow","M12.75 20.7A5.02 5.02 0 0 1 18.59 14.58A7.77 7.77 0 0 0 12.75 20.7Z"],["crater-rim","M19.44 15.78A5.34 5.34 0 0 1 13.87 21.62A7.25 7.25 0 0 0 19.44 15.78Z"],["crater","M26.8 11.68A1.22 2 -104.35 1 0 26.2 9.32A1.22 2 -104.35 1 0 26.8 11.68Z"],["crater-shadow","M24.79 11.38A1.98 1.98 0 0 1 27.77 9.35A2.98 2.98 0 0 0 24.79 11.38Z"],["crater-rim","M28.35 9.79A2.07 2.07 0 0 1 25.51 11.73A2.78 2.78 0 0 0 28.35 9.79Z"],["crater","M11.87 39.02A1.45 2.5 160.77 1 0 9.13 39.98A1.45 2.5 160.77 1 0 11.87 39.02Z"],["crater-shadow","M9.4 40.6A1.7 1.7 0 1 1 11.13 37.73A1.9 1.9 0 0 0 9.4 40.6Z"],["crater-rim","M11.78 38.79A1.6 1.6 0 0 1 10.13 41.53A1.79 1.79 0 0 0 11.78 38.79Z"],["crater","M22.81 50.83A1.86 3.2 116 1 0 21.19 54.17A1.86 3.2 116 1 0 22.81 50.83Z"],["crater-shadow","M19.89 53.28A2.07 2.07 0 1 1 23.25 51.07A2.17 2.17 0 0 0 19.89 53.28Z"],["crater-rim","M24.44 52.09A1.92 1.92 0 1 1 21.24 54.19A2.05 2.05 0 0 0 24.44 52.09Z"],["crater","M37.13 49.25A1.3 1.8 73.44 1 0 37.87 51.75A1.3 1.8 73.44 1 0 37.13 49.25Z"],["crater-shadow","M35.98 51.38A1.78 1.78 0 0 1 38.62 49.32A2.57 2.57 0 0 0 35.98 51.38Z"],["crater-rim","M39.15 49.81A1.84 1.84 0 0 1 36.63 51.78A2.4 2.4 0 0 0 39.15 49.81Z"],["shade","M32 4A28 28 0 0 1 32 60A14 28 0 0 0 32 4Z"],["rim","M32 4A28 28 0 0 1 32 60A25.6 28 0 0 0 32 4Z"],["shade-crater","M48.91 24.57A1.41 2 -23.73 1 0 51.49 23.43A1.41 2 -23.73 1 0 48.91 24.57Z"],["shade-crater","M50.3 41.53A1.01 1.6 27.51 1 0 52.1 42.47A1.01 1.6 27.51 1 0 50.3 41.53Z"],["ink","M17.5 32.6a3.5 4.5 0 1 0 7 0a3.5 4.5 0 1 0 -7 0Z"],["shine","M18.88 31.47A1.05 1.44 -28 1 0 20.74 30.49A1.05 1.44 -28 1 0 18.88 31.47Z"],["ink","M32.5 32.6a3.5 4.5 0 1 0 7 0a3.5 4.5 0 1 0 -7 0Z"],["shine","M33.88 31.47A1.05 1.44 -28 1 0 35.74 30.49A1.05 1.44 -28 1 0 33.88 31.47Z"]];var I$="var(--moonlet-lamp, currentColor)",Bk="h-[0.54em] w-[0.54em] shrink-0 translate-y-[0.03em]";function Uk({className:e}){return m("span",{role:"img","aria-label":"Moonlet",className:V("inline-flex items-baseline font-extrabold leading-none tracking-tight",e),children:[l("span",{"aria-hidden":"true",children:"m"}),l("svg",{"aria-hidden":"true",viewBox:"0 0 14 14",className:V(Bk,"ml-[0.035em] mr-[0.02em]"),children:l("circle",{cx:"7",cy:"7",r:"5.5",fill:"none",stroke:"currentColor",strokeWidth:"3"})}),l("svg",{"aria-hidden":"true",viewBox:"0 0 14 14",className:V(Bk,"ml-[0.02em] mr-[0.035em]"),children:l("circle",{cx:"7",cy:"7",r:"7",fill:I$})}),l("span",{"aria-hidden":"true",children:"nlet"})]})}function Hk({className:e}){return l("svg",{"aria-hidden":"true",viewBox:"0 0 64 64",className:V("shrink-0",e),children:Xk.map(([t,n])=>l("path",{fill:`var(--moonlet-moon-${t}, ${Kk[t]})`,d:n},n))})}function os(){let e=J(),[t,n]=_(void 0),[r,o]=_(0);return ke("config",q(()=>o(s=>s+1),[])),K(()=>{let s=!0;return e.call("threads.home",null).then(({orbitThread:i})=>{s&&n(i)},()=>{s&&n(i=>i??null)}),()=>{s=!1}},[e,r]),t}function O$(){let e=J(),[t,n]=_(void 0),[r,o]=_(null),[s,i]=_(0),a=q(()=>i(h=>h+1),[]);ke("threads",a),ke("config",a),K(()=>{let h=!0;return(async()=>{try{let{orbitThread:g}=await e.call("threads.home",null);if(!h)return;if(n(g),!g)return o([]);let x=await e.call("threads.list",{orbitThread:g});h&&o(x.threads)}catch{h&&(n(g=>g??null),o(g=>g??[]))}})(),()=>{h=!1}},[e,s]);let u=Lt(()=>r===null?null:t?[{threadId:t},...r]:r,[t,r]),{names:c,saved:d,needsYou:p,unread:f}=Fk(u);return{orbit:t,threads:r,names:c,saved:d,needsYou:p,unread:f}}function L$({thread:e,now:t,onOpen:n}){let[r,o]=_(null),s=async a=>{o(null);try{await n(a)}catch(u){o(u instanceof Error?u.message:"Couldn't open the thread. Try again.")}},i=e.outcomes.slice(-3);return m("div",{className:"flex min-w-0 flex-col gap-0.5 text-sm",children:[i.map(a=>m("button",{type:"button",onClick:u=>{s(u.shiftKey)},className:"min-w-0 truncate text-left text-foreground",children:["\u21B3 ",a.text]},a.at)),l("button",{type:"button",onClick:a=>{s(a.shiftKey)},className:"text-left text-muted-foreground hover:text-foreground",children:Sh(e,t)}),r?l("span",{role:"alert",className:"text-xs text-destructive",children:r}):null]})}function M$(e){return e.length>=600?`${e}\u2026`:e}var xa="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-state-hover hover:text-foreground",D$=400,Vk=40,F$=6;function z$(e){return e.querySelector('[role="dialog"][aria-modal="true"], [role="alertdialog"]')!==null}function K$(e,t){let[n,r]=_(null),o=Y(null);K(()=>{if(e===null)return;let{clearOverride:a,seen:u}=hk(o.current,e,t);o.current=u,a&&r(null)},[e,t]);let s=n??(e?.length??0)>0,i=q(()=>r(!s),[s]);return{open:s,toggle:i}}function X$({orbit:e,thread:t,view:n,names:r,needsYou:o,phone:s,focusRequest:i,onSaved:a,go:u}){let c=On(t,o),d=n.kind==="full",p={kind:"beside",threadId:t.threadId},f=Y(null);return m("section",{"aria-label":"Thread","data-moonlet-pane":"thread",className:V("z-10 flex min-h-0 min-w-0 flex-col overflow-hidden bg-background",s?V("absolute inset-x-0 bottom-0",d?"top-0":"top-[44%] rounded-t-2xl shadow-[0_-14px_34px_-18px_color-mix(in_oklab,var(--foreground)_60%,transparent)]"):V("row-start-1",!d&&"border-l border-border bg-sidebar")),style:s?void 0:{gridColumn:d?"2 / 4":"3"},children:[s&&!d?l("button",{type:"button","aria-label":"Drag up for full screen, down to close",className:"relative h-5 shrink-0 touch-none after:absolute after:left-1/2 after:top-2 after:h-1 after:w-10 after:-translate-x-1/2 after:rounded-full after:bg-border",onPointerDown:h=>{f.current=h.clientY,h.currentTarget.setPointerCapture(h.pointerId)},onPointerUp:h=>{if(f.current===null)return;let g=h.clientY-f.current;f.current=null,g<-Vk||Math.abs(g)<F$?u({kind:"full",threadId:t.threadId}):g>Vk&&u(hn)}}):null,m("div",{className:V("flex min-h-12 shrink-0 items-center gap-1.5 border-b border-border pl-2 pr-2",s&&d&&"min-h-14 pt-2"),children:[d?l("button",{type:"button","aria-label":"Back to the conversation",className:xa,onClick:()=>u(s?hn:p),children:l(pe,{name:"ChevronLeft","aria-hidden":!0,className:"size-4"})}):null,l("span",{className:"pl-1",children:l(Uc,{mark:c,size:18})}),m("div",{className:"flex min-w-0 flex-1 flex-col",children:[l(zk,{threadId:t.threadId,title:la(t,r),onSaved:a},t.threadId),l("span",{className:"truncate px-2 text-xs text-muted-foreground",children:Fc[c]})]}),d?s?null:l("button",{type:"button","aria-label":"Put it beside the conversation",title:"Put it beside the conversation",className:xa,onClick:()=>u(p),children:l(pe,{name:"PanelRight","aria-hidden":!0,className:"size-4"})}):l("button",{type:"button","aria-label":"Full screen",title:"Full screen",className:xa,onClick:()=>u({kind:"full",threadId:t.threadId}),children:l(pe,{name:"Maximize2","aria-hidden":!0,className:"size-4"})}),l(Bc,{orbitThread:e,threadId:t.threadId,done:t.done}),d?null:l("button",{type:"button","aria-label":"Close thread",title:"Close thread",className:xa,onClick:()=>u(hn),children:l(pe,{name:"X","aria-hidden":!0,className:"size-4"})})]}),l("div",{className:"relative min-h-0 flex-1",children:l(Ef,{threadId:t.threadId,variant:"full",focusRequest:i,experimental_sendMode:"steer-if-active",leadingContent:l(H_,{className:"mb-4 px-2",content:M$(t.rootPreview)})},t.threadId)})]})}function Zk({subPath:e}){let[t,n]=_(null),r=J(),o=Ie(),{isCompactViewport:s}=j_(),{orbit:i,threads:a,names:u,saved:c,needsYou:d,unread:p}=O$(),f=Lt(()=>a??[],[a]),h=Lt(()=>a===null?null:fk(a,d),[a,d]),g=K$(h,d),x=ck(e),b=Y(x);b.current=x;let[v,w]=_(0),[C,y]=_(0),T=Y(null),[N,S]=_(()=>Date.now());K(()=>{let ue=setInterval(()=>S(Date.now()),6e4);return()=>clearInterval(ue)},[]),K(()=>_k(document),[]),ot(()=>{T.current?.(),T.current=null},[e]);let $=Lt(()=>new Map(f.map(ue=>[ue.rootSeq,ue])),[f]),P=q((ue,ze=ue.kind==="main"?"main":"thread")=>{let zt=b.current;ze==="main"?w(mt=>mt+1):y(mt=>mt+1),!uk(zt,ue)&&vk(document,pk(zt,ue),s,()=>{let mt=new Promise(vi=>{T.current=vi,setTimeout(vi,D$)}),gt=Mc(ue);return gt?o.toPluginPanel(At,{subPath:gt}):o.toPluginPanel(At),mt})},[o,s]),L=q((ue,ze)=>P(dk(b.current,ue,ze)),[P]),ne=q(()=>{let ue=b.current;P(ue.kind==="full"?Dc(ue):ue,"main")},[P]),se=Eh(x),_e=se===null?null:f.find(ue=>ue.threadId===se)??null,ie=Y(null);K(()=>{let ue=ie.current;ie.current=_e?{threadId:_e.threadId,done:_e.done}:null,_e?.done&&ue?.threadId===_e.threadId&&!ue.done&&P(hn)},[_e?.threadId,_e?.done,P]),K(()=>{let ue=ze=>{if(ze.key!=="Escape"||ze.defaultPrevented||ze.metaKey||ze.ctrlKey||ze.altKey||ze.shiftKey)return;let zt=b.current;zt.kind==="main"||z$(document)||(ze.preventDefault(),P(Dc(zt)))};return window.addEventListener("keydown",ue),()=>window.removeEventListener("keydown",ue)},[P]);let Q=Lt(()=>h?.map(ue=>ue.threadId)??[],[h]);K(()=>xk({toggleFull:()=>{let ue=b.current;ue.kind==="full"?P(Dc(ue)):ue.kind==="beside"?P({kind:"full",threadId:ue.threadId}):Q[0]&&P({kind:"full",threadId:Q[0]})},toggleList:()=>{s||g.toggle()},cycle:ue=>{let ze=mk(b.current,Q,ue);ze===null?P(hn):L(ze,!1)}}),[P,g,Q,L,s]);let j=q(async(ue,ze=!1)=>{if(!i)return;let zt=kh(ue),{threadId:mt}=await r.call("threads.open",{orbitThread:i,rootSeq:zt,forkAt:ue.sourceSeqEnd,rootText:ue.text});L(mt,ze)},[i,r,L]),G=Lt(()=>[{id:"reply-in-thread",title:"Reply in thread",icon:"MessageCirclePlus",run:ue=>j(ue)}],[j]),ee=q(ue=>{let ze=kh(ue),zt=$.get(ze);return zt?l(L$,{thread:zt,now:N,onOpen:mt=>j(ue,mt)}):null},[$,N,j]);if(i===void 0)return null;if(i===null)return m("div",{className:"mx-auto flex h-full max-w-[560px] flex-col justify-center gap-6 p-8 text-sm text-muted-foreground",children:[m("div",{className:"flex items-center gap-3",children:[l(Hk,{className:"size-12"}),l(Uk,{className:"text-4xl text-foreground"})]}),l("p",{className:"text-base",children:"There's no conversation with your moonlet yet. It starts once your moonlet has a machine to run on and its setup is finished."}),l(B$,{})]});let be=h??[],H=!s&&g.open,xe=x.kind==="full"&&p.has(i),Cr=be.length,Cn=x.kind==="main"?null:_e?l(X$,{orbit:i,thread:_e,view:x,names:u,needsYou:d,phone:s,focusRequest:C,onSaved:c,go:P}):a===null?null:m("section",{"aria-label":"Thread",className:"z-10 flex flex-col items-start gap-2 bg-background p-6 text-sm text-muted-foreground",style:s?void 0:{gridColumn:x.kind==="full"?"2 / 4":"3"},children:[l("p",{children:"This thread isn't on your moonlet's conversation."}),l("button",{type:"button",onClick:()=>P(hn),className:"underline hover:text-foreground",children:"Back to the main conversation"})]});return m("div",{className:V("relative h-full min-h-0 overflow-hidden",!s&&"grid grid-rows-[minmax(0,1fr)]"),style:s?void 0:{gridTemplateColumns:`${H?"16rem":"0px"} minmax(0, 1fr) ${x.kind==="beside"?"min(440px, 45%)":"0px"}`},children:[H?l(kk,{orbit:i,listed:be,names:u,needsYou:d,unread:p,view:x,mainUnread:xe,now:N,onMain:ne,onThread:(ue,ze)=>L(ue.threadId,ze)}):null,m("section",{"aria-label":"Main conversation","data-moonlet-pane":"main",className:V("flex min-h-0 min-w-0 flex-col bg-background",s?"absolute inset-0":"row-start-1",x.kind==="full"&&"invisible"),style:s?void 0:{gridColumn:"2"},children:[m("div",{className:V("flex min-h-12 shrink-0 items-center gap-2 border-b border-border px-2",s&&"min-h-14 pt-2"),children:[s?null:l("button",{type:"button",onClick:g.toggle,"aria-expanded":H,"aria-controls":Nh,"aria-label":H?"Hide threads":"Show threads",className:xa,children:l(pe,{name:"PanelLeft","aria-hidden":!0,className:"size-4"})}),l("span",{className:V(s&&"pl-2"),children:l(Ah,{size:20})}),m("div",{className:"flex min-w-0 flex-1 flex-col leading-tight",children:[l("span",{className:"truncate font-semibold",children:"Moonlet"}),l("span",{className:"truncate text-xs text-muted-foreground",children:Cr>0?`Main conversation \xB7 ${Cr} thread${Cr===1?"":"s"} open`:"Main conversation"})]})]}),s?l(Sk,{listed:be,names:u,needsYou:d,view:x,onThread:ue=>L(ue.threadId,!1)}):null,m("div",{ref:n,"data-orbit-chat":"",className:"relative min-h-0 flex-1",children:[l(jc,{threadId:i,container:t}),l(Vl,{name:ik,params:{threadId:i}}),x.kind==="full"?null:l(Ef,{experimental_sendMode:"steer-if-active",threadId:i,variant:"full",focusRequest:v,messageActions:G,experimental_messageFooter:ee})]})]}),Cn]})}function B$(){let e=J(),[t,n]=_(!1),[r,o]=_(null);return m("div",{className:"flex flex-col gap-1",children:[l("div",{children:l("button",{type:"button",className:"inline-flex h-9 items-center rounded-lg bg-primary px-4 font-semibold text-primary-foreground hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:opacity-60",disabled:t,onClick:()=>{n(!0),o(null),e.call("welcome.reopen",null).then(()=>n(!1),s=>{o(s instanceof Error?s.message:String(s)),n(!1)})},children:t?"Opening setup\u2026":"Finish setting up"})}),r&&l("p",{role:"alert",className:"text-destructive",children:r})]})}function Mh({threadId:e}){let t=J(),n=Y(null),r=Y(null),[o,s]=_(null),[i,a]=_("Connecting\u2026"),[u,c]=_(!1),[d,p]=_(0);return K(()=>{t.call("desktop.station",{threadId:e}).then(s,f=>a(f instanceof Error?f.message:String(f)))},[t,e,d]),K(()=>{if(!o?.station||!n.current)return;let f=`${location.origin.replace(/^http/,"ws")}/api/v1/plugins/orbit/http/desktop?station=${encodeURIComponent(o.station)}`,h=new yt(n.current,f,{shared:!0});return h.viewOnly=!0,h.scaleViewport=!0,h.resizeSession=!1,h.background="transparent",h.addEventListener("connect",()=>a("")),h.addEventListener("disconnect",g=>{let x=g.detail?.clean;a(x?"Disconnected.":`Couldn't reach ${o.station}'s desktop.`)}),r.current=h,c(!1),()=>{h.disconnect(),r.current=null}},[o,d]),K(()=>{r.current&&(r.current.viewOnly=!u)},[u]),o&&!o.station?l("p",{className:"p-3 text-sm text-muted-foreground",children:"The desktop is your moonlet's own computer, where its conversation and the work it starts run."}):m("div",{className:"flex h-full flex-col",children:[m("div",{className:"flex items-center gap-2 border-b px-3 py-2 text-xs",children:[l("span",{className:"font-medium",children:o?.station??"\u2026"}),l("span",{className:"flex-1 text-muted-foreground",children:i||(u?"You're in control: clicks and keys go to the desktop.":"Watching.")}),i?l(R,{size:"sm",variant:"secondary",onClick:()=>p(f=>f+1),children:"Retry"}):l(R,{size:"sm",variant:u?"destructive":"default",onClick:()=>c(f=>!f),children:u?"Give back control":"Take control"})]}),l("div",{ref:n,className:"min-h-0 flex-1 bg-black"})]})}function Wk(e){let t=os();return t===void 0?null:t===null?l("p",{className:"p-3 text-sm text-muted-foreground",children:"There's no conversation with your moonlet yet, so there's no desktop to show."}):l(Mh,{threadId:t},t)}var ba=/^[a-z0-9_-][a-z0-9._-]{0,63}$/;var Ze="inbox";var Qk=1e3;var ya=400,Qc=e=>e.normalize("NFC").toLowerCase();var U$=["kind","project","conversation","tag","modified","by","subfolders"],H$=new Map([["page","html"],["html","html"],["md","md"],["markdown","md"]]),V$=new Map([["you","owner"],["owner","owner"],["me","owner"],["assistant","assistant"],["moonlet","assistant"]]),Z$=/^\d{4}-\d{2}-\d{2}$/;function Fh(e){let t=[],n=/(\S+?:"[^"]*"?|"[^"]*"?|\S+)/g;for(let r of e.slice(0,ya).matchAll(n))t.push(r[1]);return t}var Dh=e=>e.replace(/^"|"$/g,"");function Gk(e){if(!Z$.test(e))return!1;let t=Date.parse(`${e}T00:00:00Z`);return!Number.isNaN(t)&&new Date(t).toISOString().slice(0,10)===e}function W$(e){let t=e.toLowerCase();if(t==="today")return{kind:"today"};let n=/^<?(\d{1,4})d$/.exec(t);if(n)return{kind:"within",days:Number(n[1])};let r=/^>(\d{1,4})d$/.exec(t);if(r)return{kind:"older",days:Number(r[1])};let[o,s]=t.split("..");return o&&Gk(o)&&(s===void 0||Gk(s))?{kind:"range",from:o,to:s??o}:null}function Gc(e){let t={text:[],kinds:[],projects:[],conversations:[],tags:[],modified:null,by:null,subfolders:!1,problems:[]};for(let n of Fh(e)){let r=/^([a-z]+):(.*)$/i.exec(n),o=r?.[1]?.toLowerCase()??"";if(!r||!U$.includes(o)){let i=Qc(Dh(n).trim());i&&t.text.push(i.slice(0,100));continue}let s=Dh(r[2]).trim();if(s)switch(o){case"kind":{let i=H$.get(s.toLowerCase());i?t.kinds.includes(i)||t.kinds.push(i):t.problems.push(`kind:${s} isn't a kind (page or md)`);break}case"project":t.projects.push(Qc(s).slice(0,100));break;case"conversation":t.conversations.push(Qc(s).slice(0,100));break;case"tag":{let i=s.toLowerCase();ba.test(i)?t.tags.includes(i)||t.tags.push(i):t.problems.push(`tag:${s} isn't a tag`);break}case"modified":{let i=W$(s);i?t.modified=i:t.problems.push(`modified:${s} isn't a time (today, 7d, <30d, >90d or 2026-11-01..2026-11-20)`);break}case"by":{let i=V$.get(s.toLowerCase());i?t.by=i:t.problems.push(`by:${s} isn't you or assistant`);break}case"subfolders":t.subfolders=/^(yes|true|on|1)$/i.test(s);break}}return t}function _a(e){return!!(e.text.length||e.kinds.length||e.projects.length||e.conversations.length||e.tags.length||e.modified||e.by)}var WK=360*60*1e3;var j$=e=>/[\s"]/.test(e)?`"${e.replace(/"/g,"")}"`:e;function va(e,t,n){return[...Fh(e).filter(o=>!o.toLowerCase().startsWith(`${t}:`)),...n?[`${t}:${j$(n)}`]:[]].join(" ")}function Yk(e,t){let n=Fh(e).filter(r=>r.toLowerCase().startsWith(`${t}:`)).at(-1);return n?Dh(n.slice(t.length+1)):null}var qk=["name","modified","conversation","versions","size"],G$="JOIN artifact_versions v ON v.page_id = g.id AND v.n = (SELECT MAX(n) FROM artifact_versions m WHERE m.page_id = g.id)",r5=`SELECT p.path, g.thread_id, g.file, g.kind, g.project_id, g.thread_title, g.file_gone, g.thread_gone, g.canonical,
66
+ `,iK={gutter:`${Vr} > ${ar} > ${os}:not(${Mh})`,avatar:`${Vr} > ${ar} > ${Wc}[${Mn}]`};function $$(e){return!e||!/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/.test(e)?null:`url("${e}")`}function Lk(e,t,n=null,r){let o=$$(t);if(!o&&!n)return()=>{};let s=()=>r??e.querySelector(Dh),i=r??e.documentElement,a=e.createElement("style");a.id=E$,a.textContent=R$,e.head.append(a),o&&(i.style.setProperty(Oh,o),i.setAttribute(jc,""));let u=e.defaultView,c=u?new u.Image:null,d=T=>console.warn(`[Moonlet avatar] ${T}`);c&&o&&(c.onerror=()=>d("The saved avatar could not be loaded. Check the page image policy and the saved picture."),c.src=t);let p=!1,f=null,h=null,g=null,x=()=>{if(!h)return;let T=h.querySelector(`${Lh} ${os}`),y=h.querySelector(Pk);T&&!y&&!p&&f===null&&(f=setTimeout(()=>{f=null,h?.querySelector(`${Lh} ${os}`)&&!h.querySelector(Pk)&&(p=!0,d("Chat rows no longer match Moonlet's avatar layout. Update the chat avatar selectors for this Moonlet version."))},2e3))},b=()=>{let T=s();T!==h&&(g?.(),h=T,g=h?Ik(h,n,a,x):null,x())};b();let _=T=>{let y=T.effectiveDirective;(y==="img-src"||y==="style-src-elem"||y==="style-src-attr")&&d("The page policy blocked an image or style while the chat avatar was active. Check the browser policy report.")};e.addEventListener("securitypolicyviolation",_),a.sheet||d("The avatar stylesheet was not applied. Check the page style policy.");let w=new(u?.MutationObserver??MutationObserver)(()=>{h?.isConnected||b()});return r||w.observe(e.body,{childList:!0,subtree:!0}),()=>{w.disconnect(),e.removeEventListener("securitypolicyviolation",_),g?.(),f!==null&&clearTimeout(f),c&&(c.onerror=null),a.remove(),i.removeAttribute(jc),i.style.removeProperty(Oh)}}var xa="data-orbit-chat-width",I$="orbit-chat-width",Mk="#thread-detail-timeline-panel > div > [data-thread-window]",Dk=["> div > div > [data-page-scroll-viewport] > div > .max-w-\\[760px\\]","> div > div > [data-page-scroll-viewport] > div > [data-scroll-footer] > div > .max-w-\\[760px\\]"],P$=Dk.map(e=>`${Mk}[${xa}] ${e}`).join(`,
67
+ `),O$=`${P$} { max-width: ${Ok}px; }`,Ph=new WeakSet;function Fk(e,t){if(!t)return()=>{};let n=e.createElement("style");n.id=I$,n.textContent=O$,e.head.append(n);let r=null,o=null,s=()=>{let c=e.querySelector(Mk);c!==r&&(r?.removeAttribute(xa),r=c);let d=!!(r&&Dk.every(p=>r.querySelector(`:scope ${p}`)));return r?.hasAttribute(xa)!==d&&r?.toggleAttribute(xa,d),d},i=()=>{s()?(o!==null&&clearTimeout(o),o=null):!Ph.has(e)&&o===null&&(o=setTimeout(()=>{o=null,!s()&&!Ph.has(e)&&(Ph.add(e),console.warn(`[Moonlet chat width] The chat column no longer matches this Moonlet version. The ${Ok}px width could not be applied. Update the column selector in chat-avatar-style.ts.`))},2e3))};i();let a=e.defaultView,u=new(a?.MutationObserver??MutationObserver)(i);return u.observe(e.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","data-page-scroll-viewport","data-thread-window"]}),()=>{u.disconnect(),o!==null&&clearTimeout(o),r?.removeAttribute(xa),n.remove()}}function Qc({threadId:e,container:t}={}){let n=q_(),r=e??n.threadId,o=J(),[s,i]=v({threadId:null,url:null,isOrbitThread:!1,name:null}),a=s.threadId===r?s.url:null,u=ev(),[c,d]=v(0),p=q(()=>d(g=>g+1),[]);ke("config",p),M(()=>{if(!r){i({threadId:null,url:null,isOrbitThread:!1,name:null});return}let g=!0;return o.call("avatar.forThread",{threadId:r}).then(x=>{g&&i({threadId:r,url:x.url,isOrbitThread:x.isOrbitThread,name:x.name})},()=>{g&&(i({threadId:r,url:null,isOrbitThread:!1,name:null}),console.warn("[Moonlet avatar] Could not read the avatar for this conversation. It will be checked again after reconnecting or saving preferences."))}),()=>{g=!1}},[o,r,c,u]);let f=s.threadId===r?s.name:null,h=s.threadId===r&&s.isOrbitThread;return Ye(()=>{if(t===null)return;let g=Lk(document,a,f,t),x=Fk(document,h&&t===void 0);return()=>{g(),x()}},[r,a,f,h,t]),null}var L$=new Set(["title-changed","interactions-changed","read-state-changed","status-changed"]),zk=new Set;function Kk(e){let t=dn(),[n,r]=v(new Map),[o,s]=v(zk),[i,a]=v(zk),[u,c]=v(0),d=Lt(()=>e?.map(h=>h.threadId)??[],[e]),p=q(()=>c(h=>h+1),[]);M(()=>{let h=t.subscribe({event:"thread:changed",callback:x=>{x.changes.some(b=>L$.has(b))&&(!x.id||d.includes(x.id))&&p()}}),g=t.subscribe({event:"realtime:connection",callback:x=>{x.state==="connected"&&p()}});return()=>{h(),g()}},[t,d,p]),M(()=>{let h=new AbortController,g=!0;return(async()=>{let x=new Map,b=new Set,_=new Set;try{for(let w=0;w<d.length;w+=200){if(!g)return;let T=await t.threads.list({threadIds:d.slice(w,w+200),includeHidden:!0,limit:200,signal:h.signal});for(let y of T)y.title&&x.set(y.id,y.title),y.hasPendingInteraction&&b.add(y.id),(y.lastReadAt??0)<y.latestAttentionAt&&_.add(y.id)}if(!g)return;r(x),s(b),a(_)}catch{g&&r(w=>new Map(d.flatMap(T=>{let y=w.get(T);return y===void 0?[]:[[T,y]]})))}})(),()=>{g=!1,h.abort()}},[t,d,u]);let f=q((h,g)=>{r(x=>new Map(x).set(h,g)),p()},[p]);return{names:n,saved:f,needsYou:o,unread:i}}function Xk({threadId:e,title:t,onSaved:n}){let r=dn(),[o,s]=v(!1),[i,a]=v(t),[u,c]=v(!1),[d,p]=v(null),f=G(null),h=G(null),g=G(!1),x=G(!0),b=G(!1);M(()=>(x.current=!0,()=>{x.current=!1}),[]),M(()=>{o?(f.current?.focus(),f.current?.select()):b.current&&(b.current=!1,h.current?.focus())},[o]);let _=()=>{b.current=!0,s(!1),p(null)},w=async()=>{let T=i.trim();if(!(g.current||!T)){g.current=!0,c(!0),p(null);try{await r.threads.update({threadId:e,title:T}),x.current&&(n(e,T),_())}catch(y){x.current&&p(y instanceof Error?y.message:"Couldn't save the title. Try again.")}finally{g.current=!1,x.current&&c(!1)}}};return o?m("form",{className:"flex min-w-0 flex-1 flex-col gap-1",onSubmit:T=>{T.preventDefault(),w()},onKeyDown:T=>{T.key==="Escape"&&!g.current&&(T.preventDefault(),_())},children:[m("div",{className:"flex min-w-0 items-center gap-2",children:[l("input",{ref:f,"aria-label":"Title",className:"min-w-0 flex-1 rounded-md border border-border bg-background px-2 py-1 text-sm",value:i,disabled:u,onChange:T=>a(T.target.value)}),l("button",{type:"submit",disabled:u||!i.trim(),"aria-busy":u,className:"rounded-md px-2 py-1 text-xs disabled:opacity-50",children:u?"Saving\u2026":"Save title"}),l("button",{type:"button",disabled:u,className:"rounded-md px-2 py-1 text-xs disabled:opacity-50",onClick:_,children:"Cancel"})]}),d?l("span",{role:"alert",className:"text-xs text-destructive",children:d}):null]}):m("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[l("span",{className:"truncate text-sm font-medium",children:t}),l("button",{ref:h,type:"button","aria-label":"Rename",className:"shrink-0 rounded-md px-2 py-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>{a(t),s(!0)},children:"Rename"})]})}var Bk={light:"#f6cf79",gold:"#e2b04d",deep:"#c2871f",crater:"#d9a035","crater-shadow":"#b47a1c","crater-rim":"#ffe08f",shade:"#303d77",rim:"#425090","shade-crater":"#2c3766",ink:"#222940",shine:"#f5f8fd"},Uk=[["gold","M32 4A28 28 0 0 0 32 60A15 28 0 0 0 32 4Z"],["light","M7.75 46A28 28 0 0 1 30.05 4.07A33.76 33.76 0 0 0 7.75 46Z"],["deep","M32 4A14 28 0 0 1 32 60A8.8 28 0 0 0 32 4Z"],["crater","M18.11 19.84A2.8 4.3 -138.81 1 0 13.89 16.16A2.8 4.3 -138.81 1 0 18.11 19.84Z"],["crater-shadow","M12.75 20.7A5.02 5.02 0 0 1 18.59 14.58A7.77 7.77 0 0 0 12.75 20.7Z"],["crater-rim","M19.44 15.78A5.34 5.34 0 0 1 13.87 21.62A7.25 7.25 0 0 0 19.44 15.78Z"],["crater","M26.8 11.68A1.22 2 -104.35 1 0 26.2 9.32A1.22 2 -104.35 1 0 26.8 11.68Z"],["crater-shadow","M24.79 11.38A1.98 1.98 0 0 1 27.77 9.35A2.98 2.98 0 0 0 24.79 11.38Z"],["crater-rim","M28.35 9.79A2.07 2.07 0 0 1 25.51 11.73A2.78 2.78 0 0 0 28.35 9.79Z"],["crater","M11.87 39.02A1.45 2.5 160.77 1 0 9.13 39.98A1.45 2.5 160.77 1 0 11.87 39.02Z"],["crater-shadow","M9.4 40.6A1.7 1.7 0 1 1 11.13 37.73A1.9 1.9 0 0 0 9.4 40.6Z"],["crater-rim","M11.78 38.79A1.6 1.6 0 0 1 10.13 41.53A1.79 1.79 0 0 0 11.78 38.79Z"],["crater","M22.81 50.83A1.86 3.2 116 1 0 21.19 54.17A1.86 3.2 116 1 0 22.81 50.83Z"],["crater-shadow","M19.89 53.28A2.07 2.07 0 1 1 23.25 51.07A2.17 2.17 0 0 0 19.89 53.28Z"],["crater-rim","M24.44 52.09A1.92 1.92 0 1 1 21.24 54.19A2.05 2.05 0 0 0 24.44 52.09Z"],["crater","M37.13 49.25A1.3 1.8 73.44 1 0 37.87 51.75A1.3 1.8 73.44 1 0 37.13 49.25Z"],["crater-shadow","M35.98 51.38A1.78 1.78 0 0 1 38.62 49.32A2.57 2.57 0 0 0 35.98 51.38Z"],["crater-rim","M39.15 49.81A1.84 1.84 0 0 1 36.63 51.78A2.4 2.4 0 0 0 39.15 49.81Z"],["shade","M32 4A28 28 0 0 1 32 60A14 28 0 0 0 32 4Z"],["rim","M32 4A28 28 0 0 1 32 60A25.6 28 0 0 0 32 4Z"],["shade-crater","M48.91 24.57A1.41 2 -23.73 1 0 51.49 23.43A1.41 2 -23.73 1 0 48.91 24.57Z"],["shade-crater","M50.3 41.53A1.01 1.6 27.51 1 0 52.1 42.47A1.01 1.6 27.51 1 0 50.3 41.53Z"],["ink","M17.5 32.6a3.5 4.5 0 1 0 7 0a3.5 4.5 0 1 0 -7 0Z"],["shine","M18.88 31.47A1.05 1.44 -28 1 0 20.74 30.49A1.05 1.44 -28 1 0 18.88 31.47Z"],["ink","M32.5 32.6a3.5 4.5 0 1 0 7 0a3.5 4.5 0 1 0 -7 0Z"],["shine","M33.88 31.47A1.05 1.44 -28 1 0 35.74 30.49A1.05 1.44 -28 1 0 33.88 31.47Z"]];var M$="var(--moonlet-lamp, currentColor)",Hk="h-[0.54em] w-[0.54em] shrink-0 translate-y-[0.03em]";function Vk({className:e}){return m("span",{role:"img","aria-label":"Moonlet",className:V("inline-flex items-baseline font-extrabold leading-none tracking-tight",e),children:[l("span",{"aria-hidden":"true",children:"m"}),l("svg",{"aria-hidden":"true",viewBox:"0 0 14 14",className:V(Hk,"ml-[0.035em] mr-[0.02em]"),children:l("circle",{cx:"7",cy:"7",r:"5.5",fill:"none",stroke:"currentColor",strokeWidth:"3"})}),l("svg",{"aria-hidden":"true",viewBox:"0 0 14 14",className:V(Hk,"ml-[0.02em] mr-[0.035em]"),children:l("circle",{cx:"7",cy:"7",r:"7",fill:M$})}),l("span",{"aria-hidden":"true",children:"nlet"})]})}function Zk({className:e}){return l("svg",{"aria-hidden":"true",viewBox:"0 0 64 64",className:V("shrink-0",e),children:Uk.map(([t,n])=>l("path",{fill:`var(--moonlet-moon-${t}, ${Bk[t]})`,d:n},n))})}var Jt={list:{key:"moonlet.home.threads-list-width",initial:256,min:200,max:400,controls:"moonlet-threads-list",label:"Resize conversations list"},thread:{key:"moonlet.home.thread-width",initial:440,min:280,max:800,controls:"moonlet-thread-pane",label:"Resize conversation pane"}},Gc=(e,t,n)=>Math.min(n,Math.max(t,e));function Wk(e){let t=Jt[e];try{let n=window.localStorage.getItem(t.key),r=n===null||n.trim()===""?NaN:Number(n);if(Number.isFinite(r))return Gc(r,t.min,t.max)}catch{}return t.initial}function jk({phone:e,listOpen:t,beside:n,children:r}){let o=G(null),[s,i]=v(()=>window.innerWidth),[a,u]=v(()=>({list:Wk("list"),thread:Wk("thread")})),[c,d]=v(!1),p=G(null),f=Math.min(Jt.list.min,s*.25),h=Math.min(Jt.thread.min,s*.35),g=Math.min(320,s-(t?f:0)-(n?h:0)),x=t?Gc(a.list,f,Math.min(Jt.list.max,s-g-(n?h:0))):0,b=n?Gc(a.thread,h,Math.min(Jt.thread.max,s-g-x)):0,_={list:{min:f,max:Math.min(Jt.list.max,s-g-b),value:x},thread:{min:h,max:Math.min(Jt.thread.max,s-g-x),value:b}};Ye(()=>{let E=o.current;if(!E||e)return;let k=()=>i(E.getBoundingClientRect().width||window.innerWidth);k();let N=typeof ResizeObserver>"u"?null:new ResizeObserver(k);return N?.observe(E),window.addEventListener("resize",k),()=>{N?.disconnect(),window.removeEventListener("resize",k)}},[e]),M(()=>{for(let E of["list","thread"])try{window.localStorage.setItem(Jt[E].key,String(a[E]))}catch{}},[a]);let w=()=>{p.current=null,d(!1)};M(()=>{if(!c)return;let{cursor:E,userSelect:k}=document.body.style;return document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("blur",w),()=>{document.body.style.cursor=E,document.body.style.userSelect=k,window.removeEventListener("blur",w)}},[c]),M(w,[e,t,n]);let T=(E,k)=>u(N=>({...N,[E]:Gc(k,_[E].min,_[E].max)})),y=E=>l("div",{role:"separator",tabIndex:0,"aria-label":Jt[E].label,"aria-controls":Jt[E].controls,"aria-orientation":"vertical","aria-valuemin":Math.round(_[E].min),"aria-valuemax":Math.round(_[E].max),"aria-valuenow":Math.round(_[E].value),"aria-valuetext":`${Math.round(_[E].value)} pixels`,title:"Drag to resize. Arrow keys adjust width; double-click to reset.",className:"group absolute inset-y-0 z-30 flex w-3 cursor-col-resize touch-none select-none items-center justify-center outline-none hover:bg-primary/10 focus-visible:bg-primary/10 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",style:E==="list"?{left:x-6}:{right:b-6},onPointerDown:k=>{!k.isPrimary||k.button!==0||(k.preventDefault(),k.currentTarget.focus(),k.currentTarget.setPointerCapture(k.pointerId),p.current={pane:E,pointerId:k.pointerId,startX:k.clientX,startWidth:_[E].value},d(!0))},onPointerMove:k=>{let N=p.current;!N||N.pane!==E||N.pointerId!==k.pointerId||T(E,N.startWidth+(k.clientX-N.startX)*(E==="list"?1:-1))},onPointerUp:k=>{p.current?.pointerId===k.pointerId&&(w(),k.currentTarget.releasePointerCapture(k.pointerId))},onPointerCancel:w,onLostPointerCapture:w,onDoubleClick:()=>u(k=>({...k,[E]:Jt[E].initial})),onKeyDown:k=>{if(k.key!=="ArrowLeft"&&k.key!=="ArrowRight")return;k.preventDefault();let N=(k.key==="ArrowRight"?1:-1)*(E==="list"?1:-1);T(E,_[E].value+N*(k.shiftKey?40:10))},children:l("span",{"aria-hidden":"true",className:"h-8 w-1 rounded-full bg-muted-foreground/50 group-hover:bg-primary group-focus-visible:bg-primary"})},E);return m("div",{ref:o,"data-moonlet-layout":"",className:`relative h-full min-h-0 overflow-hidden${e?"":" grid grid-rows-[minmax(0,1fr)]"}`,style:e?void 0:{gridTemplateColumns:`${x}px minmax(0, 1fr) ${b}px`},children:[r,!e&&t?y("list"):null,!e&&n?y("thread"):null,c?l("div",{className:"absolute inset-0 z-20 cursor-col-resize"}):null]})}function ss(){let e=J(),[t,n]=v(void 0),[r,o]=v(0);return ke("config",q(()=>o(s=>s+1),[])),M(()=>{let s=!0;return e.call("threads.home",null).then(({orbitThread:i})=>{s&&n(i)},()=>{s&&n(i=>i??null)}),()=>{s=!1}},[e,r]),t}function F$(){let e=J(),[t,n]=v(void 0),[r,o]=v(null),[s,i]=v(0),a=q(()=>i(h=>h+1),[]);ke("threads",a),ke("config",a),M(()=>{let h=!0;return(async()=>{try{let{orbitThread:g}=await e.call("threads.home",null);if(!h)return;if(n(g),!g)return o([]);let x=await e.call("threads.list",{orbitThread:g});h&&o(x.threads)}catch{h&&(n(g=>g??null),o(g=>g??[]))}})(),()=>{h=!1}},[e,s]);let u=Lt(()=>r===null?null:t?[{threadId:t},...r]:r,[t,r]),{names:c,saved:d,needsYou:p,unread:f}=Kk(u);return{orbit:t,threads:r,names:c,saved:d,needsYou:p,unread:f}}function z$({thread:e,now:t,onOpen:n}){let[r,o]=v(null),s=async a=>{o(null);try{await n(a)}catch(u){o(u instanceof Error?u.message:"Couldn't open the thread. Try again.")}},i=e.outcomes.slice(-3);return m("div",{className:"flex min-w-0 flex-col gap-0.5 text-sm",children:[i.map(a=>m("button",{type:"button",onClick:u=>{s(u.shiftKey)},className:"min-w-0 truncate text-left text-foreground",children:["\u21B3 ",a.text]},a.at)),l("button",{type:"button",onClick:a=>{s(a.shiftKey)},className:"text-left text-muted-foreground hover:text-foreground",children:Nh(e,t)}),r?l("span",{role:"alert",className:"text-xs text-destructive",children:r}):null]})}function K$(e){return e.length>=600?`${e}\u2026`:e}var ba="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-state-hover hover:text-foreground",X$=400,Qk=40,B$=6;function U$(e){return e.querySelector('[role="dialog"][aria-modal="true"], [role="alertdialog"]')!==null}function H$(e,t){let[n,r]=v(null),o=G(null);M(()=>{if(e===null)return;let{clearOverride:a,seen:u}=gk(o.current,e,t);o.current=u,a&&r(null)},[e,t]);let s=n??(e?.length??0)>0,i=q(()=>r(!s),[s]);return{open:s,toggle:i}}function V$({orbit:e,thread:t,view:n,names:r,needsYou:o,phone:s,focusRequest:i,onSaved:a,go:u}){let c=Ln(t,o),d=n.kind==="full",p={kind:"beside",threadId:t.threadId},f=G(null);return m("section",{"aria-label":"Thread",id:"moonlet-thread-pane","data-moonlet-pane":"thread",className:V("z-10 flex min-h-0 min-w-0 flex-col overflow-hidden bg-background",s?V("absolute inset-x-0 bottom-0",d?"top-0":"top-[44%] rounded-t-2xl shadow-[0_-14px_34px_-18px_color-mix(in_oklab,var(--foreground)_60%,transparent)]"):V("row-start-1",!d&&"border-l border-border bg-sidebar")),style:s?void 0:{gridColumn:d?"2 / 4":"3"},children:[s&&!d?l("button",{type:"button","aria-label":"Drag up for full screen, down to close",className:"relative h-5 shrink-0 touch-none after:absolute after:left-1/2 after:top-2 after:h-1 after:w-10 after:-translate-x-1/2 after:rounded-full after:bg-border",onPointerDown:h=>{f.current=h.clientY,h.currentTarget.setPointerCapture(h.pointerId)},onPointerUp:h=>{if(f.current===null)return;let g=h.clientY-f.current;f.current=null,g<-Qk||Math.abs(g)<B$?u({kind:"full",threadId:t.threadId}):g>Qk&&u(mn)}}):null,m("div",{className:V("flex min-h-12 shrink-0 items-center gap-1.5 border-b border-border pl-2 pr-2",s&&d&&"min-h-14 pt-2"),children:[d?l("button",{type:"button","aria-label":"Back to the conversation",className:ba,onClick:()=>u(s?mn:p),children:l(pe,{name:"ChevronLeft","aria-hidden":!0,className:"size-4"})}):null,l("span",{className:"pl-1",children:l(Hc,{mark:c,size:18})}),m("div",{className:"flex min-w-0 flex-1 flex-col",children:[l(Xk,{threadId:t.threadId,title:ca(t,r),onSaved:a},t.threadId),l("span",{className:"truncate px-2 text-xs text-muted-foreground",children:zc[c]})]}),d?s?null:l("button",{type:"button","aria-label":"Put it beside the conversation",title:"Put it beside the conversation",className:ba,onClick:()=>u(p),children:l(pe,{name:"PanelRight","aria-hidden":!0,className:"size-4"})}):l("button",{type:"button","aria-label":"Full screen",title:"Full screen",className:ba,onClick:()=>u({kind:"full",threadId:t.threadId}),children:l(pe,{name:"Maximize2","aria-hidden":!0,className:"size-4"})}),l(Uc,{orbitThread:e,threadId:t.threadId,done:t.done}),d?null:l("button",{type:"button","aria-label":"Close thread",title:"Close thread",className:ba,onClick:()=>u(mn),children:l(pe,{name:"X","aria-hidden":!0,className:"size-4"})})]}),l("div",{className:"relative min-h-0 flex-1",children:l(Af,{threadId:t.threadId,variant:"full",focusRequest:i,experimental_sendMode:"steer-if-active",leadingContent:l(Z_,{className:"mb-4 px-2",content:K$(t.rootPreview)})},t.threadId)})]})}function Gk({subPath:e}){let[t,n]=v(null),r=J(),o=Ie(),{isCompactViewport:s}=G_(),{orbit:i,threads:a,names:u,saved:c,needsYou:d,unread:p}=F$(),f=Lt(()=>a??[],[a]),h=Lt(()=>a===null?null:mk(a,d),[a,d]),g=H$(h,d),x=dk(e),b=G(x);b.current=x;let[_,w]=v(0),[T,y]=v(0),E=G(null),[k,N]=v(()=>Date.now());M(()=>{let ue=setInterval(()=>N(Date.now()),6e4);return()=>clearInterval(ue)},[]),M(()=>wk(document),[]),Ye(()=>{E.current?.(),E.current=null},[e]);let $=Lt(()=>new Map(f.map(ue=>[ue.rootSeq,ue])),[f]),P=q((ue,ze=ue.kind==="main"?"main":"thread")=>{let zt=b.current;ze==="main"?w(mt=>mt+1):y(mt=>mt+1),!pk(zt,ue)&&kk(document,hk(zt,ue),s,()=>{let mt=new Promise(wi=>{E.current=wi,setTimeout(wi,X$)}),gt=Dc(ue);return gt?o.toPluginPanel(At,{subPath:gt}):o.toPluginPanel(At),mt})},[o,s]),L=q((ue,ze)=>P(fk(b.current,ue,ze)),[P]),ne=q(()=>{let ue=b.current;P(ue.kind==="full"?Fc(ue):ue,"main")},[P]),se=Ah(x),_e=se===null?null:f.find(ue=>ue.threadId===se)??null,ie=G(null);M(()=>{let ue=ie.current;ie.current=_e?{threadId:_e.threadId,done:_e.done}:null,_e?.done&&ue?.threadId===_e.threadId&&!ue.done&&P(mn)},[_e?.threadId,_e?.done,P]),M(()=>{let ue=ze=>{if(ze.key!=="Escape"||ze.defaultPrevented||ze.metaKey||ze.ctrlKey||ze.altKey||ze.shiftKey)return;let zt=b.current;zt.kind==="main"||U$(document)||(ze.preventDefault(),P(Fc(zt)))};return window.addEventListener("keydown",ue),()=>window.removeEventListener("keydown",ue)},[P]);let Q=Lt(()=>h?.map(ue=>ue.threadId)??[],[h]);M(()=>yk({toggleFull:()=>{let ue=b.current;ue.kind==="full"?P(Fc(ue)):ue.kind==="beside"?P({kind:"full",threadId:ue.threadId}):Q[0]&&P({kind:"full",threadId:Q[0]})},toggleList:()=>{s||g.toggle()},cycle:ue=>{let ze=xk(b.current,Q,ue);ze===null?P(mn):L(ze,!1)}}),[P,g,Q,L,s]);let j=q(async(ue,ze=!1)=>{if(!i)return;let zt=Eh(ue),{threadId:mt}=await r.call("threads.open",{orbitThread:i,rootSeq:zt,forkAt:ue.sourceSeqEnd,rootText:ue.text});L(mt,ze)},[i,r,L]),Y=Lt(()=>[{id:"reply-in-thread",title:"Reply in thread",icon:"MessageCirclePlus",run:ue=>j(ue)}],[j]),ee=q(ue=>{let ze=Eh(ue),zt=$.get(ze);return zt?l(z$,{thread:zt,now:k,onOpen:mt=>j(ue,mt)}):null},[$,k,j]);if(i===void 0)return null;if(i===null)return m("div",{className:"mx-auto flex h-full max-w-[560px] flex-col justify-center gap-6 p-8 text-sm text-muted-foreground",children:[m("div",{className:"flex items-center gap-3",children:[l(Zk,{className:"size-12"}),l(Vk,{className:"text-4xl text-foreground"})]}),l("p",{className:"text-base",children:"There's no conversation with your moonlet yet. It starts once your moonlet has a machine to run on and its setup is finished."}),l(Z$,{})]});let be=h??[],H=!s&&g.open,xe=x.kind==="full"&&p.has(i),Tr=be.length,Tn=x.kind==="main"?null:_e?l(V$,{orbit:i,thread:_e,view:x,names:u,needsYou:d,phone:s,focusRequest:T,onSaved:c,go:P}):a===null?null:m("section",{"aria-label":"Thread",id:"moonlet-thread-pane",className:"z-10 flex flex-col items-start gap-2 bg-background p-6 text-sm text-muted-foreground",style:s?void 0:{gridColumn:x.kind==="full"?"2 / 4":"3"},children:[l("p",{children:"This thread isn't on your moonlet's conversation."}),l("button",{type:"button",onClick:()=>P(mn),className:"underline hover:text-foreground",children:"Back to the main conversation"})]});return m(jk,{phone:s,listOpen:H,beside:x.kind==="beside",children:[H?l(Ek,{orbit:i,listed:be,names:u,needsYou:d,unread:p,view:x,mainUnread:xe,now:k,onMain:ne,onThread:(ue,ze)=>L(ue.threadId,ze)}):null,m("section",{"aria-label":"Main conversation","data-moonlet-pane":"main",className:V("isolate flex min-h-0 min-w-0 flex-col bg-background",s?"absolute inset-0":"row-start-1",x.kind==="full"&&"invisible"),style:s?void 0:{gridColumn:"2"},children:[m("div",{className:V("flex min-h-12 shrink-0 items-center gap-2 border-b border-border px-2",s&&"min-h-14 pt-2"),children:[s?null:l("button",{type:"button",onClick:g.toggle,"aria-expanded":H,"aria-controls":Ch,"aria-label":H?"Hide threads":"Show threads",className:ba,children:l(pe,{name:"PanelLeft","aria-hidden":!0,className:"size-4"})}),l("span",{className:V(s&&"pl-2"),children:l(Th,{size:20})}),m("div",{className:"flex min-w-0 flex-1 flex-col leading-tight",children:[l("span",{className:"truncate font-semibold",children:"Moonlet"}),l("span",{className:"truncate text-xs text-muted-foreground",children:Tr>0?`Main conversation \xB7 ${Tr} thread${Tr===1?"":"s"} open`:"Main conversation"})]})]}),s?l(Nk,{listed:be,names:u,needsYou:d,view:x,onThread:ue=>L(ue.threadId,!1)}):null,m("div",{ref:n,"data-orbit-chat":"",className:"relative min-h-0 flex-1",children:[l(Qc,{threadId:i,container:t}),l(Zl,{name:lk,params:{threadId:i}}),x.kind==="full"?null:l(Af,{experimental_sendMode:"steer-if-active",threadId:i,variant:"full",focusRequest:_,messageActions:Y,experimental_messageFooter:ee})]})]}),Tn]})}function Z$(){let e=J(),[t,n]=v(!1),[r,o]=v(null);return m("div",{className:"flex flex-col gap-1",children:[l("div",{children:l("button",{type:"button",className:"inline-flex h-9 items-center rounded-lg bg-primary px-4 font-semibold text-primary-foreground hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:opacity-60",disabled:t,onClick:()=>{n(!0),o(null),e.call("welcome.reopen",null).then(()=>n(!1),s=>{o(s instanceof Error?s.message:String(s)),n(!1)})},children:t?"Opening setup\u2026":"Finish setting up"})}),r&&l("p",{role:"alert",className:"text-destructive",children:r})]})}function Fh({threadId:e}){let t=J(),n=G(null),r=G(null),[o,s]=v(null),[i,a]=v("Connecting\u2026"),[u,c]=v(!1),[d,p]=v(0);return M(()=>{t.call("desktop.station",{threadId:e}).then(s,f=>a(f instanceof Error?f.message:String(f)))},[t,e,d]),M(()=>{if(!o?.station||!n.current)return;let f=`${location.origin.replace(/^http/,"ws")}/api/v1/plugins/orbit/http/desktop?station=${encodeURIComponent(o.station)}`,h=new yt(n.current,f,{shared:!0});return h.viewOnly=!0,h.scaleViewport=!0,h.resizeSession=!1,h.background="transparent",h.addEventListener("connect",()=>a("")),h.addEventListener("disconnect",g=>{let x=g.detail?.clean;a(x?"Disconnected.":`Couldn't reach ${o.station}'s desktop.`)}),r.current=h,c(!1),()=>{h.disconnect(),r.current=null}},[o,d]),M(()=>{r.current&&(r.current.viewOnly=!u)},[u]),o&&!o.station?l("p",{className:"p-3 text-sm text-muted-foreground",children:"The desktop is your moonlet's own computer, where its conversation and the work it starts run."}):m("div",{className:"flex h-full flex-col",children:[m("div",{className:"flex items-center gap-2 border-b px-3 py-2 text-xs",children:[l("span",{className:"font-medium",children:o?.station??"\u2026"}),l("span",{className:"flex-1 text-muted-foreground",children:i||(u?"You're in control: clicks and keys go to the desktop.":"Watching.")}),i?l(R,{size:"sm",variant:"secondary",onClick:()=>p(f=>f+1),children:"Retry"}):l(R,{size:"sm",variant:u?"destructive":"default",onClick:()=>c(f=>!f),children:u?"Give back control":"Take control"})]}),l("div",{ref:n,className:"min-h-0 flex-1 bg-black"})]})}function Yk(e){let t=ss();return t===void 0?null:t===null?l("p",{className:"p-3 text-sm text-muted-foreground",children:"There's no conversation with your moonlet yet, so there's no desktop to show."}):l(Fh,{threadId:t},t)}var ya=/^[a-z0-9_-][a-z0-9._-]{0,63}$/;var Ze="inbox";var Jk=1e3;var _a=400,Yc=e=>e.normalize("NFC").toLowerCase();var W$=["kind","project","conversation","tag","modified","by","subfolders"],j$=new Map([["page","html"],["html","html"],["md","md"],["markdown","md"]]),Q$=new Map([["you","owner"],["owner","owner"],["me","owner"],["assistant","assistant"],["moonlet","assistant"]]),G$=/^\d{4}-\d{2}-\d{2}$/;function Kh(e){let t=[],n=/(\S+?:"[^"]*"?|"[^"]*"?|\S+)/g;for(let r of e.slice(0,_a).matchAll(n))t.push(r[1]);return t}var zh=e=>e.replace(/^"|"$/g,"");function e1(e){if(!G$.test(e))return!1;let t=Date.parse(`${e}T00:00:00Z`);return!Number.isNaN(t)&&new Date(t).toISOString().slice(0,10)===e}function Y$(e){let t=e.toLowerCase();if(t==="today")return{kind:"today"};let n=/^<?(\d{1,4})d$/.exec(t);if(n)return{kind:"within",days:Number(n[1])};let r=/^>(\d{1,4})d$/.exec(t);if(r)return{kind:"older",days:Number(r[1])};let[o,s]=t.split("..");return o&&e1(o)&&(s===void 0||e1(s))?{kind:"range",from:o,to:s??o}:null}function qc(e){let t={text:[],kinds:[],projects:[],conversations:[],tags:[],modified:null,by:null,subfolders:!1,problems:[]};for(let n of Kh(e)){let r=/^([a-z]+):(.*)$/i.exec(n),o=r?.[1]?.toLowerCase()??"";if(!r||!W$.includes(o)){let i=Yc(zh(n).trim());i&&t.text.push(i.slice(0,100));continue}let s=zh(r[2]).trim();if(s)switch(o){case"kind":{let i=j$.get(s.toLowerCase());i?t.kinds.includes(i)||t.kinds.push(i):t.problems.push(`kind:${s} isn't a kind (page or md)`);break}case"project":t.projects.push(Yc(s).slice(0,100));break;case"conversation":t.conversations.push(Yc(s).slice(0,100));break;case"tag":{let i=s.toLowerCase();ya.test(i)?t.tags.includes(i)||t.tags.push(i):t.problems.push(`tag:${s} isn't a tag`);break}case"modified":{let i=Y$(s);i?t.modified=i:t.problems.push(`modified:${s} isn't a time (today, 7d, <30d, >90d or 2026-11-01..2026-11-20)`);break}case"by":{let i=Q$.get(s.toLowerCase());i?t.by=i:t.problems.push(`by:${s} isn't you or assistant`);break}case"subfolders":t.subfolders=/^(yes|true|on|1)$/i.test(s);break}}return t}function va(e){return!!(e.text.length||e.kinds.length||e.projects.length||e.conversations.length||e.tags.length||e.modified||e.by)}var t5=360*60*1e3;var q$=e=>/[\s"]/.test(e)?`"${e.replace(/"/g,"")}"`:e;function wa(e,t,n){return[...Kh(e).filter(o=>!o.toLowerCase().startsWith(`${t}:`)),...n?[`${t}:${q$(n)}`]:[]].join(" ")}function t1(e,t){let n=Kh(e).filter(r=>r.toLowerCase().startsWith(`${t}:`)).at(-1);return n?zh(n.slice(t.length+1)):null}var n1=["name","modified","conversation","versions","size"],eI="JOIN artifact_versions v ON v.page_id = g.id AND v.n = (SELECT MAX(n) FROM artifact_versions m WHERE m.page_id = g.id)",d5=`SELECT p.path, g.thread_id, g.file, g.kind, g.project_id, g.thread_title, g.file_gone, g.thread_gone, g.canonical,
68
68
  v.n, v.size, v.at, (SELECT COUNT(*) FROM artifact_versions c WHERE c.page_id = g.id) AS versions,
69
69
  (SELECT group_concat(tag, ',') FROM (SELECT tag FROM page_tags t WHERE t.page_id = g.id ORDER BY tag)) AS tags,
70
70
  EXISTS (SELECT 1 FROM page_stars s WHERE s.page_id = g.id) AS starred,
71
71
  v.n > coalesce((SELECT n FROM page_seen e WHERE e.page_id = g.id), 0) AS unread
72
- FROM library_paths p JOIN artifact_pages g ON g.id = p.page_id ${G$}
73
- WHERE p.state = 'live'`;var zh=/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,99}$/,Kh="default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' blob: data: https://cdn.jsdelivr.net https://esm.sh https://unpkg.com; style-src 'unsafe-inline' blob: data: https://cdn.jsdelivr.net https://esm.sh https://unpkg.com; img-src data:; font-src data:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'",Jt=`<!doctype html><html><head><meta charset="utf-8"><meta name="referrer" content="no-referrer"><meta http-equiv="Content-Security-Policy" content="${Kh}">`,Y$=["<meta","<link","<base","<iframe","<frame","<object","<embed","<form","<portal"];function Xh(e){return zh.test(e)?e.endsWith(".html")?"html":e.endsWith(".md")?"md":null:null}function Jk(e,t){if(new TextEncoder().encode(t).length>524288)return`a page is at most ${524288/1024} KiB`;if(e==="html"){if(!t.startsWith(Jt))return"this HTML page doesn't start with the Content Security Policy every page starts with, so it isn't shown";let n=t.slice(Jt.length).toLowerCase(),r=Y$.find(o=>n.includes(o));return r?`this HTML page has a ${r}\u2026> tag after its head, so it isn't shown`:null}return t.includes("![")?"this Markdown page has an image, so it isn't shown":/<[A-Za-z/!?]/.test(t)?"this Markdown page has raw HTML, so it isn't shown":null}var q$=500,s5=`set -u
72
+ FROM library_paths p JOIN artifact_pages g ON g.id = p.page_id ${eI}
73
+ WHERE p.state = 'live'`;var Xh=/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,99}$/,Bh="default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' blob: data: https://cdn.jsdelivr.net https://esm.sh https://unpkg.com; style-src 'unsafe-inline' blob: data: https://cdn.jsdelivr.net https://esm.sh https://unpkg.com; img-src data:; font-src data:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'",en=`<!doctype html><html><head><meta charset="utf-8"><meta name="referrer" content="no-referrer"><meta http-equiv="Content-Security-Policy" content="${Bh}">`,tI=["<meta","<link","<base","<iframe","<frame","<object","<embed","<form","<portal"];function Uh(e){return Xh.test(e)?e.endsWith(".html")?"html":e.endsWith(".md")?"md":null:null}function r1(e,t){if(new TextEncoder().encode(t).length>524288)return`a page is at most ${524288/1024} KiB`;if(e==="html"){if(!t.startsWith(en))return"this HTML page doesn't start with the Content Security Policy every page starts with, so it isn't shown";let n=t.slice(en.length).toLowerCase(),r=tI.find(o=>n.includes(o));return r?`this HTML page has a ${r}\u2026> tag after its head, so it isn't shown`:null}return t.includes("![")?"this Markdown page has an image, so it isn't shown":/<[A-Za-z/!?]/.test(t)?"this Markdown page has raw HTML, so it isn't shown":null}var nI=500,f5=`set -u
74
74
  dir=$1
75
75
  thread=\${dir%/pages}
76
76
  if [ ! -e "$dir" ] && [ -d "$thread" ] && [ ! -L "$thread" ]; then printf 'DIR %s\\nEND-PAGES\\n' "$dir"; exit 0; fi
@@ -83,17 +83,17 @@ for f in *; do
83
83
  { [ -f "$f" ] && [ ! -L "$f" ]; } || continue
84
84
  s=$(stat -c '%h %s %Y' -- "$f" 2>/dev/null || stat -f '%l %z %m' -- "$f" 2>/dev/null) || continue
85
85
  printf 'PAGE %s %s\\n' "$s" "$f"
86
- n=$((n + 1)); [ "$n" -lt ${q$} ] || break
86
+ n=$((n + 1)); [ "$n" -lt ${nI} ] || break
87
87
  done
88
88
  echo END-PAGES
89
- `;function Yc(e){return e.replace(/^---[ \t]*\r?\n[^]{0,1000}?\r?\n---[ \t]*(\r?\n|$)/,"")}var Uh="moonlet-artifact",qc="home-artifacts",Jc="artifacts",n1=320,J$=180,eI=420,tI=48,r1="moonlet-artifact-height",nI=1e5,e1=140,o1=/^thr_[a-z0-9]+$/;function s1(e,t){let n=e.name?.trim()??"";if(!n)return{problem:`This page link names no page. Write it as ::${Uh}{name="<page>.html"}.`};let r=Xh(n);return r?o1.test(t)?{threadId:t,name:n,kind:r}:{problem:"This message isn't in a conversation, so its page can't be found."}:{problem:`\u201C${n.slice(0,120)}\u201D isn't a page name: plain letters, digits, ., _ and -, ending .html or .md.`}}function Hh(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let{threadId:t,name:n}=e;return typeof t!="string"||!o1.test(t)||typeof n!="string"||!zh.test(n)||!Xh(n)?null:{threadId:t,name:n}}function t1(e){return e.replace(/&#x([0-9a-f]{1,6});/gi,(t,n)=>String.fromCodePoint(Math.min(Number.parseInt(n,16),1114111))).replace(/&#([0-9]{1,7});/g,(t,n)=>String.fromCodePoint(Math.min(Number(n),1114111))).replace(/&nbsp;/g," ").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Bh(e){let t=e.replace(/\s+/g," ").trim();return!t||/^\[[^\]]*\]$/.test(t)?null:t.length>e1?`${t.slice(0,e1-1)}\u2026`:t}function i1(e,t){if(e==="html"){let r=/<title[^>]*>([^<]{1,1000})<\/title>/i.exec(t)?.[1],o=r===void 0?null:Bh(t1(r));if(o)return o;let s=/<h1[^>]*>([^]{1,2000}?)<\/h1>/i.exec(t)?.[1];return s===void 0?null:Bh(t1(s.replace(/<[^>]*>/g,"")))}let n=/^#{1,2}[ \t]+(.+)$/m.exec(Yc(t))?.[1];return n===void 0?null:Bh(n.replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[*_`]+/g,"").replace(/\s+#+\s*$/,""))}var rI=`(() => {
89
+ `;function Jc(e){return e.replace(/^---[ \t]*\r?\n[^]{0,1000}?\r?\n---[ \t]*(\r?\n|$)/,"")}var Vh="moonlet-artifact",eu="home-artifacts",tu="artifacts",i1=320,rI=180,oI=420,sI=48,a1="moonlet-artifact-height",iI=1e5,o1=140,l1=/^thr_[a-z0-9]+$/;function c1(e,t){let n=e.name?.trim()??"";if(!n)return{problem:`This page link names no page. Write it as ::${Vh}{name="<page>.html"}.`};let r=Uh(n);return r?l1.test(t)?{threadId:t,name:n,kind:r}:{problem:"This message isn't in a conversation, so its page can't be found."}:{problem:`\u201C${n.slice(0,120)}\u201D isn't a page name: plain letters, digits, ., _ and -, ending .html or .md.`}}function Zh(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let{threadId:t,name:n}=e;return typeof t!="string"||!l1.test(t)||typeof n!="string"||!Xh.test(n)||!Uh(n)?null:{threadId:t,name:n}}function s1(e){return e.replace(/&#x([0-9a-f]{1,6});/gi,(t,n)=>String.fromCodePoint(Math.min(Number.parseInt(n,16),1114111))).replace(/&#([0-9]{1,7});/g,(t,n)=>String.fromCodePoint(Math.min(Number(n),1114111))).replace(/&nbsp;/g," ").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Hh(e){let t=e.replace(/\s+/g," ").trim();return!t||/^\[[^\]]*\]$/.test(t)?null:t.length>o1?`${t.slice(0,o1-1)}\u2026`:t}function u1(e,t){if(e==="html"){let r=/<title[^>]*>([^<]{1,1000})<\/title>/i.exec(t)?.[1],o=r===void 0?null:Hh(s1(r));if(o)return o;let s=/<h1[^>]*>([^]{1,2000}?)<\/h1>/i.exec(t)?.[1];return s===void 0?null:Hh(s1(s.replace(/<[^>]*>/g,"")))}let n=/^#{1,2}[ \t]+(.+)$/m.exec(Jc(t))?.[1];return n===void 0?null:Hh(n.replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[*_`]+/g,"").replace(/\s+#+\s*$/,""))}var aI=`(() => {
90
90
  let last = 0;
91
91
  const report = () => {
92
92
  const root = document.documentElement;
93
93
  const height = Math.ceil(root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height);
94
94
  if (!height || height === last) return;
95
95
  last = height;
96
- parent.postMessage({ type: "${r1}", height }, "*");
96
+ parent.postMessage({ type: "${a1}", height }, "*");
97
97
  };
98
98
  const watch = typeof ResizeObserver === "function" ? new ResizeObserver(report) : null;
99
99
  watch?.observe(document.documentElement);
@@ -102,7 +102,7 @@ echo END-PAGES
102
102
  report();
103
103
  });
104
104
  addEventListener("load", report);
105
- })();`;function a1(e){return e.startsWith(Jt)?`${Jt}<style>html{overflow-y:hidden!important}</style><script>${rI}<\/script>${e.slice(Jt.length)}`:e}function l1(e,t){if(!t||typeof e!="object"||e===null)return null;let n=Object.keys(e);if(n.length!==2||!n.includes("type")||!n.includes("height"))return null;let{type:r,height:o}=e;return r!==r1||typeof o!="number"||!Number.isFinite(o)||o<=0?null:Math.min(Math.ceil(o),nI)}function Vh(e,t){if(!(e>0)||!(t>0))return n1;let n=Math.min(e*.6,t*.4);return Math.round(Math.min(eI,Math.max(J$,n)))}function Zh(e,t=n1){return e===null?{height:t,clamped:!1}:e<=t+Math.round(t/4)?{height:Math.max(tI,e),clamped:!1}:{height:t,clamped:!0}}var Wh=new Set;function c1(e){for(let t of[...Wh])t(e)}function u1(e,t){let n=r=>{r.threadId===e.threadId&&r.name===e.name&&t()};return Wh.add(n),()=>{Wh.delete(n)}}var d1="orbit-artifact-link",jh=500,oI=`(() => {
105
+ })();`;function d1(e){return e.startsWith(en)?`${en}<style>html{overflow-y:hidden!important}</style><script>${aI}<\/script>${e.slice(en.length)}`:e}function p1(e,t){if(!t||typeof e!="object"||e===null)return null;let n=Object.keys(e);if(n.length!==2||!n.includes("type")||!n.includes("height"))return null;let{type:r,height:o}=e;return r!==a1||typeof o!="number"||!Number.isFinite(o)||o<=0?null:Math.min(Math.ceil(o),iI)}function Wh(e,t){if(!(e>0)||!(t>0))return i1;let n=Math.min(e*.6,t*.4);return Math.round(Math.min(oI,Math.max(rI,n)))}function jh(e,t=i1){return e===null?{height:t,clamped:!1}:e<=t+Math.round(t/4)?{height:Math.max(sI,e),clamped:!1}:{height:t,clamped:!0}}var Qh=new Set;function f1(e){for(let t of[...Qh])t(e)}function h1(e,t){let n=r=>{r.threadId===e.threadId&&r.name===e.name&&t()};return Qh.add(n),()=>{Qh.delete(n)}}var m1="orbit-artifact-link",Gh=500,lI=`(() => {
106
106
  const XLINK = "http://www.w3.org/1999/xlink";
107
107
  const hrefOf = (a) => a.getAttribute("href") ?? a.getAttributeNS(XLINK, "href");
108
108
  const scroll = (fragment) => {
@@ -124,72 +124,72 @@ echo END-PAGES
124
124
  if (kept) return;
125
125
  const h = href.trim();
126
126
  if (h.startsWith("#")) scroll(h.slice(1));
127
- else parent.postMessage({ type: "${d1}", href: h.slice(0, ${jh+1}) }, "*");
127
+ else parent.postMessage({ type: "${m1}", href: h.slice(0, ${Gh+1}) }, "*");
128
128
  }, 0);
129
129
  }, true);
130
- })();`;function p1(e){return e.startsWith(Jt)?`${Jt}<script>${oI}<\/script>${e.slice(Jt.length)}`:e}function eu(e,t){if(!t.ownFrame||!t.activated||typeof e!="object"||e===null)return null;let n=Object.keys(e);if(n.length!==2||!n.includes("type")||!n.includes("href"))return null;let{type:r,href:o}=e;return r!==d1||typeof o!="string"||!o||o.length>jh?null:o}function Vr(e){let t=e.trim();if(!t||t.length>jh)return{kind:"refused",reason:"the link's address is empty or too long"};if(/[\u0000-\u001f\u007f\\]/.test(t))return{kind:"refused",reason:"the link's address has a backslash or a control character"};if(t.startsWith("#"))return{kind:"anchor"};if(t.startsWith("//"))return{kind:"refused",reason:"the link leaves out its scheme (//\u2026), so where it goes isn't clear"};let n=/^([A-Za-z][A-Za-z0-9+.-]*):/.exec(t)?.[1]?.toLowerCase();if(n===void 0)return{kind:"page",href:t};if(n!=="https"&&n!=="http"&&n!=="mailto")return{kind:"refused",reason:`links to ${n}: addresses aren't followed`};let r;try{r=new URL(t)}catch{return{kind:"refused",reason:"the link's address isn't a valid one"}}return n!=="mailto"&&!r.hostname?{kind:"refused",reason:"the link's address has no site"}:r.username||r.password?{kind:"refused",reason:"the link's address has a user name or password in it"}:{kind:"outside",url:r.href}}function tu(e){switch(e.kind){case"anchor":case"outside":return null;case"page":return`This page links to another page (${e.href}). Links between pages aren't followed yet.`;case"refused":return`The link wasn't followed: ${e.reason}.`}}function f1(e,t){let n=t.replace(/\r\n?/g,`
130
+ })();`;function g1(e){return e.startsWith(en)?`${en}<script>${lI}<\/script>${e.slice(en.length)}`:e}function nu(e,t){if(!t.ownFrame||!t.activated||typeof e!="object"||e===null)return null;let n=Object.keys(e);if(n.length!==2||!n.includes("type")||!n.includes("href"))return null;let{type:r,href:o}=e;return r!==m1||typeof o!="string"||!o||o.length>Gh?null:o}function Zr(e){let t=e.trim();if(!t||t.length>Gh)return{kind:"refused",reason:"the link's address is empty or too long"};if(/[\u0000-\u001f\u007f\\]/.test(t))return{kind:"refused",reason:"the link's address has a backslash or a control character"};if(t.startsWith("#"))return{kind:"anchor"};if(t.startsWith("//"))return{kind:"refused",reason:"the link leaves out its scheme (//\u2026), so where it goes isn't clear"};let n=/^([A-Za-z][A-Za-z0-9+.-]*):/.exec(t)?.[1]?.toLowerCase();if(n===void 0)return{kind:"page",href:t};if(n!=="https"&&n!=="http"&&n!=="mailto")return{kind:"refused",reason:`links to ${n}: addresses aren't followed`};let r;try{r=new URL(t)}catch{return{kind:"refused",reason:"the link's address isn't a valid one"}}return n!=="mailto"&&!r.hostname?{kind:"refused",reason:"the link's address has no site"}:r.username||r.password?{kind:"refused",reason:"the link's address has a user name or password in it"}:{kind:"outside",url:r.href}}function ru(e){switch(e.kind){case"anchor":case"outside":return null;case"page":return`This page links to another page (${e.href}). Links between pages aren't followed yet.`;case"refused":return`The link wasn't followed: ${e.reason}.`}}function x1(e,t){let n=t.replace(/\r\n?/g,`
131
131
  `);return(e==="html"?n.replace(/>(?=<)/g,`>
132
132
  `):n).split(`
133
- `)}function sI(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;let r=e.length,o=t.length;for(;r>n&&o>n&&e[r-1]===t[o-1];)r--,o--;let s=r-n,i=o-n;if(s*i>4e6)return null;let a=i+1,u=new Uint32Array((s+1)*a);for(let f=s-1;f>=0;f--)for(let h=i-1;h>=0;h--)u[f*a+h]=e[n+f]===t[n+h]?u[(f+1)*a+h+1]+1:Math.max(u[(f+1)*a+h],u[f*a+h+1]);let c=[];for(let f=0;f<n;f++)c.push({t:"same",text:e[f],a:f+1,b:f+1});let d=0,p=0;for(;d<s||p<i;)d<s&&p<i&&e[n+d]===t[n+p]?(c.push({t:"same",text:e[n+d],a:n+d+1,b:n+p+1}),d++,p++):d<s&&(p===i||u[(d+1)*a+p]>=u[d*a+p+1])?(c.push({t:"del",text:e[n+d],a:n+d+1}),d++):(c.push({t:"add",text:t[n+p],b:n+p+1}),p++);for(let f=0;f<e.length-r;f++)c.push({t:"same",text:e[r+f],a:r+f+1,b:o+f+1});return c}function h1(e,t,n){let r=f1(e,t),o=f1(e,n),s=sI(r,o);if(!s)return{state:"too-big",lines:[r.length,o.length]};let i=[],a=0,u=0,c=-1;for(let d=0;d<s.length;d++){let p=s[d];if(p.t==="same")continue;p.t==="add"?a++:u++;let f=Math.max(d-3,c+1),h=i.at(-1);if(h&&f<=c+1&&c>=0)for(let x=c+1;x<=d;x++)h.lines.push(s[x]);else i.push({lines:s.slice(f,d+1),skippedBefore:f-(c+1)});c=d;let g=d+1;for(;g<s.length&&g<=d+3&&s[g].t==="same";)i.at(-1).lines.push(s[g]),c=g,g++}return{state:"ok",hunks:i,added:a,removed:u,skippedAfter:s.length-(c+1)}}function iI(e){let t=e.trim();return/^(https?:\/\/|mailto:)[^\s"'<>\\]+$/i.test(t)?t:null}function m1(e){let t=/^ {0,3}(#{1,6})(?=[ \t]|$)/.exec(e);if(!t)return null;let n=e.slice(t[0].length).trim(),r=n.length;for(;r>0&&n[r-1]==="#";)r--;return(r===0||n[r-1]===" "||n[r-1]===" ")&&(n=n.slice(0,r).trimEnd()),{level:t[1].length,text:n}}function ar(e){let t=[],n="",r=()=>{n&&t.push({t:"text",v:n}),n=""},o=0;for(;o<e.length;){let s=e.slice(o),i;if(s[0]==="\\"&&s.length>1&&/[\\`*_[\]()#+\-.!|~]/.test(s[1]))n+=s[1],o+=2;else if(i=/^(`+)([^]*?[^`])\1(?!`)/.exec(s))r(),t.push({t:"code",v:i[2].trim()||i[2]}),o+=i[0].length;else if(i=/^\[([^\]]*)\]\(([^()\s]*)\)/.exec(s)){r();let a=iI(i[2])??(Vr(i[2]).kind==="page"?i[2].trim():null),u=ar(i[1]);a?t.push({t:"link",href:a,c:u}):t.push(...u),o+=i[0].length}else(i=/^(\*\*|__)(?=\S)([^]*?\S)\1/.exec(s))?(r(),t.push({t:"strong",c:ar(i[2])}),o+=i[0].length):(i=/^(\*|_)(?=\S)([^]*?\S)\1(?![*_])/.exec(s))&&(i[1]==="*"||!/\w/.test(e[o-1]??""))?(r(),t.push({t:"em",c:ar(i[2])}),o+=i[0].length):(n+=s[0],o+=1)}return r(),t}var Qh=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&!t.endsWith("\\|")&&(t=t.slice(0,-1)),t.split(/(?<!\\)\|/).map(n=>n.trim().replace(/\\\|/g,"|"))},g1=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;function Gh(e){let t=e.replace(/\r\n?/g,`
133
+ `)}function cI(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;let r=e.length,o=t.length;for(;r>n&&o>n&&e[r-1]===t[o-1];)r--,o--;let s=r-n,i=o-n;if(s*i>4e6)return null;let a=i+1,u=new Uint32Array((s+1)*a);for(let f=s-1;f>=0;f--)for(let h=i-1;h>=0;h--)u[f*a+h]=e[n+f]===t[n+h]?u[(f+1)*a+h+1]+1:Math.max(u[(f+1)*a+h],u[f*a+h+1]);let c=[];for(let f=0;f<n;f++)c.push({t:"same",text:e[f],a:f+1,b:f+1});let d=0,p=0;for(;d<s||p<i;)d<s&&p<i&&e[n+d]===t[n+p]?(c.push({t:"same",text:e[n+d],a:n+d+1,b:n+p+1}),d++,p++):d<s&&(p===i||u[(d+1)*a+p]>=u[d*a+p+1])?(c.push({t:"del",text:e[n+d],a:n+d+1}),d++):(c.push({t:"add",text:t[n+p],b:n+p+1}),p++);for(let f=0;f<e.length-r;f++)c.push({t:"same",text:e[r+f],a:r+f+1,b:o+f+1});return c}function b1(e,t,n){let r=x1(e,t),o=x1(e,n),s=cI(r,o);if(!s)return{state:"too-big",lines:[r.length,o.length]};let i=[],a=0,u=0,c=-1;for(let d=0;d<s.length;d++){let p=s[d];if(p.t==="same")continue;p.t==="add"?a++:u++;let f=Math.max(d-3,c+1),h=i.at(-1);if(h&&f<=c+1&&c>=0)for(let x=c+1;x<=d;x++)h.lines.push(s[x]);else i.push({lines:s.slice(f,d+1),skippedBefore:f-(c+1)});c=d;let g=d+1;for(;g<s.length&&g<=d+3&&s[g].t==="same";)i.at(-1).lines.push(s[g]),c=g,g++}return{state:"ok",hunks:i,added:a,removed:u,skippedAfter:s.length-(c+1)}}function uI(e){let t=e.trim();return/^(https?:\/\/|mailto:)[^\s"'<>\\]+$/i.test(t)?t:null}function y1(e){let t=/^ {0,3}(#{1,6})(?=[ \t]|$)/.exec(e);if(!t)return null;let n=e.slice(t[0].length).trim(),r=n.length;for(;r>0&&n[r-1]==="#";)r--;return(r===0||n[r-1]===" "||n[r-1]===" ")&&(n=n.slice(0,r).trimEnd()),{level:t[1].length,text:n}}function lr(e){let t=[],n="",r=()=>{n&&t.push({t:"text",v:n}),n=""},o=0;for(;o<e.length;){let s=e.slice(o),i;if(s[0]==="\\"&&s.length>1&&/[\\`*_[\]()#+\-.!|~]/.test(s[1]))n+=s[1],o+=2;else if(i=/^(`+)([^]*?[^`])\1(?!`)/.exec(s))r(),t.push({t:"code",v:i[2].trim()||i[2]}),o+=i[0].length;else if(i=/^\[([^\]]*)\]\(([^()\s]*)\)/.exec(s)){r();let a=uI(i[2])??(Zr(i[2]).kind==="page"?i[2].trim():null),u=lr(i[1]);a?t.push({t:"link",href:a,c:u}):t.push(...u),o+=i[0].length}else(i=/^(\*\*|__)(?=\S)([^]*?\S)\1/.exec(s))?(r(),t.push({t:"strong",c:lr(i[2])}),o+=i[0].length):(i=/^(\*|_)(?=\S)([^]*?\S)\1(?![*_])/.exec(s))&&(i[1]==="*"||!/\w/.test(e[o-1]??""))?(r(),t.push({t:"em",c:lr(i[2])}),o+=i[0].length):(n+=s[0],o+=1)}return r(),t}var Yh=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&!t.endsWith("\\|")&&(t=t.slice(0,-1)),t.split(/(?<!\\)\|/).map(n=>n.trim().replace(/\\\|/g,"|"))},_1=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;function qh(e){let t=e.replace(/\r\n?/g,`
134
134
  `).split(`
135
135
  `),n=[],r=0,o=s=>/^\s{0,3}(#{1,6}\s|```|~~~|>|([-*+]|\d{1,9}[.)])\s|(\*\s*){3,}$|(-\s*){3,}$|(_\s*){3,}$)/.test(s);for(;r<t.length;){let s=t[r],i;if(!s.trim())r++;else if(i=/^\s{0,3}(```|~~~)/.exec(s)){let a=i[1],u=[];for(r++;r<t.length&&!t[r].trimStart().startsWith(a);)u.push(t[r++]);r++,n.push({t:"code",v:u.join(`
136
- `)})}else if(m1(s)){let a=m1(s);n.push({t:"h",level:a.level,c:ar(a.text)}),r++}else if(/^\s{0,3}((\*\s*){3,}|(-\s*){3,}|(_\s*){3,})$/.test(s))n.push({t:"hr"}),r++;else if(/^\s{0,3}>/.test(s)){let a=[];for(;r<t.length&&/^\s{0,3}>/.test(t[r]);)a.push(t[r++].replace(/^\s{0,3}>\s?/,""));n.push({t:"quote",blocks:Gh(a.join(`
137
- `))})}else if(i=/^\s{0,3}([-*+]|\d{1,9}[.)])\s+/.exec(s)){let a=/\d/.test(i[1]),u=a?/^\s{0,3}\d{1,9}[.)]\s+(.*)$/:/^\s{0,3}[-*+]\s+(.*)$/,c=[];for(;r<t.length&&t[r].trim();){let d=u.exec(t[r]);if(d)c.push(d[1]);else if(c.length&&!o(t[r]))c[c.length-1]+=` ${t[r].trim().replace(/^([-*+]|\d{1,9}[.)])\s+/,"")}`;else break;r++}n.push({t:a?"ol":"ul",items:c.map(ar)})}else if(s.includes("|")&&r+1<t.length&&g1.test(t[r+1])){let a=Qh(s),u=Qh(t[r+1]).map(d=>d.startsWith(":")&&d.endsWith(":")?"center":d.endsWith(":")?"right":d.startsWith(":")?"left":null);r+=2;let c=[];for(;r<t.length&&t[r].trim()&&t[r].includes("|");){let d=Qh(t[r++]);c.push(a.map((p,f)=>ar(d[f]??"")))}n.push({t:"table",align:a.map((d,p)=>u[p]??null),head:a.map(ar),rows:c})}else{let a=[];for(;r<t.length&&t[r].trim()&&!o(t[r])&&!(t[r].includes("|")&&r+1<t.length&&g1.test(t[r+1]));)a.push(t[r++].trim());a.length||a.push(t[r++].trim()),n.push({t:"p",c:ar(a.join(" "))})}}return n}function Yh(e){switch(e.state){case"offline":return`${e.machine??"This conversation's machine"} is offline, so this conversation's artifacts can't be read. Refresh once it's back.`;case"refused":return`Couldn't list the artifacts: ${e.reason}.`;case"ok":return e.artifacts.length?null:"This conversation has no artifacts yet. When it shows a page in its chat, the page appears here too."}}function Zr(e){let t=Jk(e.kind,e.content);return t?{kind:"refused",reason:t}:e.kind==="md"?{kind:"markdown",blocks:Gh(Yc(e.content))}:{kind:"frame",srcDoc:p1(e.content)}}function nu(e){return e.state==="ok"?Zr(e.page):{kind:"refused",reason:e.state==="refused"?e.reason:Yh(e)??""}}function ss(e){return{kind:"refused",reason:`Couldn't open the page: ${e instanceof Error?e.message:String(e)}`}}function ru(e){return{...{title:"Page",sandbox:"allow-scripts",referrerPolicy:"no-referrer",allow:""},csp:Kh,srcDoc:e.srcDoc}}function wa(e,t,n=Date.now()){return`${e<1024?`${e} B`:`${Math.round(e/1024)} KB`} \xB7 ${Wr(t,n)}`}function Wr(e,t=Date.now()){let n=Math.max(0,Math.round((t-e)/6e4));return n<1?"just now":n<60?`${n} min ago`:n<2880?`${Math.round(n/60)} h ago`:new Date(e).toLocaleDateString()}function x1(e,t){let n=e.by==="owner"?"you":e.by===t?"this conversation":e.by,r=e.source==="restore"?`${n}, restored v${e.restoredFrom}`:n,o=new Date(e.at).toLocaleString(void 0,{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"});return`v${e.n} \xB7 ${o} \xB7 ${r} \xB7 ${wa(e.size,e.at).split(" \xB7 ")[0]}`}function ou(e){return e.versionsError?`Versions aren't available (${e.versionsError}): this is the conversation's file as it is now.`:e.pinned!==void 0?`Pinned to v${e.pinned}: shown until it's unpinned (History), whatever the conversation writes next.${e.gone?" The conversation's file is gone.":""}`:e.gone?`The conversation's file is gone; this is the last version kept${e.version?` (v${e.version})`:""}.`:e.restoredFrom!==void 0?`v${e.version}, restored from v${e.restoredFrom}. The conversation's own file is unchanged.`:e.version?`v${e.version}`:null}function su(e){switch(e.state){case"page":return null;case"deleted":return`That page (${e.path}) was deleted from the library on ${new Date(e.at).toLocaleDateString()}.`;case"missing":return`There's no page at ${e.path} in the library.`;case"refused":return`The link wasn't followed: ${e.reason}.`}}function Mn(){try{return globalThis.localStorage??null}catch{return null}}function au({threadId:e,name:t,shown:n,about:r,onChanged:o,onNavigate:s,onBack:i}){let a=J(),[u,c]=_("page");K(()=>c("page"),[e,t]);let d=Y(0);K(()=>{d.current++},[e,t]);let p=q(async h=>{let g=++d.current,x=await a.call("artifacts.follow",{threadId:e,name:t,href:h});return g!==d.current?null:(x.state==="page"&&s(x.threadId,x.name,x.path),su(x))},[a,e,t,s]),f=h=>c(g=>g===h?"page":h);return m("div",{className:"flex min-h-0 flex-1 flex-col",children:[m("div",{className:"flex items-center gap-2 border-b px-3 py-1.5 text-xs text-muted-foreground",children:[i?l(R,{size:"sm",variant:"secondary",onClick:i,children:"Back"}):null,l("span",{className:"min-w-0 flex-1 truncate",children:u==="history"?`History of ${t}`:u==="links"?`Links of ${t}`:r??""}),l(R,{size:"sm",variant:u==="links"?"default":"secondary",onClick:()=>f("links"),children:u==="links"?"Back to the page":"Links"}),l(R,{size:"sm",variant:u==="history"?"default":"secondary",onClick:()=>f("history"),children:u==="history"?"Back to the page":"History"})]}),u==="history"?l(cI,{threadId:e,name:t,onRestored:()=>{c("page"),o()}}):u==="links"?l(lI,{threadId:e,name:t,onNavigate:s}):l(iu,{shown:n,onPageLink:p})]})}var aI={page:"",deleted:"deleted",missing:"broken: no such page",refused:"not followed",outside:"outside Moonlet"};function lI({threadId:e,name:t,onNavigate:n}){let r=J(),[o,s]=_(null),[i,a]=_("");if(K(()=>{let c=!0;return s(null),r.call("artifacts.links",{threadId:e,name:t}).then(d=>c&&s(d),d=>c&&a(d instanceof Error?d.message:String(d))),()=>{c=!1}},[r,e,t]),!o)return l("p",{className:`p-3 text-sm ${i?"text-destructive":"text-muted-foreground"}`,children:i||"Reading its links\u2026"});let u=o.out.filter(c=>c.state==="missing"||c.state==="deleted").length;return m("div",{className:"min-h-0 flex-1 overflow-auto p-3 text-sm",children:[o.path?l("p",{className:"mb-2 text-xs text-muted-foreground",children:o.path}):l("p",{className:"mb-2 text-xs text-muted-foreground",children:"Not in the library yet."}),m("h3",{className:"mb-1 font-medium",children:["Linked from (",o.from.length,")"]}),o.from.length?l("ul",{className:"mb-3",children:o.from.map(c=>l("li",{children:l("button",{type:"button",className:"underline",onClick:()=>n(c.threadId,c.name,c.path),children:c.path})},c.path))}):l("p",{className:"mb-3 text-xs text-muted-foreground",children:"No page in this project links here."}),m("h3",{className:"mb-1 font-medium",children:["Links on this page (",o.out.length,")",u?`, ${u} broken`:""]}),o.out.length?l("ul",{children:o.out.map(c=>m("li",{className:"flex gap-2 text-xs",children:[m("span",{className:"min-w-0 flex-1 truncate",children:[c.href,c.path&&c.path!==c.href?` \u2192 ${c.path}`:""]}),l("span",{className:c.state==="missing"||c.state==="deleted"?"text-destructive":"text-muted-foreground",children:aI[c.state]})]},c.href))}):l("p",{className:"text-xs text-muted-foreground",children:"This page has no links."}),u?l("p",{className:"mt-2 text-xs text-muted-foreground",children:"Only the page's conversation can fix a broken link (by rewriting the page)."}):null]})}function cI({threadId:e,name:t,onRestored:n}){let r=J(),[o,s]=_(null),[i,a]=_(""),[u,c]=_(null),[d,p]=_("page"),[f,h]=_(null),[g,x]=_(null),[b,v]=_(null),[w,C]=_(!1),[y,T]=_(null),[N,S]=_(0),$=Q=>a(Q instanceof Error?Q.message:String(Q));K(()=>a(""),[e,t]),K(()=>{let Q=!0;return r.call("artifacts.history",{threadId:e,name:t}).then(j=>{if(Q){if(j.state==="refused")return a(j.reason);s(j),c(G=>G!==null&&j.versions.some(ee=>ee.n===G)?G:j.versions[0]?.n??null)}},j=>Q&&$(j)),()=>{Q=!1}},[r,e,t,N]);let P=o?.versions[0]?.n??null,L=q(async Q=>{let j=await r.call("artifacts.version",{threadId:e,name:t,n:Q});if(j.state==="refused")throw new Error(j.reason);return j.page},[r,e,t]),ne=d==="compare"&&u!==P;K(()=>{let Q=!0;return h(null),x(null),v(null),u!==null&&!ne?L(u).then(j=>Q&&h(Zr({kind:j.kind,content:j.content})),j=>Q&&h(ss(j))):u!==null&&P!==null&&Promise.all([L(u),L(P)]).then(([j,G])=>{Q&&(x(h1(j.kind,j.content,G.content)),v([Zr({kind:j.kind,content:j.content}),Zr({kind:G.kind,content:G.content})]))},j=>Q&&$(j)),()=>{Q=!1}},[u,ne,P,L]);let se=async Q=>{if(P===null)return;let j=await r.call("artifacts.pin",{threadId:e,name:t,n:Q,latest:P});j.state==="refused"?(a(j.reason),S(G=>G+1)):n()},_e=async()=>{if(!y||P===null)return;let Q=y.what==="restore"?await r.call("artifacts.restore",{threadId:e,name:t,n:y.n,latest:P}):await r.call("artifacts.forget",{threadId:e,name:t,n:y.n,latest:P});T(null),Q.state==="refused"?(a(Q.reason),S(j=>j+1)):y.what==="restore"?n():S(j=>j+1)};if(!o)return l("p",{className:`p-3 text-sm ${i?"text-destructive":"text-muted-foreground"}`,children:i||"Loading the history\u2026"});let ie=u===P;return m("div",{className:"flex min-h-0 flex-1 flex-col",children:[l("ul",{className:"max-h-[40%] shrink-0 overflow-auto border-b",children:o.versions.map(Q=>l("li",{children:m("button",{type:"button","aria-pressed":Q.n===u,className:`flex w-full items-baseline gap-2 px-3 py-1.5 text-left text-xs hover:bg-muted ${Q.n===u?"bg-muted font-medium":""}`,onClick:()=>c(Q.n),children:[l("span",{className:"min-w-0 flex-1 truncate",children:x1(Q,e)}),Q.n===o.pinned?l("span",{className:"shrink-0 font-medium",children:"pinned"}):null,Q.n===P?l("span",{className:"shrink-0 text-muted-foreground",children:"latest"}):null,Q.n===o.fileVersion&&!o.fileGone?l("span",{className:"shrink-0 text-muted-foreground",children:"the file now"}):null]})},Q.n))}),i?l("p",{className:"px-3 py-1.5 text-xs text-destructive",children:i}):null,y?m("div",{className:"flex flex-col gap-2 border-b bg-muted px-3 py-2 text-xs",role:"alertdialog",children:[l("span",{children:y.what==="restore"?`Restore v${y.n}? It becomes v${(P??0)+1}, the latest, with v${y.n}'s content. The conversation's own file isn't changed, and every version stays.`:`Delete v${y.n} for good? Its content can't be brought back.`}),m("div",{className:"flex gap-2",children:[l(R,{size:"sm",variant:"secondary",onClick:()=>T(null),children:"Cancel"}),l(R,{size:"sm",variant:y.what==="forget"?"destructive":"default",onClick:()=>{_e().catch($)},children:y.what==="restore"?"Restore":"Delete"})]})]}):u!==null?m("div",{className:"flex flex-wrap items-center gap-2 border-b px-3 py-1.5 text-xs",children:[l(R,{size:"sm",variant:ne?"secondary":"default",onClick:()=>p("page"),children:"View"}),l(R,{size:"sm",variant:ne?"default":"secondary",disabled:ie,onClick:()=>p("compare"),children:"Compare with latest"}),l("span",{className:"flex-1"}),o.pinned!==null?m(R,{size:"sm",variant:"secondary",onClick:()=>{se(null).catch($)},children:["Unpin v",o.pinned]}):null,o.pinned!==u?l(R,{size:"sm",variant:"secondary",onClick:()=>{se(u).catch($)},children:"Pin this version"}):null,l(R,{size:"sm",variant:"secondary",disabled:ie,onClick:()=>T({what:"restore",n:u}),children:"Restore\u2026"}),l(R,{size:"sm",variant:"secondary",disabled:ie||u===o.pinned,onClick:()=>T({what:"forget",n:u}),children:"Delete\u2026"})]}):null,ne?m("div",{className:"flex min-h-0 flex-1 flex-col",children:[m("div",{className:"flex gap-2 border-b px-3 py-1.5 text-xs",children:[l(R,{size:"sm",variant:w?"default":"secondary",onClick:()=>C(!0),children:"Drawn"}),l(R,{size:"sm",variant:w?"secondary":"default",onClick:()=>C(!1),children:"Source"})]}),w?l("div",{className:"flex min-h-0 flex-1",children:b?b.map((Q,j)=>m("div",{className:"flex min-w-0 flex-1 flex-col border-r",children:[m("p",{className:"border-b px-3 py-1 text-xs text-muted-foreground",children:["v",j===0?u:P]}),l(iu,{shown:Q})]},j)):l("p",{className:"p-3 text-sm text-muted-foreground",children:"Comparing\u2026"})}):l(pI,{diff:g,older:u,newer:P})]}):l(iu,{shown:f})]})}var uI={same:" ",add:"+",del:"-"},dI={same:"",add:"bg-green-500/15",del:"bg-red-500/15"};function pI({diff:e,older:t,newer:n}){return e?e.state==="too-big"?m("p",{className:"p-3 text-sm text-muted-foreground",children:["These versions differ too much to compare line by line (",e.lines[0]," and ",e.lines[1]," lines). View each instead."]}):m("div",{className:"min-h-0 flex-1 overflow-auto font-mono text-xs",children:[m("p",{className:"px-3 py-1.5 font-sans text-muted-foreground",children:["v",t," \u2192 v",n,": ",e.added," line",e.added===1?"":"s"," added, ",e.removed," removed",e.hunks.length?"":" (the same source)"]}),e.hunks.map((r,o)=>m("div",{children:[r.skippedBefore?m("p",{className:"px-3 py-0.5 font-sans text-muted-foreground",children:["\u2026 ",r.skippedBefore," unchanged lines"]}):null,r.lines.map((s,i)=>m("pre",{className:`whitespace-pre-wrap break-all px-3 ${dI[s.t]}`,children:[uI[s.t]," ",s.text]},i))]},o)),e.skippedAfter&&e.hunks.length?m("p",{className:"px-3 py-0.5 font-sans text-muted-foreground",children:["\u2026 ",e.skippedAfter," unchanged lines"]}):null]}):l("p",{className:"p-3 text-sm text-muted-foreground",children:"Comparing\u2026"})}function fI(e){let t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),()=>t.disconnect()}function hI(){return document.documentElement.classList.contains("dark")?"dark":"light"}function lu(){return xt(fI,hI,()=>"light")}function qh({threadId:e,initial:t=null,reopened:n=0}){let r=J(),[o,s]=_(null),[i,a]=_(""),[u,c]=_(t),[d,p]=_(e),[f,h]=_([]),[g,x]=_(null),[b,v]=_(null),[w,C]=_(0),y=L=>a(L instanceof Error?L.message:String(L));K(()=>{a(""),r.call("artifacts.list",{threadId:e}).then(s,y)},[r,e,w]);let T=Y(0),N=q((L,ne=e)=>{let se=++T.current;c(L),p(ne),x(null),v(null),r.call("artifacts.read",{threadId:ne,name:L}).then(_e=>se===T.current&&(x(nu(_e)),v(_e.state==="ok"?ou(_e.page):null)),_e=>se===T.current&&x(ss(_e)))},[r,e]),S=Y(t!==null);K(()=>{t!==null&&N(t)},[]),K(()=>{n===0||t===null||(h([]),N(t))},[n]),K(()=>{o&&S.current&&(S.current=!1,w===0)||u&&d===e&&o?.state==="ok"&&o.artifacts.some(L=>L.name===u)&&N(u)},[o]);let $=i?`Couldn't reach the artifacts: ${i}`:o?Yh(o):"Loading\u2026",P=o?.state==="ok"?o.artifacts:[];return m("div",{className:"flex h-full flex-col",children:[m("div",{className:"flex items-center gap-2 border-b px-3 py-2 text-xs",children:[u?l(R,{size:"sm",variant:"secondary",onClick:()=>(c(null),x(null),h([])),children:"All artifacts"}):null,u?l("span",{className:"min-w-0 flex-1 truncate font-medium",children:`${u}${d===e?"":" (another conversation's)"}`}):l("span",{className:"min-w-0 flex-1 truncate font-medium",children:"This conversation"}),l(R,{size:"sm",variant:"secondary",onClick:()=>C(L=>L+1),children:"Refresh"})]}),u?l(au,{threadId:d,name:u,shown:g,about:b,onChanged:()=>N(u,d),onNavigate:(L,ne)=>{h(se=>[...se,{threadId:d,name:u}]),N(ne,L)},onBack:f.length?()=>{let L=f.at(-1);h(ne=>ne.slice(0,-1)),N(L.name,L.threadId)}:null},n):$?l("p",{className:"p-3 text-sm text-muted-foreground",children:$}):l("ul",{className:"min-h-0 flex-1 overflow-auto",children:P.map(L=>l("li",{children:m("button",{type:"button",className:"flex w-full items-baseline gap-2 px-3 py-2 text-left text-sm hover:bg-muted",onClick:()=>(h([]),N(L.name)),children:[l("span",{className:`min-w-0 flex-1 truncate ${L.gone?"text-muted-foreground":""}`,children:L.name}),m("span",{className:"shrink-0 text-xs text-muted-foreground",children:[L.gone?"file gone \xB7 ":"",wa(L.size,L.modifiedAt)]})]})},L.name))})]})}function iu({shown:e,onPageLink:t}){let[n,r]=_(null),[o,s]=_(null);K(()=>{r(null),s(null)},[e]);let i=q(u=>{let c=Vr(u);r(c.kind==="outside"?c.url:null),c.kind==="page"&&t?(s(null),t(u).then(s,d=>s(`The link wasn't followed: ${d instanceof Error?d.message:String(d)}.`))):s(tu(c))},[t]);if(!e)return l("p",{className:"p-3 text-sm text-muted-foreground",children:"Opening the page\u2026"});if(e.kind==="refused")return l("p",{className:"p-3 text-sm text-destructive",children:e.reason});let a=n?l(em,{url:n,onClose:()=>r(null)}):o?m("div",{className:"flex items-center gap-2 border-b bg-muted px-3 py-2 text-xs",role:"status",children:[l("span",{className:"min-w-0 flex-1",children:o}),l(R,{size:"sm",variant:"secondary",onClick:()=>s(null),children:"OK"})]}):null;return e.kind==="markdown"?m("div",{className:"flex min-h-0 flex-1 flex-col",children:[a,l("div",{className:"min-h-0 flex-1 overflow-auto p-4 text-sm leading-relaxed",children:l(Jh,{blocks:e.blocks,follow:i})})]}):m("div",{className:"flex min-h-0 flex-1 flex-col",children:[a,l(gI,{frame:e,onLink:i},e.srcDoc)]})}function Jh({blocks:e,follow:t}){return l(he,{children:e.map((n,r)=>b1(n,r,t))})}function em({url:e,onClose:t}){let[n,r]=_(!1);return m("div",{className:"flex flex-col gap-2 border-b bg-muted px-3 py-2 text-xs",role:"alertdialog","aria-label":"Open a link outside Moonlet?",children:[l("span",{className:"font-medium",children:"Open a link outside Moonlet?"}),l("code",{className:"break-all rounded bg-background px-1 py-0.5",children:e}),l("span",{className:"text-muted-foreground",children:"It opens in a new tab, with no referrer. The page can't see whether you open it."}),m("div",{className:"flex gap-2",children:[l(R,{size:"sm",variant:"secondary",onClick:t,children:"Cancel"}),l(R,{size:"sm",variant:"secondary",onClick:()=>{navigator.clipboard?.writeText(e).then(()=>r(!0),()=>{})},children:n?"Copied":"Copy address"}),l(R,{size:"sm",onClick:()=>(window.open(e,"_blank","noopener,noreferrer"),t()),children:"Open in new tab"})]})]})}var mI=15e3;function gI({frame:e,onLink:t}){let[n,r]=_(!1),[o,s]=_(!1),i=Y(null),a=lu();return K(()=>{let u=setTimeout(()=>s(!0),mI);return()=>clearTimeout(u)},[]),K(()=>{let u=c=>{let d=!!i.current?.contentWindow&&c.source===i.current.contentWindow,p=navigator.userActivation?.isActive??!0,f=eu(c.data,{ownFrame:d,activated:p});f!==null&&t(f)};return window.addEventListener("message",u),()=>window.removeEventListener("message",u)},[t]),m("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[l("iframe",{ref:i,className:"min-h-0 w-full flex-1 border-0",style:{colorScheme:a},onLoad:()=>r(!0),...ru(e)}),n?null:l("p",{className:`absolute inset-x-0 top-0 bg-background p-3 text-sm ${o?"text-destructive":"text-muted-foreground"}`,children:o?"The page hasn't loaded. Refresh to try again.":"Loading the page\u2026"})]})}var xI=["","text-xl","text-lg","text-base","text-sm","text-sm","text-sm"];function b1(e,t,n){switch(e.t){case"h":{let r=`h${e.level}`;return l(r,{className:`mb-2 mt-4 font-semibold first:mt-0 ${xI[e.level]}`,children:lr(e.c,n)},t)}case"p":return l("p",{className:"my-2",children:lr(e.c,n)},t);case"ul":case"ol":{let r=e.t;return l(r,{className:`my-2 pl-5 ${e.t==="ul"?"list-disc":"list-decimal"}`,children:e.items.map((o,s)=>l("li",{children:lr(o,n)},s))},t)}case"code":return l("pre",{className:"my-2 overflow-auto rounded bg-muted p-2 text-xs",children:l("code",{children:e.v})},t);case"quote":return l("blockquote",{className:"my-2 border-l-2 pl-3 text-muted-foreground",children:e.blocks.map((r,o)=>b1(r,o,n))},t);case"hr":return l("hr",{className:"my-4"},t);case"table":return l("div",{className:"my-2 overflow-auto",children:m("table",{className:"border-collapse text-xs",children:[l("thead",{children:l("tr",{children:e.head.map((r,o)=>l("th",{className:"border px-2 py-1 font-semibold",style:{textAlign:e.align[o]??"left"},children:lr(r,n)},o))})}),l("tbody",{children:e.rows.map((r,o)=>l("tr",{children:r.map((s,i)=>l("td",{className:"border px-2 py-1",style:{textAlign:e.align[i]??"left"},children:lr(s,n)},i))},o))})]})},t)}}function lr(e,t){return e.map((n,r)=>{switch(n.t){case"text":return n.v;case"code":return l("code",{className:"rounded bg-muted px-1 text-xs",children:n.v},r);case"strong":return l("strong",{children:lr(n.c,t)},r);case"em":return l("em",{children:lr(n.c,t)},r);case"link":return l("a",{...Vr(n.href).kind==="outside"?{href:n.href,target:"_blank",rel:"noopener noreferrer"}:{role:"link",tabIndex:0},className:"cursor-pointer underline",onClick:o=>(o.preventDefault(),t(n.href)),onAuxClick:o=>(o.preventDefault(),t(n.href)),onKeyDown:o=>o.key==="Enter"&&(o.preventDefault(),t(n.href)),children:lr(n.c,t)},r)}})}function y1(e){let[t,n]=_(0),r=e?.threadId,o=e?.name;return K(()=>{if(!(r===void 0||o===void 0))return u1({threadId:r,name:o},()=>n(s=>s+1))},[r,o]),t}function _1({threadId:e,params:t}){let n=Hh(t),r=y1(n);return l(qh,{threadId:n?.threadId??e,initial:n?.name??null,reopened:r},n?`${n.threadId}/${n.name}`:e)}function v1({params:e}){let t=os(),n=Hh(e),r=y1(n),o=n?.threadId??t;return o===void 0?null:o===null?l("p",{className:"p-3 text-sm text-muted-foreground",children:"There's no conversation with your moonlet yet, so there are no artifacts."}):l(qh,{threadId:o,initial:n?.name??null,reopened:r},n?`${n.threadId}/${n.name}`:o)}var cu="artifacts",k1="orbit.artifacts.sort",bI=880,yI=600,cr={kind:"place",place:{kind:"folder",path:""}};function as(e){let t;try{t=e.split("/").filter(Boolean).map(s=>decodeURIComponent(s))}catch{return cr}let[n,...r]=t,o=r.join("/");switch(n){case void 0:return cr;case Ze:return{kind:"place",place:{kind:"folder",path:Ze}};case"recent":return{kind:"place",place:{kind:"recent"}};case"starred":return{kind:"place",place:{kind:"starred"}};case"library":return o?{kind:"place",place:{kind:"folder",path:o}}:cr;case"project":return o?{kind:"place",place:{kind:"project",projectId:o}}:{kind:"group",by:"project"};case"conversation":return o?{kind:"place",place:{kind:"conversation",threadId:o}}:{kind:"group",by:"conversation"};case"tag":return o?{kind:"place",place:{kind:"tag",tag:o}}:cr;case"search":{let s=r.length===1?_I(r[0]):o;return s.trim()?{kind:"search",q:s}:cr}case"saved":return/^sf_[0-9a-f]{12}$/.test(o)?{kind:"saved",id:o}:cr;default:return cr}}function _I(e){try{return decodeURIComponent(e)}catch{return e}}function is(e){if(e.kind==="group")return e.by;if(e.kind==="search")return`search/${encodeURIComponent(e.q)}`;if(e.kind==="saved")return`saved/${e.id}`;let t=e.place;switch(t.kind){case"folder":return t.path===Ze?Ze:t.path?`library/${t.path}`:"";case"recent":return"recent";case"starred":return"starred";case"project":return`project/${t.projectId}`;case"conversation":return`conversation/${t.threadId}`;case"tag":return`tag/${t.tag}`}}function tm(e){return as(e.split("/").filter(Boolean).map(t=>encodeURIComponent(t)).join("/"))}var Bt=e=>({kind:"place",place:{kind:"folder",path:e}});function S1(e,t){return is(e)===is(t)}function E1(e,t){if(e.kind==="search")return[{label:`Search: ${e.q}`,where:null}];if(e.kind==="saved")return[{label:`Saved: ${t.saved(e.id)}`,where:null}];if(e.kind==="group")return[{label:e.by==="project"?"By project":"By conversation",where:null}];let n=e.place;switch(n.kind){case"folder":{if(n.path===Ze)return[{label:"Inbox",where:null}];let r=n.path?n.path.split("/"):[];return[{label:"Library",where:r.length?cr:null},...r.map((o,s)=>({label:o,where:s===r.length-1?null:Bt(r.slice(0,s+1).join("/"))}))]}case"recent":return[{label:"Recent",where:null}];case"starred":return[{label:"Starred",where:null}];case"project":return[{label:"By project",where:{kind:"group",by:"project"}},{label:t.project(n.projectId),where:null}];case"conversation":return[{label:"By conversation",where:{kind:"group",by:"conversation"}},{label:t.conversation(n.threadId),where:null}];case"tag":return[{label:`#${n.tag}`,where:null}]}}function w1(e){return e.kind==="place"&&e.place.kind==="recent"?{by:"modified",desc:!0}:{by:"name",desc:!1}}function nm(e,t){if(t.kind==="place"&&t.place.kind==="recent")return w1(t);try{let n=e?.getItem(k1)??"",[r,o]=n.split(":");if(qk.includes(r??"")&&(o==="asc"||o==="desc"))return{by:r,desc:o==="desc"}}catch{}return w1(t)}function N1(e,t){try{e?.setItem(k1,`${t.by}:${t.desc?"desc":"asc"}`)}catch{}}function A1(e,t){return e.by===t?{by:t,desc:!e.desc}:{by:t,desc:t==="modified"||t==="versions"||t==="size"}}var Pe=e=>e.slice(e.lastIndexOf("/")+1),Ut=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")):"";function uu(e,t,n){let r=o=>n===o||n.startsWith(`${o}/`);switch(e.kind){case"rename":case"move":{let o=t.find(s=>r(s.from));return o===void 0?null:`${o.to}${n.slice(o.from.length)}`}case"delete":{let o=e.items.find(r);return o===void 0?null:Ut(o)}default:return null}}function ka(e){let t=e?e.split("/"):[];return t.map((n,r)=>t.slice(0,r+1).join("/"))}function C1(e){return e>=bI?"wide":e>=yI?"medium":"compact"}function T1(e,t,n){if(!e.length)return null;let r=t===null?-1:e.findIndex(o=>o.path===t);return r<0?e[n===1?0:e.length-1].path:e[Math.max(0,Math.min(e.length-1,r+n))].path}var R1="orbit.artifacts.expanded",$1=200;function I1(e,t,n){let r=[],o=(i,a,u)=>r.push({kind:"note",key:`note:${i}`,depth:a,text:u}),s=(i,a,u,c)=>{for(let d of i){if(c!==null&&!d.path.startsWith(`${c}/`))continue;let p=n.has(d.path);if(r.push({kind:"folder",folder:d,depth:u,open:p}),!p)continue;let f=t(d.path);f?f.state==="refused"?o(d.path,u+1,`Couldn't open it: ${f.reason}`):!f.folders.length&&!f.pages.length?o(d.path,u+1,"Empty"):(s(f.folders,f.pages,u+1,d.path),f.more&&o(d.path,u+1,`Showing the first ${f.pages.length} pages.`)):o(d.path,u+1,"Loading\u2026")}for(let d of a)r.push({kind:"page",page:d,depth:u})};return s(e.folders,e.pages,0,null),r}function P1(e){return e.flatMap(t=>t.kind==="folder"?[{kind:"folder",path:t.folder.path}]:t.kind==="page"?[{kind:"page",path:t.page.path,threadId:t.page.threadId,name:t.page.name}]:[])}function vI(e){let t=new Map;for(let n of e)for(let r of n)t.has(r.path)||t.set(r.path,r);return[...t.values()]}function O1(e,t,n){return t?(+(e.gen===n)-+(t.gen===n)||e.n-t.n)>0:!0}function L1(e,t,n){let r=[...t].sort((o,s)=>+(s.gen===n)-+(o.gen===n)||s.n-o.n);return vI([e,...r.map(o=>o.branch.state==="ok"?o.branch.pages:[])])}function M1(e,t,n){let r=t.kind==="delete",o=i=>{let a=uu(t,n,i);return a===null?i:r?null:a},s=new Map;for(let[i,a]of e){let u=o(i);if(u===null)continue;let c=p=>p.flatMap(f=>{let h=o(f.path);return h!==null&&Ut(h)===u?[{...f,path:h}]:[]}),d=a.branch;s.set(u,d.state==="ok"?{...a,branch:{...d,folders:c(d.folders),pages:c(d.pages)}}:a)}return s}function D1(e){try{let t=JSON.parse(e?.getItem(R1)??"[]");return Array.isArray(t)?new Set(t.filter(n=>typeof n=="string"&&n.length>0&&n.length<=240).slice(-$1)):new Set}catch{return new Set}}function F1(e,t){try{e?.setItem(R1,JSON.stringify([...t].slice(-$1)))}catch{}}function z1(e,t,n){return t.kind!=="move"&&t.kind!=="rename"?new Set(e):new Set([...e].map(r=>uu(t,n,r)??r))}function K1(e,t,n,r,o){let s=new Set(t),i=!t.has(r),a=o&&n!==null?e.findIndex(d=>d.path===n):-1,u=e.findIndex(d=>d.path===r),c=a>=0&&u>=0?e.slice(Math.min(a,u),Math.max(a,u)+1).map(d=>d.path):[r];for(let d of c)i?s.add(d):s.delete(d);return s}var rm=50,om="orbit.artifacts.undo";function X1(e){try{let t=JSON.parse(e?.getItem(om)??"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n=="object"&&Number.isInteger(n.id)&&n.id>0&&typeof n.summary=="string").map(n=>({id:n.id,summary:n.summary.slice(0,300)})).slice(-rm):[]}catch{return[]}}var wI=24,kI=200,ls=new Map,B1=new Map;function U1(e,t,n,r){for(e.delete(t),e.set(t,n);e.size>r;){let o=e.keys().next().value;if(o===void 0)break;e.delete(o)}}var H1={maskImage:"linear-gradient(to bottom, black 60%, transparent)",WebkitMaskImage:"linear-gradient(to bottom, black 60%, transparent)"},SI=[{id:qc,context:{kind:"nav-panel",panelId:At},availability:"action"},{id:Jc,context:{kind:"thread"},availability:"action"}];function V1({attributes:e,message:t}){let n=s1(e,t.threadId);return"problem"in n?l("p",{role:"alert",className:"my-2 rounded-md border border-border bg-muted px-3 py-2 text-sm text-muted-foreground",children:n.problem}):l(CI,{page:n},`${n.threadId}/${n.name}`)}function EI(e){return e.state==="offline"?`${e.machine??"This conversation's machine"} is offline, so this page can't be shown until it's back.`:`This page can't be shown: ${e.reason}.`}function NI(){let[e,t]=_(null),[n,r]=_(()=>Vh(0,0));return ot(()=>{if(e===null)return;let o=()=>r(Vh(e.getBoundingClientRect().width,window.innerHeight));o(),window.addEventListener("resize",o);let s=typeof ResizeObserver>"u"?null:new ResizeObserver(o);return s?.observe(e),()=>{window.removeEventListener("resize",o),s?.disconnect()}},[e]),[t,n]}function AI(){let e=W_(),t=Ie();return q((n,r)=>{let o={threadId:n.threadId,name:n.name};c1(o);for(let s of SI)if(e.experimental_openTab({surface:{kind:"current"},tab:s,params:o,title:r??n.name}))return;t.toPluginPanel(cu)},[t,e])}function CI({page:e}){let t=J(),n=`${e.threadId}/${e.name}`,[r,o]=_(()=>{let T=ls.get(n);return T?{state:"ready",page:T}:{state:"loading"}});K(()=>{let T=!0;return t.call("artifacts.read",{threadId:e.threadId,name:e.name}).then(N=>{if(!T)return;if(N.state==="refused"&&ls.delete(n),N.state!=="ok"){ls.has(n)||o({state:"problem",reason:EI(N)});return}let S=Zr(N.page);if(S.kind==="refused"){ls.delete(n),o({state:"problem",reason:`This page can't be shown: ${S.reason}.`});return}let $={title:i1(N.page.kind,N.page.content),detail:wa(N.page.size,N.page.modifiedAt)},P=S.kind==="frame"?{...$,kind:"html",srcDoc:a1(S.srcDoc)}:{...$,kind:"md",blocks:S.blocks};U1(ls,n,P,wI),o({state:"ready",page:P})},N=>{T&&!ls.has(n)&&o({state:"problem",reason:`This page can't be shown: ${N instanceof Error?N.message:String(N)}.`})}),()=>{T=!1}},[t,n,e.threadId,e.name]);let s=r.state==="ready"?r.page:null,i=s?.title??null,a=J(),u=AI(),c=q(()=>u(e,i),[u,e,i]),[d,p]=_(!1),[f,h]=_(null),[g,x]=_(null),b=Y(0),v=q(T=>{let N=Vr(T),S=++b.current;if(h(N.kind==="outside"?N.url:null),N.kind!=="page")return x(tu(N));x(null),a.call("artifacts.follow",{threadId:e.threadId,name:e.name,href:T}).then($=>{S===b.current&&($.state==="page"?u({threadId:$.threadId,name:$.name},null):x(su($)))},$=>S===b.current&&x(`The link wasn't followed: ${$ instanceof Error?$.message:String($)}.`))},[u,e,a]),w=i??e.name,[C,y]=NI();return m("section",{ref:C,"aria-label":`Page: ${w}`,"data-moonlet-artifact":"",className:"my-2 min-w-0 overflow-hidden rounded-lg border border-border bg-background",children:[m("header",{className:"flex items-center gap-2 py-1.5 pl-3 pr-1.5",children:[l(pe,{name:"FileText","aria-hidden":!0,className:"size-3.5 shrink-0 text-subtle-foreground"}),m("div",{className:"flex min-w-0 flex-1 items-baseline gap-2 text-xs",children:[l("span",{className:"max-w-full shrink-0 truncate font-medium text-foreground",children:w}),r.state==="problem"?null:l("span",{className:"truncate text-subtle-foreground",children:s?`${i?`${e.name} \xB7 `:""}${s.detail}`:"Opening\u2026"})]}),l("button",{type:"button",onClick:c,"aria-label":`Open ${w} beside the chat`,title:"Open beside the chat",className:"inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-state-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",children:l(pe,{name:"PanelRight","aria-hidden":!0,className:"size-3.5"})})]}),f?l(em,{url:f,onClose:()=>h(null)}):g?m("div",{role:"status",className:"flex items-center gap-2 border-t border-border bg-muted px-3 py-2 text-xs",children:[l("span",{className:"min-w-0 flex-1",children:g}),l(R,{size:"sm",variant:"secondary",onClick:()=>x(null),children:"OK"})]}):null,l("div",{className:"border-t border-border",children:r.state==="problem"?l("p",{className:"px-3 py-2.5 text-sm text-muted-foreground",children:r.reason}):s?s.kind==="html"?l(TI,{srcDoc:s.srcDoc,heightKey:`${n}/${s.srcDoc.length}`,name:w,limit:y,onOpen:c,onLink:v,onClamped:p},s.srcDoc):l(RI,{blocks:s.blocks,limit:y,onOpen:c,onLink:v,onClamped:p}):m("div",{role:"status","aria-busy":"true","aria-label":`Opening ${e.name}`,className:"flex flex-col gap-2.5 px-4 py-4",children:[l("span",{className:"h-4 w-2/5 animate-pulse rounded bg-muted"}),l("span",{className:"h-3 w-full animate-pulse rounded bg-muted"}),l("span",{className:"h-3 w-3/5 animate-pulse rounded bg-muted"})]})}),s&&d?m("button",{type:"button",onClick:c,className:"flex w-full cursor-pointer items-center justify-center gap-1.5 border-t border-border py-1.5 text-xs text-muted-foreground transition-colors hover:bg-state-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring",children:["Read the whole page",l(pe,{name:"PanelRight","aria-hidden":!0,className:"size-3.5"})]}):null]})}function Z1({onOpen:e}){return l("button",{type:"button","aria-hidden":!0,tabIndex:-1,className:"absolute inset-0 cursor-pointer",onClick:e})}function TI({srcDoc:e,heightKey:t,name:n,limit:r,onOpen:o,onLink:s,onClamped:i}){let a=Y(null),u=lu(),[c,d]=_(()=>B1.get(t)??null);K(()=>{let f=h=>{let g=!!a.current?.contentWindow&&h.source===a.current.contentWindow,x=l1(h.data,g);if(x!==null){U1(B1,t,x,kI),d(x);return}let b=navigator.userActivation?.isActive??!0,v=eu(h.data,{ownFrame:g,activated:b});v!==null&&s(v)};return window.addEventListener("message",f),()=>window.removeEventListener("message",f)},[t,s]);let p=Zh(c,r);return K(()=>i(p.clamped),[p.clamped,i]),m("div",{className:"relative",style:{height:p.height,...p.clamped?H1:{}},children:[l("iframe",{ref:a,...ru({srcDoc:e}),title:n,tabIndex:p.clamped?-1:void 0,className:V("block size-full border-0 transition-opacity duration-150",c===null&&"opacity-0",p.clamped&&"pointer-events-none"),style:{colorScheme:u}}),p.clamped?l(Z1,{onOpen:o}):null]})}function RI({blocks:e,limit:t,onOpen:n,onLink:r,onClamped:o}){let s=Y(null),[i,a]=_(null);ot(()=>{let c=s.current;if(c===null||(a(c.getBoundingClientRect().height),typeof ResizeObserver>"u"))return;let d=new ResizeObserver(()=>a(c.getBoundingClientRect().height));return d.observe(c),()=>d.disconnect()},[]);let u=Zh(i,t);return K(()=>o(u.clamped),[u.clamped,o]),m("div",{className:"relative overflow-hidden",style:u.clamped?{maxHeight:u.height,...H1}:void 0,children:[l("div",{ref:s,className:"px-4 py-3 text-sm leading-relaxed",inert:u.clamped,children:l(Jh,{blocks:e,follow:r})}),u.clamped?l(Z1,{onOpen:n}):null]})}async function du(e,t){let n=[t.orbit,t.background,...t.policyJobs??[]].filter(d=>!!d);if(!n.length)return{jobs:[],errors:[]};let o=(await e.threadSections.list()).find(d=>d.name==="Orbit"),s=[];if(o)for(let d=0;;d+=100){let p=await e.threads.list({sectionId:o.id,includeHidden:!0,limit:100,offset:d});if(s.push(...p.map(f=>f.id)),p.length<100)break}let i=await e.threads.experimental_listDescendants({threadIds:[...new Set([...n,...s])],includeHidden:!0,includeArchived:!1}),a=[...new Set([...n,...s,...i.threads.flatMap(d=>d.descendantIds)])],u=[],c=[];for(let d=0;d<a.length;d+=8)await Promise.all(a.slice(d,d+8).map(async p=>{try{let[f,h]=await Promise.all([e.threads.get({threadId:p}),e.threads.interactions.list({threadId:p})]);for(let g of h)g.status==="pending"&&u.push({title:f.title||"Untitled work",interaction:g})}catch{c.push(p)}}));return u.sort((d,p)=>d.interaction.createdAt-p.interaction.createdAt||d.interaction.id.localeCompare(p.interaction.id)),{jobs:u,errors:c}}function sm(e,t){return e.length>0&&e.every(n=>{let r=t[n.id];return!r||!n.multiSelect&&r.selected.length+(r.freeText?.trim()?1:0)>1||r.selected.some(o=>!n.options?.some(s=>s.value===o))||r.freeText?.trim()&&!n.allowFreeText?!1:r.selected.length>0||n.allowFreeText&&!!r.freeText?.trim()})}function W1(e){let t=e.subject;switch(t.kind){case"command":return{title:"Approve running this command?",detail:t.cwd?`${t.command}
136
+ `)})}else if(y1(s)){let a=y1(s);n.push({t:"h",level:a.level,c:lr(a.text)}),r++}else if(/^\s{0,3}((\*\s*){3,}|(-\s*){3,}|(_\s*){3,})$/.test(s))n.push({t:"hr"}),r++;else if(/^\s{0,3}>/.test(s)){let a=[];for(;r<t.length&&/^\s{0,3}>/.test(t[r]);)a.push(t[r++].replace(/^\s{0,3}>\s?/,""));n.push({t:"quote",blocks:qh(a.join(`
137
+ `))})}else if(i=/^\s{0,3}([-*+]|\d{1,9}[.)])\s+/.exec(s)){let a=/\d/.test(i[1]),u=a?/^\s{0,3}\d{1,9}[.)]\s+(.*)$/:/^\s{0,3}[-*+]\s+(.*)$/,c=[];for(;r<t.length&&t[r].trim();){let d=u.exec(t[r]);if(d)c.push(d[1]);else if(c.length&&!o(t[r]))c[c.length-1]+=` ${t[r].trim().replace(/^([-*+]|\d{1,9}[.)])\s+/,"")}`;else break;r++}n.push({t:a?"ol":"ul",items:c.map(lr)})}else if(s.includes("|")&&r+1<t.length&&_1.test(t[r+1])){let a=Yh(s),u=Yh(t[r+1]).map(d=>d.startsWith(":")&&d.endsWith(":")?"center":d.endsWith(":")?"right":d.startsWith(":")?"left":null);r+=2;let c=[];for(;r<t.length&&t[r].trim()&&t[r].includes("|");){let d=Yh(t[r++]);c.push(a.map((p,f)=>lr(d[f]??"")))}n.push({t:"table",align:a.map((d,p)=>u[p]??null),head:a.map(lr),rows:c})}else{let a=[];for(;r<t.length&&t[r].trim()&&!o(t[r])&&!(t[r].includes("|")&&r+1<t.length&&_1.test(t[r+1]));)a.push(t[r++].trim());a.length||a.push(t[r++].trim()),n.push({t:"p",c:lr(a.join(" "))})}}return n}function Jh(e){switch(e.state){case"offline":return`${e.machine??"This conversation's machine"} is offline, so this conversation's artifacts can't be read. Refresh once it's back.`;case"refused":return`Couldn't list the artifacts: ${e.reason}.`;case"ok":return e.artifacts.length?null:"This conversation has no artifacts yet. When it shows a page in its chat, the page appears here too."}}function Wr(e){let t=r1(e.kind,e.content);return t?{kind:"refused",reason:t}:e.kind==="md"?{kind:"markdown",blocks:qh(Jc(e.content))}:{kind:"frame",srcDoc:g1(e.content)}}function ou(e){return e.state==="ok"?Wr(e.page):{kind:"refused",reason:e.state==="refused"?e.reason:Jh(e)??""}}function is(e){return{kind:"refused",reason:`Couldn't open the page: ${e instanceof Error?e.message:String(e)}`}}function su(e){return{...{title:"Page",sandbox:"allow-scripts",referrerPolicy:"no-referrer",allow:""},csp:Bh,srcDoc:e.srcDoc}}function ka(e,t,n=Date.now()){return`${e<1024?`${e} B`:`${Math.round(e/1024)} KB`} \xB7 ${jr(t,n)}`}function jr(e,t=Date.now()){let n=Math.max(0,Math.round((t-e)/6e4));return n<1?"just now":n<60?`${n} min ago`:n<2880?`${Math.round(n/60)} h ago`:new Date(e).toLocaleDateString()}function v1(e,t){let n=e.by==="owner"?"you":e.by===t?"this conversation":e.by,r=e.source==="restore"?`${n}, restored v${e.restoredFrom}`:n,o=new Date(e.at).toLocaleString(void 0,{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"});return`v${e.n} \xB7 ${o} \xB7 ${r} \xB7 ${ka(e.size,e.at).split(" \xB7 ")[0]}`}function iu(e){return e.versionsError?`Versions aren't available (${e.versionsError}): this is the conversation's file as it is now.`:e.pinned!==void 0?`Pinned to v${e.pinned}: shown until it's unpinned (History), whatever the conversation writes next.${e.gone?" The conversation's file is gone.":""}`:e.gone?`The conversation's file is gone; this is the last version kept${e.version?` (v${e.version})`:""}.`:e.restoredFrom!==void 0?`v${e.version}, restored from v${e.restoredFrom}. The conversation's own file is unchanged.`:e.version?`v${e.version}`:null}function au(e){switch(e.state){case"page":return null;case"deleted":return`That page (${e.path}) was deleted from the library on ${new Date(e.at).toLocaleDateString()}.`;case"missing":return`There's no page at ${e.path} in the library.`;case"refused":return`The link wasn't followed: ${e.reason}.`}}function Dn(){try{return globalThis.localStorage??null}catch{return null}}function cu({threadId:e,name:t,shown:n,about:r,onChanged:o,onNavigate:s,onBack:i}){let a=J(),[u,c]=v("page");M(()=>c("page"),[e,t]);let d=G(0);M(()=>{d.current++},[e,t]);let p=q(async h=>{let g=++d.current,x=await a.call("artifacts.follow",{threadId:e,name:t,href:h});return g!==d.current?null:(x.state==="page"&&s(x.threadId,x.name,x.path),au(x))},[a,e,t,s]),f=h=>c(g=>g===h?"page":h);return m("div",{className:"flex min-h-0 flex-1 flex-col",children:[m("div",{className:"flex items-center gap-2 border-b px-3 py-1.5 text-xs text-muted-foreground",children:[i?l(R,{size:"sm",variant:"secondary",onClick:i,children:"Back"}):null,l("span",{className:"min-w-0 flex-1 truncate",children:u==="history"?`History of ${t}`:u==="links"?`Links of ${t}`:r??""}),l(R,{size:"sm",variant:u==="links"?"default":"secondary",onClick:()=>f("links"),children:u==="links"?"Back to the page":"Links"}),l(R,{size:"sm",variant:u==="history"?"default":"secondary",onClick:()=>f("history"),children:u==="history"?"Back to the page":"History"})]}),u==="history"?l(fI,{threadId:e,name:t,onRestored:()=>{c("page"),o()}}):u==="links"?l(pI,{threadId:e,name:t,onNavigate:s}):l(lu,{shown:n,onPageLink:p})]})}var dI={page:"",deleted:"deleted",missing:"broken: no such page",refused:"not followed",outside:"outside Moonlet"};function pI({threadId:e,name:t,onNavigate:n}){let r=J(),[o,s]=v(null),[i,a]=v("");if(M(()=>{let c=!0;return s(null),r.call("artifacts.links",{threadId:e,name:t}).then(d=>c&&s(d),d=>c&&a(d instanceof Error?d.message:String(d))),()=>{c=!1}},[r,e,t]),!o)return l("p",{className:`p-3 text-sm ${i?"text-destructive":"text-muted-foreground"}`,children:i||"Reading its links\u2026"});let u=o.out.filter(c=>c.state==="missing"||c.state==="deleted").length;return m("div",{className:"min-h-0 flex-1 overflow-auto p-3 text-sm",children:[o.path?l("p",{className:"mb-2 text-xs text-muted-foreground",children:o.path}):l("p",{className:"mb-2 text-xs text-muted-foreground",children:"Not in the library yet."}),m("h3",{className:"mb-1 font-medium",children:["Linked from (",o.from.length,")"]}),o.from.length?l("ul",{className:"mb-3",children:o.from.map(c=>l("li",{children:l("button",{type:"button",className:"underline",onClick:()=>n(c.threadId,c.name,c.path),children:c.path})},c.path))}):l("p",{className:"mb-3 text-xs text-muted-foreground",children:"No page in this project links here."}),m("h3",{className:"mb-1 font-medium",children:["Links on this page (",o.out.length,")",u?`, ${u} broken`:""]}),o.out.length?l("ul",{children:o.out.map(c=>m("li",{className:"flex gap-2 text-xs",children:[m("span",{className:"min-w-0 flex-1 truncate",children:[c.href,c.path&&c.path!==c.href?` \u2192 ${c.path}`:""]}),l("span",{className:c.state==="missing"||c.state==="deleted"?"text-destructive":"text-muted-foreground",children:dI[c.state]})]},c.href))}):l("p",{className:"text-xs text-muted-foreground",children:"This page has no links."}),u?l("p",{className:"mt-2 text-xs text-muted-foreground",children:"Only the page's conversation can fix a broken link (by rewriting the page)."}):null]})}function fI({threadId:e,name:t,onRestored:n}){let r=J(),[o,s]=v(null),[i,a]=v(""),[u,c]=v(null),[d,p]=v("page"),[f,h]=v(null),[g,x]=v(null),[b,_]=v(null),[w,T]=v(!1),[y,E]=v(null),[k,N]=v(0),$=Q=>a(Q instanceof Error?Q.message:String(Q));M(()=>a(""),[e,t]),M(()=>{let Q=!0;return r.call("artifacts.history",{threadId:e,name:t}).then(j=>{if(Q){if(j.state==="refused")return a(j.reason);s(j),c(Y=>Y!==null&&j.versions.some(ee=>ee.n===Y)?Y:j.versions[0]?.n??null)}},j=>Q&&$(j)),()=>{Q=!1}},[r,e,t,k]);let P=o?.versions[0]?.n??null,L=q(async Q=>{let j=await r.call("artifacts.version",{threadId:e,name:t,n:Q});if(j.state==="refused")throw new Error(j.reason);return j.page},[r,e,t]),ne=d==="compare"&&u!==P;M(()=>{let Q=!0;return h(null),x(null),_(null),u!==null&&!ne?L(u).then(j=>Q&&h(Wr({kind:j.kind,content:j.content})),j=>Q&&h(is(j))):u!==null&&P!==null&&Promise.all([L(u),L(P)]).then(([j,Y])=>{Q&&(x(b1(j.kind,j.content,Y.content)),_([Wr({kind:j.kind,content:j.content}),Wr({kind:Y.kind,content:Y.content})]))},j=>Q&&$(j)),()=>{Q=!1}},[u,ne,P,L]);let se=async Q=>{if(P===null)return;let j=await r.call("artifacts.pin",{threadId:e,name:t,n:Q,latest:P});j.state==="refused"?(a(j.reason),N(Y=>Y+1)):n()},_e=async()=>{if(!y||P===null)return;let Q=y.what==="restore"?await r.call("artifacts.restore",{threadId:e,name:t,n:y.n,latest:P}):await r.call("artifacts.forget",{threadId:e,name:t,n:y.n,latest:P});E(null),Q.state==="refused"?(a(Q.reason),N(j=>j+1)):y.what==="restore"?n():N(j=>j+1)};if(!o)return l("p",{className:`p-3 text-sm ${i?"text-destructive":"text-muted-foreground"}`,children:i||"Loading the history\u2026"});let ie=u===P;return m("div",{className:"flex min-h-0 flex-1 flex-col",children:[l("ul",{className:"max-h-[40%] shrink-0 overflow-auto border-b",children:o.versions.map(Q=>l("li",{children:m("button",{type:"button","aria-pressed":Q.n===u,className:`flex w-full items-baseline gap-2 px-3 py-1.5 text-left text-xs hover:bg-muted ${Q.n===u?"bg-muted font-medium":""}`,onClick:()=>c(Q.n),children:[l("span",{className:"min-w-0 flex-1 truncate",children:v1(Q,e)}),Q.n===o.pinned?l("span",{className:"shrink-0 font-medium",children:"pinned"}):null,Q.n===P?l("span",{className:"shrink-0 text-muted-foreground",children:"latest"}):null,Q.n===o.fileVersion&&!o.fileGone?l("span",{className:"shrink-0 text-muted-foreground",children:"the file now"}):null]})},Q.n))}),i?l("p",{className:"px-3 py-1.5 text-xs text-destructive",children:i}):null,y?m("div",{className:"flex flex-col gap-2 border-b bg-muted px-3 py-2 text-xs",role:"alertdialog",children:[l("span",{children:y.what==="restore"?`Restore v${y.n}? It becomes v${(P??0)+1}, the latest, with v${y.n}'s content. The conversation's own file isn't changed, and every version stays.`:`Delete v${y.n} for good? Its content can't be brought back.`}),m("div",{className:"flex gap-2",children:[l(R,{size:"sm",variant:"secondary",onClick:()=>E(null),children:"Cancel"}),l(R,{size:"sm",variant:y.what==="forget"?"destructive":"default",onClick:()=>{_e().catch($)},children:y.what==="restore"?"Restore":"Delete"})]})]}):u!==null?m("div",{className:"flex flex-wrap items-center gap-2 border-b px-3 py-1.5 text-xs",children:[l(R,{size:"sm",variant:ne?"secondary":"default",onClick:()=>p("page"),children:"View"}),l(R,{size:"sm",variant:ne?"default":"secondary",disabled:ie,onClick:()=>p("compare"),children:"Compare with latest"}),l("span",{className:"flex-1"}),o.pinned!==null?m(R,{size:"sm",variant:"secondary",onClick:()=>{se(null).catch($)},children:["Unpin v",o.pinned]}):null,o.pinned!==u?l(R,{size:"sm",variant:"secondary",onClick:()=>{se(u).catch($)},children:"Pin this version"}):null,l(R,{size:"sm",variant:"secondary",disabled:ie,onClick:()=>E({what:"restore",n:u}),children:"Restore\u2026"}),l(R,{size:"sm",variant:"secondary",disabled:ie||u===o.pinned,onClick:()=>E({what:"forget",n:u}),children:"Delete\u2026"})]}):null,ne?m("div",{className:"flex min-h-0 flex-1 flex-col",children:[m("div",{className:"flex gap-2 border-b px-3 py-1.5 text-xs",children:[l(R,{size:"sm",variant:w?"default":"secondary",onClick:()=>T(!0),children:"Drawn"}),l(R,{size:"sm",variant:w?"secondary":"default",onClick:()=>T(!1),children:"Source"})]}),w?l("div",{className:"flex min-h-0 flex-1",children:b?b.map((Q,j)=>m("div",{className:"flex min-w-0 flex-1 flex-col border-r",children:[m("p",{className:"border-b px-3 py-1 text-xs text-muted-foreground",children:["v",j===0?u:P]}),l(lu,{shown:Q})]},j)):l("p",{className:"p-3 text-sm text-muted-foreground",children:"Comparing\u2026"})}):l(gI,{diff:g,older:u,newer:P})]}):l(lu,{shown:f})]})}var hI={same:" ",add:"+",del:"-"},mI={same:"",add:"bg-green-500/15",del:"bg-red-500/15"};function gI({diff:e,older:t,newer:n}){return e?e.state==="too-big"?m("p",{className:"p-3 text-sm text-muted-foreground",children:["These versions differ too much to compare line by line (",e.lines[0]," and ",e.lines[1]," lines). View each instead."]}):m("div",{className:"min-h-0 flex-1 overflow-auto font-mono text-xs",children:[m("p",{className:"px-3 py-1.5 font-sans text-muted-foreground",children:["v",t," \u2192 v",n,": ",e.added," line",e.added===1?"":"s"," added, ",e.removed," removed",e.hunks.length?"":" (the same source)"]}),e.hunks.map((r,o)=>m("div",{children:[r.skippedBefore?m("p",{className:"px-3 py-0.5 font-sans text-muted-foreground",children:["\u2026 ",r.skippedBefore," unchanged lines"]}):null,r.lines.map((s,i)=>m("pre",{className:`whitespace-pre-wrap break-all px-3 ${mI[s.t]}`,children:[hI[s.t]," ",s.text]},i))]},o)),e.skippedAfter&&e.hunks.length?m("p",{className:"px-3 py-0.5 font-sans text-muted-foreground",children:["\u2026 ",e.skippedAfter," unchanged lines"]}):null]}):l("p",{className:"p-3 text-sm text-muted-foreground",children:"Comparing\u2026"})}function xI(e){let t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),()=>t.disconnect()}function bI(){return document.documentElement.classList.contains("dark")?"dark":"light"}function uu(){return xt(xI,bI,()=>"light")}function em({threadId:e,initial:t=null,reopened:n=0}){let r=J(),[o,s]=v(null),[i,a]=v(""),[u,c]=v(t),[d,p]=v(e),[f,h]=v([]),[g,x]=v(null),[b,_]=v(null),[w,T]=v(0),y=L=>a(L instanceof Error?L.message:String(L));M(()=>{a(""),r.call("artifacts.list",{threadId:e}).then(s,y)},[r,e,w]);let E=G(0),k=q((L,ne=e)=>{let se=++E.current;c(L),p(ne),x(null),_(null),r.call("artifacts.read",{threadId:ne,name:L}).then(_e=>se===E.current&&(x(ou(_e)),_(_e.state==="ok"?iu(_e.page):null)),_e=>se===E.current&&x(is(_e)))},[r,e]),N=G(t!==null);M(()=>{t!==null&&k(t)},[]),M(()=>{n===0||t===null||(h([]),k(t))},[n]),M(()=>{o&&N.current&&(N.current=!1,w===0)||u&&d===e&&o?.state==="ok"&&o.artifacts.some(L=>L.name===u)&&k(u)},[o]);let $=i?`Couldn't reach the artifacts: ${i}`:o?Jh(o):"Loading\u2026",P=o?.state==="ok"?o.artifacts:[];return m("div",{className:"flex h-full flex-col",children:[m("div",{className:"flex items-center gap-2 border-b px-3 py-2 text-xs",children:[u?l(R,{size:"sm",variant:"secondary",onClick:()=>(c(null),x(null),h([])),children:"All artifacts"}):null,u?l("span",{className:"min-w-0 flex-1 truncate font-medium",children:`${u}${d===e?"":" (another conversation's)"}`}):l("span",{className:"min-w-0 flex-1 truncate font-medium",children:"This conversation"}),l(R,{size:"sm",variant:"secondary",onClick:()=>T(L=>L+1),children:"Refresh"})]}),u?l(cu,{threadId:d,name:u,shown:g,about:b,onChanged:()=>k(u,d),onNavigate:(L,ne)=>{h(se=>[...se,{threadId:d,name:u}]),k(ne,L)},onBack:f.length?()=>{let L=f.at(-1);h(ne=>ne.slice(0,-1)),k(L.name,L.threadId)}:null},n):$?l("p",{className:"p-3 text-sm text-muted-foreground",children:$}):l("ul",{className:"min-h-0 flex-1 overflow-auto",children:P.map(L=>l("li",{children:m("button",{type:"button",className:"flex w-full items-baseline gap-2 px-3 py-2 text-left text-sm hover:bg-muted",onClick:()=>(h([]),k(L.name)),children:[l("span",{className:`min-w-0 flex-1 truncate ${L.gone?"text-muted-foreground":""}`,children:L.name}),m("span",{className:"shrink-0 text-xs text-muted-foreground",children:[L.gone?"file gone \xB7 ":"",ka(L.size,L.modifiedAt)]})]})},L.name))})]})}function lu({shown:e,onPageLink:t}){let[n,r]=v(null),[o,s]=v(null);M(()=>{r(null),s(null)},[e]);let i=q(u=>{let c=Zr(u);r(c.kind==="outside"?c.url:null),c.kind==="page"&&t?(s(null),t(u).then(s,d=>s(`The link wasn't followed: ${d instanceof Error?d.message:String(d)}.`))):s(ru(c))},[t]);if(!e)return l("p",{className:"p-3 text-sm text-muted-foreground",children:"Opening the page\u2026"});if(e.kind==="refused")return l("p",{className:"p-3 text-sm text-destructive",children:e.reason});let a=n?l(nm,{url:n,onClose:()=>r(null)}):o?m("div",{className:"flex items-center gap-2 border-b bg-muted px-3 py-2 text-xs",role:"status",children:[l("span",{className:"min-w-0 flex-1",children:o}),l(R,{size:"sm",variant:"secondary",onClick:()=>s(null),children:"OK"})]}):null;return e.kind==="markdown"?m("div",{className:"flex min-h-0 flex-1 flex-col",children:[a,l("div",{className:"min-h-0 flex-1 overflow-auto p-4 text-sm leading-relaxed",children:l(tm,{blocks:e.blocks,follow:i})})]}):m("div",{className:"flex min-h-0 flex-1 flex-col",children:[a,l(_I,{frame:e,onLink:i},e.srcDoc)]})}function tm({blocks:e,follow:t}){return l(he,{children:e.map((n,r)=>w1(n,r,t))})}function nm({url:e,onClose:t}){let[n,r]=v(!1);return m("div",{className:"flex flex-col gap-2 border-b bg-muted px-3 py-2 text-xs",role:"alertdialog","aria-label":"Open a link outside Moonlet?",children:[l("span",{className:"font-medium",children:"Open a link outside Moonlet?"}),l("code",{className:"break-all rounded bg-background px-1 py-0.5",children:e}),l("span",{className:"text-muted-foreground",children:"It opens in a new tab, with no referrer. The page can't see whether you open it."}),m("div",{className:"flex gap-2",children:[l(R,{size:"sm",variant:"secondary",onClick:t,children:"Cancel"}),l(R,{size:"sm",variant:"secondary",onClick:()=>{navigator.clipboard?.writeText(e).then(()=>r(!0),()=>{})},children:n?"Copied":"Copy address"}),l(R,{size:"sm",onClick:()=>(window.open(e,"_blank","noopener,noreferrer"),t()),children:"Open in new tab"})]})]})}var yI=15e3;function _I({frame:e,onLink:t}){let[n,r]=v(!1),[o,s]=v(!1),i=G(null),a=uu();return M(()=>{let u=setTimeout(()=>s(!0),yI);return()=>clearTimeout(u)},[]),M(()=>{let u=c=>{let d=!!i.current?.contentWindow&&c.source===i.current.contentWindow,p=navigator.userActivation?.isActive??!0,f=nu(c.data,{ownFrame:d,activated:p});f!==null&&t(f)};return window.addEventListener("message",u),()=>window.removeEventListener("message",u)},[t]),m("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[l("iframe",{ref:i,className:"min-h-0 w-full flex-1 border-0",style:{colorScheme:a},onLoad:()=>r(!0),...su(e)}),n?null:l("p",{className:`absolute inset-x-0 top-0 bg-background p-3 text-sm ${o?"text-destructive":"text-muted-foreground"}`,children:o?"The page hasn't loaded. Refresh to try again.":"Loading the page\u2026"})]})}var vI=["","text-xl","text-lg","text-base","text-sm","text-sm","text-sm"];function w1(e,t,n){switch(e.t){case"h":{let r=`h${e.level}`;return l(r,{className:`mb-2 mt-4 font-semibold first:mt-0 ${vI[e.level]}`,children:cr(e.c,n)},t)}case"p":return l("p",{className:"my-2",children:cr(e.c,n)},t);case"ul":case"ol":{let r=e.t;return l(r,{className:`my-2 pl-5 ${e.t==="ul"?"list-disc":"list-decimal"}`,children:e.items.map((o,s)=>l("li",{children:cr(o,n)},s))},t)}case"code":return l("pre",{className:"my-2 overflow-auto rounded bg-muted p-2 text-xs",children:l("code",{children:e.v})},t);case"quote":return l("blockquote",{className:"my-2 border-l-2 pl-3 text-muted-foreground",children:e.blocks.map((r,o)=>w1(r,o,n))},t);case"hr":return l("hr",{className:"my-4"},t);case"table":return l("div",{className:"my-2 overflow-auto",children:m("table",{className:"border-collapse text-xs",children:[l("thead",{children:l("tr",{children:e.head.map((r,o)=>l("th",{className:"border px-2 py-1 font-semibold",style:{textAlign:e.align[o]??"left"},children:cr(r,n)},o))})}),l("tbody",{children:e.rows.map((r,o)=>l("tr",{children:r.map((s,i)=>l("td",{className:"border px-2 py-1",style:{textAlign:e.align[i]??"left"},children:cr(s,n)},i))},o))})]})},t)}}function cr(e,t){return e.map((n,r)=>{switch(n.t){case"text":return n.v;case"code":return l("code",{className:"rounded bg-muted px-1 text-xs",children:n.v},r);case"strong":return l("strong",{children:cr(n.c,t)},r);case"em":return l("em",{children:cr(n.c,t)},r);case"link":return l("a",{...Zr(n.href).kind==="outside"?{href:n.href,target:"_blank",rel:"noopener noreferrer"}:{role:"link",tabIndex:0},className:"cursor-pointer underline",onClick:o=>(o.preventDefault(),t(n.href)),onAuxClick:o=>(o.preventDefault(),t(n.href)),onKeyDown:o=>o.key==="Enter"&&(o.preventDefault(),t(n.href)),children:cr(n.c,t)},r)}})}function k1(e){let[t,n]=v(0),r=e?.threadId,o=e?.name;return M(()=>{if(!(r===void 0||o===void 0))return h1({threadId:r,name:o},()=>n(s=>s+1))},[r,o]),t}function S1({threadId:e,params:t}){let n=Zh(t),r=k1(n);return l(em,{threadId:n?.threadId??e,initial:n?.name??null,reopened:r},n?`${n.threadId}/${n.name}`:e)}function E1({params:e}){let t=ss(),n=Zh(e),r=k1(n),o=n?.threadId??t;return o===void 0?null:o===null?l("p",{className:"p-3 text-sm text-muted-foreground",children:"There's no conversation with your moonlet yet, so there are no artifacts."}):l(em,{threadId:o,initial:n?.name??null,reopened:r},n?`${n.threadId}/${n.name}`:o)}var du="artifacts",A1="orbit.artifacts.sort",wI=880,kI=600,ur={kind:"place",place:{kind:"folder",path:""}};function ls(e){let t;try{t=e.split("/").filter(Boolean).map(s=>decodeURIComponent(s))}catch{return ur}let[n,...r]=t,o=r.join("/");switch(n){case void 0:return ur;case Ze:return{kind:"place",place:{kind:"folder",path:Ze}};case"recent":return{kind:"place",place:{kind:"recent"}};case"starred":return{kind:"place",place:{kind:"starred"}};case"library":return o?{kind:"place",place:{kind:"folder",path:o}}:ur;case"project":return o?{kind:"place",place:{kind:"project",projectId:o}}:{kind:"group",by:"project"};case"conversation":return o?{kind:"place",place:{kind:"conversation",threadId:o}}:{kind:"group",by:"conversation"};case"tag":return o?{kind:"place",place:{kind:"tag",tag:o}}:ur;case"search":{let s=r.length===1?SI(r[0]):o;return s.trim()?{kind:"search",q:s}:ur}case"saved":return/^sf_[0-9a-f]{12}$/.test(o)?{kind:"saved",id:o}:ur;default:return ur}}function SI(e){try{return decodeURIComponent(e)}catch{return e}}function as(e){if(e.kind==="group")return e.by;if(e.kind==="search")return`search/${encodeURIComponent(e.q)}`;if(e.kind==="saved")return`saved/${e.id}`;let t=e.place;switch(t.kind){case"folder":return t.path===Ze?Ze:t.path?`library/${t.path}`:"";case"recent":return"recent";case"starred":return"starred";case"project":return`project/${t.projectId}`;case"conversation":return`conversation/${t.threadId}`;case"tag":return`tag/${t.tag}`}}function rm(e){return ls(e.split("/").filter(Boolean).map(t=>encodeURIComponent(t)).join("/"))}var Bt=e=>({kind:"place",place:{kind:"folder",path:e}});function C1(e,t){return as(e)===as(t)}function T1(e,t){if(e.kind==="search")return[{label:`Search: ${e.q}`,where:null}];if(e.kind==="saved")return[{label:`Saved: ${t.saved(e.id)}`,where:null}];if(e.kind==="group")return[{label:e.by==="project"?"By project":"By conversation",where:null}];let n=e.place;switch(n.kind){case"folder":{if(n.path===Ze)return[{label:"Inbox",where:null}];let r=n.path?n.path.split("/"):[];return[{label:"Library",where:r.length?ur:null},...r.map((o,s)=>({label:o,where:s===r.length-1?null:Bt(r.slice(0,s+1).join("/"))}))]}case"recent":return[{label:"Recent",where:null}];case"starred":return[{label:"Starred",where:null}];case"project":return[{label:"By project",where:{kind:"group",by:"project"}},{label:t.project(n.projectId),where:null}];case"conversation":return[{label:"By conversation",where:{kind:"group",by:"conversation"}},{label:t.conversation(n.threadId),where:null}];case"tag":return[{label:`#${n.tag}`,where:null}]}}function N1(e){return e.kind==="place"&&e.place.kind==="recent"?{by:"modified",desc:!0}:{by:"name",desc:!1}}function om(e,t){if(t.kind==="place"&&t.place.kind==="recent")return N1(t);try{let n=e?.getItem(A1)??"",[r,o]=n.split(":");if(n1.includes(r??"")&&(o==="asc"||o==="desc"))return{by:r,desc:o==="desc"}}catch{}return N1(t)}function R1(e,t){try{e?.setItem(A1,`${t.by}:${t.desc?"desc":"asc"}`)}catch{}}function $1(e,t){return e.by===t?{by:t,desc:!e.desc}:{by:t,desc:t==="modified"||t==="versions"||t==="size"}}var Pe=e=>e.slice(e.lastIndexOf("/")+1),Ut=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")):"";function pu(e,t,n){let r=o=>n===o||n.startsWith(`${o}/`);switch(e.kind){case"rename":case"move":{let o=t.find(s=>r(s.from));return o===void 0?null:`${o.to}${n.slice(o.from.length)}`}case"delete":{let o=e.items.find(r);return o===void 0?null:Ut(o)}default:return null}}function Sa(e){let t=e?e.split("/"):[];return t.map((n,r)=>t.slice(0,r+1).join("/"))}function I1(e){return e>=wI?"wide":e>=kI?"medium":"compact"}function P1(e,t,n){if(!e.length)return null;let r=t===null?-1:e.findIndex(o=>o.path===t);return r<0?e[n===1?0:e.length-1].path:e[Math.max(0,Math.min(e.length-1,r+n))].path}var O1="orbit.artifacts.expanded",L1=200;function M1(e,t,n){let r=[],o=(i,a,u)=>r.push({kind:"note",key:`note:${i}`,depth:a,text:u}),s=(i,a,u,c)=>{for(let d of i){if(c!==null&&!d.path.startsWith(`${c}/`))continue;let p=n.has(d.path);if(r.push({kind:"folder",folder:d,depth:u,open:p}),!p)continue;let f=t(d.path);f?f.state==="refused"?o(d.path,u+1,`Couldn't open it: ${f.reason}`):!f.folders.length&&!f.pages.length?o(d.path,u+1,"Empty"):(s(f.folders,f.pages,u+1,d.path),f.more&&o(d.path,u+1,`Showing the first ${f.pages.length} pages.`)):o(d.path,u+1,"Loading\u2026")}for(let d of a)r.push({kind:"page",page:d,depth:u})};return s(e.folders,e.pages,0,null),r}function D1(e){return e.flatMap(t=>t.kind==="folder"?[{kind:"folder",path:t.folder.path}]:t.kind==="page"?[{kind:"page",path:t.page.path,threadId:t.page.threadId,name:t.page.name}]:[])}function EI(e){let t=new Map;for(let n of e)for(let r of n)t.has(r.path)||t.set(r.path,r);return[...t.values()]}function F1(e,t,n){return t?(+(e.gen===n)-+(t.gen===n)||e.n-t.n)>0:!0}function z1(e,t,n){let r=[...t].sort((o,s)=>+(s.gen===n)-+(o.gen===n)||s.n-o.n);return EI([e,...r.map(o=>o.branch.state==="ok"?o.branch.pages:[])])}function K1(e,t,n){let r=t.kind==="delete",o=i=>{let a=pu(t,n,i);return a===null?i:r?null:a},s=new Map;for(let[i,a]of e){let u=o(i);if(u===null)continue;let c=p=>p.flatMap(f=>{let h=o(f.path);return h!==null&&Ut(h)===u?[{...f,path:h}]:[]}),d=a.branch;s.set(u,d.state==="ok"?{...a,branch:{...d,folders:c(d.folders),pages:c(d.pages)}}:a)}return s}function X1(e){try{let t=JSON.parse(e?.getItem(O1)??"[]");return Array.isArray(t)?new Set(t.filter(n=>typeof n=="string"&&n.length>0&&n.length<=240).slice(-L1)):new Set}catch{return new Set}}function B1(e,t){try{e?.setItem(O1,JSON.stringify([...t].slice(-L1)))}catch{}}function U1(e,t,n){return t.kind!=="move"&&t.kind!=="rename"?new Set(e):new Set([...e].map(r=>pu(t,n,r)??r))}function H1(e,t,n,r,o){let s=new Set(t),i=!t.has(r),a=o&&n!==null?e.findIndex(d=>d.path===n):-1,u=e.findIndex(d=>d.path===r),c=a>=0&&u>=0?e.slice(Math.min(a,u),Math.max(a,u)+1).map(d=>d.path):[r];for(let d of c)i?s.add(d):s.delete(d);return s}var sm=50,im="orbit.artifacts.undo";function V1(e){try{let t=JSON.parse(e?.getItem(im)??"[]");return Array.isArray(t)?t.filter(n=>!!n&&typeof n=="object"&&Number.isInteger(n.id)&&n.id>0&&typeof n.summary=="string").map(n=>({id:n.id,summary:n.summary.slice(0,300)})).slice(-sm):[]}catch{return[]}}var NI=24,AI=200,cs=new Map,Z1=new Map;function W1(e,t,n,r){for(e.delete(t),e.set(t,n);e.size>r;){let o=e.keys().next().value;if(o===void 0)break;e.delete(o)}}var j1={maskImage:"linear-gradient(to bottom, black 60%, transparent)",WebkitMaskImage:"linear-gradient(to bottom, black 60%, transparent)"},CI=[{id:eu,context:{kind:"nav-panel",panelId:At},availability:"action"},{id:tu,context:{kind:"thread"},availability:"action"}];function Q1({attributes:e,message:t}){let n=c1(e,t.threadId);return"problem"in n?l("p",{role:"alert",className:"my-2 rounded-md border border-border bg-muted px-3 py-2 text-sm text-muted-foreground",children:n.problem}):l(II,{page:n},`${n.threadId}/${n.name}`)}function TI(e){return e.state==="offline"?`${e.machine??"This conversation's machine"} is offline, so this page can't be shown until it's back.`:`This page can't be shown: ${e.reason}.`}function RI(){let[e,t]=v(null),[n,r]=v(()=>Wh(0,0));return Ye(()=>{if(e===null)return;let o=()=>r(Wh(e.getBoundingClientRect().width,window.innerHeight));o(),window.addEventListener("resize",o);let s=typeof ResizeObserver>"u"?null:new ResizeObserver(o);return s?.observe(e),()=>{window.removeEventListener("resize",o),s?.disconnect()}},[e]),[t,n]}function $I(){let e=Q_(),t=Ie();return q((n,r)=>{let o={threadId:n.threadId,name:n.name};f1(o);for(let s of CI)if(e.experimental_openTab({surface:{kind:"current"},tab:s,params:o,title:r??n.name}))return;t.toPluginPanel(du)},[t,e])}function II({page:e}){let t=J(),n=`${e.threadId}/${e.name}`,[r,o]=v(()=>{let E=cs.get(n);return E?{state:"ready",page:E}:{state:"loading"}});M(()=>{let E=!0;return t.call("artifacts.read",{threadId:e.threadId,name:e.name}).then(k=>{if(!E)return;if(k.state==="refused"&&cs.delete(n),k.state!=="ok"){cs.has(n)||o({state:"problem",reason:TI(k)});return}let N=Wr(k.page);if(N.kind==="refused"){cs.delete(n),o({state:"problem",reason:`This page can't be shown: ${N.reason}.`});return}let $={title:u1(k.page.kind,k.page.content),detail:ka(k.page.size,k.page.modifiedAt)},P=N.kind==="frame"?{...$,kind:"html",srcDoc:d1(N.srcDoc)}:{...$,kind:"md",blocks:N.blocks};W1(cs,n,P,NI),o({state:"ready",page:P})},k=>{E&&!cs.has(n)&&o({state:"problem",reason:`This page can't be shown: ${k instanceof Error?k.message:String(k)}.`})}),()=>{E=!1}},[t,n,e.threadId,e.name]);let s=r.state==="ready"?r.page:null,i=s?.title??null,a=J(),u=$I(),c=q(()=>u(e,i),[u,e,i]),[d,p]=v(!1),[f,h]=v(null),[g,x]=v(null),b=G(0),_=q(E=>{let k=Zr(E),N=++b.current;if(h(k.kind==="outside"?k.url:null),k.kind!=="page")return x(ru(k));x(null),a.call("artifacts.follow",{threadId:e.threadId,name:e.name,href:E}).then($=>{N===b.current&&($.state==="page"?u({threadId:$.threadId,name:$.name},null):x(au($)))},$=>N===b.current&&x(`The link wasn't followed: ${$ instanceof Error?$.message:String($)}.`))},[u,e,a]),w=i??e.name,[T,y]=RI();return m("section",{ref:T,"aria-label":`Page: ${w}`,"data-moonlet-artifact":"",className:"my-2 min-w-0 overflow-hidden rounded-lg border border-border bg-background",children:[m("header",{className:"flex items-center gap-2 py-1.5 pl-3 pr-1.5",children:[l(pe,{name:"FileText","aria-hidden":!0,className:"size-3.5 shrink-0 text-subtle-foreground"}),m("div",{className:"flex min-w-0 flex-1 items-baseline gap-2 text-xs",children:[l("span",{className:"max-w-full shrink-0 truncate font-medium text-foreground",children:w}),r.state==="problem"?null:l("span",{className:"truncate text-subtle-foreground",children:s?`${i?`${e.name} \xB7 `:""}${s.detail}`:"Opening\u2026"})]}),l("button",{type:"button",onClick:c,"aria-label":`Open ${w} beside the chat`,title:"Open beside the chat",className:"inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-state-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",children:l(pe,{name:"PanelRight","aria-hidden":!0,className:"size-3.5"})})]}),f?l(nm,{url:f,onClose:()=>h(null)}):g?m("div",{role:"status",className:"flex items-center gap-2 border-t border-border bg-muted px-3 py-2 text-xs",children:[l("span",{className:"min-w-0 flex-1",children:g}),l(R,{size:"sm",variant:"secondary",onClick:()=>x(null),children:"OK"})]}):null,l("div",{className:"border-t border-border",children:r.state==="problem"?l("p",{className:"px-3 py-2.5 text-sm text-muted-foreground",children:r.reason}):s?s.kind==="html"?l(PI,{srcDoc:s.srcDoc,heightKey:`${n}/${s.srcDoc.length}`,name:w,limit:y,onOpen:c,onLink:_,onClamped:p},s.srcDoc):l(OI,{blocks:s.blocks,limit:y,onOpen:c,onLink:_,onClamped:p}):m("div",{role:"status","aria-busy":"true","aria-label":`Opening ${e.name}`,className:"flex flex-col gap-2.5 px-4 py-4",children:[l("span",{className:"h-4 w-2/5 animate-pulse rounded bg-muted"}),l("span",{className:"h-3 w-full animate-pulse rounded bg-muted"}),l("span",{className:"h-3 w-3/5 animate-pulse rounded bg-muted"})]})}),s&&d?m("button",{type:"button",onClick:c,className:"flex w-full cursor-pointer items-center justify-center gap-1.5 border-t border-border py-1.5 text-xs text-muted-foreground transition-colors hover:bg-state-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring",children:["Read the whole page",l(pe,{name:"PanelRight","aria-hidden":!0,className:"size-3.5"})]}):null]})}function G1({onOpen:e}){return l("button",{type:"button","aria-hidden":!0,tabIndex:-1,className:"absolute inset-0 cursor-pointer",onClick:e})}function PI({srcDoc:e,heightKey:t,name:n,limit:r,onOpen:o,onLink:s,onClamped:i}){let a=G(null),u=uu(),[c,d]=v(()=>Z1.get(t)??null);M(()=>{let f=h=>{let g=!!a.current?.contentWindow&&h.source===a.current.contentWindow,x=p1(h.data,g);if(x!==null){W1(Z1,t,x,AI),d(x);return}let b=navigator.userActivation?.isActive??!0,_=nu(h.data,{ownFrame:g,activated:b});_!==null&&s(_)};return window.addEventListener("message",f),()=>window.removeEventListener("message",f)},[t,s]);let p=jh(c,r);return M(()=>i(p.clamped),[p.clamped,i]),m("div",{className:"relative",style:{height:p.height,...p.clamped?j1:{}},children:[l("iframe",{ref:a,...su({srcDoc:e}),title:n,tabIndex:p.clamped?-1:void 0,className:V("block size-full border-0 transition-opacity duration-150",c===null&&"opacity-0",p.clamped&&"pointer-events-none"),style:{colorScheme:u}}),p.clamped?l(G1,{onOpen:o}):null]})}function OI({blocks:e,limit:t,onOpen:n,onLink:r,onClamped:o}){let s=G(null),[i,a]=v(null);Ye(()=>{let c=s.current;if(c===null||(a(c.getBoundingClientRect().height),typeof ResizeObserver>"u"))return;let d=new ResizeObserver(()=>a(c.getBoundingClientRect().height));return d.observe(c),()=>d.disconnect()},[]);let u=jh(i,t);return M(()=>o(u.clamped),[u.clamped,o]),m("div",{className:"relative overflow-hidden",style:u.clamped?{maxHeight:u.height,...j1}:void 0,children:[l("div",{ref:s,className:"px-4 py-3 text-sm leading-relaxed",inert:u.clamped,children:l(tm,{blocks:e,follow:r})}),u.clamped?l(G1,{onOpen:n}):null]})}async function fu(e,t){let n=[t.orbit,t.background,...t.policyJobs??[]].filter(d=>!!d);if(!n.length)return{jobs:[],errors:[]};let o=(await e.threadSections.list()).find(d=>d.name==="Orbit"),s=[];if(o)for(let d=0;;d+=100){let p=await e.threads.list({sectionId:o.id,includeHidden:!0,limit:100,offset:d});if(s.push(...p.map(f=>f.id)),p.length<100)break}let i=await e.threads.experimental_listDescendants({threadIds:[...new Set([...n,...s])],includeHidden:!0,includeArchived:!1}),a=[...new Set([...n,...s,...i.threads.flatMap(d=>d.descendantIds)])],u=[],c=[];for(let d=0;d<a.length;d+=8)await Promise.all(a.slice(d,d+8).map(async p=>{try{let[f,h]=await Promise.all([e.threads.get({threadId:p}),e.threads.interactions.list({threadId:p})]);for(let g of h)g.status==="pending"&&u.push({title:f.title||"Untitled work",interaction:g})}catch{c.push(p)}}));return u.sort((d,p)=>d.interaction.createdAt-p.interaction.createdAt||d.interaction.id.localeCompare(p.interaction.id)),{jobs:u,errors:c}}function am(e,t){return e.length>0&&e.every(n=>{let r=t[n.id];return!r||!n.multiSelect&&r.selected.length+(r.freeText?.trim()?1:0)>1||r.selected.some(o=>!n.options?.some(s=>s.value===o))||r.freeText?.trim()&&!n.allowFreeText?!1:r.selected.length>0||n.allowFreeText&&!!r.freeText?.trim()})}function Y1(e){let t=e.subject;switch(t.kind){case"command":return{title:"Approve running this command?",detail:t.cwd?`${t.command}
138
138
  Working folder: ${t.cwd}`:t.command};case"file_change":return{title:"Approve changing files?",detail:t.writeScope??"Files shown in the work"};case"plan":return{title:"Approve this plan?",detail:t.plan};case"tool_use":return{title:t.presentation.title??`Approve using ${t.tool}?`,detail:t.presentation.detail??t.tool};case"permission_grant":return{title:"Approve this access?",detail:[...(t.permissions.fileSystem?.read??[]).map(n=>`Read files: ${n}`),...(t.permissions.fileSystem?.write??[]).map(n=>`Change files: ${n}`),...t.permissions.network?.enabled?["Use the network"]:[]].join(`
139
- `)||"No additional access requested"}}}function j1(){let{scope:e}=Y_();return l(pu,{onlyThread:e.kind==="thread"?e.threadId:""})}function pu({onlyThread:e}){let t=J(),n=un(),[r,o]=_(null),[s,i]=_(null),a=Y(()=>{});if(K(()=>{let d=!0,p=!1,f=!1,h,g=async()=>{if(p){f=!0;return}clearTimeout(h),p=!0;do{f=!1;try{let v=await t.call("work.parents",null);if(e!==void 0&&e!==v.orbit)d&&!f&&(o({orbit:v.orbit,jobs:[],warning:null}),i(null));else{let{jobs:w,errors:C}=await du(n,v);d&&!f&&(o(y=>({orbit:v.orbit,jobs:[...w,...y?.jobs.filter(T=>C.includes(T.interaction.threadId))??[]],warning:C.length?"Some work could not be checked. Trying again.":null})),i(null))}}catch{d&&!f&&i("Could not check waiting work. Trying again.")}}while(d&&f);p=!1,d&&(h=setTimeout(()=>{g()},5e3))};a.current=()=>{g()};let x=n.subscribe({event:"thread:changed",callback:v=>{v.changes.some(w=>["interactions-changed","thread-created","thread-deleted","parent-changed","archived-changed"].includes(w))&&g()}}),b=n.subscribe({event:"realtime:connection",callback:v=>{v.state==="connected"&&g()}});return g(),()=>{d=!1,a.current=()=>{},clearTimeout(h),x(),b()}},[t,n,e]),e!==void 0&&r&&r.orbit!==e)return null;let u=r?.jobs.filter(d=>d.interaction.threadId!==e)??[],c=s||r?.warning;return e!==void 0&&!u.length?c?l("p",{role:"alert",className:"text-sm",children:c}):null:m("section",{"aria-label":"Waiting for you",className:"max-h-[50vh] space-y-3 overflow-auto rounded-md border p-3 text-sm",children:[l("h2",{className:"font-medium",children:"Waiting for you"}),(s||r?.warning)&&l("p",{role:"alert",children:s||r?.warning}),!r&&!s&&l("p",{children:"Checking work\u2026"}),r&&!u.length&&!s&&!r.warning&&l("p",{children:"No questions or approvals waiting."}),u.map(d=>l($I,{job:d,sdk:n,done:()=>{o(p=>p&&{...p,jobs:p.jobs.filter(f=>f.interaction.id!==d.interaction.id)}),a.current()}},d.interaction.id))]})}function $I({job:e,sdk:t,done:n}){let{interaction:r}=e,o=Ie(),[s,i]=_(!1),a=Y(!1),[u,c]=_(null),[d,p]=_({}),f=r.payload,h=async v=>{if(a.current)return!1;a.current=!0,i(!0),c(null);try{let w=await t.threads.interactions.get({threadId:r.threadId,interactionId:r.id});return w.status!=="pending"||w.expiresAt!=null&&w.expiresAt<=Date.now()?(n(),!0):(await v(w),n(),!0)}catch{return c("The answer did not go through. Check the work and try again."),!1}finally{a.current=!1,i(!1)}},g={threadId:r.threadId,interactionId:r.id},x=v=>h(()=>t.threads.interactions.resolve({...g,resolution:v})),b;if(f.kind==="approval"){let v=W1(f);b=m("div",{className:"space-y-2",children:[l("p",{children:v.title}),f.reason&&l("p",{children:f.reason}),l("pre",{className:"max-h-60 overflow-auto whitespace-pre-wrap break-words",children:v.detail}),m("div",{className:"flex gap-2",children:[l(R,{disabled:s||!f.availableDecisions.includes("allow_once"),onClick:()=>{x({decision:"allow_once",grantedPermissions:f.subject.kind==="permission_grant"?f.subject.permissions:null})},children:"Approve"}),l(R,{variant:"destructive",disabled:s||!f.availableDecisions.includes("deny"),onClick:()=>{x({decision:"deny"})},children:"Decline"})]})]})}else if(f.kind==="user_question")b=m("form",{className:"space-y-3",onSubmit:v=>{v.preventDefault(),sm(f.questions,d)&&x({kind:"user_answer",answers:d})},children:[f.questions.map(v=>m("fieldset",{disabled:s,className:"space-y-2",children:[l("legend",{children:v.prompt}),v.options?.map(w=>m("label",{className:"block",children:[l("input",{type:v.multiSelect?"checkbox":"radio",name:`${r.id}-${v.id}`,checked:d[v.id]?.selected.includes(w.value)??!1,onChange:C=>p(y=>({...y,[v.id]:{...v.multiSelect?y[v.id]:{},selected:v.multiSelect?C.target.checked?[...y[v.id]?.selected??[],w.value]:(y[v.id]?.selected??[]).filter(T=>T!==w.value):[w.value]}}))})," ",w.label,w.description&&l("span",{className:"block text-xs text-muted-foreground",children:w.description})]},w.value)),v.allowFreeText&&m("label",{className:"block",children:["Your answer",l("textarea",{className:"block w-full rounded border bg-background p-2",value:d[v.id]?.freeText??"",onChange:w=>p(C=>({...C,[v.id]:{selected:v.multiSelect?C[v.id]?.selected??[]:[],freeText:w.target.value}}))})]})]},v.id)),m("div",{className:"flex gap-2",children:[l(R,{type:"submit",disabled:s||!sm(f.questions,d),children:"Send answer"}),l(R,{type:"button",variant:"destructive",disabled:s,onClick:()=>{h(()=>t.threads.stop({threadId:r.threadId}))},children:"Stop work"})]}),l("p",{className:"text-xs text-muted-foreground",children:"Stop work stops this work, including the question it is waiting on."})]});else if(f.kind==="plugin"&&r.origin?.kind==="plugin"&&r.origin.pluginId==="orbit"){let v={interaction:{id:r.id,threadId:r.threadId,title:f.title,payload:f.data,createdAt:r.createdAt,expiresAt:r.expiresAt??null},submit:async w=>{if(!await h(()=>t.threads.interactions.respond({...g,value:w})))throw new Error("Answer failed")},cancel:async()=>{if(!await h(()=>t.threads.interactions.cancel(g)))throw new Error("Answer failed")}};b=r.origin.rendererId==="approval"?l(tc,{...v}):r.origin.rendererId==="policy-proposal"?l(rc,{...v}):r.origin.rendererId==="owner-changes"?l(sc,{...v}):r.origin.rendererId==="station-manager"?l(nc,{...v}):l("p",{children:"Open the work to answer this request."})}else b=l("p",{children:"Open the work to answer this request."});return m("article",{className:"space-y-2 rounded border p-3","aria-busy":s,children:[l("h3",{className:"font-medium",children:e.title}),l("fieldset",{disabled:s,children:b}),l(R,{variant:"ghost",onClick:()=>o.toThread(r.threadId),children:"Open work"}),u&&l("p",{role:"alert",children:u})]})}function Q1(){return m("main",{className:"mx-auto max-w-3xl p-4",children:[l("h1",{className:"mb-4 text-lg font-medium",children:"Your moonlet"}),l(pu,{}),l(Ci,{})]})}var fu="tasks",hu=[{id:"today",label:"Today"},{id:"upcoming",label:"Upcoming"},{id:"waiting",label:"Waiting on others"},{id:"scheduled",label:"Scheduled and watched"},{id:"journal",label:"Journal"},{id:"done",label:"Done"}],II=e=>hu.some(t=>t.id===e);function am(e){let[t,n]=(e??"").split("/").filter(Boolean);return{view:II(t)?t:"today",task:n?decodeURIComponent(n):null}}function en(){let e=Ie();return q((t,n=null)=>e.toPluginPanel(fu,{subPath:n?`${t}/${encodeURIComponent(n)}`:t}),[e])}function nt(){return J()}function We(e,t){let[n,r]=_(null),[o,s]=_(""),[i,a]=_(0),u=Y(e);u.current=e;let c=q(()=>a(d=>d+1),[]);return K(()=>{let d=!0;return u.current().then(p=>{d&&(r(p),s(""))},p=>d&&s(p instanceof Error?p.message:String(p))),()=>{d=!1}},[i,...t]),K(()=>{let d=setInterval(c,6e4);return()=>clearInterval(d)},[c]),ke("tasks",c),{data:n,error:o,reload:c}}function ds(){let e=nt();return We(()=>e.call("tasks.meta",null),[e]).data}function Ea(){let e=nt(),[t,n]=_(""),[r,o]=_(!1);return{change:q(async i=>{o(!0);try{let a=await e.call("tasks.change",i);return n(""),a}catch(a){return n(a instanceof Error?a.message:String(a)),null}finally{o(!1)}},[e]),error:t,busy:r,clearError:()=>n("")}}var PI={todo:"M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z",followup:"M5 2h14M5 22h14M7 2v2.5C7 6.7 9 8.2 12 12c3-3.8 5-5.3 5-7.5V2M7 22v-2.5C7 17.3 9 15.8 12 12c3 3.8 5 5.3 5 7.5V22",once:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9M10.3 21a1.94 1.94 0 0 0 3.4 0",repeat:"m17 2 4 4-4 4M3 11v-1a4 4 0 0 1 4-4h14M7 22l-4-4 4-4M21 13v1a4 4 0 0 1-4 4H3",watch:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12zM15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0z"};function jr(e){return e.kind==="followup"?"followup":e.kind==="scheduled"?e.when?.form==="repeat"?"repeat":"once":"todo"}function Ht({glyph:e,className:t}){return l("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:V("size-4 shrink-0",t),children:l("path",{d:PI[e]})})}var mu={todo:"To-do",followup:"Follow-up",scheduled:"Scheduled"},cs={urgent:"Urgent",high:"High",medium:"Medium",low:"Low",none:"No priority"};function us({level:e,withLabel:t=!1}){let n={urgent:3,high:3,medium:2,low:1,none:0}[e];return m("span",{className:"inline-flex shrink-0 items-center gap-1.5 text-xs font-medium",title:`${cs[e]} priority`,children:[e==="urgent"?m("svg",{viewBox:"0 0 16 14",className:"h-3.5 w-4",role:"img","aria-label":"Urgent priority",children:[l("rect",{x:"1",y:"0",width:"14",height:"14",rx:"3.5",className:"fill-destructive"}),l("rect",{x:"7.1",y:"3",width:"1.8",height:"5.2",rx:".9",className:"fill-destructive-foreground"}),l("circle",{cx:"8",cy:"10.4",r:"1.05",className:"fill-destructive-foreground"})]}):l("svg",{viewBox:"0 0 16 14",className:"h-3.5 w-4",role:"img","aria-label":`${cs[e]} priority`,children:[[1.5,8,5],[6.5,4.5,8.5],[11.5,1,12]].map(([r,o,s],i)=>l("rect",{x:r,y:o,width:"3",height:s,rx:"1",className:i<n?"fill-foreground/70":"fill-foreground/15"},r))}),t?l("span",{children:cs[e]}):null]})}function De({origin:e,assistant:t,size:n=16}){return e==="assistant"?m("svg",{viewBox:"0 0 26 26",width:n,height:n,role:"img","aria-label":`Added by ${t}`,className:"shrink-0",children:[l("title",{children:`Added by ${t}`}),l("circle",{cx:"13",cy:"13",r:"13",style:{fill:"var(--moonlet-night, var(--color-foreground))"}}),l("circle",{cx:"13",cy:"13",r:"8",style:{fill:"var(--moonlet-moon-gold, var(--color-primary))"}}),l("circle",{cx:"10.3",cy:"10.8",r:"1.8",style:{fill:"var(--moonlet-moon-deep, var(--color-primary))"}}),l("circle",{cx:"15.3",cy:"15.6",r:"1.25",style:{fill:"var(--moonlet-moon-deep, var(--color-primary))"}})]}):m("svg",{viewBox:"0 0 26 26",width:n,height:n,role:"img","aria-label":"From you",className:"shrink-0",children:[l("title",{children:"From you"}),l("circle",{cx:"13",cy:"13",r:"12.25",className:"fill-muted stroke-border",strokeWidth:"1.5"}),l("circle",{cx:"13",cy:"10.4",r:"3.6",className:"fill-foreground/70"}),l("path",{d:"M6.6 20.2c1.3-3 3.6-4.5 6.4-4.5s5.1 1.5 6.4 4.5",className:"fill-foreground/70"})]})}function Sa({task:e,now:t,quiet:n=!1}){if(!e.whenText)return null;let r=e.dueAt!==null&&e.dueAt<t&&e.move!=="others",o=r||e.priority==="urgent"?"urgent":e.priority==="high"?"high":"plain";return l("span",{className:V("shrink-0 whitespace-nowrap rounded-md px-2 py-0.5 text-xs font-semibold",n&&o==="plain"?"px-0 font-medium text-muted-foreground":"",o==="urgent"&&"bg-surface-destructive text-destructive-text",o==="high"&&"bg-warning/15 text-warning-text",o==="plain"&&!n&&"bg-muted text-foreground"),children:r?`Late \xB7 ${e.whenText}`:Qr(e.whenText)})}var Qr=e=>e.charAt(0).toUpperCase()+e.slice(1);function Na({project:e}){return e.id==="personal"?null:l("span",{className:"inline-flex shrink-0 items-center rounded-md border border-border-hairline px-1.5 text-2xs font-semibold tracking-wide text-muted-foreground",title:e.name,children:e.key})}function lm({task:e,onToggle:t,busy:n}){let r=e.status==="done";return l("button",{type:"button","aria-label":r?`Reopen ${e.title}`:`Mark ${e.title} done`,"aria-pressed":r,disabled:n,onClick:o=>{o.stopPropagation(),t()},className:V("mt-0.5 grid size-5 shrink-0 cursor-pointer place-items-center rounded-full border-[1.5px] transition-colors",r?"border-foreground bg-foreground text-background":"border-foreground/35 hover:border-foreground/70 hover:bg-state-hover"),children:r?l("svg",{viewBox:"0 0 24 24",className:"size-3",fill:"none",stroke:"currentColor",strokeWidth:"3.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:l("path",{d:"M20 6 9 17l-5-5"})}):null})}function OI(e,t){return e.origin==="assistant"?`Added by ${t}${e.why?` \xB7 ${e.why}`:""}`:e.source?.kind==="import"?`From you \xB7 carried over from ${e.source.ref}`:"From you"}function q1({task:e,assistant:t,now:n,rich:r=!1,onOpen:o,onToggle:s,trailing:i,first:a}){let u=jr(e),c=e.move==="others"?`Waiting on ${e.waitingOn??"someone"}`:r?OI(e,t):e.say??e.why??e.description.split(`
140
- `)[0]??"";return m("div",{className:V("group flex items-start gap-3 px-4 transition-colors hover:bg-state-hover",r?"py-3.5":"py-2.5",!a&&"border-t border-border-hairline"),children:[l(lm,{task:e,onToggle:s}),m("button",{type:"button",onClick:o,className:"min-w-0 flex-1 cursor-pointer text-left",children:[m("span",{className:"flex min-w-0 items-center gap-2",children:[r?null:l(Ht,{glyph:u,className:"text-timeline-accent"}),l("span",{className:V("truncate",r?"text-base font-semibold":"text-sm font-medium"),children:e.title}),l(De,{origin:e.origin,assistant:t,size:15}),l(Na,{project:e.project}),e.watch?l(Ht,{glyph:"watch",className:"size-3.5 text-timeline-accent"}):null]}),r?m("span",{className:"mt-1 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground",children:[l(Ht,{glyph:u,className:"size-3.5 text-foreground/70"}),l("span",{className:"shrink-0 font-medium text-foreground/80",children:mu[e.kind]}),l("span",{"aria-hidden":!0,children:"\xB7"}),l("span",{className:"truncate",children:c})]}):c?l("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:c}):null,m("span",{className:"mt-1.5 flex items-center gap-2 sm:hidden",children:[l(Sa,{task:e,now:n,quiet:!r}),l(us,{level:e.priority})]}),r&&e.say?m("span",{className:"mt-2 flex max-w-2xl items-start gap-2 rounded-lg bg-surface-selected px-3 py-2 text-sm leading-snug",children:[l(De,{origin:"assistant",assistant:t,size:16}),l("span",{children:e.say})]}):null]}),m("span",{className:"hidden shrink-0 items-center gap-2.5 pt-0.5 sm:flex",children:[i,l(Sa,{task:e,now:n,quiet:!r}),l(us,{level:e.priority})]})]})}function Dn({title:e,count:t,hint:n,children:r,action:o}){return m("section",{className:"space-y-2.5",children:[m("div",{className:"flex items-center gap-2",children:[l("h2",{className:"text-sm font-semibold",children:e}),t!==void 0?l("span",{className:"rounded-full bg-muted px-2 text-xs font-semibold text-muted-foreground",children:t}):null,n?l("span",{className:"ml-auto text-xs text-muted-foreground",children:n}):null,o]}),l("div",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:r})]})}function Oe({children:e}){return l("p",{className:"px-4 py-6 text-center text-sm text-muted-foreground",children:e})}function _t({label:e,value:t,options:n,onChange:r}){return l("div",{role:"radiogroup","aria-label":e,className:"inline-flex gap-0.5 rounded-lg bg-muted p-0.5",children:n.map(o=>l("button",{type:"button",role:"radio","aria-checked":t===o.value,onClick:()=>r(o.value),className:V("inline-flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-xs font-semibold transition-colors",t===o.value?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:o.label},o.value))})}var J1="moonlet.tasks.filters";function LI(){try{let e=JSON.parse(globalThis.localStorage?.getItem(J1)??"null");if(e&&typeof e=="object"&&"origin"in e&&"project"in e)return{origin:e.origin==="owner"||e.origin==="assistant"?e.origin:"all",project:typeof e.project=="string"?e.project:""}}catch{}return{origin:"all",project:""}}var eS=null,im=new Set;function xn(e){eS=e;try{globalThis.localStorage?.setItem(J1,JSON.stringify(e))}catch{}for(let t of im)t()}function cm(){return[xt(t=>(im.add(t),()=>im.delete(t)),()=>eS??=LI()),xn]}var ps=e=>({...e.project?{project:e.project}:{},...e.origin!=="all"?{origin:e.origin}:{}});function Gr({filters:e,onChange:t,meta:n,children:r,origin:o=!0}){let s=n?.assistant??"Assistant";return m("div",{className:"flex flex-wrap items-center gap-3",children:[o?l(_t,{label:"Show tasks from",value:e.origin,onChange:i=>t({...e,origin:i}),options:[{value:"all",label:"All"},{value:"owner",label:m(he,{children:[l(De,{origin:"owner",assistant:s,size:14}),"From you"]})},{value:"assistant",label:m(he,{children:[l(De,{origin:"assistant",assistant:s,size:14}),`${s}\u2019s own`]})}]}):null,m("label",{className:"inline-flex items-center gap-2 text-xs text-muted-foreground",children:["Project",m("select",{value:e.project,onChange:i=>t({...e,project:i.target.value}),className:"h-8 cursor-pointer rounded-md border border-input bg-background px-2 text-xs font-medium text-foreground",children:[l("option",{value:"",children:"All projects"}),(n?.projects??[]).map(i=>m("option",{value:i.id,children:[i.name," (",i.key,")"]},i.id))]})]}),r]})}function fs(){let[e,t]=_(()=>Date.now());return K(()=>{let n=setInterval(()=>t(Date.now()),3e4);return()=>clearInterval(n)},[]),e}var G1=new Map;function Ge(e,t,n){let r=`${t}|${JSON.stringify(n)}`,o=G1.get(r);return o||(o=new Intl.DateTimeFormat(void 0,{timeZone:t,...n}),G1.set(r,o)),o.format(new Date(e))}var Ee=(e,t)=>Ge(e,t,{hour:"numeric",minute:"2-digit"}),Y1=new Map;function hs(e,t){let n=Y1.get(t);return n||(n=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}),Y1.set(t,n)),n.format(new Date(e))}function Ct(e,t="long"){let n=Date.parse(`${e}T12:00:00Z`);return Ge(n,"UTC",t==="long"?{weekday:"long",day:"numeric",month:"long"}:{weekday:"short",day:"numeric",month:"short"})}var ur=(e,t="short")=>Ge(Date.parse(`${e}T12:00:00Z`),"UTC",{weekday:t});function Yr(e,t){return new Date(Date.parse(`${e}T12:00:00Z`)+t*864e5).toISOString().slice(0,10)}function tS(){let e=J(),[t,n]=_(null),[r,o]=_(null),s=u=>o(u instanceof Error?u.message:String(u)),i=q(()=>{e.call("owner-changes.history",null).then(u=>n(u.declines),s)},[e]);K(i,[i]),ke("config",i),ke("owner-changes",i);let a=u=>{e.call("owner-changes.forget",{target:u}).then(()=>{o("Forgotten."),i()},s)};return m("section",{className:"space-y-2 text-sm","aria-label":"Declines your moonlet remembers",children:[l("h2",{className:"text-sm font-semibold",children:"Declines your moonlet remembers"}),l("p",{className:"text-xs text-muted-foreground",children:"For 30 days after you decline a change, your moonlet doesn't ask about the same thing again unless it has changed. Forget lets it ask now."}),r&&l("p",{role:"status",children:r}),t===null?null:t.length?l("ul",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised",children:t.map((u,c)=>m("li",{className:c?"flex items-center gap-3 border-t border-border-hairline px-4 py-2":"flex items-center gap-3 px-4 py-2",children:[m("span",{className:"min-w-0 flex-1",children:[u.target.replace(/^[^:]+:/,"")," \xB7 declined ",new Date(u.at).toLocaleDateString()]}),l(R,{size:"sm",variant:"ghost",onClick:()=>a(u.target),children:"Forget"})]},u.target))}):l("p",{className:"text-muted-foreground",children:"None."})]})}var Aa="activity",Jr=e=>e.charAt(0).toUpperCase()+e.slice(1),dm=["timeline","since","week","behalf"];var xs=[{id:"timeline",label:"Today",short:"Today"},{id:"since",label:"Since you looked",short:"Since you looked"},{id:"week",label:"This week",short:"This week"},{id:"behalf",label:"On your behalf",short:"On your behalf"},{id:"needs",label:"Needs you",short:"Needs you"},{id:"undo",label:"You can undo",short:"You can undo"},{id:"work",label:"Work",short:"Work"},{id:"asks",label:"Asks and approvals",short:"Asks"},{id:"messages",label:"Messages",short:"Messages"},{id:"checks",label:"Checks and routines",short:"Checks"}],pm={undo:["change","filing"],work:["work","note"],asks:["approval"],messages:["message","relay"],checks:["check"]},MI={changed:["change","filing","learned"],work:["work","note"]},DI=e=>xs.some(t=>t.id===e),FI=/^\d{4}-\d{2}-\d{2}$/,zI=e=>{let t=Date.parse(`${e}T12:00:00Z`);return Number.isFinite(t)&&new Date(t).toISOString().slice(0,10)===e};function fm(e){let[t,...n]=(e??"").split("/").filter(Boolean),r=n[0]!==void 0&&FI.test(n[0]),o=r&&zI(n[0])?n[0]:null,s=(r?n[1]:n[0])??null;return{view:DI(t)?t:"timeline",day:o,entry:s?decodeURIComponent(s):null,landing:t===void 0}}var oS=(e,t,n)=>[e,t,n===null?null:encodeURIComponent(n)].filter(r=>r!==null).join("/"),je=e=>`${e.kind}:${e.id}`,nS=new Map;function gu(e,t){let n=nS.get(t);return n||(n=new Intl.DateTimeFormat("en-US",{timeZone:t,hourCycle:"h23",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}),nS.set(t,n)),Object.fromEntries(n.formatToParts(new Date(e)).flatMap(r=>r.type==="literal"?[]:[[r.type,Number(r.value)]]))}function rS(e,t){let n=gu(e,t);return Date.UTC(n.year,n.month-1,n.day,n.hour%24,n.minute,n.second)-(e-(e%1e3+1e3)%1e3)}function qr(e,t){let n=Date.parse(`${e}T00:00:00Z`),r=n-rS(n,t);return n-rS(r,t)}function tn(e,t){return new Date(Date.parse(`${e}T12:00:00Z`)+t*864e5).toISOString().slice(0,10)}function xu(e,t){return{from:qr(e,t),to:qr(tn(e,1),t)}}var sS=(e,t)=>gu(e,t).hour%24,KI=[{from:21,label:"Late evening"},{from:17,label:"Evening"},{from:12,label:"Afternoon"},{from:9,label:"Late morning"},{from:6,label:"Early morning"},{from:0,label:"Overnight"}],XI=(e,t)=>KI.find(n=>sS(e,t)>=n.from).label,BI=new Set(["running","sharing","queued","needs_person"]),ms=e=>e.kind==="work"&&e.endedAt===null&&BI.has(e.state??""),UI=e=>e.kind==="check"&&e.title.startsWith("Check:");function gs(e){let t=e.state??"";return t==="running"?"running":t==="uncertain"?"unsure":t.startsWith("error")?"failed":t.startsWith("skipped")||t==="late-skipped"||t.startsWith("interrupted")?"skipped":UI(e)?t==="quiet"||t==="completed"?"quiet":"found":"done"}var um=e=>e.kind==="check"&&(gs(e)==="quiet"||gs(e)==="done"),HI=new Set(["completed","nothing","hit","quiet","ok","sent","sent for the owner"]);function bu(e){return e.kind!=="check"||e.detail===null||HI.has(e.detail)||e.detail===e.state?null:Jr(e.detail.replace(/^(?:error(?: \(exit \d+\))?|failed): /,""))}function iS(e,t,n,r){return e.filter(o=>(t==="everything"||o.kind==="visit"||MI[t].includes(o.kind))&&(!n||_m(o,n,r)))}function aS(e,t,n){let r=e.filter(ms),o=[];for(let s of e){if(ms(s))continue;let i=XI(s.at,t),a=o.at(-1);(!a||a.label!==i)&&(a={label:i,rows:[]},o.push(a)),s.kind==="visit"?a.rows.push({type:"visit",entry:s}):a.rows.push({type:"entry",entry:s})}if(!n)return{running:r,groups:o};for(let s of o){let i=s.rows.flatMap(c=>c.type==="entry"&&um(c.entry)?[c.entry]:[]);if(i.length<2)continue;let a=s.rows.findIndex(c=>c.type==="entry"&&um(c.entry)),u=s.rows.filter(c=>!(c.type==="entry"&&um(c.entry)));u.splice(a,0,{type:"quiet",entries:i}),s.rows=u}return{running:r,groups:o}}function yu(e,t){let n=[];for(let r of e){let o=gu(r.at,t),s=`${o.year}-${String(o.month).padStart(2,"0")}-${String(o.day).padStart(2,"0")}`,i=n.at(-1);i?.day===s?i.entries.push(r):n.push({day:s,entries:[r]})}return n}var hm=[{id:"you",label:"With you"},{id:"work",label:"Work"},{id:"checks",label:"Checks"},{id:"changes",label:"Changes, asks"}];function VI(e){return e.kind==="visit"||e.actor==="owner"?"you":e.kind==="check"?"checks":e.kind==="change"||e.kind==="filing"||e.kind==="approval"||e.kind==="learned"?"changes":"work"}function lS(e,t){return e.kind==="work"&&e.ran.length?e.ran.map(n=>({from:n.from,to:n.to??t})):e.kind==="work"||e.kind==="visit"?[{from:e.startedAt??e.at,to:e.endedAt??(ms(e)?t:null)}]:[{from:e.at,to:null}]}function _u(e,t,n){let r=t.to-t.from,o=s=>Math.min(1,Math.max(0,(s-t.from)/r));return e.flatMap(s=>lS(s,n).filter(i=>i.from<t.to&&(i.to??i.from)>=t.from).map((i,a)=>({lane:VI(s),start:o(i.from),end:i.to===null||i.to<=i.from?null:o(i.to),ref:je(s),key:`${je(s)}#${a}`})))}function mm(e,t,n){let[r,o]=e<t?[e,t]:[t,e],s=n.to-n.from,i=15*6e4,a=n.from+Math.floor(r*s/i)*i,u=n.from+Math.ceil(o*s/i)*i;return{from:a,to:Math.max(u,a+i)}}var ZI={queued:"Waiting its turn",running:"Working",sharing:"Working",needs_person:"Needs you",disposed:"Done",withdrawn:"Withdrawn",failed_before_run:"Didn\u2019t start"},WI={pending:"Waiting for your answer",applied:"Applied",undelivered:"Saved, not delivered yet",declined:"Declined",expired:"Expired",stale:"Asked again: its settings changed",withdrawn:"Withdrawn",reverted:"Undone"},jI={allow:"Allowed",deny:"Not allowed",pending:"Unanswered when Moonlet restarted"},QI={running:"Running",quiet:"Found nothing",found:"Found something",failed:"Failed",unsure:"Unsure how it went",skipped:"Skipped",done:"Done"},GI={delivered:"Delivered",read:"Delivered and read","not-woken":"Delivered, but the recipient couldn\u2019t be woken",held:"Held for you",discarded:"Discarded",refused:"Refused"},eo={work:"Work",check:"Check",change:"Change to your moonlet",filing:"Library",approval:"Approval",message:"Message",relay:"Relay",learned:"Learned",note:"Task note",visit:"Visit"};function nn(e){let t=e.state;if(t===null)return null;switch(e.kind){case"work":return e.failed&&t==="parked"?"Its last turn failed":ZI[t]??t.replaceAll("_"," ");case"check":return QI[gs(e)];case"change":return WI[t]??t;case"filing":return t==="undone"?"Undone":null;case"approval":return jI[t]??t;case"message":return GI[t]??t;case"relay":return Jr(t.replaceAll("_"," "));default:return null}}function cS(e){let t=Math.max(1,Math.round(e/6e4));if(t<60)return`${t} min`;let n=Math.floor(t/60);return t%60?`${n} h ${t%60} min`:`${n} h`}function to(e,t){if(e.kind!=="work"&&e.kind!=="visit"&&e.kind!=="check")return null;let n=e.startedAt??(e.kind==="work"?null:e.at);if(n===null)return null;let r=e.endedAt??(ms(e)?t:null);return r===null||r<n?null:cS(r-n)}var Tt=(e,t,n)=>`${e===1?"one":e} ${e===1?t:n}`;function no(e){let t=n=>e.filter(r=>r.kind===n);return{work:t("work").length,running:e.filter(ms).length,checks:t("check").length,found:t("check").filter(n=>gs(n)==="found").length,undoable:e.filter(n=>n.undo!==null).length,changes:t("change").length,filings:t("filing").length,asked:t("approval").length,allowed:t("approval").filter(n=>n.state?.startsWith("allow")).length,messages:t("message").length+t("relay").length,learned:t("learned").length}}function pr(e){return[e.work?`${Tt(e.work,"piece of work","pieces of work")}${e.running?`, ${e.running} still going`:""}`:null,e.checks?`${Tt(e.checks,"check or routine","checks and routines")}${e.found?`, ${e.found} found something`:""}`:null,e.changes||e.filings?`${Tt(e.changes+e.filings,"change","changes")}, ${e.undoable===0?"none":e.undoable} you can undo`:null,e.asked?`${Tt(e.asked,"approval","approvals")}, ${e.allowed===0?"none":e.allowed} allowed`:null,e.messages?Tt(e.messages,"message sent","messages sent"):null,e.learned?Tt(e.learned,"thing learned","things learned"):null].filter(t=>t!==null).map(Jr)}function ro(e,t,n){let r=e.changes+e.filings,o=[e.work?`I worked on ${Tt(e.work,"thing","things")}${e.running?`, and ${e.running} ${e.running===1?"is":"are"} still going`:""}.`:null,e.checks?`I ran ${Tt(e.checks,"check or routine","checks and routines")}${e.found?`, and ${Tt(e.found,"check","checks")} found something`:""}.`:null,r?`I made ${Tt(r,"change","changes")}${e.undoable===0?"":e.undoable===r?`; you can undo ${r===1?"it":"them all"}`:`; you can undo ${e.undoable}`}.`:null].filter(u=>u!==null),s={today:"So far today","so-far":"So far today",day:"That day",away:"While you were away,",week:"So far this week","past-week":"That week"}[n],i={today:"A quiet day so far.","so-far":"A quiet day so far.",day:"A quiet day.",away:"It was quiet while you were away.",week:"A quiet week so far.","past-week":"A quiet week."}[n],a=o.length?`${s} ${o.join(" ")}`:i;return n==="day"||n==="so-far"||n==="past-week"||t===null?a:`${a} ${t===0?"Nothing needs your answer.":Jr(`${Tt(t,"thing needs","things need")} your answer.`)}`}function Fn(e,t){let n=Math.floor(e/36e5);if(n<1)return cS(e);if(n<24)return t==="short"?`${n} h`:`${n} ${n===1?"hour":"hours"}`;if(t==="short"){let s=Math.round(n/12)/2;return s===1?"1 day":`${Math.floor(s)}${Number.isInteger(s)?"":"\xBD"} days`}let r=Math.floor(n/24),o=n%24;return`${r} ${r===1?"day":"days"}${o?`, ${o} ${o===1?"hour":"hours"}`:""}`}function bn(e,t){let n=gu(e,t);return`${n.year}-${String(n.month).padStart(2,"0")}-${String(n.day).padStart(2,"0")}`}var YI=new Intl.DateTimeFormat("en-US",{timeZone:"UTC",weekday:"long"}),qI=new Intl.DateTimeFormat("en-US",{timeZone:"UTC",weekday:"long",day:"numeric",month:"long"});function gm(e,t){let n=Date.parse(`${e}T12:00:00Z`),r=Math.round((Date.parse(`${t}T12:00:00Z`)-n)/864e5);return r===0?"Today":r===1?"Yesterday":r>1&&r<7?YI.format(n):qI.format(n)}var vu=(e,t,n,r)=>`${gm(bn(e,n),bn(t,n))} ${r(e)}`;function uS(e,t,n,r,o){let s=gm(e,bn(n,r));return e===bn(t,r)&&s!=="Today"?`${s} from ${o(t)}`:s}function wu(e,t,n,r,o){let s=gm(bn(t,r),bn(n,r)),i=s==="Today"?"":s==="Yesterday"?"yesterday ":`on ${s} `;return`${e} wrote this ${i}at ${o(t)}`}function xm(e){let t=new Date(`${e}T12:00:00Z`).getUTCDay();return tn(e,-((t+6)%7))}var bm=e=>Array.from({length:7},(t,n)=>tn(e,n));function JI(e,t,n){return Math.max(0,Math.min(t,n.to)-Math.max(e,n.from))}function ym(e,t,n){let r=0;for(let o of e)if(o.kind==="work")for(let s of o.ran)r+=JI(s.from,s.to??n,t);return r/36e5}var ku=e=>`${e<.05?0:e.toFixed(1)} h`;function dS(e,t,n){let r=new Map;for(let o of e){if(o.kind!=="work"&&o.kind!=="note"||o.task===null)continue;let s=o.task.project,i=r.get(s)??{work:[],notes:0,title:s};o.kind==="work"?i.work.push(o):i.notes++,r.set(s,i)}return[...r.entries()].map(([o,s])=>({key:o,title:s.title,hours:ym(s.work,t,n),done:s.work.filter(i=>i.state==="disposed").length,going:s.work.filter(ms).length,notes:s.notes})).sort((o,s)=>s.hours-o.hours||s.done-o.done||o.key.localeCompare(s.key))}function pS(e){let t=[e.done?Tt(e.done,"piece of work done","pieces of work done"):null,e.going?`${e.going} going`:null,e.notes?Tt(e.notes,"task note","task notes"):null].filter(n=>n!==null);return t.length?Jr(t.join(", ")):"Nothing finished yet"}function fS(e){return e.filter(t=>t.kind==="approval"&&t.startedAt!==null).map(t=>({entry:t,ms:Math.max(0,t.at-(t.startedAt??t.at))})).sort((t,n)=>n.ms-t.ms)}var eP=new Set(["failed_before_run","cut_off","withdrawn"]),tP=new Set(["refused","failed"]);function hS(e){return e.filter(t=>t.kind==="work"&&(eP.has(t.state??"")||t.failed)||t.kind==="check"&&(gs(t)==="failed"||gs(t)==="unsure")||(t.kind==="message"||t.kind==="relay")&&tP.has(t.state??""))}function _m(e,t,n){return lS(e,n).some(r=>r.to===null||r.to<=r.from?r.from>=t.from&&r.from<t.to:r.from<t.to&&r.to>t.from)}function mS(e,t,n){let r=e.to-e.from;return n.map(o=>{let s=e.from+o*36e5,i=[s,s-36e5,s+36e5].find(a=>a>=e.from&&a<e.to&&sS(a,t)===o)??s;return{hour:o,at:(i-e.from)/r}})}function bs(e,t){let n=r=>(r.kind==="work"||r.kind==="visit")&&(r.at<t.from||r.at>=t.to);return e.some(n)?e.map(r=>{if(!n(r))return r;if(r.kind==="visit")return{...r,at:Math.min(Math.max(r.at,t.from),t.to-1)};let o=r.ran.find(a=>a.from<t.to&&(a.to===null||a.to>t.from)),s=r.steps.find(a=>a.at>=t.from&&a.at<t.to),i=o?Math.max(t.from,o.from):s?s.at:Math.min(Math.max(r.at,t.from),t.to-1);return{...r,at:i}}).sort((r,o)=>o.at-r.at):e}var gS=[{id:"mail",label:"Mail sent"},{id:"signin",label:"Signed in for you"},{id:"commands",label:"Commands with your keys"},{id:"git",label:"Pushed and merged"},{id:"messages",label:"Messages"}],dr="secret-use-send",ys=e=>e===dr?"Mail":e;function xS(e,t){let n=t.filter(r=>wm(r)===e).map(r=>r.name);return e==="mail"&&!n.includes(dr)?[...n,dr]:n}var vm=(e,t)=>e===t&&e!==dr;function bS(e,t,n){let r=vm(e,t)?[e,dr]:[e],o=n.filter(s=>r.includes(s.capability));return o.length?{capability:e,uses:o.reduce((s,i)=>s+i.uses,0),changes:o.reduce((s,i)=>s+i.changes,0),asked:o.reduce((s,i)=>s+i.asked,0),refused:o.reduce((s,i)=>s+i.refused,0),last:Math.max(...o.map(s=>s.last))}:null}function wm(e){return e.kind==="mail"?"mail":e.kind==="login"?"signin":e.kind!=="cli"&&e.kind!=="ssh"?null:/mail/i.test(e.name)?"mail":/^git(hub)?\b/i.test(e.name)?"git":"commands"}var Su=[{level:"never-ask",label:"Never ask",about:"I use it without checking with you, sensitive commands included."},{level:"ask-changes",label:"Ask before changes",about:"Reading is free. A change waits for your yes, or one you already gave for it; sensitive ones ask every time."},{level:"always-ask",label:"Always ask",about:"Every use waits for your yes, or one you already gave for it; sensitive ones ask every time."},{level:"read-only",label:"Read only",about:"I can read with it but never change anything."}],km=e=>Su.find(t=>t.level===e)??null,nP={once:"You allowed it once",thread:"You allowed it for that conversation",always:"You allowed it from now on"};function yS(e){let t=e.startsWith("user: ")?nP[e.slice(6)]:void 0;return t||(e==="grant"?"Your earlier yes for this exact command":e==="thread"?"Your yes for that conversation":e==="standing decision"?"A standing permission":e.startsWith("existing owner decision")?"Your earlier decision":e==="level"||e==="read"||e==="owned-file"?"Its level allowed it":Jr(e))}function _S(e){let t=[e.uses?Tt(e.uses,"use","uses"):"no uses",e.changes?`${e.changes} changed something`:null,e.asked?`${e.asked} asked you first`:null,e.refused?`${e.refused} refused`:"none refused"].filter(n=>n!==null);return Jr(t.join(", "))}function yn(){let e=Ie();return q((t,n=null,r=null)=>e.toPluginPanel(Aa,{subPath:oS(t,r,n)}),[e])}function wS(e){ke("tasks",e),ke("approvals",e),ke("owner-changes",e),ke("config",e),ke("messages",e),ke("relay",e),ke("artifacts",e)}var kS=100;function ks(e,t,n){let r=J(),[o,s]=_(null),[i,a]=_(""),u=Y(()=>{}),c=q(()=>u.current(),[]),d=JSON.stringify([e.from,e.to,e.kinds,e.project,e.overlap===!0,e.behalf??null,t]);return K(()=>{let p=!0,f=!1,h=!1,g,x=async()=>{let v=[],w=null;for(let C=0;C<t;C++){let y=await r.call("activity.feed",{from:e.from,to:e.to,...e.kinds?{kinds:[...e.kinds]}:{},project:e.project,...e.overlap?{overlap:!0}:{},...e.behalf?{behalf:e.behalf}:{},before:w,limit:kS});if(!p)return null;if(v.push(...y.entries),w=y.next,!w)break}return{entries:v,more:w!==null}},b=async()=>{if(f){h=!0;return}f=!0,clearTimeout(g);do{h=!1;try{let v=await x();if(!p||!v)return;s({key:d,feed:v}),a("")}catch(v){if(!p)return;a(v instanceof Error?v.message:String(v))}}while(h);f=!1,g=setTimeout(()=>{b()},3e4)};return u.current=()=>{b()},b(),()=>{p=!1,clearTimeout(g),u.current=()=>{}}},[r,d,n]),wS(c),{data:o?.key===d?o.feed:null,error:i,reload:c}}function Em(){let e=J(),[t,n]=_(null),[r,o]=_(""),[s,i]=_(0);return K(()=>{let a=!0;return e.call("activity.since",null).then(u=>{a&&(n(u),o(""))},u=>a&&o(u instanceof Error?u.message:String(u))),()=>{a=!1}},[e,s]),K(()=>{let a=setInterval(()=>i(u=>u+1),6e4);return()=>clearInterval(a)},[]),{data:t,error:r}}var vS=10,Eu=60,zn=Eu*kS;function Ss(e,t){let[n,r]=_(vS),o=ks(e,n,t);K(()=>{o.data?.more&&n<Eu&&r(i=>Math.min(Eu,i+vS))},[o.data,n]);let s=o.data&&(!o.data.more||n>=Eu)?o.data:null;return{data:s,error:o.error,partial:s?.more===!0}}var rP=e=>Object.hasOwn(eo,e);function SS(e,t,n){let r=J(),[o,s]=_(0),i=q(()=>s(a=>a+1),[]);wS(i),K(()=>{if(e===null)return;let a=setInterval(i,3e4);return()=>clearInterval(a)},[e,i]),K(()=>{if(e===null)return;let a=e.indexOf(":"),u=e.slice(0,a);if(a<1||!rP(u))return;let c=!0;return r.call("activity.entry",{kind:u,id:e.slice(a+1)}).then(d=>{c&&d&&t([d])},()=>{}),()=>{c=!1}},[r,e,t,o,n])}function ES(e){let t=J(),n=J(),[r,o]=_(null),[s,i]=_(null);return{undo:q(async u=>{let c=u.undo;if(!c)return;let d=`${u.kind}:${u.id}`;i(d);try{let p=c.kind==="change"?{done:!0,text:(await t.call("owner-changes.undo",{id:c.id})).message}:await n.call("artifacts.undo",{id:c.id}).then(f=>f.state==="ok"?{done:!0,text:`Undone: ${f.summary}`}:{done:!1,text:`Not undone: ${f.reason}`});o({ref:d,...p})}catch(p){o({ref:d,done:!1,text:p instanceof Error?p.message:String(p)})}finally{i(null),e()}},[t,n,e]),said:r,busy:s}}var vs={jobs:[],held:0,checked:!1,error:null},Nu=new Set,ws=null,Sm,Au=!1,_s=!1,Ca=0;async function Cu(){if(Au){_s=!0;return}let e=Ca;clearTimeout(Sm),Au=!0;try{do{_s=!1;let t=ws;if(!t)break;try{let n=await t(vs);if(e!==Ca)return;_s||(vs={...n,checked:!0})}catch(n){if(e!==Ca)return;_s||(vs={...vs,error:n instanceof Error?n.message:String(n)})}for(let n of Nu)n()}while(_s&&ws)}finally{e===Ca&&(Au=!1,ws&&(Sm=setTimeout(()=>{Cu()},3e4)))}}function oP(e){return Nu.add(e),()=>{Nu.delete(e),!Nu.size&&(Ca++,ws=null,Au=!1,_s=!1,clearTimeout(Sm),vs={jobs:[],held:0,checked:!1,error:null})}}function Nm(){let e=un(),t=J(),n=J(),r=Y(async()=>({jobs:[],held:0,error:null}));r.current=async i=>{let[a,u]=await Promise.all([t.call("work.parents",null),n.call("messages.state",null)]),{jobs:c,errors:d}=await du(e,a),p=i.jobs.filter(f=>d.includes(f.interaction.threadId));return{jobs:[...c,...p].sort((f,h)=>f.interaction.createdAt-h.interaction.createdAt||f.interaction.id.localeCompare(h.interaction.id)),held:u.held.length,error:d.length?"Some work could not be checked. Trying again.":null}};let o=xt(oP,()=>vs);K(()=>{let i=ws===null;return ws=u=>r.current(u),i&&Cu(),e.subscribe({event:"thread:changed",callback:u=>{u.changes.some(c=>["interactions-changed","thread-created","thread-deleted","archived-changed"].includes(c))&&Cu()}})},[e]);let s=q(()=>{Cu()},[]);return ke("messages",s),ke("owner-changes",s),ke("approvals",s),o}var fr=e=>e.jobs.length+e.held,Es=e=>e.checked&&!e.error?fr(e):null;function Tu(e){let t=nt(),[n,r]=_(new Map),[o,s]=_(0),i=q(()=>s(u=>u+1),[]);ke("tasks",i),K(()=>{let u=setInterval(i,6e4);return()=>clearInterval(u)},[i]);let a=e.join(",");return K(()=>{let u=!0,c=a?a.split(","):[];return Promise.all(c.map(async d=>{let p=await t.call("tasks.journal",{day:d,limit:1});return[d,p.notes.find(f=>f.actor==="assistant")?.body??""]})).then(d=>u&&r(new Map(d.filter(([,p])=>p!==""))),()=>{}),()=>{u=!1}},[t,a,o]),n}var NS="text-sm max-md:pointer-coarse:text-base";var AS="h-[28px] w-[28px] rounded-md p-0 max-md:pointer-coarse:h-[36px] max-md:pointer-coarse:w-[36px]",HX=`${AS} [&_[data-icon-root]]:size-[16px] max-md:pointer-coarse:[&_[data-icon-root]]:size-[20px]`,VX=`${AS} [&_[data-icon-root]]:size-[13px] max-md:pointer-coarse:[&_[data-icon-root]]:size-[16px]`;var CS="h-9 max-md:pointer-coarse:h-10";var le=Tn(({className:e,type:t,...n},r)=>l("input",{type:t,autoComplete:"off",className:V(`flex w-full rounded-md border border-input bg-transparent pl-3 pr-3 py-1 ${Jl} file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`,CS,NS,e),ref:r,...n}));le.displayName="Input";var sP={work:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94z",check:"M21 21l-4.3-4.3M19 11a8 8 0 1 1-16 0 8 8 0 0 1 16 0z",change:"M21 4h-7M10 4H3M21 12h-9M8 12H3M21 20h-5M12 20H3M14 2v4M8 10v4M16 18v4",filing:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2z",approval:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1zM9 12l2 2 4-4",message:"M14.54 21.69a.5.5 0 0 0 .94-.03l6.5-19a.5.5 0 0 0-.64-.63l-19 6.5a.5.5 0 0 0-.03.93l7.93 3.18a2 2 0 0 1 1.11 1.11zM21.85 2.15 10.91 13.09",relay:"M15 17l5-5-5-5M4 18v-2a4 4 0 0 1 4-4h12",learned:"M12 3l1.9 5.8L20 10.7l-6.1 1.9L12 18.5l-1.9-5.9L4 10.7l6.1-1.9z",note:"M12 20h9M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4z",visit:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12zM15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0z"};function _n({kind:e,className:t}){return l("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:V("size-4 shrink-0",t),children:l("path",{d:sP[e]})})}var iP={you:"bg-foreground/55",work:"bg-timeline-accent",checks:"bg-foreground/30",changes:"bg-warning"};function aP(e,t){return[e.kind==="check"?e.title.split(":")[0]??eo.check:eo[e.kind],nn(e),to(e,t),e.task?`${e.task.key}`:null].filter(Boolean).join(" \xB7 ")}function Ta(e){return e.kind==="check"?e.title.slice(e.title.indexOf(":")+1).trim()||e.title:e.kind==="approval"?`Asked to use ${e.title}`:e.title}function lP({entry:e,meta:t}){return e.actor==="system"?l("span",{className:"mt-1 block size-3.5 shrink-0 rounded-full border border-border bg-muted",title:"Moonlet itself"}):l(De,{origin:e.actor==="owner"?"owner":"assistant",assistant:t.assistant,size:16})}function oo({entry:e,meta:t,now:n,onOpen:r,undo:o,first:s,showDay:i}){let a=Ie(),[u,c]=_(!1),d=je(e),p=bu(e),f=o.said?.ref===d?o.said:null;return m("li",{className:V("group grid grid-cols-[3.75rem_minmax(0,1fr)] gap-x-3 px-3 py-3 sm:grid-cols-[4.5rem_minmax(0,1fr)] sm:px-4",!s&&"border-t border-border-hairline"),children:[m("span",{className:"pt-0.5 text-right text-xs tabular-nums text-muted-foreground",children:[i?l("span",{className:"block",children:new Date(e.at).toLocaleDateString(void 0,{timeZone:t.zone,day:"numeric",month:"short"})}):null,Ee(e.at,t.zone)]}),m("div",{className:"min-w-0",children:[m("div",{className:"flex items-start gap-2.5",children:[l(_n,{kind:e.kind,className:V("mt-0.5",e.needsYou?"text-warning-text":"text-timeline-accent")}),m("button",{type:"button",onClick:()=>r(e),className:"min-w-0 flex-1 cursor-pointer text-left",children:[l("span",{className:V("block text-sm font-medium leading-snug",e.state==="undone"||e.state==="reverted"?"text-muted-foreground line-through":""),children:Ta(e)}),l("span",{className:"mt-0.5 block text-xs text-muted-foreground",children:aP(e,n)}),p?l("span",{className:"mt-1 block text-sm leading-snug",children:p}):null,e.kind==="approval"&&e.detail?l("code",{className:"mt-1.5 block truncate rounded-md bg-muted px-2 py-1 font-mono text-xs",children:e.detail.split(`
141
- `)[0]}):e.detail&&e.kind!=="check"&&e.kind!=="message"&&e.kind!=="relay"?l("span",{className:"mt-1 line-clamp-2 block text-sm leading-snug text-foreground/85",children:e.detail}):null]}),l(lP,{entry:e,meta:t})]}),e.kind==="work"&&e.steps.length>1?m("div",{className:"mt-1.5 pl-6",children:[m("button",{type:"button","aria-expanded":u,onClick:()=>c(h=>!h),className:"inline-flex cursor-pointer items-center gap-1 text-xs font-semibold text-timeline-accent hover:underline",children:[l(pe,{name:u?"ChevronUp":"ChevronDown","aria-hidden":!0,className:"size-3"}),u?"Hide the steps":`${e.steps.length} steps`]}),u?l("ol",{className:"mt-1.5 space-y-1 border-l border-border-hairline pl-3",children:e.steps.map((h,g)=>m("li",{className:"grid grid-cols-[3.5rem_minmax(0,1fr)] gap-2 text-xs",children:[l("span",{className:"tabular-nums text-muted-foreground",children:Ee(h.at,t.zone)}),l("span",{className:"min-w-0 break-words",children:h.text})]},`${h.at}-${g}`))}):null]}):null,e.undo||e.thread&&e.kind==="work"||f?m("div",{className:"mt-2 flex flex-wrap items-center gap-2 pl-6",children:[e.undo&&!f?.done?l(R,{size:"sm",variant:"outline",disabled:o.busy!==null,onClick:()=>o.undo(e),children:"Undo"}):null,e.thread&&e.kind==="work"?l(R,{size:"sm",variant:"ghost",onClick:()=>a.toThread(e.thread),children:"Open conversation"}):null,f?l("span",{role:"status",className:f.done?"text-xs text-muted-foreground":"text-xs text-destructive",children:f.text}):null]}):null]})]})}function cP({entry:e,meta:t,now:n}){let r=to(e,n);return m("li",{className:"flex items-center gap-3 px-4 py-1.5","aria-label":`You looked in at ${Ee(e.startedAt??e.at,t.zone)}`,children:[l("span",{className:"h-px flex-1 bg-border-hairline"}),m("span",{className:"inline-flex items-center gap-1.5 text-xs font-semibold text-muted-foreground",children:[l(_n,{kind:"visit",className:"size-3.5"}),"You looked in at ",Ee(e.startedAt??e.at,t.zone),r&&r!=="1 min"?` for ${r}`:""]}),l("span",{className:"h-px flex-1 bg-border-hairline"})]})}function uP({entries:e,render:t}){let[n,r]=_(!1),o=[...new Set(e.map(s=>s.title.slice(s.title.indexOf(":")+1).trim()))];return n?l(he,{children:e.map((s,i)=>t(s,i===0))}):m("li",{className:"flex items-center gap-3 border-t border-border-hairline px-4 py-2.5 first:border-t-0",children:[l(_n,{kind:"check",className:"text-muted-foreground"}),m("span",{className:"min-w-0 flex-1 text-sm text-muted-foreground",children:[e.length," ran quietly: ",o.slice(0,3).join(", "),o.length>3?"\u2026":""]}),m("button",{type:"button",onClick:()=>r(!0),className:"cursor-pointer text-xs font-semibold text-timeline-accent hover:underline",children:["Show ",e.length]})]})}function TS({groups:e,meta:t,now:n,onOpen:r,undo:o}){let s=(i,a)=>l(oo,{entry:i,meta:t,now:n,onOpen:r,undo:o,first:a},je(i));return l(he,{children:e.map((i,a)=>m("section",{"aria-label":i.label,className:"space-y-2",children:[l("h3",{className:"px-1 text-xs font-semibold text-muted-foreground",children:i.label}),l("ol",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:i.rows.map((u,c)=>u.type==="visit"?l(cP,{entry:u.entry,meta:t,now:n},je(u.entry)):u.type==="quiet"?l(uP,{entries:u.entries,render:s},`quiet-${je(u.entries[0])}`):s(u.entry,c===0||i.rows[c-1]?.type==="visit"))})]},`${i.label}-${a}`))})}function RS({entries:e,meta:t,now:n,onOpen:r}){let o=Ie();return e.length?m("section",{"aria-label":"Right now",className:"space-y-2",children:[l("h3",{className:"px-1 text-xs font-semibold text-muted-foreground",children:"Right now"}),l("ul",{className:"space-y-2",children:e.map(s=>m("li",{className:"flex flex-wrap items-center gap-3 rounded-xl border border-timeline-accent/40 bg-surface-selected px-4 py-3",children:[m("span",{className:"relative flex size-2.5 shrink-0",children:[l("span",{className:"absolute inline-flex size-full animate-ping rounded-full bg-timeline-accent opacity-60"}),l("span",{className:"relative inline-flex size-2.5 rounded-full bg-timeline-accent"})]}),m("button",{type:"button",onClick:()=>r(s),className:"min-w-0 flex-1 cursor-pointer text-left",children:[l("span",{className:"block text-sm font-semibold leading-snug",children:Ta(s)}),l("span",{className:"block text-xs text-muted-foreground",children:[nn(s),to(s,n)?`${to(s,n)} so far`:`since ${Ee(s.at,t.zone)}`,s.task?.key].filter(Boolean).join(" \xB7 ")})]}),s.thread?l(R,{size:"sm",variant:"outline",onClick:()=>o.toThread(s.thread),children:"Open conversation"}):null]},je(s)))})]}):null}var dP=[0,3,6,9,12,15,18,21],pP=e=>e===0?"12a":e<12?`${e}a`:e===12?"12p":`${e-12}p`;function $S({entries:e,span:t,now:n,zone:r,stretch:o,onStretch:s}){let i=Y(null),[a,u]=_(null),c=_u(e,t,n),d=g=>{let x=i.current.getBoundingClientRect();return Math.min(1,Math.max(0,(g.clientX-x.left)/x.width))},p=t.to-t.from,f=a?mm(a.a,a.b,t):o,h=n>=t.from&&n<t.to?(n-t.from)/p:null;return m("section",{"aria-label":"The day by hour",className:"space-y-2",children:[m("div",{className:"flex items-center gap-2 px-1",children:[l("h3",{className:"text-xs font-semibold text-muted-foreground",children:"The day"}),l("span",{className:"ml-auto text-xs text-muted-foreground",children:o?m("button",{type:"button",onClick:()=>s(null),className:"cursor-pointer font-semibold text-timeline-accent hover:underline",children:["Showing ",Ee(o.from,r),"\u2013",Ee(o.to,r)," \xB7 show the whole day"]}):l("span",{className:"hidden sm:inline",children:"Drag across it to narrow the list"})})]}),m("div",{className:"grid grid-cols-[minmax(0,1fr)] gap-x-2 rounded-xl border border-border-hairline bg-surface-raised px-3 py-2.5 sm:grid-cols-[6rem_minmax(0,1fr)]",children:[l("div",{className:"hidden flex-col gap-1 text-2xs font-medium text-muted-foreground sm:flex","aria-hidden":!0,children:hm.map(g=>l("span",{className:"flex h-3.5 items-center",children:g.label},g.id))}),m("div",{ref:i,role:"presentation",className:"relative cursor-crosshair touch-none select-none",onPointerDown:g=>{g.currentTarget.setPointerCapture(g.pointerId);let x=d(g);u({a:x,b:x})},onPointerMove:g=>a&&u({a:a.a,b:d(g)}),onPointerUp:()=>{a&&(s(Math.abs(a.b-a.a)<.01?null:mm(a.a,a.b,t)),u(null))},onPointerCancel:()=>u(null),children:[l("div",{className:"flex flex-col gap-1",children:hm.map(g=>l("div",{className:"relative my-0.75 h-2 rounded-full bg-muted",children:c.filter(x=>x.lane===g.id).map(x=>l("span",{className:V("absolute top-0 h-2 rounded-full",iP[g.id]),style:{left:`${x.start*100}%`,width:x.end===null?"0.5rem":`max(0.5rem, ${(x.end-x.start)*100}%)`}},x.key))},g.id))}),f?l("span",{className:"pointer-events-none absolute -inset-y-1 rounded-md bg-timeline-accent/15 ring-1 ring-timeline-accent/50",style:{left:`${(f.from-t.from)/p*100}%`,width:`${(f.to-f.from)/p*100}%`}}):null,h!==null?l("span",{className:"pointer-events-none absolute -inset-y-1 w-0.5 rounded-full bg-timeline-accent",style:{left:`${h*100}%`}}):null,l("div",{className:"relative mt-1.5 h-3 text-2xs text-muted-foreground","aria-hidden":!0,children:mS(t,r,dP).map(g=>l("span",{className:"absolute -translate-x-1/2 first:translate-x-0",style:{left:`${g.at*100}%`},children:pP(g.hour)},g.hour))})]})]})]})}function rn({eyebrow:e,title:t,children:n}){return m("div",{className:"flex flex-wrap items-end gap-3",children:[m("div",{className:"min-w-0 flex-1",children:[l("p",{className:"text-xs font-semibold text-muted-foreground",children:e}),l("h1",{className:"mt-0.5 text-2xl font-semibold tracking-tight",children:t})]}),n]})}function IS(e){let t=e.interaction.origin,n=t?.kind==="plugin"?t.rendererId:null;return n==="owner-changes"?"A change to your moonlet":n==="policy-proposal"?"A permission to decide":n==="approval"||e.interaction.payload.kind==="approval"?"An approval":"A question"}function Ns({needs:e,title:t="Needs you",hint:n="Stays here until you answer",now:r}){let o=yn(),s=fr(e);return!s&&!e.error?null:m("section",{"aria-label":t,className:"space-y-2",children:[m("div",{className:"flex items-center gap-2 px-1",children:[l("h2",{className:"text-sm font-semibold",children:t}),s?l("span",{className:"rounded-full bg-warning/15 px-2 text-xs font-semibold text-warning-text",children:s}):null,l("span",{className:"ml-auto text-xs text-muted-foreground",children:n})]}),m("ul",{className:"overflow-hidden rounded-xl border border-warning/40 bg-surface-raised shadow-sm",children:[e.jobs.slice(0,4).map((i,a)=>m("li",{className:V("flex items-center gap-3 px-4 py-3",a>0&&"border-t border-border-hairline"),children:[l(_n,{kind:"approval",className:"text-warning-text"}),m("span",{className:"min-w-0 flex-1",children:[l("span",{className:"block text-xs text-muted-foreground",children:r===void 0?IS(i):`Waiting ${Fn(r-i.interaction.createdAt,"long")} \xB7 ${IS(i).toLowerCase()}`}),l("span",{className:"block truncate text-sm font-medium",children:i.title})]}),l(R,{size:"sm",variant:"outline",onClick:()=>o("needs"),children:"Answer"})]},i.interaction.id)),e.jobs.length>4?m("li",{className:"border-t border-border-hairline px-4 py-2.5 text-sm text-muted-foreground",children:[e.jobs.length-4," more in Needs you"]}):null,e.held?m("li",{className:V("flex items-center gap-3 px-4 py-3",e.jobs.length>0&&"border-t border-border-hairline"),children:[l(_n,{kind:"message",className:"text-warning-text"}),m("span",{className:"min-w-0 flex-1",children:[l("span",{className:"block text-xs text-muted-foreground",children:"Held messages"}),m("span",{className:"block text-sm font-medium",children:[e.held===1?"A message":`${e.held} messages`," from outside your conversations, waiting for your yes"]})]}),l(R,{size:"sm",variant:"outline",onClick:()=>o("needs"),children:"Read"})]}):null,e.error?l("li",{role:"status",className:V("px-4 py-2.5 text-sm text-muted-foreground",s>0&&"border-t border-border-hairline"),children:e.error}):null]})]})}var Am=864e5,fP=366*Am,Ru="standing";function hP(){let e=J(),t=We(()=>e.call("approvals.state",null),[e]);return ke("approvals",t.reload),t}function mP(e,t,n){return e==="month"?n-30*Am:e==="year"?qr(`${t.today.slice(0,4)}-01-01`,t.zone):null}function gP({entry:e,meta:t,levels:n,open:r,first:o}){let s=Ie(),i=e.kind==="approval",a=e.steps[0]?.text??"",u=i?n.get(e.title):void 0;return m("li",{className:V("grid grid-cols-[minmax(0,1fr)_auto] items-start gap-x-3 gap-y-1 px-4 py-3 sm:grid-cols-[4rem_minmax(0,1fr)_auto]",!o&&"border-t border-border-hairline"),children:[m("span",{className:"col-span-2 text-xs tabular-nums text-muted-foreground sm:col-span-1 sm:pt-0.5 sm:text-right",children:[m("span",{className:"sm:block",children:[Ge(e.at,t.zone,{weekday:"short"})," ",Ge(e.at,t.zone,{day:"numeric"})]}),l("span",{className:"sm:hidden",children:" \xB7 "}),Ee(e.at,t.zone)]}),m("div",{className:"flex min-w-0 items-start gap-2.5",children:[l(_n,{kind:e.kind,className:"mt-0.5 text-timeline-accent"}),m("button",{type:"button",onClick:()=>r(e),className:"min-w-0 flex-1 cursor-pointer text-left",children:[l("span",{className:"block break-words text-sm font-medium leading-snug",children:i?(e.detail??e.title).split(`
142
- `)[0]:e.title}),m("span",{className:"mt-0.5 block text-xs text-muted-foreground",children:[i?`Used ${ys(e.title)}`:e.kind==="relay"?"Relayed to another machine":"Message to another conversation",!i&&nn(e)?` \xB7 ${nn(e)}`:""]}),i?m("span",{className:"mt-1 flex flex-wrap items-center gap-2 text-xs",children:[l("span",{className:"font-medium",children:yS(a)}),u?m("span",{className:"rounded-md border border-border-hairline px-1.5 py-0.5 text-muted-foreground",children:[ys(e.title)," now: ",km(u)?.label.toLowerCase()??u]}):null]}):null]})]}),e.thread?m(R,{size:"sm",variant:"ghost","aria-label":"Conversation",onClick:()=>s.toThread(e.thread),children:[l(pe,{name:"MessageSquare","aria-hidden":!0,className:"size-4 sm:hidden"}),l("span",{className:"hidden sm:inline",children:"Conversation"})]}):l("span",{})]})}function xP({meta:e,now:t,state:n}){let r=J(),o=J(),[s]=_(()=>Date.now()-30*Am),i=We(()=>o.call("activity.permissionUse",{from:s}),[o,s]);ke("approvals",i.reload);let[a,u]=_(null);if(!n.data||!i.data)return l("p",{className:"text-sm text-muted-foreground",children:n.error||i.error||"Loading\u2026"});let{mailSend:c}=n.data,d=n.data.capabilities.filter(y=>wm(y)!==null),p=i.data,f=y=>bS(y,c,p),h=y=>{let T=f(y);return T!==null&&(T.uses>0||T.refused>0)},g=d.filter(y=>h(y.name)),x=d.filter(y=>!h(y.name)),b=n.data.standing.filter(y=>!y.revoked&&!y.expired),v=(y,T,N)=>{let S=Su.find($=>$.level===N);S&&r.call("approvals.setCapability",{name:y,settings:{...T,level:S.level}}).then(()=>{u({key:y,text:`Now ${S.label.toLowerCase()}.`}),n.reload()},$=>u({key:y,text:$ instanceof Error?$.message:String($)}))},w=y=>{r.call("approvals.requestStandingRevoke",{id:y.id}).then(T=>{u({key:Ru,text:T.decision==="allow"?`Revoked: ${y.description}.`:T.decision==="pending"?`Asked to revoke ${y.description}; it ends once you confirm.`:T.reason??`${y.description} wasn\u2019t revoked.`}),n.reload()},T=>u({key:Ru,text:T instanceof Error?T.message:String(T)}))},C=y=>l("select",{"aria-label":`${ys(y.name)}: when to ask`,value:y.settings.level,onChange:T=>v(y.name,y.settings,T.target.value),className:"h-7 cursor-pointer rounded-md border border-input bg-background px-1.5 text-xs font-medium",children:Su.map(T=>l("option",{value:T.level,title:T.about,children:T.label},T.level))});return m("div",{className:"space-y-3",children:[g.map(y=>{let T=f(y.name);return m("div",{className:"space-y-1 rounded-xl border border-border-hairline bg-surface-raised px-3 py-2.5",children:[m("div",{className:"flex items-center gap-2",children:[l("span",{className:"min-w-0 flex-1 truncate text-sm font-semibold",children:ys(y.name)}),C(y)]}),l("p",{className:"text-xs text-muted-foreground",children:km(y.settings.level)?.about}),vm(y.name,c)?l("p",{className:"text-xs text-muted-foreground",children:"Its level also decides the mail I send."}):null,l("p",{className:"text-sm",children:_S(T)}),m("p",{className:"text-xs text-muted-foreground",children:["Last: ",vu(T.last,t,e.zone,N=>Ee(N,e.zone))]}),a?.key===y.name?l("p",{role:"status",className:"text-xs text-muted-foreground",children:a.text}):null]},y.name)}),b.length||a?.key===Ru?m("div",{className:"space-y-2",children:[l("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Standing permissions"}),b.map(y=>m("div",{className:"space-y-1 rounded-xl border border-border-hairline bg-surface-raised px-3 py-2.5",children:[l("p",{className:"text-sm",children:y.description}),m("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[m("span",{className:"min-w-0 flex-1",children:["On ",y.station,y.expiresAt!==null?`, until ${Ge(y.expiresAt,e.zone,{day:"numeric",month:"short"})}`:""]}),l(R,{size:"sm",variant:"outline",onClick:()=>w(y),children:"Revoke"})]})]},y.id)),a?.key===Ru?l("p",{role:"status",className:"text-xs text-muted-foreground",children:a.text}):null]}):null,x.length?m("div",{className:"space-y-1.5",children:[l("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Not used in 30 days"}),x.map(y=>m("div",{className:"flex items-center gap-2 text-sm",children:[l("span",{className:"min-w-0 flex-1 truncate",children:ys(y.name)}),C(y)]},y.name)),l("p",{className:"text-xs leading-snug text-muted-foreground",children:"You might not need these any more; Read only is the tightest."})]}):null,l("p",{className:"text-xs leading-snug text-muted-foreground",children:"Sensitive commands and how long questions wait are in Settings \u2192 Permissions."})]})}function PS({meta:e,now:t,open:n,signal:r,remember:o}){let s=J(),i=hP(),[a,u]=_(""),[c,d]=_(""),[p,f]=_("all"),[h,g]=_("anyone"),[x,b]=_(()=>({when:"all",chosen:Date.now()})),v=x.when,[w,C]=_(1),[y]=_(()=>Date.now()+fP);K(()=>{let j=setTimeout(()=>d(a.trim()),250);return()=>clearTimeout(j)},[a]),K(()=>C(1),[c,p,h,v]);let T=mP(v,e,x.chosen),N=i.data?.capabilities??[],S=j=>xS(j,N),$=We(()=>s.call("activity.behalfCounts",{from:T}),[s,T]),{data:P,error:L}=ks({from:T??0,to:y,kinds:p==="all"?null:p==="messages"?["message","relay"]:["approval"],project:null,behalf:{capabilities:p==="all"||p==="messages"?null:S(p),search:c||null,who:h}},w,r);K(()=>{P&&o(P.entries)},[P,o]);let ne=new Map(N.map(j=>[j.name,j.settings.level])),se=i.data?ne.get(i.data.mailSend):void 0;se&&!ne.has(dr)&&ne.set(dr,se);let _e=j=>j==="messages"?$.data?.messages??0:($.data?.capabilities??[]).filter(G=>S(j).includes(G.capability)).reduce((G,ee)=>G+ee.count,0),ie=[];for(let j of P?.entries??[]){let G=Ge(j.at,e.zone,{month:"long",year:"numeric"}),ee=ie.at(-1);ee?.month===G?ee.entries.push(j):ie.push({month:G,entries:[j]})}let Q=$.data?.since??null;return m("div",{className:"flex flex-wrap items-start gap-8",children:[m("div",{className:"min-w-0 flex-[999_1_34rem] space-y-5",children:[l(rn,{eyebrow:"Activity",title:"On your behalf"}),l("p",{className:"text-sm text-muted-foreground",children:"Everything I did that left your machines or used your accounts, and who said yes to it. Search it by person, place or command."}),m("label",{className:"flex items-center gap-2",children:[l(pe,{name:"Search","aria-hidden":!0,className:"size-4 text-muted-foreground"}),l("span",{className:"sr-only",children:"Search the record"}),l(le,{value:a,onChange:j=>u(j.target.value),placeholder:"Search the record","aria-label":"Search the record"}),P?m("span",{className:"shrink-0 text-xs text-muted-foreground",children:[P.entries.length,P.more?"+":""," ",P.entries.length===1?"result":"results"]}):null]}),l("div",{className:"flex flex-wrap gap-1.5",role:"group","aria-label":"What",children:[{id:"all",label:"All kinds"},...gS].map(j=>m("button",{type:"button","aria-pressed":p===j.id,onClick:()=>f(j.id),className:V("cursor-pointer rounded-full px-3 py-1 text-xs font-semibold",p===j.id?"bg-foreground text-background":"bg-muted text-muted-foreground hover:text-foreground"),children:[j.label,j.id!=="all"&&$.data?` \xB7 ${_e(j.id)||"none"}`:""]},j.id))}),m("div",{className:"flex flex-wrap items-center gap-3",children:[l(_t,{label:"Who said yes",value:h,onChange:g,options:[{value:"anyone",label:"Anyone"},{value:"owner",label:"You"},{value:"standing",label:"A standing permission"},{value:"level",label:"Its level"}]}),l(_t,{label:"When",value:v,onChange:j=>b({when:j,chosen:Date.now()}),options:[{value:"all",label:"All time"},{value:"month",label:"Last 30 days"},{value:"year",label:"This year"}]})]}),!P||p!=="all"&&p!=="messages"&&!i.data?l(Oe,{children:L||i.error||"Loading\u2026"}):P.entries.length===0?l(Oe,{children:c?`Nothing on record for \u201C${c}\u201D.`:"Nothing on record for these choices."}):m("div",{className:"space-y-5",children:[ie.map(({month:j,entries:G})=>m("section",{"aria-label":j,className:"space-y-2",children:[l("h2",{className:"px-1 text-xs font-semibold text-muted-foreground",children:j}),l("ol",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:G.map((ee,be)=>l(gP,{entry:ee,meta:e,levels:ne,open:n,first:be===0},je(ee)))})]},j)),P.more?m(R,{variant:"ghost",onClick:()=>C(j=>j+1),children:[l(pe,{name:"ChevronDown","aria-hidden":!0,className:"size-4"}),"Show older"]}):m("p",{className:"px-1 text-sm text-muted-foreground",children:[c?`That\u2019s everything for \u201C${c}\u201D. `:"",Q!==null?`The record starts on ${Ge(Q,e.zone,{day:"numeric",month:"long",year:"numeric"})}${bn(Q,e.zone)===e.today?", today":""}, and nothing is ever trimmed from it.`:""]})]})]}),m("aside",{className:"w-full shrink-0 space-y-3 xl:w-80","aria-label":"Your permissions, last 30 days",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:"Your permissions, last 30 days"}),l(xP,{meta:e,now:t,state:i})]})]})}var bP=14,yP=366*864e5;function OS({since:e,meta:t,now:n,open:r,undo:o,needs:s,signal:i,remember:a}){let u=yn(),c=e.from,[d]=_(()=>Date.now()+yP),[p,f]=_(bP),{data:h,error:g,partial:x}=Ss({from:c??0,to:d,kinds:null,project:null,overlap:!0},i);K(()=>{h&&a(h.entries)},[h,a]);let b=bs(h?.entries??[],{from:c??0,to:d}),v=yu(b.filter(S=>S.kind!=="visit"),t.zone),w=v.slice(0,p),C=Tu(w.map(S=>S.day)),y=S=>Ee(S,t.zone);if(c===null)return m("div",{className:"mx-auto max-w-3xl space-y-6",children:[l(rn,{eyebrow:"Activity",title:"Since you looked"}),l(Oe,{children:"There\u2019s no earlier visit to catch up from yet. Today\u2019s timeline has everything so far."}),l(R,{variant:"outline",onClick:()=>u("timeline"),children:"Open today"})]});let T=b.filter(S=>(S.kind==="change"||S.kind==="filing")&&S.state!=="undone"&&S.state!=="reverted"),N=no(b);return m("div",{className:"flex flex-wrap items-start gap-8",children:[m("div",{className:"min-w-0 flex-[999_1_34rem] space-y-6",children:[l(rn,{eyebrow:`Since you last looked \xB7 ${Fn(n-c,"long")}`,title:`${vu(c,n,t.zone,y)} to now`,children:l(_t,{label:"Show",value:"since",onChange:S=>S==="today"&&u("timeline"),options:[{value:"since",label:"Since you looked"},{value:"today",label:"Just today"}]})}),e.note?m("div",{className:"flex items-start gap-3.5 rounded-2xl bg-surface-selected px-4 py-3.5",children:[l(De,{origin:"assistant",assistant:t.assistant,size:28}),m("div",{className:"min-w-0",children:[l("p",{className:"whitespace-pre-wrap text-base leading-relaxed",children:e.note.body}),l("p",{className:"mt-1.5 text-xs text-muted-foreground",children:wu(t.assistant,e.note.at,n,t.zone,y)})]})]}):h?m("div",{className:"flex items-start gap-3.5 rounded-2xl bg-surface-selected px-4 py-3.5",children:[l(De,{origin:"assistant",assistant:t.assistant,size:28}),l("p",{className:"text-base leading-relaxed",children:ro(N,Es(s),"away")})]}):null,l(Ns,{needs:s,title:"Still waiting for you",hint:"Oldest first",now:n}),T.length?m("section",{"aria-label":"Changed while you were away",className:"space-y-2",children:[m("div",{className:"flex items-center gap-2 px-1",children:[l("h2",{className:"text-sm font-semibold",children:"Changed while you were away"}),l("span",{className:"ml-auto text-xs text-muted-foreground",children:"Undo is here while it can be"})]}),l("ol",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:T.map((S,$)=>l(oo,{entry:S,meta:t,now:n,onOpen:r,undo:o,first:$===0,showDay:!0},je(S)))})]}):null,m("section",{"aria-label":"Day by day",className:"space-y-2",children:[m("div",{className:"flex items-center gap-2 px-1",children:[l("h2",{className:"text-sm font-semibold",children:"Day by day"}),l("span",{className:"ml-auto text-xs text-muted-foreground",children:"Newest first \xB7 open a day to read all of it"})]}),h?w.length===0?l(Oe,{children:"Nothing happened while you were away."}):l("ol",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:w.map(({day:S,entries:$},P)=>l("li",{className:P?"border-t border-border-hairline":void 0,children:m("div",{className:"flex items-start gap-3 px-4 py-3",children:[m("div",{className:"min-w-0 flex-1",children:[m("p",{className:"text-sm font-semibold",children:[uS(S,c,n,t.zone,y),m("span",{className:"ml-2 text-xs font-medium text-muted-foreground",children:[$.length," ",$.length===1?"entry":"entries",x&&P===v.length-1?" or more":""]})]}),l("p",{className:"mt-0.5 text-sm leading-snug text-foreground/85",children:C.get(S)??ro(no($),0,S===bn(n,t.zone)?"so-far":"day")})]}),l(R,{size:"sm",variant:"outline",onClick:()=>u("timeline",null,S),children:"Open"})]})},S))}):l(Oe,{children:g||"Loading\u2026"}),h&&v.length>p?m(R,{variant:"ghost",onClick:()=>f(S=>S+7),children:[l(pe,{name:"ChevronDown","aria-hidden":!0,className:"size-4"}),"Show earlier days"]}):null,x?m("p",{className:"px-1 text-sm text-muted-foreground",children:["More than ",zn.toLocaleString()," entries since you looked, so the summary and these counts cover the newest ",zn.toLocaleString(),"."]}):null]})]}),m("aside",{className:"hidden w-72 shrink-0 space-y-2 xl:block","aria-label":"Done while you were away",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:"Done while you were away"}),h?pr(N).length?l("ul",{className:"space-y-1.5 text-sm",children:pr(N).map(S=>l("li",{children:S},S))}):l("p",{className:"text-sm text-muted-foreground",children:"Nothing yet."}):null]})]})}var LS={you:"bg-foreground/55",work:"bg-timeline-accent",checks:"bg-foreground/25",changes:"bg-warning"},_P=[{lane:"work",label:"Work"},{lane:"checks",label:"Checks and routines"},{lane:"you",label:"You"},{lane:"changes",label:"Changes and asks"}],MS=4;function vP(e){let t=J(),n=We(async()=>({week:e,...await t.call("activity.week",{week:e})}),[t,e]);return{data:n.data?.week===e?n.data:null,error:n.error,reload:n.reload}}function wP({entries:e,monday:t,today:n,meta:r,now:o}){let s=yn();return m("section",{"aria-label":"The week by hour",className:"space-y-2",children:[m("div",{className:"flex items-center gap-2 px-1",children:[l("h2",{className:"text-sm font-semibold",children:"The week by hour"}),l("span",{className:"ml-auto text-xs text-muted-foreground",children:"Pick a day to open it"})]}),m("div",{className:"space-y-1 rounded-xl border border-border-hairline bg-surface-raised px-3 py-3",children:[bm(t).map(i=>{let a=xu(i,r.zone),u=i>n,c=e.filter(f=>_m(f,a,o)),d=_u(c,a,o),p=ym(e,a,o);return m("button",{type:"button",disabled:u,onClick:()=>s("timeline",null,i),"aria-label":`${Ct(i)}: ${u?"ahead":`${ku(p)} of work`}`,className:V("grid w-full cursor-pointer grid-cols-[3rem_minmax(0,1fr)_4.5rem] items-center gap-3 rounded-md px-1 py-1.5 text-left hover:bg-state-hover disabled:cursor-default disabled:hover:bg-transparent",i===n&&"bg-surface-selected"),children:[l("span",{className:V("text-xs font-semibold",u&&"text-muted-foreground"),children:ur(i)}),l("span",{className:V("relative h-3 rounded-full bg-muted",u&&"opacity-50"),children:d.map(f=>l("span",{className:V("absolute top-0.5 h-2 rounded-full",LS[f.lane]),style:{left:`${f.start*100}%`,width:f.end===null?"0.375rem":`max(0.375rem, ${(f.end-f.start)*100}%)`}},f.key))}),l("span",{className:"text-right text-xs tabular-nums text-muted-foreground",children:u?"ahead":`${ku(p)}${i===n?" so far":""}`})]},i)}),l("div",{className:"flex flex-wrap gap-x-4 gap-y-1 px-1 pt-2 text-2xs text-muted-foreground","aria-hidden":!0,children:_P.map(i=>m("span",{className:"inline-flex items-center gap-1.5",children:[l("span",{className:V("size-2 rounded-full",LS[i.lane])}),i.label]},i.lane))})]})]})}function kP({entries:e,needs:t,meta:n,now:r,open:o}){let[s,i]=_(!1),a=fS(e),u=s?a:a.slice(0,MS),c=a.slice(MS);return!a.length&&!fr(t)?null:m("section",{"aria-label":"What's waited on you",className:"space-y-2",children:[m("div",{className:"flex items-center gap-2 px-1",children:[l("h2",{className:"text-sm font-semibold",children:"What\u2019s waited on you"}),l("span",{className:"ml-auto hidden text-xs text-muted-foreground sm:inline",children:"Open ones first, then the longest answered"})]}),l(Ns,{needs:t,title:"Waiting now",hint:"Oldest first",now:r}),u.length?l("ol",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:u.map(({entry:d,ms:p},f)=>l("li",{className:f?"border-t border-border-hairline":void 0,children:m("button",{type:"button",onClick:()=>o(d),className:"flex w-full cursor-pointer items-center gap-3 px-4 py-2.5 text-left hover:bg-state-hover",children:[m("span",{className:"min-w-0 flex-1",children:[m("span",{className:"block truncate text-sm font-medium",children:["Asked to use ",d.title]}),m("span",{className:"block text-xs text-muted-foreground",children:["Approval \xB7 asked ",Ge(d.startedAt??d.at,n.zone,{weekday:"short"})," ",Ee(d.startedAt??d.at,n.zone)]})]}),m("span",{className:"shrink-0 text-right text-xs",children:[l("span",{className:"block font-semibold tabular-nums",children:Fn(p,"long")}),l("span",{className:"block text-muted-foreground",children:nn(d)})]})]})},je(d)))}):null,c.length&&!s?m("button",{type:"button",onClick:()=>i(!0),className:"cursor-pointer px-1 text-xs font-semibold text-timeline-accent hover:underline",children:["And ",c.length," more this week, all answered within ",Fn(c[0].ms,"long"),". Show them"]}):null]})}function SP({entries:e,span:t,meta:n,now:r}){let o=en(),s=dS(e,t,r);return s.length?m("section",{"aria-label":"Where the work has gone",className:"space-y-2",children:[l("h2",{className:"px-1 text-sm font-semibold",children:"Where the work has gone"}),l("ol",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:s.map((i,a)=>{let u=n.projects.find(c=>c.key===i.key);return m("li",{className:V("flex items-center gap-3 px-4 py-2.5",a>0&&"border-t border-border-hairline"),children:[m("div",{className:"min-w-0 flex-1",children:[m("p",{className:"flex flex-wrap items-baseline gap-x-2 text-sm",children:[l("span",{className:"font-medium",children:u?.name??i.key}),l("span",{className:"text-2xs font-bold tracking-wide text-muted-foreground",children:i.key}),l("span",{className:"whitespace-nowrap tabular-nums text-muted-foreground",children:ku(i.hours)})]}),l("p",{className:"text-sm text-muted-foreground",children:pS(i)})]}),u?l(R,{size:"sm",variant:"ghost",onClick:()=>{xn({origin:"all",project:u.id}),o("today")},children:"Open"}):null]},i.key)})})]}):null}function DS({title:e,hint:t,entries:n,empty:r,meta:o,now:s,open:i,undo:a}){return m("section",{"aria-label":e,className:"space-y-2",children:[m("div",{className:"flex items-center gap-2 px-1",children:[l("h2",{className:"text-sm font-semibold",children:e}),t?l("span",{className:"ml-auto hidden text-xs text-muted-foreground sm:inline",children:t}):null]}),n.length?l("ol",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:n.map((u,c)=>l(oo,{entry:u,meta:o,now:s,onOpen:i,undo:a,first:c===0,showDay:!0},je(u)))}):l("p",{className:"px-1 text-sm text-muted-foreground",children:r})]})}function EP({meta:e,today:t,monday:n}){let r=nt(),o=en(),s=Math.max(1,7-Math.round((Date.parse(`${t}T12:00:00Z`)-Date.parse(`${n}T12:00:00Z`))/864e5)),{data:i}=We(()=>r.call("tasks.upcoming",{from:t,days:s}),[r,t,s]),a=(i?.items??[]).filter(u=>u.at>=Date.now()).slice(0,8);return m("section",{className:"space-y-2","aria-label":"Still ahead this week",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:"Still ahead this week"}),a.length===0?l("p",{className:"text-sm text-muted-foreground",children:"Nothing timed for the rest of the week."}):null,l("ol",{className:"space-y-1",children:a.map(u=>m("li",{className:"grid grid-cols-[5.5rem_minmax(0,1fr)] gap-2 text-sm",children:[m("span",{className:"text-xs tabular-nums text-muted-foreground",children:[Ge(u.at,e.zone,{weekday:"short"})," ",Ee(u.at,e.zone)]}),l("span",{className:"min-w-0 leading-snug",children:u.task.title})]},`${u.task.id}-${u.at}`))}),l("button",{type:"button",onClick:()=>o("upcoming"),className:"cursor-pointer text-xs font-semibold text-timeline-accent hover:underline",children:"See it in Tasks \u203A Upcoming"})]})}function FS({meta:e,now:t,open:n,undo:r,needs:o,signal:s,remember:i,initialDay:a}){let u=Ie(),c=J(),d=xm(e.today),[p,f]=_(xm(a??e.today)),h=p===d,g={from:qr(p,e.zone),to:qr(tn(p,7),e.zone)},{data:x,error:b,partial:v}=Ss({...g,kinds:null,project:null,overlap:!0},s);K(()=>{x&&i(x.entries)},[x,i]);let w=vP(p),C=bm(p).filter(Q=>Q<=e.today),y=Tu(C),[T,N]=_(!1),[S,$]=_(""),P=bs(x?.entries??[],g),L=no(P),ne=Q=>Ee(Q,e.zone),se=()=>{N(!0),$(""),c.call("activity.talkWeek",{week:p}).then(({thread:Q})=>{N(!1),w.reload(),u.toThread(Q)},Q=>{N(!1),$(Q instanceof Error?Q.message:String(Q))})},_e=P.filter(Q=>Q.kind==="learned"||Q.kind==="change"),ie=hS(P);return m("div",{className:"flex flex-wrap items-start gap-8",children:[m("div",{className:"min-w-0 flex-[999_1_34rem] space-y-6",children:[m(rn,{eyebrow:h?`This week so far \xB7 ${Ct(p)} to now`:`${Ct(p)} to ${Ct(tn(p,6))}`,title:`Week of ${Ge(Date.parse(`${p}T12:00:00Z`),"UTC",{month:"long",day:"numeric"})}`,children:[l(R,{variant:"outline",size:"icon","aria-label":"The week before",onClick:()=>f(tn(p,-7)),children:l(pe,{name:"ChevronLeft","aria-hidden":!0,className:"size-4"})}),l(R,{variant:"outline",size:"icon","aria-label":"The week after",disabled:h,onClick:()=>f(tn(p,7)),children:l(pe,{name:"ChevronRight","aria-hidden":!0,className:"size-4"})}),m(R,{onClick:se,disabled:T,children:[l(pe,{name:"MessageSquare","aria-hidden":!0,className:"size-4"}),w.data?.thread?"Back to this week\u2019s conversation":`Talk it over with ${e.assistant}`]})]}),S?l("p",{role:"alert",className:"text-sm text-destructive",children:S}):null,w.error&&!w.data?m("p",{role:"alert",className:"text-sm text-destructive",children:["I couldn\u2019t load the note for this week: ",w.error]}):null,w.data?.note?m("div",{className:"flex items-start gap-3.5 rounded-2xl bg-surface-selected px-4 py-3.5",children:[l(De,{origin:"assistant",assistant:e.assistant,size:28}),m("div",{className:"min-w-0",children:[l("p",{className:"whitespace-pre-wrap text-base leading-relaxed",children:w.data.note.body}),l("p",{className:"mt-1.5 text-xs text-muted-foreground",children:wu(e.assistant,w.data.note.at,t,e.zone,ne)})]})]}):x?m("div",{className:"flex items-start gap-3.5 rounded-2xl bg-surface-selected px-4 py-3.5",children:[l(De,{origin:"assistant",assistant:e.assistant,size:28}),l("p",{className:"text-base leading-relaxed",children:ro(L,Es(o),h?"week":"past-week")})]}):null,v?m("p",{className:"px-1 text-sm text-muted-foreground",children:["This week has more than ",zn.toLocaleString()," entries, so these counts cover the newest ",zn.toLocaleString(),"."]}):null,x?m(he,{children:[l(wP,{entries:P,monday:p,today:e.today,meta:e,now:t}),h?l(kP,{entries:P,needs:o,meta:e,now:t,open:n}):null,l(SP,{entries:P,span:g,meta:e,now:t}),l(DS,{title:"How I\u2019ve changed",hint:"What I learned and what I changed about myself",entries:_e,empty:"No changes to me this week.",meta:e,now:t,open:n,undo:r}),l(DS,{title:"Hasn\u2019t gone well",entries:ie,empty:"Nothing went badly this week.",meta:e,now:t,open:n,undo:r})]}):l(Oe,{children:b||"Loading\u2026"})]}),m("aside",{className:"w-full shrink-0 space-y-6 xl:w-72","aria-label":"The week at a glance",children:[m("section",{className:"space-y-2","aria-label":"My note for each day",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:"My note for each day"}),l("dl",{className:"space-y-1.5 text-sm",children:C.map(Q=>m("div",{className:"grid grid-cols-[4.5rem_minmax(0,1fr)] gap-2",children:[l("dt",{className:"text-xs font-semibold text-muted-foreground",children:Q===e.today?"Today":ur(Q,"long")}),l("dd",{className:V("leading-snug",!y.get(Q)&&"text-muted-foreground"),children:y.get(Q)??"Not written yet."})]},Q))})]}),h?l(EP,{meta:e,today:e.today,monday:p}):null,x?m("section",{className:"space-y-2",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:h?"This week so far":"That week"}),l("ul",{className:"space-y-1.5 text-sm",children:pr(L).map(Q=>l("li",{children:Q},Q))})]}):null]})]})}var $u=new Map;function NP(e){if(typeof window>"u"||!window.matchMedia)return null;let t=$u.get(e);if(t)return t;let n=window.matchMedia(e),r=new Set,o=()=>{for(let s of r)s()};return t={mql:n,subscribe(s){let i=r.size===0;return r.add(s),i&&n.addEventListener("change",o),()=>{r.delete(s),r.size===0&&(n.removeEventListener("change",o),$u.delete(e))}}},$u.set(e,t),t}function AP(e,t){return NP(e)?.subscribe(t)??(()=>{})}function CP(e){return typeof window>"u"||!window.matchMedia?!1:$u.get(e)?.mql.matches??window.matchMedia(e).matches}function Cm(e){return xt(t=>AP(e,t),()=>CP(e),()=>!1)}var TP="(max-width: 767px)",RP=Cf(null);function so(){let e=Tf(RP),t=Cm(TP);return e!==null?e:t}var Tm=globalThis.__bbPluginRuntime;if(Tm==null||Tm.reactDom==null)throw new Error('Cannot load "react-dom": this bundle must be loaded by the Moonlet app, which provides the shared plugin runtime (globalThis.__bbPluginRuntime).');var Iu=Tm.reactDom,YB="default"in Iu?Iu.default:Iu,{createPortal:zS,flushSync:qB,preconnect:JB,prefetchDNS:eU,preinit:tU,preinitModule:nU,preload:rU,preloadModule:oU,requestFormReset:sU,unstable_batchedUpdates:iU,useFormState:aU,useFormStatus:lU,version:cU}=Iu;var $P="select-none",IP=new Set(["button","checkbox","file","hidden","image","radio","range","reset","submit"]),XS=e=>V($P,e);function PP(e){return e instanceof HTMLTextAreaElement?!0:e instanceof HTMLInputElement?!e.disabled&&!e.readOnly&&!IP.has(e.type):e instanceof HTMLElement?e.isContentEditable||e.closest("[contenteditable='true']")!==null:!1}function Pu(e){if(typeof document>"u")return;let t=document.activeElement;!t||!PP(t)||e!==null&&!e.contains(t)||t.blur()}function BS(){Pu(null)}function Rm(e){e.preventDefault()}var KS="pointer";typeof document<"u"&&(document.addEventListener("keydown",()=>{KS="keyboard"},{capture:!0}),document.addEventListener("pointerdown",()=>{KS="pointer"},{capture:!0}));function US(){let e="orbit";return{"data-bb-portaled-overlay":"","data-bb-plugin-root":"",...e!==void 0?{"data-bb-plugin":e}:{}}}var OP=120;var $m="--bb-drawer-keyboard-inset",LP=80;function Ou(e){e!==null&&(e.style.height="",e.style.bottom="",e.style.removeProperty($m))}function MP({layoutViewportHeight:e,visualViewportHeight:t,visualViewportOffsetTop:n}){let r=Math.round(e-(t+n));return r>=LP?r:0}function DP(e,t){K(()=>{let n=e.current,r=window.visualViewport;if(n===null||!t||!r)return;let o=null,s=()=>{if(o=null,r.scale!==1){Ou(n);return}let a=MP({layoutViewportHeight:n.ownerDocument.documentElement.clientHeight,visualViewportHeight:r.height,visualViewportOffsetTop:r.offsetTop});if(a===0){n.style.bottom="",n.style.removeProperty($m);return}n.style.bottom=`${a}px`,n.style.setProperty($m,`${a}px`)},i=()=>{o!==null&&window.cancelAnimationFrame(o),o=window.requestAnimationFrame(s)};return s(),r.addEventListener("resize",i),r.addEventListener("scroll",i),()=>{r.removeEventListener("resize",i),r.removeEventListener("scroll",i),o!==null&&window.cancelAnimationFrame(o),Ou(n)}},[t,e])}var FP=Tn(({asChild:e,open:t,onOpenChange:n,haspopup:r,onClick:o,children:s,className:i,...a},u)=>{let c=XS(i),d=f=>{o?.(f),f.defaultPrevented||(t||BS(),n(!t))},p={"aria-expanded":t,"aria-haspopup":r,"data-state":t?"open":"closed"};return e?l(Ql,{ref:u,onClick:d,onMouseDown:Rm,className:c,...p,...a,children:s}):l("button",{ref:u,type:"button",onClick:d,onMouseDown:Rm,className:c,...p,...a,children:s})});FP.displayName="MobileTrigger";var zP=["side","sideOffset","align","alignOffset","collisionPadding","collisionBoundary","arrowPadding","sticky","hideWhenDetached","avoidCollisions","onOpenAutoFocus","onCloseAutoFocus","onEscapeKeyDown","onPointerDownOutside","onFocusOutside","onInteractOutside"],EU=new Set(zP);function Lu({open:e,enabled:t=!0}){let[n,r]=_(!1),o=q(()=>r(!0),[]);return K(()=>{if(!t||!e||n)return;let s=null,i=null;s=window.requestAnimationFrame(()=>{s=null,i=window.requestAnimationFrame(()=>{i=null,o()})});let a=window.setTimeout(o,OP);return()=>{s!==null&&window.cancelAnimationFrame(s),i!==null&&window.cancelAnimationFrame(i),window.clearTimeout(a)}},[t,n,e,o]),{isContentRealized:t&&n,realizeContent:o}}var HS="cubic-bezier(0.32, 0.72, 0, 1)",KP=.25,XP=450,BP=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(","),Im=Symbol.for("bb.persistent-drawer-stack.v1");function UP(e){return typeof e=="object"&&e!==null&&"entries"in e&&Array.isArray(e.entries)&&"handleKeyDown"in e&&typeof e.handleKeyDown=="function"}function VS(e){let t=Reflect.get(e,Im);return UP(t)?t:void 0}function HP(e){return Array.from(e.querySelectorAll(BP)).filter(t=>t.closest('[aria-hidden="true"], [inert]')===null)}function VP(e,t){let n=e?.closest("[data-bb-portaled-overlay]");return n!=null&&n!==t}function ZP(e,t){let n=t.ownerDocument.activeElement;if(!t.contains(n)&&VP(n,t))return;let r=HP(t);if(e.preventDefault(),r.length===0){t.focus({preventScroll:!0});return}let o=r[0],s=r[r.length-1];if(e.shiftKey){if(!t.contains(n)||n===t||n===o){s?.focus({preventScroll:!0});return}let a=r.indexOf(n);r[Math.max(0,a-1)]?.focus({preventScroll:!0});return}if(!t.contains(n)||n===t||n===s){o?.focus({preventScroll:!0});return}let i=r.indexOf(n);r[Math.min(r.length-1,i+1)]?.focus({preventScroll:!0})}function WP(e,t){let n=VS(e);if(n===void 0){let r=[],o=s=>{if(s.defaultPrevented)return;let i=r[r.length-1],a=i?.panel()??null;i===void 0||a===null||(s.key==="Escape"?(i.dismissOnEscape(s),s.preventDefault()):s.key==="Tab"&&ZP(s,a))};n={entries:r,handleKeyDown:o},Reflect.set(e,Im,n),e.addEventListener("keydown",o)}return n.entries.push(t),()=>{let r=VS(e);if(r===void 0)return;let o=r.entries.indexOf(t);o>=0&&r.entries.splice(o,1),r.entries.length===0&&(e.removeEventListener("keydown",r.handleKeyDown),Reflect.deleteProperty(e,Im))}}function jP({onAfterCloseAutoFocus:e,onBeforeCloseAutoFocus:t,onEscapeKeyDown:n,open:r,panelRef:o,requestClose:s}){let i=Y(null),a=Y(n);ot(()=>{a.current=n},[n]),ot(()=>{if(!r)return;let c=o.current;if(c===null)return;let d=c.ownerDocument,p=d.activeElement;i.current=p instanceof HTMLElement&&p!==d.body?p:null;let f=WP(d,{panel:()=>o.current,dismissOnEscape:h=>{a.current?.(h),h.defaultPrevented||s()}});return c.focus({preventScroll:!0}),f},[r,o,s]);let u=Y(r);ot(()=>{let c;if(u.current&&!r){t?.();let d=i.current;if(d?.isConnected&&d.closest('[aria-hidden="true"], [inert]')===null&&(d.focus({preventScroll:!0}),d.ownerDocument.activeElement!==d)){let p=d.ownerDocument.defaultView;if(p!==null){let f=p.requestAnimationFrame(()=>{d.isConnected&&d.closest('[aria-hidden="true"], [inert]')===null&&d.focus({preventScroll:!0}),e?.()});c=()=>p.cancelAnimationFrame(f)}}i.current=null,c===void 0&&e?.()}return u.current=r,c},[e,t,r])}function Mu({open:e,onOpenChange:t,onAfterCloseAutoFocus:n,closeOnBackdropClick:r=!0,srLabel:o,labelledBy:s,describedBy:i,contentClassName:a,motionDurationMs:u=220,onContentAnimationEnd:c,onEscapeKeyDown:d,onPointerDownOutside:p,onInteractOutside:f,children:h}){let g=Y(null),x=Y(null),b=Y(null),v=Y(null),w=Y(null),C=Ai(),y=US(),T=`transform ${u}ms ${HS}`,N=`opacity ${u}ms ${HS}`,S=Y(t);ot(()=>{S.current=t},[t]);let $=q(()=>{Pu(g.current),Ou(g.current),S.current(!1)},[]),P=q(()=>{Pu(g.current),Ou(g.current)},[]);jP({onAfterCloseAutoFocus:n,onBeforeCloseAutoFocus:P,onEscapeKeyDown:d,open:e,panelRef:g,requestClose:$});let L=()=>{let G=b.current;if(b.current=null,!!r){if(G!==null){let ee=new CustomEvent("dismissableLayer.pointerDownOutside",{cancelable:!0,detail:{originalEvent:G}});if(p?.(ee),f?.(ee),ee.defaultPrevented)return}$()}};DP(g,e);let ne=q(G=>{w.current!==G&&(w.current=G,c?.(G))},[c]);K(()=>{w.current=null;let G=window.setTimeout(()=>ne(e),u+50);return()=>window.clearTimeout(G)},[u,e,ne]);let se=q((G,ee,be)=>{let H=g.current,xe=x.current;H===null||xe===null||(H.style.transition=be?T:"none",H.style.transform=`translate3d(0, ${G}px, 0)`,xe.style.transition=be?N:"none",xe.style.opacity=String(Math.max(0,Math.min(1,1-G/ee))))},[N,T]),_e=q(G=>{if(!e||G.button!==0)return;G.currentTarget.setPointerCapture(G.pointerId);let ee=Date.now(),be=Math.max(g.current?.clientHeight??0,1);v.current={pointerId:G.pointerId,startY:G.clientY,lastY:G.clientY,lastTimeMs:ee,velocityY:0,height:be},se(0,be,!1),G.preventDefault()},[e,se]),ie=q(G=>{let ee=v.current;if(ee===null||ee.pointerId!==G.pointerId)return;let be=Date.now(),H=be-ee.lastTimeMs;H>0&&(ee.velocityY=(G.clientY-ee.lastY)/H*1e3,ee.lastY=G.clientY,ee.lastTimeMs=be),se(Math.max(0,G.clientY-ee.startY),ee.height,!1),G.preventDefault()},[se]),Q=q((G,ee)=>{let be=v.current;if(be===null||be.pointerId!==G.pointerId)return;v.current=null;let H=Math.max(0,G.clientY-be.startY);!ee&&(H>=be.height*KP||be.velocityY>=XP)?(se(be.height,be.height,!0),$()):se(0,be.height,!0),G.preventDefault()},[$,se]),j=typeof document>"u"?null:document.body;return j===null?null:zS(m(he,{children:[l("div",{ref:x,...y,"aria-hidden":"true","data-persistent-drawer-backdrop":"","data-state":e?"open":"closed",className:"fixed inset-0 z-50 bg-black/40",style:{opacity:e?1:0,pointerEvents:e?"auto":"none",transition:N},onPointerDown:G=>{b.current=G.nativeEvent},onClick:L,onTouchMove:G=>G.preventDefault()}),m("div",{ref:g,...y,"aria-hidden":!e,"aria-labelledby":s??(o===void 0?void 0:C),"aria-describedby":i,"aria-modal":e||void 0,"data-bb-portaled-overlay":"","data-persistent-drawer-content":"","data-state":e?"open":"closed",inert:!e,role:"dialog",tabIndex:-1,className:V("fixed inset-x-0 bottom-0 z-50 mt-24 flex max-h-[calc(92dvh-var(--bb-drawer-keyboard-inset,0px))] flex-col rounded-t-xl border bg-background pb-[var(--bb-safe-area-bottom,env(safe-area-inset-bottom))] outline-none",a),style:{transform:e?"translate3d(0, 0, 0)":"translate3d(0, 100%, 0)",transition:T,willChange:e?"transform":void 0},onTransitionEnd:G=>{G.currentTarget===G.target&&G.propertyName==="transform"&&ne(e)},children:[l("div",{"data-persistent-drawer-handle":"",className:"mx-auto flex h-8 w-16 shrink-0 touch-none cursor-grab items-center justify-center active:cursor-grabbing",onPointerDown:_e,onPointerMove:ie,onPointerUp:G=>Q(G,!1),onPointerCancel:G=>Q(G,!0),children:l("div",{className:"h-1 w-10 rounded-full bg-muted-foreground/20"})}),o===void 0?null:l("h2",{id:C,className:"sr-only",children:o}),h]})]}),j)}function Fu({open:e,onClose:t,label:n,side:r="center",children:o}){let s=so(),{isContentRealized:i}=Lu({open:e,enabled:s});return K(()=>{if(!e||s)return;let a=u=>{u.key==="Escape"&&(u.preventDefault(),t())};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[e,s,t]),s?l(Mu,{open:e,onOpenChange:a=>a?void 0:t(),srLabel:n,children:i?l("div",{className:"max-h-[85dvh] overflow-y-auto overscroll-contain pb-6",children:o}):null}):e?r==="right"?l("aside",{role:"dialog","aria-label":n,className:"fixed inset-y-0 right-0 z-40 flex w-full max-w-xl flex-col overflow-y-auto border-l border-border bg-background shadow-2xl",children:o}):l("div",{className:"fixed inset-0 z-40 grid place-items-center bg-surface-scrim p-4",onMouseDown:a=>a.target===a.currentTarget&&t(),children:l("div",{role:"dialog","aria-label":n,className:"max-h-[90dvh] w-full max-w-lg overflow-y-auto rounded-2xl border border-border bg-background shadow-2xl",children:o})}):null}var QP={todo:[{label:"Today",text:"today"},{label:"Tomorrow",text:"tomorrow"},{label:"This weekend",text:"this weekend"},{label:"Next week",text:"next week"},{label:"In a month",text:"in a month"}],followup:[{label:"Tomorrow morning",text:"check back tomorrow 9am"},{label:"In 3 days",text:"check back in 3 days 9am"},{label:"Next week",text:"check back next week 9am"}],scheduled:[{label:"Later today",text:"today 6pm"},{label:"Tomorrow morning",text:"tomorrow 9am"},{label:"Every weekday",text:"every weekday at 9am"},{label:"Every week",text:"every monday at 9am"},{label:"Monthly",text:"monthly on the 1st at 9am"}]};function YS({kind:e,zone:t,initial:n,onChange:r}){let o=nt(),[s,i]=_(n??""),[a,u]=_(null),c=Y(r);c.current=r;let d=p=>{i(p),u(null),c.current(null,!p.trim())};return K(()=>{if(!s.trim()){u(null),c.current(null,!0);return}let p=!0,f=setTimeout(()=>{o.call("tasks.when",{text:s,kind:e}).then(h=>{p&&(u(h.ok?{ok:!0,reading:h.reading,next:h.next}:h),c.current(h.ok?h.when:null,h.ok))})},220);return()=>{p=!1,clearTimeout(f)}},[s,e,o]),m("div",{className:"space-y-2.5",children:[l(le,{"aria-label":"When, in your own words",placeholder:e==="scheduled"?"every other friday at 4pm":e==="followup"?"check back friday 9am":"by friday",value:s,onChange:p=>d(p.target.value)}),a?.ok?m("div",{className:"rounded-lg bg-surface-selected px-3 py-2 text-sm",children:[m("p",{className:"flex items-center gap-2 font-semibold",children:[l(pe,{name:"Check","aria-hidden":!0,className:"size-4 text-success"}),Qr(a.reading)]}),a.next.length?l("ul",{className:"mt-1.5 space-y-0.5 pl-6 text-xs text-muted-foreground",children:a.next.map(p=>m("li",{children:[Ge(p,t,{weekday:"short",day:"numeric",month:"short"})," \xB7 ",Ee(p,t)]},p))}):null]}):a?l("p",{role:"status",className:"text-sm text-destructive-text",children:a.error}):null,l("div",{className:"flex flex-wrap gap-1.5",children:QP[e].map(p=>l("button",{type:"button",className:"cursor-pointer rounded-full border border-border px-2.5 py-1 text-xs font-medium hover:bg-state-hover",onClick:()=>d(p.text),children:p.label},p.label))})]})}function io({label:e,children:t}){return m("label",{className:"block space-y-1.5",children:[l("span",{className:"text-xs font-semibold text-muted-foreground",children:e}),t]})}var Du=["urgent","high","medium","low","none"],GP=["owner","assistant","others"];function Pm(e,t){return e.find(n=>n===t)??null}var ZS="h-9 w-full cursor-pointer rounded-md border border-input bg-background px-2 text-sm";function qS({open:e,onClose:t,meta:n,onMade:r}){let{change:o,error:s,busy:i}=Ea(),[a,u]=_(""),[c,d]=_("personal"),[p,f]=_("todo"),[h,g]=_(null),[x,b]=_(!0),[v,w]=_("medium"),[C,y]=_("assistant"),[T,N]=_(""),[S,$]=_(""),[P,L]=_(0),ne=n?.assistant??"Assistant",se=()=>{u(""),g(null),$(""),N(""),L(ie=>ie+1)};return l(Fu,{open:e,onClose:t,label:"New task",children:m("form",{onSubmit:async ie=>{if(ie.preventDefault(),!a.trim()||!x)return;let Q=await o({action:"create",task:{project:c,title:a,kind:p,when:h,priority:v,move:C,waitingOn:C==="others"&&T||null,description:S}});Q&&(se(),r(Q))},className:"space-y-4 p-5",children:[l("h2",{className:"text-lg font-semibold",children:"New task"}),l(io,{label:"What",children:l(le,{autoFocus:!0,value:a,onChange:ie=>u(ie.target.value),placeholder:"Renew the passport"})}),l("div",{className:"flex flex-wrap items-center gap-3",children:l(_t,{label:"Kind",value:p,onChange:ie=>{f(ie),ie==="followup"&&y("others")},options:["todo","followup","scheduled"].map(ie=>({value:ie,label:m(he,{children:[l(Ht,{glyph:ie==="scheduled"?"once":ie,className:"size-3.5"}),mu[ie]]})}))})}),l(io,{label:"When",children:l(YS,{kind:p,zone:n?.zone??"UTC",onChange:(ie,Q)=>{g(ie),b(Q)}},`${p}-${P}`)}),m("div",{className:"grid grid-cols-2 gap-3",children:[l(io,{label:"Project",children:l("select",{className:ZS,value:c,onChange:ie=>d(ie.target.value),children:(n?.projects??[{id:"personal",key:"ME",name:"Personal"}]).map(ie=>m("option",{value:ie.id,children:[ie.name," (",ie.key,")"]},ie.id))})}),l(io,{label:"Priority",children:l("select",{className:ZS,value:v,onChange:ie=>w(Pm(Du,ie.target.value)??"medium"),children:Du.map(ie=>l("option",{value:ie,children:cs[ie]},ie))})})]}),l(io,{label:"Whose move",children:l(_t,{label:"Whose move",value:C,onChange:y,options:[{value:"owner",label:"Mine"},{value:"assistant",label:`${ne}\u2019s`},{value:"others",label:"Waiting on someone"}]})}),C==="others"?l(io,{label:"Waiting on",children:l(le,{value:T,onChange:ie=>N(ie.target.value),placeholder:"Acme Mutual"})}):null,l(io,{label:"Notes",children:l("textarea",{value:S,onChange:ie=>$(ie.target.value),rows:3,className:"w-full resize-y rounded-md border border-input bg-background px-3 py-2 text-sm",placeholder:"Anything that helps"})}),s?l("p",{role:"alert",className:"text-sm text-destructive-text",children:s}):null,m("div",{className:"flex justify-end gap-2 pt-1",children:[l(R,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),l(R,{type:"submit",disabled:i||!a.trim()||!x||C==="others"&&!T.trim(),children:"Add task"})]})]})})}var YP=/^(?:https?:\/\/[^\s]+|\/api\/v1\/plugins\/tasks\/http\/attachments\/download\?attachmentId=[A-Za-z0-9_%-]+)$/i,WS="inline-flex max-w-full items-center gap-1.5 truncate rounded-md border border-border px-2 py-1 text-xs font-medium";function qP({link:e}){let t=Ie(),n=en(),r=m(he,{children:[l(pe,{name:e.kind==="pull_request"?"GitPullRequest":e.kind==="mail"?"Mail":e.kind==="conversation"?"ChildThread":"ExternalLink","aria-hidden":!0,className:"size-3.5"}),l("span",{className:"truncate",children:e.label??e.ref})]}),o=V(WS,"cursor-pointer hover:bg-state-hover");if(e.kind==="conversation"&&/^thr_[A-Za-z0-9_-]+$/.test(e.ref))return l("button",{type:"button",className:o,title:"Open the conversation",onClick:()=>t.toThread(e.ref),children:r});if(e.kind==="task")return l("button",{type:"button",className:o,title:"Open the task",onClick:()=>n("today",e.ref),children:r});if(YP.test(e.ref)){let s=e.ref.startsWith("/");return l("a",{href:e.ref,className:o,title:e.ref,...s?{download:e.label??!0}:{target:"_blank",rel:"noreferrer noopener"},children:r})}return l("span",{className:WS,title:e.ref,children:r})}var jS=200,QS=1e4,GS=e=>({owner:"Your move",assistant:`${e}\u2019s move`,others:"Waiting on others"});function JS({open:e,taskRef:t,meta:n,onClose:r}){let[o,s]=_("Task");return l(Fu,{open:e,onClose:r,label:o,side:"right",children:t?l(JP,{taskRef:t,meta:n,onClose:r,onLabel:s},t):null})}function JP({taskRef:e,meta:t,onClose:n,onLabel:r}){let o=nt(),{change:s,error:i}=Ea(),[a,u]=_(!1),[c,d]=_(""),[p,f]=_(jS),{data:h,error:g}=We(()=>o.call("tasks.show",{ref:e,recent:p}),[o,e,p]),[x,b]=_(""),[v,w]=_(""),[C,y]=_(!1),[T,N]=_({when:null,ok:!1}),[S,$]=_(!1),[P,L]=_(""),[ne,se]=_(!1),[_e,ie]=_(""),Q=t?.assistant??"Assistant",j=t?.zone??"UTC",G=h?.task.title??"Task";if(K(()=>r(G),[G,r]),!h)return l("p",{className:"p-6 text-sm text-muted-foreground",children:g||"Loading\u2026"});let ee=h.task,be=ee.id;return m(he,{children:[m("div",{className:"flex items-center gap-2 border-b border-border-hairline px-5 py-3 text-xs text-muted-foreground",children:[l("span",{className:"font-semibold text-foreground",children:ee.key}),l("span",{"aria-hidden":!0,children:"\xB7"}),l("span",{children:ee.project.name}),h.aliases.length?m("span",{children:["\xB7 also ",h.aliases.join(", ")]}):null,l(R,{variant:"ghost",size:"icon",className:"ml-auto size-8","aria-label":"Close",onClick:n,children:l(pe,{name:"ChevronRight","aria-hidden":!0,className:"size-4"})})]}),m("div",{className:"space-y-6 px-5 py-5",children:[m("div",{className:"flex items-start gap-3",children:[l(lm,{task:ee,onToggle:()=>{s(ee.status==="open"?{action:"done",ref:be,note:null}:{action:"reopen",ref:be,why:null})}}),ne?l("form",{className:"flex-1",onSubmit:H=>{H.preventDefault(),s({action:"update",ref:be,patch:{title:_e}}).then(xe=>xe&&se(!1))},children:l(le,{autoFocus:!0,value:_e,onChange:H=>ie(H.target.value),onBlur:()=>se(!1),"aria-label":"Title"})}):l("button",{type:"button",className:V("flex-1 cursor-text text-left text-xl font-semibold leading-snug",ee.status!=="open"&&"text-muted-foreground line-through"),onClick:()=>{ie(ee.title),se(!0)},children:ee.title})]}),m("dl",{className:"grid grid-cols-[7rem_minmax(0,1fr)] items-center gap-x-3 gap-y-2.5 text-sm",children:[l("dt",{className:"text-muted-foreground",children:"Kind"}),m("dd",{className:"flex items-center gap-1.5 font-medium",children:[l(Ht,{glyph:jr(ee),className:"text-timeline-accent"}),mu[ee.kind]]}),l("dt",{className:"text-muted-foreground",children:"Whose move"}),m("dd",{className:"flex flex-wrap items-center gap-2",children:[l("select",{"aria-label":"Whose move",className:"h-8 cursor-pointer rounded-md border border-input bg-background px-2 text-sm font-medium",value:a?"others":ee.move,onChange:H=>{let xe=Pm(GP,H.target.value);xe&&(xe==="others"?(d(ee.waitingOn??""),u(!0)):(u(!1),s({action:"update",ref:be,patch:{move:xe}})))},children:Object.entries(GS(Q)).map(([H,xe])=>l("option",{value:H,children:H==="others"&&ee.waitingOn?`Waiting on ${ee.waitingOn}`:xe},H))}),a?m("form",{className:"flex gap-2",onSubmit:H=>{H.preventDefault(),c.trim()&&s({action:"update",ref:be,patch:{move:"others",waitingOn:c}}).then(xe=>xe&&u(!1))},children:[l(le,{autoFocus:!0,value:c,onChange:H=>d(H.target.value),placeholder:"Who it waits on","aria-label":"Who it waits on",className:"h-8 w-44 text-sm"}),l(R,{size:"sm",type:"submit",disabled:!c.trim(),children:"Save"})]}):null]}),l("dt",{className:"text-muted-foreground",children:"From"}),m("dd",{className:"flex min-w-0 items-center gap-2",children:[l(De,{origin:ee.origin,assistant:Q,size:18}),l("span",{className:"truncate",children:ee.origin==="assistant"?`${Q}${ee.why?`: ${ee.why}`:""}`:"You"})]}),l("dt",{className:"text-muted-foreground",children:"Priority"}),m("dd",{className:"flex items-center gap-2",children:[l(us,{level:ee.priority}),l("select",{"aria-label":"Priority",className:"h-8 cursor-pointer rounded-md border border-input bg-background px-2 text-sm font-medium",value:ee.priority,onChange:H=>{let xe=Pm(Du,H.target.value);xe&&s({action:"update",ref:be,patch:{priority:xe}})},children:Du.map(H=>l("option",{value:H,children:cs[H]},H))})]}),l("dt",{className:"text-muted-foreground",children:"Project"}),l("dd",{children:l("select",{"aria-label":"Project",className:"h-8 cursor-pointer rounded-md border border-input bg-background px-2 text-sm font-medium",value:ee.project.id,onChange:H=>{s({action:"move",ref:be,project:H.target.value})},children:(t?.projects??[ee.project]).map(H=>m("option",{value:H.id,children:[H.name," (",H.key,")"]},H.id))})}),ee.doneWhen?m(he,{children:[l("dt",{className:"self-start text-muted-foreground",children:"Done when"}),l("dd",{className:"leading-relaxed",children:ee.doneWhen})]}):null]}),m("div",{className:"rounded-xl bg-surface-selected px-4 py-3.5",children:[l("p",{className:"text-xs font-semibold text-muted-foreground",children:ee.kind==="followup"?"Next check":ee.kind==="scheduled"?"When":"Due"}),C?m("div",{className:"mt-2 space-y-3",children:[l(YS,{kind:ee.kind,zone:j,onChange:(H,xe)=>N({when:H,ok:xe})}),m("div",{className:"flex gap-2",children:[l(R,{size:"sm",disabled:!T.ok,onClick:()=>{s({action:"update",ref:be,patch:{when:T.when}}).then(H=>H&&y(!1))},children:"Save"}),l(R,{size:"sm",variant:"outline",onClick:()=>y(!1),children:"Cancel"})]})]}):m(he,{children:[l("p",{className:"mt-0.5 text-base font-semibold",children:ee.whenText?Qr(ee.whenText):"Not set"}),ee.dueAt?l("p",{className:"text-xs text-muted-foreground",children:Ge(ee.dueAt,j,{weekday:"long",day:"numeric",month:"long",hour:"numeric",minute:"2-digit"})}):null,m("div",{className:"mt-3 flex flex-wrap gap-2",children:[m(R,{size:"sm",variant:"outline",onClick:()=>y(!0),children:[l(pe,{name:"Clock","aria-hidden":!0,className:"size-3.5"}),"Change when"]}),ee.status==="open"&&ee.move!=="owner"?l(R,{size:"sm",variant:"outline",onClick:()=>{s({action:"update",ref:be,patch:{move:"owner",why:"you took it over"}})},children:"I\u2019ll take it from here"}):null]})]})]}),ee.description?l("p",{className:"whitespace-pre-wrap text-sm leading-relaxed text-foreground/90",children:ee.description}):null,m("section",{className:"space-y-2",children:[m("h3",{className:"text-sm font-semibold",children:["Steps"," ",h.steps.length?m("span",{className:"font-normal text-muted-foreground",children:[h.steps.filter(H=>H.doneAt).length," of ",h.steps.length]}):null]}),l("ul",{className:"space-y-1",children:h.steps.map(H=>m("li",{className:"flex items-center gap-2.5 text-sm",children:[l("input",{type:"checkbox","aria-label":H.title,className:"size-4 cursor-pointer accent-foreground",checked:H.doneAt!==null,onChange:xe=>{s({action:"checkStep",ref:be,position:H.position,done:xe.target.checked})}}),l("span",{className:V(H.doneAt&&"text-muted-foreground line-through"),children:H.title}),H.doneBy?l("span",{className:"ml-auto text-xs text-muted-foreground",children:H.doneBy==="assistant"?Q:H.doneBy==="owner"?"You":"System"}):null]},H.position))}),l("form",{className:"flex gap-2",onSubmit:H=>{H.preventDefault(),v.trim()&&s({action:"addStep",ref:be,title:v}).then(xe=>xe&&w(""))},children:l(le,{value:v,onChange:H=>w(H.target.value),placeholder:"Add a step","aria-label":"Add a step",className:"h-8 text-sm"})})]}),h.links.length?m("section",{className:"space-y-2",children:[l("h3",{className:"text-sm font-semibold",children:"Linked"}),l("div",{className:"flex flex-wrap gap-2",children:h.links.map(H=>l(qP,{link:H},`${H.kind}:${H.ref}`))})]}):null,m("section",{className:"space-y-3",children:[l("h3",{className:"text-sm font-semibold",children:"Journal"}),h.earlier!==null?p<QS?m("button",{type:"button",onClick:()=>f(H=>Math.min(H+jS,QS)),className:"flex cursor-pointer items-center gap-2 text-sm font-semibold text-timeline-accent hover:underline",children:[l(pe,{name:"ChevronUp","aria-hidden":!0,className:"size-3.5"}),"Show earlier"]}):m("p",{className:"text-xs text-muted-foreground",children:["Earlier lines: moonlet orbit tasks journal --task ",h.task.key," --before ",h.earlier]}):null,l("ol",{className:"relative space-y-3 border-l border-border-hairline pl-5",children:h.journal.map(H=>m("li",{className:"relative",children:[l("span",{className:"absolute -left-[1.85rem] top-0.5",children:H.actor==="system"?l("span",{className:"block size-4 rounded-full border border-border bg-muted"}):l(De,{origin:H.actor==="assistant"?"assistant":"owner",assistant:Q,size:18})}),m("p",{className:"text-xs text-muted-foreground",children:[Ge(H.at,j,{weekday:"short",day:"numeric",month:"short"})," \xB7 ",Ee(H.at,j)," \xB7"," ",H.actor==="assistant"?Q:H.actor==="owner"?"You":"System"]}),l("p",{className:V("mt-0.5 whitespace-pre-wrap text-sm leading-relaxed",H.actor==="owner"&&H.what==="note"&&"rounded-lg bg-muted px-3 py-2",H.what==="created"&&"text-muted-foreground"),children:H.body})]},H.seq))}),m("form",{className:"flex gap-2",onSubmit:H=>{H.preventDefault(),x.trim()&&s({action:"note",ref:be,body:x}).then(xe=>xe&&b(""))},children:[l(le,{value:x,onChange:H=>b(H.target.value),placeholder:`Add a note, or something for ${Q} to know`,"aria-label":"Add a note"}),l(R,{type:"submit",disabled:!x.trim(),children:"Add"})]})]}),i?l("p",{role:"alert",className:"text-sm text-destructive-text",children:i}):null,m("div",{className:"flex flex-wrap items-center gap-2 border-t border-border-hairline pt-4",children:[ee.status==="open"?m(he,{children:[m(R,{size:"sm",onClick:()=>{s({action:"done",ref:be,note:null})},children:[l(pe,{name:"Check","aria-hidden":!0,className:"size-3.5"}),"Done"]}),S?m("form",{className:"flex flex-1 gap-2",onSubmit:H=>{H.preventDefault(),P.trim()&&s({action:"drop",ref:be,reason:P}).then(xe=>xe&&$(!1))},children:[l(le,{autoFocus:!0,value:P,onChange:H=>L(H.target.value),placeholder:"Why it no longer matters","aria-label":"Why drop it",className:"h-8 text-sm"}),l(R,{size:"sm",variant:"outline",type:"submit",disabled:!P.trim(),children:"Drop"})]}):l(R,{size:"sm",variant:"outline",onClick:()=>$(!0),children:"Drop"})]}):m(R,{size:"sm",variant:"outline",onClick:()=>{s({action:"reopen",ref:be,why:null})},children:[l(pe,{name:"RotateCcw","aria-hidden":!0,className:"size-3.5"}),"Reopen"]}),m("span",{className:"ml-auto text-xs text-muted-foreground",children:[ee.status==="open"?GS(Q)[ee.move]:ee.status==="done"?"Done":`Dropped: ${ee.reason??""}`,ee.closedAt?` \xB7 ${Ge(ee.closedAt,j,{day:"numeric",month:"short"})}`:""]})]})]})]})}function eO(e,t){let n=Ge(e.at,t.zone,{weekday:"long",day:"numeric",month:"long"}),r=e.startedAt??e.at,o=e.endedAt;return o!==null&&o-r>=6e4?`${n}, ${Ee(r,t.zone)}\u2013${Ee(o,t.zone)}`:`${n}, ${Ee(e.at,t.zone)}`}function tO(e,t){return e.actor==="owner"?"You":e.actor==="system"?"Moonlet itself":t.assistant}function eE({entry:e,open:t,meta:n,now:r,undo:o,onClose:s}){let i=Ie(),a=en(),u=e&&o.said?.ref===je(e)?o.said:null,c=e?bu(e):null,d=e?to(e,r):null;return l(Fu,{open:t&&e!==null,onClose:s,label:e?Ta(e):"Activity",side:"right",children:e?m("div",{className:"flex flex-col gap-6 p-5 sm:p-6",children:[m("div",{className:"flex items-start gap-3",children:[m("div",{className:"min-w-0 flex-1",children:[m("p",{className:"flex items-center gap-1.5 text-xs font-semibold text-muted-foreground",children:[l(_n,{kind:e.kind,className:"size-3.5 text-timeline-accent"}),[e.kind==="check"?e.title.split(":")[0]:eo[e.kind],eO(e,n),d].filter(Boolean).join(" \xB7 ")]}),l("h2",{className:"mt-1.5 text-xl font-semibold leading-snug tracking-tight",children:Ta(e)})]}),l(R,{variant:"ghost",size:"icon","aria-label":"Close",onClick:s,children:l(pe,{name:"X","aria-hidden":!0,className:"size-4"})})]}),m("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[nn(e)?l("span",{className:e.needsYou?"rounded-md bg-warning/15 px-2 py-1 font-semibold text-warning-text":"rounded-md bg-muted px-2 py-1 font-semibold",children:nn(e)}):null,e.task?m("button",{type:"button",onClick:()=>a("today",e.task.key),className:"cursor-pointer rounded-md border border-border-hairline px-2 py-1 font-semibold hover:bg-state-hover",children:[e.task.key," \xB7 ",e.task.title]}):null,m("span",{className:"inline-flex items-center gap-1.5 rounded-md border border-border-hairline px-2 py-1 text-muted-foreground",children:[e.actor==="system"?null:l(De,{origin:e.actor==="owner"?"owner":"assistant",assistant:n.assistant,size:14}),tO(e,n)]})]}),c?l("p",{className:"rounded-xl bg-surface-selected px-4 py-3 text-base leading-relaxed",children:c}):null,e.kind==="approval"?m("section",{className:"space-y-2",children:[l("h3",{className:"text-xs font-semibold text-muted-foreground",children:"What it asked to run"}),l("pre",{className:"max-h-60 overflow-auto whitespace-pre-wrap break-words rounded-lg bg-muted p-3 font-mono text-xs",children:e.detail})]}):e.detail&&e.kind!=="check"?l("p",{className:"whitespace-pre-wrap text-base leading-relaxed",children:e.detail}):null,e.kind==="change"?l(Of,{id:e.id,beforeLabel:"Before"},e.id):null,e.steps.length?m("section",{className:"space-y-2",children:[l("h3",{className:"text-xs font-semibold text-muted-foreground",children:e.kind==="approval"?"How it was decided":"How it went"}),l("ol",{className:"space-y-1.5 border-l border-border-hairline pl-4",children:e.steps.map((p,f)=>m("li",{className:"grid grid-cols-[4rem_minmax(0,1fr)] gap-2 text-sm",children:[l("span",{className:"text-xs tabular-nums text-muted-foreground",children:Ee(p.at,n.zone)}),l("span",{className:"min-w-0 break-words",children:p.text})]},`${p.at}-${f}`))})]}):null,m("div",{className:"flex flex-wrap items-center gap-2 border-t border-border-hairline pt-4",children:[e.thread?m(R,{onClick:()=>i.toThread(e.thread),children:[l(pe,{name:"MessageSquare","aria-hidden":!0,className:"size-4"}),"Open the conversation"]}):null,e.task?m(R,{variant:"outline",onClick:()=>a("today",e.task.key),children:["Open ",e.task.key]}):null,e.undo&&!u?.done?l(R,{variant:"outline",disabled:o.busy!==null,onClick:()=>o.undo(e),children:"Undo"}):null,u?l("span",{role:"status",className:u.done?"text-sm text-muted-foreground":"text-sm text-destructive",children:u.text}):null]})]}):null})}function nO(e){return e.fromThread?`${e.fromName??"(not listed)"} ${e.fromThread}${e.fromHost?` on ${e.fromHost}`:""}`:"outside Moonlet's conversations (unverified)"}function tE(){let e=J(),[t,n]=_(null),[r,o]=_(null),[s,i]=_(null),a=Y(()=>{});K(()=>{let d=!0,p=!1,f=!1,h=async()=>{if(p){f=!0;return}p=!0;do{f=!1;try{let x=await e.call("messages.state",null);d&&!f&&(n(x.held),o(null))}catch(x){d&&o(x instanceof Error?x.message:String(x))}}while(d&&f);p=!1};a.current=()=>{h()},h();let g=setInterval(()=>{p||h()},5e3);return()=>{d=!1,clearInterval(g),a.current=()=>{}}},[e]);let u=q(()=>a.current(),[]);ke("messages",u);let c=async(d,p)=>{i(p),o(null);try{let f=await e.call(d,{id:p});n(h=>h?.filter(g=>g.id!==f.id||f.status==="held")??null),u()}catch(f){o(f instanceof Error?f.message:String(f))}finally{i(null)}};return m("section",{className:"flex min-w-0 flex-col gap-2 text-sm","aria-label":"Held messages",children:[l("h2",{className:"font-medium",children:"Messages held for you"}),l("p",{className:"text-xs text-muted-foreground",children:"A message from a sender that isn't listed waits here for your yes. A sender outside Moonlet's conversations is unverified, and a message is information for its recipient, never an approval in your name."}),r&&l("p",{role:"alert",className:"text-destructive",children:r}),t===null?r?null:l("p",{className:"text-muted-foreground",children:"Loading messages\u2026"}):t.length===0?l("p",{className:"text-muted-foreground",children:"No held messages."}):l("ul",{className:"divide-y text-xs",children:t.map(d=>m("li",{className:"flex flex-col gap-1 py-2",children:[m("div",{className:"flex flex-wrap gap-2",children:[m("span",{className:"w-10 shrink-0 font-mono",children:["#",d.id]}),l("span",{className:"w-36 shrink-0 text-muted-foreground",children:new Date(d.at).toLocaleString()}),m("span",{className:"flex-1",children:["to ",l("span",{className:"font-medium",children:d.to})," from ",l("span",{className:"font-mono",children:nO(d)})]})]}),l("pre",{className:"max-h-40 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted p-2 font-mono",children:d.text}),m("div",{className:"flex gap-2",children:[m(R,{size:"sm",disabled:s!==null,onClick:()=>{c("messages.deliver",d.id)},children:["Deliver to ",d.to]}),l(R,{size:"sm",variant:"ghost",disabled:s!==null,onClick:()=>{c("messages.discard",d.id)},children:"Discard"})]})]},d.id))})]})}function oO({meta:e,now:t,open:n,undo:r,needs:o,signal:s,remember:i,day:a,onDay:u}){let[c,d]=_("everything"),[p,f]=_(!0),[h,g]=_(""),[x,b]=_(null),v=xu(a,e.zone),{data:w,error:C,partial:y}=Ss({...v,kinds:null,project:h||null,overlap:!0},s);K(()=>{w&&i(w.entries)},[w,i]);let T=a===e.today;K(()=>{b(null)},[a]);let N=se=>u(se),S=bs(w?.entries??[],v),$=iS(S,c,x,t),{running:P,groups:L}=aS($,e.zone,p),ne=no(S);return m("div",{className:"flex flex-wrap items-start gap-8",children:[m("div",{className:"min-w-0 flex-[999_1_34rem] space-y-6",children:[m(rn,{eyebrow:T?"Activity today":"Activity",title:Ct(a),children:[l(R,{variant:"outline",size:"icon","aria-label":"The day before",onClick:()=>N(tn(a,-1)),children:l(pe,{name:"ChevronLeft","aria-hidden":!0,className:"size-4"})}),l(R,{variant:"outline",size:"icon","aria-label":"The day after",disabled:T,onClick:()=>N(tn(a,1)),children:l(pe,{name:"ChevronRight","aria-hidden":!0,className:"size-4"})}),T?null:l(R,{variant:"outline",size:"sm",onClick:()=>N(e.today),children:"Back to today"})]}),w?m("div",{className:"flex items-start gap-3.5 rounded-2xl bg-surface-selected px-4 py-3.5",children:[l(De,{origin:"assistant",assistant:e.assistant,size:28}),l("p",{className:"text-base leading-relaxed",children:ro(ne,Es(o),T?"today":"day")})]}):null,T?l(Ns,{needs:o}):null,w?l($S,{entries:S,span:v,now:t,zone:e.zone,stretch:x,onStretch:b}):null,m("div",{className:"flex flex-wrap items-center gap-3",children:[l(_t,{label:"Show",value:c,onChange:d,options:[{value:"everything",label:"Everything"},{value:"changed",label:"What changed"},{value:"work",label:"Work"}]}),m("label",{className:"inline-flex items-center gap-2 text-xs text-muted-foreground",children:["Project",m("select",{value:h,onChange:se=>g(se.target.value),className:"h-8 cursor-pointer rounded-md border border-input bg-background px-2 text-xs font-medium text-foreground",children:[l("option",{value:"",children:"All projects"}),e.projects.map(se=>m("option",{value:se.key,children:[se.name," (",se.key,")"]},se.id))]})]}),m("label",{className:"inline-flex cursor-pointer items-center gap-2 text-xs font-medium text-muted-foreground",children:[l("input",{type:"checkbox",className:"size-4 accent-foreground",checked:p,onChange:se=>f(se.target.checked)}),"Fold quiet checks"]})]}),w?m("div",{className:"space-y-5",children:[$.length===0?l(Oe,{children:x?"Nothing happened in that stretch.":T?"Nothing has happened yet today.":"Nothing happened that day."}):m(he,{children:[l(RS,{entries:P,meta:e,now:t,onOpen:n}),l(TS,{groups:L,meta:e,now:t,onOpen:n,undo:r})]}),y?m("p",{className:"px-1 text-sm text-muted-foreground",children:[T?"Today":"That day"," has more than ",zn.toLocaleString()," entries, so the summary, the hours and this list cover the newest"," ",zn.toLocaleString(),"."]}):null]}):l(Oe,{children:C||"Loading\u2026"})]}),l("aside",{className:"hidden w-72 shrink-0 space-y-6 xl:block","aria-label":"The day at a glance",children:m("section",{className:"space-y-2",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:T?"Today so far":"That day"}),w?pr(ne).length?l("ul",{className:"space-y-1.5 text-sm",children:pr(ne).map(se=>l("li",{children:se},se))}):l("p",{className:"text-sm text-muted-foreground",children:"Nothing yet."}):null]})})]})}var nE={undo:{hint:"Changes to your moonlet undo while their settings still match; library filings undo newest first.",empty:"Nothing to undo yet."},work:{hint:"Each piece of work with its steps and result, and the notes left on tasks.",empty:"No work yet."},asks:{hint:"Every approval asked, what it would run and how it was decided. Standing permissions are in Settings \u2192 Permissions.",empty:"Nothing asked yet."},messages:{hint:"Messages between conversations and relays to other machines. Recipient controls are in Settings \u2192 Permissions.",empty:"No messages yet."},checks:{hint:"Scheduled checks, routines and reminders, with what each found.",empty:"No checks have run yet."}};function sO({view:e,meta:t,now:n,open:r,undo:o,signal:s,remember:i}){let[a,u]=_(1),[c]=_(()=>Date.now()+366*864e5),{data:d,error:p}=ks({from:0,to:c,kinds:pm[e],project:null},a,s);K(()=>{d&&i(d.entries)},[d,i]);let f=xs.find(h=>h.id===e).label;return m("div",{className:"mx-auto max-w-4xl space-y-6",children:[l(rn,{eyebrow:"Activity",title:f}),l("p",{className:"text-sm text-muted-foreground",children:nE[e].hint}),d?d.entries.length===0?l(Oe,{children:nE[e].empty}):m("div",{className:"space-y-5",children:[yu(d.entries,t.zone).map(({day:h,entries:g})=>m("section",{"aria-label":Ct(h),className:"space-y-2",children:[l("h2",{className:"px-1 text-xs font-semibold text-muted-foreground",children:h===t.today?"Today":Ct(h)}),l("ol",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:g.map((x,b)=>l(oo,{entry:x,meta:t,now:n,onOpen:r,undo:o,first:b===0},je(x)))})]},h)),d.more?m(R,{variant:"ghost",onClick:()=>u(h=>h+1),children:[l(pe,{name:"ChevronDown","aria-hidden":!0,className:"size-4"}),"Show older"]}):null]}):l(Oe,{children:p||"Loading\u2026"}),e==="undo"?l(tS,{}):null]})}function iO(){return m("div",{className:"mx-auto max-w-4xl space-y-6",children:[l(rn,{eyebrow:"Activity",title:"Needs you"}),l("p",{className:"text-sm text-muted-foreground",children:"Questions, approvals and changes waiting for your answer, and messages held until you say yes."}),l(pu,{}),l(Ci,{}),l(tE,{})]})}function aO({view:e,needs:t}){let n=yn();return l("nav",{"aria-label":"Activity views",className:"-mx-1 flex min-w-0 gap-1 overflow-x-auto px-1 md:hidden",children:xs.map(r=>m("button",{type:"button","aria-current":e===r.id?"page":void 0,"aria-label":r.id==="needs"&&t?`${r.short}, ${t}`:void 0,onClick:()=>n(r.id),className:V("inline-flex shrink-0 cursor-pointer items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-semibold",e===r.id?"bg-foreground text-background":"bg-muted text-muted-foreground"),children:[r.short,r.id==="needs"&&t?l("span",{className:"rounded-full bg-warning px-1.5 text-2xs text-background",children:t}):null]},r.id))})}function rE({subPath:e}){let t=fm(e),n=yn(),r=ds(),o=fs(),s=Nm(),i=Em(),a=i.data!==null&&i.data.from!==null&&o-i.data.from>144e5,u=t.landing&&i.data===null&&i.error==="",c=t.landing&&a?"since":t.view,d=Y(!1);K(()=>{!t.landing||i.data===null||d.current||(d.current=!0,a&&n("since"))},[t.landing,i.data,a,n]);let[p,f]=_(new Map),[h,g]=_(null),[x,b]=_(0),v=q(P=>f(L=>new Map([...L,...P.map(ne=>[je(ne),ne])])),[]),w=t.entry===null?null:p.get(t.entry)??null;SS(t.entry,v,x),K(()=>{w&&g(w)},[w]);let C=ES(()=>b(P=>P+1)),y={busy:C.busy,said:C.said,undo:P=>{C.undo(P)}},T=c==="timeline"||c==="week"?t.day:null,S={meta:r,now:o,open:P=>n(c,je(P),T),undo:y,signal:x,remember:v},$=!r||u?l(Oe,{children:"Loading\u2026"}):c==="timeline"?l(oO,{...S,meta:r,needs:s,day:t.day??r.today,onDay:P=>n("timeline",null,P===r.today?null:P)}):c==="week"?l(FS,{...S,meta:r,needs:s,initialDay:t.day},t.day??"this-week"):c==="since"?l(OS,{...S,meta:r,needs:s,since:i.data??{from:null,note:null}}):c==="behalf"?l(PS,{...S,meta:r}):c==="needs"?l(iO,{}):l(sO,{...S,meta:r,view:c},c);return m("main",{className:"h-full overflow-auto",children:[m("div",{className:"mx-auto flex max-w-7xl flex-col gap-6 p-4 sm:p-8",children:[l(aO,{view:c,needs:fr(s)}),$]}),r?l(eE,{entry:w??h,open:w!==null,meta:r,now:o,undo:y,onClose:()=>n(c,null,T)}):null]})}function oE({subPath:e}){let t=fm(e),n=yn(),r=Nm(),[o]=_(()=>Date.now()+366*864e5),s=ks({from:0,to:o,kinds:pm.undo,project:null},1,0).data?.entries.filter(p=>p.undo!==null).length??0,i={needs:fr(r),undo:s},a=Em().data,u=fs(),c=a?.from!=null?{since:Fn(u-a.from,"short")}:{},d=p=>m("button",{type:"button","aria-current":t.view===p.id?"page":void 0,"aria-label":i[p.id]?`${p.label}, ${i[p.id]}`:void 0,onClick:()=>n(p.id),className:V("flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm",t.view===p.id?"bg-muted font-semibold":"hover:bg-muted/60"),children:[l("span",{className:"min-w-0 flex-1 truncate",children:p.label}),i[p.id]?l("span",{className:V("rounded-full px-1.5 text-2xs font-bold",p.id==="needs"?"bg-warning/20 text-warning-text":"text-muted-foreground"),children:i[p.id]}):c[p.id]?l("span",{className:"text-2xs font-semibold text-muted-foreground",children:c[p.id]}):null]},p.id);return m("nav",{"aria-label":"Activity",className:"flex flex-col gap-0.5 p-2",children:[xs.filter(p=>dm.includes(p.id)).map(d),l("p",{className:"mt-4 px-2 pb-1 text-xs font-semibold text-muted-foreground",children:"Narrow to"}),xs.filter(p=>!dm.includes(p.id)).map(d),l("p",{className:"px-2 pt-3 text-xs leading-snug text-muted-foreground",children:"Every view is the same record, narrowed. After a few hours away, Activity opens on what happened since you looked."})]})}var ao="application/x-moonlet-artifacts";function sE(){try{return globalThis.sessionStorage??null}catch{return null}}var Xn={outcome:null,stack:X1(sE()),request:null,changed:null},Om=new Set,Kn=e=>{if(Xn={...Xn,...e},e.stack)try{sE()?.setItem(om,JSON.stringify(e.stack))}catch{}for(let t of Om)t()},Lm=e=>(Om.add(e),()=>Om.delete(e));function iE(){let e=xt(Lm,()=>Xn);return[e.outcome,e.stack.length>0,()=>Kn({outcome:null})]}function aE(){return xt(Lm,()=>Xn.changed)}function Mm(e){Kn({request:e})}function lE(){return[xt(Lm,()=>Xn.request),()=>Kn({request:null})]}function zu(e){try{let t=JSON.parse(e.getData(ao)||"[]");return Array.isArray(t)?t.filter(n=>typeof n=="string").slice(0,Qk):[]}catch{return[]}}function Ra(e){let t=J(),n=q(async o=>{try{let s=await t.call("artifacts.change",{action:o});return s.state==="refused"?(Kn({outcome:{kind:"refused",reason:s.reason}}),!1):(s.change&&Kn({outcome:{kind:"done",summary:s.change.summary},stack:[...Xn.stack,s.change].slice(-rm),changed:{action:o,moved:s.change.moved,n:(Xn.changed?.n??0)+1}}),e(),!0)}catch(s){return Kn({outcome:{kind:"refused",reason:s instanceof Error?s.message:String(s)}}),!1}},[t,e]),r=q(async()=>{let o=Xn.stack.at(-1);if(o)try{let s=await t.call("artifacts.undo",{id:o.id});s.state==="ok"?Kn({outcome:{kind:"undone",summary:s.summary},stack:Xn.stack.slice(0,-1)}):Kn({outcome:{kind:"refused",reason:s.reason},stack:[]}),e()}catch(s){Kn({outcome:{kind:"refused",reason:s instanceof Error?s.message:String(s)}})}},[t,e]);return{run:n,undo:r}}var cE=176;function As({request:e,onClose:t}){let n=so(),r=e!==null,[o,s]=_(e);K(()=>{e&&s(e)},[e]);let{isContentRealized:i}=Lu({open:r,enabled:n});K(()=>{if(!r||n)return;let c=p=>{if(p instanceof KeyboardEvent){if(p.key!=="Escape")return;p.preventDefault(),p.stopPropagation()}t()},d=setTimeout(()=>{window.addEventListener("pointerdown",c),window.addEventListener("keydown",c,!0),window.addEventListener("scroll",c,!0)});return()=>{clearTimeout(d),window.removeEventListener("pointerdown",c),window.removeEventListener("keydown",c,!0),window.removeEventListener("scroll",c,!0)}},[r,n,t]);let a=(o?.entries??[]).filter(c=>c!==null),u=c=>{t(),c.run()};return n?l(Mu,{open:r,onOpenChange:c=>c?void 0:t(),srLabel:o?.title??"Actions",children:i?m("div",{className:"flex min-h-0 flex-col pb-4",children:[l("p",{className:"px-4 pt-1 pb-2 text-sm font-medium text-muted-foreground",children:o?.title}),l("div",{role:"menu","aria-label":o?.title,className:"flex max-h-[70dvh] flex-col overflow-y-auto overscroll-contain",children:a.map((c,d)=>l("button",{type:"button",role:"menuitem",disabled:c.disabled,className:"px-4 py-3 text-left text-base hover:bg-muted disabled:opacity-40",onClick:()=>u(c),children:c.label},`${d}-${c.label}`))})]}):null}):e?l("div",{role:"menu","aria-label":e.title,className:"fixed z-50 flex flex-col rounded-md border bg-background py-1 text-sm shadow-md",style:{width:cE,left:Math.max(8,Math.min(e.x,window.innerWidth-cE-8)),top:Math.max(8,Math.min(e.y,window.innerHeight-32*a.length-16))},onPointerDown:c=>c.stopPropagation(),children:a.map((c,d)=>l("button",{type:"button",role:"menuitem",disabled:c.disabled,className:"px-3 py-1.5 text-left hover:bg-muted disabled:opacity-40",onClick:()=>u(c),children:c.label},`${d}-${c.label}`))}):null}function Cs({label:e,query:t,keyName:n,choices:r,onQuery:o,onMenu:s}){let i=Yk(t,n)??"",a=r.some(d=>d.value.toLowerCase()===i.toLowerCase()),u=so(),c=`h-8 max-w-44 rounded-md border px-2 text-sm ${i?"border-foreground/40 bg-muted font-medium":"bg-background text-muted-foreground"}`;if(u){let d=r.find(p=>p.value.toLowerCase()===i.toLowerCase());return l("button",{type:"button","aria-label":e,"aria-haspopup":"menu",className:`${c} truncate text-left`,onClick:p=>{let f=p.currentTarget.getBoundingClientRect();s({title:e,x:f.left,y:f.bottom+4,entries:[i?{label:`Any ${e.toLowerCase()}`,run:()=>o(va(t,n,null))}:null,...r.map(h=>({label:h===d?`\u2713 ${h.label}`:h.label,run:()=>o(va(t,n,h.value))}))]})},children:d?.label??(i||e)})}return m("select",{"aria-label":e,className:c,value:a?r.find(d=>d.value.toLowerCase()===i.toLowerCase()).value:i,onChange:d=>o(va(t,n,d.target.value||null)),children:[l("option",{value:"",children:e}),!a&&i?l("option",{value:i,children:i}):null,r.map(d=>l("option",{value:d.value,children:d.label},d.value))]})}function uE({query:e,onQuery:t,meta:n,inFolder:r,canSave:o,problems:s,inputRef:i,onSave:a}){let[u,c]=_(null),[d,p]=_(null),f=q(()=>p(null),[]),[h,g]=_(!1),x=S=>{if(S.length>ya)return g(!0);g(!1),t(S)},[b,v]=_(""),w=Gc(e),C=w.subfolders,y=_a(w),T=async()=>{if(u===null)return;let S=await a(u);S?v(S):(c(null),v(""))},N=m(he,{children:[l(Cs,{onMenu:p,label:"Kind",keyName:"kind",query:e,onQuery:x,choices:[{value:"page",label:"Page"},{value:"md",label:"Markdown"}]}),l(Cs,{onMenu:p,label:"Project",keyName:"project",query:e,onQuery:x,choices:(n?.projects??[]).map(S=>({value:S.id,label:S.name}))}),l(Cs,{onMenu:p,label:"Conversation",keyName:"conversation",query:e,onQuery:x,choices:(n?.conversations??[]).map(S=>({value:S.threadId,label:S.title??S.threadId}))}),l(Cs,{onMenu:p,label:"Tag",keyName:"tag",query:e,onQuery:x,choices:(n?.tags??[]).map(S=>({value:S.tag,label:`#${S.tag}`}))}),l(Cs,{onMenu:p,label:"Modified",keyName:"modified",query:e,onQuery:x,choices:[{value:"today",label:"Today"},{value:"<7d",label:"Last 7 days"},{value:"<30d",label:"Last 30 days"},{value:">90d",label:"Older than 90 days"}]}),l(Cs,{onMenu:p,label:"Written by",keyName:"by",query:e,onQuery:x,choices:[{value:"you",label:"You"},{value:"assistant",label:"The assistant"}]}),r?m("label",{className:"flex h-8 items-center gap-1.5 px-1 text-sm text-muted-foreground",children:[l("input",{type:"checkbox",checked:C||y,disabled:y,title:y?"A filter looks in every folder below this one":void 0,onChange:S=>x(va(e,"subfolders",S.target.checked?"yes":null))}),"Subfolders"]}):null]});return m("div",{className:"flex flex-col gap-1.5 border-b px-3 py-2",children:[l(As,{request:d,onClose:f}),m("div",{className:"flex flex-wrap items-center gap-1.5",children:[l(le,{ref:i,"aria-label":"Filter this list",className:"h-8 min-w-48 flex-1",placeholder:"Filter: words, tag:triage, kind:md, modified:<7d",value:e,maxLength:ya,onChange:S=>x(S.target.value),onKeyDown:S=>{S.key==="Escape"&&e&&(S.preventDefault(),S.stopPropagation(),x(""))}}),o&&u===null?l(R,{size:"sm",variant:"secondary",disabled:!e.trim(),onClick:()=>c(""),children:"Save"}):null]}),l("div",{className:"flex flex-wrap items-center gap-1.5",children:N}),u!==null?m("form",{className:"flex flex-wrap items-center gap-1.5",onSubmit:S=>{S.preventDefault(),T()},children:[l(le,{autoFocus:!0,"aria-label":"Name for this filter",className:"h-8 max-w-64",placeholder:"Name, such as Open security",value:u,maxLength:60,onChange:S=>c(S.target.value),onKeyDown:S=>{S.key==="Escape"&&(S.preventDefault(),S.stopPropagation(),c(null),v(""))}}),l(R,{size:"sm",type:"submit",disabled:!u.trim(),children:"Save filter"}),l(R,{size:"sm",variant:"secondary",type:"button",onClick:()=>(c(null),v("")),children:"Cancel"}),b?l("span",{className:"text-xs text-destructive",children:b}):null]}):null,h?m("p",{className:"text-xs text-destructive",children:["A filter is at most ",ya," characters; that change would make it longer."]}):null,s.length?l("p",{className:"text-xs text-destructive",children:s.join(" \xB7 ")}):null]})}var dE="\0new",pE=e=>e===""?"the library":e===Ze?"the Inbox":e,fE=e=>e.length===1?Pe(e[0]):`${e.length} items`;function Ku({children:e}){return l("div",{className:"flex flex-wrap items-center gap-1.5 border-b px-3 py-2 text-sm",children:e})}function hE({panel:e,folders:t,onRun:n,onClose:r}){let[o,s]=_(e.kind==="rename"?Pe(e.path):""),[i,a]=_(""),[u,c]=_("");K(()=>s(e.kind==="rename"?Pe(e.path):""),[e]);let d=async g=>{await n(g)&&r()},p=g=>{g.key==="Escape"&&(g.preventDefault(),g.stopPropagation(),r())},f=l(R,{size:"sm",variant:"secondary",type:"button",onClick:r,children:"Cancel"});if(e.kind==="move"){let g=["",Ze,...t].filter(v=>!e.items.some(w=>v===w||v.startsWith(`${w}/`))),x=i===dE,b=u.trim().toLowerCase().replace(/^\/+|\/+$/g,"");return l("form",{className:"contents",onSubmit:v=>{v.preventDefault(),x?b&&d({kind:"move",items:e.items,to:b,make:!0}):d({kind:"move",items:e.items,to:i,make:!1})},children:m(Ku,{children:[m("span",{children:["Move ",fE(e.items)," to"]}),m("select",{"aria-label":"Move to",autoFocus:!0,className:"h-8 max-w-64 rounded-md border bg-background px-2 text-sm",value:i,onChange:v=>a(v.target.value),onKeyDown:p,children:[g.map(v=>l("option",{value:v,children:pE(v)},v||"(library)")),l("option",{value:dE,children:"A new folder\u2026"})]}),x?l(le,{autoFocus:!0,"aria-label":"New folder",className:"h-8 max-w-64",placeholder:"Name, such as plans or work/screens",value:u,maxLength:240,onChange:v=>c(v.target.value),onKeyDown:p}):null,l(R,{size:"sm",type:"submit",disabled:x&&!b,children:"Move"}),f,x?l("span",{className:"text-xs text-muted-foreground",children:"Lower-case letters, digits, . _ -"}):null]})})}if(e.kind==="tag")return l("form",{className:"contents",onSubmit:g=>{g.preventDefault();let x=o.split(",").map(b=>b.trim()).filter(Boolean);x.length&&d({kind:"tag",items:e.items,tags:x})},children:m(Ku,{children:[m("span",{children:["Tag ",fE(e.items)]}),l(le,{autoFocus:!0,"aria-label":"Tags to add",className:"h-8 max-w-64",placeholder:"Tags, such as trip, plan",value:o,onChange:g=>s(g.target.value),onKeyDown:p}),l(R,{size:"sm",type:"submit",disabled:!o.trim(),children:"Add"}),f,e.tags.length?l("span",{className:"text-xs text-muted-foreground",children:"Take off:"}):null,e.tags.map(g=>m("button",{type:"button","aria-label":`Take #${g} off`,className:"rounded border px-1.5 text-xs hover:bg-muted",onClick:()=>{d({kind:"untag",items:e.items,tags:[g]})},children:["#",g," \xD7"]},g))]})});let h=e.kind==="rename";return l("form",{className:"contents",onSubmit:g=>{g.preventDefault();let x=o.trim();x&&(e.kind==="rename"?d({kind:"rename",path:e.path,name:x}):d({kind:"mkdir",path:e.parent?`${e.parent}/${x.toLowerCase()}`:x.toLowerCase()}))},children:m(Ku,{children:[l("span",{children:h?`Rename ${Pe(e.path)} to`:`New folder in ${pE(e.kind==="mkdir"?e.parent:"")}`}),l(le,{autoFocus:!0,"aria-label":h?"New name":"Folder name",className:"h-8 max-w-64",placeholder:h?"":"Name, such as plans",value:o,maxLength:64,onFocus:g=>g.currentTarget.select(),onChange:g=>s(g.target.value),onKeyDown:p}),l(R,{size:"sm",type:"submit",disabled:!o.trim(),children:h?"Rename":"Make folder"}),f,l("span",{className:"text-xs text-muted-foreground",children:"Lower-case letters, digits, . _ -"})]})})}function mE({count:e,total:t,onAll:n,allStarred:r,onMove:o,onTag:s,onStar:i,onDelete:a,onClear:u}){return m(Ku,{children:[m("span",{className:"font-medium",children:[e," selected"]}),n?m(R,{size:"sm",variant:"secondary",onClick:n,children:["Select all ",t]}):null,l(R,{size:"sm",variant:"secondary",onClick:o,children:"Move to\u2026"}),s?l(R,{size:"sm",variant:"secondary",onClick:s,children:"Tag\u2026"}):null,i?l(R,{size:"sm",variant:"secondary",onClick:i,children:r?"Unstar":"Star"}):null,l(R,{size:"sm",variant:"secondary",onClick:a,children:"Delete"}),l(R,{size:"sm",variant:"secondary",onClick:u,children:"Clear"})]})}function gE({onUndo:e}){let[t,n,r]=iE();return t?m("div",{role:"status",className:`flex items-center gap-2 border-b px-3 py-1.5 text-sm ${t.kind==="refused"?"text-destructive":""}`,children:[l("span",{className:"min-w-0 flex-1 truncate",children:t.kind==="done"?t.summary:t.kind==="undone"?`Undone: ${t.summary}`:`That didn't happen: ${t.reason}`}),n&&t.kind!=="refused"?l(R,{size:"sm",variant:"secondary",onClick:e,children:t.kind==="undone"?"Undo the one before":"Undo"}):null,l("button",{type:"button","aria-label":"Dismiss",className:"px-1 text-muted-foreground hover:text-foreground",onClick:r,children:"\xD7"})]}):null}var xE="orbit.artifacts.open-folders",bE=0,Dm=new Set;function hr(){bE++;for(let e of Dm)e()}function Fm(){return xt(e=>(Dm.add(e),()=>Dm.delete(e)),()=>bE)}function lO(){try{let e=Mn()?.getItem(xE),t=e?JSON.parse(e):[];return new Set(Array.isArray(t)?t.filter(n=>typeof n=="string"):[])}catch{return new Set}}function zm(){let e=Ie();return t=>e.toPluginPanel(cu,{subPath:is(t)})}function cO(e){let{run:t}=Ra(hr),[n,r]=_(!1);return e===void 0?{over:!1,props:{}}:{over:n,props:{onDragOver:o=>{o.dataTransfer.types.includes(ao)&&(o.preventDefault(),o.dataTransfer.dropEffect="move",r(!0))},onDragLeave:()=>r(!1),onDrop:o=>{o.preventDefault(),r(!1);let s=zu(o.dataTransfer).filter(i=>i!==e);s.length&&t({kind:"move",items:s,to:e,make:!1})}}}}function Bn({active:e,label:t,count:n,depth:r=0,onClick:o,toggle:s,drop:i,onDoubleClick:a,onMenu:u,after:c}){let d=cO(i);return m("div",{className:`group relative flex items-center gap-1 rounded px-2 py-1 text-sm ${e?"bg-muted font-medium":"hover:bg-muted/60"} ${d.over?"outline outline-1 outline-ring":""}`,style:{paddingLeft:`${8+r*14}px`},onContextMenu:u?p=>{p.preventDefault(),u(p.clientX,p.clientY)}:void 0,...d.props,children:[s??l("span",{className:"w-4 shrink-0"}),l("button",{type:"button","aria-current":e?"page":void 0,className:"min-w-0 flex-1 truncate text-left",onClick:o,onDoubleClick:a,children:t}),n!==void 0&&n>0?l("span",{className:`shrink-0 text-xs text-muted-foreground ${u?"group-hover:hidden [@media(hover:none)]:hidden":""}`,children:n}):null,u?l("button",{type:"button","aria-label":`More for ${typeof t=="string"?t:"this folder"}`,"aria-haspopup":"menu",className:"hidden shrink-0 rounded px-1 text-muted-foreground hover:text-foreground focus:inline group-hover:inline [@media(hover:none)]:inline",onClick:p=>{let f=p.currentTarget.getBoundingClientRect();u(f.right-176,f.bottom+4)},children:"\u2026"}):null,c]})}function uO({path:e,count:t,depth:n,active:r,toggle:o,onOpen:s,onMenu:i}){let{run:a}=Ra(hr),[u,c]=_(null),d=(p,f)=>i({title:Pe(e),x:p,y:f,entries:[{label:"New folder inside",run:()=>c({kind:"mkdir",text:""})},{label:"Rename",run:()=>c({kind:"rename",text:Pe(e)})},{label:"Move to\u2026",run:()=>Mm({kind:"move",items:[e]})},{label:"Filter inside",run:()=>(s(),Mm({kind:"focus-filter"}))},{label:"Delete folder",run:()=>{a({kind:"delete",items:[e]})}}]});return u?m(he,{children:[u.kind==="mkdir"?l(Bn,{active:r,label:Pe(e),count:t,depth:n,toggle:o,onClick:s}):null,l("form",{className:"py-0.5 pr-2",style:{paddingLeft:`${8+(n+(u.kind==="mkdir"?1:0))*14+20}px`},onSubmit:p=>{p.preventDefault();let f=u.text.trim();c(null),f&&(u.kind==="rename"?f!==Pe(e)&&a({kind:"rename",path:e,name:f}):a({kind:"mkdir",path:`${e}/${f.toLowerCase()}`}))},children:l(le,{autoFocus:!0,"aria-label":u.kind==="rename"?`New name for ${Pe(e)}`:`New folder in ${Pe(e)}`,className:"h-7",placeholder:u.kind==="mkdir"?"New folder's name":"",maxLength:64,value:u.text,onFocus:p=>p.currentTarget.select(),onChange:p=>c({...u,text:p.target.value}),onBlur:p=>p.currentTarget.form?.requestSubmit(),onKeyDown:p=>{p.key==="Escape"&&(p.preventDefault(),p.stopPropagation(),c(null))}})})]}):l(Bn,{active:r,label:Pe(e),count:t,depth:n,toggle:o,drop:e,onClick:s,onDoubleClick:()=>c({kind:"rename",text:Pe(e)}),onMenu:d})}function Xu({children:e}){return l("p",{className:"mt-3 px-2 pb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground",children:e})}function dO({row:e,index:t,count:n,active:r,onOpen:o,onChanged:s,onDeleted:i,onMenu:a}){let u=J(),[c,d]=_(null),[p,f]=_(""),h=async x=>{let b=await x.catch(v=>({state:"refused",reason:v instanceof Error?v.message:String(v)}));b.state==="ok"?(f(""),s()):f(b.reason)},g=(x,b)=>a({title:e.name,x,y:b,entries:[{label:"Rename",run:()=>d(e.name)},{label:"Move up",disabled:t===0,run:()=>{h(u.call("artifacts.saved.move",{id:e.id,to:t-1}))}},{label:"Move down",disabled:t===n-1,run:()=>{h(u.call("artifacts.saved.move",{id:e.id,to:t+1}))}},{label:"Delete",run:()=>{h(u.call("artifacts.saved.delete",{id:e.id})).then(i)}}]});return c!==null?l("form",{className:"px-2 py-0.5",onSubmit:x=>{x.preventDefault(),c.trim()&&c.trim()!==e.name&&h(u.call("artifacts.saved.rename",{id:e.id,name:c})),d(null)},children:l(le,{autoFocus:!0,"aria-label":`New name for ${e.name}`,className:"h-7",onFocus:x=>x.currentTarget.select(),value:c,maxLength:60,onChange:x=>d(x.target.value),onBlur:x=>x.currentTarget.form?.requestSubmit(),onKeyDown:x=>{x.key==="Escape"&&(x.preventDefault(),x.stopPropagation(),d(null))}})}):m("div",{className:`group relative flex items-center gap-1 rounded px-2 py-1 text-sm ${r?"bg-muted font-medium":"hover:bg-muted/60"}`,onContextMenu:x=>{x.preventDefault(),g(x.clientX,x.clientY)},children:[l("span",{className:"w-4 shrink-0"}),l("button",{type:"button","aria-current":r?"page":void 0,className:"min-w-0 flex-1 truncate text-left",onClick:o,onDoubleClick:()=>d(e.name),children:e.name}),l("button",{type:"button","aria-label":`More for ${e.name}`,"aria-haspopup":"menu",className:"shrink-0 rounded px-1 text-muted-foreground opacity-0 hover:text-foreground focus:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100",onClick:x=>{let b=x.currentTarget.getBoundingClientRect();g(b.right-176,b.bottom+4)},children:"\u2026"}),p?l("span",{className:"absolute left-6 top-full z-10 text-xs text-destructive",children:p}):null]})}function yE({subPath:e}){let t=J(),n=zm(),r=as(e),o=Fm(),[s,i]=_(null),[a,u]=_(""),[c,d]=_(null),p=q(()=>d(null),[]),[f,h]=_(r.kind==="search"?r.q:""),[g,x]=_(lO);K(()=>{let $=!0;return t.call("artifacts.folders",{}).then(P=>{$&&(i(P),u(""))},P=>$&&u(P instanceof Error?P.message:String(P))),()=>{$=!1}},[t,o]);let b=r.kind==="place"&&r.place.kind==="folder"?r.place.path:null,v=new Set([...g,...b?ka(b):[]]),w=$=>{let P=new Set(g);P.has($)?P.delete($):P.add($),x(P);try{Mn()?.setItem(xE,JSON.stringify([...P]))}catch{}},C=s?.folders??[],y=$=>C.some(P=>Ut(P.path)===$),T=C.filter($=>ka(Ut($.path)).every(P=>v.has(P))),N=$=>S1(r,$),S=$=>r.kind==="group"&&r.by===$||r.kind==="place"&&r.place.kind===$;return K(()=>h(r.kind==="search"?r.q:""),[e]),m("nav",{"aria-label":"Artifacts",className:"flex flex-col gap-0.5 px-2 pb-4",children:[l("form",{className:"pb-2",onSubmit:$=>{$.preventDefault(),f.trim()&&n({kind:"search",q:f.trim()})},children:l(le,{"aria-label":"Search all artifacts",className:"h-8",placeholder:"Search all",value:f,onChange:$=>h($.target.value)})}),a?m("p",{className:"px-2 text-xs text-destructive",children:["Couldn't load the folders: ",a]}):null,l(Bn,{active:N(Bt(Ze)),label:"Inbox",count:s?.inbox,drop:Ze,onClick:()=>n(Bt(Ze))}),l(Bn,{active:N({kind:"place",place:{kind:"recent"}}),label:"Recent",onClick:()=>n({kind:"place",place:{kind:"recent"}})}),l(Bn,{active:N({kind:"place",place:{kind:"starred"}}),label:"Starred",count:s?.starred,onClick:()=>n({kind:"place",place:{kind:"starred"}})}),l(Xu,{children:"Library"}),l(Bn,{active:N(Bt("")),label:"All folders",drop:"",onClick:()=>n(Bt(""))}),T.map($=>{let P=$.path.split("/").length,L=y($.path)?l("button",{type:"button","aria-label":v.has($.path)?`Close ${Pe($.path)}`:`Open ${Pe($.path)}`,"aria-expanded":v.has($.path),className:"w-4 shrink-0 text-xs text-muted-foreground",onClick:()=>w($.path),children:v.has($.path)?"\u25BE":"\u25B8"}):void 0;return l(uO,{path:$.path,active:b===$.path,count:$.pages,depth:P,toggle:L,onOpen:()=>n(Bt($.path)),onMenu:d},$.path)}),s&&!C.length?l("p",{className:"px-2 py-1 text-xs text-muted-foreground",children:"No folders yet."}):null,s?.saved.length?m(he,{children:[l(Xu,{children:"Saved"}),s.saved.map(($,P)=>l(dO,{row:$,index:P,count:s.saved.length,active:r.kind==="saved"&&r.id===$.id,onOpen:()=>n({kind:"saved",id:$.id}),onChanged:hr,onDeleted:()=>r.kind==="saved"&&r.id===$.id&&n(Bt("")),onMenu:d},$.id))]}):null,l(Xu,{children:"Views"}),l(Bn,{active:S("project"),label:"By project",onClick:()=>n({kind:"group",by:"project"})}),l(Bn,{active:S("conversation"),label:"By conversation",onClick:()=>n({kind:"group",by:"conversation"})}),s?.tags.length?m(he,{children:[l(Xu,{children:"Tags"}),s.tags.map($=>l(Bn,{active:N({kind:"place",place:{kind:"tag",tag:$.tag}}),label:`#${$.tag}`,count:$.pages,onClick:()=>n({kind:"place",place:{kind:"tag",tag:$.tag}})},$.tag))]}):null,l(As,{request:c,onClose:p})]})}var _E=1e3,pO=250;function vE(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch{return"UTC"}}function fO(){try{return globalThis.matchMedia?.("(hover: none)").matches===!0}catch{return!1}}var hO=[{by:"name",label:"Name"},{by:"modified",label:"Modified"},{by:null,label:"Project",wide:!0},{by:"conversation",label:"Conversation",wide:!0},{by:null,label:"Tags",wide:!0},{by:"versions",label:"Versions",wide:!0},{by:"size",label:"Size",wide:!0}],wE=(e,t)=>`${e} ${t}${e===1?"":"s"}`,mO=e=>[e.folders.length?wE(e.folders.length,"folder"):"",e.pages.length||!e.folders.length?`${wE(e.pages.length,"page")}${e.more?"+":""}`:""].filter(Boolean).join(" \xB7 "),gO=e=>e<1024?`${e} B`:`${Math.round(e/1024)} KB`;function xO(){let e=Y(null),[t,n]=_("wide");return ot(()=>{let r=e.current;if(!r)return;let o=()=>n(C1(r.getBoundingClientRect().width));o();let s=new ResizeObserver(o);return s.observe(r),()=>s.disconnect()},[]),[e,t]}function CE(e){return l(R,{size:"sm",variant:"secondary",onClick:hr,children:"Refresh"})}function TE({subPath:e}){let t=J(),n=J(),r=Ie(),o=zm(),s=as(e),i=e,a=Fm();ke("artifacts",hr);let[u,c]=xO(),[d,p]=_(()=>nm(Mn(),s)),[f,h]=_(null),[g,x]=_(null),[b,v]=_(""),[w,C]=_(""),[y,T]=_(null),[N,S]=_(!0),[$,P]=_(!1),[L,ne]=_(null),[se,_e]=_([]),[ie,Q]=_(null),[j,G]=_(null),[ee,be]=_(""),[H,xe]=_(new Set),[Cr,Cn]=_(null),[ue,ze]=_(null),zt=q(()=>ze(null),[]),[mt,gt]=_(null),[vi,To]=_(null),[S_,E_]=_(null),[Ro,nf]=_(()=>D1(Mn())),[wi,rf]=_(new Map),ki=Y(Ro);ki.current=Ro;let{run:Qn,undo:N_}=Ra(hr),[Ll,A_]=lE(),jt=aE(),C_=Y(jt?.n??0);K(()=>{if(!jt||jt.n===C_.current||(C_.current=jt.n,nf(O=>z1(O,jt.action,jt.moved)),rf(O=>M1(O,jt.action,jt.moved)),s.kind!=="place"||s.place.kind!=="folder"))return;let k=uu(jt.action,jt.moved,s.place.path);k!==null&&k!==s.place.path&&o(Bt(k))},[jt]),K(()=>F1(Mn(),Ro),[Ro]),K(()=>{if(!g)return;let k=new Set(g.folders.map(O=>O.path));nf(O=>[...O].every(Z=>k.has(Z))?O:new Set([...O].filter(Z=>k.has(Z))))},[g]),K(()=>{if(f?.state!=="refused"||!g||s.kind!=="place"||s.place.kind!=="folder")return;let k=s.place.path,O=new Set(g.folders.map(Z=>Z.path));k===""||k===Ze||O.has(k)||o(Bt(ka(Ut(k)).filter(Z=>O.has(Z)).at(-1)??""))},[f,g]);let[LT,of]=_(null),Tr=Y(null);K(()=>()=>{Tr.current&&clearTimeout(Tr.current)},[]);let Ml=Y(null),Dl=Y(null),Fl=k=>be(k instanceof Error?k.message:String(k)),MT=k=>{p(k),N1(Mn(),k)},zl=s.kind==="saved"?g?.saved.find(k=>k.id===s.id)??null:null,Qt=s.kind==="saved"?zl?tm(zl.place):null:s,Si=Qt?is(Qt):null,sf=zl?.query??"";K(()=>{T(null),xe(new Set),Cn(null),gt(null),ze(null),ne(null),P(!1),_e([]),p(nm(Mn(),as(i)))},[i]),K(()=>{Ll&&(Ll.kind==="move"?(gt({kind:"move",items:Ll.items}),A_()):Dl.current&&(Dl.current.focus(),A_()))},[Ll,i,f===null]),K(()=>of(null),[i]),K(()=>{v(sf),C(sf)},[i,sf]),K(()=>{if(b===w)return;let k=setTimeout(()=>C(b),250);return()=>clearTimeout(k)},[b,w]),K(()=>{t.call("artifacts.folders",{}).then(x,Fl)},[t,a]),K(()=>{let k=!0;h(null),be("");let O=Si===null?null:tm(Si),Z=ae=>k&&h(ae);if(!O){s.kind==="saved"&&g&&Z({state:"refused",reason:"That saved filter is gone."});return}return O.kind==="group"?t.call("artifacts.group",{by:O.by}).then(ae=>Z({state:"groups",by:O.by,groups:ae.groups}),Fl):O.kind==="search"?t.call("artifacts.search",{q:O.q,versions:!0}).then(ae=>Z({state:"search",results:ae.results}),Fl):O.kind==="place"&&t.call("artifacts.library",{place:O.place,sort:d,limit:_E,query:w,zone:vE()}).then(Z,Fl),()=>{k=!1}},[t,Si,d,a,w,g===null]);let af=Y({key:"",listed:!1});K(()=>{if(!L||!f||f.state!=="ok"&&f.state!=="search")return;let k=`${L.threadId}\0${L.name}`,O=f.state==="ok"?pf().find(ae=>ae.threadId===L.threadId&&ae.name===L.name)?.path:f.results.filter(ae=>ae.threadId===L.threadId&&ae.name===L.name).map(ae=>ae.kind==="moved"?ae.to:ae.path)[0],Z=af.current.key===k&&af.current.listed;O===void 0&&Z&&hf.length>0||(af.current={key:k,listed:O!==void 0},O!==void 0?O!==L.path&&(ne({...L,path:O}),T(ae=>ae===null||ae===L.path?O:ae)):Z&&(P(!1),ne(null)))},[f,L,wi]);let lf=Y(0),$o=q(k=>{let O=++lf.current;ne(k),Q(null),G(null),n.call("artifacts.read",{threadId:k.threadId,name:k.name}).then(Z=>{if(O!==lf.current||(Q(nu(Z)),G(Z.state==="ok"?ou(Z.page):null),Z.state!=="ok"))return;t.call("artifacts.seen",{threadId:k.threadId,name:k.name}).catch(()=>{});let ae=we=>we.map(Kt=>Kt.threadId===k.threadId&&Kt.name===k.name?{...Kt,unread:!1}:Kt);h(we=>we?.state==="ok"?{...we,pages:ae(we.pages)}:we),rf(we=>new Map([...we].map(([Kt,qn])=>[Kt,qn.branch.state==="ok"?{...qn,branch:{...qn.branch,pages:ae(qn.branch.pages)}}:qn])))},Z=>O===lf.current&&Q(ss(Z)))},[n,t]),T_=Y(a);K(()=>{T_.current!==a&&(T_.current=a,L&&$o(L))},[a]);let cf=k=>k?g?.projects.find(O=>O.id===k)?.name??k:"\u2014",uf=Gc(w),DT=uf.subfolders||_a(uf),df=f?.state==="ok"?I1(f,k=>wi.get(k)?.branch,Ro):[],Ve=f?.state==="ok"?P1(df):f?.state==="search"?f.results.map(k=>({kind:"page",path:k.kind==="moved"?k.to:k.path,threadId:k.threadId,name:k.name})):f?.state==="groups"?f.groups.map(k=>({kind:"folder",path:k.key})):[],Rr=`${a}:${d.by}:${d.desc?"desc":"asc"}`,R_=Y(Rr);R_.current=Rr;let pf=()=>f?.state==="ok"?L1(f.pages,wi.values(),Rr):f?.state==="search"?[...new Map(f.results.map(k=>[k.page.path,k.page])).values()]:[],$_=k=>pf().find(O=>O.path===k);K(()=>{if(!f)return;let k=new Set(f.state==="ok"||f.state==="search"?Ve.map(O=>O.path):[]);xe(O=>O.size&&[...O].some(Z=>!k.has(Z))?new Set([...O].filter(Z=>k.has(Z))):O),T(O=>O!==null&&!k.has(O)?null:O),Cn(O=>O!==null&&!k.has(O)?null:O)},[f,Ve.map(k=>k.path).join(`
143
- `)]);let ff=f?.state==="ok"&&L?.path&&!f.pages.some(k=>k.path===L.path)?Ut(L.path):null,hf=[...new Set([...df.flatMap(k=>k.kind==="folder"&&k.open?[k.folder.path]:[]),...ff!==null&&wi.has(ff)?[ff]:[]])].filter(k=>wi.get(k)?.gen!==Rr),mf=Y(new Set),FT=Y(0);K(()=>{for(let k of hf){let O=`${Rr}\0${k}`;if(mf.current.has(O))continue;mf.current.add(O);let Z=++FT.current,ae=we=>rf(Kt=>{let qn={n:Z,gen:Rr,branch:we};return O1(qn,Kt.get(k),R_.current)?new Map(Kt).set(k,qn):Kt});t.call("artifacts.library",{place:{kind:"folder",path:k},sort:d,limit:_E,query:"",zone:vE()}).then(we=>ae(we.state==="ok"?{state:"ok",folders:we.folders,pages:we.pages,more:we.more}:we),we=>ae({state:"refused",reason:we instanceof Error?we.message:String(we)})).finally(()=>mf.current.delete(O))}},[t,Rr,hf.join(`
144
- `)]);let gf=(k,O)=>{if(ki.current.has(k)===O)return;let Z=new Set(ki.current);if(O?Z.add(k):Z.delete(k),ki.current=Z,nf(Z),O)return;let ae=we=>we.startsWith(`${k}/`);T(we=>we!==null&&ae(we)?k:we),Cn(we=>we!==null&&ae(we)?k:we),xe(we=>[...we].some(ae)?new Set([...we].filter(Kt=>!ae(Kt))):we)},I_=k=>gf(k,!ki.current.has(k)),lt=f?.state==="ok"||f?.state==="search",Kl=Qt?.kind==="place"&&Qt.place.kind==="folder"?Qt.place.path:null,P_=Kl===Ze?null:Kl,O_=()=>{xe(new Set),T(null),Cn(null)},Gn=()=>H.size?[...H]:y&&lt?[y]:[],Xl=k=>pf().filter(O=>k.includes(O.path)),L_=k=>{let O=Xl(k);return O.length>0&&O.every(Z=>Z.starred)},xf=k=>f?.state==="ok"&&Ve.some(O=>O.kind==="folder"&&O.path===k),bf=(k,O)=>{xe(K1(Ve,H,Cr,k,O)),Cn(k)},yf=Ve.length>0&&Ve.every(k=>H.has(k.path)),M_=()=>xe(yf?new Set:new Set(Ve.map(k=>k.path))),zT=(k,O)=>{if(!lt)return Io(k);if(H.size&&!O.metaKey&&!O.ctrlKey&&fO())return bf(k.path,O.shiftKey);if(O.metaKey||O.ctrlKey){let Z=new Set(H.size?H:y?[y]:[]),ae=Z.has(k.path);ae?Z.delete(k.path):Z.add(k.path),xe(Z),Cn(k.path),T(ae?[...Z].at(-1)??null:k.path);return}if(O.shiftKey&&Cr){let Z=Ve.findIndex(we=>we.path===Cr),ae=Ve.findIndex(we=>we.path===k.path);if(Z>=0&&ae>=0){xe(new Set(Ve.slice(Math.min(Z,ae),Math.max(Z,ae)+1).map(we=>we.path))),T(k.path);return}}if(xe(new Set),Cn(k.path),k.kind==="folder"&&f?.state==="ok"){if(Tr.current&&clearTimeout(Tr.current),Tr.current=null,O.detail>=2)return of(k.path);T(k.path),Tr.current=setTimeout(()=>{Tr.current=null,I_(k.path)},pO);return}Io(k)},Bl=k=>k.length&&void Qn({kind:"delete",items:k}).then(O=>O&&(xe(new Set),ne(null),P(!1))),_f=k=>{let O=Xl(k);O.length&&Qn({kind:"star",items:O.map(Z=>Z.path),starred:!O.every(Z=>Z.starred)})},Ul=k=>{let O=k.filter(Z=>!xf(Z));O.length&&gt({kind:"tag",items:O,tags:[...new Set(Xl(O).flatMap(Z=>Z.tags))].sort()})},vf=k=>gt({kind:"rename",path:k,folder:xf(k)}),D_=(k,O)=>{O.preventDefault(),To(null);let Z=zu(O.dataTransfer).filter(ae=>ae!==k);Z.length&&Qn({kind:"move",items:Z,to:k,make:!1}).then(ae=>ae&&xe(new Set))},KT=k=>({onDragOver:O=>{O.dataTransfer.types.includes(ao)&&(O.preventDefault(),O.dataTransfer.dropEffect="move",To(k))},onDragLeave:()=>To(O=>O===k?null:O),onDrop:O=>D_(k,O)}),XT=k=>({onDragOver:O=>{!lt||!O.dataTransfer.types.includes(ao)||(O.preventDefault(),To(`crumb:${k}`))},onDragLeave:()=>To(O=>O===`crumb:${k}`?null:O),onDrop:O=>D_(k,O)}),F_=k=>{let O=Ve.find(ae=>ae.path===k);if(O)return O;let Z=$_(k);return Z&&{kind:"page",path:k,threadId:Z.threadId,name:Z.name}},BT=k=>{let O=F_(k);if(!O)return[];let Z=H.has(k)&&H.size>1?[...H]:[k],ae=Z.length>1;return O.kind==="folder"?[{label:"Open",run:()=>Io(O)},ae?null:{label:"New folder inside",run:()=>gt({kind:"mkdir",parent:k})},ae?null:{label:"Rename",run:()=>vf(k)},{label:"Move to\u2026",run:()=>gt({kind:"move",items:Z})},{label:ae?`Delete ${Z.length} items`:"Delete folder",run:()=>Bl(Z)}]:[ae?null:{label:"Open",run:()=>wf(O)},ae?null:{label:"Rename",run:()=>vf(k)},{label:"Move to\u2026",run:()=>gt({kind:"move",items:Z})},{label:"Tag\u2026",run:()=>Ul(Z)},{label:L_(Z)?"Unstar":"Star",run:()=>_f(Z)},{label:ae?`Delete ${Z.length} items`:"Delete",run:()=>Bl(Z)}]},Io=k=>{if(T(k.path),k.kind==="page"){_e([]),$o({threadId:k.threadId,name:k.name,path:k.path}),S(!0);return}f?.state==="groups"?o({kind:"place",place:f.by==="project"?{kind:"project",projectId:k.path}:{kind:"conversation",threadId:k.path}}):o(Bt(k.path))},wf=k=>{if(k.kind!=="page")return Io(k);Io(k),P(!0)},z_=()=>{P(!1),c!=="wide"&&ne(null),requestAnimationFrame(()=>Ml.current?.focus())},kf=k=>{T(k);let O=Ve.find(Z=>Z.path===k);O?.kind==="page"&&N&&c==="wide"&&$o({threadId:O.threadId,name:O.name,path:O.path}),Ml.current?.querySelector(`[data-path="${CSS.escape(k??"")}"]`)?.scrollIntoView({block:"nearest"})},UT=k=>{if(k.target instanceof HTMLInputElement&&k.key===" ")return;let O=Ve.find(Z=>Z.path===y);if(k.key==="ArrowDown"||k.key==="ArrowUp")k.preventDefault(),kf(T1(Ve,y,k.key==="ArrowDown"?1:-1));else if((k.key==="ArrowRight"||k.key==="ArrowLeft")&&f?.state==="ok"&&O){k.preventDefault();let Z=O.kind==="folder"&&Ro.has(O.path);if(k.key==="ArrowRight"){if(O.kind!=="folder")return;if(!Z)return gf(O.path,!0);let ae=Ve[Ve.indexOf(O)+1];ae?.path.startsWith(`${O.path}/`)&&kf(ae.path)}else Z?gf(O.path,!1):Ve.some(ae=>ae.kind==="folder"&&ae.path===Ut(O.path))&&kf(Ut(O.path))}else lt&&(k.metaKey||k.ctrlKey)&&k.key.toLowerCase()==="a"?(k.preventDefault(),xe(new Set(Ve.map(Z=>Z.path)))):lt&&(k.metaKey||k.ctrlKey)&&k.key.toLowerCase()==="x"&&Gn().length?(k.preventDefault(),E_(Gn())):lt&&(k.metaKey||k.ctrlKey)&&k.key.toLowerCase()==="v"&&S_&&Kl!==null?(k.preventDefault(),Qn({kind:"move",items:S_,to:Kl,make:!1}).then(Z=>Z&&E_(null))):(k.metaKey||k.ctrlKey)&&k.key.toLowerCase()==="z"?(k.preventDefault(),N_()):lt&&(k.key==="Delete"||k.key==="Backspace")&&Gn().length?(k.preventDefault(),Bl(Gn())):lt&&k.key==="F2"&&y?(k.preventDefault(),vf(y)):lt&&k.key==="t"&&!k.metaKey&&!k.ctrlKey&&Gn().length?(k.preventDefault(),Ul(Gn())):lt&&(k.key==="x"||k.key==="X")&&!k.metaKey&&!k.ctrlKey&&y?(k.preventDefault(),bf(y,k.shiftKey)):lt&&k.key==="s"&&!k.metaKey&&!k.ctrlKey&&Gn().length?(k.preventDefault(),_f(Gn())):k.key==="Escape"&&(H.size||mt)?(k.preventDefault(),k.stopPropagation(),H.size&&O_(),gt(null)):k.key==="/"&&K_?(k.preventDefault(),Dl.current?.focus()):k.key==="Enter"&&O?(k.preventDefault(),wf(O)):k.key===" "&&O?.kind==="page"&&(k.preventDefault(),N&&L?.path===O.path?S(!1):Io(O))},HT=E1(s,{project:k=>cf(k),conversation:k=>g?.conversations.find(O=>O.threadId===k)?.title??k,saved:()=>zl?.name??"\u2026"}),Yn=L&&N?L:null,K_=Qt?.kind==="place",X_=!$&&!(Yn&&c!=="wide"),B_=$||Yn!==null&&c!=="wide",U_=ue!==null||mt!==null;K(()=>{if(!B_)return;let k=O=>{O.key!=="Escape"||O.defaultPrevented||(O.preventDefault(),U_?(ze(null),gt(null)):$?z_():ne(null))};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[B_,$,U_]);let tt=L?.path?$_(L.path):void 0,VT=L?l(au,{threadId:L.threadId,name:L.name,shown:ie,about:j,onChanged:()=>$o(L),onNavigate:(k,O,Z)=>{_e(ae=>[...ae,L]),$o({threadId:k,name:O,path:Z})},onBack:se.length?()=>{let k=se.at(-1);_e(O=>O.slice(0,-1)),$o(k)}:null}):null;return m("div",{ref:u,className:"flex h-full min-h-0 flex-col",children:[m("div",{className:"flex min-h-10 items-center gap-1 border-b px-3 py-1.5 text-sm",children:[$||Yn&&c!=="wide"?l(R,{size:"sm",variant:"secondary",onClick:()=>$?z_():ne(null),children:"Back to the list"}):null,l("ol",{className:"flex min-w-0 flex-1 items-center gap-1 truncate","aria-label":"Where you are",children:HT.map((k,O)=>m("li",{className:"flex min-w-0 items-center gap-1",children:[O?l("span",{className:"text-muted-foreground",children:"\u203A"}):null,k.where?l("button",{type:"button",className:`truncate rounded px-0.5 text-muted-foreground hover:underline ${k.where.kind==="place"&&k.where.place.kind==="folder"&&vi===`crumb:${k.where.place.path}`?"bg-muted ring-1 ring-ring":""}`,onClick:()=>o(k.where),...k.where.kind==="place"&&k.where.place.kind==="folder"?XT(k.where.place.path):{},children:k.label}):l("span",{className:"truncate font-medium",children:k.label})]},`${O}:${k.label}`))}),f?.state==="ok"?l("span",{className:"shrink-0 text-xs text-muted-foreground",children:mO(f)}):null,P_!==null&&!$&&!(Yn&&c!=="wide")?l(R,{size:"sm",variant:"secondary",onClick:()=>gt({kind:"mkdir",parent:P_}),children:"New folder"}):null]}),l(gE,{onUndo:()=>{N_()}}),mt?l(hE,{panel:mt,folders:(g?.folders??[]).map(k=>k.path),onRun:Qn,onClose:()=>gt(null)}):null,H.size>0&&!mt&&!$?l(mE,{count:H.size,onAll:yf?null:M_,total:Ve.length,allStarred:L_([...H]),onMove:()=>gt({kind:"move",items:[...H]}),onTag:[...H].some(k=>!xf(k))?()=>Ul([...H]):null,onStar:Xl([...H]).length?()=>_f([...H]):null,onDelete:()=>Bl([...H]),onClear:O_}):null,K_&&H.size===0&&!$&&!(Yn&&c!=="wide")?l(uE,{query:b,onQuery:v,meta:g,inFolder:Qt?.kind==="place"&&Qt.place.kind==="folder"&&Qt.place.path!==Ze,canSave:Qt?.kind==="place",problems:f?.state==="ok"?f.problems:[],inputRef:Dl,onSave:async k=>{if(Si===null)return"There's nothing here to save.";let O=await t.call("artifacts.saved.create",{name:k,place:Si,query:b});return O.state!=="ok"?O.reason:(x(await t.call("artifacts.folders",{})),hr(),o({kind:"saved",id:O.id}),null)}}):null,ee?m("p",{className:"px-3 py-2 text-sm text-destructive",children:["Couldn't reach the artifacts: ",ee]}):null,m("div",{className:"flex min-h-0 flex-1",children:[l("div",{ref:Ml,role:"listbox","aria-label":"Artifacts","aria-hidden":!X_,tabIndex:0,onKeyDown:UT,onDoubleClick:k=>{if(k.target instanceof HTMLInputElement)return;let O=k.target.closest("[data-path]")?.getAttribute("data-path"),Z=Ve.find(ae=>ae.path===O);Z&&!(Z.kind==="folder"&&f?.state==="ok")&&wf(Z)},onContextMenu:k=>{let O=k.target.closest("[data-path]")?.getAttribute("data-path");!lt||!O||!Ve.some(Z=>Z.path===O)||(k.preventDefault(),H.has(O)||(xe(new Set),T(O)),ze({x:k.clientX,y:k.clientY,path:O}))},onDragStart:k=>{let O=k.target.closest("[data-path]")?.getAttribute("data-path");if(!lt||!O)return;let Z=H.has(O)?[...H]:[O];k.dataTransfer.setData(ao,JSON.stringify(Z)),k.dataTransfer.setData("text/plain",Z.join(`
145
- `)),k.dataTransfer.effectAllowed="move"},onDragEnd:()=>To(null),className:`min-h-0 overflow-auto outline-none ${X_?"":"hidden"} ${Yn?"w-1/2 border-r":"flex-1"}`,children:f?f.state==="refused"?l("p",{className:"p-3 text-sm text-destructive",children:f.reason}):l(bO,{listing:f,lines:df,onToggle:k=>{I_(k),Ml.current?.focus({preventScroll:!0})},layout:Yn||c==="compact"?"compact":"wide",sort:d,onSort:k=>MT(A1(d,k)),isChosen:k=>H.size?H.has(k):y===k,ticks:lt?{isTicked:k=>H.has(k),any:H.size>0,all:yf,tick:bf,tickAll:M_}:null,draggable:lt,dropOn:vi,dropTarget:KT,renaming:LT,onRename:(k,O)=>{of(null),O&&O!==Pe(k)&&Qn({kind:"rename",path:k,name:O})},projectName:cf,where:Qt??s,flat:DT,filtering:_a(uf),onSelect:zT}):l("p",{className:"p-3 text-sm text-muted-foreground",children:"Loading\u2026"})}),l(As,{request:ue?{title:Pe(ue.path),entries:BT(ue.path),x:ue.x,y:ue.y}:null,onClose:zt}),$||Yn?m("div",{className:"flex min-w-0 flex-1 flex-col",children:[tt||L?m("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 border-b px-3 py-1.5 text-xs text-muted-foreground",children:[l("span",{className:"font-medium text-foreground",children:L?.path??L?.name}),tt?l("span",{children:cf(tt.projectId)}):null,tt?.threadTitle?l("span",{className:"truncate",children:tt.threadTitle}):null,tt?l("span",{children:Wr(tt.at)}):null,tt?.tags.map(k=>m("button",{type:"button","aria-label":`Take #${k} off`,title:`Take #${k} off`,className:"rounded px-1 hover:bg-muted hover:line-through",onClick:()=>{Qn({kind:"untag",items:[tt.path],tags:[k]})},children:["#",k]},k)),tt?l("button",{type:"button",className:"rounded px-1 hover:bg-muted",onClick:()=>Ul([tt.path]),children:"+ Tag"}):null,tt?l("button",{type:"button","aria-pressed":tt.starred,"aria-label":tt.starred?"Unstar":"Star",className:`rounded px-1 hover:bg-muted ${tt.starred?"text-foreground":""}`,onClick:()=>{Qn({kind:"star",items:[tt.path],starred:!tt.starred})},children:tt.starred?"\u2605":"\u2606"}):null,l("span",{className:"flex-1"}),$?null:l(R,{size:"sm",variant:"secondary",onClick:()=>P(!0),children:"Open"}),L?l(R,{size:"sm",variant:"secondary",onClick:()=>r.toThread(L.threadId),children:"Open in chat"}):null,L?.path&&lt&&F_(L.path)?l(R,{size:"sm",variant:"secondary","aria-label":`More for ${Pe(L.path)}`,"aria-haspopup":"menu",onClick:k=>{let O=k.currentTarget.getBoundingClientRect();L.path&&ze({x:O.right-176,y:O.bottom+4,path:L.path})},children:"\u2026"}):null]}):null,VT]}):null]})]})}function bO({listing:e,lines:t,onToggle:n,layout:r,sort:o,onSort:s,isChosen:i,ticks:a,draggable:u,dropOn:c,dropTarget:d,renaming:p,onRename:f,projectName:h,where:g,flat:x,filtering:b,onSelect:v}){if(e.state==="groups")return e.groups.length?l("ul",{children:e.groups.map(N=>{let S={kind:"folder",path:N.key};return m($a,{row:S,selected:i(N.key),onSelect:v,children:[l("span",{className:"min-w-0 flex-1 truncate",children:N.title??N.key}),e.by==="conversation"?l("span",{className:"hidden truncate text-muted-foreground sm:inline",children:h(N.projectId)}):null,m("span",{className:"shrink-0 text-xs text-muted-foreground",children:[N.pages," page",N.pages===1?"":"s"," \xB7 ",Wr(N.at)]})]},N.key)})}):l(Bu,{children:"No pages yet."});if(e.state==="search")return e.results.length?l("ul",{children:e.results.map(N=>{if(N.kind==="moved"){let $={kind:"page",path:N.to,threadId:N.threadId,name:N.name};return l($a,{row:$,selected:!1,onSelect:v,draggable:u,tall:!0,children:m("span",{className:"min-w-0 flex-1",children:[l("span",{className:"block truncate font-medium",children:N.to}),m("span",{className:"block truncate text-xs text-muted-foreground",children:["Moved from ",N.path]})]})},`moved:${N.path}`)}let S={kind:"page",path:N.path,threadId:N.threadId,name:N.name};return l($a,{row:S,selected:i(N.path),onSelect:v,draggable:u,ticks:a,tall:!0,children:m("span",{className:"min-w-0 flex-1",children:[l("span",{className:"block truncate font-medium",children:N.title}),m("span",{className:"block truncate text-xs text-muted-foreground",children:[N.path,N.version?` \xB7 matched in v${N.version}`:""]}),l("span",{className:"block truncate text-xs text-muted-foreground",children:N.snippet})]})},`page:${N.path}`)})}):l(Bu,{children:"Nothing matches."});let w=x||!(g.kind==="place"&&g.place.kind==="folder");if(!e.folders.length&&!e.pages.length)return l(Bu,{children:b?"Nothing matches this filter.":g.kind==="place"&&g.place.kind==="folder"&&g.place.path===Ze?"The Inbox is empty: every page is filed.":"Nothing here yet."});let C=t.some(N=>N.kind==="folder"),y=(N,S)=>N*16+(S?20:0);if(r!=="wide")return m("ul",{children:[t.map(N=>{if(N.kind==="note")return m("li",{className:"flex items-center gap-2 border-b border-border/40 px-3 py-1.5 text-xs text-muted-foreground",children:[a?l("span",{"aria-hidden":!0,className:"size-4 shrink-0 max-md:pointer-coarse:size-5"}):null,l("span",{className:"min-w-0 flex-1 truncate",style:{paddingLeft:`${y(N.depth,!0)}px`},children:N.text})]},N.key);if(N.kind==="folder"){let $=N.folder;return m($a,{row:{kind:"folder",path:$.path},selected:i($.path),onSelect:v,draggable:u,ticks:a,dropping:c===$.path,drop:d($.path),children:[m("span",{className:"min-w-0 flex-1 truncate",style:{paddingLeft:`${y(N.depth,!1)}px`},children:[l(kE,{path:$.path,open:N.open,onToggle:n}),p===$.path?l(EE,{path:$.path,onDone:f}):Pe($.path)]}),l("span",{className:"shrink-0 text-xs text-muted-foreground",children:$.pages})]},$.path)}let S=N.page;return l($a,{row:{kind:"page",path:S.path,threadId:S.threadId,name:S.name},selected:i(S.path),onSelect:v,draggable:u,ticks:a,tall:!0,children:m("span",{className:`min-w-0 flex-1 ${S.fileGone||S.threadGone?"opacity-60":""}`,style:{paddingLeft:`${y(N.depth,C)}px`},children:[m("span",{className:"block truncate",children:[S.unread?l(NE,{}):null,Pe(S.path),S.starred?l(AE,{}):null]}),m("span",{className:"block truncate text-xs text-muted-foreground",children:[w?`${Ut(S.path)||"Library"} \xB7 `:"",Wr(S.at)," \xB7 ",h(S.projectId)]})]})},S.path)}),e.more?m(Bu,{children:["Showing the first ",e.pages.length," pages."]}):null]});let T=(N,S)=>({paddingLeft:`${12+y(N,S)}px`});return m("table",{className:"w-full table-fixed text-sm",children:[l("thead",{className:"sticky top-0 bg-background text-left text-xs text-muted-foreground",children:m("tr",{className:"border-b",children:[a?l("th",{className:"w-8 py-1.5 pl-3 font-normal",children:l(Km,{label:a.all?"Select none":"Select all",on:a.all,mixed:a.any&&!a.all,shown:!0,onTick:a.tickAll})}):null,hO.map(N=>l("th",{className:`px-3 py-1.5 font-normal ${N.by==="name"?"w-[34%]":""}`,"aria-sort":N.by&&o.by===N.by?o.desc?"descending":"ascending":void 0,children:N.by?m("button",{type:"button",className:"hover:text-foreground",onClick:()=>s(N.by),children:[N.label,o.by===N.by?o.desc?" \u25BE":" \u25B4":""]}):N.label},N.label))]})}),m("tbody",{children:[t.map(N=>{if(N.kind==="note")return m("tr",{className:"border-b border-border/40",children:[a?l("td",{}):null,l("td",{colSpan:7,className:"truncate px-3 py-1.5 text-xs text-muted-foreground",style:T(N.depth,!0),children:N.text})]},N.key);if(N.kind==="folder"){let P=N.folder,L={kind:"folder",path:P.path};return m("tr",{"data-path":P.path,role:"option","aria-selected":i(P.path),draggable:u,className:`group cursor-default border-b border-border/40 ${i(P.path)?"bg-muted":"hover:bg-muted/50"} ${c===P.path?"outline outline-1 outline-ring":""}`,onClick:ne=>v(L,ne),...d(P.path),children:[a?l(SE,{path:P.path,ticks:a}):null,m("td",{className:"truncate px-3 py-1.5",style:T(N.depth,!1),children:[l(kE,{path:P.path,open:N.open,onToggle:n}),p===P.path?l(EE,{path:P.path,onDone:f}):`${Pe(P.path)}/`]}),l("td",{className:"px-3 py-1.5 text-muted-foreground",children:P.at?Wr(P.at):"\u2014"}),m("td",{className:"px-3 py-1.5 text-muted-foreground",colSpan:5,children:[P.pages," page",P.pages===1?"":"s"]})]},P.path)}let S=N.page,$={kind:"page",path:S.path,threadId:S.threadId,name:S.name};return m("tr",{"data-path":S.path,role:"option","aria-selected":i(S.path),draggable:u,className:`group cursor-default border-b border-border/40 ${i(S.path)?"bg-muted":"hover:bg-muted/50"} ${S.fileGone||S.threadGone?"opacity-60":""}`,onClick:P=>v($,P),children:[a?l(SE,{path:S.path,ticks:a}):null,m("td",{className:"truncate px-3 py-1.5",style:T(N.depth,C),children:[S.unread?l(NE,{}):null,Pe(S.path),S.starred?l(AE,{}):null,w?l("span",{className:"ml-2 text-xs text-muted-foreground",children:Ut(S.path)||"Library"}):null]}),l("td",{className:"truncate px-3 py-1.5 text-muted-foreground",children:Wr(S.at)}),l("td",{className:"truncate px-3 py-1.5 text-muted-foreground",children:h(S.projectId)}),l("td",{className:"truncate px-3 py-1.5 text-muted-foreground",children:S.threadTitle??"\u2014"}),l("td",{className:"truncate px-3 py-1.5 text-muted-foreground",children:S.tags.map(P=>`#${P}`).join(" ")}),l("td",{className:"px-3 py-1.5 text-muted-foreground",children:S.versions}),l("td",{className:"px-3 py-1.5 text-muted-foreground",children:gO(S.size)})]},S.path)}),e.more?l("tr",{children:m("td",{colSpan:a?8:7,className:"px-3 py-2 text-xs text-muted-foreground",children:["Showing the first ",e.pages.length," pages."]})}):null]})]})}function kE({path:e,open:t,onToggle:n}){return l("button",{type:"button",tabIndex:-1,"aria-expanded":t,"aria-label":`${t?"Collapse":"Expand"} ${Pe(e)}`,className:"mr-1 inline-block w-4 text-center text-muted-foreground hover:text-foreground",onMouseDown:r=>r.preventDefault(),onClick:r=>{r.stopPropagation(),n(e)},onDoubleClick:r=>r.stopPropagation(),children:t?"\u25BE":"\u25B8"})}function $a({row:e,selected:t,onSelect:n,draggable:r,ticks:o,dropping:s,drop:i,tall:a,children:u}){return m("li",{"data-path":e.path,role:"option","aria-selected":t,draggable:r,className:`group flex cursor-default items-center gap-2 border-b border-border/40 px-3 ${a?"py-2":"py-1.5"} text-sm ${t?"bg-muted":"hover:bg-muted/50"} ${s?"outline outline-1 outline-ring":""}`,onClick:c=>n(e,c),...i,children:[o?l(Km,{label:`Select ${Pe(e.path)}`,on:o.isTicked(e.path),shown:o.any,onTick:c=>o.tick(e.path,c),quiet:!0}):null,u]})}function SE({path:e,ticks:t}){return l("td",{className:"w-8 py-1.5 pl-3",children:l(Km,{label:`Select ${Pe(e)}`,on:t.isTicked(e),shown:t.any,onTick:n=>t.tick(e,n),quiet:!0})})}function Km({label:e,on:t,mixed:n=!1,shown:r,quiet:o=!1,onTick:s}){return l("span",{className:`-m-2 flex shrink-0 cursor-pointer items-center p-2 ${r||t||n?"":"opacity-0 focus-within:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100"}`,onClick:a=>{a.stopPropagation(),a.target===a.currentTarget&&s(a.shiftKey)},children:l("input",{type:"checkbox","aria-label":e,title:e,checked:t,readOnly:!0,tabIndex:o?-1:0,ref:a=>{a&&(a.indeterminate=n)},className:"size-4 cursor-pointer max-md:pointer-coarse:size-5",onClick:a=>{a.stopPropagation(),s(a.shiftKey)}})})}function EE({path:e,onDone:t}){let[n,r]=_(Pe(e)),o=s=>s.stopPropagation();return l("form",{className:"inline-block align-middle",onClick:o,onDoubleClick:o,onSubmit:s=>{s.preventDefault(),t(e,n.trim()||null)},children:l(le,{autoFocus:!0,"aria-label":`New name for ${Pe(e)}`,className:"h-7 w-48",maxLength:64,value:n,onFocus:s=>s.currentTarget.select(),onChange:s=>r(s.target.value),onBlur:s=>s.currentTarget.form?.requestSubmit(),onKeyDown:s=>{s.stopPropagation(),s.key==="Escape"&&(s.preventDefault(),t(e,null))}})})}function NE(){return l("span",{role:"img","aria-label":"Changed since you last opened it",className:"mr-1.5 inline-block size-1.5 rounded-full bg-foreground align-middle"})}function AE(){return l("span",{role:"img","aria-label":"Starred",className:"ml-1.5 text-muted-foreground",children:"\u2605"})}function Bu({children:e}){return l("p",{className:"p-3 text-sm text-muted-foreground",children:e})}var RE=(e,t,n)=>`${e===0?"No":e===1?"One":e} ${e===1?t:n}`;function $E(){let{change:e}=Ea();return t=>{e(t.status==="open"?{action:"done",ref:t.id,note:null}:{action:"reopen",ref:t.id,why:null})}}function Rs({eyebrow:e,title:t,children:n}){return m("div",{className:"flex flex-wrap items-end gap-4",children:[m("div",{className:"min-w-0 flex-1",children:[l("p",{className:"text-xs font-semibold text-muted-foreground",children:e}),l("h1",{className:"mt-0.5 text-2xl font-semibold tracking-tight",children:t})]}),n]})}function Ts({tasks:e,meta:t,now:n,open:r,rich:o,empty:s,limit:i}){let a=$E(),[u,c]=_(!1),d=i&&!u?e.slice(0,i):e;return e.length?m(he,{children:[d.map((p,f)=>l(q1,{task:p,assistant:t.assistant,now:n,rich:o,first:f===0,onOpen:()=>r(p),onToggle:()=>a(p)},p.id)),d.length<e.length?m("button",{type:"button",onClick:()=>c(!0),className:"flex w-full cursor-pointer items-center gap-2 border-t border-border-hairline px-4 py-2.5 text-left text-sm font-semibold text-timeline-accent hover:bg-state-hover",children:[l(pe,{name:"ChevronDown","aria-hidden":!0,className:"size-3.5"}),e.length-d.length," more:"," ",e.slice(d.length,d.length+4).map(p=>p.title.toLowerCase()).join(", "),e.length-d.length>4?"\u2026":""]}):null]}):l(Oe,{children:s})}function yO({meta:e,filters:t,open:n,now:r}){let o=nt(),s=ps(t),{data:i,error:a}=We(()=>o.call("tasks.today",s),[o,t.origin,t.project]),u=We(()=>o.call("tasks.upcoming",{...s,days:7}),[o,t.origin,t.project]).data,c=We(()=>o.call("tasks.journal",{day:e.today,newest:!0,limit:3}),[o,e.today]).data;if(!i)return l(Oe,{children:a||"Loading\u2026"});let d=i.yours.filter(x=>x.dueAt!==null&&hs(x.dueAt,i.zone)<=i.day).length,p=[i.yours.length===0?"Nothing needs you right now.":`${RE(i.yours.length,"thing needs","things need")} you${d?`, ${d===i.yours.length&&d>1?"all":d} today`:""}.`,`I\u2019m handling ${i.onIt.length===1?"one other":`${i.onIt.length} others`} and waiting on ${i.waiting.length===1?"one reply":`${i.waiting.length} replies`}.`].join(" "),f=Array.from({length:7},(x,b)=>Yr(i.day,b)),h=new Map(f.map(x=>[x,u?.items.filter(b=>hs(b.at,i.zone)===x)??[]])),g=(c?.entries??[]).slice(-3).reverse();return m("div",{className:"flex flex-wrap items-start gap-8",children:[m("div",{className:"min-w-0 flex-[999_1_34rem] space-y-7",children:[l(Rs,{eyebrow:"Today",title:Ct(i.day)}),m("div",{className:"flex items-start gap-3.5 rounded-2xl bg-surface-selected px-4 py-3.5",children:[l(De,{origin:"assistant",assistant:e.assistant,size:28}),l("p",{className:"text-base leading-relaxed",children:p})]}),l(Gr,{filters:t,onChange:xn,meta:e}),l(Dn,{title:"Your move",count:i.yours.length,hint:"By priority, then when",children:l(Ts,{tasks:i.yours,meta:e,now:r,open:n,rich:!0,empty:"Nothing is waiting on you. Enjoy it."})}),l(Dn,{title:`${e.assistant}\u2019s on it`,count:i.onIt.length,hint:"Nothing here needs you",children:l(Ts,{tasks:i.onIt,meta:e,now:r,open:n,limit:6,empty:`${e.assistant} has nothing in hand.`})}),l(Dn,{title:"Waiting on others",count:i.waiting.length,hint:`${e.assistant} checks back on the date shown`,children:l(Ts,{tasks:i.waiting,meta:e,now:r,open:n,empty:"Nobody owes you an answer."})})]}),m("aside",{className:"hidden w-80 shrink-0 space-y-7 xl:block","aria-label":"Today at a glance",children:[m("section",{className:"space-y-3",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:"This week"}),l("div",{className:"grid grid-cols-7 gap-1",children:f.map((x,b)=>m("div",{className:V("flex flex-col items-center gap-1 rounded-lg py-2",b===0?"bg-foreground text-background":""),children:[l("span",{className:V("text-2xs font-semibold",b===0?"opacity-80":"text-muted-foreground"),children:ur(x)}),l("span",{className:"text-sm font-semibold",children:Number(x.slice(8))}),l("span",{className:"flex h-1.5 gap-0.5",children:(h.get(x)??[]).slice(0,4).map(v=>l("span",{className:V("size-1.5 rounded-full",b===0?"bg-background":v.task.move==="owner"?"bg-warning":"bg-timeline-accent")},`${v.task.id}-${v.at}`))})]},x))})]}),m("section",{className:"space-y-2",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:"Today\u2019s schedule"}),i.schedule.length===0?l("p",{className:"text-sm text-muted-foreground",children:"Nothing timed today."}):null,l("ol",{className:"space-y-0.5",children:i.schedule.map((x,b)=>{let v=x.at<r,w=v&&(i.schedule[b+1]?.at??1/0)>=r;return m("li",{children:[m("button",{type:"button",onClick:()=>n(x.task),className:"grid w-full cursor-pointer grid-cols-[4rem_1rem_minmax(0,1fr)] items-start gap-2.5 rounded-md py-1.5 text-left hover:bg-state-hover",children:[l("span",{className:"pt-px text-right text-xs tabular-nums text-muted-foreground",children:Ee(x.at,i.zone)}),l(Ht,{glyph:jr(x.task),className:V("mt-px size-3.5",v?"text-muted-foreground":"text-timeline-accent")}),l("span",{className:V("min-w-0 text-sm leading-snug",v?"text-muted-foreground":"font-medium"),children:x.task.title})]}),w?m("div",{className:"my-1 grid grid-cols-[4rem_minmax(0,1fr)] items-center gap-2.5","aria-hidden":!0,children:[l("span",{className:"text-right text-2xs font-bold text-timeline-accent",children:Ee(r,i.zone)}),l("span",{className:"h-0.5 rounded-full bg-timeline-accent"})]}):null]},`${x.task.id}-${x.at}`)})})]}),g.length?m("section",{className:"space-y-3",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:"From the journal"}),g.map(x=>m("p",{className:"text-sm leading-snug",children:[m("span",{className:"block text-xs text-muted-foreground",children:[Ee(x.at,i.zone)," \xB7 ",x.actor==="assistant"?e.assistant:x.actor==="owner"?"You":"System"," \xB7 ",x.title]}),x.body]},x.seq))]}):null]})]})}function _O({meta:e,filters:t,open:n,now:r}){let o=nt(),[s,i]=_(!0),{data:a,error:u}=We(()=>o.call("tasks.upcoming",{...ps(t),days:28}),[o,t.origin,t.project]);if(!a)return l(Oe,{children:u||"Loading\u2026"});let c=g=>g.kind==="scheduled"&&g.project.id==="internal",d=a.items.filter(g=>s||!c(g.task)),p=new Map;for(let g of d)p.set(hs(g.at,a.zone),[...p.get(hs(g.at,a.zone))??[],g]);let f=Array.from({length:7},(g,x)=>Yr(a.from,x)),h=g=>g===a.from?"Today":g===Yr(a.from,1)?"Tomorrow":ur(g,"long");return m("div",{className:"space-y-7",children:[l(Rs,{eyebrow:"Upcoming",title:"This week and later",children:m("label",{className:"inline-flex cursor-pointer items-center gap-2 text-xs font-medium text-muted-foreground",children:[l("input",{type:"checkbox",className:"size-4 accent-foreground",checked:s,onChange:g=>i(g.target.checked)}),"Show ",e.assistant,"\u2019s routines"]})}),l(Gr,{filters:t,onChange:xn,meta:e}),l("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4 lg:grid-cols-7","aria-label":"The week ahead",children:f.map((g,x)=>m("div",{className:V("flex min-h-36 flex-col gap-1 rounded-xl border bg-surface-raised p-2.5",x===0?"border-foreground/40 ring-1 ring-foreground/20":"border-border-hairline"),children:[m("p",{className:"flex items-baseline gap-1.5",children:[l("span",{className:"text-base font-semibold",children:Number(g.slice(8))}),l("span",{className:"text-xs font-semibold text-muted-foreground",children:x===0?"Today":ur(g)})]}),(p.get(g)??[]).slice(0,5).map(b=>m("button",{type:"button",onClick:()=>n(b.task),className:V("flex cursor-pointer items-center gap-1.5 truncate rounded-md px-1.5 py-1 text-left text-xs",c(b.task)?"border border-dashed border-border text-muted-foreground":b.task.priority==="urgent"?"bg-surface-destructive font-semibold text-destructive-text":b.task.priority==="high"?"bg-warning/15 font-semibold text-warning-text":"bg-surface-selected font-medium"),children:[b.timed?l("span",{className:"shrink-0 tabular-nums opacity-75",children:Ee(b.at,a.zone)}):null,l("span",{className:"truncate",children:b.task.title})]},`${b.task.id}-${b.at}`)),(p.get(g)?.length??0)>5?m("span",{className:"px-1.5 text-2xs text-muted-foreground",children:["+",(p.get(g)?.length??0)-5," more"]}):null]},g))}),m("div",{className:"space-y-6",children:[[...p.entries()].map(([g,x])=>m("section",{className:"space-y-2",children:[m("h2",{className:"flex items-baseline gap-2",children:[l("span",{className:"text-sm font-semibold",children:h(g)}),l("span",{className:"text-xs text-muted-foreground",children:Ct(g)})]}),l("div",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised",children:x.map((b,v)=>m("button",{type:"button",onClick:()=>n(b.task),className:V("grid w-full cursor-pointer grid-cols-[4.5rem_1rem_minmax(0,1fr)_auto] items-center gap-3 px-4 py-2.5 text-left hover:bg-state-hover",v>0&&"border-t border-border-hairline"),children:[l("span",{className:V("text-right text-xs font-semibold tabular-nums",(c(b.task)||!b.timed)&&"font-normal text-muted-foreground"),children:b.timed?Ee(b.at,a.zone):"Due"}),l(Ht,{glyph:jr(b.task),className:c(b.task)?"text-muted-foreground":"text-timeline-accent"}),m("span",{className:"flex min-w-0 items-center gap-2",children:[l("span",{className:V("truncate text-sm",c(b.task)?"text-muted-foreground":"font-semibold"),children:b.task.title}),l(De,{origin:b.task.origin,assistant:e.assistant,size:15}),l(Na,{project:b.task.project})]}),m("span",{className:"flex items-center gap-2.5",children:[l("span",{className:"hidden truncate text-xs text-muted-foreground sm:inline",children:b.task.whenText?Qr(b.task.whenText):""}),l(us,{level:b.task.priority})]})]},`${b.task.id}-${b.at}`))})]},g)),p.size===0?l(Oe,{children:"Nothing timed in the next four weeks."}):null,a.undated.length?l(Dn,{title:"No date",count:a.undated.length,hint:"Open, with no when",children:l(Ts,{tasks:a.undated,meta:e,now:r,open:n,limit:8,empty:""})}):null]})]})}async function IE(e,t,n,r){let o=[],s=0,i=0;for(let a=0;a<n&&s!==null;a++){let u=await e.call("tasks.list",{...t,limit:r,offset:s});o.push(...u.tasks),i=u.total,s=u.next}return{tasks:o,total:i,more:s!==null}}function PE({label:e,onClick:t}){return m("button",{type:"button",onClick:t,className:"flex w-full cursor-pointer items-center gap-2 border-t border-border-hairline px-4 py-2.5 text-left text-sm font-semibold text-timeline-accent hover:bg-state-hover",children:[l(pe,{name:"ChevronDown","aria-hidden":!0,className:"size-3.5"}),e]})}function vO({meta:e,filters:t,open:n,now:r}){let o=nt(),[s,i]=_(1),{data:a,error:u}=We(()=>IE(o,{...ps(t),move:"others",status:"open",sort:"due"},s,200),[o,s,t.origin,t.project]);return m("div",{className:"space-y-7",children:[l(Rs,{eyebrow:"Waiting on others",title:a?`${RE(a.total,"reply","replies")} outstanding`:"Waiting on others"}),l(Gr,{filters:t,onChange:xn,meta:e}),l(Dn,{title:"Waiting",count:a?.total,hint:`Soonest check-back first. ${e.assistant} nudges at most twice, then hands it back with what was tried`,children:a?m(he,{children:[l(Ts,{tasks:a.tasks,meta:e,now:r,open:n,rich:!0,empty:"Nobody owes you an answer."}),a.more?l(PE,{label:`Show more (${a.total-a.tasks.length} left)`,onClick:()=>i(c=>c+1)}):null]}):l(Oe,{children:u||"Loading\u2026"})})]})}function wO({meta:e,filters:t,open:n,now:r}){let o=nt(),[s,i]=_("both"),{data:a,error:u}=We(()=>o.call("tasks.rhythms",ps(t)),[o,t.origin,t.project]);if(!a)return l(Oe,{children:u||"Loading\u2026"});let c=Array.from({length:14},(d,p)=>Yr(a.from,p));return m("div",{className:"space-y-7",children:[l(Rs,{eyebrow:"Scheduled and watched",title:"What happens on a rhythm, and what\u2019s being watched"}),m("p",{className:"-mt-4 max-w-2xl text-sm text-muted-foreground",children:["Scheduled tasks happen at set times. A watch belongs to a task that\u2019s waiting: ",e.assistant," checks quietly and only acts or tells you when something changes."]}),l(Gr,{filters:t,onChange:xn,meta:e,children:l(_t,{label:"Show",value:s,onChange:i,options:[{value:"both",label:"Both"},{value:"scheduled",label:"Scheduled"},{value:"watching",label:"Watching"}]})}),s!=="watching"?l(Dn,{title:"Scheduled",count:a.scheduled.length,hint:"The next two weeks",children:a.scheduled.length?m(he,{children:[m("div",{className:"hidden grid-cols-[1rem_minmax(0,1.4fr)_minmax(0,1fr)_15rem] gap-4 border-b border-border-hairline bg-muted/40 px-4 py-2 text-2xs font-semibold text-muted-foreground md:grid",children:[l("span",{}),l("span",{children:"Name"}),l("span",{children:"When"}),l("span",{className:"grid gap-0.5 text-center",style:{gridTemplateColumns:"repeat(14, minmax(0, 1fr))"},children:c.map((d,p)=>l("span",{className:p===0?"text-foreground":"",children:ur(d).charAt(0)},d))})]}),a.scheduled.map(({task:d,next:p},f)=>{let h=new Set(p.map(g=>hs(g,a.zone)));return m("button",{type:"button",onClick:()=>n(d),className:V("grid w-full cursor-pointer grid-cols-[1rem_minmax(0,1fr)] items-center gap-x-4 gap-y-2 px-4 py-3 text-left hover:bg-state-hover md:grid-cols-[1rem_minmax(0,1.4fr)_minmax(0,1fr)_15rem]",f>0&&"border-t border-border-hairline"),children:[l(Ht,{glyph:"repeat",className:"text-timeline-accent"}),m("span",{className:"min-w-0",children:[m("span",{className:"flex items-center gap-2",children:[l("span",{className:"truncate text-sm font-semibold",children:d.title}),l(De,{origin:d.origin,assistant:e.assistant,size:15}),l(Na,{project:d.project})]}),l("span",{className:"block truncate text-xs text-muted-foreground",children:d.move==="owner"?"Reminder for you":`${e.assistant} does it`})]}),l("span",{className:"col-start-2 text-sm font-medium md:col-start-auto",children:d.whenText?Qr(d.whenText):""}),l("span",{className:"col-start-2 grid gap-0.5 md:col-start-auto",style:{gridTemplateColumns:"repeat(14, minmax(0, 1fr))"},"aria-label":`Runs on ${h.size} of the next 14 days`,children:c.map((g,x)=>l("span",{className:V("h-4 rounded",h.has(g)?d.move==="owner"?"bg-warning":"bg-foreground/80":"bg-muted",x===0&&"ring-2 ring-foreground/25 ring-offset-1 ring-offset-surface-raised")},g))})]},d.id)})]}):l(Oe,{children:"No repeating tasks yet. Say \u201Cevery Friday at 4pm, \u2026\u201D in the conversation, or add one here."})}):null,s!=="scheduled"?l(Dn,{title:"Watching",count:a.watched.length,hint:"Each one ends when its task does",children:a.watched.length?a.watched.map((d,p)=>m("button",{type:"button",onClick:()=>n(d),className:V("flex w-full cursor-pointer items-center gap-3 px-4 py-3 text-left hover:bg-state-hover",p>0&&"border-t border-border-hairline"),children:[l(Ht,{glyph:"watch",className:"text-timeline-accent"}),m("span",{className:"min-w-0 flex-1",children:[m("span",{className:"flex items-center gap-2",children:[l("span",{className:"truncate text-sm font-semibold",children:d.title}),l(De,{origin:d.origin,assistant:e.assistant,size:15}),l(Na,{project:d.project})]}),l("span",{className:"block truncate text-xs text-muted-foreground",children:d.when?.form==="on_change"&&d.watch===null?`No watch yet; ${e.assistant} sets one up`:d.waitingOn?`Waiting on ${d.waitingOn}`:d.why??""})]}),l(Sa,{task:d,now:r})]},d.id)):l(Oe,{children:"Nothing is being watched."})}):null]})}async function kO(e,t,n){let r=[],o=[],s=null;for(let i=0;i<n;i++){let a=await e.call("tasks.journal",{...t,newest:!0,limit:200,...s===null?{}:{before:s}});if(r.unshift(...a.entries),o=a.notes,s=a.next,s===null)break}return{entries:r,notes:o,more:s!==null}}function SO({meta:e,filters:t}){let n=nt(),[r,o]=_(e.today),[s,i]=_(1),[a,u]=_("both"),[c,d]=_(null),[p,f]=_(""),{data:h,error:g,reload:x}=We(async()=>({day:r,journal:await kO(n,{day:r,...a!=="both"?{actor:a}:{},...t.project?{project:t.project}:{}},s)}),[n,r,a,s,t.project]),b=h?.day===r?h.journal:null,v=b?.notes.find(y=>y.actor==="owner")?.body??"",w=b?.notes.find(y=>y.actor==="assistant")?.body,C=e.zone;return m("div",{className:"mx-auto max-w-3xl space-y-7",children:[m(Rs,{eyebrow:"Journal",title:Ct(r),children:[l(R,{variant:"outline",size:"icon","aria-label":"The day before",onClick:()=>(o(Yr(r,-1)),d(null),f(""),i(1)),children:l(pe,{name:"ChevronLeft","aria-hidden":!0,className:"size-4"})}),l(R,{variant:"outline",size:"icon","aria-label":"The day after",disabled:r>=e.today,onClick:()=>(o(Yr(r,1)),d(null),f(""),i(1)),children:l(pe,{name:"ChevronRight","aria-hidden":!0,className:"size-4"})}),r!==e.today?l(R,{variant:"outline",size:"sm",onClick:()=>(o(e.today),d(null),f(""),i(1)),children:"Today"}):null]}),w?m("div",{className:"flex items-start gap-3.5 rounded-2xl bg-surface-selected px-4 py-3.5",children:[l(De,{origin:"assistant",assistant:e.assistant,size:26}),l("p",{className:"whitespace-pre-wrap text-base leading-relaxed",children:w})]}):null,m("div",{className:"flex flex-wrap items-center gap-3",children:[l(_t,{label:"Whose lines",value:a,onChange:u,options:[{value:"both",label:"Both"},{value:"assistant",label:e.assistant},{value:"owner",label:"You"}]}),l(Gr,{filters:t,onChange:xn,meta:e,origin:!1})]}),b?b.entries.length===0?m(Oe,{children:["Nothing was written ",r===e.today?"yet today":"that day","."]}):m("ol",{className:"relative space-y-4 border-l border-border-hairline pl-6",children:[b.more?l("li",{children:m("button",{type:"button",onClick:()=>i(y=>y+1),className:"flex cursor-pointer items-center gap-2 text-sm font-semibold text-timeline-accent hover:underline",children:[l(pe,{name:"ChevronUp","aria-hidden":!0,className:"size-3.5"}),"Show earlier"]})}):null,b.entries.map(y=>m("li",{className:"relative",children:[l("span",{className:"absolute -left-[2.15rem] top-0",children:y.actor==="system"?l("span",{className:"block size-5 rounded-full border border-border bg-muted"}):l(De,{origin:y.actor==="assistant"?"assistant":"owner",assistant:e.assistant,size:22})}),m("p",{className:"text-xs text-muted-foreground",children:[Ee(y.at,C)," \xB7 ",y.actor==="assistant"?e.assistant:y.actor==="owner"?"You":"System"]}),l("p",{className:V("mt-0.5 whitespace-pre-wrap text-sm leading-relaxed",y.actor==="owner"&&y.what==="note"&&"rounded-lg border border-border-hairline bg-surface-raised px-3 py-2",y.what==="created"&&"text-muted-foreground"),children:y.body}),m("p",{className:"mt-1.5 text-xs font-medium text-muted-foreground",children:[y.key," \xB7 ",y.title]})]},y.seq))]}):l(Oe,{children:g||"Loading\u2026"}),m("form",{className:"space-y-2 rounded-2xl border border-border bg-surface-raised p-4",onSubmit:y=>{y.preventDefault(),b&&n.call("tasks.dayNote",{day:r,body:c??v}).then(()=>{f(`Saved ${Ee(Date.now(),C)}`),x()},T=>f(`Couldn\u2019t save: ${T instanceof Error?T.message:String(T)}`))},children:[m("label",{className:"flex items-center gap-2 text-sm font-semibold",children:[l(De,{origin:"owner",assistant:e.assistant,size:18}),"Your note for ",r===e.today?"today":Ct(r,"short")]}),l("textarea",{value:c??v,disabled:!b,onChange:y=>d(y.target.value),rows:3,className:"w-full resize-y rounded-md border border-input bg-background px-3 py-2 text-sm leading-relaxed",placeholder:`How did it go? Anything on your mind, or anything ${e.assistant} should know?`}),m("div",{className:"flex items-center justify-end gap-3",children:[l("span",{className:"text-xs text-muted-foreground",children:p||`${e.assistant} reads your notes as context`}),l(R,{type:"submit",size:"sm",disabled:!b||c===null||c===v,children:"Save note"})]})]})]})}function EO({meta:e,filters:t,open:n,now:r}){let o=nt(),[s,i]=_("done"),[a,u]=_(1),{data:c,error:d}=We(()=>IE(o,{...ps(t),status:s,sort:"closed"},a,50),[o,s,a,t.origin,t.project]),p=c?.tasks??[];return m("div",{className:"space-y-7",children:[l(Rs,{eyebrow:"Done",title:"Finished and dropped",children:l(_t,{label:"Which",value:s,onChange:f=>{i(f),u(1)},options:[{value:"done",label:"Done"},{value:"dropped",label:"Dropped"}]})}),l(Gr,{filters:t,onChange:xn,meta:e}),l(Dn,{title:s==="done"?"Done":"Dropped",count:c?.total,hint:s==="dropped"?"Each with its reason; reopen any of them":"Most recent first",children:c?m(he,{children:[l(Ts,{tasks:p,meta:e,now:r,open:n,empty:s==="done"?"Nothing finished yet.":"Nothing dropped."}),c.more?l(PE,{label:"Show older",onClick:()=>u(f=>f+1)}):null]}):l(Oe,{children:d||"Loading\u2026"})})]})}function OE({subPath:e}){let t=am(e),[n,r]=_(t.task);K(()=>{t.task&&r(t.task)},[t.task]);let o=ds(),[s]=cm(),i=en(),a=fs(),[u,c]=_(!1),d=f=>i(t.view,f.key),p=o?{today:l(yO,{meta:o,filters:s,open:d,now:a}),upcoming:l(_O,{meta:o,filters:s,open:d,now:a}),waiting:l(vO,{meta:o,filters:s,open:d,now:a}),scheduled:l(wO,{meta:o,filters:s,open:d,now:a}),journal:l(SO,{meta:o,filters:s}),done:l(EO,{meta:o,filters:s,open:d,now:a})}:{today:null,upcoming:null,waiting:null,scheduled:null,journal:null,done:null};return m("main",{className:"h-full overflow-auto",children:[m("div",{className:"mx-auto flex max-w-7xl flex-col gap-6 p-4 sm:p-8",children:[m("div",{className:"flex items-center gap-2",children:[l("nav",{"aria-label":"Task views",className:"flex min-w-0 flex-1 gap-1 overflow-x-auto md:hidden",children:hu.map(f=>l("button",{type:"button","aria-current":t.view===f.id?"page":void 0,onClick:()=>i(f.id),className:V("shrink-0 cursor-pointer rounded-full px-3 py-1.5 text-xs font-semibold",t.view===f.id?"bg-foreground text-background":"bg-muted text-muted-foreground"),children:f.label},f.id))}),m(R,{className:"ml-auto shrink-0","aria-label":"New task",onClick:()=>c(!0),children:[l(pe,{name:"Plus","aria-hidden":!0,className:"size-4"}),l("span",{className:"hidden sm:inline",children:"New task"})]})]}),o?p[t.view]:l(Oe,{children:"Loading\u2026"})]}),l(qS,{open:u,onClose:()=>c(!1),meta:o,onMade:f=>{c(!1),i(t.view,f.key)}}),l(JS,{open:t.task!==null,taskRef:t.task??n,meta:o,onClose:()=>i(t.view)})]})}function LE({subPath:e}){let t=am(e),n=en(),r=nt(),o=ds(),[s,i]=cm(),a=We(()=>r.call("tasks.today",{}),[r]).data,u={today:a?.yours.length,waiting:a?.waiting.length};return m("nav",{"aria-label":"Tasks",className:"flex flex-col gap-0.5 p-2",children:[hu.map(c=>m("button",{type:"button","aria-current":t.view===c.id?"page":void 0,onClick:()=>n(c.id),className:V("flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm",t.view===c.id?"bg-muted font-semibold":"hover:bg-muted/60"),children:[l("span",{className:"min-w-0 flex-1 truncate",children:c.label}),u[c.id]?l("span",{className:V("rounded-full px-1.5 text-2xs font-bold",c.id==="today"?"bg-foreground text-background":"text-muted-foreground"),children:u[c.id]}):null]},c.id)),l("p",{className:"mt-4 px-2 pb-1 text-xs font-semibold text-muted-foreground",children:"Projects"}),(o?.projects??[]).map(c=>m("button",{type:"button","aria-pressed":s.project===c.id,onClick:()=>i({...s,project:s.project===c.id?"":c.id}),className:V("flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm",s.project===c.id?"bg-muted font-semibold":"hover:bg-muted/60"),children:[l("span",{className:"min-w-0 flex-1 truncate",children:c.name}),l("span",{className:"text-2xs font-bold tracking-wide text-muted-foreground",children:c.key})]},c.id)),m("p",{className:"px-2 pt-2 text-xs leading-snug text-muted-foreground",children:["A project is a GitHub repo. Personal holds your life; Internals holds ",o?.assistant??"the assistant","\u2019s own workings."]})]})}function ME(){let e=nt(),t=ds(),n=en(),r=fs(),o=$E(),{data:s,error:i}=We(()=>e.call("tasks.today",{}),[e]);if(!s||!t)return l(Oe,{children:i||"Loading\u2026"});let a=s.schedule.filter(u=>u.at>=r).slice(0,4);return m("div",{className:"space-y-6 p-4",children:[m("section",{className:"space-y-2",children:[m("h2",{className:"flex items-center gap-2 text-sm font-semibold",children:["Your move ",l("span",{className:"rounded-full bg-muted px-2 text-xs text-muted-foreground",children:s.yours.length}),l("button",{type:"button",className:"ml-auto cursor-pointer text-xs font-semibold text-timeline-accent",onClick:()=>n("today"),children:"Open Tasks"})]}),s.yours.length===0?l("p",{className:"text-sm text-muted-foreground",children:"Nothing needs you."}):null,l("ul",{className:"divide-y divide-border-hairline",children:s.yours.map(u=>m("li",{className:"flex items-center gap-2.5 py-2",children:[l("button",{type:"button","aria-label":`Mark ${u.title} done`,onClick:()=>o(u),className:"size-4 shrink-0 cursor-pointer rounded-full border-[1.5px] border-foreground/35 hover:border-foreground/70"}),l("button",{type:"button",onClick:()=>n("today",u.key),className:"min-w-0 flex-1 cursor-pointer truncate text-left text-sm font-medium",children:u.title}),l(De,{origin:u.origin,assistant:t.assistant,size:14}),l(Sa,{task:u,now:r})]},u.id))})]}),a.length?m("section",{className:"space-y-1.5",children:[l("h2",{className:"text-sm font-semibold",children:"Next up today"}),a.map(u=>m("button",{type:"button",onClick:()=>n("today",u.task.key),className:"grid w-full cursor-pointer grid-cols-[4rem_1rem_minmax(0,1fr)] items-center gap-2 py-1 text-left text-sm",children:[l("span",{className:"text-right text-xs tabular-nums text-muted-foreground",children:Ee(u.at,s.zone)}),l(Ht,{glyph:jr(u.task),className:"size-3.5 text-timeline-accent"}),l("span",{className:"truncate",children:u.task.title})]},`${u.task.id}-${u.at}`))]}):null,m("p",{className:"border-t border-border-hairline pt-3 text-xs leading-relaxed text-muted-foreground",children:[t.assistant," is handling ",s.onIt.length," and waiting on ",s.waiting.length===1?"one reply":`${s.waiting.length} replies`,".",s.waiting[0]?.whenText?` Next check: ${s.waiting[0].title}, ${s.waiting[0].whenText}.`:""]})]})}function $s(e){let t=e?.nickname?.trim(),n=e?.name.trim();return t||(n&&n!=="Orbit"?n:"your moonlet")}function Is(){let e=J(),[t,n]=_(null),[r,o]=_(null),s=q(()=>{e.call("config.state",null).then(i=>{n(i),o(null)},i=>o(i instanceof Error?i.message:String(i)))},[e]);return K(s,[s]),ke("config",s),{rpc:e,state:t,error:r,refetch:s}}function DE(e,t){let n=URL.createObjectURL(new Blob([t],{type:"application/toml"})),r=document.createElement("a");r.href=n,r.download=e,r.click(),setTimeout(()=>URL.revokeObjectURL(n),1e3)}function FE(e){let t=document.createElement("input");t.type="file",t.accept=".toml,text/plain",t.onchange=()=>{t.files?.[0]?.text().then(e)},t.click()}function zE({at:e,by:t}){return e?m("span",{className:"text-xs text-muted-foreground",children:["Last changed ",new Date(e).toLocaleString(),t?` by ${t}`:""]}):null}function Ia(){let{state:e}=Is(),t=$s(e?.prefs.identity);return t==="your moonlet"?"Your moonlet":t}var NO=256,AO=.85,CO=[["image/webp","webp"],["image/png","png"],["image/jpeg","jpg"]],lo=class extends Error{};function TO(e,t,n=NO){let r=Math.min(e,t);return{x:Math.floor((e-r)/2),y:Math.floor((t-r)/2),side:r,edge:Math.min(r,n)}}var Xm=e=>Math.ceil(e/1024);async function KE(e){let t=new Uint8Array(await e.arrayBuffer()),n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(n)}var XE={decode:e=>createImageBitmap(e,{imageOrientation:"from-image"}),encode:(e,t,n)=>new Promise((r,o)=>{let s=document.createElement("canvas");s.width=t.edge,s.height=t.edge;let i=s.getContext("2d");if(!i){o(new lo("This browser can't shrink pictures. Choose one of at most 128 KB."));return}n==="image/jpeg"&&(i.fillStyle="#fff",i.fillRect(0,0,t.edge,t.edge)),i.imageSmoothingQuality="high",i.drawImage(e,t.x,t.y,t.side,t.side,0,0,t.edge,t.edge),s.toBlob(a=>a?r(a):o(new lo("The picture couldn't be saved smaller.")),n,AO)})};async function BE(e,t){if(e.type==="image/svg+xml"||/\.svg$/i.test(e.name)){if(e.size>131072)throw new lo(`An SVG avatar is at most ${Xm(131072)} KB, and an SVG can't be shrunk (${e.name} is ${Xm(e.size)} KB).`);return{name:"avatar.svg",base64:await KE(e)}}let n;try{n=await t.decode(e)}catch{throw new lo(`${e.name} isn't a picture this browser can open. Choose a PNG, JPEG, WebP or SVG.`)}try{let r=TO(n.width,n.height);for(let[o,s]of CO){let i=await t.encode(n,r,o);if(i.type===o&&i.size>0&&i.size<=131072)return{name:`avatar.${s}`,base64:await KE(i)}}throw new lo(`${e.name} couldn't be made smaller than ${Xm(131072)} KB. Try a simpler picture.`)}finally{n.close()}}var RO=[["orbit","In your moonlet's conversation"],["work","On the conversations it starts"]],$O="image/png,image/jpeg,image/webp,image/svg+xml,.png,.jpg,.jpeg,.webp,.svg";function UE({avatar:e,onChange:t,shrink:n=r=>BE(r,XE)}){let r=J(),[o,s]=_(null),i=Y({}),a=(u,c)=>{s({which:u,text:"Shrinking the picture\u2026",failed:!1}),n(c).then(d=>r.call("config.avatarFromUpload",d)).then(d=>{if(d.url){let p=d.url;t(f=>({...f,[u]:p})),s(null)}else s({which:u,text:d.problem??"The picture was refused.",failed:!0})},d=>s({which:u,text:d instanceof Error?d.message:String(d),failed:!0}))};return l("div",{className:"flex flex-wrap gap-6",children:RO.map(([u,c])=>m("div",{className:"flex items-center gap-3",children:[l(oc,{url:e[u],label:c,size:48}),m("div",{className:"flex flex-col gap-1",children:[l("span",{className:"font-medium",children:c}),m("div",{className:"flex gap-2",children:[l("input",{ref:d=>{i.current[u]=d},type:"file",accept:$O,hidden:!0,"aria-label":`Picture for ${c}`,onChange:d=>{let p=d.currentTarget.files?.[0];d.currentTarget.value="",p&&a(u,p)}}),l(R,{size:"sm",variant:"secondary",disabled:o?.which===u&&!o.failed,onClick:()=>i.current[u]?.click(),children:e[u]?"Replace\u2026":"Choose\u2026"}),l(R,{size:"sm",variant:"ghost",disabled:!e[u],onClick:()=>{s(null),t(({[u]:d,...p})=>p)},children:"Clear"})]}),o?.which===u&&l("p",{role:o.failed?"alert":"status",className:o.failed?"text-xs text-destructive":"text-xs text-muted-foreground",children:o.text})]})]},u))})}function Ps(){let{rpc:e,state:t,error:n,refetch:r}=Is(),o=Y(null),s=Y(0),i=Y(Promise.resolve()),[a,u]=_(null),[c,d]=_(null);ot(()=>{t&&s.current===0&&(o.current={prefs:t.prefs,base:t.prefsBase})},[t]);let p=q(f=>(s.current+=1,i.current=i.current.then(async()=>{try{let h=o.current;if(!h)return;let g=f(h.prefs);if(JSON.stringify(g)===JSON.stringify(h.prefs))return;await e.call("config.savePrefs",{prefs:g,base:h.base});let x=await e.call("config.state",null);o.current={prefs:x.prefs,base:x.prefsBase},u(null),d(Date.now())}catch(h){u(h instanceof Error?h.message:String(h))}finally{s.current-=1,r()}}),i.current),[e,r]);return{rpc:e,state:t,error:n,refetch:r,save:p,problem:a,savedAt:c}}function Hu({problem:e,savedAt:t}){return e?l("p",{role:"alert",className:"text-xs text-destructive",children:e}):t===null?null:l("p",{role:"status",className:"text-xs text-muted-foreground",children:"Saved. Your moonlet uses it from now on."})}function Vu({label:e,value:t,onCommit:n,multiline:r=!1,rows:o=3,placeholder:s,className:i=""}){let[a,u]=_(t),c=Y(!1),d=Y(t);K(()=>{d.current=t,c.current||u(t)},[t]);let p=()=>{c.current=!1,!(a===t&&a===d.current)&&(d.current=a,n(a))};return r?l("textarea",{"aria-label":e,rows:o,placeholder:s,className:`w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm leading-relaxed outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 ${i}`,value:a,onFocus:()=>{c.current=!0},onChange:f=>u(f.target.value),onBlur:p}):l(le,{"aria-label":e,placeholder:s,className:`h-8 w-64 text-sm ${i}`,value:a,onFocus:()=>{c.current=!0},onChange:f=>u(f.target.value),onBlur:p,onKeyDown:f=>{f.key==="Enter"&&f.currentTarget.blur()}})}function IO(e,t,n){let r={...e};return n.trim()||t==="name"?r[t]=n:delete r[t],r}function HE(){let{state:e,error:t,save:n,problem:r,savedAt:o}=Ps();if(t)return l("p",{className:"text-sm text-destructive",children:t});if(!e)return l("p",{className:"text-sm text-muted-foreground",children:"Loading\u2026"});let s=e.prefs.identity,i=$s(s),a=(u,c,d,p={})=>l(Ei,{label:c,description:d,controlPlacement:p.multiline?"below":"inline",children:l(Vu,{label:c,multiline:p.multiline,rows:2,value:s[u]??"",onCommit:f=>{n(h=>({...h,identity:IO(h.identity,u,f)}))}})});return m("div",{className:"space-y-10",children:[l(Hu,{problem:r,savedAt:o}),l(ct,{title:"Identity",description:`How ${i==="your moonlet"?"your moonlet":i} introduces itself in chat, commits and mail.`,children:m("div",{className:"space-y-5",children:[a("name","Name","Its formal name, on commits and as the sender in mail."),a("nickname","Nickname","What you call it day to day. Empty: the name."),a("pronouns","Pronouns",void 0),a("signature","Signature","One line under its sign-off in mail. Empty: the nickname, else the name."),a("bio","Bio","One or two sentences, for introductions.",{multiline:!0})]})}),l(ct,{title:"Pictures",description:"Shown beside its messages. PNG, JPEG or WebP is cropped square and shrunk to 256 pixels; an SVG may be up to 128 KB.",children:l(UE,{avatar:e.prefs.avatar,onChange:u=>{n(c=>({...c,avatar:u(c.avatar)}))}})}),l(ct,{title:"Accounts",description:"Its own accounts. Change the account itself first, then update it here. Without an email address it doesn't commit or send mail.",children:m("div",{className:"space-y-5",children:[a("email","Email address","Where it commits and sends mail from."),a("github","GitHub username",void 0)]})}),l(ct,{title:"Owner",children:a("owner","Works for",'Who it works for, by name. Empty: "your owner". Only you can change this.')})]})}var Os=e=>typeof e=="string"?e:e.text,VE=e=>typeof e=="string"?null:e.until,ZE=(e,t)=>Os(e)===Os(t)&&VE(e)===VE(t);function WE(e,t,n){let r=e[n];return r!==void 0&&ZE(r,t)?n:e.findIndex(o=>ZE(o,t))}function PO(e,t){return new Date(e).toLocaleString("en-US",{timeZone:t,weekday:"short",day:"numeric",month:"short",year:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}function OO({r:e,n:t,zone:n,onChange:r,onRemove:o}){let s=J(),[i,a]=_(!1),[u,c]=_(""),[d,p]=_(null),f=typeof e=="string"?null:e.until,h=f!==null&&Date.parse(f)<=Date.now();return m("li",{className:"flex flex-col gap-2 py-2.5 text-sm first:pt-0 last:pb-0",children:[m("div",{className:"flex items-start gap-3",children:[l("span",{className:"w-5 shrink-0 pt-px text-right text-xs tabular-nums text-muted-foreground",children:t}),m("div",{className:"min-w-0 flex-1",children:[l("p",{className:h?"text-muted-foreground line-through":"text-foreground",children:Os(e)}),f!==null&&l("p",{className:`mt-0.5 text-xs ${h?"text-destructive":"text-muted-foreground"}`,children:`${h?"Lapsed":"Until"} ${PO(f,n)}`})]}),f!==null&&l(R,{size:"sm",variant:h?"secondary":"ghost",onClick:()=>a(!i),children:"Renew"}),l(R,{size:"sm",variant:"ghost",onClick:o,children:"Remove"})]}),i&&m("div",{className:"ml-8 flex flex-wrap items-center gap-2 text-xs",children:[l(le,{type:"datetime-local",className:"w-56",value:u,onChange:g=>c(g.target.value)}),m("span",{className:"text-muted-foreground",children:["in ",n]}),l(R,{size:"sm",variant:"secondary",disabled:!u,onClick:()=>{s.call("config.untilInstant",{at:u}).then(g=>{if(g.until===null)return p(g.problem);p(null),a(!1),r({text:Os(e),until:g.until})},g=>p(g instanceof Error?g.message:String(g)))},children:"Until then"}),l(R,{size:"sm",variant:"ghost",onClick:()=>{a(!1),r(Os(e))},children:"No end"}),d&&l("span",{className:"text-destructive",children:d})]})]})}function jE(){let{state:e,error:t,save:n,problem:r,savedAt:o}=Ps(),[s,i]=_("");if(t)return l("p",{className:"text-sm text-destructive",children:t});if(!e)return l("p",{className:"text-sm text-muted-foreground",children:"Loading\u2026"});let a=e.prefs.instructions,u=()=>{let c=s.trim();c&&(i(""),n(d=>({...d,instructions:[...d.instructions,c]})))};return m("div",{className:"space-y-10",children:[l(Hu,{problem:r,savedAt:o}),l(ct,{title:"Tone",description:"How it talks to you. {{owner}} stands for your name.",children:l(Vu,{label:"Tone and persona",multiline:!0,rows:6,value:e.prefs.tone,onCommit:c=>{n(d=>({...d,tone:c}))}})}),l(ct,{title:"Standing instructions",description:"Rules it always follows. When it adds one itself, you see it here.",children:m("div",{className:"space-y-4",children:[a.length===0?l("p",{className:"text-sm text-muted-foreground",children:"None yet."}):l("ol",{className:"divide-y divide-border",children:a.map((c,d)=>l(OO,{r:c,n:d+1,zone:e.zone,onChange:p=>{n(f=>{let h=WE(f.instructions,c,d);return{...f,instructions:f.instructions.map((g,x)=>x===h?p:g)}})},onRemove:()=>{n(p=>{let f=WE(p.instructions,c,d);return{...p,instructions:p.instructions.filter((h,g)=>g!==f)}})}},`${d}-${Os(c)}`))}),m("div",{className:"flex gap-2",children:[l(le,{"aria-label":"New instruction",placeholder:"Never book anything before 9am",value:s,onChange:c=>i(c.target.value),onKeyDown:c=>{c.key==="Enter"&&u()}}),l(R,{size:"sm",variant:"outline",disabled:!s.trim(),onClick:u,children:"Add"})]})]})})]})}function QE(){let e=0;return{async take(t){let n=++e,r=await t;return n===e?{current:!0,value:r}:{current:!1}},cancel(){e++}}}var qE=[{id:"you",title:"About you",lead:"Your moonlet works for you. Tell it who you are; it keeps the rest in memory as you go."},{id:"reach",title:"Reaching you",lead:"Your moonlet talks with you in its conversation in Moonlet. Say where else it should put things, and when to leave you alone."},{id:"touchpoints",title:"Your day",lead:'When your moonlet comes to you on its own. To change one later, just tell your moonlet ("move the morning digest to 8"), or change it in Settings \u2192 your moonlet \u2192 Daily rhythm.'},{id:"sign-ins",title:"Machine sign-ins",lead:"The keys your moonlet's machines sign in with. Both can wait: add them later in Settings, the 1Password key under Integrations and the Claude Code token under Providers."}],GE=["Text message (SMS)","Voice call","WhatsApp","Telegram","Signal","iMessage","Slack","Discord"],LO=[["mon","Monday"],["tue","Tuesday"],["wed","Wednesday"],["thu","Thursday"],["fri","Friday"],["sat","Saturday"],["sun","Sunday"]],Ls=e=>e instanceof Error?e.message:String(e);function Hm(){let e=J(),[t,n]=_(null),[r,o]=_(null),s=q(()=>{e.call("welcome.state",null).then(i=>{n(i),o(null)},i=>o(i instanceof Error?i.message:String(i)))},[e]);return K(s,[s]),ke("config",s),{rpc:e,state:t,error:r,refetch:s}}function Bm({label:e,hint:t,children:n}){return m("label",{className:"flex flex-col gap-1 text-sm",children:[l("span",{className:"font-medium",children:e}),n,t&&l("span",{className:"text-xs text-muted-foreground",children:t})]})}function on({label:e,hint:t,checked:n,onChange:r}){return m("label",{className:"flex items-start gap-2 text-sm",children:[l("input",{type:"checkbox",className:"mt-1",checked:n,onChange:o=>r(o.target.checked)}),m("span",{children:[e,t&&l("span",{className:"block text-xs text-muted-foreground",children:t})]})]})}function Vm(e,t,n,r){let[o,s]=_([]),[i,a]=_(!1),[u,c]=_(null),[d,p]=_(!1);return{save:g=>{p(!0),c(null),e.call("welcome.save",{step:t,values:g}).then(x=>{let b=(x.handover??[]).some(v=>v.state==="failed");s(x.lines),a(b),p(!1),n(),b||r()},x=>{c(Ls(x)),p(!1)})},retry:()=>{p(!0),c(null),e.call("welcome.handover",null).then(g=>{s(g.lines),a(g.handover.some(x=>x.state==="failed")),p(!1)},g=>{c(Ls(g)),p(!1)})},lines:o,failed:i,problem:u,busy:d}}function Wu({onBack:e,onSkip:t,onContinue:n,busy:r,problem:o,label:s="Save and continue",settings:i=!1}){return m("div",{className:"mt-6 flex flex-col gap-2",children:[o&&l("p",{className:"text-sm text-destructive",children:o}),m("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e&&l(R,{variant:"ghost",className:"mr-auto",onClick:e,children:"Back"}),!i&&l(R,{variant:"ghost",onClick:t,children:"Skip for now"}),l(R,{disabled:r,onClick:n,children:r?"Saving\u2026":i?"Save":s})]})]})}function Um(e){return[e.name,...[e.admin,e.country].filter(t=>!!t&&t!==e.name)].join(", ")}function MO({city:e,place:t,zone:n,rpc:r,onCity:o,onPlace:s}){let[i,a]=_(null),[u,c]=_(!1),[d,p]=_(null),[f,h]=_(!1),g=Lt(()=>QE(),[]),x=t!==void 0&&(e.trim()===t.name||(i?.includes(t)??!1));return K(()=>{let b=e.trim();if(!b||x)return;let v=setTimeout(()=>{c(!0),p(null),g.take(r.call("welcome.places",{query:b})).then(w=>{w.current&&(a(w.value.places),s(w.value.places[0]),h(!1),c(!1))},w=>{p(Ls(w)),c(!1)})},600);return()=>clearTimeout(v)},[e,x,r,s,g]),m(Bm,{label:"Where you live",hint:"A city. The weather in your morning digest, anything local, and your time zone come from it.",children:[l(le,{value:e,onChange:b=>{o(b.target.value),g.cancel(),a(null),h(!1),c(!1),t&&b.target.value.trim()!==t.name&&s(void 0)}}),u?l("span",{className:"text-xs text-muted-foreground",children:"Looking it up\u2026"}):d?m("span",{className:"text-xs text-destructive",children:[d,". Your moonlet keeps its time zone, ",n,"; change it in Settings \u2192 General if it's wrong."]}):t?m("span",{className:"text-xs text-muted-foreground",children:[Um(t)," \xB7 ",t.timezone,i&&i.length>1&&!f&&m(he,{children:[" \xB7 ",l("button",{type:"button",className:"underline",onClick:()=>h(!0),children:"Not this one?"})]})]}):e.trim()&&i&&i.length===0?m("span",{className:"text-xs text-muted-foreground",children:["No place of that name; your moonlet keeps the city as you wrote it and its time zone, ",n,"."]}):m("span",{className:"text-xs text-muted-foreground",children:["Time zone now: ",n,"."]}),f&&i&&l("select",{className:"h-9 rounded-md border border-input bg-background px-2 text-sm",value:t?i.indexOf(t):0,onChange:b=>{s(i[Number(b.target.value)]),h(!1)},children:i.map((b,v)=>m("option",{value:v,children:[Um(b)," \xB7 ",b.timezone]},`${b.latitude},${b.longitude}`))})]})}function DO({state:e,rpc:t,refetch:n,onDone:r,onSkip:o,onBack:s}){let[i,a]=_(e.record.you),{save:u,problem:c,busy:d}=Vm(t,"you",n,r),p=(h,g)=>a(x=>({...x,[h]:g.trim()?g:void 0})),f=q(h=>a(g=>({...g,place:h})),[]);return m(he,{children:[m("div",{className:"flex flex-col gap-4",children:[l(Bm,{label:"Your name",hint:"What your moonlet calls you. Without one it says \u201Cyour owner\u201D.",children:l(le,{autoFocus:!0,value:i.name??"",onChange:h=>p("name",h.target.value)})}),l(MO,{city:i.city??"",place:i.place,zone:e.zone,rpc:t,onCity:h=>p("city",h),onPlace:f}),l(Bm,{label:"Your email address",hint:"Where your moonlet mails you when you want that, and how it knows mail from you is yours.",children:l(le,{value:i.email??"",onChange:h=>p("email",h.target.value)})})]}),l(Wu,{onBack:s,onSkip:o,busy:d,problem:c,onContinue:()=>u({you:{...i.name?{name:i.name}:{},...i.city?{city:i.city}:{},...i.city&&i.place?{place:i.place}:{},...i.email?{email:i.email}:{}}})})]})}function Zm({settings:e=!1,state:t,rpc:n,refetch:r,onDone:o,onSkip:s,onBack:i}){let[a,u]=_(t.record.reach),[c,d]=_(a.quiet_from!==void 0),[p,f]=_(""),{save:h,problem:g,busy:x}=Vm(n,"reach",r,o),b=a.other??[],v=b.filter(y=>!GE.includes(y)),w=(y,T)=>u({...a,other:T?[...b.filter(N=>N!==y),y]:b.filter(N=>N!==y)}),C=()=>{let y=p.trim().slice(0,60);if(!y||b.some(T=>T.toLowerCase()===y.toLowerCase()))return f("");b.length>=10||(u({...a,other:[...b,y]}),f(""))};return m(he,{children:[m("div",{className:"flex flex-col gap-4",children:[l(on,{label:"Put decisions and anything waiting on me in my Moonlet inbox",hint:"One item each, with a link, in your Moonlet inbox; your moonlet still says a line in its conversation.",checked:a.inbox,onChange:y=>u({...a,inbox:y})}),l(on,{label:"Mail me the digests too",hint:t.record.you.email?`To ${t.record.you.email}, from your moonlet's own mailbox.`:"Needs your email address (About you) and a station with mail.",checked:a.mail,onChange:y=>u({...a,mail:y})}),l(on,{label:"Quiet hours",hint:"Nothing that can wait is sent between them (in your time zone); it comes after.",checked:c,onChange:d}),c&&m("div",{className:"ml-6 flex flex-wrap items-center gap-2 text-sm",children:[l("span",{children:"From"}),l(le,{type:"time",className:"w-32",value:a.quiet_from??"22:00",onChange:y=>u({...a,quiet_from:y.target.value})}),l("span",{children:"to"}),l(le,{type:"time",className:"w-32",value:a.quiet_to??"07:00",onChange:y=>u({...a,quiet_to:y.target.value})})]}),m("section",{className:"flex flex-col gap-2 rounded-md border p-3",children:[l("span",{className:"text-sm font-medium",children:"Other ways"}),l("span",{className:"text-xs text-muted-foreground",children:"How else you'd want your moonlet to reach you. None of these is connected yet: your moonlet reaches you in Moonlet, and by mail when you ask for it. It notes what you'd want, says so when it comes up, and never claims to have sent something a way it can't."}),l("div",{className:"grid grid-cols-2 gap-1",children:GE.map(y=>l(on,{label:y,checked:b.includes(y),onChange:T=>w(y,T)},y))}),v.length>0&&l("ul",{className:"flex flex-wrap gap-2 text-xs",children:v.map(y=>m("li",{className:"flex items-center gap-1 rounded-full border px-2 py-0.5",children:[y,l("button",{type:"button",className:"text-muted-foreground","aria-label":`Remove ${y}`,onClick:()=>w(y,!1),children:"\xD7"})]},y))}),m("div",{className:"flex items-center gap-2",children:[l(le,{className:"max-w-xs",placeholder:"Something else: Matrix, a pager, \u2026",value:p,onChange:y=>f(y.target.value),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),C())}}),l(R,{size:"sm",variant:"secondary",disabled:!p.trim()||b.length>=10,onClick:C,children:"Add"})]})]})]}),l(Wu,{settings:e,onBack:i,onSkip:s,busy:x,problem:g,onContinue:()=>h({reach:{inbox:a.inbox,mail:a.mail,...c?{quiet_from:a.quiet_from??"22:00",quiet_to:a.quiet_to??"07:00"}:{},other:b}})})]})}function Wm({settings:e=!1,state:t,rpc:n,refetch:r,onDone:o,onSkip:s,onBack:i}){let[a,u]=_(t.record.touchpoints),{save:c,problem:d,busy:p}=Vm(n,"touchpoints",r,o),f=h=>u({...a,morning:{...a.morning,...h}});return m(he,{children:[m("div",{className:"flex flex-col gap-3",children:[m("p",{className:"text-xs text-muted-foreground",children:["Times are in ",t.zone,". Each becomes a routine your moonlet keeps, and your moonlet changes or drops it when you ask."]}),m("section",{className:"flex flex-col gap-2 rounded-md border p-3",children:[m("div",{className:"flex items-center gap-3",children:[l(on,{label:"Morning digest",checked:a.morning.on,onChange:h=>f({on:h})}),l("span",{className:"text-sm",children:"at"}),l(le,{type:"time",className:"w-32",value:a.morning.at,onChange:h=>f({at:h.target.value})})]}),a.morning.on&&m("div",{className:"ml-6 flex flex-col gap-1",children:[l(on,{label:"Today's weather",hint:t.record.you.place?`In ${Um(t.record.you.place)}.`:t.record.you.city?`In ${t.record.you.city}.`:"Give your city under About you, or your moonlet asks once.",checked:a.morning.weather,onChange:h=>f({weather:h})}),l(on,{label:"What's on my calendar",checked:a.morning.calendar,onChange:h=>f({calendar:h})}),l(on,{label:"New mail waiting on me",checked:a.morning.mail,onChange:h=>f({mail:h})}),l(on,{label:"Unfinished tasks due today, and what's waiting on me",checked:a.morning.loops,onChange:h=>f({loops:h})})]})]}),m("section",{className:"flex flex-wrap items-center gap-3 rounded-md border p-3",children:[l(on,{label:"End of day wrap-up",hint:"What got done, what's waiting on you, what's first tomorrow.",checked:a.evening.on,onChange:h=>u({...a,evening:{...a.evening,on:h}})}),l("span",{className:"text-sm",children:"at"}),l(le,{type:"time",className:"w-32",value:a.evening.at,onChange:h=>u({...a,evening:{...a.evening,at:h.target.value}})})]}),m("section",{className:"flex flex-wrap items-center gap-3 rounded-md border p-3",children:[l(on,{label:"Weekly review",hint:"The week's outcomes, what stalled, next week's first things.",checked:a.weekly.on,onChange:h=>u({...a,weekly:{...a.weekly,on:h}})}),l("span",{className:"text-sm",children:"on"}),l("select",{className:"h-9 rounded-md border border-input bg-background px-2 text-sm",value:a.weekly.day,onChange:h=>u({...a,weekly:{...a.weekly,day:h.target.value}}),children:LO.map(([h,g])=>l("option",{value:h,children:g},h))}),l("span",{className:"text-sm",children:"at"}),l(le,{type:"time",className:"w-32",value:a.weekly.at,onChange:h=>u({...a,weekly:{...a.weekly,at:h.target.value}})})]})]}),l(Wu,{settings:e,onBack:i,onSkip:s,busy:p,problem:d,onContinue:()=>c({touchpoints:a})})]})}function YE({which:e,label:t,hint:n,stored:r,rpc:o,refetch:s}){let[i,a]=_(""),[u,c]=_(null),[d,p]=_(null),[f,h]=_(!1),g=b=>{p(null),o.call("welcome.secret",{which:e,value:b}).then(v=>{c(v.line),h((v.handover??[]).some(w=>w.state==="failed")),a(""),s()},v=>p(Ls(v)))},x=()=>{p(null),o.call("welcome.handover",null).then(b=>{c(b.lines.join(" ")),h(b.handover.some(v=>v.state==="failed"))},b=>p(Ls(b)))};return m("div",{className:"flex flex-col gap-1 rounded-md border p-3 text-sm",children:[m("div",{className:"flex items-center gap-2",children:[l("span",{className:"font-medium",children:t}),l("span",{className:V("text-xs",r?"text-muted-foreground":"text-destructive"),children:r?"stored":"not set"})]}),l("span",{className:"text-xs text-muted-foreground",children:n}),m("div",{className:"flex items-center gap-2",children:[l(le,{type:"password",className:"max-w-md",placeholder:r?"Paste a new one to replace it":"Paste it here",value:i,onChange:b=>a(b.target.value)}),l(R,{size:"sm",variant:"secondary",disabled:!i.trim(),onClick:()=>g(i),children:"Store"}),r&&l(R,{size:"sm",variant:"ghost",onClick:()=>g(null),children:"Clear"})]}),d?l("span",{className:"text-xs text-destructive",children:d}):u&&l("span",{className:V("text-xs",f?"text-destructive":"text-muted-foreground"),children:u}),f&&l("div",{children:l(R,{size:"sm",variant:"secondary",onClick:x,children:"Try again"})})]})}function FO({state:e,rpc:t,refetch:n,onDone:r,onBack:o}){let[s,i]=_(null),[a,u]=_(!1),c=()=>{u(!0),i(null),t.call("welcome.finish",null).then(()=>{u(!1),n(),r()},d=>{i(Ls(d)),u(!1)})};return m(he,{children:[m("div",{className:"flex flex-col gap-3",children:[l(YE,{which:"claude",label:"Claude Code key",hint:"What your moonlet uses to sign in to Claude on its machines. Run claude setup-token on your computer and paste what it prints here.",stored:e.secrets.claude,rpc:t,refetch:n}),l(YE,{which:"onepassword",label:"1Password key (optional)",hint:"Only if your moonlet's own logins live in 1Password: a key for a 1Password service account that can read only a vault named Orbit. Your moonlet's machine uses it to fetch those logins; your moonlet never sees it.",stored:e.secrets.onepassword,rpc:t,refetch:n}),l("p",{className:"text-xs text-muted-foreground",children:"Continuing tells your moonlet, in its conversation, what you saved and what you skipped. With no conversation yet, it's told once its conversation starts."})]}),l(Wu,{onBack:o,onSkip:c,busy:a,problem:s,label:"Continue",onContinue:c}),s&&l("div",{className:"mt-2 flex justify-end",children:l(R,{variant:"ghost",onClick:r,children:"Continue anyway"})})]})}function Zu(e){return function({onContinue:n,onBack:r}){let{rpc:o,state:s,error:i,refetch:a}=Hm();return i?m("div",{className:"flex flex-col items-start gap-3 text-sm",children:[l("p",{role:"alert",className:"text-destructive",children:i}),l(R,{onClick:n,children:"Continue"})]}):s?l(e,{state:s,rpc:o,refetch:a,onDone:n,onSkip:n,onBack:r}):l("p",{className:"text-sm text-muted-foreground",children:"Loading\u2026"})}}var JE={you:Zu(DO),reach:Zu(Zm),touchpoints:Zu(Wm),"sign-ins":Zu(FO)};function eN(){let{rpc:e,state:t,error:n,refetch:r}=Hm(),[o,s]=_("");if(n)return l("p",{role:"alert",children:n});if(!t)return l("p",{className:"text-sm text-muted-foreground",children:"Loading\u2026"});let i={state:t,rpc:e,refetch:r,onDone:()=>s("Saved."),onSkip:()=>{},onBack:null,settings:!0};return m("div",{className:"space-y-10",children:[l(ct,{title:"How it reaches you",description:"Where it puts what's waiting on you, and when it stays quiet.",children:l("section",{"aria-label":"How it reaches you",children:l(Zm,{...i})})}),l(ct,{title:"Daily rhythm",description:"Check-ins it sends you. Times are in your time zone.",children:l("section",{"aria-label":"Daily rhythm",children:l(Wm,{...i})})}),o&&l("p",{role:"status",className:"text-xs text-muted-foreground",children:o})]})}function tN(){let e=J(),t=q(async()=>({kinds:await e.call("userland.kinds",null),artifacts:await e.call("userland.list",{})}),[e]),[n,r]=_(null),[o,s]=_(null),i=Y(!1),[a,u]=_(!1),[c,d]=_(null),[p,f]=_(""),h=q(()=>{t().then(x=>{r(x),s(null)},x=>s(x instanceof Error?x.message:String(x)))},[t]);K(()=>{h();let x=setInterval(()=>{i.current||h()},3e3);return()=>clearInterval(x)},[h]);let g=async x=>{if(!i.current){i.current=!0,u(!0),s(null);try{await x(),f("Saved. Machine delivery may still be waiting."),d(null),r(await t())}catch(b){s(b instanceof Error?b.message:String(b))}finally{i.current=!1,u(!1)}}};return m(ct,{title:"What it taught itself",description:"Tools and notes it saved to help it work.",children:[m("div",{className:"flex flex-col divide-y divide-border text-sm",children:[o&&l("p",{role:"alert",className:"pb-2.5 text-destructive",children:o}),!n&&l("p",{className:"text-muted-foreground",children:"Loading\u2026"}),n?.kinds.map(x=>m("div",{className:"flex flex-wrap items-center gap-3 py-2.5 first:pt-0 last:pb-0",children:[m("span",{className:"flex-1",children:[x.title,x.waiting?" \xB7 Waiting for delivery":""]}),m(R,{disabled:a,size:"sm",onClick:()=>{g(()=>e.call("userland.setKind",{kind:x.id,off:!x.off,why:"Changed in Settings"}))},children:[x.off?"Turn on":"Turn off"," ",x.title]})]},x.id)),n?.artifacts.length===0&&l("p",{className:"py-2.5 text-muted-foreground first:pt-0 last:pb-0",children:"No saved items."}),n?.artifacts.map(x=>{let b=`${x.kind}/${x.name}`,v=x.switches.some(w=>w.holder==="owner");return m("div",{className:"flex flex-wrap items-center gap-2 py-2.5 first:pt-0 last:pb-0",children:[m("span",{className:"flex-1",children:[b," \xB7 ",x.state,x.kindOff?" \xB7 Kind turned off":""]}),m(R,{disabled:a,size:"sm",onClick:()=>{g(()=>v?e.call("userland.enable",{artifact:b,holder:"owner"}):e.call("userland.disable",{artifact:b,why:"Turned off in Settings"}))},children:[v?"Turn on":"Turn off"," ",x.name]}),x.retiredAt===null?m(R,{disabled:a,size:"sm",variant:"secondary",onClick:()=>{g(()=>e.call("userland.retire",{artifact:b,why:"Retired in Settings"}))},children:["Retire ",x.name]}):m(R,{disabled:a,size:"sm",variant:"secondary",onClick:()=>d(b),children:["Delete ",x.name,"\u2026"]}),x.switches.map(w=>m("span",{className:"w-full text-xs text-muted-foreground",children:[w.holder==="breaker"?"Automatic pause":w.holder==="orbit"?"Assistant pause":"Your pause",": ",w.why]},w.holder)),c===b&&m("div",{className:"flex flex-wrap items-center gap-2",children:[l("span",{children:"Delete this item and its saved versions? This cannot be undone."}),l(R,{disabled:a,size:"sm",variant:"destructive",onClick:()=>{g(()=>e.call("userland.purge",{artifact:b}))},children:"Delete permanently"}),l(R,{size:"sm",variant:"ghost",onClick:()=>d(null),children:"Cancel"})]})]},b)})]}),p&&l("p",{role:"status",className:"mt-2 text-xs text-muted-foreground",children:p})]})}function nN(){let{rpc:e,state:t,error:n,refetch:r}=Ps(),[o,s]=_(null),[i,a]=_(null),[u,c]=_(!1);if(n)return l("p",{className:"text-sm text-destructive",children:n});if(!t)return l("p",{className:"text-sm text-muted-foreground",children:"Loading\u2026"});let d=t.history.prefs,p=f=>a(f instanceof Error?f.message:String(f));return m("div",{className:"space-y-10",children:[i&&l("p",{role:"status",className:"text-xs text-muted-foreground",children:i}),l(ct,{title:"Changes",description:"Every saved version of its profile, personality and models, newest first, by you or by it.",children:d.length===0?l("p",{className:"text-sm text-muted-foreground",children:"No changes yet."}):l("ul",{className:"divide-y divide-border",children:d.map(f=>m("li",{className:"flex flex-col gap-2 py-2.5 text-sm first:pt-0 last:pb-0",children:[m("div",{className:"flex items-center gap-3",children:[l("span",{className:"w-44 shrink-0 text-xs tabular-nums text-muted-foreground",children:new Date(f.at).toLocaleString()}),l("span",{className:"min-w-0 flex-1 truncate text-foreground",children:f.by}),l(R,{size:"sm",variant:"ghost",onClick:()=>o?.id===f.id?s(null):void e.call("config.historyText",{id:f.id}).then(h=>s({id:f.id,text:h.text}),p),children:o?.id===f.id?"Hide":"View"})]}),o?.id===f.id&&l("pre",{className:"max-h-80 overflow-auto rounded-md border border-border bg-muted/30 p-3 text-xs whitespace-pre-wrap",children:o.text})]},f.id))})}),l(tN,{}),l(ct,{title:"Copy or start over",children:m("div",{className:"space-y-5",children:[l(Ei,{label:"Export or import",description:"Its profile, personality and models as one prefs.toml file.",children:m("div",{className:"flex items-center gap-2",children:[l(R,{size:"sm",variant:"outline",onClick:()=>{e.call("config.exportPrefs",null).then(f=>DE("prefs.toml",f.text),p)},children:"Export"}),l(R,{size:"sm",variant:"outline",onClick:()=>FE(f=>{e.call("config.importPrefs",{text:f,base:t.prefsBase}).then(()=>{a("Imported and saved."),r()},p)}),children:"Import\u2026"})]})}),l(Ei,{label:"Reset personality",description:"Tone and standing instructions back to a new install's. The profile and models stay, and today's versions stay in Changes.",children:u?m("div",{className:"flex items-center gap-2",children:[l(R,{size:"sm",variant:"destructive",onClick:()=>{e.call("config.resetPrefs",{base:t.prefsBase}).then(()=>{c(!1),a("The tone and standing instructions are back to the defaults."),r()},f=>{c(!1),p(f)})},children:"Reset"}),l(R,{size:"sm",variant:"ghost",onClick:()=>c(!1),children:"Cancel"})]}):l(R,{size:"sm",variant:"outline",onClick:()=>c(!0),children:"Reset\u2026"})})]})})]})}function rN(){let e=Ie(),t=Y(0),n=Y(!1),r=Y(!1),o=J(),[s,i]=_(null),[a,u]=_(!1),[c,d]=_(null),p=q(()=>{r.current=!0;let h=++t.current,g=!0;return o.call("events.state",null).then(x=>{g&&h===t.current&&(i(x),d(null))},x=>{g&&h===t.current&&(i(null),d(x instanceof Error?x.message:String(x)))}).finally(()=>{r.current=!1}),()=>{g=!1}},[o]);K(()=>{let h=p(),g=setInterval(()=>{!n.current&&!r.current&&(h(),h=p())},3e3);return()=>{h(),clearInterval(g)}},[p]);let f=a||s?.pending===!0;return m("section",{className:"flex flex-col gap-2","aria-label":"Event service",children:[m("div",{className:"flex items-center justify-between gap-4",children:[l("label",{id:"event-service-label",htmlFor:"event-service-switch",className:"text-sm font-medium",children:"Event service"}),l("button",{id:"event-service-switch",type:"button",role:"switch","aria-labelledby":"event-service-label","aria-describedby":"event-service-status","aria-checked":s?.active??!1,disabled:!s||f,className:"relative h-6 w-11 shrink-0 rounded-full border bg-muted transition-colors aria-checked:bg-primary disabled:cursor-wait disabled:opacity-60",onClick:async()=>{if(!(!s||f||n.current)){n.current=!0,t.current++,u(!0),d(null);try{i(await o.call("events.switch",{active:!s.active}))}catch(h){d(h instanceof Error?h.message:String(h))}finally{n.current=!1,u(!1)}}},children:l("span",{className:`absolute top-0.5 h-4 w-4 rounded-full bg-background shadow transition-transform ${s?.active?"left-0.5 translate-x-5":"left-0.5"}`})})]}),l("p",{className:"text-sm text-muted-foreground",children:"Runs mail, notices and routine work on the station. Changing it asks for your approval."}),l("p",{id:"event-service-status",role:"status",className:"text-sm",children:f?"Waiting for your approval":s?`${s.active?"Running":"Stopped"} on the station`:"Reading station\u2026"}),s?.pending&&s.thread&&l("button",{type:"button",className:"text-left text-sm underline",onClick:()=>e.toThread(s.thread),children:"Open approval question"}),c&&l("p",{role:"alert",className:"text-sm text-destructive",children:c}),!c&&s?.message&&!f&&l("p",{className:"text-sm text-muted-foreground",children:s.message})]})}function oN(){let e=J(),[t,n]=_(!1),[r,o]=_(null);return m("section",{className:"flex flex-col gap-1 text-sm","aria-label":"First run",children:[l("p",{className:"text-muted-foreground",children:"Go through setup again, with your saved answers filled in. Each answer still saves where it lives here, and your moonlet's name and identity stay as they are."}),l("div",{children:l("button",{type:"button",className:"underline disabled:opacity-60",disabled:t,onClick:()=>{n(!0),o(null),e.call("welcome.reopen",null).then(()=>n(!1),s=>{o(s instanceof Error?s.message:String(s)),n(!1)})},children:t?"Opening setup\u2026":"Set up again"})}),r&&l("p",{role:"alert",className:"text-destructive",children:r})]})}var sN=["s3","gcs","azureblob","b2","drive","dropbox","onedrive","box","webdav","sftp","ftp","swift"];var zO={type:"s3",path:"",options:"",item:"",recipient:""};function KO(e){return e.match(/.{1,4}/g)?.join(" ")??e}function XO(e){let t={};for(let[n,r]of e.split(`
146
- `).entries()){let o=r.trim();if(!o)continue;let s=o.match(/^([^=\s]+)\s*=\s*(.*)$/);if(!s)throw new Error(`Store settings line ${n+1} needs the form name = value.`);t[s[1]]=s[2]}return t}function Pa({label:e,help:t,children:n}){let r=Ai(),o=`${r}-help`;return m("div",{className:"flex flex-col gap-1",children:[l("label",{htmlFor:r,className:"font-medium",children:e}),n(t?{id:r,"aria-describedby":o}:{id:r}),t&&l("p",{id:o,className:"text-xs text-muted-foreground",children:t})]})}function BO(e){return e?{type:e.type,path:e.path,options:Object.entries(e.options).map(([t,n])=>`${t} = ${n}`).join(`
147
- `),item:e.item??"",recipient:e.recipient}:zO}function iN(){let e=J(),[t,n]=_(null),[r,o]=_(null),[s,i]=_(null),[a,u]=_(!1),[c,d]=_(null),[p,f]=_(null),h=q(()=>{e.call("permissions.policy",null).then(b=>{n({base:b.base,backup:b.backup}),o(null)},b=>o(b instanceof Error?b.message:String(b)))},[e]);K(h,[h]),ke("config",h);let g=async(b,v,w)=>{u(!0),f(null),d(null);try{await e.call("permissions.edit",{base:b,section:"backup",value:v}),d(w),i(null),h()}catch(C){f(C instanceof Error?C.message:String(C))}finally{u(!1)}},x=t?.backup??null;return m("div",{className:"flex max-w-xl flex-col gap-3 text-sm",children:[l("p",{children:"Optional. Every night at 3:30, each prepared machine encrypts a copy of the assistant's files (OrbitData) and its deploy record to your OpenPGP key, then copies it to a storage location you own. Only you can open a copy, with the secret part of that key on your own computer. Backup stays off until you set a store."}),l("p",{role:"status",children:r?"Backup status is unavailable.":t?x?`On: nightly to ${x.type}: ${x.path}.`:"Off. No store set.":"Loading backup status\u2026"}),x&&m("dl",{className:"grid grid-cols-[max-content_1fr] gap-x-3 gap-y-1",children:[l("dt",{className:"text-muted-foreground",children:"Encrypted to"}),l("dd",{className:"break-all font-mono text-xs",children:x.fingerprint?KO(x.fingerprint):"a key this page can't read; check it with gpg --show-keys"}),l("dt",{className:"text-muted-foreground",children:"Credential"}),l("dd",{children:x.item?`vault item \u201C${x.item}\u201D (its contents are never shown)`:"no vault item named"})]}),t&&!s&&m("div",{className:"flex flex-wrap gap-2",children:[l(R,{variant:"secondary",disabled:a,onClick:()=>i({...BO(x),base:t.base}),children:x?"Change store":"Set up backup"}),x&&l(R,{variant:"secondary",disabled:a,onClick:()=>g(t.base,null,"Backup turned off. Review and apply sends it to machines."),children:"Turn off backup"})]}),s&&m("form",{className:"flex flex-col gap-3 rounded-md border p-3",onSubmit:b=>{b.preventDefault();let v;try{v=XO(s.options)}catch(y){f(y instanceof Error?y.message:String(y));return}let w=s.item.trim(),C={type:s.type,path:s.path.trim(),options:v,recipient:`${s.recipient.trim()}
148
- `,...w?{item:w}:{}};g(s.base,C,"Backup saved. Review and apply sends it to machines.")},children:[l(Pa,{label:"Store type",children:b=>l("select",{...b,className:"h-9 rounded-md border border-input bg-background px-2 text-sm",value:s.type,onChange:v=>i({...s,type:v.target.value}),children:sN.map(v=>l("option",{value:v,children:v},v))})}),l(Pa,{label:"Folder in the store",children:b=>l(le,{...b,required:!0,value:s.path,placeholder:"bucket/moonlet-backups",onChange:v=>i({...s,path:v.target.value})})}),l(Pa,{label:"Store settings",help:"rclone settings, one name = value per line. No keys or passwords here.",children:b=>l("textarea",{...b,className:"h-20 w-full rounded-md border bg-background p-2 font-mono text-xs",value:s.options,placeholder:`provider = AWS
149
- region = us-west-2`,onChange:v=>i({...s,options:v.target.value})})}),l(Pa,{label:"Credential vault item",help:"The name of the vault item that holds the store's write-only credential. Its fields become rclone settings on the machine when the backup runs. Only the name is saved here.",children:b=>l(le,{...b,value:s.item,placeholder:"Backup writer",onChange:v=>i({...s,item:v.target.value})})}),l(Pa,{label:"Your OpenPGP key",help:"Paste the output of gpg --armor --export you@example.com: the part you can share. The secret part stays on your own computer.",children:b=>l("textarea",{...b,required:!0,className:"h-28 w-full rounded-md border bg-background p-2 font-mono text-xs",value:s.recipient,onChange:v=>i({...s,recipient:v.target.value})})}),m("div",{className:"flex flex-wrap gap-2",children:[l(R,{type:"submit",disabled:a,children:"Save backup"}),l(R,{type:"button",variant:"secondary",disabled:a,onClick:()=>i(null),children:"Cancel"})]})]}),m("p",{className:"text-muted-foreground",children:["Saving changes the policy only. Settings \u2192 Permissions \u2192 Review and apply sends it to machines with the usual approval. To restore, download a copy from your store and, on your own machine, run ",l("code",{children:"gpg --decrypt <file> | tar -xzf -"}),"."]}),c&&l("p",{role:"status",children:c}),(r||p)&&l("p",{role:"alert",className:"text-destructive",children:p||r})]})}function vn(){let e=J(),t=q(()=>e.call("welcome.state",null),[e]),[n,r]=_(null),[o,s]=_(null),i=q(()=>{t().then(a=>{r(a),s(null)},a=>s(a instanceof Error?a.message:String(a)))},[t]);return K(i,[i]),ke("config",i),{rpc:e,state:n,error:o,refetch:i}}function aN(){let{rpc:e,state:t,error:n,refetch:r}=vn(),[o,s]=_(!1),[i,a]=_(null),[u,c]=_(null);return m("div",{className:"flex max-w-xl flex-col gap-3 text-sm",children:[l("p",{children:"Optional. Paste a private .ics link above to include upcoming events in calendar checks. In Google Calendar, use the calendar's Secret address in iCal format. In Proton Calendar, share by link with full details. Anyone with the link can read the calendar; keep it private."}),l("p",{children:"The link stays in protected storage on your Moonlet server. Stations receive upcoming events, never the link. Saving a link does not confirm that the calendar is reachable."}),l("p",{role:"status",children:t?t.secrets.calendar?"Calendar link saved.":"No calendar set up. Add a private link above when you want to use it.":"Loading calendar status\u2026"}),t?.secrets.calendar&&l("p",{className:"text-muted-foreground",children:"Removing the link or refreshing setup resends saved contacts and calendar events to machines enabled for assistant work. Removing the link sends the setup without calendar events."}),t?.secrets.calendar&&l(R,{variant:"secondary",disabled:o,onClick:async()=>{s(!0),c(null);try{let d=await e.call("welcome.secret",{which:"calendar",value:null});a(d.line),r()}catch(d){c(d instanceof Error?d.message:String(d))}finally{s(!1)}},children:"Remove calendar link"}),t&&(t.secrets.calendar||i)&&l(R,{variant:"secondary",disabled:o,onClick:async()=>{s(!0),c(null);try{let d=await e.call("welcome.handover",null);a(d.lines.join(" "))}catch(d){c(d instanceof Error?d.message:String(d))}finally{s(!1)}},children:"Refresh contacts and calendar on machines"}),i&&l("p",{role:"status",children:i}),(n||u)&&l("p",{role:"alert",className:"text-destructive",children:u||n})]})}var re={};cn(re,{$brand:()=>lg,$input:()=>Px,$output:()=>Ix,INVALID:()=>kt,NEVER:()=>ag,TimePrecision:()=>Hx,ZodAny:()=>$y,ZodArray:()=>Ly,ZodBase64:()=>Hp,ZodBase64URL:()=>Vp,ZodBigInt:()=>xi,ZodBigIntFormat:()=>jp,ZodBoolean:()=>gi,ZodCIDRv4:()=>Bp,ZodCIDRv6:()=>Up,ZodCUID:()=>Lp,ZodCUID2:()=>Mp,ZodCatch:()=>n_,ZodCodec:()=>Nl,ZodCompileAsyncError:()=>an,ZodCompileUnsupportedError:()=>Se,ZodCreditCard:()=>ky,ZodCustom:()=>Al,ZodCustomStringFormat:()=>Ao,ZodDate:()=>_l,ZodDefault:()=>Gy,ZodDiscriminatedUnion:()=>Dy,ZodE164:()=>Zp,ZodEmail:()=>$p,ZodEmoji:()=>Pp,ZodEnum:()=>fi,ZodError:()=>qD,ZodExactOptional:()=>qp,ZodFile:()=>Zy,ZodFirstPartyTypeKind:()=>g_,ZodFunction:()=>p_,ZodGUID:()=>Ip,ZodIBAN:()=>Sy,ZodIPv4:()=>Kp,ZodIPv6:()=>Xp,ZodISODate:()=>Sr,ZodISODateTime:()=>kr,ZodISODuration:()=>Nr,ZodISOTime:()=>Er,ZodInstanceOf:()=>m_,ZodIntersection:()=>Fy,ZodIssueCode:()=>t3,ZodJWT:()=>Wp,ZodKSUID:()=>zp,ZodLazy:()=>c_,ZodLiteral:()=>Vy,ZodMAC:()=>wy,ZodMap:()=>Uy,ZodNaN:()=>o_,ZodNanoID:()=>Op,ZodNever:()=>Py,ZodNonOptional:()=>Jp,ZodNull:()=>Ty,ZodNullable:()=>Qy,ZodNumber:()=>mi,ZodNumberFormat:()=>Co,ZodObject:()=>wl,ZodOptional:()=>Sl,ZodPipe:()=>El,ZodPrefault:()=>qy,ZodPreprocess:()=>s_,ZodPromise:()=>d_,ZodReadonly:()=>i_,ZodRealError:()=>Ot,ZodRecord:()=>pi,ZodSet:()=>Hy,ZodString:()=>hi,ZodStringFormat:()=>Le,ZodSuccess:()=>t_,ZodSymbol:()=>Ay,ZodTemplateLiteral:()=>l_,ZodTransform:()=>Wy,ZodTuple:()=>Ky,ZodType:()=>ye,ZodULID:()=>Dp,ZodURL:()=>yl,ZodUUID:()=>En,ZodUndefined:()=>Cy,ZodUnion:()=>kl,ZodUnknown:()=>Iy,ZodVoid:()=>Oy,ZodXID:()=>Fp,ZodXor:()=>My,_ZodString:()=>Rp,_default:()=>Yy,_function:()=>$C,any:()=>lC,array:()=>vl,base64:()=>BA,base64url:()=>UA,bigint:()=>rC,boolean:()=>Ny,catch:()=>r_,check:()=>IC,cidrv4:()=>KA,cidrv6:()=>XA,clone:()=>Te,codec:()=>AC,coerce:()=>b_,compile:()=>Dx,config:()=>He,core:()=>Wn,creditCard:()=>VA,cuid:()=>IA,cuid2:()=>PA,currencyCode:()=>YA,custom:()=>PC,date:()=>uC,decode:()=>my,decodeAsync:()=>xy,deepPartial:()=>ZC,describe:()=>OC,discriminatedUnion:()=>gC,e164:()=>HA,email:()=>wA,emoji:()=>RA,encode:()=>hy,encodeAsync:()=>gy,endsWith:()=>ti,enum:()=>Gp,exactOptional:()=>jy,file:()=>kC,flattenError:()=>Ua,float32:()=>JA,float64:()=>eC,formatError:()=>Ha,fromJSONSchema:()=>HC,function:()=>$C,getDiscriminatedOption:()=>ix,getErrorMap:()=>r3,globalRegistry:()=>at,gt:()=>kn,gte:()=>Ft,guid:()=>kA,hash:()=>qA,hex:()=>GA,hostname:()=>QA,httpUrl:()=>TA,iban:()=>ZA,includes:()=>Js,input:()=>jC,instanceof:()=>MC,int:()=>Cp,int32:()=>tC,int64:()=>oC,intersection:()=>zy,invertCodec:()=>CC,ipv4:()=>DA,ipv6:()=>zA,iso:()=>Cl,json:()=>FC,jwt:()=>WA,keyof:()=>dC,ksuid:()=>MA,lazy:()=>u_,length:()=>wo,literal:()=>wC,locales:()=>cl,looseObject:()=>hC,looseRecord:()=>bC,lowercase:()=>Ys,lt:()=>wn,lte:()=>Dt,mac:()=>FA,map:()=>yC,maxLength:()=>vo,maxSize:()=>yr,memoizer:()=>ll,meta:()=>LC,mime:()=>ri,minLength:()=>Zn,minSize:()=>Sn,multipleOf:()=>br,nan:()=>NC,nanoid:()=>$A,nativeEnum:()=>vC,negative:()=>xp,never:()=>Qp,nonnegative:()=>yp,nonoptional:()=>e_,nonpositive:()=>bp,normalize:()=>oi,null:()=>Ry,nullable:()=>bl,nullish:()=>SC,number:()=>Ey,object:()=>pC,optional:()=>Eo,output:()=>QC,overwrite:()=>ln,parse:()=>uy,parseAsync:()=>dy,partialRecord:()=>xC,pipe:()=>Tp,positive:()=>gp,prefault:()=>Jy,preprocess:()=>zC,prettifyError:()=>fg,promise:()=>RC,properties:()=>ni,property:()=>_p,readonly:()=>a_,record:()=>By,refine:()=>f_,regex:()=>Gs,regexes:()=>Wt,registry:()=>Vd,safeDecode:()=>yy,safeDecodeAsync:()=>vy,safeEncode:()=>by,safeEncodeAsync:()=>_y,safeParse:()=>py,safeParseAsync:()=>fy,set:()=>_C,setErrorMap:()=>n3,size:()=>_o,slugify:()=>li,startsWith:()=>ei,strictObject:()=>fC,string:()=>xl,stringFormat:()=>jA,stringbool:()=>DC,success:()=>EC,superRefine:()=>h_,symbol:()=>iC,templateLiteral:()=>TC,toJSONSchema:()=>Sp,toLowerCase:()=>ii,toUpperCase:()=>ai,toZod:()=>Oa,transform:()=>Yp,treeifyError:()=>pg,trim:()=>si,tuple:()=>Xy,uint32:()=>nC,uint64:()=>sC,ulid:()=>OA,undefined:()=>aC,union:()=>bi,unknown:()=>So,uppercase:()=>qs,url:()=>CA,util:()=>oe,uuid:()=>SA,uuidv4:()=>EA,uuidv6:()=>NA,uuidv7:()=>AA,validate:()=>Va,validateAsync:()=>Za,void:()=>cC,withParser:()=>Zd,xid:()=>LA,xor:()=>mC});var Wn={};cn(Wn,{$ZodAny:()=>q0,$ZodArray:()=>rx,$ZodAsyncError:()=>It,$ZodBase64:()=>K0,$ZodBase64URL:()=>X0,$ZodBigInt:()=>Pd,$ZodBigIntFormat:()=>j0,$ZodBoolean:()=>nl,$ZodCIDRv4:()=>F0,$ZodCIDRv6:()=>z0,$ZodCUID:()=>N0,$ZodCUID2:()=>A0,$ZodCatch:()=>wx,$ZodCheck:()=>Fe,$ZodCheckBigIntFormat:()=>Jg,$ZodCheckEndsWith:()=>d0,$ZodCheckGreaterThan:()=>xd,$ZodCheckIncludes:()=>c0,$ZodCheckLengthEquals:()=>s0,$ZodCheckLessThan:()=>gd,$ZodCheckLowerCase:()=>a0,$ZodCheckMaxLength:()=>r0,$ZodCheckMaxSize:()=>e0,$ZodCheckMimeType:()=>h0,$ZodCheckMinLength:()=>o0,$ZodCheckMinSize:()=>t0,$ZodCheckMultipleOf:()=>Yg,$ZodCheckNumberFormat:()=>qg,$ZodCheckOverwrite:()=>m0,$ZodCheckProperties:()=>f0,$ZodCheckProperty:()=>p0,$ZodCheckRegex:()=>i0,$ZodCheckSizeEquals:()=>n0,$ZodCheckStartsWith:()=>u0,$ZodCheckStringFormat:()=>Zs,$ZodCheckUpperCase:()=>l0,$ZodCodec:()=>ol,$ZodCreditCard:()=>U0,$ZodCustom:()=>Tx,$ZodCustomStringFormat:()=>Z0,$ZodCyclicError:()=>Kd,$ZodDate:()=>nx,$ZodDefault:()=>bx,$ZodDiscriminatedUnion:()=>ax,$ZodE164:()=>B0,$ZodEmail:()=>_0,$ZodEmoji:()=>S0,$ZodEncodeError:()=>xr,$ZodEnum:()=>px,$ZodError:()=>dg,$ZodExactOptional:()=>gx,$ZodFile:()=>hx,$ZodFunction:()=>Ax,$ZodGUID:()=>b0,$ZodIBAN:()=>H0,$ZodIPv4:()=>L0,$ZodIPv6:()=>M0,$ZodISODate:()=>I0,$ZodISODateTime:()=>$0,$ZodISODuration:()=>O0,$ZodISOTime:()=>P0,$ZodIntersection:()=>lx,$ZodJWT:()=>V0,$ZodKSUID:()=>R0,$ZodLazy:()=>sl,$ZodLiteral:()=>fx,$ZodMAC:()=>D0,$ZodMap:()=>ux,$ZodNaN:()=>kx,$ZodNanoID:()=>E0,$ZodNever:()=>ex,$ZodNonOptional:()=>_x,$ZodNull:()=>Y0,$ZodNullable:()=>xx,$ZodNumber:()=>Id,$ZodNumberFormat:()=>W0,$ZodObject:()=>BN,$ZodObjectJIT:()=>ox,$ZodOptional:()=>Ld,$ZodPipe:()=>Md,$ZodPrefault:()=>yx,$ZodPreprocess:()=>Sx,$ZodPromise:()=>Cx,$ZodReadonly:()=>Ex,$ZodRealError:()=>Pt,$ZodRecord:()=>cx,$ZodRegistry:()=>Hd,$ZodSet:()=>dx,$ZodString:()=>mo,$ZodStringFormat:()=>Re,$ZodSuccess:()=>vx,$ZodSymbol:()=>Q0,$ZodTemplateLiteral:()=>Nx,$ZodTransform:()=>mx,$ZodTuple:()=>Od,$ZodType:()=>me,$ZodULID:()=>C0,$ZodURL:()=>k0,$ZodUUID:()=>y0,$ZodUndefined:()=>G0,$ZodUnion:()=>rl,$ZodUnknown:()=>J0,$ZodVoid:()=>tx,$ZodXID:()=>T0,$ZodXor:()=>sx,$brand:()=>lg,$constructor:()=>I,$input:()=>Px,$output:()=>Ix,Doc:()=>ho,INVALID:()=>kt,JSONSchema:()=>yA,JSONSchemaGenerator:()=>Ep,NEVER:()=>ag,TimePrecision:()=>Hx,URL_BAD_FORMAT:()=>v0,URL_UNPARSEABLE:()=>Ya,ZodCompileAsyncError:()=>an,ZodCompileUnsupportedError:()=>Se,_any:()=>ab,_array:()=>hb,_base64:()=>pp,_base64url:()=>fp,_bigint:()=>eb,_boolean:()=>qx,_catch:()=>KD,_check:()=>rA,_cidrv4:()=>up,_cidrv6:()=>dp,_coercedBigint:()=>tb,_coercedBoolean:()=>Jx,_coercedDate:()=>pb,_coercedNumber:()=>Zx,_coercedString:()=>Kx,_creditCard:()=>Bx,_cuid:()=>rp,_cuid2:()=>op,_custom:()=>gb,_date:()=>db,_decode:()=>sd,_decodeAsync:()=>ad,_default:()=>DD,_discriminatedUnion:()=>ED,_e164:()=>hp,_email:()=>Qd,_emoji:()=>tp,_encode:()=>od,_encodeAsync:()=>id,_endsWith:()=>ti,_enum:()=>$D,_file:()=>mb,_float32:()=>jx,_float64:()=>Qx,_gt:()=>kn,_gte:()=>Ft,_guid:()=>Gd,_iban:()=>Ux,_includes:()=>Js,_int:()=>Wx,_int32:()=>Gx,_int64:()=>nb,_intersection:()=>ND,_ipv4:()=>lp,_ipv6:()=>cp,_isoDate:()=>pl,_isoDateTime:()=>dl,_isoDuration:()=>hl,_isoTime:()=>fl,_jwt:()=>mp,_ksuid:()=>ap,_lazy:()=>HD,_length:()=>wo,_literal:()=>PD,_lowercase:()=>Ys,_lt:()=>wn,_lte:()=>Dt,_mac:()=>Xx,_map:()=>TD,_max:()=>Dt,_maxLength:()=>vo,_maxSize:()=>yr,_mime:()=>ri,_min:()=>Ft,_minLength:()=>Zn,_minSize:()=>Sn,_multipleOf:()=>br,_nan:()=>fb,_nanoid:()=>np,_nativeEnum:()=>ID,_negative:()=>xp,_never:()=>cb,_nonnegative:()=>yp,_nonoptional:()=>FD,_nonpositive:()=>bp,_normalize:()=>oi,_null:()=>ib,_nullable:()=>MD,_number:()=>Vx,_optional:()=>LD,_overwrite:()=>ln,_parse:()=>Bs,_parseAsync:()=>Us,_pipe:()=>XD,_positive:()=>gp,_promise:()=>VD,_properties:()=>ni,_property:()=>_p,_readonly:()=>BD,_record:()=>CD,_refine:()=>xb,_regex:()=>Gs,_safeDecode:()=>cd,_safeDecodeAsync:()=>dd,_safeEncode:()=>ld,_safeEncodeAsync:()=>ud,_safeParse:()=>Hs,_safeParseAsync:()=>Vs,_set:()=>RD,_size:()=>_o,_slugify:()=>li,_startsWith:()=>ei,_string:()=>zx,_stringFormat:()=>ko,_stringbool:()=>vb,_success:()=>zD,_superRefine:()=>bb,_symbol:()=>ob,_templateLiteral:()=>UD,_toLowerCase:()=>ii,_toUpperCase:()=>ai,_transform:()=>OD,_trim:()=>si,_tuple:()=>AD,_uint32:()=>Yx,_uint64:()=>rb,_ulid:()=>sp,_undefined:()=>sb,_union:()=>kD,_unknown:()=>lb,_uppercase:()=>qs,_url:()=>ul,_uuid:()=>Yd,_uuidv4:()=>qd,_uuidv6:()=>Jd,_uuidv7:()=>ep,_void:()=>ub,_xid:()=>ip,_xor:()=>SD,base64Charset:()=>Ad,base64urlCharset:()=>tl,canParseURL:()=>w0,clone:()=>Te,compile:()=>Dx,compileFn:()=>Wd,config:()=>He,createStandardJSONSchemaMethod:()=>ci,createToJSONSchemaMethod:()=>kb,decode:()=>PL,decodeAsync:()=>LL,describe:()=>yb,encode:()=>IL,encodeAsync:()=>OL,extractDefs:()=>vr,finalize:()=>wr,flattenError:()=>Ua,formatError:()=>Ha,getDiscriminatedOption:()=>ix,globalConfig:()=>rt,globalRegistry:()=>at,handleUnrepresentable:()=>Je,initializeContext:()=>_r,isBackEdge:()=>Bd,isRecursiveSchema:()=>Xd,isValidBase64:()=>el,isValidBase64URL:()=>Cd,isValidCIDRv6:()=>Nd,isValidCreditCard:()=>Td,isValidIBAN:()=>Rd,isValidIPv6:()=>Ja,isValidJWT:()=>$d,locales:()=>cl,memoizer:()=>ll,mergeValues:()=>Ws,meta:()=>_b,parse:()=>nd,parseAsync:()=>rd,parseURLObject:()=>zN,prettifyError:()=>fg,process:()=>$e,processSchema:()=>$e,regexes:()=>Wt,registry:()=>Vd,safeDecode:()=>DL,safeDecodeAsync:()=>zL,safeEncode:()=>ML,safeEncodeAsync:()=>FL,safeParse:()=>AL,safeParseAsync:()=>CL,standardProps:()=>wd,stripTabAndNewline:()=>qa,toDotPath:()=>bN,toJSONSchema:()=>Sp,toZod:()=>Oa,treeifyError:()=>pg,urlHostnameOk:()=>Sd,urlProtocolOk:()=>Ed,util:()=>oe,validate:()=>Va,validateAsync:()=>Za,validateURL:()=>kd,version:()=>g0,withParser:()=>Zd});var oe={};cn(oe,{BIGINT_FORMAT_RANGES:()=>za,CONSTANT_CATCH:()=>ed,Class:()=>Gm,NUMBER_FORMAT_RANGES:()=>Fa,aborted:()=>wt,allowsEval:()=>Jm,assert:()=>WO,assertEqual:()=>UO,assertIs:()=>VO,assertNever:()=>ZO,assertNotEqual:()=>HO,assignProp:()=>it,attachSchema:()=>Ju,base64ToUint8Array:()=>pN,base64urlToUint8Array:()=>pL,cached:()=>zs,captureStackTrace:()=>Gu,cleanEnum:()=>dL,cleanRegex:()=>Hn,clone:()=>Te,cloneDef:()=>GO,codePointLength:()=>po,constantCatch:()=>sg,createTransparentProxy:()=>nL,defineLazy:()=>Ym,defineLazyInternal:()=>ve,derived:()=>gL,esc:()=>vt,escapeRegex:()=>Zt,explicitlyAborted:()=>ng,extend:()=>sL,finalizeIssue:()=>$t,floatSafeRemainder:()=>La,getElementAtPath:()=>YO,getEnumValues:()=>Ds,getLengthableOrigin:()=>Xa,getParsedType:()=>tL,getSizableOrigin:()=>Ka,hexToUint8Array:()=>hL,hide:()=>Ba,installLazyProp:()=>_L,isObject:()=>uo,isPlainObject:()=>Vt,issue:()=>Xs,joinValues:()=>ju,jsonStringifyReplacer:()=>Fs,members:()=>og,merge:()=>aL,mergeDefs:()=>sn,normalizeParams:()=>W,nullish:()=>Qu,numKeys:()=>eL,objectClone:()=>jO,omit:()=>oL,optionalKeys:()=>tg,own:()=>gr,parsedType:()=>rg,partial:()=>lL,pick:()=>rL,prefixIssues:()=>Rt,primitiveTypes:()=>eg,promiseAllObject:()=>qO,propertyKeyTypes:()=>Da,randomString:()=>JO,rawShape:()=>Ks,required:()=>cL,safeExtend:()=>iL,shallowClone:()=>Ma,slugify:()=>qm,stringifyPrimitive:()=>Yu,toZod:()=>Oa,uint8ArrayToBase64:()=>fN,uint8ArrayToBase64url:()=>fL,uint8ArrayToHex:()=>mL,unwrapMessage:()=>Ms});function UO(e){return e}function HO(e){return e}function Oa(){return e=>e}function VO(e){}function ZO(e){throw new Error("Unexpected value in exhaustive check")}function WO(e){}function Ds(e){let t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function ju(e,t="|"){return e.map(n=>Yu(n)).join(t)}function Fs(e,t){return typeof t=="bigint"?t.toString():t}var Qm=class{constructor(t){this._getter=t,this._value=void 0}get value(){let t=this._getter;return t!==void 0&&(this._value=t(),this._getter=void 0),this._value}};function zs(e){return new Qm(e)}function Qu(e){return e==null}function Hn(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function La(e,t){let n=e/t,r=Math.round(n),o=4*Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<o?0:n-r}var lN=Symbol("evaluating");function Ym(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==lN)return r===void 0&&(r=lN,r=n()),r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function jO(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function it(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ks(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Un(e){return Ks(e._zod.def)??e._zod.def.shape}function cN(e,t,n){Object.defineProperty(e,t,{get(){let r=n();return it(this,t,r),r},enumerable:!0,configurable:!0})}function uN(e,t,n){t in e?it(e,t,n):e[t]=n}function co(e,t,n,r){let o=Un(t);for(let s of n){let i=Object.getOwnPropertyDescriptor(o,s);i.enumerable&&(i.get?cN(e,s,()=>{let a=t._zod.def.shape[s];return r?r(a,s):a}):uN(e,s,r?r(i.value,s):i.value))}}function QO(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?cN(e,n,()=>t[n]):uN(e,n,r.value))}}function sn(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function GO(e){return sn(e._zod.def)}function YO(e,t){return t?t.reduce((n,r)=>n?.[r],e):e}function qO(e){let t=Object.keys(e),n=t.map(r=>e[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;s<t.length;s++)o[t[s]]=r[s];return o})}function JO(e=10){let t="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<e;r++)n+=t[Math.floor(Math.random()*t.length)];return n}function vt(e){return JSON.stringify(e)}function qm(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Gu="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function uo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Jm=zs(()=>{if(rt.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Vt(e){if(uo(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(uo(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Ma(e){return Vt(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function eL(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}var tL=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Da=new Set(["string","number","symbol"]),eg=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Zt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Te(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function W(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function nL(e){let t;return new Proxy({},{get(n,r,o){return t??(t=e()),Reflect.get(t,r,o)},set(n,r,o,s){return t??(t=e()),Reflect.set(t,r,o,s)},has(n,r){return t??(t=e()),Reflect.has(t,r)},deleteProperty(n,r){return t??(t=e()),Reflect.deleteProperty(t,r)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,r){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,r)},defineProperty(n,r,o){return t??(t=e()),Reflect.defineProperty(t,r,o)}})}function Yu(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function tg(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var Fa={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},za={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function rL(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s={};return co(s,e,qu(e,t)),Te(e,sn(n,{shape:s,checks:[]}))}function qu(e,t){let n=Un(e),r=[];for(let o of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,o)?.enumerable)throw new Error(`Unrecognized key: "${String(o)}"`);t[o]&&r.push(o)}return r}function oL(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=new Set(qu(e,t)),i={};return co(i,e,Reflect.ownKeys(Un(e)).filter(a=>!s.has(a))),Te(e,sn(n,{shape:i,checks:[]}))}function sL(e,t){if(!Vt(t))throw new Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let o=Un(e);for(let s of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Te(e,sn(e._zod.def,{shape:dN(e,t)}))}function dN(e,t){let n={};return co(n,e,Reflect.ownKeys(Un(e))),QO(n,t),n}function iL(e,t){if(!Vt(t))throw new Error("Invalid input to safeExtend: expected a plain object");return Te(e,sn(e._zod.def,{shape:dN(e,t)}))}function aL(e,t){if(!t?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n={};co(n,e,Reflect.ownKeys(Un(e))),co(n,t,Reflect.ownKeys(Un(t)));let r=sn(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Te(e,r)}function lL(e,t,n,r="partial"){let s=t._zod.def.checks;if(s&&s.length>0)throw new Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(qu(t,n)):void 0,u={};return co(u,t,Reflect.ownKeys(Un(t)),e&&((c,d)=>a&&!a.has(d)?c:new e({type:"optional",innerType:c}))),Te(t,sn(t._zod.def,{shape:u,checks:[]}))}function cL(e,t,n){let r=n?new Set(qu(t,n)):void 0,o={};return co(o,t,Reflect.ownKeys(Un(t)),(s,i)=>r&&!r.has(i)?s:new e({type:"nonoptional",innerType:s})),Te(t,sn(t._zod.def,{shape:o}))}function wt(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function ng(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Rt(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Ms(e){return typeof e=="string"?e:e?.message}function Ju(e,t,n){var r;for(let o=t;o<e.length;o++)(r=e[o]).schema??(r.schema=n)}function $t(e,t,n){var r;let o=e.inst?._zod?.traits;o?.has("$ZodType")&&(o.has("$ZodCheck")?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let s=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,i=e.message?e.message:Ms(e.inst?._zod.def?.error?.(e))??Ms(s?.(e))??Ms(t?.error?.(e))??Ms(n.customError?.(e))??Ms(n.localeError?.(e))??"Invalid input",a={};for(let u of Object.keys(e))u==="inst"||u==="schema"||u==="continue"||u==="input"||u==="__proto__"||(a[u]=e[u]);return a.path??(a.path=[]),a.message=i,t?.reportInput&&(a.input=e.input),a}function Ka(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}var uL=/[\uD800-\uDBFF]/;function po(e){let t=e.length;if(!uL.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320&&(n--,r++);return n}function Xa(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function rg(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function Xs(...e){let[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}function dL(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function pN(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function fN(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function pL(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return pN(t+n)}function fL(e){return fN(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hL(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=Number.parseInt(t.slice(r,r+2),16);return n}function mL(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var Gm=class{constructor(...t){}};function og(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):xL(e,n,r.value)}}function gr(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function Ba(e,t,n){return gr(e,t,n,!1)}function gL(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return gr(this,n,r(this))},set(o){gr(this,n,o)}})}return t}function xL(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:gr(this,t,n.bind(this))},set(r){gr(this,t,r)}})}function bL(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var jm,mr=!1,yL={configurable:!0,get(){mr=!0}};function ve(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&jm!==e._zod){jm=void 0;return}jm=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,yL);let o=mr;mr=!1;try{let s=n(this);return mr?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:s}),mr=mr||o,s}catch(s){throw delete this[t],mr=mr||o,s}},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o})}})}function _L(e,t,n,r){let o=bL(e,t);o&&Object.defineProperty(o,t,{configurable:!0,get(){let s={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,s),s.value=n(this),Object.defineProperty(this,t,s),s.value},set(s){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:s})}})}var ed="~constantCatch";function sg(e){let t=()=>e;return t[ed]=!0,t}var hN,ag=Object.freeze({status:"aborted"}),ig={value:void 0,enumerable:!1},mN="captureStackTrace"in Error?Error:null;function vL(e){let t=mN;if(t){let n=t.stackTraceLimit;if(typeof n=="number"){try{t.stackTraceLimit=0}catch{return mN=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function I(e,t,n,r){let o={};function s(f){this.def=f,this.constr=p,this.traits=new Set}s.prototype=o;let i=n,a=i&&new WeakSet;function u(f,h){if(f._zod){if(f._zod.traits.has(e))return}else{ig.value=new s(h);try{Object.defineProperty(f,"_zod",ig)}finally{ig.value=void 0}}if(f._zod.traits.add(e),t(f,h),a){let x=Object.getPrototypeOf(f),b=f._zod.constr.prototype,v=x;for(;v&&v!==b;)v=Object.getPrototypeOf(v);let w=v??x;a.has(w)||(a.add(w),og(w,i))}let g=p.prototype;for(let x in g)Object.prototype.hasOwnProperty.call(g,x)&&(x in f||(f[x]=g[x].bind(f)))}let c=r?.Parent??Object;class d extends c{}Object.defineProperty(d,"name",{value:e});function p(f){let h=r?.Parent?vL(d):this;u(h,f);let g=h._zod.deferred;if(g){for(let b of g)b();h._zod.deferred=void 0}let x=globalThis.__zod_globalConfig?.postProcessor;return x&&x(h),h}return Object.defineProperty(p,"init",{value:u}),Object.defineProperty(p,Symbol.hasInstance,{value:f=>r?.Parent&&f instanceof r.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(p,"name",{value:e}),p}var lg=Symbol("zod_brand"),It=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},xr=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(hN=globalThis).__zod_globalConfig??(hN.__zod_globalConfig={});var rt=globalThis.__zod_globalConfig;function He(e){return e&&Object.assign(rt,e),rt}function wL(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Fs,2)),e.message}function kL(e){this._zod.message=e}var SL={get:wL,set:kL,enumerable:!0,configurable:!0},ug={value:void 0,enumerable:!1},gN=new WeakSet([Object.prototype,Error.prototype]),xN=(e,t)=>{e.name="$ZodError",ug.value=t,Object.defineProperty(e,"issues",ug),ug.value=void 0,Object.defineProperty(e,"message",SL);let n=Object.getPrototypeOf(e);gN.has(n)||(gN.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let r=()=>this.message;return Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0})}}))},dg=I("$ZodError",xN),Pt=I("$ZodError",xN,void 0,{Parent:Error});function EL(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t==="__proto__"?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function Ua(e,t=n=>n.message){let n={},r=[];for(let o of e.issues)o.path.length>0?EL(n,o.path[0],()=>[]).push(t(o)):r.push(t(o));return{formErrors:r,fieldErrors:n}}function Ha(e,t=n=>n.message){let n={_errors:[]},r=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>r({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")r({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")r({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)n._errors.push(t(i));else{let u=n,c=0;for(;c<a.length;){let d=a[c],p=c===a.length-1;if(d==="_errors"){p&&u._errors.push(t(i)),c++;continue}Object.prototype.hasOwnProperty.call(u,d)||Object.defineProperty(u,d,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let f=u[d];p&&f._errors.push(t(i)),u=f,c++}}}};return r(e),n}function pg(e,t=n=>n.message){let n={errors:[]},r=(o,s=[])=>{var i;for(let a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(u=>r({issues:u},[...s,...a.path]));else if(a.code==="invalid_key")r({issues:a.issues},[...s,...a.path]);else if(a.code==="invalid_element")r({issues:a.issues},[...s,...a.path]);else{let u=[...s,...a.path];if(u.length===0){n.errors.push(t(a));continue}let c=n,d=0;for(;d<u.length;){let p=u[d],f=d===u.length-1;typeof p=="string"?(c.properties??(c.properties={}),Object.prototype.hasOwnProperty.call(c.properties,p)||Object.defineProperty(c.properties,p,{value:{errors:[]},enumerable:!0,writable:!0,configurable:!0}),c=c.properties[p]):(c.items??(c.items=[]),(i=c.items)[p]??(i[p]={errors:[]}),c=c.items[p]),f&&c.errors.push(t(a)),d++}}};return r(e),n}function bN(e){let t=[],n=e.map(r=>typeof r=="object"?r.key:r);for(let r of n)typeof r=="number"?t.push(`[${r}]`):typeof r=="symbol"?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}function fg(e){let t=[],n=[...e.issues].sort((r,o)=>(r.path??[]).length-(o.path??[]).length);for(let r of n)t.push(`\u2716 ${r.message}`),r.path?.length&&t.push(` \u2192 at ${bN(r.path)}`);return t.join(`
150
- `)}function td(e,t){return{callee:t?.callee??e,Err:t?.Err}}var Bs=e=>{let t=(n,r,o,s)=>{let i=o?{...o,async:!1}:{async:!1},a=n._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new It;if(a.issues.length){let u=new(s?.Err??e)(a.issues.map(c=>$t(c,i,He())));throw Gu(u,s?.callee??t),u}return a.value};return t},nd=Bs(Pt),Us=e=>{let t=async(n,r,o,s)=>{let i=o?{...o,async:!0}:{async:!0},a=n._zod.run({value:r,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let u=new(s?.Err??e)(a.issues.map(c=>$t(c,i,He())));throw Gu(u,s?.callee??t),u}return a.value};return t},rd=Us(Pt),Hs=e=>(t,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new It;return s.issues.length?yN(e,s.issues,o):{success:!0,data:s.value}},AL=Hs(Pt);function yN(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(o=>$t(o,n,He()))),t=void 0,n=void 0),r},set error(o){r=o,t=void 0,n=void 0}}}var Vs=e=>async(t,n,r)=>{let o=r?{...r,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?yN(e,s.issues,o):{success:!0,data:s.value}},CL=Vs(Pt),TL=Symbol.for("zod.compile.invalid"),RL=Symbol.for("zod.compile.fallback"),Va=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==TL)return!0;if(r.definite===!0&&n===void 0)return!1}return $L(e,t,n)});function $L(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=e._zod.bag.fallbackRun,s;if(o?(r[RL]=!0,s=o({value:t,issues:[]},r)):s=e._zod.run({value:t,issues:[]},r),s instanceof Promise)throw new It;return s.issues.length===0}var Za=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},o=e._zod.run({value:t,issues:[]},r);return o instanceof Promise&&(o=await o),o.issues.length===0},od=e=>{let t=Bs(e),n=(r,o,s,i)=>{let a=s?{...s,direction:"backward"}:{direction:"backward"};return t(r,o,a,td(n,i))};return n},IL=od(Pt),sd=e=>{let t=Bs(e),n=(r,o,s,i)=>t(r,o,s,td(n,i));return n},PL=sd(Pt),id=e=>{let t=Us(e),n=async(r,o,s,i)=>{let a=s?{...s,direction:"backward"}:{direction:"backward"};return await t(r,o,a,td(n,i))};return n},OL=id(Pt),ad=e=>{let t=Us(e),n=async(r,o,s,i)=>await t(r,o,s,td(n,i));return n},LL=ad(Pt),ld=e=>(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Hs(e)(t,n,o)},ML=ld(Pt),cd=e=>(t,n,r)=>Hs(e)(t,n,r),DL=cd(Pt),ud=e=>async(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Vs(e)(t,n,o)},FL=ud(Pt),dd=e=>async(t,n,r)=>Vs(e)(t,n,r),zL=dd(Pt);var Wt={};cn(Wt,{anyString:()=>Kg,base64:()=>$g,base64url:()=>Ig,bigint:()=>Bg,boolean:()=>Ug,browserEmail:()=>WL,cidrv4:()=>Tg,cidrv6:()=>Rg,creditCard:()=>pd,cuid:()=>mg,cuid2:()=>gg,currencyCode:()=>Mg,date:()=>Dg,datetime:()=>zg,domain:()=>Og,duration:()=>wg,e164:()=>Lg,email:()=>Sg,emoji:()=>Eg,extendedDuration:()=>KL,guid:()=>kg,hex:()=>jg,hostname:()=>Pg,html5Email:()=>HL,httpProtocol:()=>Wa,iban:()=>fd,idnEmail:()=>ZL,integer:()=>ja,ipv4:()=>Ng,ipv6:()=>Ag,ksuid:()=>yg,lowercase:()=>Zg,mac:()=>Cg,md5_base64:()=>YL,md5_base64url:()=>qL,md5_hex:()=>GL,nanoid:()=>_g,nanoidOfLength:()=>vg,null:()=>Hg,number:()=>Vn,rfc5322Email:()=>VL,sha1_base64:()=>eM,sha1_base64url:()=>tM,sha1_hex:()=>JL,sha256_base64:()=>rM,sha256_base64url:()=>oM,sha256_hex:()=>nM,sha384_base64:()=>iM,sha384_base64url:()=>aM,sha384_hex:()=>sM,sha512_base64:()=>cM,sha512_base64url:()=>uM,sha512_hex:()=>lM,string:()=>Xg,time:()=>Fg,ulid:()=>xg,undefined:()=>Vg,unicodeEmail:()=>_N,uppercase:()=>Wg,uuid:()=>fo,uuid4:()=>XL,uuid6:()=>BL,uuid7:()=>UL,xid:()=>bg});var mg=/^[cC][0-9a-z]{6,}$/,gg=/^[0-9a-z]+$/,xg=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,bg=/^[0-9a-vA-V]{20}$/,yg=/^[A-Za-z0-9]{27}$/,_g=/^[a-zA-Z0-9_-]{21}$/;function vg(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var wg=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,KL=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,kg=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,fo=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,XL=fo(4),BL=fo(6),UL=fo(7),Sg=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,HL=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,VL=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,_N=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,ZL=_N,WL=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,jL="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function Eg(){return new RegExp(jL,"u")}var Ng=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ag=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Cg=e=>{let t=Zt(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},Tg=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Rg=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,$g=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ig=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,Pg=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,Og=/^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/,Wa=/^https?$/,Lg=/^\+[1-9]\d{6,14}$/,pd=/^\d(?:[ -]?\d){11,18}$/,Mg=/^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/,fd=/^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/,vN="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function QL(e){return new RegExp(`^${e}$`)}var Dg=QL(vN);function hg(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Fg(e){return new RegExp(`^${hg(e)}$`)}function zg(e){let t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${hg({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${hg({precision:e.precision})}`:n;return new RegExp(`^${vN}T(?:${r})$`)}var Kg=/^[\s\S]{0,}$/,Xg=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Bg=/^-?\d+n?$/,ja=/^-?\d+$/,Vn=/^-?\d+(?:\.\d+)?$/,Ug=/^(?:true|false)$/i,Hg=/^null$/i;var Vg=/^undefined$/i;var Zg=/^[^A-Z]*$/,Wg=/^[^a-z]*$/,jg=/^[0-9a-fA-F]*$/;function Qa(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Ga(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var GL=/^[0-9a-fA-F]{32}$/,YL=Qa(22,"=="),qL=Ga(22),JL=/^[0-9a-fA-F]{40}$/,eM=Qa(27,"="),tM=Ga(27),nM=/^[0-9a-fA-F]{64}$/,rM=Qa(43,"="),oM=Ga(43),sM=/^[0-9a-fA-F]{96}$/,iM=Qa(64,""),aM=Ga(64),lM=/^[0-9a-fA-F]{128}$/,cM=Qa(86,"=="),uM=Ga(86);var Fe=I("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Qg=e=>{let t=e.value;return!Qu(t)&&t.size!==void 0},Gg=e=>{let t=e.value;return!Qu(t)&&t.length!==void 0},hd={number:"number",bigint:"bigint",object:"date"},gd=I("$ZodCheckLessThan",(e,t)=>{Fe.init(e,t);let n=hd[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:hd[typeof r.value]??n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),xd=I("$ZodCheckGreaterThan",(e,t)=>{Fe.init(e,t);let n=hd[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:hd[typeof r.value]??n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Yg=I("$ZodCheckMultipleOf",(e,t)=>{Fe.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):La(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),qg=I("$ZodCheckNumberFormat",(e,t)=>{Fe.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[o,s]=Fa[t.format];e._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),Jg=I("$ZodCheckBigIntFormat",(e,t)=>{Fe.init(e,t);let[n,r]=za[t.format];e._zod.check=o=>{let s=o.value;s<n&&o.issues.push({origin:"bigint",input:s,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),s>r&&o.issues.push({origin:"bigint",input:s,code:"too_big",maximum:r,inclusive:!0,inst:e,continue:!t.abort})}}),e0=I("$ZodCheckMaxSize",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=Qg),e._zod.check=r=>{let o=r.value;o.size<=t.maximum||r.issues.push({origin:Ka(o),code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),t0=I("$ZodCheckMinSize",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=Qg),e._zod.check=r=>{let o=r.value;o.size>=t.minimum||r.issues.push({origin:Ka(o),code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),n0=I("$ZodCheckSizeEquals",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=Qg),e._zod.check=r=>{let o=r.value,s=o.size;if(s===t.size)return;let i=s>t.size;r.issues.push({origin:Ka(o),...i?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),r0=I("$ZodCheckMaxLength",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=Gg),e._zod.check=r=>{let o=r.value,s=o.length;if((typeof o=="string"&&s>t.maximum?po(o):s)<=t.maximum)return;let a=Xa(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),o0=I("$ZodCheckMinLength",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=Gg),e._zod.check=r=>{let o=r.value,s=o.length;if((typeof o=="string"&&s>=t.minimum&&s<t.minimum*2?po(o):s)>=t.minimum)return;let a=Xa(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),s0=I("$ZodCheckLengthEquals",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=Gg),e._zod.check=r=>{let o=r.value,s=o.length,i=typeof o=="string"&&s>=t.length&&s<=t.length*2?po(o):s;if(i===t.length)return;let a=Xa(o),u=i>t.length;r.issues.push({origin:a,...u?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Zs=I("$ZodCheckStringFormat",(e,t)=>{var n,r;Fe.init(e,t),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),i0=I("$ZodCheckRegex",(e,t)=>{Zs.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),a0=I("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Zg),Zs.init(e,t)}),l0=I("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Wg),Zs.init(e,t)}),c0=I("$ZodCheckIncludes",(e,t)=>{Fe.init(e,t);let n=Zt(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),u0=I("$ZodCheckStartsWith",(e,t)=>{Fe.init(e,t);let n=new RegExp(`^${Zt(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),d0=I("$ZodCheckEndsWith",(e,t)=>{Fe.init(e,t);let n=new RegExp(`.*${Zt(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});function md(e,t,n){e.issues.length&&t.issues.push(...Rt(n,e.issues))}var p0=I("$ZodCheckProperty",(e,t)=>{Fe.init(e,t),e._zod.check=n=>{let r=t.schema._zod.run({value:n.value[t.property],issues:[]},{});if(r instanceof Promise)return r.then(o=>md(o,n,t.property));md(r,n,t.property)}}),f0=I("$ZodCheckProperties",(e,t)=>{Fe.init(e,t),Ba(e,Symbol.iterator,function*(){yield e});let n;e._zod.check=r=>{if(r.value==null){r.issues.push({expected:"object",code:"invalid_type",input:r.value,inst:e});return}n??(n=Reflect.ownKeys(t.shape).map(i=>[i,t.shape[i]]));let o=r.value,s;for(let[i,a]of n){let u=a._zod.run({value:o[i],issues:[]},{});u instanceof Promise?(s??(s=[]),s.push(u.then(c=>md(c,r,i)))):md(u,r,i)}if(s)return Promise.all(s).then(()=>{})}}),h0=I("$ZodCheckMimeType",(e,t)=>{Fe.init(e,t);let n=new Set(t.mime);e._zod.check=r=>{n.has(r.value.type)||r.issues.push({code:"invalid_value",values:t.mime,input:r.value.type,inst:e,continue:!t.abort})}}),m0=I("$ZodCheckOverwrite",(e,t)=>{Fe.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});var ho=class{constructor(t=[],n={}){this.content=[],this.indent=0,this.args=t,this.closed=n}indented(t){this.indent+=1;try{t(this)}finally{this.indent-=1}}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let r=t.split(`
139
+ `)||"No additional access requested"}}}function q1(){let{scope:e}=J_();return l(hu,{onlyThread:e.kind==="thread"?e.threadId:""})}function hu({onlyThread:e}){let t=J(),n=dn(),[r,o]=v(null),[s,i]=v(null),a=G(()=>{});if(M(()=>{let d=!0,p=!1,f=!1,h,g=async()=>{if(p){f=!0;return}clearTimeout(h),p=!0;do{f=!1;try{let _=await t.call("work.parents",null);if(e!==void 0&&e!==_.orbit)d&&!f&&(o({orbit:_.orbit,jobs:[],warning:null}),i(null));else{let{jobs:w,errors:T}=await fu(n,_);d&&!f&&(o(y=>({orbit:_.orbit,jobs:[...w,...y?.jobs.filter(E=>T.includes(E.interaction.threadId))??[]],warning:T.length?"Some work could not be checked. Trying again.":null})),i(null))}}catch{d&&!f&&i("Could not check waiting work. Trying again.")}}while(d&&f);p=!1,d&&(h=setTimeout(()=>{g()},5e3))};a.current=()=>{g()};let x=n.subscribe({event:"thread:changed",callback:_=>{_.changes.some(w=>["interactions-changed","thread-created","thread-deleted","parent-changed","archived-changed"].includes(w))&&g()}}),b=n.subscribe({event:"realtime:connection",callback:_=>{_.state==="connected"&&g()}});return g(),()=>{d=!1,a.current=()=>{},clearTimeout(h),x(),b()}},[t,n,e]),e!==void 0&&r&&r.orbit!==e)return null;let u=r?.jobs.filter(d=>d.interaction.threadId!==e)??[],c=s||r?.warning;return e!==void 0&&!u.length?c?l("p",{role:"alert",className:"text-sm",children:c}):null:m("section",{"aria-label":"Waiting for you",className:"max-h-[50vh] space-y-3 overflow-auto rounded-md border p-3 text-sm",children:[l("h2",{className:"font-medium",children:"Waiting for you"}),(s||r?.warning)&&l("p",{role:"alert",children:s||r?.warning}),!r&&!s&&l("p",{children:"Checking work\u2026"}),r&&!u.length&&!s&&!r.warning&&l("p",{children:"No questions or approvals waiting."}),u.map(d=>l(LI,{job:d,sdk:n,done:()=>{o(p=>p&&{...p,jobs:p.jobs.filter(f=>f.interaction.id!==d.interaction.id)}),a.current()}},d.interaction.id))]})}function LI({job:e,sdk:t,done:n}){let{interaction:r}=e,o=Ie(),[s,i]=v(!1),a=G(!1),[u,c]=v(null),[d,p]=v({}),f=r.payload,h=async _=>{if(a.current)return!1;a.current=!0,i(!0),c(null);try{let w=await t.threads.interactions.get({threadId:r.threadId,interactionId:r.id});return w.status!=="pending"||w.expiresAt!=null&&w.expiresAt<=Date.now()?(n(),!0):(await _(w),n(),!0)}catch{return c("The answer did not go through. Check the work and try again."),!1}finally{a.current=!1,i(!1)}},g={threadId:r.threadId,interactionId:r.id},x=_=>h(()=>t.threads.interactions.resolve({...g,resolution:_})),b;if(f.kind==="approval"){let _=Y1(f);b=m("div",{className:"space-y-2",children:[l("p",{children:_.title}),f.reason&&l("p",{children:f.reason}),l("pre",{className:"max-h-60 overflow-auto whitespace-pre-wrap break-words",children:_.detail}),m("div",{className:"flex gap-2",children:[l(R,{disabled:s||!f.availableDecisions.includes("allow_once"),onClick:()=>{x({decision:"allow_once",grantedPermissions:f.subject.kind==="permission_grant"?f.subject.permissions:null})},children:"Approve"}),l(R,{variant:"destructive",disabled:s||!f.availableDecisions.includes("deny"),onClick:()=>{x({decision:"deny"})},children:"Decline"})]})]})}else if(f.kind==="user_question")b=m("form",{className:"space-y-3",onSubmit:_=>{_.preventDefault(),am(f.questions,d)&&x({kind:"user_answer",answers:d})},children:[f.questions.map(_=>m("fieldset",{disabled:s,className:"space-y-2",children:[l("legend",{children:_.prompt}),_.options?.map(w=>m("label",{className:"block",children:[l("input",{type:_.multiSelect?"checkbox":"radio",name:`${r.id}-${_.id}`,checked:d[_.id]?.selected.includes(w.value)??!1,onChange:T=>p(y=>({...y,[_.id]:{..._.multiSelect?y[_.id]:{},selected:_.multiSelect?T.target.checked?[...y[_.id]?.selected??[],w.value]:(y[_.id]?.selected??[]).filter(E=>E!==w.value):[w.value]}}))})," ",w.label,w.description&&l("span",{className:"block text-xs text-muted-foreground",children:w.description})]},w.value)),_.allowFreeText&&m("label",{className:"block",children:["Your answer",l("textarea",{className:"block w-full rounded border bg-background p-2",value:d[_.id]?.freeText??"",onChange:w=>p(T=>({...T,[_.id]:{selected:_.multiSelect?T[_.id]?.selected??[]:[],freeText:w.target.value}}))})]})]},_.id)),m("div",{className:"flex gap-2",children:[l(R,{type:"submit",disabled:s||!am(f.questions,d),children:"Send answer"}),l(R,{type:"button",variant:"destructive",disabled:s,onClick:()=>{h(()=>t.threads.stop({threadId:r.threadId}))},children:"Stop work"})]}),l("p",{className:"text-xs text-muted-foreground",children:"Stop work stops this work, including the question it is waiting on."})]});else if(f.kind==="plugin"&&r.origin?.kind==="plugin"&&r.origin.pluginId==="orbit"){let _={interaction:{id:r.id,threadId:r.threadId,title:f.title,payload:f.data,createdAt:r.createdAt,expiresAt:r.expiresAt??null},submit:async w=>{if(!await h(()=>t.threads.interactions.respond({...g,value:w})))throw new Error("Answer failed")},cancel:async()=>{if(!await h(()=>t.threads.interactions.cancel(g)))throw new Error("Answer failed")}};b=r.origin.rendererId==="approval"?l(nc,{..._}):r.origin.rendererId==="policy-proposal"?l(oc,{..._}):r.origin.rendererId==="owner-changes"?l(ic,{..._}):r.origin.rendererId==="station-manager"?l(rc,{..._}):l("p",{children:"Open the work to answer this request."})}else b=l("p",{children:"Open the work to answer this request."});return m("article",{className:"space-y-2 rounded border p-3","aria-busy":s,children:[l("h3",{className:"font-medium",children:e.title}),l("fieldset",{disabled:s,children:b}),l(R,{variant:"ghost",onClick:()=>o.toThread(r.threadId),children:"Open work"}),u&&l("p",{role:"alert",children:u})]})}function J1(){return m("main",{className:"mx-auto max-w-3xl p-4",children:[l("h1",{className:"mb-4 text-lg font-medium",children:"Your moonlet"}),l(hu,{}),l(Ti,{})]})}var mu="tasks",gu=[{id:"today",label:"Today"},{id:"upcoming",label:"Upcoming"},{id:"waiting",label:"Waiting on others"},{id:"scheduled",label:"Scheduled and watched"},{id:"journal",label:"Journal"},{id:"done",label:"Done"}],MI=e=>gu.some(t=>t.id===e);function cm(e){let[t,n]=(e??"").split("/").filter(Boolean);return{view:MI(t)?t:"today",task:n?decodeURIComponent(n):null}}function tn(){let e=Ie();return q((t,n=null)=>e.toPluginPanel(mu,{subPath:n?`${t}/${encodeURIComponent(n)}`:t}),[e])}function rt(){return J()}function We(e,t){let[n,r]=v(null),[o,s]=v(""),[i,a]=v(0),u=G(e);u.current=e;let c=q(()=>a(d=>d+1),[]);return M(()=>{let d=!0;return u.current().then(p=>{d&&(r(p),s(""))},p=>d&&s(p instanceof Error?p.message:String(p))),()=>{d=!1}},[i,...t]),M(()=>{let d=setInterval(c,6e4);return()=>clearInterval(d)},[c]),ke("tasks",c),{data:n,error:o,reload:c}}function ps(){let e=rt();return We(()=>e.call("tasks.meta",null),[e]).data}function Na(){let e=rt(),[t,n]=v(""),[r,o]=v(!1);return{change:q(async i=>{o(!0);try{let a=await e.call("tasks.change",i);return n(""),a}catch(a){return n(a instanceof Error?a.message:String(a)),null}finally{o(!1)}},[e]),error:t,busy:r,clearError:()=>n("")}}var DI={todo:"M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z",followup:"M5 2h14M5 22h14M7 2v2.5C7 6.7 9 8.2 12 12c3-3.8 5-5.3 5-7.5V2M7 22v-2.5C7 17.3 9 15.8 12 12c3 3.8 5 5.3 5 7.5V22",once:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9M10.3 21a1.94 1.94 0 0 0 3.4 0",repeat:"m17 2 4 4-4 4M3 11v-1a4 4 0 0 1 4-4h14M7 22l-4-4 4-4M21 13v1a4 4 0 0 1-4 4H3",watch:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12zM15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0z"};function Qr(e){return e.kind==="followup"?"followup":e.kind==="scheduled"?e.when?.form==="repeat"?"repeat":"once":"todo"}function Ht({glyph:e,className:t}){return l("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:V("size-4 shrink-0",t),children:l("path",{d:DI[e]})})}var xu={todo:"To-do",followup:"Follow-up",scheduled:"Scheduled"},us={urgent:"Urgent",high:"High",medium:"Medium",low:"Low",none:"No priority"};function ds({level:e,withLabel:t=!1}){let n={urgent:3,high:3,medium:2,low:1,none:0}[e];return m("span",{className:"inline-flex shrink-0 items-center gap-1.5 text-xs font-medium",title:`${us[e]} priority`,children:[e==="urgent"?m("svg",{viewBox:"0 0 16 14",className:"h-3.5 w-4",role:"img","aria-label":"Urgent priority",children:[l("rect",{x:"1",y:"0",width:"14",height:"14",rx:"3.5",className:"fill-destructive"}),l("rect",{x:"7.1",y:"3",width:"1.8",height:"5.2",rx:".9",className:"fill-destructive-foreground"}),l("circle",{cx:"8",cy:"10.4",r:"1.05",className:"fill-destructive-foreground"})]}):l("svg",{viewBox:"0 0 16 14",className:"h-3.5 w-4",role:"img","aria-label":`${us[e]} priority`,children:[[1.5,8,5],[6.5,4.5,8.5],[11.5,1,12]].map(([r,o,s],i)=>l("rect",{x:r,y:o,width:"3",height:s,rx:"1",className:i<n?"fill-foreground/70":"fill-foreground/15"},r))}),t?l("span",{children:us[e]}):null]})}function De({origin:e,assistant:t,size:n=16}){return e==="assistant"?m("svg",{viewBox:"0 0 26 26",width:n,height:n,role:"img","aria-label":`Added by ${t}`,className:"shrink-0",children:[l("title",{children:`Added by ${t}`}),l("circle",{cx:"13",cy:"13",r:"13",style:{fill:"var(--moonlet-night, var(--color-foreground))"}}),l("circle",{cx:"13",cy:"13",r:"8",style:{fill:"var(--moonlet-moon-gold, var(--color-primary))"}}),l("circle",{cx:"10.3",cy:"10.8",r:"1.8",style:{fill:"var(--moonlet-moon-deep, var(--color-primary))"}}),l("circle",{cx:"15.3",cy:"15.6",r:"1.25",style:{fill:"var(--moonlet-moon-deep, var(--color-primary))"}})]}):m("svg",{viewBox:"0 0 26 26",width:n,height:n,role:"img","aria-label":"From you",className:"shrink-0",children:[l("title",{children:"From you"}),l("circle",{cx:"13",cy:"13",r:"12.25",className:"fill-muted stroke-border",strokeWidth:"1.5"}),l("circle",{cx:"13",cy:"10.4",r:"3.6",className:"fill-foreground/70"}),l("path",{d:"M6.6 20.2c1.3-3 3.6-4.5 6.4-4.5s5.1 1.5 6.4 4.5",className:"fill-foreground/70"})]})}function Ea({task:e,now:t,quiet:n=!1}){if(!e.whenText)return null;let r=e.dueAt!==null&&e.dueAt<t&&e.move!=="others",o=r||e.priority==="urgent"?"urgent":e.priority==="high"?"high":"plain";return l("span",{className:V("shrink-0 whitespace-nowrap rounded-md px-2 py-0.5 text-xs font-semibold",n&&o==="plain"?"px-0 font-medium text-muted-foreground":"",o==="urgent"&&"bg-surface-destructive text-destructive-text",o==="high"&&"bg-warning/15 text-warning-text",o==="plain"&&!n&&"bg-muted text-foreground"),children:r?`Late \xB7 ${e.whenText}`:Gr(e.whenText)})}var Gr=e=>e.charAt(0).toUpperCase()+e.slice(1);function Aa({project:e}){return e.id==="personal"?null:l("span",{className:"inline-flex shrink-0 items-center rounded-md border border-border-hairline px-1.5 text-2xs font-semibold tracking-wide text-muted-foreground",title:e.name,children:e.key})}function um({task:e,onToggle:t,busy:n}){let r=e.status==="done";return l("button",{type:"button","aria-label":r?`Reopen ${e.title}`:`Mark ${e.title} done`,"aria-pressed":r,disabled:n,onClick:o=>{o.stopPropagation(),t()},className:V("mt-0.5 grid size-5 shrink-0 cursor-pointer place-items-center rounded-full border-[1.5px] transition-colors",r?"border-foreground bg-foreground text-background":"border-foreground/35 hover:border-foreground/70 hover:bg-state-hover"),children:r?l("svg",{viewBox:"0 0 24 24",className:"size-3",fill:"none",stroke:"currentColor",strokeWidth:"3.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:l("path",{d:"M20 6 9 17l-5-5"})}):null})}function FI(e,t){return e.origin==="assistant"?`Added by ${t}${e.why?` \xB7 ${e.why}`:""}`:e.source?.kind==="import"?`From you \xB7 carried over from ${e.source.ref}`:"From you"}function nS({task:e,assistant:t,now:n,rich:r=!1,onOpen:o,onToggle:s,trailing:i,first:a}){let u=Qr(e),c=e.move==="others"?`Waiting on ${e.waitingOn??"someone"}`:r?FI(e,t):e.say??e.why??e.description.split(`
140
+ `)[0]??"";return m("div",{className:V("group flex items-start gap-3 px-4 transition-colors hover:bg-state-hover",r?"py-3.5":"py-2.5",!a&&"border-t border-border-hairline"),children:[l(um,{task:e,onToggle:s}),m("button",{type:"button",onClick:o,className:"min-w-0 flex-1 cursor-pointer text-left",children:[m("span",{className:"flex min-w-0 items-center gap-2",children:[r?null:l(Ht,{glyph:u,className:"text-timeline-accent"}),l("span",{className:V("truncate",r?"text-base font-semibold":"text-sm font-medium"),children:e.title}),l(De,{origin:e.origin,assistant:t,size:15}),l(Aa,{project:e.project}),e.watch?l(Ht,{glyph:"watch",className:"size-3.5 text-timeline-accent"}):null]}),r?m("span",{className:"mt-1 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground",children:[l(Ht,{glyph:u,className:"size-3.5 text-foreground/70"}),l("span",{className:"shrink-0 font-medium text-foreground/80",children:xu[e.kind]}),l("span",{"aria-hidden":!0,children:"\xB7"}),l("span",{className:"truncate",children:c})]}):c?l("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:c}):null,m("span",{className:"mt-1.5 flex items-center gap-2 sm:hidden",children:[l(Ea,{task:e,now:n,quiet:!r}),l(ds,{level:e.priority})]}),r&&e.say?m("span",{className:"mt-2 flex max-w-2xl items-start gap-2 rounded-lg bg-surface-selected px-3 py-2 text-sm leading-snug",children:[l(De,{origin:"assistant",assistant:t,size:16}),l("span",{children:e.say})]}):null]}),m("span",{className:"hidden shrink-0 items-center gap-2.5 pt-0.5 sm:flex",children:[i,l(Ea,{task:e,now:n,quiet:!r}),l(ds,{level:e.priority})]})]})}function Fn({title:e,count:t,hint:n,children:r,action:o}){return m("section",{className:"space-y-2.5",children:[m("div",{className:"flex items-center gap-2",children:[l("h2",{className:"text-sm font-semibold",children:e}),t!==void 0?l("span",{className:"rounded-full bg-muted px-2 text-xs font-semibold text-muted-foreground",children:t}):null,n?l("span",{className:"ml-auto text-xs text-muted-foreground",children:n}):null,o]}),l("div",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:r})]})}function Oe({children:e}){return l("p",{className:"px-4 py-6 text-center text-sm text-muted-foreground",children:e})}function _t({label:e,value:t,options:n,onChange:r}){return l("div",{role:"radiogroup","aria-label":e,className:"inline-flex gap-0.5 rounded-lg bg-muted p-0.5",children:n.map(o=>l("button",{type:"button",role:"radio","aria-checked":t===o.value,onClick:()=>r(o.value),className:V("inline-flex cursor-pointer items-center gap-1.5 rounded-md px-3 py-1 text-xs font-semibold transition-colors",t===o.value?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:o.label},o.value))})}var rS="moonlet.tasks.filters";function zI(){try{let e=JSON.parse(globalThis.localStorage?.getItem(rS)??"null");if(e&&typeof e=="object"&&"origin"in e&&"project"in e)return{origin:e.origin==="owner"||e.origin==="assistant"?e.origin:"all",project:typeof e.project=="string"?e.project:""}}catch{}return{origin:"all",project:""}}var oS=null,lm=new Set;function bn(e){oS=e;try{globalThis.localStorage?.setItem(rS,JSON.stringify(e))}catch{}for(let t of lm)t()}function dm(){return[xt(t=>(lm.add(t),()=>lm.delete(t)),()=>oS??=zI()),bn]}var fs=e=>({...e.project?{project:e.project}:{},...e.origin!=="all"?{origin:e.origin}:{}});function Yr({filters:e,onChange:t,meta:n,children:r,origin:o=!0}){let s=n?.assistant??"Assistant";return m("div",{className:"flex flex-wrap items-center gap-3",children:[o?l(_t,{label:"Show tasks from",value:e.origin,onChange:i=>t({...e,origin:i}),options:[{value:"all",label:"All"},{value:"owner",label:m(he,{children:[l(De,{origin:"owner",assistant:s,size:14}),"From you"]})},{value:"assistant",label:m(he,{children:[l(De,{origin:"assistant",assistant:s,size:14}),`${s}\u2019s own`]})}]}):null,m("label",{className:"inline-flex items-center gap-2 text-xs text-muted-foreground",children:["Project",m("select",{value:e.project,onChange:i=>t({...e,project:i.target.value}),className:"h-8 cursor-pointer rounded-md border border-input bg-background px-2 text-xs font-medium text-foreground",children:[l("option",{value:"",children:"All projects"}),(n?.projects??[]).map(i=>m("option",{value:i.id,children:[i.name," (",i.key,")"]},i.id))]})]}),r]})}function hs(){let[e,t]=v(()=>Date.now());return M(()=>{let n=setInterval(()=>t(Date.now()),3e4);return()=>clearInterval(n)},[]),e}var eS=new Map;function Ge(e,t,n){let r=`${t}|${JSON.stringify(n)}`,o=eS.get(r);return o||(o=new Intl.DateTimeFormat(void 0,{timeZone:t,...n}),eS.set(r,o)),o.format(new Date(e))}var Ee=(e,t)=>Ge(e,t,{hour:"numeric",minute:"2-digit"}),tS=new Map;function ms(e,t){let n=tS.get(t);return n||(n=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}),tS.set(t,n)),n.format(new Date(e))}function Ct(e,t="long"){let n=Date.parse(`${e}T12:00:00Z`);return Ge(n,"UTC",t==="long"?{weekday:"long",day:"numeric",month:"long"}:{weekday:"short",day:"numeric",month:"short"})}var dr=(e,t="short")=>Ge(Date.parse(`${e}T12:00:00Z`),"UTC",{weekday:t});function qr(e,t){return new Date(Date.parse(`${e}T12:00:00Z`)+t*864e5).toISOString().slice(0,10)}function sS(){let e=J(),[t,n]=v(null),[r,o]=v(null),s=u=>o(u instanceof Error?u.message:String(u)),i=q(()=>{e.call("owner-changes.history",null).then(u=>n(u.declines),s)},[e]);M(i,[i]),ke("config",i),ke("owner-changes",i);let a=u=>{e.call("owner-changes.forget",{target:u}).then(()=>{o("Forgotten."),i()},s)};return m("section",{className:"space-y-2 text-sm","aria-label":"Declines your moonlet remembers",children:[l("h2",{className:"text-sm font-semibold",children:"Declines your moonlet remembers"}),l("p",{className:"text-xs text-muted-foreground",children:"For 30 days after you decline a change, your moonlet doesn't ask about the same thing again unless it has changed. Forget lets it ask now."}),r&&l("p",{role:"status",children:r}),t===null?null:t.length?l("ul",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised",children:t.map((u,c)=>m("li",{className:c?"flex items-center gap-3 border-t border-border-hairline px-4 py-2":"flex items-center gap-3 px-4 py-2",children:[m("span",{className:"min-w-0 flex-1",children:[u.target.replace(/^[^:]+:/,"")," \xB7 declined ",new Date(u.at).toLocaleDateString()]}),l(R,{size:"sm",variant:"ghost",onClick:()=>a(u.target),children:"Forget"})]},u.target))}):l("p",{className:"text-muted-foreground",children:"None."})]})}var Ca="activity",eo=e=>e.charAt(0).toUpperCase()+e.slice(1),fm=["timeline","since","week","behalf"];var bs=[{id:"timeline",label:"Today",short:"Today"},{id:"since",label:"Since you looked",short:"Since you looked"},{id:"week",label:"This week",short:"This week"},{id:"behalf",label:"On your behalf",short:"On your behalf"},{id:"needs",label:"Needs you",short:"Needs you"},{id:"undo",label:"You can undo",short:"You can undo"},{id:"work",label:"Work",short:"Work"},{id:"asks",label:"Asks and approvals",short:"Asks"},{id:"messages",label:"Messages",short:"Messages"},{id:"checks",label:"Checks and routines",short:"Checks"}],hm={undo:["change","filing"],work:["work","note"],asks:["approval"],messages:["message","relay"],checks:["check"]},KI={changed:["change","filing","learned"],work:["work","note"]},XI=e=>bs.some(t=>t.id===e),BI=/^\d{4}-\d{2}-\d{2}$/,UI=e=>{let t=Date.parse(`${e}T12:00:00Z`);return Number.isFinite(t)&&new Date(t).toISOString().slice(0,10)===e};function mm(e){let[t,...n]=(e??"").split("/").filter(Boolean),r=n[0]!==void 0&&BI.test(n[0]),o=r&&UI(n[0])?n[0]:null,s=(r?n[1]:n[0])??null;return{view:XI(t)?t:"timeline",day:o,entry:s?decodeURIComponent(s):null,landing:t===void 0}}var lS=(e,t,n)=>[e,t,n===null?null:encodeURIComponent(n)].filter(r=>r!==null).join("/"),je=e=>`${e.kind}:${e.id}`,iS=new Map;function bu(e,t){let n=iS.get(t);return n||(n=new Intl.DateTimeFormat("en-US",{timeZone:t,hourCycle:"h23",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}),iS.set(t,n)),Object.fromEntries(n.formatToParts(new Date(e)).flatMap(r=>r.type==="literal"?[]:[[r.type,Number(r.value)]]))}function aS(e,t){let n=bu(e,t);return Date.UTC(n.year,n.month-1,n.day,n.hour%24,n.minute,n.second)-(e-(e%1e3+1e3)%1e3)}function Jr(e,t){let n=Date.parse(`${e}T00:00:00Z`),r=n-aS(n,t);return n-aS(r,t)}function nn(e,t){return new Date(Date.parse(`${e}T12:00:00Z`)+t*864e5).toISOString().slice(0,10)}function yu(e,t){return{from:Jr(e,t),to:Jr(nn(e,1),t)}}var cS=(e,t)=>bu(e,t).hour%24,HI=[{from:21,label:"Late evening"},{from:17,label:"Evening"},{from:12,label:"Afternoon"},{from:9,label:"Late morning"},{from:6,label:"Early morning"},{from:0,label:"Overnight"}],VI=(e,t)=>HI.find(n=>cS(e,t)>=n.from).label,ZI=new Set(["running","sharing","queued","needs_person"]),gs=e=>e.kind==="work"&&e.endedAt===null&&ZI.has(e.state??""),WI=e=>e.kind==="check"&&e.title.startsWith("Check:");function xs(e){let t=e.state??"";return t==="running"?"running":t==="uncertain"?"unsure":t.startsWith("error")?"failed":t.startsWith("skipped")||t==="late-skipped"||t.startsWith("interrupted")?"skipped":WI(e)?t==="quiet"||t==="completed"?"quiet":"found":"done"}var pm=e=>e.kind==="check"&&(xs(e)==="quiet"||xs(e)==="done"),jI=new Set(["completed","nothing","hit","quiet","ok","sent","sent for the owner"]);function _u(e){return e.kind!=="check"||e.detail===null||jI.has(e.detail)||e.detail===e.state?null:eo(e.detail.replace(/^(?:error(?: \(exit \d+\))?|failed): /,""))}function uS(e,t,n,r){return e.filter(o=>(t==="everything"||o.kind==="visit"||KI[t].includes(o.kind))&&(!n||wm(o,n,r)))}function dS(e,t,n){let r=e.filter(gs),o=[];for(let s of e){if(gs(s))continue;let i=VI(s.at,t),a=o.at(-1);(!a||a.label!==i)&&(a={label:i,rows:[]},o.push(a)),s.kind==="visit"?a.rows.push({type:"visit",entry:s}):a.rows.push({type:"entry",entry:s})}if(!n)return{running:r,groups:o};for(let s of o){let i=s.rows.flatMap(c=>c.type==="entry"&&pm(c.entry)?[c.entry]:[]);if(i.length<2)continue;let a=s.rows.findIndex(c=>c.type==="entry"&&pm(c.entry)),u=s.rows.filter(c=>!(c.type==="entry"&&pm(c.entry)));u.splice(a,0,{type:"quiet",entries:i}),s.rows=u}return{running:r,groups:o}}function vu(e,t){let n=[];for(let r of e){let o=bu(r.at,t),s=`${o.year}-${String(o.month).padStart(2,"0")}-${String(o.day).padStart(2,"0")}`,i=n.at(-1);i?.day===s?i.entries.push(r):n.push({day:s,entries:[r]})}return n}var gm=[{id:"you",label:"With you"},{id:"work",label:"Work"},{id:"checks",label:"Checks"},{id:"changes",label:"Changes, asks"}];function QI(e){return e.kind==="visit"||e.actor==="owner"?"you":e.kind==="check"?"checks":e.kind==="change"||e.kind==="filing"||e.kind==="approval"||e.kind==="learned"?"changes":"work"}function pS(e,t){return e.kind==="work"&&e.ran.length?e.ran.map(n=>({from:n.from,to:n.to??t})):e.kind==="work"||e.kind==="visit"?[{from:e.startedAt??e.at,to:e.endedAt??(gs(e)?t:null)}]:[{from:e.at,to:null}]}function wu(e,t,n){let r=t.to-t.from,o=s=>Math.min(1,Math.max(0,(s-t.from)/r));return e.flatMap(s=>pS(s,n).filter(i=>i.from<t.to&&(i.to??i.from)>=t.from).map((i,a)=>({lane:QI(s),start:o(i.from),end:i.to===null||i.to<=i.from?null:o(i.to),ref:je(s),key:`${je(s)}#${a}`})))}function xm(e,t,n){let[r,o]=e<t?[e,t]:[t,e],s=n.to-n.from,i=15*6e4,a=n.from+Math.floor(r*s/i)*i,u=n.from+Math.ceil(o*s/i)*i;return{from:a,to:Math.max(u,a+i)}}var GI={queued:"Waiting its turn",running:"Working",sharing:"Working",needs_person:"Needs you",disposed:"Done",withdrawn:"Withdrawn",failed_before_run:"Didn\u2019t start"},YI={pending:"Waiting for your answer",applied:"Applied",undelivered:"Saved, not delivered yet",declined:"Declined",expired:"Expired",stale:"Asked again: its settings changed",withdrawn:"Withdrawn",reverted:"Undone"},qI={allow:"Allowed",deny:"Not allowed",pending:"Unanswered when Moonlet restarted"},JI={running:"Running",quiet:"Found nothing",found:"Found something",failed:"Failed",unsure:"Unsure how it went",skipped:"Skipped",done:"Done"},eP={delivered:"Delivered",read:"Delivered and read","not-woken":"Delivered, but the recipient couldn\u2019t be woken",held:"Held for you",discarded:"Discarded",refused:"Refused"},to={work:"Work",check:"Check",change:"Change to your moonlet",filing:"Library",approval:"Approval",message:"Message",relay:"Relay",learned:"Learned",note:"Task note",visit:"Visit"};function rn(e){let t=e.state;if(t===null)return null;switch(e.kind){case"work":return e.failed&&t==="parked"?"Its last turn failed":GI[t]??t.replaceAll("_"," ");case"check":return JI[xs(e)];case"change":return YI[t]??t;case"filing":return t==="undone"?"Undone":null;case"approval":return qI[t]??t;case"message":return eP[t]??t;case"relay":return eo(t.replaceAll("_"," "));default:return null}}function fS(e){let t=Math.max(1,Math.round(e/6e4));if(t<60)return`${t} min`;let n=Math.floor(t/60);return t%60?`${n} h ${t%60} min`:`${n} h`}function no(e,t){if(e.kind!=="work"&&e.kind!=="visit"&&e.kind!=="check")return null;let n=e.startedAt??(e.kind==="work"?null:e.at);if(n===null)return null;let r=e.endedAt??(gs(e)?t:null);return r===null||r<n?null:fS(r-n)}var Tt=(e,t,n)=>`${e===1?"one":e} ${e===1?t:n}`;function ro(e){let t=n=>e.filter(r=>r.kind===n);return{work:t("work").length,running:e.filter(gs).length,checks:t("check").length,found:t("check").filter(n=>xs(n)==="found").length,undoable:e.filter(n=>n.undo!==null).length,changes:t("change").length,filings:t("filing").length,asked:t("approval").length,allowed:t("approval").filter(n=>n.state?.startsWith("allow")).length,messages:t("message").length+t("relay").length,learned:t("learned").length}}function fr(e){return[e.work?`${Tt(e.work,"piece of work","pieces of work")}${e.running?`, ${e.running} still going`:""}`:null,e.checks?`${Tt(e.checks,"check or routine","checks and routines")}${e.found?`, ${e.found} found something`:""}`:null,e.changes||e.filings?`${Tt(e.changes+e.filings,"change","changes")}, ${e.undoable===0?"none":e.undoable} you can undo`:null,e.asked?`${Tt(e.asked,"approval","approvals")}, ${e.allowed===0?"none":e.allowed} allowed`:null,e.messages?Tt(e.messages,"message sent","messages sent"):null,e.learned?Tt(e.learned,"thing learned","things learned"):null].filter(t=>t!==null).map(eo)}function oo(e,t,n){let r=e.changes+e.filings,o=[e.work?`I worked on ${Tt(e.work,"thing","things")}${e.running?`, and ${e.running} ${e.running===1?"is":"are"} still going`:""}.`:null,e.checks?`I ran ${Tt(e.checks,"check or routine","checks and routines")}${e.found?`, and ${Tt(e.found,"check","checks")} found something`:""}.`:null,r?`I made ${Tt(r,"change","changes")}${e.undoable===0?"":e.undoable===r?`; you can undo ${r===1?"it":"them all"}`:`; you can undo ${e.undoable}`}.`:null].filter(u=>u!==null),s={today:"So far today","so-far":"So far today",day:"That day",away:"While you were away,",week:"So far this week","past-week":"That week"}[n],i={today:"A quiet day so far.","so-far":"A quiet day so far.",day:"A quiet day.",away:"It was quiet while you were away.",week:"A quiet week so far.","past-week":"A quiet week."}[n],a=o.length?`${s} ${o.join(" ")}`:i;return n==="day"||n==="so-far"||n==="past-week"||t===null?a:`${a} ${t===0?"Nothing needs your answer.":eo(`${Tt(t,"thing needs","things need")} your answer.`)}`}function zn(e,t){let n=Math.floor(e/36e5);if(n<1)return fS(e);if(n<24)return t==="short"?`${n} h`:`${n} ${n===1?"hour":"hours"}`;if(t==="short"){let s=Math.round(n/12)/2;return s===1?"1 day":`${Math.floor(s)}${Number.isInteger(s)?"":"\xBD"} days`}let r=Math.floor(n/24),o=n%24;return`${r} ${r===1?"day":"days"}${o?`, ${o} ${o===1?"hour":"hours"}`:""}`}function yn(e,t){let n=bu(e,t);return`${n.year}-${String(n.month).padStart(2,"0")}-${String(n.day).padStart(2,"0")}`}var tP=new Intl.DateTimeFormat("en-US",{timeZone:"UTC",weekday:"long"}),nP=new Intl.DateTimeFormat("en-US",{timeZone:"UTC",weekday:"long",day:"numeric",month:"long"});function bm(e,t){let n=Date.parse(`${e}T12:00:00Z`),r=Math.round((Date.parse(`${t}T12:00:00Z`)-n)/864e5);return r===0?"Today":r===1?"Yesterday":r>1&&r<7?tP.format(n):nP.format(n)}var ku=(e,t,n,r)=>`${bm(yn(e,n),yn(t,n))} ${r(e)}`;function hS(e,t,n,r,o){let s=bm(e,yn(n,r));return e===yn(t,r)&&s!=="Today"?`${s} from ${o(t)}`:s}function Su(e,t,n,r,o){let s=bm(yn(t,r),yn(n,r)),i=s==="Today"?"":s==="Yesterday"?"yesterday ":`on ${s} `;return`${e} wrote this ${i}at ${o(t)}`}function ym(e){let t=new Date(`${e}T12:00:00Z`).getUTCDay();return nn(e,-((t+6)%7))}var _m=e=>Array.from({length:7},(t,n)=>nn(e,n));function rP(e,t,n){return Math.max(0,Math.min(t,n.to)-Math.max(e,n.from))}function vm(e,t,n){let r=0;for(let o of e)if(o.kind==="work")for(let s of o.ran)r+=rP(s.from,s.to??n,t);return r/36e5}var Eu=e=>`${e<.05?0:e.toFixed(1)} h`;function mS(e,t,n){let r=new Map;for(let o of e){if(o.kind!=="work"&&o.kind!=="note"||o.task===null)continue;let s=o.task.project,i=r.get(s)??{work:[],notes:0,title:s};o.kind==="work"?i.work.push(o):i.notes++,r.set(s,i)}return[...r.entries()].map(([o,s])=>({key:o,title:s.title,hours:vm(s.work,t,n),done:s.work.filter(i=>i.state==="disposed").length,going:s.work.filter(gs).length,notes:s.notes})).sort((o,s)=>s.hours-o.hours||s.done-o.done||o.key.localeCompare(s.key))}function gS(e){let t=[e.done?Tt(e.done,"piece of work done","pieces of work done"):null,e.going?`${e.going} going`:null,e.notes?Tt(e.notes,"task note","task notes"):null].filter(n=>n!==null);return t.length?eo(t.join(", ")):"Nothing finished yet"}function xS(e){return e.filter(t=>t.kind==="approval"&&t.startedAt!==null).map(t=>({entry:t,ms:Math.max(0,t.at-(t.startedAt??t.at))})).sort((t,n)=>n.ms-t.ms)}var oP=new Set(["failed_before_run","cut_off","withdrawn"]),sP=new Set(["refused","failed"]);function bS(e){return e.filter(t=>t.kind==="work"&&(oP.has(t.state??"")||t.failed)||t.kind==="check"&&(xs(t)==="failed"||xs(t)==="unsure")||(t.kind==="message"||t.kind==="relay")&&sP.has(t.state??""))}function wm(e,t,n){return pS(e,n).some(r=>r.to===null||r.to<=r.from?r.from>=t.from&&r.from<t.to:r.from<t.to&&r.to>t.from)}function yS(e,t,n){let r=e.to-e.from;return n.map(o=>{let s=e.from+o*36e5,i=[s,s-36e5,s+36e5].find(a=>a>=e.from&&a<e.to&&cS(a,t)===o)??s;return{hour:o,at:(i-e.from)/r}})}function ys(e,t){let n=r=>(r.kind==="work"||r.kind==="visit")&&(r.at<t.from||r.at>=t.to);return e.some(n)?e.map(r=>{if(!n(r))return r;if(r.kind==="visit")return{...r,at:Math.min(Math.max(r.at,t.from),t.to-1)};let o=r.ran.find(a=>a.from<t.to&&(a.to===null||a.to>t.from)),s=r.steps.find(a=>a.at>=t.from&&a.at<t.to),i=o?Math.max(t.from,o.from):s?s.at:Math.min(Math.max(r.at,t.from),t.to-1);return{...r,at:i}}).sort((r,o)=>o.at-r.at):e}var _S=[{id:"mail",label:"Mail sent"},{id:"signin",label:"Signed in for you"},{id:"commands",label:"Commands with your keys"},{id:"git",label:"Pushed and merged"},{id:"messages",label:"Messages"}],pr="secret-use-send",_s=e=>e===pr?"Mail":e;function vS(e,t){let n=t.filter(r=>Sm(r)===e).map(r=>r.name);return e==="mail"&&!n.includes(pr)?[...n,pr]:n}var km=(e,t)=>e===t&&e!==pr;function wS(e,t,n){let r=km(e,t)?[e,pr]:[e],o=n.filter(s=>r.includes(s.capability));return o.length?{capability:e,uses:o.reduce((s,i)=>s+i.uses,0),changes:o.reduce((s,i)=>s+i.changes,0),asked:o.reduce((s,i)=>s+i.asked,0),refused:o.reduce((s,i)=>s+i.refused,0),last:Math.max(...o.map(s=>s.last))}:null}function Sm(e){return e.kind==="mail"?"mail":e.kind==="login"?"signin":e.kind!=="cli"&&e.kind!=="ssh"?null:/mail/i.test(e.name)?"mail":/^git(hub)?\b/i.test(e.name)?"git":"commands"}var Nu=[{level:"never-ask",label:"Never ask",about:"I use it without checking with you, sensitive commands included."},{level:"ask-changes",label:"Ask before changes",about:"Reading is free. A change waits for your yes, or one you already gave for it; sensitive ones ask every time."},{level:"always-ask",label:"Always ask",about:"Every use waits for your yes, or one you already gave for it; sensitive ones ask every time."},{level:"read-only",label:"Read only",about:"I can read with it but never change anything."}],Em=e=>Nu.find(t=>t.level===e)??null,iP={once:"You allowed it once",thread:"You allowed it for that conversation",always:"You allowed it from now on"};function kS(e){let t=e.startsWith("user: ")?iP[e.slice(6)]:void 0;return t||(e==="grant"?"Your earlier yes for this exact command":e==="thread"?"Your yes for that conversation":e==="standing decision"?"A standing permission":e.startsWith("existing owner decision")?"Your earlier decision":e==="level"||e==="read"||e==="owned-file"?"Its level allowed it":eo(e))}function SS(e){let t=[e.uses?Tt(e.uses,"use","uses"):"no uses",e.changes?`${e.changes} changed something`:null,e.asked?`${e.asked} asked you first`:null,e.refused?`${e.refused} refused`:"none refused"].filter(n=>n!==null);return eo(t.join(", "))}function _n(){let e=Ie();return q((t,n=null,r=null)=>e.toPluginPanel(Ca,{subPath:lS(t,r,n)}),[e])}function NS(e){ke("tasks",e),ke("approvals",e),ke("owner-changes",e),ke("config",e),ke("messages",e),ke("relay",e),ke("artifacts",e)}var AS=100;function Ss(e,t,n){let r=J(),[o,s]=v(null),[i,a]=v(""),u=G(()=>{}),c=q(()=>u.current(),[]),d=JSON.stringify([e.from,e.to,e.kinds,e.project,e.overlap===!0,e.behalf??null,t]);return M(()=>{let p=!0,f=!1,h=!1,g,x=async()=>{let _=[],w=null;for(let T=0;T<t;T++){let y=await r.call("activity.feed",{from:e.from,to:e.to,...e.kinds?{kinds:[...e.kinds]}:{},project:e.project,...e.overlap?{overlap:!0}:{},...e.behalf?{behalf:e.behalf}:{},before:w,limit:AS});if(!p)return null;if(_.push(...y.entries),w=y.next,!w)break}return{entries:_,more:w!==null}},b=async()=>{if(f){h=!0;return}f=!0,clearTimeout(g);do{h=!1;try{let _=await x();if(!p||!_)return;s({key:d,feed:_}),a("")}catch(_){if(!p)return;a(_ instanceof Error?_.message:String(_))}}while(h);f=!1,g=setTimeout(()=>{b()},3e4)};return u.current=()=>{b()},b(),()=>{p=!1,clearTimeout(g),u.current=()=>{}}},[r,d,n]),NS(c),{data:o?.key===d?o.feed:null,error:i,reload:c}}function Am(){let e=J(),[t,n]=v(null),[r,o]=v(""),[s,i]=v(0);return M(()=>{let a=!0;return e.call("activity.since",null).then(u=>{a&&(n(u),o(""))},u=>a&&o(u instanceof Error?u.message:String(u))),()=>{a=!1}},[e,s]),M(()=>{let a=setInterval(()=>i(u=>u+1),6e4);return()=>clearInterval(a)},[]),{data:t,error:r}}var ES=10,Au=60,Kn=Au*AS;function Es(e,t){let[n,r]=v(ES),o=Ss(e,n,t);M(()=>{o.data?.more&&n<Au&&r(i=>Math.min(Au,i+ES))},[o.data,n]);let s=o.data&&(!o.data.more||n>=Au)?o.data:null;return{data:s,error:o.error,partial:s?.more===!0}}var aP=e=>Object.hasOwn(to,e);function CS(e,t,n){let r=J(),[o,s]=v(0),i=q(()=>s(a=>a+1),[]);NS(i),M(()=>{if(e===null)return;let a=setInterval(i,3e4);return()=>clearInterval(a)},[e,i]),M(()=>{if(e===null)return;let a=e.indexOf(":"),u=e.slice(0,a);if(a<1||!aP(u))return;let c=!0;return r.call("activity.entry",{kind:u,id:e.slice(a+1)}).then(d=>{c&&d&&t([d])},()=>{}),()=>{c=!1}},[r,e,t,o,n])}function TS(e){let t=J(),n=J(),[r,o]=v(null),[s,i]=v(null);return{undo:q(async u=>{let c=u.undo;if(!c)return;let d=`${u.kind}:${u.id}`;i(d);try{let p=c.kind==="change"?{done:!0,text:(await t.call("owner-changes.undo",{id:c.id})).message}:await n.call("artifacts.undo",{id:c.id}).then(f=>f.state==="ok"?{done:!0,text:`Undone: ${f.summary}`}:{done:!1,text:`Not undone: ${f.reason}`});o({ref:d,...p})}catch(p){o({ref:d,done:!1,text:p instanceof Error?p.message:String(p)})}finally{i(null),e()}},[t,n,e]),said:r,busy:s}}var ws={jobs:[],held:0,checked:!1,error:null},Cu=new Set,ks=null,Nm,Tu=!1,vs=!1,Ta=0;async function Ru(){if(Tu){vs=!0;return}let e=Ta;clearTimeout(Nm),Tu=!0;try{do{vs=!1;let t=ks;if(!t)break;try{let n=await t(ws);if(e!==Ta)return;vs||(ws={...n,checked:!0})}catch(n){if(e!==Ta)return;vs||(ws={...ws,error:n instanceof Error?n.message:String(n)})}for(let n of Cu)n()}while(vs&&ks)}finally{e===Ta&&(Tu=!1,ks&&(Nm=setTimeout(()=>{Ru()},3e4)))}}function lP(e){return Cu.add(e),()=>{Cu.delete(e),!Cu.size&&(Ta++,ks=null,Tu=!1,vs=!1,clearTimeout(Nm),ws={jobs:[],held:0,checked:!1,error:null})}}function Cm(){let e=dn(),t=J(),n=J(),r=G(async()=>({jobs:[],held:0,error:null}));r.current=async i=>{let[a,u]=await Promise.all([t.call("work.parents",null),n.call("messages.state",null)]),{jobs:c,errors:d}=await fu(e,a),p=i.jobs.filter(f=>d.includes(f.interaction.threadId));return{jobs:[...c,...p].sort((f,h)=>f.interaction.createdAt-h.interaction.createdAt||f.interaction.id.localeCompare(h.interaction.id)),held:u.held.length,error:d.length?"Some work could not be checked. Trying again.":null}};let o=xt(lP,()=>ws);M(()=>{let i=ks===null;return ks=u=>r.current(u),i&&Ru(),e.subscribe({event:"thread:changed",callback:u=>{u.changes.some(c=>["interactions-changed","thread-created","thread-deleted","archived-changed"].includes(c))&&Ru()}})},[e]);let s=q(()=>{Ru()},[]);return ke("messages",s),ke("owner-changes",s),ke("approvals",s),o}var hr=e=>e.jobs.length+e.held,Ns=e=>e.checked&&!e.error?hr(e):null;function $u(e){let t=rt(),[n,r]=v(new Map),[o,s]=v(0),i=q(()=>s(u=>u+1),[]);ke("tasks",i),M(()=>{let u=setInterval(i,6e4);return()=>clearInterval(u)},[i]);let a=e.join(",");return M(()=>{let u=!0,c=a?a.split(","):[];return Promise.all(c.map(async d=>{let p=await t.call("tasks.journal",{day:d,limit:1});return[d,p.notes.find(f=>f.actor==="assistant")?.body??""]})).then(d=>u&&r(new Map(d.filter(([,p])=>p!==""))),()=>{}),()=>{u=!1}},[t,a,o]),n}var RS="text-sm max-md:pointer-coarse:text-base";var $S="h-[28px] w-[28px] rounded-md p-0 max-md:pointer-coarse:h-[36px] max-md:pointer-coarse:w-[36px]",qX=`${$S} [&_[data-icon-root]]:size-[16px] max-md:pointer-coarse:[&_[data-icon-root]]:size-[20px]`,JX=`${$S} [&_[data-icon-root]]:size-[13px] max-md:pointer-coarse:[&_[data-icon-root]]:size-[16px]`;var IS="h-9 max-md:pointer-coarse:h-10";var le=Rn(({className:e,type:t,...n},r)=>l("input",{type:t,autoComplete:"off",className:V(`flex w-full rounded-md border border-input bg-transparent pl-3 pr-3 py-1 ${ec} file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`,IS,RS,e),ref:r,...n}));le.displayName="Input";var cP={work:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94z",check:"M21 21l-4.3-4.3M19 11a8 8 0 1 1-16 0 8 8 0 0 1 16 0z",change:"M21 4h-7M10 4H3M21 12h-9M8 12H3M21 20h-5M12 20H3M14 2v4M8 10v4M16 18v4",filing:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2z",approval:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1zM9 12l2 2 4-4",message:"M14.54 21.69a.5.5 0 0 0 .94-.03l6.5-19a.5.5 0 0 0-.64-.63l-19 6.5a.5.5 0 0 0-.03.93l7.93 3.18a2 2 0 0 1 1.11 1.11zM21.85 2.15 10.91 13.09",relay:"M15 17l5-5-5-5M4 18v-2a4 4 0 0 1 4-4h12",learned:"M12 3l1.9 5.8L20 10.7l-6.1 1.9L12 18.5l-1.9-5.9L4 10.7l6.1-1.9z",note:"M12 20h9M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4z",visit:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12zM15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0z"};function vn({kind:e,className:t}){return l("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:V("size-4 shrink-0",t),children:l("path",{d:cP[e]})})}var uP={you:"bg-foreground/55",work:"bg-timeline-accent",checks:"bg-foreground/30",changes:"bg-warning"};function dP(e,t){return[e.kind==="check"?e.title.split(":")[0]??to.check:to[e.kind],rn(e),no(e,t),e.task?`${e.task.key}`:null].filter(Boolean).join(" \xB7 ")}function Ra(e){return e.kind==="check"?e.title.slice(e.title.indexOf(":")+1).trim()||e.title:e.kind==="approval"?`Asked to use ${e.title}`:e.title}function pP({entry:e,meta:t}){return e.actor==="system"?l("span",{className:"mt-1 block size-3.5 shrink-0 rounded-full border border-border bg-muted",title:"Moonlet itself"}):l(De,{origin:e.actor==="owner"?"owner":"assistant",assistant:t.assistant,size:16})}function so({entry:e,meta:t,now:n,onOpen:r,undo:o,first:s,showDay:i}){let a=Ie(),[u,c]=v(!1),d=je(e),p=_u(e),f=o.said?.ref===d?o.said:null;return m("li",{className:V("group grid grid-cols-[3.75rem_minmax(0,1fr)] gap-x-3 px-3 py-3 sm:grid-cols-[4.5rem_minmax(0,1fr)] sm:px-4",!s&&"border-t border-border-hairline"),children:[m("span",{className:"pt-0.5 text-right text-xs tabular-nums text-muted-foreground",children:[i?l("span",{className:"block",children:new Date(e.at).toLocaleDateString(void 0,{timeZone:t.zone,day:"numeric",month:"short"})}):null,Ee(e.at,t.zone)]}),m("div",{className:"min-w-0",children:[m("div",{className:"flex items-start gap-2.5",children:[l(vn,{kind:e.kind,className:V("mt-0.5",e.needsYou?"text-warning-text":"text-timeline-accent")}),m("button",{type:"button",onClick:()=>r(e),className:"min-w-0 flex-1 cursor-pointer text-left",children:[l("span",{className:V("block text-sm font-medium leading-snug",e.state==="undone"||e.state==="reverted"?"text-muted-foreground line-through":""),children:Ra(e)}),l("span",{className:"mt-0.5 block text-xs text-muted-foreground",children:dP(e,n)}),p?l("span",{className:"mt-1 block text-sm leading-snug",children:p}):null,e.kind==="approval"&&e.detail?l("code",{className:"mt-1.5 block truncate rounded-md bg-muted px-2 py-1 font-mono text-xs",children:e.detail.split(`
141
+ `)[0]}):e.detail&&e.kind!=="check"&&e.kind!=="message"&&e.kind!=="relay"?l("span",{className:"mt-1 line-clamp-2 block text-sm leading-snug text-foreground/85",children:e.detail}):null]}),l(pP,{entry:e,meta:t})]}),e.kind==="work"&&e.steps.length>1?m("div",{className:"mt-1.5 pl-6",children:[m("button",{type:"button","aria-expanded":u,onClick:()=>c(h=>!h),className:"inline-flex cursor-pointer items-center gap-1 text-xs font-semibold text-timeline-accent hover:underline",children:[l(pe,{name:u?"ChevronUp":"ChevronDown","aria-hidden":!0,className:"size-3"}),u?"Hide the steps":`${e.steps.length} steps`]}),u?l("ol",{className:"mt-1.5 space-y-1 border-l border-border-hairline pl-3",children:e.steps.map((h,g)=>m("li",{className:"grid grid-cols-[3.5rem_minmax(0,1fr)] gap-2 text-xs",children:[l("span",{className:"tabular-nums text-muted-foreground",children:Ee(h.at,t.zone)}),l("span",{className:"min-w-0 break-words",children:h.text})]},`${h.at}-${g}`))}):null]}):null,e.undo||e.thread&&e.kind==="work"||f?m("div",{className:"mt-2 flex flex-wrap items-center gap-2 pl-6",children:[e.undo&&!f?.done?l(R,{size:"sm",variant:"outline",disabled:o.busy!==null,onClick:()=>o.undo(e),children:"Undo"}):null,e.thread&&e.kind==="work"?l(R,{size:"sm",variant:"ghost",onClick:()=>a.toThread(e.thread),children:"Open conversation"}):null,f?l("span",{role:"status",className:f.done?"text-xs text-muted-foreground":"text-xs text-destructive",children:f.text}):null]}):null]})]})}function fP({entry:e,meta:t,now:n}){let r=no(e,n);return m("li",{className:"flex items-center gap-3 px-4 py-1.5","aria-label":`You looked in at ${Ee(e.startedAt??e.at,t.zone)}`,children:[l("span",{className:"h-px flex-1 bg-border-hairline"}),m("span",{className:"inline-flex items-center gap-1.5 text-xs font-semibold text-muted-foreground",children:[l(vn,{kind:"visit",className:"size-3.5"}),"You looked in at ",Ee(e.startedAt??e.at,t.zone),r&&r!=="1 min"?` for ${r}`:""]}),l("span",{className:"h-px flex-1 bg-border-hairline"})]})}function hP({entries:e,render:t}){let[n,r]=v(!1),o=[...new Set(e.map(s=>s.title.slice(s.title.indexOf(":")+1).trim()))];return n?l(he,{children:e.map((s,i)=>t(s,i===0))}):m("li",{className:"flex items-center gap-3 border-t border-border-hairline px-4 py-2.5 first:border-t-0",children:[l(vn,{kind:"check",className:"text-muted-foreground"}),m("span",{className:"min-w-0 flex-1 text-sm text-muted-foreground",children:[e.length," ran quietly: ",o.slice(0,3).join(", "),o.length>3?"\u2026":""]}),m("button",{type:"button",onClick:()=>r(!0),className:"cursor-pointer text-xs font-semibold text-timeline-accent hover:underline",children:["Show ",e.length]})]})}function PS({groups:e,meta:t,now:n,onOpen:r,undo:o}){let s=(i,a)=>l(so,{entry:i,meta:t,now:n,onOpen:r,undo:o,first:a},je(i));return l(he,{children:e.map((i,a)=>m("section",{"aria-label":i.label,className:"space-y-2",children:[l("h3",{className:"px-1 text-xs font-semibold text-muted-foreground",children:i.label}),l("ol",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:i.rows.map((u,c)=>u.type==="visit"?l(fP,{entry:u.entry,meta:t,now:n},je(u.entry)):u.type==="quiet"?l(hP,{entries:u.entries,render:s},`quiet-${je(u.entries[0])}`):s(u.entry,c===0||i.rows[c-1]?.type==="visit"))})]},`${i.label}-${a}`))})}function OS({entries:e,meta:t,now:n,onOpen:r}){let o=Ie();return e.length?m("section",{"aria-label":"Right now",className:"space-y-2",children:[l("h3",{className:"px-1 text-xs font-semibold text-muted-foreground",children:"Right now"}),l("ul",{className:"space-y-2",children:e.map(s=>m("li",{className:"flex flex-wrap items-center gap-3 rounded-xl border border-timeline-accent/40 bg-surface-selected px-4 py-3",children:[m("span",{className:"relative flex size-2.5 shrink-0",children:[l("span",{className:"absolute inline-flex size-full animate-ping rounded-full bg-timeline-accent opacity-60"}),l("span",{className:"relative inline-flex size-2.5 rounded-full bg-timeline-accent"})]}),m("button",{type:"button",onClick:()=>r(s),className:"min-w-0 flex-1 cursor-pointer text-left",children:[l("span",{className:"block text-sm font-semibold leading-snug",children:Ra(s)}),l("span",{className:"block text-xs text-muted-foreground",children:[rn(s),no(s,n)?`${no(s,n)} so far`:`since ${Ee(s.at,t.zone)}`,s.task?.key].filter(Boolean).join(" \xB7 ")})]}),s.thread?l(R,{size:"sm",variant:"outline",onClick:()=>o.toThread(s.thread),children:"Open conversation"}):null]},je(s)))})]}):null}var mP=[0,3,6,9,12,15,18,21],gP=e=>e===0?"12a":e<12?`${e}a`:e===12?"12p":`${e-12}p`;function LS({entries:e,span:t,now:n,zone:r,stretch:o,onStretch:s}){let i=G(null),[a,u]=v(null),c=wu(e,t,n),d=g=>{let x=i.current.getBoundingClientRect();return Math.min(1,Math.max(0,(g.clientX-x.left)/x.width))},p=t.to-t.from,f=a?xm(a.a,a.b,t):o,h=n>=t.from&&n<t.to?(n-t.from)/p:null;return m("section",{"aria-label":"The day by hour",className:"space-y-2",children:[m("div",{className:"flex items-center gap-2 px-1",children:[l("h3",{className:"text-xs font-semibold text-muted-foreground",children:"The day"}),l("span",{className:"ml-auto text-xs text-muted-foreground",children:o?m("button",{type:"button",onClick:()=>s(null),className:"cursor-pointer font-semibold text-timeline-accent hover:underline",children:["Showing ",Ee(o.from,r),"\u2013",Ee(o.to,r)," \xB7 show the whole day"]}):l("span",{className:"hidden sm:inline",children:"Drag across it to narrow the list"})})]}),m("div",{className:"grid grid-cols-[minmax(0,1fr)] gap-x-2 rounded-xl border border-border-hairline bg-surface-raised px-3 py-2.5 sm:grid-cols-[6rem_minmax(0,1fr)]",children:[l("div",{className:"hidden flex-col gap-1 text-2xs font-medium text-muted-foreground sm:flex","aria-hidden":!0,children:gm.map(g=>l("span",{className:"flex h-3.5 items-center",children:g.label},g.id))}),m("div",{ref:i,role:"presentation",className:"relative cursor-crosshair touch-none select-none",onPointerDown:g=>{g.currentTarget.setPointerCapture(g.pointerId);let x=d(g);u({a:x,b:x})},onPointerMove:g=>a&&u({a:a.a,b:d(g)}),onPointerUp:()=>{a&&(s(Math.abs(a.b-a.a)<.01?null:xm(a.a,a.b,t)),u(null))},onPointerCancel:()=>u(null),children:[l("div",{className:"flex flex-col gap-1",children:gm.map(g=>l("div",{className:"relative my-0.75 h-2 rounded-full bg-muted",children:c.filter(x=>x.lane===g.id).map(x=>l("span",{className:V("absolute top-0 h-2 rounded-full",uP[g.id]),style:{left:`${x.start*100}%`,width:x.end===null?"0.5rem":`max(0.5rem, ${(x.end-x.start)*100}%)`}},x.key))},g.id))}),f?l("span",{className:"pointer-events-none absolute -inset-y-1 rounded-md bg-timeline-accent/15 ring-1 ring-timeline-accent/50",style:{left:`${(f.from-t.from)/p*100}%`,width:`${(f.to-f.from)/p*100}%`}}):null,h!==null?l("span",{className:"pointer-events-none absolute -inset-y-1 w-0.5 rounded-full bg-timeline-accent",style:{left:`${h*100}%`}}):null,l("div",{className:"relative mt-1.5 h-3 text-2xs text-muted-foreground","aria-hidden":!0,children:yS(t,r,mP).map(g=>l("span",{className:"absolute -translate-x-1/2 first:translate-x-0",style:{left:`${g.at*100}%`},children:gP(g.hour)},g.hour))})]})]})]})}function on({eyebrow:e,title:t,children:n}){return m("div",{className:"flex flex-wrap items-end gap-3",children:[m("div",{className:"min-w-0 flex-1",children:[l("p",{className:"text-xs font-semibold text-muted-foreground",children:e}),l("h1",{className:"mt-0.5 text-2xl font-semibold tracking-tight",children:t})]}),n]})}function MS(e){let t=e.interaction.origin,n=t?.kind==="plugin"?t.rendererId:null;return n==="owner-changes"?"A change to your moonlet":n==="policy-proposal"?"A permission to decide":n==="approval"||e.interaction.payload.kind==="approval"?"An approval":"A question"}function As({needs:e,title:t="Needs you",hint:n="Stays here until you answer",now:r}){let o=_n(),s=hr(e);return!s&&!e.error?null:m("section",{"aria-label":t,className:"space-y-2",children:[m("div",{className:"flex items-center gap-2 px-1",children:[l("h2",{className:"text-sm font-semibold",children:t}),s?l("span",{className:"rounded-full bg-warning/15 px-2 text-xs font-semibold text-warning-text",children:s}):null,l("span",{className:"ml-auto text-xs text-muted-foreground",children:n})]}),m("ul",{className:"overflow-hidden rounded-xl border border-warning/40 bg-surface-raised shadow-sm",children:[e.jobs.slice(0,4).map((i,a)=>m("li",{className:V("flex items-center gap-3 px-4 py-3",a>0&&"border-t border-border-hairline"),children:[l(vn,{kind:"approval",className:"text-warning-text"}),m("span",{className:"min-w-0 flex-1",children:[l("span",{className:"block text-xs text-muted-foreground",children:r===void 0?MS(i):`Waiting ${zn(r-i.interaction.createdAt,"long")} \xB7 ${MS(i).toLowerCase()}`}),l("span",{className:"block truncate text-sm font-medium",children:i.title})]}),l(R,{size:"sm",variant:"outline",onClick:()=>o("needs"),children:"Answer"})]},i.interaction.id)),e.jobs.length>4?m("li",{className:"border-t border-border-hairline px-4 py-2.5 text-sm text-muted-foreground",children:[e.jobs.length-4," more in Needs you"]}):null,e.held?m("li",{className:V("flex items-center gap-3 px-4 py-3",e.jobs.length>0&&"border-t border-border-hairline"),children:[l(vn,{kind:"message",className:"text-warning-text"}),m("span",{className:"min-w-0 flex-1",children:[l("span",{className:"block text-xs text-muted-foreground",children:"Held messages"}),m("span",{className:"block text-sm font-medium",children:[e.held===1?"A message":`${e.held} messages`," from outside your conversations, waiting for your yes"]})]}),l(R,{size:"sm",variant:"outline",onClick:()=>o("needs"),children:"Read"})]}):null,e.error?l("li",{role:"status",className:V("px-4 py-2.5 text-sm text-muted-foreground",s>0&&"border-t border-border-hairline"),children:e.error}):null]})]})}var Tm=864e5,xP=366*Tm,Iu="standing";function bP(){let e=J(),t=We(()=>e.call("approvals.state",null),[e]);return ke("approvals",t.reload),t}function yP(e,t,n){return e==="month"?n-30*Tm:e==="year"?Jr(`${t.today.slice(0,4)}-01-01`,t.zone):null}function _P({entry:e,meta:t,levels:n,open:r,first:o}){let s=Ie(),i=e.kind==="approval",a=e.steps[0]?.text??"",u=i?n.get(e.title):void 0;return m("li",{className:V("grid grid-cols-[minmax(0,1fr)_auto] items-start gap-x-3 gap-y-1 px-4 py-3 sm:grid-cols-[4rem_minmax(0,1fr)_auto]",!o&&"border-t border-border-hairline"),children:[m("span",{className:"col-span-2 text-xs tabular-nums text-muted-foreground sm:col-span-1 sm:pt-0.5 sm:text-right",children:[m("span",{className:"sm:block",children:[Ge(e.at,t.zone,{weekday:"short"})," ",Ge(e.at,t.zone,{day:"numeric"})]}),l("span",{className:"sm:hidden",children:" \xB7 "}),Ee(e.at,t.zone)]}),m("div",{className:"flex min-w-0 items-start gap-2.5",children:[l(vn,{kind:e.kind,className:"mt-0.5 text-timeline-accent"}),m("button",{type:"button",onClick:()=>r(e),className:"min-w-0 flex-1 cursor-pointer text-left",children:[l("span",{className:"block break-words text-sm font-medium leading-snug",children:i?(e.detail??e.title).split(`
142
+ `)[0]:e.title}),m("span",{className:"mt-0.5 block text-xs text-muted-foreground",children:[i?`Used ${_s(e.title)}`:e.kind==="relay"?"Relayed to another machine":"Message to another conversation",!i&&rn(e)?` \xB7 ${rn(e)}`:""]}),i?m("span",{className:"mt-1 flex flex-wrap items-center gap-2 text-xs",children:[l("span",{className:"font-medium",children:kS(a)}),u?m("span",{className:"rounded-md border border-border-hairline px-1.5 py-0.5 text-muted-foreground",children:[_s(e.title)," now: ",Em(u)?.label.toLowerCase()??u]}):null]}):null]})]}),e.thread?m(R,{size:"sm",variant:"ghost","aria-label":"Conversation",onClick:()=>s.toThread(e.thread),children:[l(pe,{name:"MessageSquare","aria-hidden":!0,className:"size-4 sm:hidden"}),l("span",{className:"hidden sm:inline",children:"Conversation"})]}):l("span",{})]})}function vP({meta:e,now:t,state:n}){let r=J(),o=J(),[s]=v(()=>Date.now()-30*Tm),i=We(()=>o.call("activity.permissionUse",{from:s}),[o,s]);ke("approvals",i.reload);let[a,u]=v(null);if(!n.data||!i.data)return l("p",{className:"text-sm text-muted-foreground",children:n.error||i.error||"Loading\u2026"});let{mailSend:c}=n.data,d=n.data.capabilities.filter(y=>Sm(y)!==null),p=i.data,f=y=>wS(y,c,p),h=y=>{let E=f(y);return E!==null&&(E.uses>0||E.refused>0)},g=d.filter(y=>h(y.name)),x=d.filter(y=>!h(y.name)),b=n.data.standing.filter(y=>!y.revoked&&!y.expired),_=(y,E,k)=>{let N=Nu.find($=>$.level===k);N&&r.call("approvals.setCapability",{name:y,settings:{...E,level:N.level}}).then(()=>{u({key:y,text:`Now ${N.label.toLowerCase()}.`}),n.reload()},$=>u({key:y,text:$ instanceof Error?$.message:String($)}))},w=y=>{r.call("approvals.requestStandingRevoke",{id:y.id}).then(E=>{u({key:Iu,text:E.decision==="allow"?`Revoked: ${y.description}.`:E.decision==="pending"?`Asked to revoke ${y.description}; it ends once you confirm.`:E.reason??`${y.description} wasn\u2019t revoked.`}),n.reload()},E=>u({key:Iu,text:E instanceof Error?E.message:String(E)}))},T=y=>l("select",{"aria-label":`${_s(y.name)}: when to ask`,value:y.settings.level,onChange:E=>_(y.name,y.settings,E.target.value),className:"h-7 cursor-pointer rounded-md border border-input bg-background px-1.5 text-xs font-medium",children:Nu.map(E=>l("option",{value:E.level,title:E.about,children:E.label},E.level))});return m("div",{className:"space-y-3",children:[g.map(y=>{let E=f(y.name);return m("div",{className:"space-y-1 rounded-xl border border-border-hairline bg-surface-raised px-3 py-2.5",children:[m("div",{className:"flex items-center gap-2",children:[l("span",{className:"min-w-0 flex-1 truncate text-sm font-semibold",children:_s(y.name)}),T(y)]}),l("p",{className:"text-xs text-muted-foreground",children:Em(y.settings.level)?.about}),km(y.name,c)?l("p",{className:"text-xs text-muted-foreground",children:"Its level also decides the mail I send."}):null,l("p",{className:"text-sm",children:SS(E)}),m("p",{className:"text-xs text-muted-foreground",children:["Last: ",ku(E.last,t,e.zone,k=>Ee(k,e.zone))]}),a?.key===y.name?l("p",{role:"status",className:"text-xs text-muted-foreground",children:a.text}):null]},y.name)}),b.length||a?.key===Iu?m("div",{className:"space-y-2",children:[l("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Standing permissions"}),b.map(y=>m("div",{className:"space-y-1 rounded-xl border border-border-hairline bg-surface-raised px-3 py-2.5",children:[l("p",{className:"text-sm",children:y.description}),m("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[m("span",{className:"min-w-0 flex-1",children:["On ",y.station,y.expiresAt!==null?`, until ${Ge(y.expiresAt,e.zone,{day:"numeric",month:"short"})}`:""]}),l(R,{size:"sm",variant:"outline",onClick:()=>w(y),children:"Revoke"})]})]},y.id)),a?.key===Iu?l("p",{role:"status",className:"text-xs text-muted-foreground",children:a.text}):null]}):null,x.length?m("div",{className:"space-y-1.5",children:[l("h3",{className:"text-xs font-semibold text-muted-foreground",children:"Not used in 30 days"}),x.map(y=>m("div",{className:"flex items-center gap-2 text-sm",children:[l("span",{className:"min-w-0 flex-1 truncate",children:_s(y.name)}),T(y)]},y.name)),l("p",{className:"text-xs leading-snug text-muted-foreground",children:"You might not need these any more; Read only is the tightest."})]}):null,l("p",{className:"text-xs leading-snug text-muted-foreground",children:"Sensitive commands and how long questions wait are in Settings \u2192 Permissions."})]})}function DS({meta:e,now:t,open:n,signal:r,remember:o}){let s=J(),i=bP(),[a,u]=v(""),[c,d]=v(""),[p,f]=v("all"),[h,g]=v("anyone"),[x,b]=v(()=>({when:"all",chosen:Date.now()})),_=x.when,[w,T]=v(1),[y]=v(()=>Date.now()+xP);M(()=>{let j=setTimeout(()=>d(a.trim()),250);return()=>clearTimeout(j)},[a]),M(()=>T(1),[c,p,h,_]);let E=yP(_,e,x.chosen),k=i.data?.capabilities??[],N=j=>vS(j,k),$=We(()=>s.call("activity.behalfCounts",{from:E}),[s,E]),{data:P,error:L}=Ss({from:E??0,to:y,kinds:p==="all"?null:p==="messages"?["message","relay"]:["approval"],project:null,behalf:{capabilities:p==="all"||p==="messages"?null:N(p),search:c||null,who:h}},w,r);M(()=>{P&&o(P.entries)},[P,o]);let ne=new Map(k.map(j=>[j.name,j.settings.level])),se=i.data?ne.get(i.data.mailSend):void 0;se&&!ne.has(pr)&&ne.set(pr,se);let _e=j=>j==="messages"?$.data?.messages??0:($.data?.capabilities??[]).filter(Y=>N(j).includes(Y.capability)).reduce((Y,ee)=>Y+ee.count,0),ie=[];for(let j of P?.entries??[]){let Y=Ge(j.at,e.zone,{month:"long",year:"numeric"}),ee=ie.at(-1);ee?.month===Y?ee.entries.push(j):ie.push({month:Y,entries:[j]})}let Q=$.data?.since??null;return m("div",{className:"flex flex-wrap items-start gap-8",children:[m("div",{className:"min-w-0 flex-[999_1_34rem] space-y-5",children:[l(on,{eyebrow:"Activity",title:"On your behalf"}),l("p",{className:"text-sm text-muted-foreground",children:"Everything I did that left your machines or used your accounts, and who said yes to it. Search it by person, place or command."}),m("label",{className:"flex items-center gap-2",children:[l(pe,{name:"Search","aria-hidden":!0,className:"size-4 text-muted-foreground"}),l("span",{className:"sr-only",children:"Search the record"}),l(le,{value:a,onChange:j=>u(j.target.value),placeholder:"Search the record","aria-label":"Search the record"}),P?m("span",{className:"shrink-0 text-xs text-muted-foreground",children:[P.entries.length,P.more?"+":""," ",P.entries.length===1?"result":"results"]}):null]}),l("div",{className:"flex flex-wrap gap-1.5",role:"group","aria-label":"What",children:[{id:"all",label:"All kinds"},..._S].map(j=>m("button",{type:"button","aria-pressed":p===j.id,onClick:()=>f(j.id),className:V("cursor-pointer rounded-full px-3 py-1 text-xs font-semibold",p===j.id?"bg-foreground text-background":"bg-muted text-muted-foreground hover:text-foreground"),children:[j.label,j.id!=="all"&&$.data?` \xB7 ${_e(j.id)||"none"}`:""]},j.id))}),m("div",{className:"flex flex-wrap items-center gap-3",children:[l(_t,{label:"Who said yes",value:h,onChange:g,options:[{value:"anyone",label:"Anyone"},{value:"owner",label:"You"},{value:"standing",label:"A standing permission"},{value:"level",label:"Its level"}]}),l(_t,{label:"When",value:_,onChange:j=>b({when:j,chosen:Date.now()}),options:[{value:"all",label:"All time"},{value:"month",label:"Last 30 days"},{value:"year",label:"This year"}]})]}),!P||p!=="all"&&p!=="messages"&&!i.data?l(Oe,{children:L||i.error||"Loading\u2026"}):P.entries.length===0?l(Oe,{children:c?`Nothing on record for \u201C${c}\u201D.`:"Nothing on record for these choices."}):m("div",{className:"space-y-5",children:[ie.map(({month:j,entries:Y})=>m("section",{"aria-label":j,className:"space-y-2",children:[l("h2",{className:"px-1 text-xs font-semibold text-muted-foreground",children:j}),l("ol",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:Y.map((ee,be)=>l(_P,{entry:ee,meta:e,levels:ne,open:n,first:be===0},je(ee)))})]},j)),P.more?m(R,{variant:"ghost",onClick:()=>T(j=>j+1),children:[l(pe,{name:"ChevronDown","aria-hidden":!0,className:"size-4"}),"Show older"]}):m("p",{className:"px-1 text-sm text-muted-foreground",children:[c?`That\u2019s everything for \u201C${c}\u201D. `:"",Q!==null?`The record starts on ${Ge(Q,e.zone,{day:"numeric",month:"long",year:"numeric"})}${yn(Q,e.zone)===e.today?", today":""}, and nothing is ever trimmed from it.`:""]})]})]}),m("aside",{className:"w-full shrink-0 space-y-3 xl:w-80","aria-label":"Your permissions, last 30 days",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:"Your permissions, last 30 days"}),l(vP,{meta:e,now:t,state:i})]})]})}var wP=14,kP=366*864e5;function FS({since:e,meta:t,now:n,open:r,undo:o,needs:s,signal:i,remember:a}){let u=_n(),c=e.from,[d]=v(()=>Date.now()+kP),[p,f]=v(wP),{data:h,error:g,partial:x}=Es({from:c??0,to:d,kinds:null,project:null,overlap:!0},i);M(()=>{h&&a(h.entries)},[h,a]);let b=ys(h?.entries??[],{from:c??0,to:d}),_=vu(b.filter(N=>N.kind!=="visit"),t.zone),w=_.slice(0,p),T=$u(w.map(N=>N.day)),y=N=>Ee(N,t.zone);if(c===null)return m("div",{className:"mx-auto max-w-3xl space-y-6",children:[l(on,{eyebrow:"Activity",title:"Since you looked"}),l(Oe,{children:"There\u2019s no earlier visit to catch up from yet. Today\u2019s timeline has everything so far."}),l(R,{variant:"outline",onClick:()=>u("timeline"),children:"Open today"})]});let E=b.filter(N=>(N.kind==="change"||N.kind==="filing")&&N.state!=="undone"&&N.state!=="reverted"),k=ro(b);return m("div",{className:"flex flex-wrap items-start gap-8",children:[m("div",{className:"min-w-0 flex-[999_1_34rem] space-y-6",children:[l(on,{eyebrow:`Since you last looked \xB7 ${zn(n-c,"long")}`,title:`${ku(c,n,t.zone,y)} to now`,children:l(_t,{label:"Show",value:"since",onChange:N=>N==="today"&&u("timeline"),options:[{value:"since",label:"Since you looked"},{value:"today",label:"Just today"}]})}),e.note?m("div",{className:"flex items-start gap-3.5 rounded-2xl bg-surface-selected px-4 py-3.5",children:[l(De,{origin:"assistant",assistant:t.assistant,size:28}),m("div",{className:"min-w-0",children:[l("p",{className:"whitespace-pre-wrap text-base leading-relaxed",children:e.note.body}),l("p",{className:"mt-1.5 text-xs text-muted-foreground",children:Su(t.assistant,e.note.at,n,t.zone,y)})]})]}):h?m("div",{className:"flex items-start gap-3.5 rounded-2xl bg-surface-selected px-4 py-3.5",children:[l(De,{origin:"assistant",assistant:t.assistant,size:28}),l("p",{className:"text-base leading-relaxed",children:oo(k,Ns(s),"away")})]}):null,l(As,{needs:s,title:"Still waiting for you",hint:"Oldest first",now:n}),E.length?m("section",{"aria-label":"Changed while you were away",className:"space-y-2",children:[m("div",{className:"flex items-center gap-2 px-1",children:[l("h2",{className:"text-sm font-semibold",children:"Changed while you were away"}),l("span",{className:"ml-auto text-xs text-muted-foreground",children:"Undo is here while it can be"})]}),l("ol",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:E.map((N,$)=>l(so,{entry:N,meta:t,now:n,onOpen:r,undo:o,first:$===0,showDay:!0},je(N)))})]}):null,m("section",{"aria-label":"Day by day",className:"space-y-2",children:[m("div",{className:"flex items-center gap-2 px-1",children:[l("h2",{className:"text-sm font-semibold",children:"Day by day"}),l("span",{className:"ml-auto text-xs text-muted-foreground",children:"Newest first \xB7 open a day to read all of it"})]}),h?w.length===0?l(Oe,{children:"Nothing happened while you were away."}):l("ol",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:w.map(({day:N,entries:$},P)=>l("li",{className:P?"border-t border-border-hairline":void 0,children:m("div",{className:"flex items-start gap-3 px-4 py-3",children:[m("div",{className:"min-w-0 flex-1",children:[m("p",{className:"text-sm font-semibold",children:[hS(N,c,n,t.zone,y),m("span",{className:"ml-2 text-xs font-medium text-muted-foreground",children:[$.length," ",$.length===1?"entry":"entries",x&&P===_.length-1?" or more":""]})]}),l("p",{className:"mt-0.5 text-sm leading-snug text-foreground/85",children:T.get(N)??oo(ro($),0,N===yn(n,t.zone)?"so-far":"day")})]}),l(R,{size:"sm",variant:"outline",onClick:()=>u("timeline",null,N),children:"Open"})]})},N))}):l(Oe,{children:g||"Loading\u2026"}),h&&_.length>p?m(R,{variant:"ghost",onClick:()=>f(N=>N+7),children:[l(pe,{name:"ChevronDown","aria-hidden":!0,className:"size-4"}),"Show earlier days"]}):null,x?m("p",{className:"px-1 text-sm text-muted-foreground",children:["More than ",Kn.toLocaleString()," entries since you looked, so the summary and these counts cover the newest ",Kn.toLocaleString(),"."]}):null]})]}),m("aside",{className:"hidden w-72 shrink-0 space-y-2 xl:block","aria-label":"Done while you were away",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:"Done while you were away"}),h?fr(k).length?l("ul",{className:"space-y-1.5 text-sm",children:fr(k).map(N=>l("li",{children:N},N))}):l("p",{className:"text-sm text-muted-foreground",children:"Nothing yet."}):null]})]})}var zS={you:"bg-foreground/55",work:"bg-timeline-accent",checks:"bg-foreground/25",changes:"bg-warning"},SP=[{lane:"work",label:"Work"},{lane:"checks",label:"Checks and routines"},{lane:"you",label:"You"},{lane:"changes",label:"Changes and asks"}],KS=4;function EP(e){let t=J(),n=We(async()=>({week:e,...await t.call("activity.week",{week:e})}),[t,e]);return{data:n.data?.week===e?n.data:null,error:n.error,reload:n.reload}}function NP({entries:e,monday:t,today:n,meta:r,now:o}){let s=_n();return m("section",{"aria-label":"The week by hour",className:"space-y-2",children:[m("div",{className:"flex items-center gap-2 px-1",children:[l("h2",{className:"text-sm font-semibold",children:"The week by hour"}),l("span",{className:"ml-auto text-xs text-muted-foreground",children:"Pick a day to open it"})]}),m("div",{className:"space-y-1 rounded-xl border border-border-hairline bg-surface-raised px-3 py-3",children:[_m(t).map(i=>{let a=yu(i,r.zone),u=i>n,c=e.filter(f=>wm(f,a,o)),d=wu(c,a,o),p=vm(e,a,o);return m("button",{type:"button",disabled:u,onClick:()=>s("timeline",null,i),"aria-label":`${Ct(i)}: ${u?"ahead":`${Eu(p)} of work`}`,className:V("grid w-full cursor-pointer grid-cols-[3rem_minmax(0,1fr)_4.5rem] items-center gap-3 rounded-md px-1 py-1.5 text-left hover:bg-state-hover disabled:cursor-default disabled:hover:bg-transparent",i===n&&"bg-surface-selected"),children:[l("span",{className:V("text-xs font-semibold",u&&"text-muted-foreground"),children:dr(i)}),l("span",{className:V("relative h-3 rounded-full bg-muted",u&&"opacity-50"),children:d.map(f=>l("span",{className:V("absolute top-0.5 h-2 rounded-full",zS[f.lane]),style:{left:`${f.start*100}%`,width:f.end===null?"0.375rem":`max(0.375rem, ${(f.end-f.start)*100}%)`}},f.key))}),l("span",{className:"text-right text-xs tabular-nums text-muted-foreground",children:u?"ahead":`${Eu(p)}${i===n?" so far":""}`})]},i)}),l("div",{className:"flex flex-wrap gap-x-4 gap-y-1 px-1 pt-2 text-2xs text-muted-foreground","aria-hidden":!0,children:SP.map(i=>m("span",{className:"inline-flex items-center gap-1.5",children:[l("span",{className:V("size-2 rounded-full",zS[i.lane])}),i.label]},i.lane))})]})]})}function AP({entries:e,needs:t,meta:n,now:r,open:o}){let[s,i]=v(!1),a=xS(e),u=s?a:a.slice(0,KS),c=a.slice(KS);return!a.length&&!hr(t)?null:m("section",{"aria-label":"What's waited on you",className:"space-y-2",children:[m("div",{className:"flex items-center gap-2 px-1",children:[l("h2",{className:"text-sm font-semibold",children:"What\u2019s waited on you"}),l("span",{className:"ml-auto hidden text-xs text-muted-foreground sm:inline",children:"Open ones first, then the longest answered"})]}),l(As,{needs:t,title:"Waiting now",hint:"Oldest first",now:r}),u.length?l("ol",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:u.map(({entry:d,ms:p},f)=>l("li",{className:f?"border-t border-border-hairline":void 0,children:m("button",{type:"button",onClick:()=>o(d),className:"flex w-full cursor-pointer items-center gap-3 px-4 py-2.5 text-left hover:bg-state-hover",children:[m("span",{className:"min-w-0 flex-1",children:[m("span",{className:"block truncate text-sm font-medium",children:["Asked to use ",d.title]}),m("span",{className:"block text-xs text-muted-foreground",children:["Approval \xB7 asked ",Ge(d.startedAt??d.at,n.zone,{weekday:"short"})," ",Ee(d.startedAt??d.at,n.zone)]})]}),m("span",{className:"shrink-0 text-right text-xs",children:[l("span",{className:"block font-semibold tabular-nums",children:zn(p,"long")}),l("span",{className:"block text-muted-foreground",children:rn(d)})]})]})},je(d)))}):null,c.length&&!s?m("button",{type:"button",onClick:()=>i(!0),className:"cursor-pointer px-1 text-xs font-semibold text-timeline-accent hover:underline",children:["And ",c.length," more this week, all answered within ",zn(c[0].ms,"long"),". Show them"]}):null]})}function CP({entries:e,span:t,meta:n,now:r}){let o=tn(),s=mS(e,t,r);return s.length?m("section",{"aria-label":"Where the work has gone",className:"space-y-2",children:[l("h2",{className:"px-1 text-sm font-semibold",children:"Where the work has gone"}),l("ol",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:s.map((i,a)=>{let u=n.projects.find(c=>c.key===i.key);return m("li",{className:V("flex items-center gap-3 px-4 py-2.5",a>0&&"border-t border-border-hairline"),children:[m("div",{className:"min-w-0 flex-1",children:[m("p",{className:"flex flex-wrap items-baseline gap-x-2 text-sm",children:[l("span",{className:"font-medium",children:u?.name??i.key}),l("span",{className:"text-2xs font-bold tracking-wide text-muted-foreground",children:i.key}),l("span",{className:"whitespace-nowrap tabular-nums text-muted-foreground",children:Eu(i.hours)})]}),l("p",{className:"text-sm text-muted-foreground",children:gS(i)})]}),u?l(R,{size:"sm",variant:"ghost",onClick:()=>{bn({origin:"all",project:u.id}),o("today")},children:"Open"}):null]},i.key)})})]}):null}function XS({title:e,hint:t,entries:n,empty:r,meta:o,now:s,open:i,undo:a}){return m("section",{"aria-label":e,className:"space-y-2",children:[m("div",{className:"flex items-center gap-2 px-1",children:[l("h2",{className:"text-sm font-semibold",children:e}),t?l("span",{className:"ml-auto hidden text-xs text-muted-foreground sm:inline",children:t}):null]}),n.length?l("ol",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:n.map((u,c)=>l(so,{entry:u,meta:o,now:s,onOpen:i,undo:a,first:c===0,showDay:!0},je(u)))}):l("p",{className:"px-1 text-sm text-muted-foreground",children:r})]})}function TP({meta:e,today:t,monday:n}){let r=rt(),o=tn(),s=Math.max(1,7-Math.round((Date.parse(`${t}T12:00:00Z`)-Date.parse(`${n}T12:00:00Z`))/864e5)),{data:i}=We(()=>r.call("tasks.upcoming",{from:t,days:s}),[r,t,s]),a=(i?.items??[]).filter(u=>u.at>=Date.now()).slice(0,8);return m("section",{className:"space-y-2","aria-label":"Still ahead this week",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:"Still ahead this week"}),a.length===0?l("p",{className:"text-sm text-muted-foreground",children:"Nothing timed for the rest of the week."}):null,l("ol",{className:"space-y-1",children:a.map(u=>m("li",{className:"grid grid-cols-[5.5rem_minmax(0,1fr)] gap-2 text-sm",children:[m("span",{className:"text-xs tabular-nums text-muted-foreground",children:[Ge(u.at,e.zone,{weekday:"short"})," ",Ee(u.at,e.zone)]}),l("span",{className:"min-w-0 leading-snug",children:u.task.title})]},`${u.task.id}-${u.at}`))}),l("button",{type:"button",onClick:()=>o("upcoming"),className:"cursor-pointer text-xs font-semibold text-timeline-accent hover:underline",children:"See it in Tasks \u203A Upcoming"})]})}function BS({meta:e,now:t,open:n,undo:r,needs:o,signal:s,remember:i,initialDay:a}){let u=Ie(),c=J(),d=ym(e.today),[p,f]=v(ym(a??e.today)),h=p===d,g={from:Jr(p,e.zone),to:Jr(nn(p,7),e.zone)},{data:x,error:b,partial:_}=Es({...g,kinds:null,project:null,overlap:!0},s);M(()=>{x&&i(x.entries)},[x,i]);let w=EP(p),T=_m(p).filter(Q=>Q<=e.today),y=$u(T),[E,k]=v(!1),[N,$]=v(""),P=ys(x?.entries??[],g),L=ro(P),ne=Q=>Ee(Q,e.zone),se=()=>{k(!0),$(""),c.call("activity.talkWeek",{week:p}).then(({thread:Q})=>{k(!1),w.reload(),u.toThread(Q)},Q=>{k(!1),$(Q instanceof Error?Q.message:String(Q))})},_e=P.filter(Q=>Q.kind==="learned"||Q.kind==="change"),ie=bS(P);return m("div",{className:"flex flex-wrap items-start gap-8",children:[m("div",{className:"min-w-0 flex-[999_1_34rem] space-y-6",children:[m(on,{eyebrow:h?`This week so far \xB7 ${Ct(p)} to now`:`${Ct(p)} to ${Ct(nn(p,6))}`,title:`Week of ${Ge(Date.parse(`${p}T12:00:00Z`),"UTC",{month:"long",day:"numeric"})}`,children:[l(R,{variant:"outline",size:"icon","aria-label":"The week before",onClick:()=>f(nn(p,-7)),children:l(pe,{name:"ChevronLeft","aria-hidden":!0,className:"size-4"})}),l(R,{variant:"outline",size:"icon","aria-label":"The week after",disabled:h,onClick:()=>f(nn(p,7)),children:l(pe,{name:"ChevronRight","aria-hidden":!0,className:"size-4"})}),m(R,{onClick:se,disabled:E,children:[l(pe,{name:"MessageSquare","aria-hidden":!0,className:"size-4"}),w.data?.thread?"Back to this week\u2019s conversation":`Talk it over with ${e.assistant}`]})]}),N?l("p",{role:"alert",className:"text-sm text-destructive",children:N}):null,w.error&&!w.data?m("p",{role:"alert",className:"text-sm text-destructive",children:["I couldn\u2019t load the note for this week: ",w.error]}):null,w.data?.note?m("div",{className:"flex items-start gap-3.5 rounded-2xl bg-surface-selected px-4 py-3.5",children:[l(De,{origin:"assistant",assistant:e.assistant,size:28}),m("div",{className:"min-w-0",children:[l("p",{className:"whitespace-pre-wrap text-base leading-relaxed",children:w.data.note.body}),l("p",{className:"mt-1.5 text-xs text-muted-foreground",children:Su(e.assistant,w.data.note.at,t,e.zone,ne)})]})]}):x?m("div",{className:"flex items-start gap-3.5 rounded-2xl bg-surface-selected px-4 py-3.5",children:[l(De,{origin:"assistant",assistant:e.assistant,size:28}),l("p",{className:"text-base leading-relaxed",children:oo(L,Ns(o),h?"week":"past-week")})]}):null,_?m("p",{className:"px-1 text-sm text-muted-foreground",children:["This week has more than ",Kn.toLocaleString()," entries, so these counts cover the newest ",Kn.toLocaleString(),"."]}):null,x?m(he,{children:[l(NP,{entries:P,monday:p,today:e.today,meta:e,now:t}),h?l(AP,{entries:P,needs:o,meta:e,now:t,open:n}):null,l(CP,{entries:P,span:g,meta:e,now:t}),l(XS,{title:"How I\u2019ve changed",hint:"What I learned and what I changed about myself",entries:_e,empty:"No changes to me this week.",meta:e,now:t,open:n,undo:r}),l(XS,{title:"Hasn\u2019t gone well",entries:ie,empty:"Nothing went badly this week.",meta:e,now:t,open:n,undo:r})]}):l(Oe,{children:b||"Loading\u2026"})]}),m("aside",{className:"w-full shrink-0 space-y-6 xl:w-72","aria-label":"The week at a glance",children:[m("section",{className:"space-y-2","aria-label":"My note for each day",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:"My note for each day"}),l("dl",{className:"space-y-1.5 text-sm",children:T.map(Q=>m("div",{className:"grid grid-cols-[4.5rem_minmax(0,1fr)] gap-2",children:[l("dt",{className:"text-xs font-semibold text-muted-foreground",children:Q===e.today?"Today":dr(Q,"long")}),l("dd",{className:V("leading-snug",!y.get(Q)&&"text-muted-foreground"),children:y.get(Q)??"Not written yet."})]},Q))})]}),h?l(TP,{meta:e,today:e.today,monday:p}):null,x?m("section",{className:"space-y-2",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:h?"This week so far":"That week"}),l("ul",{className:"space-y-1.5 text-sm",children:fr(L).map(Q=>l("li",{children:Q},Q))})]}):null]})]})}var Pu=new Map;function RP(e){if(typeof window>"u"||!window.matchMedia)return null;let t=Pu.get(e);if(t)return t;let n=window.matchMedia(e),r=new Set,o=()=>{for(let s of r)s()};return t={mql:n,subscribe(s){let i=r.size===0;return r.add(s),i&&n.addEventListener("change",o),()=>{r.delete(s),r.size===0&&(n.removeEventListener("change",o),Pu.delete(e))}}},Pu.set(e,t),t}function $P(e,t){return RP(e)?.subscribe(t)??(()=>{})}function IP(e){return typeof window>"u"||!window.matchMedia?!1:Pu.get(e)?.mql.matches??window.matchMedia(e).matches}function Rm(e){return xt(t=>$P(e,t),()=>IP(e),()=>!1)}var PP="(max-width: 767px)",OP=Rf(null);function io(){let e=$f(OP),t=Rm(PP);return e!==null?e:t}var $m=globalThis.__bbPluginRuntime;if($m==null||$m.reactDom==null)throw new Error('Cannot load "react-dom": this bundle must be loaded by the Moonlet app, which provides the shared plugin runtime (globalThis.__bbPluginRuntime).');var Ou=$m.reactDom,sU="default"in Ou?Ou.default:Ou,{createPortal:US,flushSync:iU,preconnect:aU,prefetchDNS:lU,preinit:cU,preinitModule:uU,preload:dU,preloadModule:pU,requestFormReset:fU,unstable_batchedUpdates:hU,useFormState:mU,useFormStatus:gU,version:xU}=Ou;var LP="select-none",MP=new Set(["button","checkbox","file","hidden","image","radio","range","reset","submit"]),VS=e=>V(LP,e);function DP(e){return e instanceof HTMLTextAreaElement?!0:e instanceof HTMLInputElement?!e.disabled&&!e.readOnly&&!MP.has(e.type):e instanceof HTMLElement?e.isContentEditable||e.closest("[contenteditable='true']")!==null:!1}function Lu(e){if(typeof document>"u")return;let t=document.activeElement;!t||!DP(t)||e!==null&&!e.contains(t)||t.blur()}function ZS(){Lu(null)}function Im(e){e.preventDefault()}var HS="pointer";typeof document<"u"&&(document.addEventListener("keydown",()=>{HS="keyboard"},{capture:!0}),document.addEventListener("pointerdown",()=>{HS="pointer"},{capture:!0}));function WS(){let e="orbit";return{"data-bb-portaled-overlay":"","data-bb-plugin-root":"",...e!==void 0?{"data-bb-plugin":e}:{}}}var FP=120;var Pm="--bb-drawer-keyboard-inset",zP=80;function Mu(e){e!==null&&(e.style.height="",e.style.bottom="",e.style.removeProperty(Pm))}function KP({layoutViewportHeight:e,visualViewportHeight:t,visualViewportOffsetTop:n}){let r=Math.round(e-(t+n));return r>=zP?r:0}function XP(e,t){M(()=>{let n=e.current,r=window.visualViewport;if(n===null||!t||!r)return;let o=null,s=()=>{if(o=null,r.scale!==1){Mu(n);return}let a=KP({layoutViewportHeight:n.ownerDocument.documentElement.clientHeight,visualViewportHeight:r.height,visualViewportOffsetTop:r.offsetTop});if(a===0){n.style.bottom="",n.style.removeProperty(Pm);return}n.style.bottom=`${a}px`,n.style.setProperty(Pm,`${a}px`)},i=()=>{o!==null&&window.cancelAnimationFrame(o),o=window.requestAnimationFrame(s)};return s(),r.addEventListener("resize",i),r.addEventListener("scroll",i),()=>{r.removeEventListener("resize",i),r.removeEventListener("scroll",i),o!==null&&window.cancelAnimationFrame(o),Mu(n)}},[t,e])}var BP=Rn(({asChild:e,open:t,onOpenChange:n,haspopup:r,onClick:o,children:s,className:i,...a},u)=>{let c=VS(i),d=f=>{o?.(f),f.defaultPrevented||(t||ZS(),n(!t))},p={"aria-expanded":t,"aria-haspopup":r,"data-state":t?"open":"closed"};return e?l(Gl,{ref:u,onClick:d,onMouseDown:Im,className:c,...p,...a,children:s}):l("button",{ref:u,type:"button",onClick:d,onMouseDown:Im,className:c,...p,...a,children:s})});BP.displayName="MobileTrigger";var UP=["side","sideOffset","align","alignOffset","collisionPadding","collisionBoundary","arrowPadding","sticky","hideWhenDetached","avoidCollisions","onOpenAutoFocus","onCloseAutoFocus","onEscapeKeyDown","onPointerDownOutside","onFocusOutside","onInteractOutside"],PU=new Set(UP);function Du({open:e,enabled:t=!0}){let[n,r]=v(!1),o=q(()=>r(!0),[]);return M(()=>{if(!t||!e||n)return;let s=null,i=null;s=window.requestAnimationFrame(()=>{s=null,i=window.requestAnimationFrame(()=>{i=null,o()})});let a=window.setTimeout(o,FP);return()=>{s!==null&&window.cancelAnimationFrame(s),i!==null&&window.cancelAnimationFrame(i),window.clearTimeout(a)}},[t,n,e,o]),{isContentRealized:t&&n,realizeContent:o}}var jS="cubic-bezier(0.32, 0.72, 0, 1)",HP=.25,VP=450,ZP=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(","),Om=Symbol.for("bb.persistent-drawer-stack.v1");function WP(e){return typeof e=="object"&&e!==null&&"entries"in e&&Array.isArray(e.entries)&&"handleKeyDown"in e&&typeof e.handleKeyDown=="function"}function QS(e){let t=Reflect.get(e,Om);return WP(t)?t:void 0}function jP(e){return Array.from(e.querySelectorAll(ZP)).filter(t=>t.closest('[aria-hidden="true"], [inert]')===null)}function QP(e,t){let n=e?.closest("[data-bb-portaled-overlay]");return n!=null&&n!==t}function GP(e,t){let n=t.ownerDocument.activeElement;if(!t.contains(n)&&QP(n,t))return;let r=jP(t);if(e.preventDefault(),r.length===0){t.focus({preventScroll:!0});return}let o=r[0],s=r[r.length-1];if(e.shiftKey){if(!t.contains(n)||n===t||n===o){s?.focus({preventScroll:!0});return}let a=r.indexOf(n);r[Math.max(0,a-1)]?.focus({preventScroll:!0});return}if(!t.contains(n)||n===t||n===s){o?.focus({preventScroll:!0});return}let i=r.indexOf(n);r[Math.min(r.length-1,i+1)]?.focus({preventScroll:!0})}function YP(e,t){let n=QS(e);if(n===void 0){let r=[],o=s=>{if(s.defaultPrevented)return;let i=r[r.length-1],a=i?.panel()??null;i===void 0||a===null||(s.key==="Escape"?(i.dismissOnEscape(s),s.preventDefault()):s.key==="Tab"&&GP(s,a))};n={entries:r,handleKeyDown:o},Reflect.set(e,Om,n),e.addEventListener("keydown",o)}return n.entries.push(t),()=>{let r=QS(e);if(r===void 0)return;let o=r.entries.indexOf(t);o>=0&&r.entries.splice(o,1),r.entries.length===0&&(e.removeEventListener("keydown",r.handleKeyDown),Reflect.deleteProperty(e,Om))}}function qP({onAfterCloseAutoFocus:e,onBeforeCloseAutoFocus:t,onEscapeKeyDown:n,open:r,panelRef:o,requestClose:s}){let i=G(null),a=G(n);Ye(()=>{a.current=n},[n]),Ye(()=>{if(!r)return;let c=o.current;if(c===null)return;let d=c.ownerDocument,p=d.activeElement;i.current=p instanceof HTMLElement&&p!==d.body?p:null;let f=YP(d,{panel:()=>o.current,dismissOnEscape:h=>{a.current?.(h),h.defaultPrevented||s()}});return c.focus({preventScroll:!0}),f},[r,o,s]);let u=G(r);Ye(()=>{let c;if(u.current&&!r){t?.();let d=i.current;if(d?.isConnected&&d.closest('[aria-hidden="true"], [inert]')===null&&(d.focus({preventScroll:!0}),d.ownerDocument.activeElement!==d)){let p=d.ownerDocument.defaultView;if(p!==null){let f=p.requestAnimationFrame(()=>{d.isConnected&&d.closest('[aria-hidden="true"], [inert]')===null&&d.focus({preventScroll:!0}),e?.()});c=()=>p.cancelAnimationFrame(f)}}i.current=null,c===void 0&&e?.()}return u.current=r,c},[e,t,r])}function Fu({open:e,onOpenChange:t,onAfterCloseAutoFocus:n,closeOnBackdropClick:r=!0,srLabel:o,labelledBy:s,describedBy:i,contentClassName:a,motionDurationMs:u=220,onContentAnimationEnd:c,onEscapeKeyDown:d,onPointerDownOutside:p,onInteractOutside:f,children:h}){let g=G(null),x=G(null),b=G(null),_=G(null),w=G(null),T=Ci(),y=WS(),E=`transform ${u}ms ${jS}`,k=`opacity ${u}ms ${jS}`,N=G(t);Ye(()=>{N.current=t},[t]);let $=q(()=>{Lu(g.current),Mu(g.current),N.current(!1)},[]),P=q(()=>{Lu(g.current),Mu(g.current)},[]);qP({onAfterCloseAutoFocus:n,onBeforeCloseAutoFocus:P,onEscapeKeyDown:d,open:e,panelRef:g,requestClose:$});let L=()=>{let Y=b.current;if(b.current=null,!!r){if(Y!==null){let ee=new CustomEvent("dismissableLayer.pointerDownOutside",{cancelable:!0,detail:{originalEvent:Y}});if(p?.(ee),f?.(ee),ee.defaultPrevented)return}$()}};XP(g,e);let ne=q(Y=>{w.current!==Y&&(w.current=Y,c?.(Y))},[c]);M(()=>{w.current=null;let Y=window.setTimeout(()=>ne(e),u+50);return()=>window.clearTimeout(Y)},[u,e,ne]);let se=q((Y,ee,be)=>{let H=g.current,xe=x.current;H===null||xe===null||(H.style.transition=be?E:"none",H.style.transform=`translate3d(0, ${Y}px, 0)`,xe.style.transition=be?k:"none",xe.style.opacity=String(Math.max(0,Math.min(1,1-Y/ee))))},[k,E]),_e=q(Y=>{if(!e||Y.button!==0)return;Y.currentTarget.setPointerCapture(Y.pointerId);let ee=Date.now(),be=Math.max(g.current?.clientHeight??0,1);_.current={pointerId:Y.pointerId,startY:Y.clientY,lastY:Y.clientY,lastTimeMs:ee,velocityY:0,height:be},se(0,be,!1),Y.preventDefault()},[e,se]),ie=q(Y=>{let ee=_.current;if(ee===null||ee.pointerId!==Y.pointerId)return;let be=Date.now(),H=be-ee.lastTimeMs;H>0&&(ee.velocityY=(Y.clientY-ee.lastY)/H*1e3,ee.lastY=Y.clientY,ee.lastTimeMs=be),se(Math.max(0,Y.clientY-ee.startY),ee.height,!1),Y.preventDefault()},[se]),Q=q((Y,ee)=>{let be=_.current;if(be===null||be.pointerId!==Y.pointerId)return;_.current=null;let H=Math.max(0,Y.clientY-be.startY);!ee&&(H>=be.height*HP||be.velocityY>=VP)?(se(be.height,be.height,!0),$()):se(0,be.height,!0),Y.preventDefault()},[$,se]),j=typeof document>"u"?null:document.body;return j===null?null:US(m(he,{children:[l("div",{ref:x,...y,"aria-hidden":"true","data-persistent-drawer-backdrop":"","data-state":e?"open":"closed",className:"fixed inset-0 z-50 bg-black/40",style:{opacity:e?1:0,pointerEvents:e?"auto":"none",transition:k},onPointerDown:Y=>{b.current=Y.nativeEvent},onClick:L,onTouchMove:Y=>Y.preventDefault()}),m("div",{ref:g,...y,"aria-hidden":!e,"aria-labelledby":s??(o===void 0?void 0:T),"aria-describedby":i,"aria-modal":e||void 0,"data-bb-portaled-overlay":"","data-persistent-drawer-content":"","data-state":e?"open":"closed",inert:!e,role:"dialog",tabIndex:-1,className:V("fixed inset-x-0 bottom-0 z-50 mt-24 flex max-h-[calc(92dvh-var(--bb-drawer-keyboard-inset,0px))] flex-col rounded-t-xl border bg-background pb-[var(--bb-safe-area-bottom,env(safe-area-inset-bottom))] outline-none",a),style:{transform:e?"translate3d(0, 0, 0)":"translate3d(0, 100%, 0)",transition:E,willChange:e?"transform":void 0},onTransitionEnd:Y=>{Y.currentTarget===Y.target&&Y.propertyName==="transform"&&ne(e)},children:[l("div",{"data-persistent-drawer-handle":"",className:"mx-auto flex h-8 w-16 shrink-0 touch-none cursor-grab items-center justify-center active:cursor-grabbing",onPointerDown:_e,onPointerMove:ie,onPointerUp:Y=>Q(Y,!1),onPointerCancel:Y=>Q(Y,!0),children:l("div",{className:"h-1 w-10 rounded-full bg-muted-foreground/20"})}),o===void 0?null:l("h2",{id:T,className:"sr-only",children:o}),h]})]}),j)}function Ku({open:e,onClose:t,label:n,side:r="center",children:o}){let s=io(),{isContentRealized:i}=Du({open:e,enabled:s});return M(()=>{if(!e||s)return;let a=u=>{u.key==="Escape"&&(u.preventDefault(),t())};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[e,s,t]),s?l(Fu,{open:e,onOpenChange:a=>a?void 0:t(),srLabel:n,children:i?l("div",{className:"max-h-[85dvh] overflow-y-auto overscroll-contain pb-6",children:o}):null}):e?r==="right"?l("aside",{role:"dialog","aria-label":n,className:"fixed inset-y-0 right-0 z-40 flex w-full max-w-xl flex-col overflow-y-auto border-l border-border bg-background shadow-2xl",children:o}):l("div",{className:"fixed inset-0 z-40 grid place-items-center bg-surface-scrim p-4",onMouseDown:a=>a.target===a.currentTarget&&t(),children:l("div",{role:"dialog","aria-label":n,className:"max-h-[90dvh] w-full max-w-lg overflow-y-auto rounded-2xl border border-border bg-background shadow-2xl",children:o})}):null}var JP={todo:[{label:"Today",text:"today"},{label:"Tomorrow",text:"tomorrow"},{label:"This weekend",text:"this weekend"},{label:"Next week",text:"next week"},{label:"In a month",text:"in a month"}],followup:[{label:"Tomorrow morning",text:"check back tomorrow 9am"},{label:"In 3 days",text:"check back in 3 days 9am"},{label:"Next week",text:"check back next week 9am"}],scheduled:[{label:"Later today",text:"today 6pm"},{label:"Tomorrow morning",text:"tomorrow 9am"},{label:"Every weekday",text:"every weekday at 9am"},{label:"Every week",text:"every monday at 9am"},{label:"Monthly",text:"monthly on the 1st at 9am"}]};function tE({kind:e,zone:t,initial:n,onChange:r}){let o=rt(),[s,i]=v(n??""),[a,u]=v(null),c=G(r);c.current=r;let d=p=>{i(p),u(null),c.current(null,!p.trim())};return M(()=>{if(!s.trim()){u(null),c.current(null,!0);return}let p=!0,f=setTimeout(()=>{o.call("tasks.when",{text:s,kind:e}).then(h=>{p&&(u(h.ok?{ok:!0,reading:h.reading,next:h.next}:h),c.current(h.ok?h.when:null,h.ok))})},220);return()=>{p=!1,clearTimeout(f)}},[s,e,o]),m("div",{className:"space-y-2.5",children:[l(le,{"aria-label":"When, in your own words",placeholder:e==="scheduled"?"every other friday at 4pm":e==="followup"?"check back friday 9am":"by friday",value:s,onChange:p=>d(p.target.value)}),a?.ok?m("div",{className:"rounded-lg bg-surface-selected px-3 py-2 text-sm",children:[m("p",{className:"flex items-center gap-2 font-semibold",children:[l(pe,{name:"Check","aria-hidden":!0,className:"size-4 text-success"}),Gr(a.reading)]}),a.next.length?l("ul",{className:"mt-1.5 space-y-0.5 pl-6 text-xs text-muted-foreground",children:a.next.map(p=>m("li",{children:[Ge(p,t,{weekday:"short",day:"numeric",month:"short"})," \xB7 ",Ee(p,t)]},p))}):null]}):a?l("p",{role:"status",className:"text-sm text-destructive-text",children:a.error}):null,l("div",{className:"flex flex-wrap gap-1.5",children:JP[e].map(p=>l("button",{type:"button",className:"cursor-pointer rounded-full border border-border px-2.5 py-1 text-xs font-medium hover:bg-state-hover",onClick:()=>d(p.text),children:p.label},p.label))})]})}function ao({label:e,children:t}){return m("label",{className:"block space-y-1.5",children:[l("span",{className:"text-xs font-semibold text-muted-foreground",children:e}),t]})}var zu=["urgent","high","medium","low","none"],eO=["owner","assistant","others"];function Lm(e,t){return e.find(n=>n===t)??null}var GS="h-9 w-full cursor-pointer rounded-md border border-input bg-background px-2 text-sm";function nE({open:e,onClose:t,meta:n,onMade:r}){let{change:o,error:s,busy:i}=Na(),[a,u]=v(""),[c,d]=v("personal"),[p,f]=v("todo"),[h,g]=v(null),[x,b]=v(!0),[_,w]=v("medium"),[T,y]=v("assistant"),[E,k]=v(""),[N,$]=v(""),[P,L]=v(0),ne=n?.assistant??"Assistant",se=()=>{u(""),g(null),$(""),k(""),L(ie=>ie+1)};return l(Ku,{open:e,onClose:t,label:"New task",children:m("form",{onSubmit:async ie=>{if(ie.preventDefault(),!a.trim()||!x)return;let Q=await o({action:"create",task:{project:c,title:a,kind:p,when:h,priority:_,move:T,waitingOn:T==="others"&&E||null,description:N}});Q&&(se(),r(Q))},className:"space-y-4 p-5",children:[l("h2",{className:"text-lg font-semibold",children:"New task"}),l(ao,{label:"What",children:l(le,{autoFocus:!0,value:a,onChange:ie=>u(ie.target.value),placeholder:"Renew the passport"})}),l("div",{className:"flex flex-wrap items-center gap-3",children:l(_t,{label:"Kind",value:p,onChange:ie=>{f(ie),ie==="followup"&&y("others")},options:["todo","followup","scheduled"].map(ie=>({value:ie,label:m(he,{children:[l(Ht,{glyph:ie==="scheduled"?"once":ie,className:"size-3.5"}),xu[ie]]})}))})}),l(ao,{label:"When",children:l(tE,{kind:p,zone:n?.zone??"UTC",onChange:(ie,Q)=>{g(ie),b(Q)}},`${p}-${P}`)}),m("div",{className:"grid grid-cols-2 gap-3",children:[l(ao,{label:"Project",children:l("select",{className:GS,value:c,onChange:ie=>d(ie.target.value),children:(n?.projects??[{id:"personal",key:"ME",name:"Personal"}]).map(ie=>m("option",{value:ie.id,children:[ie.name," (",ie.key,")"]},ie.id))})}),l(ao,{label:"Priority",children:l("select",{className:GS,value:_,onChange:ie=>w(Lm(zu,ie.target.value)??"medium"),children:zu.map(ie=>l("option",{value:ie,children:us[ie]},ie))})})]}),l(ao,{label:"Whose move",children:l(_t,{label:"Whose move",value:T,onChange:y,options:[{value:"owner",label:"Mine"},{value:"assistant",label:`${ne}\u2019s`},{value:"others",label:"Waiting on someone"}]})}),T==="others"?l(ao,{label:"Waiting on",children:l(le,{value:E,onChange:ie=>k(ie.target.value),placeholder:"Acme Mutual"})}):null,l(ao,{label:"Notes",children:l("textarea",{value:N,onChange:ie=>$(ie.target.value),rows:3,className:"w-full resize-y rounded-md border border-input bg-background px-3 py-2 text-sm",placeholder:"Anything that helps"})}),s?l("p",{role:"alert",className:"text-sm text-destructive-text",children:s}):null,m("div",{className:"flex justify-end gap-2 pt-1",children:[l(R,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),l(R,{type:"submit",disabled:i||!a.trim()||!x||T==="others"&&!E.trim(),children:"Add task"})]})]})})}var tO=/^(?:https?:\/\/[^\s]+|\/api\/v1\/plugins\/tasks\/http\/attachments\/download\?attachmentId=[A-Za-z0-9_%-]+)$/i,YS="inline-flex max-w-full items-center gap-1.5 truncate rounded-md border border-border px-2 py-1 text-xs font-medium";function nO({link:e}){let t=Ie(),n=tn(),r=m(he,{children:[l(pe,{name:e.kind==="pull_request"?"GitPullRequest":e.kind==="mail"?"Mail":e.kind==="conversation"?"ChildThread":"ExternalLink","aria-hidden":!0,className:"size-3.5"}),l("span",{className:"truncate",children:e.label??e.ref})]}),o=V(YS,"cursor-pointer hover:bg-state-hover");if(e.kind==="conversation"&&/^thr_[A-Za-z0-9_-]+$/.test(e.ref))return l("button",{type:"button",className:o,title:"Open the conversation",onClick:()=>t.toThread(e.ref),children:r});if(e.kind==="task")return l("button",{type:"button",className:o,title:"Open the task",onClick:()=>n("today",e.ref),children:r});if(tO.test(e.ref)){let s=e.ref.startsWith("/");return l("a",{href:e.ref,className:o,title:e.ref,...s?{download:e.label??!0}:{target:"_blank",rel:"noreferrer noopener"},children:r})}return l("span",{className:YS,title:e.ref,children:r})}var qS=200,JS=1e4,eE=e=>({owner:"Your move",assistant:`${e}\u2019s move`,others:"Waiting on others"});function rE({open:e,taskRef:t,meta:n,onClose:r}){let[o,s]=v("Task");return l(Ku,{open:e,onClose:r,label:o,side:"right",children:t?l(rO,{taskRef:t,meta:n,onClose:r,onLabel:s},t):null})}function rO({taskRef:e,meta:t,onClose:n,onLabel:r}){let o=rt(),{change:s,error:i}=Na(),[a,u]=v(!1),[c,d]=v(""),[p,f]=v(qS),{data:h,error:g}=We(()=>o.call("tasks.show",{ref:e,recent:p}),[o,e,p]),[x,b]=v(""),[_,w]=v(""),[T,y]=v(!1),[E,k]=v({when:null,ok:!1}),[N,$]=v(!1),[P,L]=v(""),[ne,se]=v(!1),[_e,ie]=v(""),Q=t?.assistant??"Assistant",j=t?.zone??"UTC",Y=h?.task.title??"Task";if(M(()=>r(Y),[Y,r]),!h)return l("p",{className:"p-6 text-sm text-muted-foreground",children:g||"Loading\u2026"});let ee=h.task,be=ee.id;return m(he,{children:[m("div",{className:"flex items-center gap-2 border-b border-border-hairline px-5 py-3 text-xs text-muted-foreground",children:[l("span",{className:"font-semibold text-foreground",children:ee.key}),l("span",{"aria-hidden":!0,children:"\xB7"}),l("span",{children:ee.project.name}),h.aliases.length?m("span",{children:["\xB7 also ",h.aliases.join(", ")]}):null,l(R,{variant:"ghost",size:"icon",className:"ml-auto size-8","aria-label":"Close",onClick:n,children:l(pe,{name:"ChevronRight","aria-hidden":!0,className:"size-4"})})]}),m("div",{className:"space-y-6 px-5 py-5",children:[m("div",{className:"flex items-start gap-3",children:[l(um,{task:ee,onToggle:()=>{s(ee.status==="open"?{action:"done",ref:be,note:null}:{action:"reopen",ref:be,why:null})}}),ne?l("form",{className:"flex-1",onSubmit:H=>{H.preventDefault(),s({action:"update",ref:be,patch:{title:_e}}).then(xe=>xe&&se(!1))},children:l(le,{autoFocus:!0,value:_e,onChange:H=>ie(H.target.value),onBlur:()=>se(!1),"aria-label":"Title"})}):l("button",{type:"button",className:V("flex-1 cursor-text text-left text-xl font-semibold leading-snug",ee.status!=="open"&&"text-muted-foreground line-through"),onClick:()=>{ie(ee.title),se(!0)},children:ee.title})]}),m("dl",{className:"grid grid-cols-[7rem_minmax(0,1fr)] items-center gap-x-3 gap-y-2.5 text-sm",children:[l("dt",{className:"text-muted-foreground",children:"Kind"}),m("dd",{className:"flex items-center gap-1.5 font-medium",children:[l(Ht,{glyph:Qr(ee),className:"text-timeline-accent"}),xu[ee.kind]]}),l("dt",{className:"text-muted-foreground",children:"Whose move"}),m("dd",{className:"flex flex-wrap items-center gap-2",children:[l("select",{"aria-label":"Whose move",className:"h-8 cursor-pointer rounded-md border border-input bg-background px-2 text-sm font-medium",value:a?"others":ee.move,onChange:H=>{let xe=Lm(eO,H.target.value);xe&&(xe==="others"?(d(ee.waitingOn??""),u(!0)):(u(!1),s({action:"update",ref:be,patch:{move:xe}})))},children:Object.entries(eE(Q)).map(([H,xe])=>l("option",{value:H,children:H==="others"&&ee.waitingOn?`Waiting on ${ee.waitingOn}`:xe},H))}),a?m("form",{className:"flex gap-2",onSubmit:H=>{H.preventDefault(),c.trim()&&s({action:"update",ref:be,patch:{move:"others",waitingOn:c}}).then(xe=>xe&&u(!1))},children:[l(le,{autoFocus:!0,value:c,onChange:H=>d(H.target.value),placeholder:"Who it waits on","aria-label":"Who it waits on",className:"h-8 w-44 text-sm"}),l(R,{size:"sm",type:"submit",disabled:!c.trim(),children:"Save"})]}):null]}),l("dt",{className:"text-muted-foreground",children:"From"}),m("dd",{className:"flex min-w-0 items-center gap-2",children:[l(De,{origin:ee.origin,assistant:Q,size:18}),l("span",{className:"truncate",children:ee.origin==="assistant"?`${Q}${ee.why?`: ${ee.why}`:""}`:"You"})]}),l("dt",{className:"text-muted-foreground",children:"Priority"}),m("dd",{className:"flex items-center gap-2",children:[l(ds,{level:ee.priority}),l("select",{"aria-label":"Priority",className:"h-8 cursor-pointer rounded-md border border-input bg-background px-2 text-sm font-medium",value:ee.priority,onChange:H=>{let xe=Lm(zu,H.target.value);xe&&s({action:"update",ref:be,patch:{priority:xe}})},children:zu.map(H=>l("option",{value:H,children:us[H]},H))})]}),l("dt",{className:"text-muted-foreground",children:"Project"}),l("dd",{children:l("select",{"aria-label":"Project",className:"h-8 cursor-pointer rounded-md border border-input bg-background px-2 text-sm font-medium",value:ee.project.id,onChange:H=>{s({action:"move",ref:be,project:H.target.value})},children:(t?.projects??[ee.project]).map(H=>m("option",{value:H.id,children:[H.name," (",H.key,")"]},H.id))})}),ee.doneWhen?m(he,{children:[l("dt",{className:"self-start text-muted-foreground",children:"Done when"}),l("dd",{className:"leading-relaxed",children:ee.doneWhen})]}):null]}),m("div",{className:"rounded-xl bg-surface-selected px-4 py-3.5",children:[l("p",{className:"text-xs font-semibold text-muted-foreground",children:ee.kind==="followup"?"Next check":ee.kind==="scheduled"?"When":"Due"}),T?m("div",{className:"mt-2 space-y-3",children:[l(tE,{kind:ee.kind,zone:j,onChange:(H,xe)=>k({when:H,ok:xe})}),m("div",{className:"flex gap-2",children:[l(R,{size:"sm",disabled:!E.ok,onClick:()=>{s({action:"update",ref:be,patch:{when:E.when}}).then(H=>H&&y(!1))},children:"Save"}),l(R,{size:"sm",variant:"outline",onClick:()=>y(!1),children:"Cancel"})]})]}):m(he,{children:[l("p",{className:"mt-0.5 text-base font-semibold",children:ee.whenText?Gr(ee.whenText):"Not set"}),ee.dueAt?l("p",{className:"text-xs text-muted-foreground",children:Ge(ee.dueAt,j,{weekday:"long",day:"numeric",month:"long",hour:"numeric",minute:"2-digit"})}):null,m("div",{className:"mt-3 flex flex-wrap gap-2",children:[m(R,{size:"sm",variant:"outline",onClick:()=>y(!0),children:[l(pe,{name:"Clock","aria-hidden":!0,className:"size-3.5"}),"Change when"]}),ee.status==="open"&&ee.move!=="owner"?l(R,{size:"sm",variant:"outline",onClick:()=>{s({action:"update",ref:be,patch:{move:"owner",why:"you took it over"}})},children:"I\u2019ll take it from here"}):null]})]})]}),ee.description?l("p",{className:"whitespace-pre-wrap text-sm leading-relaxed text-foreground/90",children:ee.description}):null,m("section",{className:"space-y-2",children:[m("h3",{className:"text-sm font-semibold",children:["Steps"," ",h.steps.length?m("span",{className:"font-normal text-muted-foreground",children:[h.steps.filter(H=>H.doneAt).length," of ",h.steps.length]}):null]}),l("ul",{className:"space-y-1",children:h.steps.map(H=>m("li",{className:"flex items-center gap-2.5 text-sm",children:[l("input",{type:"checkbox","aria-label":H.title,className:"size-4 cursor-pointer accent-foreground",checked:H.doneAt!==null,onChange:xe=>{s({action:"checkStep",ref:be,position:H.position,done:xe.target.checked})}}),l("span",{className:V(H.doneAt&&"text-muted-foreground line-through"),children:H.title}),H.doneBy?l("span",{className:"ml-auto text-xs text-muted-foreground",children:H.doneBy==="assistant"?Q:H.doneBy==="owner"?"You":"System"}):null]},H.position))}),l("form",{className:"flex gap-2",onSubmit:H=>{H.preventDefault(),_.trim()&&s({action:"addStep",ref:be,title:_}).then(xe=>xe&&w(""))},children:l(le,{value:_,onChange:H=>w(H.target.value),placeholder:"Add a step","aria-label":"Add a step",className:"h-8 text-sm"})})]}),h.links.length?m("section",{className:"space-y-2",children:[l("h3",{className:"text-sm font-semibold",children:"Linked"}),l("div",{className:"flex flex-wrap gap-2",children:h.links.map(H=>l(nO,{link:H},`${H.kind}:${H.ref}`))})]}):null,m("section",{className:"space-y-3",children:[l("h3",{className:"text-sm font-semibold",children:"Journal"}),h.earlier!==null?p<JS?m("button",{type:"button",onClick:()=>f(H=>Math.min(H+qS,JS)),className:"flex cursor-pointer items-center gap-2 text-sm font-semibold text-timeline-accent hover:underline",children:[l(pe,{name:"ChevronUp","aria-hidden":!0,className:"size-3.5"}),"Show earlier"]}):m("p",{className:"text-xs text-muted-foreground",children:["Earlier lines: moonlet orbit tasks journal --task ",h.task.key," --before ",h.earlier]}):null,l("ol",{className:"relative space-y-3 border-l border-border-hairline pl-5",children:h.journal.map(H=>m("li",{className:"relative",children:[l("span",{className:"absolute -left-[1.85rem] top-0.5",children:H.actor==="system"?l("span",{className:"block size-4 rounded-full border border-border bg-muted"}):l(De,{origin:H.actor==="assistant"?"assistant":"owner",assistant:Q,size:18})}),m("p",{className:"text-xs text-muted-foreground",children:[Ge(H.at,j,{weekday:"short",day:"numeric",month:"short"})," \xB7 ",Ee(H.at,j)," \xB7"," ",H.actor==="assistant"?Q:H.actor==="owner"?"You":"System"]}),l("p",{className:V("mt-0.5 whitespace-pre-wrap text-sm leading-relaxed",H.actor==="owner"&&H.what==="note"&&"rounded-lg bg-muted px-3 py-2",H.what==="created"&&"text-muted-foreground"),children:H.body})]},H.seq))}),m("form",{className:"flex gap-2",onSubmit:H=>{H.preventDefault(),x.trim()&&s({action:"note",ref:be,body:x}).then(xe=>xe&&b(""))},children:[l(le,{value:x,onChange:H=>b(H.target.value),placeholder:`Add a note, or something for ${Q} to know`,"aria-label":"Add a note"}),l(R,{type:"submit",disabled:!x.trim(),children:"Add"})]})]}),i?l("p",{role:"alert",className:"text-sm text-destructive-text",children:i}):null,m("div",{className:"flex flex-wrap items-center gap-2 border-t border-border-hairline pt-4",children:[ee.status==="open"?m(he,{children:[m(R,{size:"sm",onClick:()=>{s({action:"done",ref:be,note:null})},children:[l(pe,{name:"Check","aria-hidden":!0,className:"size-3.5"}),"Done"]}),N?m("form",{className:"flex flex-1 gap-2",onSubmit:H=>{H.preventDefault(),P.trim()&&s({action:"drop",ref:be,reason:P}).then(xe=>xe&&$(!1))},children:[l(le,{autoFocus:!0,value:P,onChange:H=>L(H.target.value),placeholder:"Why it no longer matters","aria-label":"Why drop it",className:"h-8 text-sm"}),l(R,{size:"sm",variant:"outline",type:"submit",disabled:!P.trim(),children:"Drop"})]}):l(R,{size:"sm",variant:"outline",onClick:()=>$(!0),children:"Drop"})]}):m(R,{size:"sm",variant:"outline",onClick:()=>{s({action:"reopen",ref:be,why:null})},children:[l(pe,{name:"RotateCcw","aria-hidden":!0,className:"size-3.5"}),"Reopen"]}),m("span",{className:"ml-auto text-xs text-muted-foreground",children:[ee.status==="open"?eE(Q)[ee.move]:ee.status==="done"?"Done":`Dropped: ${ee.reason??""}`,ee.closedAt?` \xB7 ${Ge(ee.closedAt,j,{day:"numeric",month:"short"})}`:""]})]})]})]})}function oO(e,t){let n=Ge(e.at,t.zone,{weekday:"long",day:"numeric",month:"long"}),r=e.startedAt??e.at,o=e.endedAt;return o!==null&&o-r>=6e4?`${n}, ${Ee(r,t.zone)}\u2013${Ee(o,t.zone)}`:`${n}, ${Ee(e.at,t.zone)}`}function sO(e,t){return e.actor==="owner"?"You":e.actor==="system"?"Moonlet itself":t.assistant}function oE({entry:e,open:t,meta:n,now:r,undo:o,onClose:s}){let i=Ie(),a=tn(),u=e&&o.said?.ref===je(e)?o.said:null,c=e?_u(e):null,d=e?no(e,r):null;return l(Ku,{open:t&&e!==null,onClose:s,label:e?Ra(e):"Activity",side:"right",children:e?m("div",{className:"flex flex-col gap-6 p-5 sm:p-6",children:[m("div",{className:"flex items-start gap-3",children:[m("div",{className:"min-w-0 flex-1",children:[m("p",{className:"flex items-center gap-1.5 text-xs font-semibold text-muted-foreground",children:[l(vn,{kind:e.kind,className:"size-3.5 text-timeline-accent"}),[e.kind==="check"?e.title.split(":")[0]:to[e.kind],oO(e,n),d].filter(Boolean).join(" \xB7 ")]}),l("h2",{className:"mt-1.5 text-xl font-semibold leading-snug tracking-tight",children:Ra(e)})]}),l(R,{variant:"ghost",size:"icon","aria-label":"Close",onClick:s,children:l(pe,{name:"X","aria-hidden":!0,className:"size-4"})})]}),m("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[rn(e)?l("span",{className:e.needsYou?"rounded-md bg-warning/15 px-2 py-1 font-semibold text-warning-text":"rounded-md bg-muted px-2 py-1 font-semibold",children:rn(e)}):null,e.task?m("button",{type:"button",onClick:()=>a("today",e.task.key),className:"cursor-pointer rounded-md border border-border-hairline px-2 py-1 font-semibold hover:bg-state-hover",children:[e.task.key," \xB7 ",e.task.title]}):null,m("span",{className:"inline-flex items-center gap-1.5 rounded-md border border-border-hairline px-2 py-1 text-muted-foreground",children:[e.actor==="system"?null:l(De,{origin:e.actor==="owner"?"owner":"assistant",assistant:n.assistant,size:14}),sO(e,n)]})]}),c?l("p",{className:"rounded-xl bg-surface-selected px-4 py-3 text-base leading-relaxed",children:c}):null,e.kind==="approval"?m("section",{className:"space-y-2",children:[l("h3",{className:"text-xs font-semibold text-muted-foreground",children:"What it asked to run"}),l("pre",{className:"max-h-60 overflow-auto whitespace-pre-wrap break-words rounded-lg bg-muted p-3 font-mono text-xs",children:e.detail})]}):e.detail&&e.kind!=="check"?l("p",{className:"whitespace-pre-wrap text-base leading-relaxed",children:e.detail}):null,e.kind==="change"?l(Mf,{id:e.id,beforeLabel:"Before"},e.id):null,e.steps.length?m("section",{className:"space-y-2",children:[l("h3",{className:"text-xs font-semibold text-muted-foreground",children:e.kind==="approval"?"How it was decided":"How it went"}),l("ol",{className:"space-y-1.5 border-l border-border-hairline pl-4",children:e.steps.map((p,f)=>m("li",{className:"grid grid-cols-[4rem_minmax(0,1fr)] gap-2 text-sm",children:[l("span",{className:"text-xs tabular-nums text-muted-foreground",children:Ee(p.at,n.zone)}),l("span",{className:"min-w-0 break-words",children:p.text})]},`${p.at}-${f}`))})]}):null,m("div",{className:"flex flex-wrap items-center gap-2 border-t border-border-hairline pt-4",children:[e.thread?m(R,{onClick:()=>i.toThread(e.thread),children:[l(pe,{name:"MessageSquare","aria-hidden":!0,className:"size-4"}),"Open the conversation"]}):null,e.task?m(R,{variant:"outline",onClick:()=>a("today",e.task.key),children:["Open ",e.task.key]}):null,e.undo&&!u?.done?l(R,{variant:"outline",disabled:o.busy!==null,onClick:()=>o.undo(e),children:"Undo"}):null,u?l("span",{role:"status",className:u.done?"text-sm text-muted-foreground":"text-sm text-destructive",children:u.text}):null]})]}):null})}function iO(e){return e.fromThread?`${e.fromName??"(not listed)"} ${e.fromThread}${e.fromHost?` on ${e.fromHost}`:""}`:"outside Moonlet's conversations (unverified)"}function sE(){let e=J(),[t,n]=v(null),[r,o]=v(null),[s,i]=v(null),a=G(()=>{});M(()=>{let d=!0,p=!1,f=!1,h=async()=>{if(p){f=!0;return}p=!0;do{f=!1;try{let x=await e.call("messages.state",null);d&&!f&&(n(x.held),o(null))}catch(x){d&&o(x instanceof Error?x.message:String(x))}}while(d&&f);p=!1};a.current=()=>{h()},h();let g=setInterval(()=>{p||h()},5e3);return()=>{d=!1,clearInterval(g),a.current=()=>{}}},[e]);let u=q(()=>a.current(),[]);ke("messages",u);let c=async(d,p)=>{i(p),o(null);try{let f=await e.call(d,{id:p});n(h=>h?.filter(g=>g.id!==f.id||f.status==="held")??null),u()}catch(f){o(f instanceof Error?f.message:String(f))}finally{i(null)}};return m("section",{className:"flex min-w-0 flex-col gap-2 text-sm","aria-label":"Held messages",children:[l("h2",{className:"font-medium",children:"Messages held for you"}),l("p",{className:"text-xs text-muted-foreground",children:"A message from a sender that isn't listed waits here for your yes. A sender outside Moonlet's conversations is unverified, and a message is information for its recipient, never an approval in your name."}),r&&l("p",{role:"alert",className:"text-destructive",children:r}),t===null?r?null:l("p",{className:"text-muted-foreground",children:"Loading messages\u2026"}):t.length===0?l("p",{className:"text-muted-foreground",children:"No held messages."}):l("ul",{className:"divide-y text-xs",children:t.map(d=>m("li",{className:"flex flex-col gap-1 py-2",children:[m("div",{className:"flex flex-wrap gap-2",children:[m("span",{className:"w-10 shrink-0 font-mono",children:["#",d.id]}),l("span",{className:"w-36 shrink-0 text-muted-foreground",children:new Date(d.at).toLocaleString()}),m("span",{className:"flex-1",children:["to ",l("span",{className:"font-medium",children:d.to})," from ",l("span",{className:"font-mono",children:iO(d)})]})]}),l("pre",{className:"max-h-40 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted p-2 font-mono",children:d.text}),m("div",{className:"flex gap-2",children:[m(R,{size:"sm",disabled:s!==null,onClick:()=>{c("messages.deliver",d.id)},children:["Deliver to ",d.to]}),l(R,{size:"sm",variant:"ghost",disabled:s!==null,onClick:()=>{c("messages.discard",d.id)},children:"Discard"})]})]},d.id))})]})}function lO({meta:e,now:t,open:n,undo:r,needs:o,signal:s,remember:i,day:a,onDay:u}){let[c,d]=v("everything"),[p,f]=v(!0),[h,g]=v(""),[x,b]=v(null),_=yu(a,e.zone),{data:w,error:T,partial:y}=Es({..._,kinds:null,project:h||null,overlap:!0},s);M(()=>{w&&i(w.entries)},[w,i]);let E=a===e.today;M(()=>{b(null)},[a]);let k=se=>u(se),N=ys(w?.entries??[],_),$=uS(N,c,x,t),{running:P,groups:L}=dS($,e.zone,p),ne=ro(N);return m("div",{className:"flex flex-wrap items-start gap-8",children:[m("div",{className:"min-w-0 flex-[999_1_34rem] space-y-6",children:[m(on,{eyebrow:E?"Activity today":"Activity",title:Ct(a),children:[l(R,{variant:"outline",size:"icon","aria-label":"The day before",onClick:()=>k(nn(a,-1)),children:l(pe,{name:"ChevronLeft","aria-hidden":!0,className:"size-4"})}),l(R,{variant:"outline",size:"icon","aria-label":"The day after",disabled:E,onClick:()=>k(nn(a,1)),children:l(pe,{name:"ChevronRight","aria-hidden":!0,className:"size-4"})}),E?null:l(R,{variant:"outline",size:"sm",onClick:()=>k(e.today),children:"Back to today"})]}),w?m("div",{className:"flex items-start gap-3.5 rounded-2xl bg-surface-selected px-4 py-3.5",children:[l(De,{origin:"assistant",assistant:e.assistant,size:28}),l("p",{className:"text-base leading-relaxed",children:oo(ne,Ns(o),E?"today":"day")})]}):null,E?l(As,{needs:o}):null,w?l(LS,{entries:N,span:_,now:t,zone:e.zone,stretch:x,onStretch:b}):null,m("div",{className:"flex flex-wrap items-center gap-3",children:[l(_t,{label:"Show",value:c,onChange:d,options:[{value:"everything",label:"Everything"},{value:"changed",label:"What changed"},{value:"work",label:"Work"}]}),m("label",{className:"inline-flex items-center gap-2 text-xs text-muted-foreground",children:["Project",m("select",{value:h,onChange:se=>g(se.target.value),className:"h-8 cursor-pointer rounded-md border border-input bg-background px-2 text-xs font-medium text-foreground",children:[l("option",{value:"",children:"All projects"}),e.projects.map(se=>m("option",{value:se.key,children:[se.name," (",se.key,")"]},se.id))]})]}),m("label",{className:"inline-flex cursor-pointer items-center gap-2 text-xs font-medium text-muted-foreground",children:[l("input",{type:"checkbox",className:"size-4 accent-foreground",checked:p,onChange:se=>f(se.target.checked)}),"Fold quiet checks"]})]}),w?m("div",{className:"space-y-5",children:[$.length===0?l(Oe,{children:x?"Nothing happened in that stretch.":E?"Nothing has happened yet today.":"Nothing happened that day."}):m(he,{children:[l(OS,{entries:P,meta:e,now:t,onOpen:n}),l(PS,{groups:L,meta:e,now:t,onOpen:n,undo:r})]}),y?m("p",{className:"px-1 text-sm text-muted-foreground",children:[E?"Today":"That day"," has more than ",Kn.toLocaleString()," entries, so the summary, the hours and this list cover the newest"," ",Kn.toLocaleString(),"."]}):null]}):l(Oe,{children:T||"Loading\u2026"})]}),l("aside",{className:"hidden w-72 shrink-0 space-y-6 xl:block","aria-label":"The day at a glance",children:m("section",{className:"space-y-2",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:E?"Today so far":"That day"}),w?fr(ne).length?l("ul",{className:"space-y-1.5 text-sm",children:fr(ne).map(se=>l("li",{children:se},se))}):l("p",{className:"text-sm text-muted-foreground",children:"Nothing yet."}):null]})})]})}var iE={undo:{hint:"Changes to your moonlet undo while their settings still match; library filings undo newest first.",empty:"Nothing to undo yet."},work:{hint:"Each piece of work with its steps and result, and the notes left on tasks.",empty:"No work yet."},asks:{hint:"Every approval asked, what it would run and how it was decided. Standing permissions are in Settings \u2192 Permissions.",empty:"Nothing asked yet."},messages:{hint:"Messages between conversations and relays to other machines. Recipient controls are in Settings \u2192 Permissions.",empty:"No messages yet."},checks:{hint:"Scheduled checks, routines and reminders, with what each found.",empty:"No checks have run yet."}};function cO({view:e,meta:t,now:n,open:r,undo:o,signal:s,remember:i}){let[a,u]=v(1),[c]=v(()=>Date.now()+366*864e5),{data:d,error:p}=Ss({from:0,to:c,kinds:hm[e],project:null},a,s);M(()=>{d&&i(d.entries)},[d,i]);let f=bs.find(h=>h.id===e).label;return m("div",{className:"mx-auto max-w-4xl space-y-6",children:[l(on,{eyebrow:"Activity",title:f}),l("p",{className:"text-sm text-muted-foreground",children:iE[e].hint}),d?d.entries.length===0?l(Oe,{children:iE[e].empty}):m("div",{className:"space-y-5",children:[vu(d.entries,t.zone).map(({day:h,entries:g})=>m("section",{"aria-label":Ct(h),className:"space-y-2",children:[l("h2",{className:"px-1 text-xs font-semibold text-muted-foreground",children:h===t.today?"Today":Ct(h)}),l("ol",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised shadow-sm",children:g.map((x,b)=>l(so,{entry:x,meta:t,now:n,onOpen:r,undo:o,first:b===0},je(x)))})]},h)),d.more?m(R,{variant:"ghost",onClick:()=>u(h=>h+1),children:[l(pe,{name:"ChevronDown","aria-hidden":!0,className:"size-4"}),"Show older"]}):null]}):l(Oe,{children:p||"Loading\u2026"}),e==="undo"?l(sS,{}):null]})}function uO(){return m("div",{className:"mx-auto max-w-4xl space-y-6",children:[l(on,{eyebrow:"Activity",title:"Needs you"}),l("p",{className:"text-sm text-muted-foreground",children:"Questions, approvals and changes waiting for your answer, and messages held until you say yes."}),l(hu,{}),l(Ti,{}),l(sE,{})]})}function dO({view:e,needs:t}){let n=_n();return l("nav",{"aria-label":"Activity views",className:"-mx-1 flex min-w-0 gap-1 overflow-x-auto px-1 md:hidden",children:bs.map(r=>m("button",{type:"button","aria-current":e===r.id?"page":void 0,"aria-label":r.id==="needs"&&t?`${r.short}, ${t}`:void 0,onClick:()=>n(r.id),className:V("inline-flex shrink-0 cursor-pointer items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-semibold",e===r.id?"bg-foreground text-background":"bg-muted text-muted-foreground"),children:[r.short,r.id==="needs"&&t?l("span",{className:"rounded-full bg-warning px-1.5 text-2xs text-background",children:t}):null]},r.id))})}function aE({subPath:e}){let t=mm(e),n=_n(),r=ps(),o=hs(),s=Cm(),i=Am(),a=i.data!==null&&i.data.from!==null&&o-i.data.from>144e5,u=t.landing&&i.data===null&&i.error==="",c=t.landing&&a?"since":t.view,d=G(!1);M(()=>{!t.landing||i.data===null||d.current||(d.current=!0,a&&n("since"))},[t.landing,i.data,a,n]);let[p,f]=v(new Map),[h,g]=v(null),[x,b]=v(0),_=q(P=>f(L=>new Map([...L,...P.map(ne=>[je(ne),ne])])),[]),w=t.entry===null?null:p.get(t.entry)??null;CS(t.entry,_,x),M(()=>{w&&g(w)},[w]);let T=TS(()=>b(P=>P+1)),y={busy:T.busy,said:T.said,undo:P=>{T.undo(P)}},E=c==="timeline"||c==="week"?t.day:null,N={meta:r,now:o,open:P=>n(c,je(P),E),undo:y,signal:x,remember:_},$=!r||u?l(Oe,{children:"Loading\u2026"}):c==="timeline"?l(lO,{...N,meta:r,needs:s,day:t.day??r.today,onDay:P=>n("timeline",null,P===r.today?null:P)}):c==="week"?l(BS,{...N,meta:r,needs:s,initialDay:t.day},t.day??"this-week"):c==="since"?l(FS,{...N,meta:r,needs:s,since:i.data??{from:null,note:null}}):c==="behalf"?l(DS,{...N,meta:r}):c==="needs"?l(uO,{}):l(cO,{...N,meta:r,view:c},c);return m("main",{className:"h-full overflow-auto",children:[m("div",{className:"mx-auto flex max-w-7xl flex-col gap-6 p-4 sm:p-8",children:[l(dO,{view:c,needs:hr(s)}),$]}),r?l(oE,{entry:w??h,open:w!==null,meta:r,now:o,undo:y,onClose:()=>n(c,null,E)}):null]})}function lE({subPath:e}){let t=mm(e),n=_n(),r=Cm(),[o]=v(()=>Date.now()+366*864e5),s=Ss({from:0,to:o,kinds:hm.undo,project:null},1,0).data?.entries.filter(p=>p.undo!==null).length??0,i={needs:hr(r),undo:s},a=Am().data,u=hs(),c=a?.from!=null?{since:zn(u-a.from,"short")}:{},d=p=>m("button",{type:"button","aria-current":t.view===p.id?"page":void 0,"aria-label":i[p.id]?`${p.label}, ${i[p.id]}`:void 0,onClick:()=>n(p.id),className:V("flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm",t.view===p.id?"bg-muted font-semibold":"hover:bg-muted/60"),children:[l("span",{className:"min-w-0 flex-1 truncate",children:p.label}),i[p.id]?l("span",{className:V("rounded-full px-1.5 text-2xs font-bold",p.id==="needs"?"bg-warning/20 text-warning-text":"text-muted-foreground"),children:i[p.id]}):c[p.id]?l("span",{className:"text-2xs font-semibold text-muted-foreground",children:c[p.id]}):null]},p.id);return m("nav",{"aria-label":"Activity",className:"flex flex-col gap-0.5 p-2",children:[bs.filter(p=>fm.includes(p.id)).map(d),l("p",{className:"mt-4 px-2 pb-1 text-xs font-semibold text-muted-foreground",children:"Narrow to"}),bs.filter(p=>!fm.includes(p.id)).map(d),l("p",{className:"px-2 pt-3 text-xs leading-snug text-muted-foreground",children:"Every view is the same record, narrowed. After a few hours away, Activity opens on what happened since you looked."})]})}var lo="application/x-moonlet-artifacts";function cE(){try{return globalThis.sessionStorage??null}catch{return null}}var Bn={outcome:null,stack:V1(cE()),request:null,changed:null},Mm=new Set,Xn=e=>{if(Bn={...Bn,...e},e.stack)try{cE()?.setItem(im,JSON.stringify(e.stack))}catch{}for(let t of Mm)t()},Dm=e=>(Mm.add(e),()=>Mm.delete(e));function uE(){let e=xt(Dm,()=>Bn);return[e.outcome,e.stack.length>0,()=>Xn({outcome:null})]}function dE(){return xt(Dm,()=>Bn.changed)}function Fm(e){Xn({request:e})}function pE(){return[xt(Dm,()=>Bn.request),()=>Xn({request:null})]}function Xu(e){try{let t=JSON.parse(e.getData(lo)||"[]");return Array.isArray(t)?t.filter(n=>typeof n=="string").slice(0,Jk):[]}catch{return[]}}function $a(e){let t=J(),n=q(async o=>{try{let s=await t.call("artifacts.change",{action:o});return s.state==="refused"?(Xn({outcome:{kind:"refused",reason:s.reason}}),!1):(s.change&&Xn({outcome:{kind:"done",summary:s.change.summary},stack:[...Bn.stack,s.change].slice(-sm),changed:{action:o,moved:s.change.moved,n:(Bn.changed?.n??0)+1}}),e(),!0)}catch(s){return Xn({outcome:{kind:"refused",reason:s instanceof Error?s.message:String(s)}}),!1}},[t,e]),r=q(async()=>{let o=Bn.stack.at(-1);if(o)try{let s=await t.call("artifacts.undo",{id:o.id});s.state==="ok"?Xn({outcome:{kind:"undone",summary:s.summary},stack:Bn.stack.slice(0,-1)}):Xn({outcome:{kind:"refused",reason:s.reason},stack:[]}),e()}catch(s){Xn({outcome:{kind:"refused",reason:s instanceof Error?s.message:String(s)}})}},[t,e]);return{run:n,undo:r}}var fE=176;function Cs({request:e,onClose:t}){let n=io(),r=e!==null,[o,s]=v(e);M(()=>{e&&s(e)},[e]);let{isContentRealized:i}=Du({open:r,enabled:n});M(()=>{if(!r||n)return;let c=p=>{if(p instanceof KeyboardEvent){if(p.key!=="Escape")return;p.preventDefault(),p.stopPropagation()}t()},d=setTimeout(()=>{window.addEventListener("pointerdown",c),window.addEventListener("keydown",c,!0),window.addEventListener("scroll",c,!0)});return()=>{clearTimeout(d),window.removeEventListener("pointerdown",c),window.removeEventListener("keydown",c,!0),window.removeEventListener("scroll",c,!0)}},[r,n,t]);let a=(o?.entries??[]).filter(c=>c!==null),u=c=>{t(),c.run()};return n?l(Fu,{open:r,onOpenChange:c=>c?void 0:t(),srLabel:o?.title??"Actions",children:i?m("div",{className:"flex min-h-0 flex-col pb-4",children:[l("p",{className:"px-4 pt-1 pb-2 text-sm font-medium text-muted-foreground",children:o?.title}),l("div",{role:"menu","aria-label":o?.title,className:"flex max-h-[70dvh] flex-col overflow-y-auto overscroll-contain",children:a.map((c,d)=>l("button",{type:"button",role:"menuitem",disabled:c.disabled,className:"px-4 py-3 text-left text-base hover:bg-muted disabled:opacity-40",onClick:()=>u(c),children:c.label},`${d}-${c.label}`))})]}):null}):e?l("div",{role:"menu","aria-label":e.title,className:"fixed z-50 flex flex-col rounded-md border bg-background py-1 text-sm shadow-md",style:{width:fE,left:Math.max(8,Math.min(e.x,window.innerWidth-fE-8)),top:Math.max(8,Math.min(e.y,window.innerHeight-32*a.length-16))},onPointerDown:c=>c.stopPropagation(),children:a.map((c,d)=>l("button",{type:"button",role:"menuitem",disabled:c.disabled,className:"px-3 py-1.5 text-left hover:bg-muted disabled:opacity-40",onClick:()=>u(c),children:c.label},`${d}-${c.label}`))}):null}function Ts({label:e,query:t,keyName:n,choices:r,onQuery:o,onMenu:s}){let i=t1(t,n)??"",a=r.some(d=>d.value.toLowerCase()===i.toLowerCase()),u=io(),c=`h-8 max-w-44 rounded-md border px-2 text-sm ${i?"border-foreground/40 bg-muted font-medium":"bg-background text-muted-foreground"}`;if(u){let d=r.find(p=>p.value.toLowerCase()===i.toLowerCase());return l("button",{type:"button","aria-label":e,"aria-haspopup":"menu",className:`${c} truncate text-left`,onClick:p=>{let f=p.currentTarget.getBoundingClientRect();s({title:e,x:f.left,y:f.bottom+4,entries:[i?{label:`Any ${e.toLowerCase()}`,run:()=>o(wa(t,n,null))}:null,...r.map(h=>({label:h===d?`\u2713 ${h.label}`:h.label,run:()=>o(wa(t,n,h.value))}))]})},children:d?.label??(i||e)})}return m("select",{"aria-label":e,className:c,value:a?r.find(d=>d.value.toLowerCase()===i.toLowerCase()).value:i,onChange:d=>o(wa(t,n,d.target.value||null)),children:[l("option",{value:"",children:e}),!a&&i?l("option",{value:i,children:i}):null,r.map(d=>l("option",{value:d.value,children:d.label},d.value))]})}function hE({query:e,onQuery:t,meta:n,inFolder:r,canSave:o,problems:s,inputRef:i,onSave:a}){let[u,c]=v(null),[d,p]=v(null),f=q(()=>p(null),[]),[h,g]=v(!1),x=N=>{if(N.length>_a)return g(!0);g(!1),t(N)},[b,_]=v(""),w=qc(e),T=w.subfolders,y=va(w),E=async()=>{if(u===null)return;let N=await a(u);N?_(N):(c(null),_(""))},k=m(he,{children:[l(Ts,{onMenu:p,label:"Kind",keyName:"kind",query:e,onQuery:x,choices:[{value:"page",label:"Page"},{value:"md",label:"Markdown"}]}),l(Ts,{onMenu:p,label:"Project",keyName:"project",query:e,onQuery:x,choices:(n?.projects??[]).map(N=>({value:N.id,label:N.name}))}),l(Ts,{onMenu:p,label:"Conversation",keyName:"conversation",query:e,onQuery:x,choices:(n?.conversations??[]).map(N=>({value:N.threadId,label:N.title??N.threadId}))}),l(Ts,{onMenu:p,label:"Tag",keyName:"tag",query:e,onQuery:x,choices:(n?.tags??[]).map(N=>({value:N.tag,label:`#${N.tag}`}))}),l(Ts,{onMenu:p,label:"Modified",keyName:"modified",query:e,onQuery:x,choices:[{value:"today",label:"Today"},{value:"<7d",label:"Last 7 days"},{value:"<30d",label:"Last 30 days"},{value:">90d",label:"Older than 90 days"}]}),l(Ts,{onMenu:p,label:"Written by",keyName:"by",query:e,onQuery:x,choices:[{value:"you",label:"You"},{value:"assistant",label:"The assistant"}]}),r?m("label",{className:"flex h-8 items-center gap-1.5 px-1 text-sm text-muted-foreground",children:[l("input",{type:"checkbox",checked:T||y,disabled:y,title:y?"A filter looks in every folder below this one":void 0,onChange:N=>x(wa(e,"subfolders",N.target.checked?"yes":null))}),"Subfolders"]}):null]});return m("div",{className:"flex flex-col gap-1.5 border-b px-3 py-2",children:[l(Cs,{request:d,onClose:f}),m("div",{className:"flex flex-wrap items-center gap-1.5",children:[l(le,{ref:i,"aria-label":"Filter this list",className:"h-8 min-w-48 flex-1",placeholder:"Filter: words, tag:triage, kind:md, modified:<7d",value:e,maxLength:_a,onChange:N=>x(N.target.value),onKeyDown:N=>{N.key==="Escape"&&e&&(N.preventDefault(),N.stopPropagation(),x(""))}}),o&&u===null?l(R,{size:"sm",variant:"secondary",disabled:!e.trim(),onClick:()=>c(""),children:"Save"}):null]}),l("div",{className:"flex flex-wrap items-center gap-1.5",children:k}),u!==null?m("form",{className:"flex flex-wrap items-center gap-1.5",onSubmit:N=>{N.preventDefault(),E()},children:[l(le,{autoFocus:!0,"aria-label":"Name for this filter",className:"h-8 max-w-64",placeholder:"Name, such as Open security",value:u,maxLength:60,onChange:N=>c(N.target.value),onKeyDown:N=>{N.key==="Escape"&&(N.preventDefault(),N.stopPropagation(),c(null),_(""))}}),l(R,{size:"sm",type:"submit",disabled:!u.trim(),children:"Save filter"}),l(R,{size:"sm",variant:"secondary",type:"button",onClick:()=>(c(null),_("")),children:"Cancel"}),b?l("span",{className:"text-xs text-destructive",children:b}):null]}):null,h?m("p",{className:"text-xs text-destructive",children:["A filter is at most ",_a," characters; that change would make it longer."]}):null,s.length?l("p",{className:"text-xs text-destructive",children:s.join(" \xB7 ")}):null]})}var mE="\0new",gE=e=>e===""?"the library":e===Ze?"the Inbox":e,xE=e=>e.length===1?Pe(e[0]):`${e.length} items`;function Bu({children:e}){return l("div",{className:"flex flex-wrap items-center gap-1.5 border-b px-3 py-2 text-sm",children:e})}function bE({panel:e,folders:t,onRun:n,onClose:r}){let[o,s]=v(e.kind==="rename"?Pe(e.path):""),[i,a]=v(""),[u,c]=v("");M(()=>s(e.kind==="rename"?Pe(e.path):""),[e]);let d=async g=>{await n(g)&&r()},p=g=>{g.key==="Escape"&&(g.preventDefault(),g.stopPropagation(),r())},f=l(R,{size:"sm",variant:"secondary",type:"button",onClick:r,children:"Cancel"});if(e.kind==="move"){let g=["",Ze,...t].filter(_=>!e.items.some(w=>_===w||_.startsWith(`${w}/`))),x=i===mE,b=u.trim().toLowerCase().replace(/^\/+|\/+$/g,"");return l("form",{className:"contents",onSubmit:_=>{_.preventDefault(),x?b&&d({kind:"move",items:e.items,to:b,make:!0}):d({kind:"move",items:e.items,to:i,make:!1})},children:m(Bu,{children:[m("span",{children:["Move ",xE(e.items)," to"]}),m("select",{"aria-label":"Move to",autoFocus:!0,className:"h-8 max-w-64 rounded-md border bg-background px-2 text-sm",value:i,onChange:_=>a(_.target.value),onKeyDown:p,children:[g.map(_=>l("option",{value:_,children:gE(_)},_||"(library)")),l("option",{value:mE,children:"A new folder\u2026"})]}),x?l(le,{autoFocus:!0,"aria-label":"New folder",className:"h-8 max-w-64",placeholder:"Name, such as plans or work/screens",value:u,maxLength:240,onChange:_=>c(_.target.value),onKeyDown:p}):null,l(R,{size:"sm",type:"submit",disabled:x&&!b,children:"Move"}),f,x?l("span",{className:"text-xs text-muted-foreground",children:"Lower-case letters, digits, . _ -"}):null]})})}if(e.kind==="tag")return l("form",{className:"contents",onSubmit:g=>{g.preventDefault();let x=o.split(",").map(b=>b.trim()).filter(Boolean);x.length&&d({kind:"tag",items:e.items,tags:x})},children:m(Bu,{children:[m("span",{children:["Tag ",xE(e.items)]}),l(le,{autoFocus:!0,"aria-label":"Tags to add",className:"h-8 max-w-64",placeholder:"Tags, such as trip, plan",value:o,onChange:g=>s(g.target.value),onKeyDown:p}),l(R,{size:"sm",type:"submit",disabled:!o.trim(),children:"Add"}),f,e.tags.length?l("span",{className:"text-xs text-muted-foreground",children:"Take off:"}):null,e.tags.map(g=>m("button",{type:"button","aria-label":`Take #${g} off`,className:"rounded border px-1.5 text-xs hover:bg-muted",onClick:()=>{d({kind:"untag",items:e.items,tags:[g]})},children:["#",g," \xD7"]},g))]})});let h=e.kind==="rename";return l("form",{className:"contents",onSubmit:g=>{g.preventDefault();let x=o.trim();x&&(e.kind==="rename"?d({kind:"rename",path:e.path,name:x}):d({kind:"mkdir",path:e.parent?`${e.parent}/${x.toLowerCase()}`:x.toLowerCase()}))},children:m(Bu,{children:[l("span",{children:h?`Rename ${Pe(e.path)} to`:`New folder in ${gE(e.kind==="mkdir"?e.parent:"")}`}),l(le,{autoFocus:!0,"aria-label":h?"New name":"Folder name",className:"h-8 max-w-64",placeholder:h?"":"Name, such as plans",value:o,maxLength:64,onFocus:g=>g.currentTarget.select(),onChange:g=>s(g.target.value),onKeyDown:p}),l(R,{size:"sm",type:"submit",disabled:!o.trim(),children:h?"Rename":"Make folder"}),f,l("span",{className:"text-xs text-muted-foreground",children:"Lower-case letters, digits, . _ -"})]})})}function yE({count:e,total:t,onAll:n,allStarred:r,onMove:o,onTag:s,onStar:i,onDelete:a,onClear:u}){return m(Bu,{children:[m("span",{className:"font-medium",children:[e," selected"]}),n?m(R,{size:"sm",variant:"secondary",onClick:n,children:["Select all ",t]}):null,l(R,{size:"sm",variant:"secondary",onClick:o,children:"Move to\u2026"}),s?l(R,{size:"sm",variant:"secondary",onClick:s,children:"Tag\u2026"}):null,i?l(R,{size:"sm",variant:"secondary",onClick:i,children:r?"Unstar":"Star"}):null,l(R,{size:"sm",variant:"secondary",onClick:a,children:"Delete"}),l(R,{size:"sm",variant:"secondary",onClick:u,children:"Clear"})]})}function _E({onUndo:e}){let[t,n,r]=uE();return t?m("div",{role:"status",className:`flex items-center gap-2 border-b px-3 py-1.5 text-sm ${t.kind==="refused"?"text-destructive":""}`,children:[l("span",{className:"min-w-0 flex-1 truncate",children:t.kind==="done"?t.summary:t.kind==="undone"?`Undone: ${t.summary}`:`That didn't happen: ${t.reason}`}),n&&t.kind!=="refused"?l(R,{size:"sm",variant:"secondary",onClick:e,children:t.kind==="undone"?"Undo the one before":"Undo"}):null,l("button",{type:"button","aria-label":"Dismiss",className:"px-1 text-muted-foreground hover:text-foreground",onClick:r,children:"\xD7"})]}):null}var vE="orbit.artifacts.open-folders",wE=0,zm=new Set;function mr(){wE++;for(let e of zm)e()}function Km(){return xt(e=>(zm.add(e),()=>zm.delete(e)),()=>wE)}function pO(){try{let e=Dn()?.getItem(vE),t=e?JSON.parse(e):[];return new Set(Array.isArray(t)?t.filter(n=>typeof n=="string"):[])}catch{return new Set}}function Xm(){let e=Ie();return t=>e.toPluginPanel(du,{subPath:as(t)})}function fO(e){let{run:t}=$a(mr),[n,r]=v(!1);return e===void 0?{over:!1,props:{}}:{over:n,props:{onDragOver:o=>{o.dataTransfer.types.includes(lo)&&(o.preventDefault(),o.dataTransfer.dropEffect="move",r(!0))},onDragLeave:()=>r(!1),onDrop:o=>{o.preventDefault(),r(!1);let s=Xu(o.dataTransfer).filter(i=>i!==e);s.length&&t({kind:"move",items:s,to:e,make:!1})}}}}function Un({active:e,label:t,count:n,depth:r=0,onClick:o,toggle:s,drop:i,onDoubleClick:a,onMenu:u,after:c}){let d=fO(i);return m("div",{className:`group relative flex items-center gap-1 rounded px-2 py-1 text-sm ${e?"bg-muted font-medium":"hover:bg-muted/60"} ${d.over?"outline outline-1 outline-ring":""}`,style:{paddingLeft:`${8+r*14}px`},onContextMenu:u?p=>{p.preventDefault(),u(p.clientX,p.clientY)}:void 0,...d.props,children:[s??l("span",{className:"w-4 shrink-0"}),l("button",{type:"button","aria-current":e?"page":void 0,className:"min-w-0 flex-1 truncate text-left",onClick:o,onDoubleClick:a,children:t}),n!==void 0&&n>0?l("span",{className:`shrink-0 text-xs text-muted-foreground ${u?"group-hover:hidden [@media(hover:none)]:hidden":""}`,children:n}):null,u?l("button",{type:"button","aria-label":`More for ${typeof t=="string"?t:"this folder"}`,"aria-haspopup":"menu",className:"hidden shrink-0 rounded px-1 text-muted-foreground hover:text-foreground focus:inline group-hover:inline [@media(hover:none)]:inline",onClick:p=>{let f=p.currentTarget.getBoundingClientRect();u(f.right-176,f.bottom+4)},children:"\u2026"}):null,c]})}function hO({path:e,count:t,depth:n,active:r,toggle:o,onOpen:s,onMenu:i}){let{run:a}=$a(mr),[u,c]=v(null),d=(p,f)=>i({title:Pe(e),x:p,y:f,entries:[{label:"New folder inside",run:()=>c({kind:"mkdir",text:""})},{label:"Rename",run:()=>c({kind:"rename",text:Pe(e)})},{label:"Move to\u2026",run:()=>Fm({kind:"move",items:[e]})},{label:"Filter inside",run:()=>(s(),Fm({kind:"focus-filter"}))},{label:"Delete folder",run:()=>{a({kind:"delete",items:[e]})}}]});return u?m(he,{children:[u.kind==="mkdir"?l(Un,{active:r,label:Pe(e),count:t,depth:n,toggle:o,onClick:s}):null,l("form",{className:"py-0.5 pr-2",style:{paddingLeft:`${8+(n+(u.kind==="mkdir"?1:0))*14+20}px`},onSubmit:p=>{p.preventDefault();let f=u.text.trim();c(null),f&&(u.kind==="rename"?f!==Pe(e)&&a({kind:"rename",path:e,name:f}):a({kind:"mkdir",path:`${e}/${f.toLowerCase()}`}))},children:l(le,{autoFocus:!0,"aria-label":u.kind==="rename"?`New name for ${Pe(e)}`:`New folder in ${Pe(e)}`,className:"h-7",placeholder:u.kind==="mkdir"?"New folder's name":"",maxLength:64,value:u.text,onFocus:p=>p.currentTarget.select(),onChange:p=>c({...u,text:p.target.value}),onBlur:p=>p.currentTarget.form?.requestSubmit(),onKeyDown:p=>{p.key==="Escape"&&(p.preventDefault(),p.stopPropagation(),c(null))}})})]}):l(Un,{active:r,label:Pe(e),count:t,depth:n,toggle:o,drop:e,onClick:s,onDoubleClick:()=>c({kind:"rename",text:Pe(e)}),onMenu:d})}function Uu({children:e}){return l("p",{className:"mt-3 px-2 pb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground",children:e})}function mO({row:e,index:t,count:n,active:r,onOpen:o,onChanged:s,onDeleted:i,onMenu:a}){let u=J(),[c,d]=v(null),[p,f]=v(""),h=async x=>{let b=await x.catch(_=>({state:"refused",reason:_ instanceof Error?_.message:String(_)}));b.state==="ok"?(f(""),s()):f(b.reason)},g=(x,b)=>a({title:e.name,x,y:b,entries:[{label:"Rename",run:()=>d(e.name)},{label:"Move up",disabled:t===0,run:()=>{h(u.call("artifacts.saved.move",{id:e.id,to:t-1}))}},{label:"Move down",disabled:t===n-1,run:()=>{h(u.call("artifacts.saved.move",{id:e.id,to:t+1}))}},{label:"Delete",run:()=>{h(u.call("artifacts.saved.delete",{id:e.id})).then(i)}}]});return c!==null?l("form",{className:"px-2 py-0.5",onSubmit:x=>{x.preventDefault(),c.trim()&&c.trim()!==e.name&&h(u.call("artifacts.saved.rename",{id:e.id,name:c})),d(null)},children:l(le,{autoFocus:!0,"aria-label":`New name for ${e.name}`,className:"h-7",onFocus:x=>x.currentTarget.select(),value:c,maxLength:60,onChange:x=>d(x.target.value),onBlur:x=>x.currentTarget.form?.requestSubmit(),onKeyDown:x=>{x.key==="Escape"&&(x.preventDefault(),x.stopPropagation(),d(null))}})}):m("div",{className:`group relative flex items-center gap-1 rounded px-2 py-1 text-sm ${r?"bg-muted font-medium":"hover:bg-muted/60"}`,onContextMenu:x=>{x.preventDefault(),g(x.clientX,x.clientY)},children:[l("span",{className:"w-4 shrink-0"}),l("button",{type:"button","aria-current":r?"page":void 0,className:"min-w-0 flex-1 truncate text-left",onClick:o,onDoubleClick:()=>d(e.name),children:e.name}),l("button",{type:"button","aria-label":`More for ${e.name}`,"aria-haspopup":"menu",className:"shrink-0 rounded px-1 text-muted-foreground opacity-0 hover:text-foreground focus:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100",onClick:x=>{let b=x.currentTarget.getBoundingClientRect();g(b.right-176,b.bottom+4)},children:"\u2026"}),p?l("span",{className:"absolute left-6 top-full z-10 text-xs text-destructive",children:p}):null]})}function kE({subPath:e}){let t=J(),n=Xm(),r=ls(e),o=Km(),[s,i]=v(null),[a,u]=v(""),[c,d]=v(null),p=q(()=>d(null),[]),[f,h]=v(r.kind==="search"?r.q:""),[g,x]=v(pO);M(()=>{let $=!0;return t.call("artifacts.folders",{}).then(P=>{$&&(i(P),u(""))},P=>$&&u(P instanceof Error?P.message:String(P))),()=>{$=!1}},[t,o]);let b=r.kind==="place"&&r.place.kind==="folder"?r.place.path:null,_=new Set([...g,...b?Sa(b):[]]),w=$=>{let P=new Set(g);P.has($)?P.delete($):P.add($),x(P);try{Dn()?.setItem(vE,JSON.stringify([...P]))}catch{}},T=s?.folders??[],y=$=>T.some(P=>Ut(P.path)===$),E=T.filter($=>Sa(Ut($.path)).every(P=>_.has(P))),k=$=>C1(r,$),N=$=>r.kind==="group"&&r.by===$||r.kind==="place"&&r.place.kind===$;return M(()=>h(r.kind==="search"?r.q:""),[e]),m("nav",{"aria-label":"Artifacts",className:"flex flex-col gap-0.5 px-2 pb-4",children:[l("form",{className:"pb-2",onSubmit:$=>{$.preventDefault(),f.trim()&&n({kind:"search",q:f.trim()})},children:l(le,{"aria-label":"Search all artifacts",className:"h-8",placeholder:"Search all",value:f,onChange:$=>h($.target.value)})}),a?m("p",{className:"px-2 text-xs text-destructive",children:["Couldn't load the folders: ",a]}):null,l(Un,{active:k(Bt(Ze)),label:"Inbox",count:s?.inbox,drop:Ze,onClick:()=>n(Bt(Ze))}),l(Un,{active:k({kind:"place",place:{kind:"recent"}}),label:"Recent",onClick:()=>n({kind:"place",place:{kind:"recent"}})}),l(Un,{active:k({kind:"place",place:{kind:"starred"}}),label:"Starred",count:s?.starred,onClick:()=>n({kind:"place",place:{kind:"starred"}})}),l(Uu,{children:"Library"}),l(Un,{active:k(Bt("")),label:"All folders",drop:"",onClick:()=>n(Bt(""))}),E.map($=>{let P=$.path.split("/").length,L=y($.path)?l("button",{type:"button","aria-label":_.has($.path)?`Close ${Pe($.path)}`:`Open ${Pe($.path)}`,"aria-expanded":_.has($.path),className:"w-4 shrink-0 text-xs text-muted-foreground",onClick:()=>w($.path),children:_.has($.path)?"\u25BE":"\u25B8"}):void 0;return l(hO,{path:$.path,active:b===$.path,count:$.pages,depth:P,toggle:L,onOpen:()=>n(Bt($.path)),onMenu:d},$.path)}),s&&!T.length?l("p",{className:"px-2 py-1 text-xs text-muted-foreground",children:"No folders yet."}):null,s?.saved.length?m(he,{children:[l(Uu,{children:"Saved"}),s.saved.map(($,P)=>l(mO,{row:$,index:P,count:s.saved.length,active:r.kind==="saved"&&r.id===$.id,onOpen:()=>n({kind:"saved",id:$.id}),onChanged:mr,onDeleted:()=>r.kind==="saved"&&r.id===$.id&&n(Bt("")),onMenu:d},$.id))]}):null,l(Uu,{children:"Views"}),l(Un,{active:N("project"),label:"By project",onClick:()=>n({kind:"group",by:"project"})}),l(Un,{active:N("conversation"),label:"By conversation",onClick:()=>n({kind:"group",by:"conversation"})}),s?.tags.length?m(he,{children:[l(Uu,{children:"Tags"}),s.tags.map($=>l(Un,{active:k({kind:"place",place:{kind:"tag",tag:$.tag}}),label:`#${$.tag}`,count:$.pages,onClick:()=>n({kind:"place",place:{kind:"tag",tag:$.tag}})},$.tag))]}):null,l(Cs,{request:c,onClose:p})]})}var SE=1e3,gO=250;function EE(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch{return"UTC"}}function xO(){try{return globalThis.matchMedia?.("(hover: none)").matches===!0}catch{return!1}}var bO=[{by:"name",label:"Name"},{by:"modified",label:"Modified"},{by:null,label:"Project",wide:!0},{by:"conversation",label:"Conversation",wide:!0},{by:null,label:"Tags",wide:!0},{by:"versions",label:"Versions",wide:!0},{by:"size",label:"Size",wide:!0}],NE=(e,t)=>`${e} ${t}${e===1?"":"s"}`,yO=e=>[e.folders.length?NE(e.folders.length,"folder"):"",e.pages.length||!e.folders.length?`${NE(e.pages.length,"page")}${e.more?"+":""}`:""].filter(Boolean).join(" \xB7 "),_O=e=>e<1024?`${e} B`:`${Math.round(e/1024)} KB`;function vO(){let e=G(null),[t,n]=v("wide");return Ye(()=>{let r=e.current;if(!r)return;let o=()=>n(I1(r.getBoundingClientRect().width));o();let s=new ResizeObserver(o);return s.observe(r),()=>s.disconnect()},[]),[e,t]}function IE(e){return l(R,{size:"sm",variant:"secondary",onClick:mr,children:"Refresh"})}function PE({subPath:e}){let t=J(),n=J(),r=Ie(),o=Xm(),s=ls(e),i=e,a=Km();ke("artifacts",mr);let[u,c]=vO(),[d,p]=v(()=>om(Dn(),s)),[f,h]=v(null),[g,x]=v(null),[b,_]=v(""),[w,T]=v(""),[y,E]=v(null),[k,N]=v(!0),[$,P]=v(!1),[L,ne]=v(null),[se,_e]=v([]),[ie,Q]=v(null),[j,Y]=v(null),[ee,be]=v(""),[H,xe]=v(new Set),[Tr,Tn]=v(null),[ue,ze]=v(null),zt=q(()=>ze(null),[]),[mt,gt]=v(null),[wi,Ro]=v(null),[N_,A_]=v(null),[$o,of]=v(()=>X1(Dn())),[ki,sf]=v(new Map),Si=G($o);Si.current=$o;let{run:Gn,undo:C_}=$a(mr),[Ml,T_]=pE(),jt=dE(),R_=G(jt?.n??0);M(()=>{if(!jt||jt.n===R_.current||(R_.current=jt.n,of(O=>U1(O,jt.action,jt.moved)),sf(O=>K1(O,jt.action,jt.moved)),s.kind!=="place"||s.place.kind!=="folder"))return;let S=pu(jt.action,jt.moved,s.place.path);S!==null&&S!==s.place.path&&o(Bt(S))},[jt]),M(()=>B1(Dn(),$o),[$o]),M(()=>{if(!g)return;let S=new Set(g.folders.map(O=>O.path));of(O=>[...O].every(Z=>S.has(Z))?O:new Set([...O].filter(Z=>S.has(Z))))},[g]),M(()=>{if(f?.state!=="refused"||!g||s.kind!=="place"||s.place.kind!=="folder")return;let S=s.place.path,O=new Set(g.folders.map(Z=>Z.path));S===""||S===Ze||O.has(S)||o(Bt(Sa(Ut(S)).filter(Z=>O.has(Z)).at(-1)??""))},[f,g]);let[zT,af]=v(null),Rr=G(null);M(()=>()=>{Rr.current&&clearTimeout(Rr.current)},[]);let Dl=G(null),Fl=G(null),zl=S=>be(S instanceof Error?S.message:String(S)),KT=S=>{p(S),R1(Dn(),S)},Kl=s.kind==="saved"?g?.saved.find(S=>S.id===s.id)??null:null,Qt=s.kind==="saved"?Kl?rm(Kl.place):null:s,Ei=Qt?as(Qt):null,lf=Kl?.query??"";M(()=>{E(null),xe(new Set),Tn(null),gt(null),ze(null),ne(null),P(!1),_e([]),p(om(Dn(),ls(i)))},[i]),M(()=>{Ml&&(Ml.kind==="move"?(gt({kind:"move",items:Ml.items}),T_()):Fl.current&&(Fl.current.focus(),T_()))},[Ml,i,f===null]),M(()=>af(null),[i]),M(()=>{_(lf),T(lf)},[i,lf]),M(()=>{if(b===w)return;let S=setTimeout(()=>T(b),250);return()=>clearTimeout(S)},[b,w]),M(()=>{t.call("artifacts.folders",{}).then(x,zl)},[t,a]),M(()=>{let S=!0;h(null),be("");let O=Ei===null?null:rm(Ei),Z=ae=>S&&h(ae);if(!O){s.kind==="saved"&&g&&Z({state:"refused",reason:"That saved filter is gone."});return}return O.kind==="group"?t.call("artifacts.group",{by:O.by}).then(ae=>Z({state:"groups",by:O.by,groups:ae.groups}),zl):O.kind==="search"?t.call("artifacts.search",{q:O.q,versions:!0}).then(ae=>Z({state:"search",results:ae.results}),zl):O.kind==="place"&&t.call("artifacts.library",{place:O.place,sort:d,limit:SE,query:w,zone:EE()}).then(Z,zl),()=>{S=!1}},[t,Ei,d,a,w,g===null]);let cf=G({key:"",listed:!1});M(()=>{if(!L||!f||f.state!=="ok"&&f.state!=="search")return;let S=`${L.threadId}\0${L.name}`,O=f.state==="ok"?hf().find(ae=>ae.threadId===L.threadId&&ae.name===L.name)?.path:f.results.filter(ae=>ae.threadId===L.threadId&&ae.name===L.name).map(ae=>ae.kind==="moved"?ae.to:ae.path)[0],Z=cf.current.key===S&&cf.current.listed;O===void 0&&Z&&gf.length>0||(cf.current={key:S,listed:O!==void 0},O!==void 0?O!==L.path&&(ne({...L,path:O}),E(ae=>ae===null||ae===L.path?O:ae)):Z&&(P(!1),ne(null)))},[f,L,ki]);let uf=G(0),Io=q(S=>{let O=++uf.current;ne(S),Q(null),Y(null),n.call("artifacts.read",{threadId:S.threadId,name:S.name}).then(Z=>{if(O!==uf.current||(Q(ou(Z)),Y(Z.state==="ok"?iu(Z.page):null),Z.state!=="ok"))return;t.call("artifacts.seen",{threadId:S.threadId,name:S.name}).catch(()=>{});let ae=we=>we.map(Kt=>Kt.threadId===S.threadId&&Kt.name===S.name?{...Kt,unread:!1}:Kt);h(we=>we?.state==="ok"?{...we,pages:ae(we.pages)}:we),sf(we=>new Map([...we].map(([Kt,Jn])=>[Kt,Jn.branch.state==="ok"?{...Jn,branch:{...Jn.branch,pages:ae(Jn.branch.pages)}}:Jn])))},Z=>O===uf.current&&Q(is(Z)))},[n,t]),$_=G(a);M(()=>{$_.current!==a&&($_.current=a,L&&Io(L))},[a]);let df=S=>S?g?.projects.find(O=>O.id===S)?.name??S:"\u2014",pf=qc(w),XT=pf.subfolders||va(pf),ff=f?.state==="ok"?M1(f,S=>ki.get(S)?.branch,$o):[],Ve=f?.state==="ok"?D1(ff):f?.state==="search"?f.results.map(S=>({kind:"page",path:S.kind==="moved"?S.to:S.path,threadId:S.threadId,name:S.name})):f?.state==="groups"?f.groups.map(S=>({kind:"folder",path:S.key})):[],$r=`${a}:${d.by}:${d.desc?"desc":"asc"}`,I_=G($r);I_.current=$r;let hf=()=>f?.state==="ok"?z1(f.pages,ki.values(),$r):f?.state==="search"?[...new Map(f.results.map(S=>[S.page.path,S.page])).values()]:[],P_=S=>hf().find(O=>O.path===S);M(()=>{if(!f)return;let S=new Set(f.state==="ok"||f.state==="search"?Ve.map(O=>O.path):[]);xe(O=>O.size&&[...O].some(Z=>!S.has(Z))?new Set([...O].filter(Z=>S.has(Z))):O),E(O=>O!==null&&!S.has(O)?null:O),Tn(O=>O!==null&&!S.has(O)?null:O)},[f,Ve.map(S=>S.path).join(`
143
+ `)]);let mf=f?.state==="ok"&&L?.path&&!f.pages.some(S=>S.path===L.path)?Ut(L.path):null,gf=[...new Set([...ff.flatMap(S=>S.kind==="folder"&&S.open?[S.folder.path]:[]),...mf!==null&&ki.has(mf)?[mf]:[]])].filter(S=>ki.get(S)?.gen!==$r),xf=G(new Set),BT=G(0);M(()=>{for(let S of gf){let O=`${$r}\0${S}`;if(xf.current.has(O))continue;xf.current.add(O);let Z=++BT.current,ae=we=>sf(Kt=>{let Jn={n:Z,gen:$r,branch:we};return F1(Jn,Kt.get(S),I_.current)?new Map(Kt).set(S,Jn):Kt});t.call("artifacts.library",{place:{kind:"folder",path:S},sort:d,limit:SE,query:"",zone:EE()}).then(we=>ae(we.state==="ok"?{state:"ok",folders:we.folders,pages:we.pages,more:we.more}:we),we=>ae({state:"refused",reason:we instanceof Error?we.message:String(we)})).finally(()=>xf.current.delete(O))}},[t,$r,gf.join(`
144
+ `)]);let bf=(S,O)=>{if(Si.current.has(S)===O)return;let Z=new Set(Si.current);if(O?Z.add(S):Z.delete(S),Si.current=Z,of(Z),O)return;let ae=we=>we.startsWith(`${S}/`);E(we=>we!==null&&ae(we)?S:we),Tn(we=>we!==null&&ae(we)?S:we),xe(we=>[...we].some(ae)?new Set([...we].filter(Kt=>!ae(Kt))):we)},O_=S=>bf(S,!Si.current.has(S)),lt=f?.state==="ok"||f?.state==="search",Xl=Qt?.kind==="place"&&Qt.place.kind==="folder"?Qt.place.path:null,L_=Xl===Ze?null:Xl,M_=()=>{xe(new Set),E(null),Tn(null)},Yn=()=>H.size?[...H]:y&&lt?[y]:[],Bl=S=>hf().filter(O=>S.includes(O.path)),D_=S=>{let O=Bl(S);return O.length>0&&O.every(Z=>Z.starred)},yf=S=>f?.state==="ok"&&Ve.some(O=>O.kind==="folder"&&O.path===S),_f=(S,O)=>{xe(H1(Ve,H,Tr,S,O)),Tn(S)},vf=Ve.length>0&&Ve.every(S=>H.has(S.path)),F_=()=>xe(vf?new Set:new Set(Ve.map(S=>S.path))),UT=(S,O)=>{if(!lt)return Po(S);if(H.size&&!O.metaKey&&!O.ctrlKey&&xO())return _f(S.path,O.shiftKey);if(O.metaKey||O.ctrlKey){let Z=new Set(H.size?H:y?[y]:[]),ae=Z.has(S.path);ae?Z.delete(S.path):Z.add(S.path),xe(Z),Tn(S.path),E(ae?[...Z].at(-1)??null:S.path);return}if(O.shiftKey&&Tr){let Z=Ve.findIndex(we=>we.path===Tr),ae=Ve.findIndex(we=>we.path===S.path);if(Z>=0&&ae>=0){xe(new Set(Ve.slice(Math.min(Z,ae),Math.max(Z,ae)+1).map(we=>we.path))),E(S.path);return}}if(xe(new Set),Tn(S.path),S.kind==="folder"&&f?.state==="ok"){if(Rr.current&&clearTimeout(Rr.current),Rr.current=null,O.detail>=2)return af(S.path);E(S.path),Rr.current=setTimeout(()=>{Rr.current=null,O_(S.path)},gO);return}Po(S)},Ul=S=>S.length&&void Gn({kind:"delete",items:S}).then(O=>O&&(xe(new Set),ne(null),P(!1))),wf=S=>{let O=Bl(S);O.length&&Gn({kind:"star",items:O.map(Z=>Z.path),starred:!O.every(Z=>Z.starred)})},Hl=S=>{let O=S.filter(Z=>!yf(Z));O.length&&gt({kind:"tag",items:O,tags:[...new Set(Bl(O).flatMap(Z=>Z.tags))].sort()})},kf=S=>gt({kind:"rename",path:S,folder:yf(S)}),z_=(S,O)=>{O.preventDefault(),Ro(null);let Z=Xu(O.dataTransfer).filter(ae=>ae!==S);Z.length&&Gn({kind:"move",items:Z,to:S,make:!1}).then(ae=>ae&&xe(new Set))},HT=S=>({onDragOver:O=>{O.dataTransfer.types.includes(lo)&&(O.preventDefault(),O.dataTransfer.dropEffect="move",Ro(S))},onDragLeave:()=>Ro(O=>O===S?null:O),onDrop:O=>z_(S,O)}),VT=S=>({onDragOver:O=>{!lt||!O.dataTransfer.types.includes(lo)||(O.preventDefault(),Ro(`crumb:${S}`))},onDragLeave:()=>Ro(O=>O===`crumb:${S}`?null:O),onDrop:O=>z_(S,O)}),K_=S=>{let O=Ve.find(ae=>ae.path===S);if(O)return O;let Z=P_(S);return Z&&{kind:"page",path:S,threadId:Z.threadId,name:Z.name}},ZT=S=>{let O=K_(S);if(!O)return[];let Z=H.has(S)&&H.size>1?[...H]:[S],ae=Z.length>1;return O.kind==="folder"?[{label:"Open",run:()=>Po(O)},ae?null:{label:"New folder inside",run:()=>gt({kind:"mkdir",parent:S})},ae?null:{label:"Rename",run:()=>kf(S)},{label:"Move to\u2026",run:()=>gt({kind:"move",items:Z})},{label:ae?`Delete ${Z.length} items`:"Delete folder",run:()=>Ul(Z)}]:[ae?null:{label:"Open",run:()=>Sf(O)},ae?null:{label:"Rename",run:()=>kf(S)},{label:"Move to\u2026",run:()=>gt({kind:"move",items:Z})},{label:"Tag\u2026",run:()=>Hl(Z)},{label:D_(Z)?"Unstar":"Star",run:()=>wf(Z)},{label:ae?`Delete ${Z.length} items`:"Delete",run:()=>Ul(Z)}]},Po=S=>{if(E(S.path),S.kind==="page"){_e([]),Io({threadId:S.threadId,name:S.name,path:S.path}),N(!0);return}f?.state==="groups"?o({kind:"place",place:f.by==="project"?{kind:"project",projectId:S.path}:{kind:"conversation",threadId:S.path}}):o(Bt(S.path))},Sf=S=>{if(S.kind!=="page")return Po(S);Po(S),P(!0)},X_=()=>{P(!1),c!=="wide"&&ne(null),requestAnimationFrame(()=>Dl.current?.focus())},Ef=S=>{E(S);let O=Ve.find(Z=>Z.path===S);O?.kind==="page"&&k&&c==="wide"&&Io({threadId:O.threadId,name:O.name,path:O.path}),Dl.current?.querySelector(`[data-path="${CSS.escape(S??"")}"]`)?.scrollIntoView({block:"nearest"})},WT=S=>{if(S.target instanceof HTMLInputElement&&S.key===" ")return;let O=Ve.find(Z=>Z.path===y);if(S.key==="ArrowDown"||S.key==="ArrowUp")S.preventDefault(),Ef(P1(Ve,y,S.key==="ArrowDown"?1:-1));else if((S.key==="ArrowRight"||S.key==="ArrowLeft")&&f?.state==="ok"&&O){S.preventDefault();let Z=O.kind==="folder"&&$o.has(O.path);if(S.key==="ArrowRight"){if(O.kind!=="folder")return;if(!Z)return bf(O.path,!0);let ae=Ve[Ve.indexOf(O)+1];ae?.path.startsWith(`${O.path}/`)&&Ef(ae.path)}else Z?bf(O.path,!1):Ve.some(ae=>ae.kind==="folder"&&ae.path===Ut(O.path))&&Ef(Ut(O.path))}else lt&&(S.metaKey||S.ctrlKey)&&S.key.toLowerCase()==="a"?(S.preventDefault(),xe(new Set(Ve.map(Z=>Z.path)))):lt&&(S.metaKey||S.ctrlKey)&&S.key.toLowerCase()==="x"&&Yn().length?(S.preventDefault(),A_(Yn())):lt&&(S.metaKey||S.ctrlKey)&&S.key.toLowerCase()==="v"&&N_&&Xl!==null?(S.preventDefault(),Gn({kind:"move",items:N_,to:Xl,make:!1}).then(Z=>Z&&A_(null))):(S.metaKey||S.ctrlKey)&&S.key.toLowerCase()==="z"?(S.preventDefault(),C_()):lt&&(S.key==="Delete"||S.key==="Backspace")&&Yn().length?(S.preventDefault(),Ul(Yn())):lt&&S.key==="F2"&&y?(S.preventDefault(),kf(y)):lt&&S.key==="t"&&!S.metaKey&&!S.ctrlKey&&Yn().length?(S.preventDefault(),Hl(Yn())):lt&&(S.key==="x"||S.key==="X")&&!S.metaKey&&!S.ctrlKey&&y?(S.preventDefault(),_f(y,S.shiftKey)):lt&&S.key==="s"&&!S.metaKey&&!S.ctrlKey&&Yn().length?(S.preventDefault(),wf(Yn())):S.key==="Escape"&&(H.size||mt)?(S.preventDefault(),S.stopPropagation(),H.size&&M_(),gt(null)):S.key==="/"&&B_?(S.preventDefault(),Fl.current?.focus()):S.key==="Enter"&&O?(S.preventDefault(),Sf(O)):S.key===" "&&O?.kind==="page"&&(S.preventDefault(),k&&L?.path===O.path?N(!1):Po(O))},jT=T1(s,{project:S=>df(S),conversation:S=>g?.conversations.find(O=>O.threadId===S)?.title??S,saved:()=>Kl?.name??"\u2026"}),qn=L&&k?L:null,B_=Qt?.kind==="place",U_=!$&&!(qn&&c!=="wide"),H_=$||qn!==null&&c!=="wide",V_=ue!==null||mt!==null;M(()=>{if(!H_)return;let S=O=>{O.key!=="Escape"||O.defaultPrevented||(O.preventDefault(),V_?(ze(null),gt(null)):$?X_():ne(null))};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[H_,$,V_]);let nt=L?.path?P_(L.path):void 0,QT=L?l(cu,{threadId:L.threadId,name:L.name,shown:ie,about:j,onChanged:()=>Io(L),onNavigate:(S,O,Z)=>{_e(ae=>[...ae,L]),Io({threadId:S,name:O,path:Z})},onBack:se.length?()=>{let S=se.at(-1);_e(O=>O.slice(0,-1)),Io(S)}:null}):null;return m("div",{ref:u,className:"flex h-full min-h-0 flex-col",children:[m("div",{className:"flex min-h-10 items-center gap-1 border-b px-3 py-1.5 text-sm",children:[$||qn&&c!=="wide"?l(R,{size:"sm",variant:"secondary",onClick:()=>$?X_():ne(null),children:"Back to the list"}):null,l("ol",{className:"flex min-w-0 flex-1 items-center gap-1 truncate","aria-label":"Where you are",children:jT.map((S,O)=>m("li",{className:"flex min-w-0 items-center gap-1",children:[O?l("span",{className:"text-muted-foreground",children:"\u203A"}):null,S.where?l("button",{type:"button",className:`truncate rounded px-0.5 text-muted-foreground hover:underline ${S.where.kind==="place"&&S.where.place.kind==="folder"&&wi===`crumb:${S.where.place.path}`?"bg-muted ring-1 ring-ring":""}`,onClick:()=>o(S.where),...S.where.kind==="place"&&S.where.place.kind==="folder"?VT(S.where.place.path):{},children:S.label}):l("span",{className:"truncate font-medium",children:S.label})]},`${O}:${S.label}`))}),f?.state==="ok"?l("span",{className:"shrink-0 text-xs text-muted-foreground",children:yO(f)}):null,L_!==null&&!$&&!(qn&&c!=="wide")?l(R,{size:"sm",variant:"secondary",onClick:()=>gt({kind:"mkdir",parent:L_}),children:"New folder"}):null]}),l(_E,{onUndo:()=>{C_()}}),mt?l(bE,{panel:mt,folders:(g?.folders??[]).map(S=>S.path),onRun:Gn,onClose:()=>gt(null)}):null,H.size>0&&!mt&&!$?l(yE,{count:H.size,onAll:vf?null:F_,total:Ve.length,allStarred:D_([...H]),onMove:()=>gt({kind:"move",items:[...H]}),onTag:[...H].some(S=>!yf(S))?()=>Hl([...H]):null,onStar:Bl([...H]).length?()=>wf([...H]):null,onDelete:()=>Ul([...H]),onClear:M_}):null,B_&&H.size===0&&!$&&!(qn&&c!=="wide")?l(hE,{query:b,onQuery:_,meta:g,inFolder:Qt?.kind==="place"&&Qt.place.kind==="folder"&&Qt.place.path!==Ze,canSave:Qt?.kind==="place",problems:f?.state==="ok"?f.problems:[],inputRef:Fl,onSave:async S=>{if(Ei===null)return"There's nothing here to save.";let O=await t.call("artifacts.saved.create",{name:S,place:Ei,query:b});return O.state!=="ok"?O.reason:(x(await t.call("artifacts.folders",{})),mr(),o({kind:"saved",id:O.id}),null)}}):null,ee?m("p",{className:"px-3 py-2 text-sm text-destructive",children:["Couldn't reach the artifacts: ",ee]}):null,m("div",{className:"flex min-h-0 flex-1",children:[l("div",{ref:Dl,role:"listbox","aria-label":"Artifacts","aria-hidden":!U_,tabIndex:0,onKeyDown:WT,onDoubleClick:S=>{if(S.target instanceof HTMLInputElement)return;let O=S.target.closest("[data-path]")?.getAttribute("data-path"),Z=Ve.find(ae=>ae.path===O);Z&&!(Z.kind==="folder"&&f?.state==="ok")&&Sf(Z)},onContextMenu:S=>{let O=S.target.closest("[data-path]")?.getAttribute("data-path");!lt||!O||!Ve.some(Z=>Z.path===O)||(S.preventDefault(),H.has(O)||(xe(new Set),E(O)),ze({x:S.clientX,y:S.clientY,path:O}))},onDragStart:S=>{let O=S.target.closest("[data-path]")?.getAttribute("data-path");if(!lt||!O)return;let Z=H.has(O)?[...H]:[O];S.dataTransfer.setData(lo,JSON.stringify(Z)),S.dataTransfer.setData("text/plain",Z.join(`
145
+ `)),S.dataTransfer.effectAllowed="move"},onDragEnd:()=>Ro(null),className:`min-h-0 overflow-auto outline-none ${U_?"":"hidden"} ${qn?"w-1/2 border-r":"flex-1"}`,children:f?f.state==="refused"?l("p",{className:"p-3 text-sm text-destructive",children:f.reason}):l(wO,{listing:f,lines:ff,onToggle:S=>{O_(S),Dl.current?.focus({preventScroll:!0})},layout:qn||c==="compact"?"compact":"wide",sort:d,onSort:S=>KT($1(d,S)),isChosen:S=>H.size?H.has(S):y===S,ticks:lt?{isTicked:S=>H.has(S),any:H.size>0,all:vf,tick:_f,tickAll:F_}:null,draggable:lt,dropOn:wi,dropTarget:HT,renaming:zT,onRename:(S,O)=>{af(null),O&&O!==Pe(S)&&Gn({kind:"rename",path:S,name:O})},projectName:df,where:Qt??s,flat:XT,filtering:va(pf),onSelect:UT}):l("p",{className:"p-3 text-sm text-muted-foreground",children:"Loading\u2026"})}),l(Cs,{request:ue?{title:Pe(ue.path),entries:ZT(ue.path),x:ue.x,y:ue.y}:null,onClose:zt}),$||qn?m("div",{className:"flex min-w-0 flex-1 flex-col",children:[nt||L?m("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 border-b px-3 py-1.5 text-xs text-muted-foreground",children:[l("span",{className:"font-medium text-foreground",children:L?.path??L?.name}),nt?l("span",{children:df(nt.projectId)}):null,nt?.threadTitle?l("span",{className:"truncate",children:nt.threadTitle}):null,nt?l("span",{children:jr(nt.at)}):null,nt?.tags.map(S=>m("button",{type:"button","aria-label":`Take #${S} off`,title:`Take #${S} off`,className:"rounded px-1 hover:bg-muted hover:line-through",onClick:()=>{Gn({kind:"untag",items:[nt.path],tags:[S]})},children:["#",S]},S)),nt?l("button",{type:"button",className:"rounded px-1 hover:bg-muted",onClick:()=>Hl([nt.path]),children:"+ Tag"}):null,nt?l("button",{type:"button","aria-pressed":nt.starred,"aria-label":nt.starred?"Unstar":"Star",className:`rounded px-1 hover:bg-muted ${nt.starred?"text-foreground":""}`,onClick:()=>{Gn({kind:"star",items:[nt.path],starred:!nt.starred})},children:nt.starred?"\u2605":"\u2606"}):null,l("span",{className:"flex-1"}),$?null:l(R,{size:"sm",variant:"secondary",onClick:()=>P(!0),children:"Open"}),L?l(R,{size:"sm",variant:"secondary",onClick:()=>r.toThread(L.threadId),children:"Open in chat"}):null,L?.path&&lt&&K_(L.path)?l(R,{size:"sm",variant:"secondary","aria-label":`More for ${Pe(L.path)}`,"aria-haspopup":"menu",onClick:S=>{let O=S.currentTarget.getBoundingClientRect();L.path&&ze({x:O.right-176,y:O.bottom+4,path:L.path})},children:"\u2026"}):null]}):null,QT]}):null]})]})}function wO({listing:e,lines:t,onToggle:n,layout:r,sort:o,onSort:s,isChosen:i,ticks:a,draggable:u,dropOn:c,dropTarget:d,renaming:p,onRename:f,projectName:h,where:g,flat:x,filtering:b,onSelect:_}){if(e.state==="groups")return e.groups.length?l("ul",{children:e.groups.map(k=>{let N={kind:"folder",path:k.key};return m(Ia,{row:N,selected:i(k.key),onSelect:_,children:[l("span",{className:"min-w-0 flex-1 truncate",children:k.title??k.key}),e.by==="conversation"?l("span",{className:"hidden truncate text-muted-foreground sm:inline",children:h(k.projectId)}):null,m("span",{className:"shrink-0 text-xs text-muted-foreground",children:[k.pages," page",k.pages===1?"":"s"," \xB7 ",jr(k.at)]})]},k.key)})}):l(Hu,{children:"No pages yet."});if(e.state==="search")return e.results.length?l("ul",{children:e.results.map(k=>{if(k.kind==="moved"){let $={kind:"page",path:k.to,threadId:k.threadId,name:k.name};return l(Ia,{row:$,selected:!1,onSelect:_,draggable:u,tall:!0,children:m("span",{className:"min-w-0 flex-1",children:[l("span",{className:"block truncate font-medium",children:k.to}),m("span",{className:"block truncate text-xs text-muted-foreground",children:["Moved from ",k.path]})]})},`moved:${k.path}`)}let N={kind:"page",path:k.path,threadId:k.threadId,name:k.name};return l(Ia,{row:N,selected:i(k.path),onSelect:_,draggable:u,ticks:a,tall:!0,children:m("span",{className:"min-w-0 flex-1",children:[l("span",{className:"block truncate font-medium",children:k.title}),m("span",{className:"block truncate text-xs text-muted-foreground",children:[k.path,k.version?` \xB7 matched in v${k.version}`:""]}),l("span",{className:"block truncate text-xs text-muted-foreground",children:k.snippet})]})},`page:${k.path}`)})}):l(Hu,{children:"Nothing matches."});let w=x||!(g.kind==="place"&&g.place.kind==="folder");if(!e.folders.length&&!e.pages.length)return l(Hu,{children:b?"Nothing matches this filter.":g.kind==="place"&&g.place.kind==="folder"&&g.place.path===Ze?"The Inbox is empty: every page is filed.":"Nothing here yet."});let T=t.some(k=>k.kind==="folder"),y=(k,N)=>k*16+(N?20:0);if(r!=="wide")return m("ul",{children:[t.map(k=>{if(k.kind==="note")return m("li",{className:"flex items-center gap-2 border-b border-border/40 px-3 py-1.5 text-xs text-muted-foreground",children:[a?l("span",{"aria-hidden":!0,className:"size-4 shrink-0 max-md:pointer-coarse:size-5"}):null,l("span",{className:"min-w-0 flex-1 truncate",style:{paddingLeft:`${y(k.depth,!0)}px`},children:k.text})]},k.key);if(k.kind==="folder"){let $=k.folder;return m(Ia,{row:{kind:"folder",path:$.path},selected:i($.path),onSelect:_,draggable:u,ticks:a,dropping:c===$.path,drop:d($.path),children:[m("span",{className:"min-w-0 flex-1 truncate",style:{paddingLeft:`${y(k.depth,!1)}px`},children:[l(AE,{path:$.path,open:k.open,onToggle:n}),p===$.path?l(TE,{path:$.path,onDone:f}):Pe($.path)]}),l("span",{className:"shrink-0 text-xs text-muted-foreground",children:$.pages})]},$.path)}let N=k.page;return l(Ia,{row:{kind:"page",path:N.path,threadId:N.threadId,name:N.name},selected:i(N.path),onSelect:_,draggable:u,ticks:a,tall:!0,children:m("span",{className:`min-w-0 flex-1 ${N.fileGone||N.threadGone?"opacity-60":""}`,style:{paddingLeft:`${y(k.depth,T)}px`},children:[m("span",{className:"block truncate",children:[N.unread?l(RE,{}):null,Pe(N.path),N.starred?l($E,{}):null]}),m("span",{className:"block truncate text-xs text-muted-foreground",children:[w?`${Ut(N.path)||"Library"} \xB7 `:"",jr(N.at)," \xB7 ",h(N.projectId)]})]})},N.path)}),e.more?m(Hu,{children:["Showing the first ",e.pages.length," pages."]}):null]});let E=(k,N)=>({paddingLeft:`${12+y(k,N)}px`});return m("table",{className:"w-full table-fixed text-sm",children:[l("thead",{className:"sticky top-0 bg-background text-left text-xs text-muted-foreground",children:m("tr",{className:"border-b",children:[a?l("th",{className:"w-8 py-1.5 pl-3 font-normal",children:l(Bm,{label:a.all?"Select none":"Select all",on:a.all,mixed:a.any&&!a.all,shown:!0,onTick:a.tickAll})}):null,bO.map(k=>l("th",{className:`px-3 py-1.5 font-normal ${k.by==="name"?"w-[34%]":""}`,"aria-sort":k.by&&o.by===k.by?o.desc?"descending":"ascending":void 0,children:k.by?m("button",{type:"button",className:"hover:text-foreground",onClick:()=>s(k.by),children:[k.label,o.by===k.by?o.desc?" \u25BE":" \u25B4":""]}):k.label},k.label))]})}),m("tbody",{children:[t.map(k=>{if(k.kind==="note")return m("tr",{className:"border-b border-border/40",children:[a?l("td",{}):null,l("td",{colSpan:7,className:"truncate px-3 py-1.5 text-xs text-muted-foreground",style:E(k.depth,!0),children:k.text})]},k.key);if(k.kind==="folder"){let P=k.folder,L={kind:"folder",path:P.path};return m("tr",{"data-path":P.path,role:"option","aria-selected":i(P.path),draggable:u,className:`group cursor-default border-b border-border/40 ${i(P.path)?"bg-muted":"hover:bg-muted/50"} ${c===P.path?"outline outline-1 outline-ring":""}`,onClick:ne=>_(L,ne),...d(P.path),children:[a?l(CE,{path:P.path,ticks:a}):null,m("td",{className:"truncate px-3 py-1.5",style:E(k.depth,!1),children:[l(AE,{path:P.path,open:k.open,onToggle:n}),p===P.path?l(TE,{path:P.path,onDone:f}):`${Pe(P.path)}/`]}),l("td",{className:"px-3 py-1.5 text-muted-foreground",children:P.at?jr(P.at):"\u2014"}),m("td",{className:"px-3 py-1.5 text-muted-foreground",colSpan:5,children:[P.pages," page",P.pages===1?"":"s"]})]},P.path)}let N=k.page,$={kind:"page",path:N.path,threadId:N.threadId,name:N.name};return m("tr",{"data-path":N.path,role:"option","aria-selected":i(N.path),draggable:u,className:`group cursor-default border-b border-border/40 ${i(N.path)?"bg-muted":"hover:bg-muted/50"} ${N.fileGone||N.threadGone?"opacity-60":""}`,onClick:P=>_($,P),children:[a?l(CE,{path:N.path,ticks:a}):null,m("td",{className:"truncate px-3 py-1.5",style:E(k.depth,T),children:[N.unread?l(RE,{}):null,Pe(N.path),N.starred?l($E,{}):null,w?l("span",{className:"ml-2 text-xs text-muted-foreground",children:Ut(N.path)||"Library"}):null]}),l("td",{className:"truncate px-3 py-1.5 text-muted-foreground",children:jr(N.at)}),l("td",{className:"truncate px-3 py-1.5 text-muted-foreground",children:h(N.projectId)}),l("td",{className:"truncate px-3 py-1.5 text-muted-foreground",children:N.threadTitle??"\u2014"}),l("td",{className:"truncate px-3 py-1.5 text-muted-foreground",children:N.tags.map(P=>`#${P}`).join(" ")}),l("td",{className:"px-3 py-1.5 text-muted-foreground",children:N.versions}),l("td",{className:"px-3 py-1.5 text-muted-foreground",children:_O(N.size)})]},N.path)}),e.more?l("tr",{children:m("td",{colSpan:a?8:7,className:"px-3 py-2 text-xs text-muted-foreground",children:["Showing the first ",e.pages.length," pages."]})}):null]})]})}function AE({path:e,open:t,onToggle:n}){return l("button",{type:"button",tabIndex:-1,"aria-expanded":t,"aria-label":`${t?"Collapse":"Expand"} ${Pe(e)}`,className:"mr-1 inline-block w-4 text-center text-muted-foreground hover:text-foreground",onMouseDown:r=>r.preventDefault(),onClick:r=>{r.stopPropagation(),n(e)},onDoubleClick:r=>r.stopPropagation(),children:t?"\u25BE":"\u25B8"})}function Ia({row:e,selected:t,onSelect:n,draggable:r,ticks:o,dropping:s,drop:i,tall:a,children:u}){return m("li",{"data-path":e.path,role:"option","aria-selected":t,draggable:r,className:`group flex cursor-default items-center gap-2 border-b border-border/40 px-3 ${a?"py-2":"py-1.5"} text-sm ${t?"bg-muted":"hover:bg-muted/50"} ${s?"outline outline-1 outline-ring":""}`,onClick:c=>n(e,c),...i,children:[o?l(Bm,{label:`Select ${Pe(e.path)}`,on:o.isTicked(e.path),shown:o.any,onTick:c=>o.tick(e.path,c),quiet:!0}):null,u]})}function CE({path:e,ticks:t}){return l("td",{className:"w-8 py-1.5 pl-3",children:l(Bm,{label:`Select ${Pe(e)}`,on:t.isTicked(e),shown:t.any,onTick:n=>t.tick(e,n),quiet:!0})})}function Bm({label:e,on:t,mixed:n=!1,shown:r,quiet:o=!1,onTick:s}){return l("span",{className:`-m-2 flex shrink-0 cursor-pointer items-center p-2 ${r||t||n?"":"opacity-0 focus-within:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100"}`,onClick:a=>{a.stopPropagation(),a.target===a.currentTarget&&s(a.shiftKey)},children:l("input",{type:"checkbox","aria-label":e,title:e,checked:t,readOnly:!0,tabIndex:o?-1:0,ref:a=>{a&&(a.indeterminate=n)},className:"size-4 cursor-pointer max-md:pointer-coarse:size-5",onClick:a=>{a.stopPropagation(),s(a.shiftKey)}})})}function TE({path:e,onDone:t}){let[n,r]=v(Pe(e)),o=s=>s.stopPropagation();return l("form",{className:"inline-block align-middle",onClick:o,onDoubleClick:o,onSubmit:s=>{s.preventDefault(),t(e,n.trim()||null)},children:l(le,{autoFocus:!0,"aria-label":`New name for ${Pe(e)}`,className:"h-7 w-48",maxLength:64,value:n,onFocus:s=>s.currentTarget.select(),onChange:s=>r(s.target.value),onBlur:s=>s.currentTarget.form?.requestSubmit(),onKeyDown:s=>{s.stopPropagation(),s.key==="Escape"&&(s.preventDefault(),t(e,null))}})})}function RE(){return l("span",{role:"img","aria-label":"Changed since you last opened it",className:"mr-1.5 inline-block size-1.5 rounded-full bg-foreground align-middle"})}function $E(){return l("span",{role:"img","aria-label":"Starred",className:"ml-1.5 text-muted-foreground",children:"\u2605"})}function Hu({children:e}){return l("p",{className:"p-3 text-sm text-muted-foreground",children:e})}var OE=(e,t,n)=>`${e===0?"No":e===1?"One":e} ${e===1?t:n}`;function LE(){let{change:e}=Na();return t=>{e(t.status==="open"?{action:"done",ref:t.id,note:null}:{action:"reopen",ref:t.id,why:null})}}function $s({eyebrow:e,title:t,children:n}){return m("div",{className:"flex flex-wrap items-end gap-4",children:[m("div",{className:"min-w-0 flex-1",children:[l("p",{className:"text-xs font-semibold text-muted-foreground",children:e}),l("h1",{className:"mt-0.5 text-2xl font-semibold tracking-tight",children:t})]}),n]})}function Rs({tasks:e,meta:t,now:n,open:r,rich:o,empty:s,limit:i}){let a=LE(),[u,c]=v(!1),d=i&&!u?e.slice(0,i):e;return e.length?m(he,{children:[d.map((p,f)=>l(nS,{task:p,assistant:t.assistant,now:n,rich:o,first:f===0,onOpen:()=>r(p),onToggle:()=>a(p)},p.id)),d.length<e.length?m("button",{type:"button",onClick:()=>c(!0),className:"flex w-full cursor-pointer items-center gap-2 border-t border-border-hairline px-4 py-2.5 text-left text-sm font-semibold text-timeline-accent hover:bg-state-hover",children:[l(pe,{name:"ChevronDown","aria-hidden":!0,className:"size-3.5"}),e.length-d.length," more:"," ",e.slice(d.length,d.length+4).map(p=>p.title.toLowerCase()).join(", "),e.length-d.length>4?"\u2026":""]}):null]}):l(Oe,{children:s})}function kO({meta:e,filters:t,open:n,now:r}){let o=rt(),s=fs(t),{data:i,error:a}=We(()=>o.call("tasks.today",s),[o,t.origin,t.project]),u=We(()=>o.call("tasks.upcoming",{...s,days:7}),[o,t.origin,t.project]).data,c=We(()=>o.call("tasks.journal",{day:e.today,newest:!0,limit:3}),[o,e.today]).data;if(!i)return l(Oe,{children:a||"Loading\u2026"});let d=i.yours.filter(x=>x.dueAt!==null&&ms(x.dueAt,i.zone)<=i.day).length,p=[i.yours.length===0?"Nothing needs you right now.":`${OE(i.yours.length,"thing needs","things need")} you${d?`, ${d===i.yours.length&&d>1?"all":d} today`:""}.`,`I\u2019m handling ${i.onIt.length===1?"one other":`${i.onIt.length} others`} and waiting on ${i.waiting.length===1?"one reply":`${i.waiting.length} replies`}.`].join(" "),f=Array.from({length:7},(x,b)=>qr(i.day,b)),h=new Map(f.map(x=>[x,u?.items.filter(b=>ms(b.at,i.zone)===x)??[]])),g=(c?.entries??[]).slice(-3).reverse();return m("div",{className:"flex flex-wrap items-start gap-8",children:[m("div",{className:"min-w-0 flex-[999_1_34rem] space-y-7",children:[l($s,{eyebrow:"Today",title:Ct(i.day)}),m("div",{className:"flex items-start gap-3.5 rounded-2xl bg-surface-selected px-4 py-3.5",children:[l(De,{origin:"assistant",assistant:e.assistant,size:28}),l("p",{className:"text-base leading-relaxed",children:p})]}),l(Yr,{filters:t,onChange:bn,meta:e}),l(Fn,{title:"Your move",count:i.yours.length,hint:"By priority, then when",children:l(Rs,{tasks:i.yours,meta:e,now:r,open:n,rich:!0,empty:"Nothing is waiting on you. Enjoy it."})}),l(Fn,{title:`${e.assistant}\u2019s on it`,count:i.onIt.length,hint:"Nothing here needs you",children:l(Rs,{tasks:i.onIt,meta:e,now:r,open:n,limit:6,empty:`${e.assistant} has nothing in hand.`})}),l(Fn,{title:"Waiting on others",count:i.waiting.length,hint:`${e.assistant} checks back on the date shown`,children:l(Rs,{tasks:i.waiting,meta:e,now:r,open:n,empty:"Nobody owes you an answer."})})]}),m("aside",{className:"hidden w-80 shrink-0 space-y-7 xl:block","aria-label":"Today at a glance",children:[m("section",{className:"space-y-3",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:"This week"}),l("div",{className:"grid grid-cols-7 gap-1",children:f.map((x,b)=>m("div",{className:V("flex flex-col items-center gap-1 rounded-lg py-2",b===0?"bg-foreground text-background":""),children:[l("span",{className:V("text-2xs font-semibold",b===0?"opacity-80":"text-muted-foreground"),children:dr(x)}),l("span",{className:"text-sm font-semibold",children:Number(x.slice(8))}),l("span",{className:"flex h-1.5 gap-0.5",children:(h.get(x)??[]).slice(0,4).map(_=>l("span",{className:V("size-1.5 rounded-full",b===0?"bg-background":_.task.move==="owner"?"bg-warning":"bg-timeline-accent")},`${_.task.id}-${_.at}`))})]},x))})]}),m("section",{className:"space-y-2",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:"Today\u2019s schedule"}),i.schedule.length===0?l("p",{className:"text-sm text-muted-foreground",children:"Nothing timed today."}):null,l("ol",{className:"space-y-0.5",children:i.schedule.map((x,b)=>{let _=x.at<r,w=_&&(i.schedule[b+1]?.at??1/0)>=r;return m("li",{children:[m("button",{type:"button",onClick:()=>n(x.task),className:"grid w-full cursor-pointer grid-cols-[4rem_1rem_minmax(0,1fr)] items-start gap-2.5 rounded-md py-1.5 text-left hover:bg-state-hover",children:[l("span",{className:"pt-px text-right text-xs tabular-nums text-muted-foreground",children:Ee(x.at,i.zone)}),l(Ht,{glyph:Qr(x.task),className:V("mt-px size-3.5",_?"text-muted-foreground":"text-timeline-accent")}),l("span",{className:V("min-w-0 text-sm leading-snug",_?"text-muted-foreground":"font-medium"),children:x.task.title})]}),w?m("div",{className:"my-1 grid grid-cols-[4rem_minmax(0,1fr)] items-center gap-2.5","aria-hidden":!0,children:[l("span",{className:"text-right text-2xs font-bold text-timeline-accent",children:Ee(r,i.zone)}),l("span",{className:"h-0.5 rounded-full bg-timeline-accent"})]}):null]},`${x.task.id}-${x.at}`)})})]}),g.length?m("section",{className:"space-y-3",children:[l("h2",{className:"text-xs font-semibold text-muted-foreground",children:"From the journal"}),g.map(x=>m("p",{className:"text-sm leading-snug",children:[m("span",{className:"block text-xs text-muted-foreground",children:[Ee(x.at,i.zone)," \xB7 ",x.actor==="assistant"?e.assistant:x.actor==="owner"?"You":"System"," \xB7 ",x.title]}),x.body]},x.seq))]}):null]})]})}function SO({meta:e,filters:t,open:n,now:r}){let o=rt(),[s,i]=v(!0),{data:a,error:u}=We(()=>o.call("tasks.upcoming",{...fs(t),days:28}),[o,t.origin,t.project]);if(!a)return l(Oe,{children:u||"Loading\u2026"});let c=g=>g.kind==="scheduled"&&g.project.id==="internal",d=a.items.filter(g=>s||!c(g.task)),p=new Map;for(let g of d)p.set(ms(g.at,a.zone),[...p.get(ms(g.at,a.zone))??[],g]);let f=Array.from({length:7},(g,x)=>qr(a.from,x)),h=g=>g===a.from?"Today":g===qr(a.from,1)?"Tomorrow":dr(g,"long");return m("div",{className:"space-y-7",children:[l($s,{eyebrow:"Upcoming",title:"This week and later",children:m("label",{className:"inline-flex cursor-pointer items-center gap-2 text-xs font-medium text-muted-foreground",children:[l("input",{type:"checkbox",className:"size-4 accent-foreground",checked:s,onChange:g=>i(g.target.checked)}),"Show ",e.assistant,"\u2019s routines"]})}),l(Yr,{filters:t,onChange:bn,meta:e}),l("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4 lg:grid-cols-7","aria-label":"The week ahead",children:f.map((g,x)=>m("div",{className:V("flex min-h-36 flex-col gap-1 rounded-xl border bg-surface-raised p-2.5",x===0?"border-foreground/40 ring-1 ring-foreground/20":"border-border-hairline"),children:[m("p",{className:"flex items-baseline gap-1.5",children:[l("span",{className:"text-base font-semibold",children:Number(g.slice(8))}),l("span",{className:"text-xs font-semibold text-muted-foreground",children:x===0?"Today":dr(g)})]}),(p.get(g)??[]).slice(0,5).map(b=>m("button",{type:"button",onClick:()=>n(b.task),className:V("flex cursor-pointer items-center gap-1.5 truncate rounded-md px-1.5 py-1 text-left text-xs",c(b.task)?"border border-dashed border-border text-muted-foreground":b.task.priority==="urgent"?"bg-surface-destructive font-semibold text-destructive-text":b.task.priority==="high"?"bg-warning/15 font-semibold text-warning-text":"bg-surface-selected font-medium"),children:[b.timed?l("span",{className:"shrink-0 tabular-nums opacity-75",children:Ee(b.at,a.zone)}):null,l("span",{className:"truncate",children:b.task.title})]},`${b.task.id}-${b.at}`)),(p.get(g)?.length??0)>5?m("span",{className:"px-1.5 text-2xs text-muted-foreground",children:["+",(p.get(g)?.length??0)-5," more"]}):null]},g))}),m("div",{className:"space-y-6",children:[[...p.entries()].map(([g,x])=>m("section",{className:"space-y-2",children:[m("h2",{className:"flex items-baseline gap-2",children:[l("span",{className:"text-sm font-semibold",children:h(g)}),l("span",{className:"text-xs text-muted-foreground",children:Ct(g)})]}),l("div",{className:"overflow-hidden rounded-xl border border-border-hairline bg-surface-raised",children:x.map((b,_)=>m("button",{type:"button",onClick:()=>n(b.task),className:V("grid w-full cursor-pointer grid-cols-[4.5rem_1rem_minmax(0,1fr)_auto] items-center gap-3 px-4 py-2.5 text-left hover:bg-state-hover",_>0&&"border-t border-border-hairline"),children:[l("span",{className:V("text-right text-xs font-semibold tabular-nums",(c(b.task)||!b.timed)&&"font-normal text-muted-foreground"),children:b.timed?Ee(b.at,a.zone):"Due"}),l(Ht,{glyph:Qr(b.task),className:c(b.task)?"text-muted-foreground":"text-timeline-accent"}),m("span",{className:"flex min-w-0 items-center gap-2",children:[l("span",{className:V("truncate text-sm",c(b.task)?"text-muted-foreground":"font-semibold"),children:b.task.title}),l(De,{origin:b.task.origin,assistant:e.assistant,size:15}),l(Aa,{project:b.task.project})]}),m("span",{className:"flex items-center gap-2.5",children:[l("span",{className:"hidden truncate text-xs text-muted-foreground sm:inline",children:b.task.whenText?Gr(b.task.whenText):""}),l(ds,{level:b.task.priority})]})]},`${b.task.id}-${b.at}`))})]},g)),p.size===0?l(Oe,{children:"Nothing timed in the next four weeks."}):null,a.undated.length?l(Fn,{title:"No date",count:a.undated.length,hint:"Open, with no when",children:l(Rs,{tasks:a.undated,meta:e,now:r,open:n,limit:8,empty:""})}):null]})]})}async function ME(e,t,n,r){let o=[],s=0,i=0;for(let a=0;a<n&&s!==null;a++){let u=await e.call("tasks.list",{...t,limit:r,offset:s});o.push(...u.tasks),i=u.total,s=u.next}return{tasks:o,total:i,more:s!==null}}function DE({label:e,onClick:t}){return m("button",{type:"button",onClick:t,className:"flex w-full cursor-pointer items-center gap-2 border-t border-border-hairline px-4 py-2.5 text-left text-sm font-semibold text-timeline-accent hover:bg-state-hover",children:[l(pe,{name:"ChevronDown","aria-hidden":!0,className:"size-3.5"}),e]})}function EO({meta:e,filters:t,open:n,now:r}){let o=rt(),[s,i]=v(1),{data:a,error:u}=We(()=>ME(o,{...fs(t),move:"others",status:"open",sort:"due"},s,200),[o,s,t.origin,t.project]);return m("div",{className:"space-y-7",children:[l($s,{eyebrow:"Waiting on others",title:a?`${OE(a.total,"reply","replies")} outstanding`:"Waiting on others"}),l(Yr,{filters:t,onChange:bn,meta:e}),l(Fn,{title:"Waiting",count:a?.total,hint:`Soonest check-back first. ${e.assistant} nudges at most twice, then hands it back with what was tried`,children:a?m(he,{children:[l(Rs,{tasks:a.tasks,meta:e,now:r,open:n,rich:!0,empty:"Nobody owes you an answer."}),a.more?l(DE,{label:`Show more (${a.total-a.tasks.length} left)`,onClick:()=>i(c=>c+1)}):null]}):l(Oe,{children:u||"Loading\u2026"})})]})}function NO({meta:e,filters:t,open:n,now:r}){let o=rt(),[s,i]=v("both"),{data:a,error:u}=We(()=>o.call("tasks.rhythms",fs(t)),[o,t.origin,t.project]);if(!a)return l(Oe,{children:u||"Loading\u2026"});let c=Array.from({length:14},(d,p)=>qr(a.from,p));return m("div",{className:"space-y-7",children:[l($s,{eyebrow:"Scheduled and watched",title:"What happens on a rhythm, and what\u2019s being watched"}),m("p",{className:"-mt-4 max-w-2xl text-sm text-muted-foreground",children:["Scheduled tasks happen at set times. A watch belongs to a task that\u2019s waiting: ",e.assistant," checks quietly and only acts or tells you when something changes."]}),l(Yr,{filters:t,onChange:bn,meta:e,children:l(_t,{label:"Show",value:s,onChange:i,options:[{value:"both",label:"Both"},{value:"scheduled",label:"Scheduled"},{value:"watching",label:"Watching"}]})}),s!=="watching"?l(Fn,{title:"Scheduled",count:a.scheduled.length,hint:"The next two weeks",children:a.scheduled.length?m(he,{children:[m("div",{className:"hidden grid-cols-[1rem_minmax(0,1.4fr)_minmax(0,1fr)_15rem] gap-4 border-b border-border-hairline bg-muted/40 px-4 py-2 text-2xs font-semibold text-muted-foreground md:grid",children:[l("span",{}),l("span",{children:"Name"}),l("span",{children:"When"}),l("span",{className:"grid gap-0.5 text-center",style:{gridTemplateColumns:"repeat(14, minmax(0, 1fr))"},children:c.map((d,p)=>l("span",{className:p===0?"text-foreground":"",children:dr(d).charAt(0)},d))})]}),a.scheduled.map(({task:d,next:p},f)=>{let h=new Set(p.map(g=>ms(g,a.zone)));return m("button",{type:"button",onClick:()=>n(d),className:V("grid w-full cursor-pointer grid-cols-[1rem_minmax(0,1fr)] items-center gap-x-4 gap-y-2 px-4 py-3 text-left hover:bg-state-hover md:grid-cols-[1rem_minmax(0,1.4fr)_minmax(0,1fr)_15rem]",f>0&&"border-t border-border-hairline"),children:[l(Ht,{glyph:"repeat",className:"text-timeline-accent"}),m("span",{className:"min-w-0",children:[m("span",{className:"flex items-center gap-2",children:[l("span",{className:"truncate text-sm font-semibold",children:d.title}),l(De,{origin:d.origin,assistant:e.assistant,size:15}),l(Aa,{project:d.project})]}),l("span",{className:"block truncate text-xs text-muted-foreground",children:d.move==="owner"?"Reminder for you":`${e.assistant} does it`})]}),l("span",{className:"col-start-2 text-sm font-medium md:col-start-auto",children:d.whenText?Gr(d.whenText):""}),l("span",{className:"col-start-2 grid gap-0.5 md:col-start-auto",style:{gridTemplateColumns:"repeat(14, minmax(0, 1fr))"},"aria-label":`Runs on ${h.size} of the next 14 days`,children:c.map((g,x)=>l("span",{className:V("h-4 rounded",h.has(g)?d.move==="owner"?"bg-warning":"bg-foreground/80":"bg-muted",x===0&&"ring-2 ring-foreground/25 ring-offset-1 ring-offset-surface-raised")},g))})]},d.id)})]}):l(Oe,{children:"No repeating tasks yet. Say \u201Cevery Friday at 4pm, \u2026\u201D in the conversation, or add one here."})}):null,s!=="scheduled"?l(Fn,{title:"Watching",count:a.watched.length,hint:"Each one ends when its task does",children:a.watched.length?a.watched.map((d,p)=>m("button",{type:"button",onClick:()=>n(d),className:V("flex w-full cursor-pointer items-center gap-3 px-4 py-3 text-left hover:bg-state-hover",p>0&&"border-t border-border-hairline"),children:[l(Ht,{glyph:"watch",className:"text-timeline-accent"}),m("span",{className:"min-w-0 flex-1",children:[m("span",{className:"flex items-center gap-2",children:[l("span",{className:"truncate text-sm font-semibold",children:d.title}),l(De,{origin:d.origin,assistant:e.assistant,size:15}),l(Aa,{project:d.project})]}),l("span",{className:"block truncate text-xs text-muted-foreground",children:d.when?.form==="on_change"&&d.watch===null?`No watch yet; ${e.assistant} sets one up`:d.waitingOn?`Waiting on ${d.waitingOn}`:d.why??""})]}),l(Ea,{task:d,now:r})]},d.id)):l(Oe,{children:"Nothing is being watched."})}):null]})}async function AO(e,t,n){let r=[],o=[],s=null;for(let i=0;i<n;i++){let a=await e.call("tasks.journal",{...t,newest:!0,limit:200,...s===null?{}:{before:s}});if(r.unshift(...a.entries),o=a.notes,s=a.next,s===null)break}return{entries:r,notes:o,more:s!==null}}function CO({meta:e,filters:t}){let n=rt(),[r,o]=v(e.today),[s,i]=v(1),[a,u]=v("both"),[c,d]=v(null),[p,f]=v(""),{data:h,error:g,reload:x}=We(async()=>({day:r,journal:await AO(n,{day:r,...a!=="both"?{actor:a}:{},...t.project?{project:t.project}:{}},s)}),[n,r,a,s,t.project]),b=h?.day===r?h.journal:null,_=b?.notes.find(y=>y.actor==="owner")?.body??"",w=b?.notes.find(y=>y.actor==="assistant")?.body,T=e.zone;return m("div",{className:"mx-auto max-w-3xl space-y-7",children:[m($s,{eyebrow:"Journal",title:Ct(r),children:[l(R,{variant:"outline",size:"icon","aria-label":"The day before",onClick:()=>(o(qr(r,-1)),d(null),f(""),i(1)),children:l(pe,{name:"ChevronLeft","aria-hidden":!0,className:"size-4"})}),l(R,{variant:"outline",size:"icon","aria-label":"The day after",disabled:r>=e.today,onClick:()=>(o(qr(r,1)),d(null),f(""),i(1)),children:l(pe,{name:"ChevronRight","aria-hidden":!0,className:"size-4"})}),r!==e.today?l(R,{variant:"outline",size:"sm",onClick:()=>(o(e.today),d(null),f(""),i(1)),children:"Today"}):null]}),w?m("div",{className:"flex items-start gap-3.5 rounded-2xl bg-surface-selected px-4 py-3.5",children:[l(De,{origin:"assistant",assistant:e.assistant,size:26}),l("p",{className:"whitespace-pre-wrap text-base leading-relaxed",children:w})]}):null,m("div",{className:"flex flex-wrap items-center gap-3",children:[l(_t,{label:"Whose lines",value:a,onChange:u,options:[{value:"both",label:"Both"},{value:"assistant",label:e.assistant},{value:"owner",label:"You"}]}),l(Yr,{filters:t,onChange:bn,meta:e,origin:!1})]}),b?b.entries.length===0?m(Oe,{children:["Nothing was written ",r===e.today?"yet today":"that day","."]}):m("ol",{className:"relative space-y-4 border-l border-border-hairline pl-6",children:[b.more?l("li",{children:m("button",{type:"button",onClick:()=>i(y=>y+1),className:"flex cursor-pointer items-center gap-2 text-sm font-semibold text-timeline-accent hover:underline",children:[l(pe,{name:"ChevronUp","aria-hidden":!0,className:"size-3.5"}),"Show earlier"]})}):null,b.entries.map(y=>m("li",{className:"relative",children:[l("span",{className:"absolute -left-[2.15rem] top-0",children:y.actor==="system"?l("span",{className:"block size-5 rounded-full border border-border bg-muted"}):l(De,{origin:y.actor==="assistant"?"assistant":"owner",assistant:e.assistant,size:22})}),m("p",{className:"text-xs text-muted-foreground",children:[Ee(y.at,T)," \xB7 ",y.actor==="assistant"?e.assistant:y.actor==="owner"?"You":"System"]}),l("p",{className:V("mt-0.5 whitespace-pre-wrap text-sm leading-relaxed",y.actor==="owner"&&y.what==="note"&&"rounded-lg border border-border-hairline bg-surface-raised px-3 py-2",y.what==="created"&&"text-muted-foreground"),children:y.body}),m("p",{className:"mt-1.5 text-xs font-medium text-muted-foreground",children:[y.key," \xB7 ",y.title]})]},y.seq))]}):l(Oe,{children:g||"Loading\u2026"}),m("form",{className:"space-y-2 rounded-2xl border border-border bg-surface-raised p-4",onSubmit:y=>{y.preventDefault(),b&&n.call("tasks.dayNote",{day:r,body:c??_}).then(()=>{f(`Saved ${Ee(Date.now(),T)}`),x()},E=>f(`Couldn\u2019t save: ${E instanceof Error?E.message:String(E)}`))},children:[m("label",{className:"flex items-center gap-2 text-sm font-semibold",children:[l(De,{origin:"owner",assistant:e.assistant,size:18}),"Your note for ",r===e.today?"today":Ct(r,"short")]}),l("textarea",{value:c??_,disabled:!b,onChange:y=>d(y.target.value),rows:3,className:"w-full resize-y rounded-md border border-input bg-background px-3 py-2 text-sm leading-relaxed",placeholder:`How did it go? Anything on your mind, or anything ${e.assistant} should know?`}),m("div",{className:"flex items-center justify-end gap-3",children:[l("span",{className:"text-xs text-muted-foreground",children:p||`${e.assistant} reads your notes as context`}),l(R,{type:"submit",size:"sm",disabled:!b||c===null||c===_,children:"Save note"})]})]})]})}function TO({meta:e,filters:t,open:n,now:r}){let o=rt(),[s,i]=v("done"),[a,u]=v(1),{data:c,error:d}=We(()=>ME(o,{...fs(t),status:s,sort:"closed"},a,50),[o,s,a,t.origin,t.project]),p=c?.tasks??[];return m("div",{className:"space-y-7",children:[l($s,{eyebrow:"Done",title:"Finished and dropped",children:l(_t,{label:"Which",value:s,onChange:f=>{i(f),u(1)},options:[{value:"done",label:"Done"},{value:"dropped",label:"Dropped"}]})}),l(Yr,{filters:t,onChange:bn,meta:e}),l(Fn,{title:s==="done"?"Done":"Dropped",count:c?.total,hint:s==="dropped"?"Each with its reason; reopen any of them":"Most recent first",children:c?m(he,{children:[l(Rs,{tasks:p,meta:e,now:r,open:n,empty:s==="done"?"Nothing finished yet.":"Nothing dropped."}),c.more?l(DE,{label:"Show older",onClick:()=>u(f=>f+1)}):null]}):l(Oe,{children:d||"Loading\u2026"})})]})}function FE({subPath:e}){let t=cm(e),[n,r]=v(t.task);M(()=>{t.task&&r(t.task)},[t.task]);let o=ps(),[s]=dm(),i=tn(),a=hs(),[u,c]=v(!1),d=f=>i(t.view,f.key),p=o?{today:l(kO,{meta:o,filters:s,open:d,now:a}),upcoming:l(SO,{meta:o,filters:s,open:d,now:a}),waiting:l(EO,{meta:o,filters:s,open:d,now:a}),scheduled:l(NO,{meta:o,filters:s,open:d,now:a}),journal:l(CO,{meta:o,filters:s}),done:l(TO,{meta:o,filters:s,open:d,now:a})}:{today:null,upcoming:null,waiting:null,scheduled:null,journal:null,done:null};return m("main",{className:"h-full overflow-auto",children:[m("div",{className:"mx-auto flex max-w-7xl flex-col gap-6 p-4 sm:p-8",children:[m("div",{className:"flex items-center gap-2",children:[l("nav",{"aria-label":"Task views",className:"flex min-w-0 flex-1 gap-1 overflow-x-auto md:hidden",children:gu.map(f=>l("button",{type:"button","aria-current":t.view===f.id?"page":void 0,onClick:()=>i(f.id),className:V("shrink-0 cursor-pointer rounded-full px-3 py-1.5 text-xs font-semibold",t.view===f.id?"bg-foreground text-background":"bg-muted text-muted-foreground"),children:f.label},f.id))}),m(R,{className:"ml-auto shrink-0","aria-label":"New task",onClick:()=>c(!0),children:[l(pe,{name:"Plus","aria-hidden":!0,className:"size-4"}),l("span",{className:"hidden sm:inline",children:"New task"})]})]}),o?p[t.view]:l(Oe,{children:"Loading\u2026"})]}),l(nE,{open:u,onClose:()=>c(!1),meta:o,onMade:f=>{c(!1),i(t.view,f.key)}}),l(rE,{open:t.task!==null,taskRef:t.task??n,meta:o,onClose:()=>i(t.view)})]})}function zE({subPath:e}){let t=cm(e),n=tn(),r=rt(),o=ps(),[s,i]=dm(),a=We(()=>r.call("tasks.today",{}),[r]).data,u={today:a?.yours.length,waiting:a?.waiting.length};return m("nav",{"aria-label":"Tasks",className:"flex flex-col gap-0.5 p-2",children:[gu.map(c=>m("button",{type:"button","aria-current":t.view===c.id?"page":void 0,onClick:()=>n(c.id),className:V("flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm",t.view===c.id?"bg-muted font-semibold":"hover:bg-muted/60"),children:[l("span",{className:"min-w-0 flex-1 truncate",children:c.label}),u[c.id]?l("span",{className:V("rounded-full px-1.5 text-2xs font-bold",c.id==="today"?"bg-foreground text-background":"text-muted-foreground"),children:u[c.id]}):null]},c.id)),l("p",{className:"mt-4 px-2 pb-1 text-xs font-semibold text-muted-foreground",children:"Projects"}),(o?.projects??[]).map(c=>m("button",{type:"button","aria-pressed":s.project===c.id,onClick:()=>i({...s,project:s.project===c.id?"":c.id}),className:V("flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm",s.project===c.id?"bg-muted font-semibold":"hover:bg-muted/60"),children:[l("span",{className:"min-w-0 flex-1 truncate",children:c.name}),l("span",{className:"text-2xs font-bold tracking-wide text-muted-foreground",children:c.key})]},c.id)),m("p",{className:"px-2 pt-2 text-xs leading-snug text-muted-foreground",children:["A project is a GitHub repo. Personal holds your life; Internals holds ",o?.assistant??"the assistant","\u2019s own workings."]})]})}function KE(){let e=rt(),t=ps(),n=tn(),r=hs(),o=LE(),{data:s,error:i}=We(()=>e.call("tasks.today",{}),[e]);if(!s||!t)return l(Oe,{children:i||"Loading\u2026"});let a=s.schedule.filter(u=>u.at>=r).slice(0,4);return m("div",{className:"space-y-6 p-4",children:[m("section",{className:"space-y-2",children:[m("h2",{className:"flex items-center gap-2 text-sm font-semibold",children:["Your move ",l("span",{className:"rounded-full bg-muted px-2 text-xs text-muted-foreground",children:s.yours.length}),l("button",{type:"button",className:"ml-auto cursor-pointer text-xs font-semibold text-timeline-accent",onClick:()=>n("today"),children:"Open Tasks"})]}),s.yours.length===0?l("p",{className:"text-sm text-muted-foreground",children:"Nothing needs you."}):null,l("ul",{className:"divide-y divide-border-hairline",children:s.yours.map(u=>m("li",{className:"flex items-center gap-2.5 py-2",children:[l("button",{type:"button","aria-label":`Mark ${u.title} done`,onClick:()=>o(u),className:"size-4 shrink-0 cursor-pointer rounded-full border-[1.5px] border-foreground/35 hover:border-foreground/70"}),l("button",{type:"button",onClick:()=>n("today",u.key),className:"min-w-0 flex-1 cursor-pointer truncate text-left text-sm font-medium",children:u.title}),l(De,{origin:u.origin,assistant:t.assistant,size:14}),l(Ea,{task:u,now:r})]},u.id))})]}),a.length?m("section",{className:"space-y-1.5",children:[l("h2",{className:"text-sm font-semibold",children:"Next up today"}),a.map(u=>m("button",{type:"button",onClick:()=>n("today",u.task.key),className:"grid w-full cursor-pointer grid-cols-[4rem_1rem_minmax(0,1fr)] items-center gap-2 py-1 text-left text-sm",children:[l("span",{className:"text-right text-xs tabular-nums text-muted-foreground",children:Ee(u.at,s.zone)}),l(Ht,{glyph:Qr(u.task),className:"size-3.5 text-timeline-accent"}),l("span",{className:"truncate",children:u.task.title})]},`${u.task.id}-${u.at}`))]}):null,m("p",{className:"border-t border-border-hairline pt-3 text-xs leading-relaxed text-muted-foreground",children:[t.assistant," is handling ",s.onIt.length," and waiting on ",s.waiting.length===1?"one reply":`${s.waiting.length} replies`,".",s.waiting[0]?.whenText?` Next check: ${s.waiting[0].title}, ${s.waiting[0].whenText}.`:""]})]})}function Is(e){let t=e?.nickname?.trim(),n=e?.name.trim();return t||(n&&n!=="Orbit"?n:"your moonlet")}function Ps(){let e=J(),[t,n]=v(null),[r,o]=v(null),s=q(()=>{e.call("config.state",null).then(i=>{n(i),o(null)},i=>o(i instanceof Error?i.message:String(i)))},[e]);return M(s,[s]),ke("config",s),{rpc:e,state:t,error:r,refetch:s}}function XE(e,t){let n=URL.createObjectURL(new Blob([t],{type:"application/toml"})),r=document.createElement("a");r.href=n,r.download=e,r.click(),setTimeout(()=>URL.revokeObjectURL(n),1e3)}function BE(e){let t=document.createElement("input");t.type="file",t.accept=".toml,text/plain",t.onchange=()=>{t.files?.[0]?.text().then(e)},t.click()}function UE({at:e,by:t}){return e?m("span",{className:"text-xs text-muted-foreground",children:["Last changed ",new Date(e).toLocaleString(),t?` by ${t}`:""]}):null}function Pa(){let{state:e}=Ps(),t=Is(e?.prefs.identity);return t==="your moonlet"?"Your moonlet":t}var RO=256,$O=.85,IO=[["image/webp","webp"],["image/png","png"],["image/jpeg","jpg"]],co=class extends Error{};function PO(e,t,n=RO){let r=Math.min(e,t);return{x:Math.floor((e-r)/2),y:Math.floor((t-r)/2),side:r,edge:Math.min(r,n)}}var Um=e=>Math.ceil(e/1024);async function HE(e){let t=new Uint8Array(await e.arrayBuffer()),n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(n)}var VE={decode:e=>createImageBitmap(e,{imageOrientation:"from-image"}),encode:(e,t,n)=>new Promise((r,o)=>{let s=document.createElement("canvas");s.width=t.edge,s.height=t.edge;let i=s.getContext("2d");if(!i){o(new co("This browser can't shrink pictures. Choose one of at most 128 KB."));return}n==="image/jpeg"&&(i.fillStyle="#fff",i.fillRect(0,0,t.edge,t.edge)),i.imageSmoothingQuality="high",i.drawImage(e,t.x,t.y,t.side,t.side,0,0,t.edge,t.edge),s.toBlob(a=>a?r(a):o(new co("The picture couldn't be saved smaller.")),n,$O)})};async function ZE(e,t){if(e.type==="image/svg+xml"||/\.svg$/i.test(e.name)){if(e.size>131072)throw new co(`An SVG avatar is at most ${Um(131072)} KB, and an SVG can't be shrunk (${e.name} is ${Um(e.size)} KB).`);return{name:"avatar.svg",base64:await HE(e)}}let n;try{n=await t.decode(e)}catch{throw new co(`${e.name} isn't a picture this browser can open. Choose a PNG, JPEG, WebP or SVG.`)}try{let r=PO(n.width,n.height);for(let[o,s]of IO){let i=await t.encode(n,r,o);if(i.type===o&&i.size>0&&i.size<=131072)return{name:`avatar.${s}`,base64:await HE(i)}}throw new co(`${e.name} couldn't be made smaller than ${Um(131072)} KB. Try a simpler picture.`)}finally{n.close()}}var OO=[["orbit","In your moonlet's conversation"],["work","On the conversations it starts"]],LO="image/png,image/jpeg,image/webp,image/svg+xml,.png,.jpg,.jpeg,.webp,.svg";function WE({avatar:e,onChange:t,shrink:n=r=>ZE(r,VE)}){let r=J(),[o,s]=v(null),i=G({}),a=(u,c)=>{s({which:u,text:"Shrinking the picture\u2026",failed:!1}),n(c).then(d=>r.call("config.avatarFromUpload",d)).then(d=>{if(d.url){let p=d.url;t(f=>({...f,[u]:p})),s(null)}else s({which:u,text:d.problem??"The picture was refused.",failed:!0})},d=>s({which:u,text:d instanceof Error?d.message:String(d),failed:!0}))};return l("div",{className:"flex flex-wrap gap-6",children:OO.map(([u,c])=>m("div",{className:"flex items-center gap-3",children:[l(sc,{url:e[u],label:c,size:48}),m("div",{className:"flex flex-col gap-1",children:[l("span",{className:"font-medium",children:c}),m("div",{className:"flex gap-2",children:[l("input",{ref:d=>{i.current[u]=d},type:"file",accept:LO,hidden:!0,"aria-label":`Picture for ${c}`,onChange:d=>{let p=d.currentTarget.files?.[0];d.currentTarget.value="",p&&a(u,p)}}),l(R,{size:"sm",variant:"secondary",disabled:o?.which===u&&!o.failed,onClick:()=>i.current[u]?.click(),children:e[u]?"Replace\u2026":"Choose\u2026"}),l(R,{size:"sm",variant:"ghost",disabled:!e[u],onClick:()=>{s(null),t(({[u]:d,...p})=>p)},children:"Clear"})]}),o?.which===u&&l("p",{role:o.failed?"alert":"status",className:o.failed?"text-xs text-destructive":"text-xs text-muted-foreground",children:o.text})]})]},u))})}function Os(){let{rpc:e,state:t,error:n,refetch:r}=Ps(),o=G(null),s=G(0),i=G(Promise.resolve()),[a,u]=v(null),[c,d]=v(null);Ye(()=>{t&&s.current===0&&(o.current={prefs:t.prefs,base:t.prefsBase})},[t]);let p=q(f=>(s.current+=1,i.current=i.current.then(async()=>{try{let h=o.current;if(!h)return;let g=f(h.prefs);if(JSON.stringify(g)===JSON.stringify(h.prefs))return;await e.call("config.savePrefs",{prefs:g,base:h.base});let x=await e.call("config.state",null);o.current={prefs:x.prefs,base:x.prefsBase},u(null),d(Date.now())}catch(h){u(h instanceof Error?h.message:String(h))}finally{s.current-=1,r()}}),i.current),[e,r]);return{rpc:e,state:t,error:n,refetch:r,save:p,problem:a,savedAt:c}}function Zu({problem:e,savedAt:t}){return e?l("p",{role:"alert",className:"text-xs text-destructive",children:e}):t===null?null:l("p",{role:"status",className:"text-xs text-muted-foreground",children:"Saved. Your moonlet uses it from now on."})}function Wu({label:e,value:t,onCommit:n,multiline:r=!1,rows:o=3,placeholder:s,className:i=""}){let[a,u]=v(t),c=G(!1),d=G(t);M(()=>{d.current=t,c.current||u(t)},[t]);let p=()=>{c.current=!1,!(a===t&&a===d.current)&&(d.current=a,n(a))};return r?l("textarea",{"aria-label":e,rows:o,placeholder:s,className:`w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm leading-relaxed outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 ${i}`,value:a,onFocus:()=>{c.current=!0},onChange:f=>u(f.target.value),onBlur:p}):l(le,{"aria-label":e,placeholder:s,className:`h-8 w-64 text-sm ${i}`,value:a,onFocus:()=>{c.current=!0},onChange:f=>u(f.target.value),onBlur:p,onKeyDown:f=>{f.key==="Enter"&&f.currentTarget.blur()}})}function MO(e,t,n){let r={...e};return n.trim()||t==="name"?r[t]=n:delete r[t],r}function jE(){let{state:e,error:t,save:n,problem:r,savedAt:o}=Os();if(t)return l("p",{className:"text-sm text-destructive",children:t});if(!e)return l("p",{className:"text-sm text-muted-foreground",children:"Loading\u2026"});let s=e.prefs.identity,i=Is(s),a=(u,c,d,p={})=>l(Ni,{label:c,description:d,controlPlacement:p.multiline?"below":"inline",children:l(Wu,{label:c,multiline:p.multiline,rows:2,value:s[u]??"",onCommit:f=>{n(h=>({...h,identity:MO(h.identity,u,f)}))}})});return m("div",{className:"space-y-10",children:[l(Zu,{problem:r,savedAt:o}),l(ct,{title:"Identity",description:`How ${i==="your moonlet"?"your moonlet":i} introduces itself in chat, commits and mail.`,children:m("div",{className:"space-y-5",children:[a("name","Name","Its formal name, on commits and as the sender in mail."),a("nickname","Nickname","What you call it day to day. Empty: the name."),a("pronouns","Pronouns",void 0),a("signature","Signature","One line under its sign-off in mail. Empty: the nickname, else the name."),a("bio","Bio","One or two sentences, for introductions.",{multiline:!0})]})}),l(ct,{title:"Pictures",description:"Shown beside its messages. PNG, JPEG or WebP is cropped square and shrunk to 256 pixels; an SVG may be up to 128 KB.",children:l(WE,{avatar:e.prefs.avatar,onChange:u=>{n(c=>({...c,avatar:u(c.avatar)}))}})}),l(ct,{title:"Accounts",description:"Its own accounts. Change the account itself first, then update it here. Without an email address it doesn't commit or send mail.",children:m("div",{className:"space-y-5",children:[a("email","Email address","Where it commits and sends mail from."),a("github","GitHub username",void 0)]})}),l(ct,{title:"Owner",children:a("owner","Works for",'Who it works for, by name. Empty: "your owner". Only you can change this.')})]})}var Ls=e=>typeof e=="string"?e:e.text,QE=e=>typeof e=="string"?null:e.until,GE=(e,t)=>Ls(e)===Ls(t)&&QE(e)===QE(t);function YE(e,t,n){let r=e[n];return r!==void 0&&GE(r,t)?n:e.findIndex(o=>GE(o,t))}function DO(e,t){return new Date(e).toLocaleString("en-US",{timeZone:t,weekday:"short",day:"numeric",month:"short",year:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}function FO({r:e,n:t,zone:n,onChange:r,onRemove:o}){let s=J(),[i,a]=v(!1),[u,c]=v(""),[d,p]=v(null),f=typeof e=="string"?null:e.until,h=f!==null&&Date.parse(f)<=Date.now();return m("li",{className:"flex flex-col gap-2 py-2.5 text-sm first:pt-0 last:pb-0",children:[m("div",{className:"flex items-start gap-3",children:[l("span",{className:"w-5 shrink-0 pt-px text-right text-xs tabular-nums text-muted-foreground",children:t}),m("div",{className:"min-w-0 flex-1",children:[l("p",{className:h?"text-muted-foreground line-through":"text-foreground",children:Ls(e)}),f!==null&&l("p",{className:`mt-0.5 text-xs ${h?"text-destructive":"text-muted-foreground"}`,children:`${h?"Lapsed":"Until"} ${DO(f,n)}`})]}),f!==null&&l(R,{size:"sm",variant:h?"secondary":"ghost",onClick:()=>a(!i),children:"Renew"}),l(R,{size:"sm",variant:"ghost",onClick:o,children:"Remove"})]}),i&&m("div",{className:"ml-8 flex flex-wrap items-center gap-2 text-xs",children:[l(le,{type:"datetime-local",className:"w-56",value:u,onChange:g=>c(g.target.value)}),m("span",{className:"text-muted-foreground",children:["in ",n]}),l(R,{size:"sm",variant:"secondary",disabled:!u,onClick:()=>{s.call("config.untilInstant",{at:u}).then(g=>{if(g.until===null)return p(g.problem);p(null),a(!1),r({text:Ls(e),until:g.until})},g=>p(g instanceof Error?g.message:String(g)))},children:"Until then"}),l(R,{size:"sm",variant:"ghost",onClick:()=>{a(!1),r(Ls(e))},children:"No end"}),d&&l("span",{className:"text-destructive",children:d})]})]})}function qE(){let{state:e,error:t,save:n,problem:r,savedAt:o}=Os(),[s,i]=v("");if(t)return l("p",{className:"text-sm text-destructive",children:t});if(!e)return l("p",{className:"text-sm text-muted-foreground",children:"Loading\u2026"});let a=e.prefs.instructions,u=()=>{let c=s.trim();c&&(i(""),n(d=>({...d,instructions:[...d.instructions,c]})))};return m("div",{className:"space-y-10",children:[l(Zu,{problem:r,savedAt:o}),l(ct,{title:"Tone",description:"How it talks to you. {{owner}} stands for your name.",children:l(Wu,{label:"Tone and persona",multiline:!0,rows:6,value:e.prefs.tone,onCommit:c=>{n(d=>({...d,tone:c}))}})}),l(ct,{title:"Standing instructions",description:"Rules it always follows. When it adds one itself, you see it here.",children:m("div",{className:"space-y-4",children:[a.length===0?l("p",{className:"text-sm text-muted-foreground",children:"None yet."}):l("ol",{className:"divide-y divide-border",children:a.map((c,d)=>l(FO,{r:c,n:d+1,zone:e.zone,onChange:p=>{n(f=>{let h=YE(f.instructions,c,d);return{...f,instructions:f.instructions.map((g,x)=>x===h?p:g)}})},onRemove:()=>{n(p=>{let f=YE(p.instructions,c,d);return{...p,instructions:p.instructions.filter((h,g)=>g!==f)}})}},`${d}-${Ls(c)}`))}),m("div",{className:"flex gap-2",children:[l(le,{"aria-label":"New instruction",placeholder:"Never book anything before 9am",value:s,onChange:c=>i(c.target.value),onKeyDown:c=>{c.key==="Enter"&&u()}}),l(R,{size:"sm",variant:"outline",disabled:!s.trim(),onClick:u,children:"Add"})]})]})})]})}function JE(){let e=0;return{async take(t){let n=++e,r=await t;return n===e?{current:!0,value:r}:{current:!1}},cancel(){e++}}}var nN=[{id:"you",title:"About you",lead:"Your moonlet works for you. Tell it who you are; it keeps the rest in memory as you go."},{id:"reach",title:"Reaching you",lead:"Your moonlet talks with you in its conversation in Moonlet. Say where else it should put things, and when to leave you alone."},{id:"touchpoints",title:"Your day",lead:'When your moonlet comes to you on its own. To change one later, just tell your moonlet ("move the morning digest to 8"), or change it in Settings \u2192 your moonlet \u2192 Daily rhythm.'},{id:"sign-ins",title:"Machine sign-ins",lead:"The keys your moonlet's machines sign in with. Both can wait: add them later in Settings, the 1Password key under Integrations and the Claude Code token under Providers."}],eN=["Text message (SMS)","Voice call","WhatsApp","Telegram","Signal","iMessage","Slack","Discord"],zO=[["mon","Monday"],["tue","Tuesday"],["wed","Wednesday"],["thu","Thursday"],["fri","Friday"],["sat","Saturday"],["sun","Sunday"]],Ms=e=>e instanceof Error?e.message:String(e);function Zm(){let e=J(),[t,n]=v(null),[r,o]=v(null),s=q(()=>{e.call("welcome.state",null).then(i=>{n(i),o(null)},i=>o(i instanceof Error?i.message:String(i)))},[e]);return M(s,[s]),ke("config",s),{rpc:e,state:t,error:r,refetch:s}}function Hm({label:e,hint:t,children:n}){return m("label",{className:"flex flex-col gap-1 text-sm",children:[l("span",{className:"font-medium",children:e}),n,t&&l("span",{className:"text-xs text-muted-foreground",children:t})]})}function sn({label:e,hint:t,checked:n,onChange:r}){return m("label",{className:"flex items-start gap-2 text-sm",children:[l("input",{type:"checkbox",className:"mt-1",checked:n,onChange:o=>r(o.target.checked)}),m("span",{children:[e,t&&l("span",{className:"block text-xs text-muted-foreground",children:t})]})]})}function Wm(e,t,n,r){let[o,s]=v([]),[i,a]=v(!1),[u,c]=v(null),[d,p]=v(!1);return{save:g=>{p(!0),c(null),e.call("welcome.save",{step:t,values:g}).then(x=>{let b=(x.handover??[]).some(_=>_.state==="failed");s(x.lines),a(b),p(!1),n(),b||r()},x=>{c(Ms(x)),p(!1)})},retry:()=>{p(!0),c(null),e.call("welcome.handover",null).then(g=>{s(g.lines),a(g.handover.some(x=>x.state==="failed")),p(!1)},g=>{c(Ms(g)),p(!1)})},lines:o,failed:i,problem:u,busy:d}}function Qu({onBack:e,onSkip:t,onContinue:n,busy:r,problem:o,label:s="Save and continue",settings:i=!1}){return m("div",{className:"mt-6 flex flex-col gap-2",children:[o&&l("p",{className:"text-sm text-destructive",children:o}),m("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e&&l(R,{variant:"ghost",className:"mr-auto",onClick:e,children:"Back"}),!i&&l(R,{variant:"ghost",onClick:t,children:"Skip for now"}),l(R,{disabled:r,onClick:n,children:r?"Saving\u2026":i?"Save":s})]})]})}function Vm(e){return[e.name,...[e.admin,e.country].filter(t=>!!t&&t!==e.name)].join(", ")}function KO({city:e,place:t,zone:n,rpc:r,onCity:o,onPlace:s}){let[i,a]=v(null),[u,c]=v(!1),[d,p]=v(null),[f,h]=v(!1),g=Lt(()=>JE(),[]),x=t!==void 0&&(e.trim()===t.name||(i?.includes(t)??!1));return M(()=>{let b=e.trim();if(!b||x)return;let _=setTimeout(()=>{c(!0),p(null),g.take(r.call("welcome.places",{query:b})).then(w=>{w.current&&(a(w.value.places),s(w.value.places[0]),h(!1),c(!1))},w=>{p(Ms(w)),c(!1)})},600);return()=>clearTimeout(_)},[e,x,r,s,g]),m(Hm,{label:"Where you live",hint:"A city. The weather in your morning digest, anything local, and your time zone come from it.",children:[l(le,{value:e,onChange:b=>{o(b.target.value),g.cancel(),a(null),h(!1),c(!1),t&&b.target.value.trim()!==t.name&&s(void 0)}}),u?l("span",{className:"text-xs text-muted-foreground",children:"Looking it up\u2026"}):d?m("span",{className:"text-xs text-destructive",children:[d,". Your moonlet keeps its time zone, ",n,"; change it in Settings \u2192 General if it's wrong."]}):t?m("span",{className:"text-xs text-muted-foreground",children:[Vm(t)," \xB7 ",t.timezone,i&&i.length>1&&!f&&m(he,{children:[" \xB7 ",l("button",{type:"button",className:"underline",onClick:()=>h(!0),children:"Not this one?"})]})]}):e.trim()&&i&&i.length===0?m("span",{className:"text-xs text-muted-foreground",children:["No place of that name; your moonlet keeps the city as you wrote it and its time zone, ",n,"."]}):m("span",{className:"text-xs text-muted-foreground",children:["Time zone now: ",n,"."]}),f&&i&&l("select",{className:"h-9 rounded-md border border-input bg-background px-2 text-sm",value:t?i.indexOf(t):0,onChange:b=>{s(i[Number(b.target.value)]),h(!1)},children:i.map((b,_)=>m("option",{value:_,children:[Vm(b)," \xB7 ",b.timezone]},`${b.latitude},${b.longitude}`))})]})}function XO({state:e,rpc:t,refetch:n,onDone:r,onSkip:o,onBack:s}){let[i,a]=v(e.record.you),{save:u,problem:c,busy:d}=Wm(t,"you",n,r),p=(h,g)=>a(x=>({...x,[h]:g.trim()?g:void 0})),f=q(h=>a(g=>({...g,place:h})),[]);return m(he,{children:[m("div",{className:"flex flex-col gap-4",children:[l(Hm,{label:"Your name",hint:"What your moonlet calls you. Without one it says \u201Cyour owner\u201D.",children:l(le,{autoFocus:!0,value:i.name??"",onChange:h=>p("name",h.target.value)})}),l(KO,{city:i.city??"",place:i.place,zone:e.zone,rpc:t,onCity:h=>p("city",h),onPlace:f}),l(Hm,{label:"Your email address",hint:"Where your moonlet mails you when you want that, and how it knows mail from you is yours.",children:l(le,{value:i.email??"",onChange:h=>p("email",h.target.value)})})]}),l(Qu,{onBack:s,onSkip:o,busy:d,problem:c,onContinue:()=>u({you:{...i.name?{name:i.name}:{},...i.city?{city:i.city}:{},...i.city&&i.place?{place:i.place}:{},...i.email?{email:i.email}:{}}})})]})}function jm({settings:e=!1,state:t,rpc:n,refetch:r,onDone:o,onSkip:s,onBack:i}){let[a,u]=v(t.record.reach),[c,d]=v(a.quiet_from!==void 0),[p,f]=v(""),{save:h,problem:g,busy:x}=Wm(n,"reach",r,o),b=a.other??[],_=b.filter(y=>!eN.includes(y)),w=(y,E)=>u({...a,other:E?[...b.filter(k=>k!==y),y]:b.filter(k=>k!==y)}),T=()=>{let y=p.trim().slice(0,60);if(!y||b.some(E=>E.toLowerCase()===y.toLowerCase()))return f("");b.length>=10||(u({...a,other:[...b,y]}),f(""))};return m(he,{children:[m("div",{className:"flex flex-col gap-4",children:[l(sn,{label:"Put decisions and anything waiting on me in my Moonlet inbox",hint:"One item each, with a link, in your Moonlet inbox; your moonlet still says a line in its conversation.",checked:a.inbox,onChange:y=>u({...a,inbox:y})}),l(sn,{label:"Mail me the digests too",hint:t.record.you.email?`To ${t.record.you.email}, from your moonlet's own mailbox.`:"Needs your email address (About you) and a station with mail.",checked:a.mail,onChange:y=>u({...a,mail:y})}),l(sn,{label:"Quiet hours",hint:"Nothing that can wait is sent between them (in your time zone); it comes after.",checked:c,onChange:d}),c&&m("div",{className:"ml-6 flex flex-wrap items-center gap-2 text-sm",children:[l("span",{children:"From"}),l(le,{type:"time",className:"w-32",value:a.quiet_from??"22:00",onChange:y=>u({...a,quiet_from:y.target.value})}),l("span",{children:"to"}),l(le,{type:"time",className:"w-32",value:a.quiet_to??"07:00",onChange:y=>u({...a,quiet_to:y.target.value})})]}),m("section",{className:"flex flex-col gap-2 rounded-md border p-3",children:[l("span",{className:"text-sm font-medium",children:"Other ways"}),l("span",{className:"text-xs text-muted-foreground",children:"How else you'd want your moonlet to reach you. None of these is connected yet: your moonlet reaches you in Moonlet, and by mail when you ask for it. It notes what you'd want, says so when it comes up, and never claims to have sent something a way it can't."}),l("div",{className:"grid grid-cols-2 gap-1",children:eN.map(y=>l(sn,{label:y,checked:b.includes(y),onChange:E=>w(y,E)},y))}),_.length>0&&l("ul",{className:"flex flex-wrap gap-2 text-xs",children:_.map(y=>m("li",{className:"flex items-center gap-1 rounded-full border px-2 py-0.5",children:[y,l("button",{type:"button",className:"text-muted-foreground","aria-label":`Remove ${y}`,onClick:()=>w(y,!1),children:"\xD7"})]},y))}),m("div",{className:"flex items-center gap-2",children:[l(le,{className:"max-w-xs",placeholder:"Something else: Matrix, a pager, \u2026",value:p,onChange:y=>f(y.target.value),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),T())}}),l(R,{size:"sm",variant:"secondary",disabled:!p.trim()||b.length>=10,onClick:T,children:"Add"})]})]})]}),l(Qu,{settings:e,onBack:i,onSkip:s,busy:x,problem:g,onContinue:()=>h({reach:{inbox:a.inbox,mail:a.mail,...c?{quiet_from:a.quiet_from??"22:00",quiet_to:a.quiet_to??"07:00"}:{},other:b}})})]})}function Qm({settings:e=!1,state:t,rpc:n,refetch:r,onDone:o,onSkip:s,onBack:i}){let[a,u]=v(t.record.touchpoints),{save:c,problem:d,busy:p}=Wm(n,"touchpoints",r,o),f=h=>u({...a,morning:{...a.morning,...h}});return m(he,{children:[m("div",{className:"flex flex-col gap-3",children:[m("p",{className:"text-xs text-muted-foreground",children:["Times are in ",t.zone,". Each becomes a routine your moonlet keeps, and your moonlet changes or drops it when you ask."]}),m("section",{className:"flex flex-col gap-2 rounded-md border p-3",children:[m("div",{className:"flex items-center gap-3",children:[l(sn,{label:"Morning digest",checked:a.morning.on,onChange:h=>f({on:h})}),l("span",{className:"text-sm",children:"at"}),l(le,{type:"time",className:"w-32",value:a.morning.at,onChange:h=>f({at:h.target.value})})]}),a.morning.on&&m("div",{className:"ml-6 flex flex-col gap-1",children:[l(sn,{label:"Today's weather",hint:t.record.you.place?`In ${Vm(t.record.you.place)}.`:t.record.you.city?`In ${t.record.you.city}.`:"Give your city under About you, or your moonlet asks once.",checked:a.morning.weather,onChange:h=>f({weather:h})}),l(sn,{label:"What's on my calendar",checked:a.morning.calendar,onChange:h=>f({calendar:h})}),l(sn,{label:"New mail waiting on me",checked:a.morning.mail,onChange:h=>f({mail:h})}),l(sn,{label:"Unfinished tasks due today, and what's waiting on me",checked:a.morning.loops,onChange:h=>f({loops:h})})]})]}),m("section",{className:"flex flex-wrap items-center gap-3 rounded-md border p-3",children:[l(sn,{label:"End of day wrap-up",hint:"What got done, what's waiting on you, what's first tomorrow.",checked:a.evening.on,onChange:h=>u({...a,evening:{...a.evening,on:h}})}),l("span",{className:"text-sm",children:"at"}),l(le,{type:"time",className:"w-32",value:a.evening.at,onChange:h=>u({...a,evening:{...a.evening,at:h.target.value}})})]}),m("section",{className:"flex flex-wrap items-center gap-3 rounded-md border p-3",children:[l(sn,{label:"Weekly review",hint:"The week's outcomes, what stalled, next week's first things.",checked:a.weekly.on,onChange:h=>u({...a,weekly:{...a.weekly,on:h}})}),l("span",{className:"text-sm",children:"on"}),l("select",{className:"h-9 rounded-md border border-input bg-background px-2 text-sm",value:a.weekly.day,onChange:h=>u({...a,weekly:{...a.weekly,day:h.target.value}}),children:zO.map(([h,g])=>l("option",{value:h,children:g},h))}),l("span",{className:"text-sm",children:"at"}),l(le,{type:"time",className:"w-32",value:a.weekly.at,onChange:h=>u({...a,weekly:{...a.weekly,at:h.target.value}})})]})]}),l(Qu,{settings:e,onBack:i,onSkip:s,busy:p,problem:d,onContinue:()=>c({touchpoints:a})})]})}function tN({which:e,label:t,hint:n,stored:r,rpc:o,refetch:s}){let[i,a]=v(""),[u,c]=v(null),[d,p]=v(null),[f,h]=v(!1),g=b=>{p(null),o.call("welcome.secret",{which:e,value:b}).then(_=>{c(_.line),h((_.handover??[]).some(w=>w.state==="failed")),a(""),s()},_=>p(Ms(_)))},x=()=>{p(null),o.call("welcome.handover",null).then(b=>{c(b.lines.join(" ")),h(b.handover.some(_=>_.state==="failed"))},b=>p(Ms(b)))};return m("div",{className:"flex flex-col gap-1 rounded-md border p-3 text-sm",children:[m("div",{className:"flex items-center gap-2",children:[l("span",{className:"font-medium",children:t}),l("span",{className:V("text-xs",r?"text-muted-foreground":"text-destructive"),children:r?"stored":"not set"})]}),l("span",{className:"text-xs text-muted-foreground",children:n}),m("div",{className:"flex items-center gap-2",children:[l(le,{type:"password",className:"max-w-md",placeholder:r?"Paste a new one to replace it":"Paste it here",value:i,onChange:b=>a(b.target.value)}),l(R,{size:"sm",variant:"secondary",disabled:!i.trim(),onClick:()=>g(i),children:"Store"}),r&&l(R,{size:"sm",variant:"ghost",onClick:()=>g(null),children:"Clear"})]}),d?l("span",{className:"text-xs text-destructive",children:d}):u&&l("span",{className:V("text-xs",f?"text-destructive":"text-muted-foreground"),children:u}),f&&l("div",{children:l(R,{size:"sm",variant:"secondary",onClick:x,children:"Try again"})})]})}function BO({state:e,rpc:t,refetch:n,onDone:r,onBack:o}){let[s,i]=v(null),[a,u]=v(!1),c=()=>{u(!0),i(null),t.call("welcome.finish",null).then(()=>{u(!1),n(),r()},d=>{i(Ms(d)),u(!1)})};return m(he,{children:[m("div",{className:"flex flex-col gap-3",children:[l(tN,{which:"claude",label:"Claude Code key",hint:"What your moonlet uses to sign in to Claude on its machines. Run claude setup-token on your computer and paste what it prints here.",stored:e.secrets.claude,rpc:t,refetch:n}),l(tN,{which:"onepassword",label:"1Password key (optional)",hint:"Only if your moonlet's own logins live in 1Password: a key for a 1Password service account that can read only a vault named Orbit. Your moonlet's machine uses it to fetch those logins; your moonlet never sees it.",stored:e.secrets.onepassword,rpc:t,refetch:n}),l("p",{className:"text-xs text-muted-foreground",children:"Continuing tells your moonlet, in its conversation, what you saved and what you skipped. With no conversation yet, it's told once its conversation starts."})]}),l(Qu,{onBack:o,onSkip:c,busy:a,problem:s,label:"Continue",onContinue:c}),s&&l("div",{className:"mt-2 flex justify-end",children:l(R,{variant:"ghost",onClick:r,children:"Continue anyway"})})]})}function ju(e){return function({onContinue:n,onBack:r}){let{rpc:o,state:s,error:i,refetch:a}=Zm();return i?m("div",{className:"flex flex-col items-start gap-3 text-sm",children:[l("p",{role:"alert",className:"text-destructive",children:i}),l(R,{onClick:n,children:"Continue"})]}):s?l(e,{state:s,rpc:o,refetch:a,onDone:n,onSkip:n,onBack:r}):l("p",{className:"text-sm text-muted-foreground",children:"Loading\u2026"})}}var rN={you:ju(XO),reach:ju(jm),touchpoints:ju(Qm),"sign-ins":ju(BO)};function oN(){let{rpc:e,state:t,error:n,refetch:r}=Zm(),[o,s]=v("");if(n)return l("p",{role:"alert",children:n});if(!t)return l("p",{className:"text-sm text-muted-foreground",children:"Loading\u2026"});let i={state:t,rpc:e,refetch:r,onDone:()=>s("Saved."),onSkip:()=>{},onBack:null,settings:!0};return m("div",{className:"space-y-10",children:[l(ct,{title:"How it reaches you",description:"Where it puts what's waiting on you, and when it stays quiet.",children:l("section",{"aria-label":"How it reaches you",children:l(jm,{...i})})}),l(ct,{title:"Daily rhythm",description:"Check-ins it sends you. Times are in your time zone.",children:l("section",{"aria-label":"Daily rhythm",children:l(Qm,{...i})})}),o&&l("p",{role:"status",className:"text-xs text-muted-foreground",children:o})]})}function sN(){let e=J(),t=q(async()=>({kinds:await e.call("userland.kinds",null),artifacts:await e.call("userland.list",{})}),[e]),[n,r]=v(null),[o,s]=v(null),i=G(!1),[a,u]=v(!1),[c,d]=v(null),[p,f]=v(""),h=q(()=>{t().then(x=>{r(x),s(null)},x=>s(x instanceof Error?x.message:String(x)))},[t]);M(()=>{h();let x=setInterval(()=>{i.current||h()},3e3);return()=>clearInterval(x)},[h]);let g=async x=>{if(!i.current){i.current=!0,u(!0),s(null);try{await x(),f("Saved. Machine delivery may still be waiting."),d(null),r(await t())}catch(b){s(b instanceof Error?b.message:String(b))}finally{i.current=!1,u(!1)}}};return m(ct,{title:"What it taught itself",description:"Tools and notes it saved to help it work.",children:[m("div",{className:"flex flex-col divide-y divide-border text-sm",children:[o&&l("p",{role:"alert",className:"pb-2.5 text-destructive",children:o}),!n&&l("p",{className:"text-muted-foreground",children:"Loading\u2026"}),n?.kinds.map(x=>m("div",{className:"flex flex-wrap items-center gap-3 py-2.5 first:pt-0 last:pb-0",children:[m("span",{className:"flex-1",children:[x.title,x.waiting?" \xB7 Waiting for delivery":""]}),m(R,{disabled:a,size:"sm",onClick:()=>{g(()=>e.call("userland.setKind",{kind:x.id,off:!x.off,why:"Changed in Settings"}))},children:[x.off?"Turn on":"Turn off"," ",x.title]})]},x.id)),n?.artifacts.length===0&&l("p",{className:"py-2.5 text-muted-foreground first:pt-0 last:pb-0",children:"No saved items."}),n?.artifacts.map(x=>{let b=`${x.kind}/${x.name}`,_=x.switches.some(w=>w.holder==="owner");return m("div",{className:"flex flex-wrap items-center gap-2 py-2.5 first:pt-0 last:pb-0",children:[m("span",{className:"flex-1",children:[b," \xB7 ",x.state,x.kindOff?" \xB7 Kind turned off":""]}),m(R,{disabled:a,size:"sm",onClick:()=>{g(()=>_?e.call("userland.enable",{artifact:b,holder:"owner"}):e.call("userland.disable",{artifact:b,why:"Turned off in Settings"}))},children:[_?"Turn on":"Turn off"," ",x.name]}),x.retiredAt===null?m(R,{disabled:a,size:"sm",variant:"secondary",onClick:()=>{g(()=>e.call("userland.retire",{artifact:b,why:"Retired in Settings"}))},children:["Retire ",x.name]}):m(R,{disabled:a,size:"sm",variant:"secondary",onClick:()=>d(b),children:["Delete ",x.name,"\u2026"]}),x.switches.map(w=>m("span",{className:"w-full text-xs text-muted-foreground",children:[w.holder==="breaker"?"Automatic pause":w.holder==="orbit"?"Assistant pause":"Your pause",": ",w.why]},w.holder)),c===b&&m("div",{className:"flex flex-wrap items-center gap-2",children:[l("span",{children:"Delete this item and its saved versions? This cannot be undone."}),l(R,{disabled:a,size:"sm",variant:"destructive",onClick:()=>{g(()=>e.call("userland.purge",{artifact:b}))},children:"Delete permanently"}),l(R,{size:"sm",variant:"ghost",onClick:()=>d(null),children:"Cancel"})]})]},b)})]}),p&&l("p",{role:"status",className:"mt-2 text-xs text-muted-foreground",children:p})]})}function iN(){let{rpc:e,state:t,error:n,refetch:r}=Os(),[o,s]=v(null),[i,a]=v(null),[u,c]=v(!1);if(n)return l("p",{className:"text-sm text-destructive",children:n});if(!t)return l("p",{className:"text-sm text-muted-foreground",children:"Loading\u2026"});let d=t.history.prefs,p=f=>a(f instanceof Error?f.message:String(f));return m("div",{className:"space-y-10",children:[i&&l("p",{role:"status",className:"text-xs text-muted-foreground",children:i}),l(ct,{title:"Changes",description:"Every saved version of its profile, personality and models, newest first, by you or by it.",children:d.length===0?l("p",{className:"text-sm text-muted-foreground",children:"No changes yet."}):l("ul",{className:"divide-y divide-border",children:d.map(f=>m("li",{className:"flex flex-col gap-2 py-2.5 text-sm first:pt-0 last:pb-0",children:[m("div",{className:"flex items-center gap-3",children:[l("span",{className:"w-44 shrink-0 text-xs tabular-nums text-muted-foreground",children:new Date(f.at).toLocaleString()}),l("span",{className:"min-w-0 flex-1 truncate text-foreground",children:f.by}),l(R,{size:"sm",variant:"ghost",onClick:()=>o?.id===f.id?s(null):void e.call("config.historyText",{id:f.id}).then(h=>s({id:f.id,text:h.text}),p),children:o?.id===f.id?"Hide":"View"})]}),o?.id===f.id&&l("pre",{className:"max-h-80 overflow-auto rounded-md border border-border bg-muted/30 p-3 text-xs whitespace-pre-wrap",children:o.text})]},f.id))})}),l(sN,{}),l(ct,{title:"Copy or start over",children:m("div",{className:"space-y-5",children:[l(Ni,{label:"Export or import",description:"Its profile, personality and models as one prefs.toml file.",children:m("div",{className:"flex items-center gap-2",children:[l(R,{size:"sm",variant:"outline",onClick:()=>{e.call("config.exportPrefs",null).then(f=>XE("prefs.toml",f.text),p)},children:"Export"}),l(R,{size:"sm",variant:"outline",onClick:()=>BE(f=>{e.call("config.importPrefs",{text:f,base:t.prefsBase}).then(()=>{a("Imported and saved."),r()},p)}),children:"Import\u2026"})]})}),l(Ni,{label:"Reset personality",description:"Tone and standing instructions back to a new install's. The profile and models stay, and today's versions stay in Changes.",children:u?m("div",{className:"flex items-center gap-2",children:[l(R,{size:"sm",variant:"destructive",onClick:()=>{e.call("config.resetPrefs",{base:t.prefsBase}).then(()=>{c(!1),a("The tone and standing instructions are back to the defaults."),r()},f=>{c(!1),p(f)})},children:"Reset"}),l(R,{size:"sm",variant:"ghost",onClick:()=>c(!1),children:"Cancel"})]}):l(R,{size:"sm",variant:"outline",onClick:()=>c(!0),children:"Reset\u2026"})})]})})]})}function aN(){let e=Ie(),t=G(0),n=G(!1),r=G(!1),o=J(),[s,i]=v(null),[a,u]=v(!1),[c,d]=v(null),p=q(()=>{r.current=!0;let h=++t.current,g=!0;return o.call("events.state",null).then(x=>{g&&h===t.current&&(i(x),d(null))},x=>{g&&h===t.current&&(i(null),d(x instanceof Error?x.message:String(x)))}).finally(()=>{r.current=!1}),()=>{g=!1}},[o]);M(()=>{let h=p(),g=setInterval(()=>{!n.current&&!r.current&&(h(),h=p())},3e3);return()=>{h(),clearInterval(g)}},[p]);let f=a||s?.pending===!0;return m("section",{className:"flex flex-col gap-2","aria-label":"Event service",children:[m("div",{className:"flex items-center justify-between gap-4",children:[l("label",{id:"event-service-label",htmlFor:"event-service-switch",className:"text-sm font-medium",children:"Event service"}),l("button",{id:"event-service-switch",type:"button",role:"switch","aria-labelledby":"event-service-label","aria-describedby":"event-service-status","aria-checked":s?.active??!1,disabled:!s||f,className:"relative h-6 w-11 shrink-0 rounded-full border bg-muted transition-colors aria-checked:bg-primary disabled:cursor-wait disabled:opacity-60",onClick:async()=>{if(!(!s||f||n.current)){n.current=!0,t.current++,u(!0),d(null);try{i(await o.call("events.switch",{active:!s.active}))}catch(h){d(h instanceof Error?h.message:String(h))}finally{n.current=!1,u(!1)}}},children:l("span",{className:`absolute top-0.5 h-4 w-4 rounded-full bg-background shadow transition-transform ${s?.active?"left-0.5 translate-x-5":"left-0.5"}`})})]}),l("p",{className:"text-sm text-muted-foreground",children:"Runs mail, notices and routine work on the station. Changing it asks for your approval."}),l("p",{id:"event-service-status",role:"status",className:"text-sm",children:f?"Waiting for your approval":s?`${s.active?"Running":"Stopped"} on the station`:"Reading station\u2026"}),s?.pending&&s.thread&&l("button",{type:"button",className:"text-left text-sm underline",onClick:()=>e.toThread(s.thread),children:"Open approval question"}),c&&l("p",{role:"alert",className:"text-sm text-destructive",children:c}),!c&&s?.message&&!f&&l("p",{className:"text-sm text-muted-foreground",children:s.message})]})}function lN(){let e=J(),[t,n]=v(!1),[r,o]=v(null);return m("section",{className:"flex flex-col gap-1 text-sm","aria-label":"First run",children:[l("p",{className:"text-muted-foreground",children:"Go through setup again, with your saved answers filled in. Each answer still saves where it lives here, and your moonlet's name and identity stay as they are."}),l("div",{children:l("button",{type:"button",className:"underline disabled:opacity-60",disabled:t,onClick:()=>{n(!0),o(null),e.call("welcome.reopen",null).then(()=>n(!1),s=>{o(s instanceof Error?s.message:String(s)),n(!1)})},children:t?"Opening setup\u2026":"Set up again"})}),r&&l("p",{role:"alert",className:"text-destructive",children:r})]})}var cN=["s3","gcs","azureblob","b2","drive","dropbox","onedrive","box","webdav","sftp","ftp","swift"];var UO={type:"s3",path:"",options:"",item:"",recipient:""};function HO(e){return e.match(/.{1,4}/g)?.join(" ")??e}function VO(e){let t={};for(let[n,r]of e.split(`
146
+ `).entries()){let o=r.trim();if(!o)continue;let s=o.match(/^([^=\s]+)\s*=\s*(.*)$/);if(!s)throw new Error(`Store settings line ${n+1} needs the form name = value.`);t[s[1]]=s[2]}return t}function Oa({label:e,help:t,children:n}){let r=Ci(),o=`${r}-help`;return m("div",{className:"flex flex-col gap-1",children:[l("label",{htmlFor:r,className:"font-medium",children:e}),n(t?{id:r,"aria-describedby":o}:{id:r}),t&&l("p",{id:o,className:"text-xs text-muted-foreground",children:t})]})}function ZO(e){return e?{type:e.type,path:e.path,options:Object.entries(e.options).map(([t,n])=>`${t} = ${n}`).join(`
147
+ `),item:e.item??"",recipient:e.recipient}:UO}function uN(){let e=J(),[t,n]=v(null),[r,o]=v(null),[s,i]=v(null),[a,u]=v(!1),[c,d]=v(null),[p,f]=v(null),h=q(()=>{e.call("permissions.policy",null).then(b=>{n({base:b.base,backup:b.backup}),o(null)},b=>o(b instanceof Error?b.message:String(b)))},[e]);M(h,[h]),ke("config",h);let g=async(b,_,w)=>{u(!0),f(null),d(null);try{await e.call("permissions.edit",{base:b,section:"backup",value:_}),d(w),i(null),h()}catch(T){f(T instanceof Error?T.message:String(T))}finally{u(!1)}},x=t?.backup??null;return m("div",{className:"flex max-w-xl flex-col gap-3 text-sm",children:[l("p",{children:"Optional. Every night at 3:30, each prepared machine encrypts a copy of the assistant's files (OrbitData) and its deploy record to your OpenPGP key, then copies it to a storage location you own. Only you can open a copy, with the secret part of that key on your own computer. Backup stays off until you set a store."}),l("p",{role:"status",children:r?"Backup status is unavailable.":t?x?`On: nightly to ${x.type}: ${x.path}.`:"Off. No store set.":"Loading backup status\u2026"}),x&&m("dl",{className:"grid grid-cols-[max-content_1fr] gap-x-3 gap-y-1",children:[l("dt",{className:"text-muted-foreground",children:"Encrypted to"}),l("dd",{className:"break-all font-mono text-xs",children:x.fingerprint?HO(x.fingerprint):"a key this page can't read; check it with gpg --show-keys"}),l("dt",{className:"text-muted-foreground",children:"Credential"}),l("dd",{children:x.item?`vault item \u201C${x.item}\u201D (its contents are never shown)`:"no vault item named"})]}),t&&!s&&m("div",{className:"flex flex-wrap gap-2",children:[l(R,{variant:"secondary",disabled:a,onClick:()=>i({...ZO(x),base:t.base}),children:x?"Change store":"Set up backup"}),x&&l(R,{variant:"secondary",disabled:a,onClick:()=>g(t.base,null,"Backup turned off. Review and apply sends it to machines."),children:"Turn off backup"})]}),s&&m("form",{className:"flex flex-col gap-3 rounded-md border p-3",onSubmit:b=>{b.preventDefault();let _;try{_=VO(s.options)}catch(y){f(y instanceof Error?y.message:String(y));return}let w=s.item.trim(),T={type:s.type,path:s.path.trim(),options:_,recipient:`${s.recipient.trim()}
148
+ `,...w?{item:w}:{}};g(s.base,T,"Backup saved. Review and apply sends it to machines.")},children:[l(Oa,{label:"Store type",children:b=>l("select",{...b,className:"h-9 rounded-md border border-input bg-background px-2 text-sm",value:s.type,onChange:_=>i({...s,type:_.target.value}),children:cN.map(_=>l("option",{value:_,children:_},_))})}),l(Oa,{label:"Folder in the store",children:b=>l(le,{...b,required:!0,value:s.path,placeholder:"bucket/moonlet-backups",onChange:_=>i({...s,path:_.target.value})})}),l(Oa,{label:"Store settings",help:"rclone settings, one name = value per line. No keys or passwords here.",children:b=>l("textarea",{...b,className:"h-20 w-full rounded-md border bg-background p-2 font-mono text-xs",value:s.options,placeholder:`provider = AWS
149
+ region = us-west-2`,onChange:_=>i({...s,options:_.target.value})})}),l(Oa,{label:"Credential vault item",help:"The name of the vault item that holds the store's write-only credential. Its fields become rclone settings on the machine when the backup runs. Only the name is saved here.",children:b=>l(le,{...b,value:s.item,placeholder:"Backup writer",onChange:_=>i({...s,item:_.target.value})})}),l(Oa,{label:"Your OpenPGP key",help:"Paste the output of gpg --armor --export you@example.com: the part you can share. The secret part stays on your own computer.",children:b=>l("textarea",{...b,required:!0,className:"h-28 w-full rounded-md border bg-background p-2 font-mono text-xs",value:s.recipient,onChange:_=>i({...s,recipient:_.target.value})})}),m("div",{className:"flex flex-wrap gap-2",children:[l(R,{type:"submit",disabled:a,children:"Save backup"}),l(R,{type:"button",variant:"secondary",disabled:a,onClick:()=>i(null),children:"Cancel"})]})]}),m("p",{className:"text-muted-foreground",children:["Saving changes the policy only. Settings \u2192 Permissions \u2192 Review and apply sends it to machines with the usual approval. To restore, download a copy from your store and, on your own machine, run ",l("code",{children:"gpg --decrypt <file> | tar -xzf -"}),"."]}),c&&l("p",{role:"status",children:c}),(r||p)&&l("p",{role:"alert",className:"text-destructive",children:p||r})]})}function wn(){let e=J(),t=q(()=>e.call("welcome.state",null),[e]),[n,r]=v(null),[o,s]=v(null),i=q(()=>{t().then(a=>{r(a),s(null)},a=>s(a instanceof Error?a.message:String(a)))},[t]);return M(i,[i]),ke("config",i),{rpc:e,state:n,error:o,refetch:i}}function dN(){let{rpc:e,state:t,error:n,refetch:r}=wn(),[o,s]=v(!1),[i,a]=v(null),[u,c]=v(null);return m("div",{className:"flex max-w-xl flex-col gap-3 text-sm",children:[l("p",{children:"Optional. Paste a private .ics link above to include upcoming events in calendar checks. In Google Calendar, use the calendar's Secret address in iCal format. In Proton Calendar, share by link with full details. Anyone with the link can read the calendar; keep it private."}),l("p",{children:"The link stays in protected storage on your Moonlet server. Stations receive upcoming events, never the link. Saving a link does not confirm that the calendar is reachable."}),l("p",{role:"status",children:t?t.secrets.calendar?"Calendar link saved.":"No calendar set up. Add a private link above when you want to use it.":"Loading calendar status\u2026"}),t?.secrets.calendar&&l("p",{className:"text-muted-foreground",children:"Removing the link or refreshing setup resends saved contacts and calendar events to machines enabled for assistant work. Removing the link sends the setup without calendar events."}),t?.secrets.calendar&&l(R,{variant:"secondary",disabled:o,onClick:async()=>{s(!0),c(null);try{let d=await e.call("welcome.secret",{which:"calendar",value:null});a(d.line),r()}catch(d){c(d instanceof Error?d.message:String(d))}finally{s(!1)}},children:"Remove calendar link"}),t&&(t.secrets.calendar||i)&&l(R,{variant:"secondary",disabled:o,onClick:async()=>{s(!0),c(null);try{let d=await e.call("welcome.handover",null);a(d.lines.join(" "))}catch(d){c(d instanceof Error?d.message:String(d))}finally{s(!1)}},children:"Refresh contacts and calendar on machines"}),i&&l("p",{role:"status",children:i}),(n||u)&&l("p",{role:"alert",className:"text-destructive",children:u||n})]})}var re={};un(re,{$brand:()=>ug,$input:()=>Lx,$output:()=>Ox,INVALID:()=>kt,NEVER:()=>cg,TimePrecision:()=>Zx,ZodAny:()=>Py,ZodArray:()=>Dy,ZodBase64:()=>Zp,ZodBase64URL:()=>Wp,ZodBigInt:()=>bi,ZodBigIntFormat:()=>Gp,ZodBoolean:()=>xi,ZodCIDRv4:()=>Hp,ZodCIDRv6:()=>Vp,ZodCUID:()=>Dp,ZodCUID2:()=>Fp,ZodCatch:()=>o_,ZodCodec:()=>Al,ZodCompileAsyncError:()=>ln,ZodCompileUnsupportedError:()=>Se,ZodCreditCard:()=>Ey,ZodCustom:()=>Cl,ZodCustomStringFormat:()=>Co,ZodDate:()=>vl,ZodDefault:()=>qy,ZodDiscriminatedUnion:()=>zy,ZodE164:()=>jp,ZodEmail:()=>Pp,ZodEmoji:()=>Lp,ZodEnum:()=>hi,ZodError:()=>n3,ZodExactOptional:()=>ef,ZodFile:()=>jy,ZodFirstPartyTypeKind:()=>b_,ZodFunction:()=>h_,ZodGUID:()=>Op,ZodIBAN:()=>Ny,ZodIPv4:()=>Bp,ZodIPv6:()=>Up,ZodISODate:()=>Er,ZodISODateTime:()=>Sr,ZodISODuration:()=>Ar,ZodISOTime:()=>Nr,ZodInstanceOf:()=>x_,ZodIntersection:()=>Ky,ZodIssueCode:()=>s3,ZodJWT:()=>Qp,ZodKSUID:()=>Xp,ZodLazy:()=>d_,ZodLiteral:()=>Wy,ZodMAC:()=>Sy,ZodMap:()=>Vy,ZodNaN:()=>i_,ZodNanoID:()=>Mp,ZodNever:()=>Ly,ZodNonOptional:()=>tf,ZodNull:()=>$y,ZodNullable:()=>Yy,ZodNumber:()=>gi,ZodNumberFormat:()=>To,ZodObject:()=>kl,ZodOptional:()=>El,ZodPipe:()=>Nl,ZodPrefault:()=>e_,ZodPreprocess:()=>a_,ZodPromise:()=>f_,ZodReadonly:()=>l_,ZodRealError:()=>Ot,ZodRecord:()=>fi,ZodSet:()=>Zy,ZodString:()=>mi,ZodStringFormat:()=>Le,ZodSuccess:()=>r_,ZodSymbol:()=>Ty,ZodTemplateLiteral:()=>u_,ZodTransform:()=>Qy,ZodTuple:()=>By,ZodType:()=>ye,ZodULID:()=>zp,ZodURL:()=>_l,ZodUUID:()=>Nn,ZodUndefined:()=>Ry,ZodUnion:()=>Sl,ZodUnknown:()=>Oy,ZodVoid:()=>My,ZodXID:()=>Kp,ZodXor:()=>Fy,_ZodString:()=>Ip,_default:()=>Jy,_function:()=>LC,any:()=>pC,array:()=>wl,base64:()=>ZA,base64url:()=>WA,bigint:()=>aC,boolean:()=>Cy,catch:()=>s_,check:()=>MC,cidrv4:()=>HA,cidrv6:()=>VA,clone:()=>Te,codec:()=>$C,coerce:()=>__,compile:()=>zx,config:()=>He,core:()=>jn,creditCard:()=>QA,cuid:()=>MA,cuid2:()=>DA,currencyCode:()=>tC,custom:()=>DC,date:()=>hC,decode:()=>xy,decodeAsync:()=>yy,deepPartial:()=>GC,describe:()=>FC,discriminatedUnion:()=>_C,e164:()=>jA,email:()=>NA,emoji:()=>OA,encode:()=>gy,encodeAsync:()=>by,endsWith:()=>ni,enum:()=>qp,exactOptional:()=>Gy,file:()=>AC,flattenError:()=>Ha,float32:()=>rC,float64:()=>oC,formatError:()=>Va,fromJSONSchema:()=>jC,function:()=>LC,getDiscriminatedOption:()=>lx,getErrorMap:()=>a3,globalRegistry:()=>at,gt:()=>Sn,gte:()=>Ft,guid:()=>AA,hash:()=>nC,hex:()=>eC,hostname:()=>JA,httpUrl:()=>PA,iban:()=>GA,includes:()=>ei,input:()=>qC,instanceof:()=>KC,int:()=>Rp,int32:()=>sC,int64:()=>lC,intersection:()=>Xy,invertCodec:()=>IC,ipv4:()=>XA,ipv6:()=>UA,iso:()=>Tl,json:()=>BC,jwt:()=>YA,keyof:()=>mC,ksuid:()=>KA,lazy:()=>p_,length:()=>ko,literal:()=>NC,locales:()=>ul,looseObject:()=>bC,looseRecord:()=>wC,lowercase:()=>qs,lt:()=>kn,lte:()=>Dt,mac:()=>BA,map:()=>kC,maxLength:()=>wo,maxSize:()=>_r,memoizer:()=>cl,meta:()=>zC,mime:()=>oi,minLength:()=>Wn,minSize:()=>En,multipleOf:()=>yr,nan:()=>RC,nanoid:()=>LA,nativeEnum:()=>EC,negative:()=>yp,never:()=>Yp,nonnegative:()=>vp,nonoptional:()=>n_,nonpositive:()=>_p,normalize:()=>si,null:()=>Iy,nullable:()=>yl,nullish:()=>CC,number:()=>Ay,object:()=>gC,optional:()=>No,output:()=>JC,overwrite:()=>cn,parse:()=>py,parseAsync:()=>fy,partialRecord:()=>vC,pipe:()=>$p,positive:()=>bp,prefault:()=>t_,preprocess:()=>UC,prettifyError:()=>mg,promise:()=>OC,properties:()=>ri,property:()=>wp,readonly:()=>c_,record:()=>Hy,refine:()=>m_,regex:()=>Ys,regexes:()=>Wt,registry:()=>Wd,safeDecode:()=>vy,safeDecodeAsync:()=>ky,safeEncode:()=>_y,safeEncodeAsync:()=>wy,safeParse:()=>hy,safeParseAsync:()=>my,set:()=>SC,setErrorMap:()=>i3,size:()=>vo,slugify:()=>ci,startsWith:()=>ti,strictObject:()=>xC,string:()=>bl,stringFormat:()=>qA,stringbool:()=>XC,success:()=>TC,superRefine:()=>g_,symbol:()=>uC,templateLiteral:()=>PC,toJSONSchema:()=>Np,toLowerCase:()=>ai,toUpperCase:()=>li,toZod:()=>La,transform:()=>Jp,treeifyError:()=>hg,trim:()=>ii,tuple:()=>Uy,uint32:()=>iC,uint64:()=>cC,ulid:()=>FA,undefined:()=>dC,union:()=>yi,unknown:()=>Eo,uppercase:()=>Js,url:()=>IA,util:()=>oe,uuid:()=>CA,uuidv4:()=>TA,uuidv6:()=>RA,uuidv7:()=>$A,validate:()=>Za,validateAsync:()=>Wa,void:()=>fC,withParser:()=>jd,xid:()=>zA,xor:()=>yC});var jn={};un(jn,{$ZodAny:()=>ex,$ZodArray:()=>sx,$ZodAsyncError:()=>It,$ZodBase64:()=>B0,$ZodBase64URL:()=>U0,$ZodBigInt:()=>Ld,$ZodBigIntFormat:()=>G0,$ZodBoolean:()=>rl,$ZodCIDRv4:()=>K0,$ZodCIDRv6:()=>X0,$ZodCUID:()=>C0,$ZodCUID2:()=>T0,$ZodCatch:()=>Sx,$ZodCheck:()=>Fe,$ZodCheckBigIntFormat:()=>t0,$ZodCheckEndsWith:()=>f0,$ZodCheckGreaterThan:()=>yd,$ZodCheckIncludes:()=>d0,$ZodCheckLengthEquals:()=>a0,$ZodCheckLessThan:()=>bd,$ZodCheckLowerCase:()=>c0,$ZodCheckMaxLength:()=>s0,$ZodCheckMaxSize:()=>n0,$ZodCheckMimeType:()=>g0,$ZodCheckMinLength:()=>i0,$ZodCheckMinSize:()=>r0,$ZodCheckMultipleOf:()=>Jg,$ZodCheckNumberFormat:()=>e0,$ZodCheckOverwrite:()=>x0,$ZodCheckProperties:()=>m0,$ZodCheckProperty:()=>h0,$ZodCheckRegex:()=>l0,$ZodCheckSizeEquals:()=>o0,$ZodCheckStartsWith:()=>p0,$ZodCheckStringFormat:()=>Ws,$ZodCheckUpperCase:()=>u0,$ZodCodec:()=>sl,$ZodCreditCard:()=>V0,$ZodCustom:()=>$x,$ZodCustomStringFormat:()=>j0,$ZodCyclicError:()=>Bd,$ZodDate:()=>ox,$ZodDefault:()=>_x,$ZodDiscriminatedUnion:()=>cx,$ZodE164:()=>H0,$ZodEmail:()=>w0,$ZodEmoji:()=>N0,$ZodEncodeError:()=>br,$ZodEnum:()=>hx,$ZodError:()=>fg,$ZodExactOptional:()=>bx,$ZodFile:()=>gx,$ZodFunction:()=>Tx,$ZodGUID:()=>_0,$ZodIBAN:()=>Z0,$ZodIPv4:()=>D0,$ZodIPv6:()=>F0,$ZodISODate:()=>O0,$ZodISODateTime:()=>P0,$ZodISODuration:()=>M0,$ZodISOTime:()=>L0,$ZodIntersection:()=>ux,$ZodJWT:()=>W0,$ZodKSUID:()=>I0,$ZodLazy:()=>il,$ZodLiteral:()=>mx,$ZodMAC:()=>z0,$ZodMap:()=>px,$ZodNaN:()=>Ex,$ZodNanoID:()=>A0,$ZodNever:()=>nx,$ZodNonOptional:()=>wx,$ZodNull:()=>J0,$ZodNullable:()=>yx,$ZodNumber:()=>Od,$ZodNumberFormat:()=>Q0,$ZodObject:()=>ZN,$ZodObjectJIT:()=>ix,$ZodOptional:()=>Dd,$ZodPipe:()=>Fd,$ZodPrefault:()=>vx,$ZodPreprocess:()=>Nx,$ZodPromise:()=>Rx,$ZodReadonly:()=>Ax,$ZodRealError:()=>Pt,$ZodRecord:()=>dx,$ZodRegistry:()=>Zd,$ZodSet:()=>fx,$ZodString:()=>go,$ZodStringFormat:()=>Re,$ZodSuccess:()=>kx,$ZodSymbol:()=>Y0,$ZodTemplateLiteral:()=>Cx,$ZodTransform:()=>xx,$ZodTuple:()=>Md,$ZodType:()=>me,$ZodULID:()=>R0,$ZodURL:()=>E0,$ZodUUID:()=>v0,$ZodUndefined:()=>q0,$ZodUnion:()=>ol,$ZodUnknown:()=>tx,$ZodVoid:()=>rx,$ZodXID:()=>$0,$ZodXor:()=>ax,$brand:()=>ug,$constructor:()=>I,$input:()=>Lx,$output:()=>Ox,Doc:()=>mo,INVALID:()=>kt,JSONSchema:()=>kA,JSONSchemaGenerator:()=>Ap,NEVER:()=>cg,TimePrecision:()=>Zx,URL_BAD_FORMAT:()=>k0,URL_UNPARSEABLE:()=>qa,ZodCompileAsyncError:()=>ln,ZodCompileUnsupportedError:()=>Se,_any:()=>cb,_array:()=>gb,_base64:()=>hp,_base64url:()=>mp,_bigint:()=>nb,_boolean:()=>eb,_catch:()=>HD,_check:()=>aA,_cidrv4:()=>pp,_cidrv6:()=>fp,_coercedBigint:()=>rb,_coercedBoolean:()=>tb,_coercedDate:()=>hb,_coercedNumber:()=>jx,_coercedString:()=>Bx,_creditCard:()=>Hx,_cuid:()=>sp,_cuid2:()=>ip,_custom:()=>bb,_date:()=>fb,_decode:()=>ad,_decodeAsync:()=>cd,_default:()=>XD,_discriminatedUnion:()=>TD,_e164:()=>gp,_email:()=>Yd,_emoji:()=>rp,_encode:()=>id,_encodeAsync:()=>ld,_endsWith:()=>ni,_enum:()=>LD,_file:()=>xb,_float32:()=>Gx,_float64:()=>Yx,_gt:()=>Sn,_gte:()=>Ft,_guid:()=>qd,_iban:()=>Vx,_includes:()=>ei,_int:()=>Qx,_int32:()=>qx,_int64:()=>ob,_intersection:()=>RD,_ipv4:()=>up,_ipv6:()=>dp,_isoDate:()=>fl,_isoDateTime:()=>pl,_isoDuration:()=>ml,_isoTime:()=>hl,_jwt:()=>xp,_ksuid:()=>cp,_lazy:()=>jD,_length:()=>ko,_literal:()=>DD,_lowercase:()=>qs,_lt:()=>kn,_lte:()=>Dt,_mac:()=>Ux,_map:()=>PD,_max:()=>Dt,_maxLength:()=>wo,_maxSize:()=>_r,_mime:()=>oi,_min:()=>Ft,_minLength:()=>Wn,_minSize:()=>En,_multipleOf:()=>yr,_nan:()=>mb,_nanoid:()=>op,_nativeEnum:()=>MD,_negative:()=>yp,_never:()=>db,_nonnegative:()=>vp,_nonoptional:()=>BD,_nonpositive:()=>_p,_normalize:()=>si,_null:()=>lb,_nullable:()=>KD,_number:()=>Wx,_optional:()=>zD,_overwrite:()=>cn,_parse:()=>Us,_parseAsync:()=>Hs,_pipe:()=>VD,_positive:()=>bp,_promise:()=>QD,_properties:()=>ri,_property:()=>wp,_readonly:()=>ZD,_record:()=>ID,_refine:()=>yb,_regex:()=>Ys,_safeDecode:()=>dd,_safeDecodeAsync:()=>fd,_safeEncode:()=>ud,_safeEncodeAsync:()=>pd,_safeParse:()=>Vs,_safeParseAsync:()=>Zs,_set:()=>OD,_size:()=>vo,_slugify:()=>ci,_startsWith:()=>ti,_string:()=>Xx,_stringFormat:()=>So,_stringbool:()=>kb,_success:()=>UD,_superRefine:()=>_b,_symbol:()=>ib,_templateLiteral:()=>WD,_toLowerCase:()=>ai,_toUpperCase:()=>li,_transform:()=>FD,_trim:()=>ii,_tuple:()=>$D,_uint32:()=>Jx,_uint64:()=>sb,_ulid:()=>ap,_undefined:()=>ab,_union:()=>AD,_unknown:()=>ub,_uppercase:()=>Js,_url:()=>dl,_uuid:()=>Jd,_uuidv4:()=>ep,_uuidv6:()=>tp,_uuidv7:()=>np,_void:()=>pb,_xid:()=>lp,_xor:()=>CD,base64Charset:()=>Td,base64urlCharset:()=>nl,canParseURL:()=>S0,clone:()=>Te,compile:()=>zx,compileFn:()=>Qd,config:()=>He,createStandardJSONSchemaMethod:()=>ui,createToJSONSchemaMethod:()=>Eb,decode:()=>DL,decodeAsync:()=>zL,describe:()=>vb,encode:()=>ML,encodeAsync:()=>FL,extractDefs:()=>wr,finalize:()=>kr,flattenError:()=>Ha,formatError:()=>Va,getDiscriminatedOption:()=>lx,globalConfig:()=>ot,globalRegistry:()=>at,handleUnrepresentable:()=>et,initializeContext:()=>vr,isBackEdge:()=>Hd,isRecursiveSchema:()=>Ud,isValidBase64:()=>tl,isValidBase64URL:()=>Rd,isValidCIDRv6:()=>Cd,isValidCreditCard:()=>$d,isValidIBAN:()=>Id,isValidIPv6:()=>el,isValidJWT:()=>Pd,locales:()=>ul,memoizer:()=>cl,mergeValues:()=>js,meta:()=>wb,parse:()=>od,parseAsync:()=>sd,parseURLObject:()=>UN,prettifyError:()=>mg,process:()=>$e,processSchema:()=>$e,regexes:()=>Wt,registry:()=>Wd,safeDecode:()=>XL,safeDecodeAsync:()=>UL,safeEncode:()=>KL,safeEncodeAsync:()=>BL,safeParse:()=>$L,safeParseAsync:()=>IL,standardProps:()=>Sd,stripTabAndNewline:()=>Ja,toDotPath:()=>wN,toJSONSchema:()=>Np,toZod:()=>La,treeifyError:()=>hg,urlHostnameOk:()=>Nd,urlProtocolOk:()=>Ad,util:()=>oe,validate:()=>Za,validateAsync:()=>Wa,validateURL:()=>Ed,version:()=>b0,withParser:()=>jd});var oe={};un(oe,{BIGINT_FORMAT_RANGES:()=>Ka,CONSTANT_CATCH:()=>nd,Class:()=>qm,NUMBER_FORMAT_RANGES:()=>za,aborted:()=>wt,allowsEval:()=>tg,assert:()=>YO,assertEqual:()=>WO,assertIs:()=>QO,assertNever:()=>GO,assertNotEqual:()=>jO,assignProp:()=>it,attachSchema:()=>td,base64ToUint8Array:()=>gN,base64urlToUint8Array:()=>gL,cached:()=>Ks,captureStackTrace:()=>qu,cleanEnum:()=>mL,cleanRegex:()=>Vn,clone:()=>Te,cloneDef:()=>eL,codePointLength:()=>fo,constantCatch:()=>ag,createTransparentProxy:()=>iL,defineLazy:()=>Jm,defineLazyInternal:()=>ve,derived:()=>_L,esc:()=>vt,escapeRegex:()=>Zt,explicitlyAborted:()=>og,extend:()=>cL,finalizeIssue:()=>$t,floatSafeRemainder:()=>Ma,getElementAtPath:()=>tL,getEnumValues:()=>Fs,getLengthableOrigin:()=>Ba,getParsedType:()=>sL,getSizableOrigin:()=>Xa,hexToUint8Array:()=>bL,hide:()=>Ua,installLazyProp:()=>SL,isObject:()=>po,isPlainObject:()=>Vt,issue:()=>Bs,joinValues:()=>Gu,jsonStringifyReplacer:()=>zs,members:()=>ig,merge:()=>dL,mergeDefs:()=>an,normalizeParams:()=>W,nullish:()=>Yu,numKeys:()=>oL,objectClone:()=>qO,omit:()=>lL,optionalKeys:()=>rg,own:()=>xr,parsedType:()=>sg,partial:()=>pL,pick:()=>aL,prefixIssues:()=>Rt,primitiveTypes:()=>ng,promiseAllObject:()=>nL,propertyKeyTypes:()=>Fa,randomString:()=>rL,rawShape:()=>Xs,required:()=>fL,safeExtend:()=>uL,shallowClone:()=>Da,slugify:()=>eg,stringifyPrimitive:()=>Ju,toZod:()=>La,uint8ArrayToBase64:()=>xN,uint8ArrayToBase64url:()=>xL,uint8ArrayToHex:()=>yL,unwrapMessage:()=>Ds});function WO(e){return e}function jO(e){return e}function La(){return e=>e}function QO(e){}function GO(e){throw new Error("Unexpected value in exhaustive check")}function YO(e){}function Fs(e){let t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function Gu(e,t="|"){return e.map(n=>Ju(n)).join(t)}function zs(e,t){return typeof t=="bigint"?t.toString():t}var Ym=class{constructor(t){this._getter=t,this._value=void 0}get value(){let t=this._getter;return t!==void 0&&(this._value=t(),this._getter=void 0),this._value}};function Ks(e){return new Ym(e)}function Yu(e){return e==null}function Vn(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Ma(e,t){let n=e/t,r=Math.round(n),o=4*Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<o?0:n-r}var pN=Symbol("evaluating");function Jm(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==pN)return r===void 0&&(r=pN,r=n()),r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function qO(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function it(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Xs(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Hn(e){return Xs(e._zod.def)??e._zod.def.shape}function fN(e,t,n){Object.defineProperty(e,t,{get(){let r=n();return it(this,t,r),r},enumerable:!0,configurable:!0})}function hN(e,t,n){t in e?it(e,t,n):e[t]=n}function uo(e,t,n,r){let o=Hn(t);for(let s of n){let i=Object.getOwnPropertyDescriptor(o,s);i.enumerable&&(i.get?fN(e,s,()=>{let a=t._zod.def.shape[s];return r?r(a,s):a}):hN(e,s,r?r(i.value,s):i.value))}}function JO(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?fN(e,n,()=>t[n]):hN(e,n,r.value))}}function an(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function eL(e){return an(e._zod.def)}function tL(e,t){return t?t.reduce((n,r)=>n?.[r],e):e}function nL(e){let t=Object.keys(e),n=t.map(r=>e[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;s<t.length;s++)o[t[s]]=r[s];return o})}function rL(e=10){let t="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<e;r++)n+=t[Math.floor(Math.random()*t.length)];return n}function vt(e){return JSON.stringify(e)}function eg(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var qu="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function po(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var tg=Ks(()=>{if(ot.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Vt(e){if(po(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(po(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Da(e){return Vt(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function oL(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}var sL=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Fa=new Set(["string","number","symbol"]),ng=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Zt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Te(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function W(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function iL(e){let t;return new Proxy({},{get(n,r,o){return t??(t=e()),Reflect.get(t,r,o)},set(n,r,o,s){return t??(t=e()),Reflect.set(t,r,o,s)},has(n,r){return t??(t=e()),Reflect.has(t,r)},deleteProperty(n,r){return t??(t=e()),Reflect.deleteProperty(t,r)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,r){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,r)},defineProperty(n,r,o){return t??(t=e()),Reflect.defineProperty(t,r,o)}})}function Ju(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function rg(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var za={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ka={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function aL(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s={};return uo(s,e,ed(e,t)),Te(e,an(n,{shape:s,checks:[]}))}function ed(e,t){let n=Hn(e),r=[];for(let o of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,o)?.enumerable)throw new Error(`Unrecognized key: "${String(o)}"`);t[o]&&r.push(o)}return r}function lL(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=new Set(ed(e,t)),i={};return uo(i,e,Reflect.ownKeys(Hn(e)).filter(a=>!s.has(a))),Te(e,an(n,{shape:i,checks:[]}))}function cL(e,t){if(!Vt(t))throw new Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let o=Hn(e);for(let s of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Te(e,an(e._zod.def,{shape:mN(e,t)}))}function mN(e,t){let n={};return uo(n,e,Reflect.ownKeys(Hn(e))),JO(n,t),n}function uL(e,t){if(!Vt(t))throw new Error("Invalid input to safeExtend: expected a plain object");return Te(e,an(e._zod.def,{shape:mN(e,t)}))}function dL(e,t){if(!t?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n={};uo(n,e,Reflect.ownKeys(Hn(e))),uo(n,t,Reflect.ownKeys(Hn(t)));let r=an(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Te(e,r)}function pL(e,t,n,r="partial"){let s=t._zod.def.checks;if(s&&s.length>0)throw new Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(ed(t,n)):void 0,u={};return uo(u,t,Reflect.ownKeys(Hn(t)),e&&((c,d)=>a&&!a.has(d)?c:new e({type:"optional",innerType:c}))),Te(t,an(t._zod.def,{shape:u,checks:[]}))}function fL(e,t,n){let r=n?new Set(ed(t,n)):void 0,o={};return uo(o,t,Reflect.ownKeys(Hn(t)),(s,i)=>r&&!r.has(i)?s:new e({type:"nonoptional",innerType:s})),Te(t,an(t._zod.def,{shape:o}))}function wt(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function og(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Rt(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Ds(e){return typeof e=="string"?e:e?.message}function td(e,t,n){var r;for(let o=t;o<e.length;o++)(r=e[o]).schema??(r.schema=n)}function $t(e,t,n){var r;let o=e.inst?._zod?.traits;o?.has("$ZodType")&&(o.has("$ZodCheck")?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let s=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,i=e.message?e.message:Ds(e.inst?._zod.def?.error?.(e))??Ds(s?.(e))??Ds(t?.error?.(e))??Ds(n.customError?.(e))??Ds(n.localeError?.(e))??"Invalid input",a={};for(let u of Object.keys(e))u==="inst"||u==="schema"||u==="continue"||u==="input"||u==="__proto__"||(a[u]=e[u]);return a.path??(a.path=[]),a.message=i,t?.reportInput&&(a.input=e.input),a}function Xa(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}var hL=/[\uD800-\uDBFF]/;function fo(e){let t=e.length;if(!hL.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320&&(n--,r++);return n}function Ba(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function sg(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function Bs(...e){let[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}function mL(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function gN(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function xN(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function gL(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return gN(t+n)}function xL(e){return xN(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function bL(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=Number.parseInt(t.slice(r,r+2),16);return n}function yL(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var qm=class{constructor(...t){}};function ig(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):vL(e,n,r.value)}}function xr(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function Ua(e,t,n){return xr(e,t,n,!1)}function _L(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return xr(this,n,r(this))},set(o){xr(this,n,o)}})}return t}function vL(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:xr(this,t,n.bind(this))},set(r){xr(this,t,r)}})}function wL(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var Gm,gr=!1,kL={configurable:!0,get(){gr=!0}};function ve(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&Gm!==e._zod){Gm=void 0;return}Gm=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,kL);let o=gr;gr=!1;try{let s=n(this);return gr?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:s}),gr=gr||o,s}catch(s){throw delete this[t],gr=gr||o,s}},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o})}})}function SL(e,t,n,r){let o=wL(e,t);o&&Object.defineProperty(o,t,{configurable:!0,get(){let s={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,s),s.value=n(this),Object.defineProperty(this,t,s),s.value},set(s){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:s})}})}var nd="~constantCatch";function ag(e){let t=()=>e;return t[nd]=!0,t}var bN,cg=Object.freeze({status:"aborted"}),lg={value:void 0,enumerable:!1},yN="captureStackTrace"in Error?Error:null;function EL(e){let t=yN;if(t){let n=t.stackTraceLimit;if(typeof n=="number"){try{t.stackTraceLimit=0}catch{return yN=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function I(e,t,n,r){let o={};function s(f){this.def=f,this.constr=p,this.traits=new Set}s.prototype=o;let i=n,a=i&&new WeakSet;function u(f,h){if(f._zod){if(f._zod.traits.has(e))return}else{lg.value=new s(h);try{Object.defineProperty(f,"_zod",lg)}finally{lg.value=void 0}}if(f._zod.traits.add(e),t(f,h),a){let x=Object.getPrototypeOf(f),b=f._zod.constr.prototype,_=x;for(;_&&_!==b;)_=Object.getPrototypeOf(_);let w=_??x;a.has(w)||(a.add(w),ig(w,i))}let g=p.prototype;for(let x in g)Object.prototype.hasOwnProperty.call(g,x)&&(x in f||(f[x]=g[x].bind(f)))}let c=r?.Parent??Object;class d extends c{}Object.defineProperty(d,"name",{value:e});function p(f){let h=r?.Parent?EL(d):this;u(h,f);let g=h._zod.deferred;if(g){for(let b of g)b();h._zod.deferred=void 0}let x=globalThis.__zod_globalConfig?.postProcessor;return x&&x(h),h}return Object.defineProperty(p,"init",{value:u}),Object.defineProperty(p,Symbol.hasInstance,{value:f=>r?.Parent&&f instanceof r.Parent?!0:f?._zod?.traits?.has(e)}),Object.defineProperty(p,"name",{value:e}),p}var ug=Symbol("zod_brand"),It=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},br=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(bN=globalThis).__zod_globalConfig??(bN.__zod_globalConfig={});var ot=globalThis.__zod_globalConfig;function He(e){return e&&Object.assign(ot,e),ot}function NL(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,zs,2)),e.message}function AL(e){this._zod.message=e}var CL={get:NL,set:AL,enumerable:!0,configurable:!0},pg={value:void 0,enumerable:!1},_N=new WeakSet([Object.prototype,Error.prototype]),vN=(e,t)=>{e.name="$ZodError",pg.value=t,Object.defineProperty(e,"issues",pg),pg.value=void 0,Object.defineProperty(e,"message",CL);let n=Object.getPrototypeOf(e);_N.has(n)||(_N.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let r=()=>this.message;return Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0})}}))},fg=I("$ZodError",vN),Pt=I("$ZodError",vN,void 0,{Parent:Error});function TL(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t==="__proto__"?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function Ha(e,t=n=>n.message){let n={},r=[];for(let o of e.issues)o.path.length>0?TL(n,o.path[0],()=>[]).push(t(o)):r.push(t(o));return{formErrors:r,fieldErrors:n}}function Va(e,t=n=>n.message){let n={_errors:[]},r=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>r({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")r({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")r({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)n._errors.push(t(i));else{let u=n,c=0;for(;c<a.length;){let d=a[c],p=c===a.length-1;if(d==="_errors"){p&&u._errors.push(t(i)),c++;continue}Object.prototype.hasOwnProperty.call(u,d)||Object.defineProperty(u,d,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let f=u[d];p&&f._errors.push(t(i)),u=f,c++}}}};return r(e),n}function hg(e,t=n=>n.message){let n={errors:[]},r=(o,s=[])=>{var i;for(let a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(u=>r({issues:u},[...s,...a.path]));else if(a.code==="invalid_key")r({issues:a.issues},[...s,...a.path]);else if(a.code==="invalid_element")r({issues:a.issues},[...s,...a.path]);else{let u=[...s,...a.path];if(u.length===0){n.errors.push(t(a));continue}let c=n,d=0;for(;d<u.length;){let p=u[d],f=d===u.length-1;typeof p=="string"?(c.properties??(c.properties={}),Object.prototype.hasOwnProperty.call(c.properties,p)||Object.defineProperty(c.properties,p,{value:{errors:[]},enumerable:!0,writable:!0,configurable:!0}),c=c.properties[p]):(c.items??(c.items=[]),(i=c.items)[p]??(i[p]={errors:[]}),c=c.items[p]),f&&c.errors.push(t(a)),d++}}};return r(e),n}function wN(e){let t=[],n=e.map(r=>typeof r=="object"?r.key:r);for(let r of n)typeof r=="number"?t.push(`[${r}]`):typeof r=="symbol"?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}function mg(e){let t=[],n=[...e.issues].sort((r,o)=>(r.path??[]).length-(o.path??[]).length);for(let r of n)t.push(`\u2716 ${r.message}`),r.path?.length&&t.push(` \u2192 at ${wN(r.path)}`);return t.join(`
150
+ `)}function rd(e,t){return{callee:t?.callee??e,Err:t?.Err}}var Us=e=>{let t=(n,r,o,s)=>{let i=o?{...o,async:!1}:{async:!1},a=n._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new It;if(a.issues.length){let u=new(s?.Err??e)(a.issues.map(c=>$t(c,i,He())));throw qu(u,s?.callee??t),u}return a.value};return t},od=Us(Pt),Hs=e=>{let t=async(n,r,o,s)=>{let i=o?{...o,async:!0}:{async:!0},a=n._zod.run({value:r,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let u=new(s?.Err??e)(a.issues.map(c=>$t(c,i,He())));throw qu(u,s?.callee??t),u}return a.value};return t},sd=Hs(Pt),Vs=e=>(t,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new It;return s.issues.length?kN(e,s.issues,o):{success:!0,data:s.value}},$L=Vs(Pt);function kN(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(o=>$t(o,n,He()))),t=void 0,n=void 0),r},set error(o){r=o,t=void 0,n=void 0}}}var Zs=e=>async(t,n,r)=>{let o=r?{...r,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?kN(e,s.issues,o):{success:!0,data:s.value}},IL=Zs(Pt),PL=Symbol.for("zod.compile.invalid"),OL=Symbol.for("zod.compile.fallback"),Za=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==PL)return!0;if(r.definite===!0&&n===void 0)return!1}return LL(e,t,n)});function LL(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=e._zod.bag.fallbackRun,s;if(o?(r[OL]=!0,s=o({value:t,issues:[]},r)):s=e._zod.run({value:t,issues:[]},r),s instanceof Promise)throw new It;return s.issues.length===0}var Wa=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},o=e._zod.run({value:t,issues:[]},r);return o instanceof Promise&&(o=await o),o.issues.length===0},id=e=>{let t=Us(e),n=(r,o,s,i)=>{let a=s?{...s,direction:"backward"}:{direction:"backward"};return t(r,o,a,rd(n,i))};return n},ML=id(Pt),ad=e=>{let t=Us(e),n=(r,o,s,i)=>t(r,o,s,rd(n,i));return n},DL=ad(Pt),ld=e=>{let t=Hs(e),n=async(r,o,s,i)=>{let a=s?{...s,direction:"backward"}:{direction:"backward"};return await t(r,o,a,rd(n,i))};return n},FL=ld(Pt),cd=e=>{let t=Hs(e),n=async(r,o,s,i)=>await t(r,o,s,rd(n,i));return n},zL=cd(Pt),ud=e=>(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Vs(e)(t,n,o)},KL=ud(Pt),dd=e=>(t,n,r)=>Vs(e)(t,n,r),XL=dd(Pt),pd=e=>async(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Zs(e)(t,n,o)},BL=pd(Pt),fd=e=>async(t,n,r)=>Zs(e)(t,n,r),UL=fd(Pt);var Wt={};un(Wt,{anyString:()=>Bg,base64:()=>Pg,base64url:()=>Og,bigint:()=>Hg,boolean:()=>Vg,browserEmail:()=>YL,cidrv4:()=>$g,cidrv6:()=>Ig,creditCard:()=>hd,cuid:()=>xg,cuid2:()=>bg,currencyCode:()=>Fg,date:()=>zg,datetime:()=>Xg,domain:()=>Mg,duration:()=>Sg,e164:()=>Dg,email:()=>Ng,emoji:()=>Ag,extendedDuration:()=>HL,guid:()=>Eg,hex:()=>Gg,hostname:()=>Lg,html5Email:()=>jL,httpProtocol:()=>ja,iban:()=>md,idnEmail:()=>GL,integer:()=>Qa,ipv4:()=>Cg,ipv6:()=>Tg,ksuid:()=>vg,lowercase:()=>jg,mac:()=>Rg,md5_base64:()=>tM,md5_base64url:()=>nM,md5_hex:()=>eM,nanoid:()=>wg,nanoidOfLength:()=>kg,null:()=>Zg,number:()=>Zn,rfc5322Email:()=>QL,sha1_base64:()=>oM,sha1_base64url:()=>sM,sha1_hex:()=>rM,sha256_base64:()=>aM,sha256_base64url:()=>lM,sha256_hex:()=>iM,sha384_base64:()=>uM,sha384_base64url:()=>dM,sha384_hex:()=>cM,sha512_base64:()=>fM,sha512_base64url:()=>hM,sha512_hex:()=>pM,string:()=>Ug,time:()=>Kg,ulid:()=>yg,undefined:()=>Wg,unicodeEmail:()=>SN,uppercase:()=>Qg,uuid:()=>ho,uuid4:()=>VL,uuid6:()=>ZL,uuid7:()=>WL,xid:()=>_g});var xg=/^[cC][0-9a-z]{6,}$/,bg=/^[0-9a-z]+$/,yg=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,_g=/^[0-9a-vA-V]{20}$/,vg=/^[A-Za-z0-9]{27}$/,wg=/^[a-zA-Z0-9_-]{21}$/;function kg(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var Sg=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,HL=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Eg=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ho=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,VL=ho(4),ZL=ho(6),WL=ho(7),Ng=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,jL=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,QL=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,SN=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,GL=SN,YL=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,qL="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function Ag(){return new RegExp(qL,"u")}var Cg=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Tg=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Rg=e=>{let t=Zt(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},$g=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Ig=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Pg=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Og=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,Lg=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,Mg=/^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/,ja=/^https?$/,Dg=/^\+[1-9]\d{6,14}$/,hd=/^\d(?:[ -]?\d){11,18}$/,Fg=/^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/,md=/^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/,EN="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function JL(e){return new RegExp(`^${e}$`)}var zg=JL(EN);function gg(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Kg(e){return new RegExp(`^${gg(e)}$`)}function Xg(e){let t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${gg({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${gg({precision:e.precision})}`:n;return new RegExp(`^${EN}T(?:${r})$`)}var Bg=/^[\s\S]{0,}$/,Ug=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Hg=/^-?\d+n?$/,Qa=/^-?\d+$/,Zn=/^-?\d+(?:\.\d+)?$/,Vg=/^(?:true|false)$/i,Zg=/^null$/i;var Wg=/^undefined$/i;var jg=/^[^A-Z]*$/,Qg=/^[^a-z]*$/,Gg=/^[0-9a-fA-F]*$/;function Ga(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Ya(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var eM=/^[0-9a-fA-F]{32}$/,tM=Ga(22,"=="),nM=Ya(22),rM=/^[0-9a-fA-F]{40}$/,oM=Ga(27,"="),sM=Ya(27),iM=/^[0-9a-fA-F]{64}$/,aM=Ga(43,"="),lM=Ya(43),cM=/^[0-9a-fA-F]{96}$/,uM=Ga(64,""),dM=Ya(64),pM=/^[0-9a-fA-F]{128}$/,fM=Ga(86,"=="),hM=Ya(86);var Fe=I("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Yg=e=>{let t=e.value;return!Yu(t)&&t.size!==void 0},qg=e=>{let t=e.value;return!Yu(t)&&t.length!==void 0},gd={number:"number",bigint:"bigint",object:"date"},bd=I("$ZodCheckLessThan",(e,t)=>{Fe.init(e,t);let n=gd[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:gd[typeof r.value]??n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),yd=I("$ZodCheckGreaterThan",(e,t)=>{Fe.init(e,t);let n=gd[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:gd[typeof r.value]??n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Jg=I("$ZodCheckMultipleOf",(e,t)=>{Fe.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Ma(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),e0=I("$ZodCheckNumberFormat",(e,t)=>{Fe.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[o,s]=za[t.format];e._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),t0=I("$ZodCheckBigIntFormat",(e,t)=>{Fe.init(e,t);let[n,r]=Ka[t.format];e._zod.check=o=>{let s=o.value;s<n&&o.issues.push({origin:"bigint",input:s,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),s>r&&o.issues.push({origin:"bigint",input:s,code:"too_big",maximum:r,inclusive:!0,inst:e,continue:!t.abort})}}),n0=I("$ZodCheckMaxSize",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=Yg),e._zod.check=r=>{let o=r.value;o.size<=t.maximum||r.issues.push({origin:Xa(o),code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),r0=I("$ZodCheckMinSize",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=Yg),e._zod.check=r=>{let o=r.value;o.size>=t.minimum||r.issues.push({origin:Xa(o),code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),o0=I("$ZodCheckSizeEquals",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=Yg),e._zod.check=r=>{let o=r.value,s=o.size;if(s===t.size)return;let i=s>t.size;r.issues.push({origin:Xa(o),...i?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),s0=I("$ZodCheckMaxLength",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=qg),e._zod.check=r=>{let o=r.value,s=o.length;if((typeof o=="string"&&s>t.maximum?fo(o):s)<=t.maximum)return;let a=Ba(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),i0=I("$ZodCheckMinLength",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=qg),e._zod.check=r=>{let o=r.value,s=o.length;if((typeof o=="string"&&s>=t.minimum&&s<t.minimum*2?fo(o):s)>=t.minimum)return;let a=Ba(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),a0=I("$ZodCheckLengthEquals",(e,t)=>{var n;Fe.init(e,t),(n=e._zod.def).when??(n.when=qg),e._zod.check=r=>{let o=r.value,s=o.length,i=typeof o=="string"&&s>=t.length&&s<=t.length*2?fo(o):s;if(i===t.length)return;let a=Ba(o),u=i>t.length;r.issues.push({origin:a,...u?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Ws=I("$ZodCheckStringFormat",(e,t)=>{var n,r;Fe.init(e,t),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),l0=I("$ZodCheckRegex",(e,t)=>{Ws.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),c0=I("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=jg),Ws.init(e,t)}),u0=I("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Qg),Ws.init(e,t)}),d0=I("$ZodCheckIncludes",(e,t)=>{Fe.init(e,t);let n=Zt(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),p0=I("$ZodCheckStartsWith",(e,t)=>{Fe.init(e,t);let n=new RegExp(`^${Zt(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),f0=I("$ZodCheckEndsWith",(e,t)=>{Fe.init(e,t);let n=new RegExp(`.*${Zt(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});function xd(e,t,n){e.issues.length&&t.issues.push(...Rt(n,e.issues))}var h0=I("$ZodCheckProperty",(e,t)=>{Fe.init(e,t),e._zod.check=n=>{let r=t.schema._zod.run({value:n.value[t.property],issues:[]},{});if(r instanceof Promise)return r.then(o=>xd(o,n,t.property));xd(r,n,t.property)}}),m0=I("$ZodCheckProperties",(e,t)=>{Fe.init(e,t),Ua(e,Symbol.iterator,function*(){yield e});let n;e._zod.check=r=>{if(r.value==null){r.issues.push({expected:"object",code:"invalid_type",input:r.value,inst:e});return}n??(n=Reflect.ownKeys(t.shape).map(i=>[i,t.shape[i]]));let o=r.value,s;for(let[i,a]of n){let u=a._zod.run({value:o[i],issues:[]},{});u instanceof Promise?(s??(s=[]),s.push(u.then(c=>xd(c,r,i)))):xd(u,r,i)}if(s)return Promise.all(s).then(()=>{})}}),g0=I("$ZodCheckMimeType",(e,t)=>{Fe.init(e,t);let n=new Set(t.mime);e._zod.check=r=>{n.has(r.value.type)||r.issues.push({code:"invalid_value",values:t.mime,input:r.value.type,inst:e,continue:!t.abort})}}),x0=I("$ZodCheckOverwrite",(e,t)=>{Fe.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});var mo=class{constructor(t=[],n={}){this.content=[],this.indent=0,this.args=t,this.closed=n}indented(t){this.indent+=1;try{t(this)}finally{this.indent-=1}}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let r=t.split(`
151
151
  `).filter(i=>i),o=Math.min(...r.map(i=>i.length-i.trimStart().length)),s=r.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let t=Function,n=this?.content??[""];return new t(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
152
152
  ${n.join(`
153
153
  `)}
154
- };`)(...Object.values(this.closed))}};var g0={major:4,minor:6,patch:5};var me=I("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=g0;let r=e._zod.def.checks,o=e._zod.traits.has("$ZodCheck")?[e,...r??[]]:r?.length?[...r]:[];for(let s of o)for(let i of s._zod.onattach)i(e);if(o.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let s=(a,u,c)=>{if(a.memo)return a;let d=wt(a),p;for(let f of u){if(f._zod.def.when){if(ng(a)||!f._zod.def.when(a))continue}else if(d)continue;let h=a.issues.length,g=f._zod.check(a);if(g instanceof Promise&&c?.async===!1)throw new It;if(p||g instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await g,a.issues.length!==h&&(Ju(a.issues,h,e),d||(d=wt(a,h)))});else{if(a.issues.length===h)continue;Ju(a.issues,h,e),d||(d=wt(a,h))}}return p?p.then(()=>a):a},i=(a,u,c)=>{if(wt(a))return a.aborted=!0,a;let d=s(u,o,c);if(d instanceof Promise){if(c.async===!1)throw new It;return d.then(p=>e._zod.parse(p,c))}return e._zod.parse(d,c)};e._zod.run=(a,u)=>{if(u.skipChecks)return e._zod.parse(a,u);if(u.direction==="backward"){let d=e._zod.parse({value:a.value,issues:[]},{...u,skipChecks:!0});return d instanceof Promise?d.then(p=>i(p,a,u)):i(d,a,u)}let c=e._zod.parse(a,u);if(c instanceof Promise){if(u.async===!1)throw new It;return c.then(d=>s(d,o,u))}return s(c,o,u)}}},{get"~standard"(){return Ba(this,"~standard",wd(this))},set"~standard"(e){gr(this,"~standard",e)}}),FN=(e,t)=>e.issues.length?{issues:e.issues.map(n=>$t(n,t,He()))}:{value:e.value};async function dM(e,t){let n={async:!0};return FN(await e._zod.run({value:t,issues:[]},n),n)}function wd(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return FN(r,n)}catch{}return dM(e,t)},vendor:"zod",version:1}}var mo=I("$ZodString",(e,t)=>{me.init(e,t),e._zod.pattern=t.pattern??Kg,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Re=I("$ZodStringFormat",(e,t)=>{Zs.init(e,t),mo.init(e,t)}),b0=I("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=kg),Re.init(e,t)}),y0=I("$ZodUUID",(e,t)=>{if(t.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=fo(r))}else t.pattern??(t.pattern=fo());Re.init(e,t)}),_0=I("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Sg),Re.init(e,t)}),v0=1,Ya=2;function w0(e){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function kd(e,t){return!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t)?w0(e)||Ya:zN(e,t)}function zN(e,t){if(!t.normalize&&t.protocol?.source===Wa.source&&!/^https?:\/\//i.test(e))return v0;try{if(typeof URL<"u"){let n=URL;if(typeof n.parse=="function")return n.parse(e)??Ya}return new URL(e)}catch{return Ya}}var pM=/[\t\n\r]/g;function qa(e){return e.replace(pM,"")}function Sd(e,t){return t.lastIndex=0,t.test(e.hostname)}function Ed(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var k0=I("$ZodURL",(e,t)=>{Re.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),o=kd(r,t);if(o===v0){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(o===Ya){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(o===!0){n.value=qa(r);return}t.hostname&&!Sd(o,t.hostname)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!Ed(o,t.protocol)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?o.href:qa(r);return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),S0=I("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Eg()),Re.init(e,t)}),E0=I("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw new Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?_g:vg(t.length)),Re.init(e,t)}),N0=I("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=mg),Re.init(e,t)}),A0=I("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=gg),Re.init(e,t)}),C0=I("$ZodULID",(e,t)=>{t.pattern??(t.pattern=xg),Re.init(e,t)}),T0=I("$ZodXID",(e,t)=>{t.pattern??(t.pattern=bg),Re.init(e,t)}),R0=I("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=yg),Re.init(e,t)}),$0=I("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=zg(t)),Re.init(e,t)}),I0=I("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Dg),Re.init(e,t)}),P0=I("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Fg(t)),Re.init(e,t)}),O0=I("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=wg),Re.init(e,t)}),L0=I("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ng),Re.init(e,t)}),fM=/^[0-9a-fA-F:.]+$/;function Ja(e){return fM.test(e)?w0(`http://[${e}]`):!1}var M0=I("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Ag),Re.init(e,t),e._zod.check=n=>{Ja(n.value)||n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),D0=I("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=Cg(t.delimiter)),Re.init(e,t)}),F0=I("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Tg),Re.init(e,t)});function Nd(e){let t=e.split("/");if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let o=Number(r);return`${o}`!==r||o<0||o>128?!1:Ja(n)}var z0=I("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Rg),Re.init(e,t),e._zod.check=n=>{Nd(n.value)||n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function el(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Ad=/^[0-9a-zA-Z+/]*={0,2}$/,K0=I("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Ad),Re.init(e,t),e._zod.check=n=>{el(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),tl=/^[A-Za-z0-9_-]*$/;function Cd(e){if(!tl.test(e))return!1;let t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return el(n)}var X0=I("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=tl),Re.init(e,t),e._zod.check=n=>{Cd(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),B0=I("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Lg),Re.init(e,t)}),hM=/[- ]/g;function mM(e){let t=e.length,n=1,r=0;for(;t;){let o=e.charCodeAt(--t)-48;n^=1,r+=n?[0,2,4,6,8,1,3,5,7,9][o]:o}return r%10===0}function Td(e){return pd.test(e)?mM(e.replace(hM,"")):!1}var U0=I("$ZodCreditCard",(e,t)=>{t.pattern??(t.pattern=pd),Re.init(e,t),e._zod.check=n=>{Td(n.value)||n.issues.push({code:"invalid_format",format:"credit_card",input:n.value,inst:e,continue:!t.abort})}});function gM(e){let t=0,n=e.length;for(let r=4;r<n;r++){let o=e.charCodeAt(r);t=(o>=65?t*100+(o-55):t*10+(o-48))%97}for(let r=0;r<4;r++){let o=e.charCodeAt(r);t=(o>=65?t*100+(o-55):t*10+(o-48))%97}return t===1}function Rd(e){return fd.test(e)?gM(e):!1}var H0=I("$ZodIBAN",(e,t)=>{t.pattern??(t.pattern=fd),Re.init(e,t),e._zod.check=n=>{Rd(n.value)||n.issues.push({code:"invalid_format",format:"iban",input:n.value,inst:e,continue:!t.abort})}});function $d(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}var V0=I("$ZodJWT",(e,t)=>{Re.init(e,t),e._zod.check=n=>{$d(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Z0=I("$ZodCustomStringFormat",(e,t)=>{Re.init(e,t),e._zod.check=n=>{t.fn(n.value)||n.issues.push({code:"invalid_format",format:t.format,input:n.value,inst:e,continue:!t.abort})}}),Id=I("$ZodNumber",(e,t)=>{me.init(e,t),e._zod.pattern=Vn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:String(o):void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),n}}),W0=I("$ZodNumberFormat",(e,t)=>{qg.init(e,t),Id.init(e,t)}),nl=I("$ZodBoolean",(e,t)=>{me.init(e,t),e._zod.pattern=Ug,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),Pd=I("$ZodBigInt",(e,t)=>{me.init(e,t),e._zod.pattern=Bg,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}}),j0=I("$ZodBigIntFormat",(e,t)=>{Jg.init(e,t),Pd.init(e,t)}),Q0=I("$ZodSymbol",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;return typeof o=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:o,inst:e}),n}}),G0=I("$ZodUndefined",(e,t)=>{me.init(e,t),e._zod.pattern=Vg,e._zod.values=new Set([void 0]),e._zod.parse=(n,r)=>{let o=n.value;return typeof o>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:e}),n}}),Y0=I("$ZodNull",(e,t)=>{me.init(e,t),e._zod.pattern=Hg,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),q0=I("$ZodAny",(e,t)=>{me.init(e,t),e._zod.parse=n=>n}),J0=I("$ZodUnknown",(e,t)=>{me.init(e,t),e._zod.parse=n=>n}),ex=I("$ZodNever",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)}),tx=I("$ZodVoid",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;return typeof o>"u"||n.issues.push({expected:"void",code:"invalid_type",input:o,inst:e}),n}}),nx=I("$ZodDate",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch{}let o=n.value,s=o instanceof Date;return s&&!Number.isNaN(o.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:o,...s?{received:"Invalid Date"}:{},inst:e}),n}});function kN(e,t,n){e.issues.length&&t.issues.push(...Rt(n,e.issues)),t.value[n]=e.value}var rx=I("$ZodArray",(e,t)=>{me.init(e,t);let n=rt.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let s=r.value;if(!Array.isArray(s))return r.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),r;r.value=n?n.alloc(e,r,Array(s.length),o):Array(s.length);let i=[],a=o?.abortEarly;for(let u=0;u<s.length;u++){let c=s[u],d=t.element._zod.run({value:c,issues:[]},o);if(d instanceof Promise)i.push(d.then(p=>kN(p,r,u)));else if(kN(d,r,u),a&&d.issues.length!==0&&wt(d))break}return i.length?Promise.all(i).then(()=>r):r}});function vd(e,t,n,r,o,s){let i=n in r,a=s==="optional";if(!(!i&&a&&o==="optional")){if(e.issues.length){if(o!==void 0&&a&&!i)return;t.issues.push(...Rt(n,e.issues))}if(!i&&o===void 0){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?(i||o==="defaulted"&&!a)&&(t.value[n]=void 0):t.value[n]=e.value}}var xM=[];function KN(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:xM,o=r.length?[...t,...r]:t;for(let i of o)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(i)}": expected a Zod schema`);let s=tg(e.shape);return{...e,allKeys:o,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(s)}}function XN(e,t,n,r,o,s,i){let a=[],u=o.keySet,c=o.catchall._zod,d=c.def.type,p=c.optin,f=c.optout,h=0;for(let g in t){if(i&&n.issues.length!==h){if(wt(n,h))break;h=n.issues.length}if(u.has(g))continue;if(g==="__proto__"){d==="never"&&a.push(g);continue}if(d==="never"){a.push(g);continue}let x=c.run({value:t[g],issues:[]},r);x instanceof Promise?e.push(x.then(b=>vd(b,n,g,t,p,f))):vd(x,n,g,t,p,f)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s,continue:!0}),e.length?Promise.all(e).then(()=>n):n}var BN=I("$ZodObject",(e,t)=>{me.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape"),r=n?.get?n.get.raw:t.shape??{};if(r){let c=()=>{let d={...r};return Object.defineProperty(t,"shape",{value:d}),c.raw=d,d};c.raw=r,Object.defineProperty(t,"shape",{get:c})}let o=zs(()=>KN(t));ve(e,"propValues",c=>{let d=c.def.shape,p={};for(let f in d){let h=d[f]._zod;if(h.values){Object.prototype.hasOwnProperty.call(p,f)||it(p,f,new Set);for(let g of h.values)p[f].add(g);h.optin!==void 0&&p[f].add(void 0)}}return p});let s=uo,i=t.catchall,a,u=rt.memoizer;u?.attach(e),e._zod.parse=(c,d)=>{a??(a=o.value);let p=c.value;if(!s(p))return c.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),c;c.value=u?u.alloc(e,c,{},d):{};let f=[],h=a.shape,g=d?.abortEarly,x=c.issues.length;for(let b of a.allKeys){if(g&&c.issues.length!==x){if(wt(c,x))break;x=c.issues.length}if(b==="__proto__")continue;let v=h[b],w=v._zod.optin,C=v._zod.optout,y=v._zod.run({value:p[b],issues:[]},d);y instanceof Promise?f.push(y.then(T=>vd(T,c,b,p,w,C))):vd(y,c,b,p,w,C)}return i?XN(f,p,c,d,o.value,e,g===!0):f.length?Promise.all(f).then(()=>c):c}}),ox=I("$ZodObjectJIT",(e,t)=>{BN.init(e,t);let n=e._zod.parse,r=zs(()=>KN(t)),o=rt.memoizer,s=h=>{let g=r.value,x=g.symbolKeys,b=new ho(["payload","ctx"],{shape:h,inst:e,memo:o,syms:x}),v=T=>`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`,w=(T,N)=>`
155
- let ${T}_ab = false;
156
- for (let i = 0; i < ${T}.issues.length; i++) {
157
- const iss = ${T}.issues[i];
158
- iss.path = iss.path ? [${N}, ...iss.path] : [${N}];
154
+ };`)(...Object.values(this.closed))}};var b0={major:4,minor:6,patch:5};var me=I("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=b0;let r=e._zod.def.checks,o=e._zod.traits.has("$ZodCheck")?[e,...r??[]]:r?.length?[...r]:[];for(let s of o)for(let i of s._zod.onattach)i(e);if(o.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let s=(a,u,c)=>{if(a.memo)return a;let d=wt(a),p;for(let f of u){if(f._zod.def.when){if(og(a)||!f._zod.def.when(a))continue}else if(d)continue;let h=a.issues.length,g=f._zod.check(a);if(g instanceof Promise&&c?.async===!1)throw new It;if(p||g instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await g,a.issues.length!==h&&(td(a.issues,h,e),d||(d=wt(a,h)))});else{if(a.issues.length===h)continue;td(a.issues,h,e),d||(d=wt(a,h))}}return p?p.then(()=>a):a},i=(a,u,c)=>{if(wt(a))return a.aborted=!0,a;let d=s(u,o,c);if(d instanceof Promise){if(c.async===!1)throw new It;return d.then(p=>e._zod.parse(p,c))}return e._zod.parse(d,c)};e._zod.run=(a,u)=>{if(u.skipChecks)return e._zod.parse(a,u);if(u.direction==="backward"){let d=e._zod.parse({value:a.value,issues:[]},{...u,skipChecks:!0});return d instanceof Promise?d.then(p=>i(p,a,u)):i(d,a,u)}let c=e._zod.parse(a,u);if(c instanceof Promise){if(u.async===!1)throw new It;return c.then(d=>s(d,o,u))}return s(c,o,u)}}},{get"~standard"(){return Ua(this,"~standard",Sd(this))},set"~standard"(e){xr(this,"~standard",e)}}),BN=(e,t)=>e.issues.length?{issues:e.issues.map(n=>$t(n,t,He()))}:{value:e.value};async function mM(e,t){let n={async:!0};return BN(await e._zod.run({value:t,issues:[]},n),n)}function Sd(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return BN(r,n)}catch{}return mM(e,t)},vendor:"zod",version:1}}var go=I("$ZodString",(e,t)=>{me.init(e,t),e._zod.pattern=t.pattern??Bg,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Re=I("$ZodStringFormat",(e,t)=>{Ws.init(e,t),go.init(e,t)}),_0=I("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Eg),Re.init(e,t)}),v0=I("$ZodUUID",(e,t)=>{if(t.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ho(r))}else t.pattern??(t.pattern=ho());Re.init(e,t)}),w0=I("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ng),Re.init(e,t)}),k0=1,qa=2;function S0(e){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function Ed(e,t){return!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t)?S0(e)||qa:UN(e,t)}function UN(e,t){if(!t.normalize&&t.protocol?.source===ja.source&&!/^https?:\/\//i.test(e))return k0;try{if(typeof URL<"u"){let n=URL;if(typeof n.parse=="function")return n.parse(e)??qa}return new URL(e)}catch{return qa}}var gM=/[\t\n\r]/g;function Ja(e){return e.replace(gM,"")}function Nd(e,t){return t.lastIndex=0,t.test(e.hostname)}function Ad(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var E0=I("$ZodURL",(e,t)=>{Re.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),o=Ed(r,t);if(o===k0){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(o===qa){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(o===!0){n.value=Ja(r);return}t.hostname&&!Nd(o,t.hostname)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!Ad(o,t.protocol)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?o.href:Ja(r);return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),N0=I("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Ag()),Re.init(e,t)}),A0=I("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw new Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?wg:kg(t.length)),Re.init(e,t)}),C0=I("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=xg),Re.init(e,t)}),T0=I("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=bg),Re.init(e,t)}),R0=I("$ZodULID",(e,t)=>{t.pattern??(t.pattern=yg),Re.init(e,t)}),$0=I("$ZodXID",(e,t)=>{t.pattern??(t.pattern=_g),Re.init(e,t)}),I0=I("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=vg),Re.init(e,t)}),P0=I("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Xg(t)),Re.init(e,t)}),O0=I("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=zg),Re.init(e,t)}),L0=I("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Kg(t)),Re.init(e,t)}),M0=I("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Sg),Re.init(e,t)}),D0=I("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Cg),Re.init(e,t)}),xM=/^[0-9a-fA-F:.]+$/;function el(e){return xM.test(e)?S0(`http://[${e}]`):!1}var F0=I("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Tg),Re.init(e,t),e._zod.check=n=>{el(n.value)||n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),z0=I("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=Rg(t.delimiter)),Re.init(e,t)}),K0=I("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=$g),Re.init(e,t)});function Cd(e){let t=e.split("/");if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let o=Number(r);return`${o}`!==r||o<0||o>128?!1:el(n)}var X0=I("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Ig),Re.init(e,t),e._zod.check=n=>{Cd(n.value)||n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function tl(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Td=/^[0-9a-zA-Z+/]*={0,2}$/,B0=I("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Td),Re.init(e,t),e._zod.check=n=>{tl(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),nl=/^[A-Za-z0-9_-]*$/;function Rd(e){if(!nl.test(e))return!1;let t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return tl(n)}var U0=I("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=nl),Re.init(e,t),e._zod.check=n=>{Rd(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),H0=I("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Dg),Re.init(e,t)}),bM=/[- ]/g;function yM(e){let t=e.length,n=1,r=0;for(;t;){let o=e.charCodeAt(--t)-48;n^=1,r+=n?[0,2,4,6,8,1,3,5,7,9][o]:o}return r%10===0}function $d(e){return hd.test(e)?yM(e.replace(bM,"")):!1}var V0=I("$ZodCreditCard",(e,t)=>{t.pattern??(t.pattern=hd),Re.init(e,t),e._zod.check=n=>{$d(n.value)||n.issues.push({code:"invalid_format",format:"credit_card",input:n.value,inst:e,continue:!t.abort})}});function _M(e){let t=0,n=e.length;for(let r=4;r<n;r++){let o=e.charCodeAt(r);t=(o>=65?t*100+(o-55):t*10+(o-48))%97}for(let r=0;r<4;r++){let o=e.charCodeAt(r);t=(o>=65?t*100+(o-55):t*10+(o-48))%97}return t===1}function Id(e){return md.test(e)?_M(e):!1}var Z0=I("$ZodIBAN",(e,t)=>{t.pattern??(t.pattern=md),Re.init(e,t),e._zod.check=n=>{Id(n.value)||n.issues.push({code:"invalid_format",format:"iban",input:n.value,inst:e,continue:!t.abort})}});function Pd(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}var W0=I("$ZodJWT",(e,t)=>{Re.init(e,t),e._zod.check=n=>{Pd(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),j0=I("$ZodCustomStringFormat",(e,t)=>{Re.init(e,t),e._zod.check=n=>{t.fn(n.value)||n.issues.push({code:"invalid_format",format:t.format,input:n.value,inst:e,continue:!t.abort})}}),Od=I("$ZodNumber",(e,t)=>{me.init(e,t),e._zod.pattern=Zn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:String(o):void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),n}}),Q0=I("$ZodNumberFormat",(e,t)=>{e0.init(e,t),Od.init(e,t)}),rl=I("$ZodBoolean",(e,t)=>{me.init(e,t),e._zod.pattern=Vg,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),Ld=I("$ZodBigInt",(e,t)=>{me.init(e,t),e._zod.pattern=Hg,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}}),G0=I("$ZodBigIntFormat",(e,t)=>{t0.init(e,t),Ld.init(e,t)}),Y0=I("$ZodSymbol",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;return typeof o=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:o,inst:e}),n}}),q0=I("$ZodUndefined",(e,t)=>{me.init(e,t),e._zod.pattern=Wg,e._zod.values=new Set([void 0]),e._zod.parse=(n,r)=>{let o=n.value;return typeof o>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:e}),n}}),J0=I("$ZodNull",(e,t)=>{me.init(e,t),e._zod.pattern=Zg,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),ex=I("$ZodAny",(e,t)=>{me.init(e,t),e._zod.parse=n=>n}),tx=I("$ZodUnknown",(e,t)=>{me.init(e,t),e._zod.parse=n=>n}),nx=I("$ZodNever",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)}),rx=I("$ZodVoid",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;return typeof o>"u"||n.issues.push({expected:"void",code:"invalid_type",input:o,inst:e}),n}}),ox=I("$ZodDate",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch{}let o=n.value,s=o instanceof Date;return s&&!Number.isNaN(o.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:o,...s?{received:"Invalid Date"}:{},inst:e}),n}});function AN(e,t,n){e.issues.length&&t.issues.push(...Rt(n,e.issues)),t.value[n]=e.value}var sx=I("$ZodArray",(e,t)=>{me.init(e,t);let n=ot.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let s=r.value;if(!Array.isArray(s))return r.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),r;r.value=n?n.alloc(e,r,Array(s.length),o):Array(s.length);let i=[],a=o?.abortEarly;for(let u=0;u<s.length;u++){let c=s[u],d=t.element._zod.run({value:c,issues:[]},o);if(d instanceof Promise)i.push(d.then(p=>AN(p,r,u)));else if(AN(d,r,u),a&&d.issues.length!==0&&wt(d))break}return i.length?Promise.all(i).then(()=>r):r}});function kd(e,t,n,r,o,s){let i=n in r,a=s==="optional";if(!(!i&&a&&o==="optional")){if(e.issues.length){if(o!==void 0&&a&&!i)return;t.issues.push(...Rt(n,e.issues))}if(!i&&o===void 0){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?(i||o==="defaulted"&&!a)&&(t.value[n]=void 0):t.value[n]=e.value}}var vM=[];function HN(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:vM,o=r.length?[...t,...r]:t;for(let i of o)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(i)}": expected a Zod schema`);let s=rg(e.shape);return{...e,allKeys:o,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(s)}}function VN(e,t,n,r,o,s,i){let a=[],u=o.keySet,c=o.catchall._zod,d=c.def.type,p=c.optin,f=c.optout,h=0;for(let g in t){if(i&&n.issues.length!==h){if(wt(n,h))break;h=n.issues.length}if(u.has(g))continue;if(g==="__proto__"){d==="never"&&a.push(g);continue}if(d==="never"){a.push(g);continue}let x=c.run({value:t[g],issues:[]},r);x instanceof Promise?e.push(x.then(b=>kd(b,n,g,t,p,f))):kd(x,n,g,t,p,f)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s,continue:!0}),e.length?Promise.all(e).then(()=>n):n}var ZN=I("$ZodObject",(e,t)=>{me.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape"),r=n?.get?n.get.raw:t.shape??{};if(r){let c=()=>{let d={...r};return Object.defineProperty(t,"shape",{value:d}),c.raw=d,d};c.raw=r,Object.defineProperty(t,"shape",{get:c})}let o=Ks(()=>HN(t));ve(e,"propValues",c=>{let d=c.def.shape,p={};for(let f in d){let h=d[f]._zod;if(h.values){Object.prototype.hasOwnProperty.call(p,f)||it(p,f,new Set);for(let g of h.values)p[f].add(g);h.optin!==void 0&&p[f].add(void 0)}}return p});let s=po,i=t.catchall,a,u=ot.memoizer;u?.attach(e),e._zod.parse=(c,d)=>{a??(a=o.value);let p=c.value;if(!s(p))return c.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),c;c.value=u?u.alloc(e,c,{},d):{};let f=[],h=a.shape,g=d?.abortEarly,x=c.issues.length;for(let b of a.allKeys){if(g&&c.issues.length!==x){if(wt(c,x))break;x=c.issues.length}if(b==="__proto__")continue;let _=h[b],w=_._zod.optin,T=_._zod.optout,y=_._zod.run({value:p[b],issues:[]},d);y instanceof Promise?f.push(y.then(E=>kd(E,c,b,p,w,T))):kd(y,c,b,p,w,T)}return i?VN(f,p,c,d,o.value,e,g===!0):f.length?Promise.all(f).then(()=>c):c}}),ix=I("$ZodObjectJIT",(e,t)=>{ZN.init(e,t);let n=e._zod.parse,r=Ks(()=>HN(t)),o=ot.memoizer,s=h=>{let g=r.value,x=g.symbolKeys,b=new mo(["payload","ctx"],{shape:h,inst:e,memo:o,syms:x}),_=E=>`shape[${E}]._zod.run({ value: input[${E}], issues: [] }, ctx)`,w=(E,k)=>`
155
+ let ${E}_ab = false;
156
+ for (let i = 0; i < ${E}.issues.length; i++) {
157
+ const iss = ${E}.issues[i];
158
+ iss.path = iss.path ? [${k}, ...iss.path] : [${k}];
159
159
  payload.issues.push(iss);
160
- if (iss.continue !== true) ${T}_ab = true;
160
+ if (iss.continue !== true) ${E}_ab = true;
161
161
  }
162
- if (${T}_ab && ctx && ctx.abortEarly) {
162
+ if (${E}_ab && ctx && ctx.abortEarly) {
163
163
  payload.value = newResult;
164
164
  return payload;
165
- }`;b.write("const input = payload.value;");let C=Object.create(null),y=0;for(let T of g.allKeys)C[T]=`key_${y++}`;b.write(o?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let T of g.allKeys){if(T==="__proto__")continue;let N=C[T],S=typeof T=="symbol"?`syms[${x.indexOf(T)}]`:vt(T),$=`${S} in input`,P=h[T],L=P?._zod?.optin,ne=L!==void 0,se=P?._zod?.optout==="optional";if(b.write(`const ${N} = ${v(S)};`),ne&&se){let _e=L==="optional"?`${N}_present`:`${N}.value !== undefined || ${N}_present`;b.write(`
166
- const ${N}_present = ${$};
167
- if (!${N}.issues.length || ${N}_present) {
168
- if (${N}.issues.length) {${w(N,S)}
165
+ }`;b.write("const input = payload.value;");let T=Object.create(null),y=0;for(let E of g.allKeys)T[E]=`key_${y++}`;b.write(o?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let E of g.allKeys){if(E==="__proto__")continue;let k=T[E],N=typeof E=="symbol"?`syms[${x.indexOf(E)}]`:vt(E),$=`${N} in input`,P=h[E],L=P?._zod?.optin,ne=L!==void 0,se=P?._zod?.optout==="optional";if(b.write(`const ${k} = ${_(N)};`),ne&&se){let _e=L==="optional"?`${k}_present`:`${k}.value !== undefined || ${k}_present`;b.write(`
166
+ const ${k}_present = ${$};
167
+ if (!${k}.issues.length || ${k}_present) {
168
+ if (${k}.issues.length) {${w(k,N)}
169
169
  }
170
170
 
171
171
  if (${_e}) {
172
- newResult[${S}] = ${N}.value;
172
+ newResult[${N}] = ${k}.value;
173
173
  }
174
174
  }
175
175
 
176
176
  `)}else ne?(b.write(`
177
- if (${N}.issues.length) {${w(N,S)}
177
+ if (${k}.issues.length) {${w(k,N)}
178
178
  }
179
- `),L==="defaulted"?b.write(`newResult[${S}] = ${N}.value;`):b.write(`
180
- if (${N}.value !== undefined || ${$}) {
181
- newResult[${S}] = ${N}.value;
179
+ `),L==="defaulted"?b.write(`newResult[${N}] = ${k}.value;`):b.write(`
180
+ if (${k}.value !== undefined || ${$}) {
181
+ newResult[${N}] = ${k}.value;
182
182
  }
183
183
  `)):b.write(`
184
- const ${N}_present = ${$};
185
- if (${N}.issues.length) {${w(N,S)}
184
+ const ${k}_present = ${$};
185
+ if (${k}.issues.length) {${w(k,N)}
186
186
  }
187
- if (!${N}_present && !${N}.issues.length) {
187
+ if (!${k}_present && !${k}.issues.length) {
188
188
  payload.issues.push({
189
189
  code: "invalid_type",
190
190
  expected: "nonoptional",
191
191
  input: undefined,
192
- path: [${S}]
192
+ path: [${N}]
193
193
  });
194
194
  if (ctx && ctx.abortEarly) {
195
195
  payload.value = newResult;
@@ -197,25 +197,25 @@ ${n.join(`
197
197
  }
198
198
  }
199
199
 
200
- if (${N}_present) {
201
- newResult[${S}] = ${N}.value;
200
+ if (${k}_present) {
201
+ newResult[${N}] = ${k}.value;
202
202
  }
203
203
 
204
- `)}return b.write("payload.value = newResult;"),b.write("return payload;"),b.compile()},i,a=uo,u=!rt.jitless,d=u&&Jm.value,p=t.catchall,f;e._zod.parse=(h,g)=>{f??(f=r.value);let x=h.value;return a(x)?u&&d&&g?.async===!1&&g.jitless!==!0?(i||(i=s(t.shape)),h=i(h,g),p?XN([],x,h,g,f,e,g?.abortEarly===!0):h):n(h,g):(h.issues.push({expected:"object",code:"invalid_type",input:x,inst:e}),h)}});function SN(e,t,n,r){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter(s=>!wt(s));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(s=>s.issues.map(i=>$t(i,r,He())))}),t)}var rl=I("$ZodUnion",(e,t)=>{me.init(e,t),ve(e,"optin",r=>r.def.options.some(o=>o._zod.optin==="defaulted")?"defaulted":r.def.options.some(o=>o._zod.optin!==void 0)?"optional":void 0),ve(e,"optout",r=>r.def.options.some(o=>o._zod.optout==="optional")?"optional":void 0),ve(e,"values",r=>{if(r.def.options.every(o=>o._zod.values))return new Set(r.def.options.flatMap(o=>Array.from(o._zod.values)))}),ve(e,"pattern",r=>{if(r.def.options.every(o=>o._zod.pattern)){let o=r.def.options.map(s=>s._zod.pattern);return new RegExp(`^(${o.map(s=>Hn(s.source)).join("|")})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let s=!1,i=[];for(let a of t.options){let u=a._zod.run({value:r.value,issues:[]},o);if(u instanceof Promise)i.push(u),s=!0;else{if(u.issues.length===0)return u;i.push(u)}}return s?Promise.all(i).then(a=>SN(a,r,e,o)):SN(i,r,e,o)}});function EN(e,t,n,r){let o=[];for(let s=0;s<e.length;s++)e[s].issues.length===0&&o.push(s);return o.length===1?(t.value=e[o[0]].value,t):(o.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(s=>s.issues.map(i=>$t(i,r,He())))}):t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:[],inclusive:!1,matches:o}),t)}var sx=I("$ZodXor",(e,t)=>{rl.init(e,t),t.inclusive=!1;let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let s=!1,i=[];for(let a of t.options){let u=a._zod.run({value:r.value,issues:[]},o);u instanceof Promise?(i.push(u),s=!0):i.push(u)}return s?Promise.all(i).then(a=>EN(a,r,e,o)):EN(i,r,e,o)}});function ix(e,t){let n=e._zod,r=n.bag.optionsMap;r||(r=UN(n.def),n.bag.optionsMap=r);let o=r.get(t);if(o===null)throw new Error(`Ambiguous discriminator value "${String(t)}"`);return o}function UN(e){let t=new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let o of r)if(t.has(o)){if(o!==void 0)throw new Error(`Duplicate discriminator value "${String(o)}"`);t.set(o,null)}else t.set(o,n)}return t}var ax=I("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,rl.init(e,t);let n=e._zod.parse;ve(e,"propValues",o=>{let s={},i=0;for(let a of o.def.options){let u=a._zod.propValues;if(!u||Object.keys(u).length===0)throw new Error(`Invalid discriminated union option at index "${o.def.options.indexOf(a)}"`);u[o.def.discriminator]?.has(void 0)&&i++;for(let[c,d]of Object.entries(u)){Object.prototype.hasOwnProperty.call(s,c)||it(s,c,new Set);for(let p of d)s[c].add(p)}}return!o.def.unionFallback&&i>1&&s[o.def.discriminator]?.delete(void 0),s}),t.options.forEach((o,s)=>{let i=Ks(o._zod.def);if(i&&!Object.prototype.hasOwnProperty.call(i,t.discriminator))throw new Error(`Invalid discriminated union option at index "${s}"`)});let r=zs(()=>UN(t));e._zod.parse=(o,s)=>{let i=o.value;if(!uo(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let a=i?.[t.discriminator],u=r.value.get(a);return u&&(a!==void 0||s.direction!=="backward")?u._zod.run(o,s):t.unionFallback||s.direction==="backward"?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(c=>r.value.get(c)!==null),input:i,path:[t.discriminator],inst:e}),o)}}),lx=I("$ZodIntersection",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>{let o=n.value,s=t.left._zod.run({value:o,issues:[]},r),i=t.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([u,c])=>NN(n,u,c)):NN(n,s,i)}});function Ws(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Vt(e)&&Vt(t)){let n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),o={...e,...t};Object.prototype.hasOwnProperty.call(o,"__proto__")&&delete o.__proto__;for(let s of r){if(s==="__proto__")continue;let i=Ws(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let o=e[r],s=t[r],i=Ws(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function NN(e,t,n){let r=new Map,o,s=new Map,i=(c,d)=>{let p;if(c.code==="unrecognized_keys"&&!c.path?.length)o??(o=c),p=c.keys;else if(c.code==="invalid_key"&&c.origin==="record"&&c.path?.length===1){let f=String(c.path[0]);s.has(f)||s.set(f,c),p=[f]}else return!1;for(let f of p)r.has(f)||r.set(f,{}),r.get(f)[d]=!0;return!0};for(let c of t.issues)i(c,"l")||e.issues.push(c);for(let c of n.issues)i(c,"r")||e.issues.push(c);let a=[...r].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(a.length){let c=o?a.filter(d=>o.keys.includes(d)):[];c.length&&e.issues.push({...o,keys:c});for(let d of a)!c.includes(d)&&s.has(d)&&e.issues.push(s.get(d))}let u=Ws(t.value,n.value);if(!u.valid){if(wt(e))return e;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`)}return e.value=u.data,e}var Od=I("$ZodTuple",(e,t)=>{me.init(e,t);let n=t.items,r=rt.memoizer;r?.attach(e),e._zod.parse=(o,s)=>{let i=o.value;if(!Array.isArray(i))return o.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),o;o.value=r?r.alloc(e,o,[],s):[];let a=[],u=AN(n,"optin"),c=AN(n,"optout");if(!t.rest){if(i.length<u)return o.issues.push({code:"too_small",minimum:u,inclusive:!0,input:i,inst:e,origin:"array"}),o;i.length>n.length&&o.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:i,inst:e,origin:"array"})}let d=new Array(n.length),p=t.rest?s?.abortEarly:void 0,f=!1;for(let h=0;h<n.length;h++){let g=n[h]._zod.run({value:i[h],issues:[]},s);g instanceof Promise?a.push(g.then(x=>{d[h]=x})):(d[h]=g,p&&!f&&g.issues.length&&(f=wt(g)))}if(t.rest&&!f){let h=n.length-1,g=i.slice(n.length),x=o.issues.length;for(let b of g){if(p&&o.issues.length!==x){if(wt(o,x))break;x=o.issues.length}h++;let v=t.rest._zod.run({value:b,issues:[]},s);v instanceof Promise?a.push(v.then(w=>CN(w,o,h))):CN(v,o,h)}}return a.length?Promise.all(a).then(()=>TN(d,o,n,i,c)):TN(d,o,n,i,c)}});function AN(e,t){for(let n=e.length-1;n>=0;n--)if(!(t==="optin"?e[n]._zod.optin!==void 0:e[n]._zod.optout==="optional"))return n+1;return 0}function CN(e,t,n){e.issues.length&&t.issues.push(...Rt(n,e.issues)),t.value[n]=e.value}function TN(e,t,n,r,o){for(let s=0;s<n.length;s++){let i=e[s],a=s<r.length;if(!a&&s>=o&&n[s]._zod.optin==="optional"){t.value.length=s;break}if(i.issues.length){if(!a&&s>=o){t.value.length=s;break}t.issues.push(...Rt(s,i.issues))}t.value[s]=i.value}for(let s=t.value.length-1;s>=r.length&&(n[s]._zod.optout==="optional"&&t.value[s]===void 0);s--)t.value.length=s;return t}var cx=I("$ZodRecord",(e,t)=>{me.init(e,t);let n=rt.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let s=r.value;if(!Vt(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),r;let i=[],a=t.keyType._zod.values;if(a&&!t.partial){r.value=n?n.alloc(e,r,{},o):{};let u=new Set;for(let d of a)if(typeof d=="string"||typeof d=="number"||typeof d=="symbol"){if(u.add(typeof d=="number"?d.toString():d),d==="__proto__")continue;let p=t.keyType._zod.run({value:d,issues:[]},o);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(p.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map(g=>$t(g,o,He())),input:d,path:[d],inst:e});continue}let f=p.value;if(f==="__proto__")continue;let h=t.valueType._zod.run({value:s[d],issues:[]},o);h instanceof Promise?i.push(h.then(g=>{g.issues.length&&r.issues.push(...Rt(d,g.issues)),r.value[f]=g.value})):(h.issues.length&&r.issues.push(...Rt(d,h.issues)),r.value[f]=h.value)}let c;for(let d in s)if(!u.has(d))if(t.mode==="loose"){if(d==="__proto__")continue;r.value[d]=s[d]}else c=c??[],c.push(d);c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:c,continue:!0})}else{r.value=n?n.alloc(e,r,{},o):{};let u;for(let c of Reflect.ownKeys(s)){if(c==="__proto__"||!Object.prototype.propertyIsEnumerable.call(s,c))continue;let d=t.keyType._zod.run({value:c,issues:[]},o);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof c=="string"&&Vn.test(c)&&d.issues.length){let g=t.keyType._zod.run({value:Number(c),issues:[]},o);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");g.issues.length===0&&(d=g)}if(d.issues.length){t.mode==="loose"?r.value[c]=s[c]:a?(u=u??[],u.push(c)):r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(g=>$t(g,o,He())),input:c,path:[c],inst:e});continue}let f=d.value;if(f==="__proto__")continue;let h=t.valueType._zod.run({value:s[c],issues:[]},o);h instanceof Promise?i.push(h.then(g=>{g.issues.length&&r.issues.push(...Rt(c,g.issues)),r.value[f]=g.value})):(h.issues.length&&r.issues.push(...Rt(c,h.issues)),r.value[f]=h.value)}u&&u.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:u,continue:!0})}return i.length?Promise.all(i).then(()=>r):r}}),ux=I("$ZodMap",(e,t)=>{me.init(e,t);let n=rt.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let s=r.value;if(!(s instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:s,inst:e}),r;let i=[];r.value=n?n.alloc(e,r,new Map,o):new Map;let a=o?.abortEarly,u=r.issues.length;for(let[c,d]of s){if(a&&r.issues.length!==u){if(wt(r,u))break;u=r.issues.length}let p=t.keyType._zod.run({value:c,issues:[]},o),f=t.valueType._zod.run({value:d,issues:[]},o);p instanceof Promise||f instanceof Promise?i.push(Promise.all([p,f]).then(([h,g])=>{RN(h,g,r,c,s,e,o)})):RN(p,f,r,c,s,e,o)}return i.length?Promise.all(i).then(()=>r):r}});function RN(e,t,n,r,o,s,i){e.issues.length&&(Da.has(typeof r)?n.issues.push(...Rt(r,e.issues)):n.issues.push({code:"invalid_key",origin:"map",input:o,inst:s,issues:e.issues.map(a=>$t(a,i,He()))})),t.issues.length&&(Da.has(typeof r)?n.issues.push(...Rt(r,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:o,inst:s,key:r,issues:t.issues.map(a=>$t(a,i,He()))})),n.value.set(e.value,t.value)}var dx=I("$ZodSet",(e,t)=>{me.init(e,t);let n=rt.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let s=r.value;if(!(s instanceof Set))return r.issues.push({input:s,inst:e,expected:"set",code:"invalid_type"}),r;let i=[];r.value=n?n.alloc(e,r,new Set,o):new Set;let a=o?.abortEarly,u=r.issues.length;for(let c of s){if(a&&r.issues.length!==u){if(wt(r,u))break;u=r.issues.length}let d=t.valueType._zod.run({value:c,issues:[]},o);d instanceof Promise?i.push(d.then(p=>$N(p,r))):$N(d,r)}return i.length?Promise.all(i).then(()=>r):r}});function $N(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}var px=I("$ZodEnum",(e,t)=>{me.init(e,t);let n=Ds(t.entries),r=new Set(n);e._zod.values=r,ve(e,"pattern",o=>{let s=Ds(o.def.entries).filter(i=>Da.has(typeof i));return new RegExp(s.length?`^(${s.map(i=>Zt(i.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,s)=>{let i=o.value;return r.has(i)||o.issues.push({code:"invalid_value",values:n,input:i,inst:e}),o}}),fx=I("$ZodLiteral",(e,t)=>{me.init(e,t);let n=new Set(t.values);e._zod.values=n,ve(e,"pattern",r=>{let o=r.def.values;return new RegExp(o.length?`^(${o.map(s=>typeof s=="string"?Zt(s):s?Zt(s.toString()):String(s)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,o)=>{let s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),r}}),hx=I("$ZodFile",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;return o instanceof File||n.issues.push({expected:"file",code:"invalid_type",input:o,inst:e}),n}}),mx=I("$ZodTransform",(e,t)=>{me.init(e,t),e._zod.optin="optional",rt.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new xr(e.constructor.name);let o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n));if(o instanceof Promise)throw new It;return n.value=o,n}});function IN(e,t){return e.value=t.issues.length?void 0:t.value,e}var Ld=I("$ZodOptional",(e,t)=>{me.init(e,t),ve(e,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",ve(e,"values",n=>{let r=n.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),ve(e,"pattern",n=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${Hn(r.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;let o=t.innerType._zod.run({value:n.value,issues:[]},r);return o instanceof Promise?o.then(s=>IN(n,s)):IN(n,o)}return t.innerType._zod.run(n,r)}}),gx=I("$ZodExactOptional",(e,t)=>{Ld.init(e,t),ve(e,"values",n=>n.def.innerType._zod.values),ve(e,"pattern",n=>n.def.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),xx=I("$ZodNullable",(e,t)=>{me.init(e,t),ve(e,"optin",n=>n.def.innerType._zod.optin),ve(e,"optout",n=>n.def.innerType._zod.optout),ve(e,"pattern",n=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${Hn(r.source)}|null)$`):void 0}),ve(e,"values",n=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),bx=I("$ZodDefault",(e,t)=>{me.init(e,t),e._zod.optin="defaulted",ve(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>PN(s,t)):PN(o,t)}});function PN(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var yx=I("$ZodPrefault",(e,t)=>{me.init(e,t),e._zod.optin="defaulted",ve(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),_x=I("$ZodNonOptional",(e,t)=>{me.init(e,t),ve(e,"values",n=>{let r=n.def.innerType._zod.values;return r?new Set([...r].filter(o=>o!==void 0)):void 0}),e._zod.parse=(n,r)=>{let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>ON(s,e)):ON(o,e)}});function ON(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var vx=I("$ZodSuccess",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new xr("ZodSuccess");let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.issues.length===0,n)):(n.value=o.issues.length===0,n)}});function LN(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(o=>$t(o,r,He()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var wx=I("$ZodCatch",(e,t)=>{me.init(e,t),ve(e,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),ve(e,"optout",n=>n.def.innerType._zod.optout),ve(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run({value:n.value,issues:[]},r);return o instanceof Promise?o.then(s=>LN(n,s,t,r)):LN(n,o,t,r)}}),kx=I("$ZodNaN",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>((typeof n.value!="number"||!Number.isNaN(n.value))&&n.issues.push({input:n.value,inst:e,expected:"nan",code:"invalid_type"}),n)}),Md=I("$ZodPipe",(e,t)=>{me.init(e,t),ve(e,"values",n=>n.def.in._zod.values),ve(e,"optin",n=>n.def.in._zod.optin),ve(e,"optout",n=>n.def.out._zod.optout),ve(e,"propValues",n=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let s=t.out._zod.run(n,r);return s instanceof Promise?s.then(i=>bd(i,t.in,r)):bd(s,t.in,r)}let o=t.in._zod.run(n,r);return o instanceof Promise?o.then(s=>bd(s,t.out,r)):bd(o,t.out,r)}});function bd(e,t,n){return e.issues.some(r=>r.code!=="unrecognized_keys")?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var ol=I("$ZodCodec",(e,t)=>{me.init(e,t),ve(e,"values",n=>n.def.in._zod.values),ve(e,"optin",n=>n.def.in._zod.optin),ve(e,"optout",n=>n.def.out._zod.optout),ve(e,"propValues",n=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if((r.direction||"forward")==="forward"){let s=t.in._zod.run(n,r);return s instanceof Promise?s.then(i=>yd(i,t,r)):yd(s,t,r)}else{let s=t.out._zod.run(n,r);return s instanceof Promise?s.then(i=>yd(i,t,r)):yd(s,t,r)}}});function yd(e,t,n){if(e.issues.length)return e.aborted=!0,e;if((n.direction||"forward")==="forward"){let o=t.transform(e.value,e);return o instanceof Promise?o.then(s=>_d(e,s,t.out,n)):_d(e,o,t.out,n)}else{let o=t.reverseTransform(e.value,e);return o instanceof Promise?o.then(s=>_d(e,s,t.in,n)):_d(e,o,t.in,n)}}function _d(e,t,n,r){return e.issues.length?(e.aborted=!0,e):n._zod.run({value:t,issues:e.issues},r)}var Sx=I("$ZodPreprocess",(e,t)=>{Md.init(e,t)}),Ex=I("$ZodReadonly",(e,t)=>{me.init(e,t),ve(e,"propValues",n=>n.def.innerType._zod.propValues),ve(e,"values",n=>n.def.innerType._zod.values),ve(e,"optin",n=>n.def.innerType?._zod?.optin),ve(e,"optout",n=>n.def.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(MN):MN(o)}});function MN(e){return e.memo||(e.value=Object.freeze(e.value)),e}function bM(e){let t=e._zod.def,n=t.pattern,r=!!t.format?.includes("int"),o,s;for(let a of t.checks??[]){let u=a._zod.def;u.pattern&&(n=u.pattern),r||(r=!!u.format?.includes("int"));let c=u.minimum??u.length,d=u.maximum??u.length;c!==void 0&&(o===void 0||c>o)&&(o=c),d!==void 0&&(s===void 0||d<s)&&(s=d)}if(n)return n.source;if(o!==void 0&&s!==void 0&&o>s)return"(?!)";if(o!==void 0||s!==void 0)return Xg({minimum:o,maximum:s}).source;let i=e._zod.pattern;return(r&&i===Vn?ja:i)?.source}function x0(e){let t=e._zod.def,n=e._zod.pattern?.source,r=t.innerType??e._zod.innerType;if(r){let o=r._zod.pattern?.source,s=x0(r);return n&&o&&s&&s!==o?n.replace(Hn(o),()=>Hn(s)):n}if(t.options){let o=t.options.map(x0);if(o.every(Boolean))return`^(${o.map(s=>Hn(s)).join("|")})$`}return bM(e)}var Nx=I("$ZodTemplateLiteral",(e,t)=>{me.init(e,t);let n=[];for(let r of t.parts)if(typeof r=="object"&&r!==null){let o=x0(r);if(!o)throw new Error(`Invalid template literal part, no pattern found: ${[...r._zod.traits].shift()}`);n.push(Hn(o))}else if(r===null||eg.has(typeof r))n.push(Zt(`${r}`));else throw new Error(`Invalid template literal part: ${r}`);e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(r,o)=>typeof r.value!="string"?(r.issues.push({input:r.value,inst:e,expected:"string",code:"invalid_type"}),r):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(r.value)||r.issues.push({input:r.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),r)}),Ax=I("$ZodFunction",(e,t)=>(me.init(e,t),Object.defineProperty(e,"_def",{value:t}),e._zod.def=t,e.implement=n=>{if(typeof n!="function")throw new Error("implement() must be called with a function");return Object.defineProperty(function(...r){let o=e._def.input?nd(e._def.input,r):r,s=Reflect.apply(n,this,o);return e._def.output?nd(e._def.output,s):s},"_zod",{value:e._zod,enumerable:!1})},e.implementAsync=n=>{if(typeof n!="function")throw new Error("implementAsync() must be called with a function");return Object.defineProperty(async function(...r){let o=e._def.input?await rd(e._def.input,r):r,s=await Reflect.apply(n,this,o);return e._def.output?await rd(e._def.output,s):s},"_zod",{value:e._zod,enumerable:!1})},e._zod.parse=(n,r)=>typeof n.value!="function"?(n.issues.push({code:"invalid_type",expected:"function",input:n.value,inst:e}),n):(e._def.output&&e._def.output._zod.def.type==="promise"?n.value=e.implementAsync(n.value):n.value=e.implement(n.value),n),e.input=(...n)=>{let r=e.constructor;return Array.isArray(n[0])?new r({type:"function",input:new Od({type:"tuple",items:n[0],rest:n[1]}),output:e._def.output}):new r({type:"function",input:n[0],output:e._def.output})},e.output=n=>{let r=e.constructor;return new r({type:"function",input:e._def.input,output:n})},e)),Cx=I("$ZodPromise",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>Promise.resolve(n.value).then(o=>t.innerType._zod.run({value:o,issues:[]},r))}),sl=I("$ZodLazy",(e,t)=>{me.init(e,t),Ym(e._zod,"innerType",()=>{let n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),ve(e,"pattern",n=>n.innerType?._zod?.pattern),ve(e,"propValues",n=>n.innerType?._zod?.propValues),ve(e,"optin",n=>n.innerType?._zod?.optin??void 0),ve(e,"optout",n=>n.innerType?._zod?.optout??void 0),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),Tx=I("$ZodCustom",(e,t)=>{Fe.init(e,t),me.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{let r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(s=>DN(s,n,r,e));DN(o,n,r,e)}});function DN(e,t,n,r){if(!e){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(Xs(o))}}var Kd=class extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}},$x="~memo",VN=[];function ZN(e){return e!==null&&typeof e=="object"}function Rx(e){return e.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}var WN=new WeakMap,js=0,zd=1,il=2;function al(e,t,n){let r=WN.get(e);if(r!==void 0)return r?il:js;if(t.has(e))return il;t.add(e);let o=js,s=d=>{if(o!==il&&d?._zod){let p=al(d,t,n);p>o&&(o=p)}},i=(d,p)=>{let f=js;for(let h of Reflect.ownKeys(d)){let g=Object.getOwnPropertyDescriptor(d,h);if(p&&!g.enumerable)continue;let x=g.get?zd:g.value?._zod?al(g.value,t,n):js;x>f&&(f=x)}return f},a=d=>{d>o&&(o=d)},u=e._zod.def,c=u.type;switch(c){case"object":{let d=Ks(u);a(d?i(d,!0):zd),s(u.catchall);break}case"array":s(u.element);break;case"tuple":for(let d of u.items)s(d);s(u.rest);break;case"record":case"map":s(u.keyType),s(u.valueType);break;case"set":s(u.valueType);break;case"union":for(let d of u.options)s(d);break;case"intersection":s(u.left),s(u.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":s(u.innerType);break;case"pipe":s(u.in),s(u.out);break;case"function":s(u.input),s(u.output);break;case"lazy":{let d=u._cachedInner??(n?e._zod.innerType:void 0);a(d?al(d,t,!1):zd);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let d in u){let p=Object.getOwnPropertyDescriptor(u,d);if(!p||p.get)continue;let f=p.value;if(!(!f||typeof f!="object")){if(f._zod)s(f);else if(Array.isArray(f))for(let h of f)s(h)}}}return t.delete(e),yM(e,o)}function yM(e,t){return t!==zd&&WN.set(e,t===il),t}function Xd(e){return al(e,new Set,!0)!==js}function _M(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}var Dd,Fd=[],vM={alloc(e,t,n){let r=Dd;if(!r)return n;Dd=void 0;let o={value:n,issues:null};return r.set(t.value,o),Fd.push(o),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let n=e._zod.parse,r=(o,s)=>{if(s.direction!=="backward"&&Bd(s,o.value))throw new Kd;return n(o,s)};e._zod.parse=r,e._zod.run===n&&(e._zod.run=r)})},attach(e){var t;let n,r=!1,o,s;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let i=e._zod.parse,a=(u,c)=>{if(n===void 0){let v=al(e,new Set,!1);if(v===js)return e._zod.parse=i,e._zod.run===a&&(e._zod.run=i),i(u,c);v===il||r?n=!0:r=!0}let d=u.value;if(!ZN(d))return i(u,c);let p=c[$x];p||(p={buckets:new WeakMap,backEdges:void 0},c[$x]=p);let f;o===c?f=s:(f=_M(p,e),o=c,s=f);let h=f.get(d);if(h)return u.value=h.value,h.issues?h.issues.length&&u.issues.push(...Rx(h.issues)):(u.memo=!0,p.backEdges??(p.backEdges=new WeakSet),p.backEdges.add(h.value)),u;Dd=f;let g=Fd.length,x=i(u,c);Dd=void 0;let b=Fd.length>g?Fd.pop():void 0;return x instanceof Promise?x.then(v=>(b&&(b.issues=v.issues.length?Rx(v.issues):VN),v)):(b&&(b.issues=x.issues.length?Rx(x.issues):VN),x)};e._zod.parse=a,e._zod.run===i&&(e._zod.run=a)})}};function ll(){return vM}function Bd(e,t){let n=e[$x]?.backEdges;return n!==void 0&&ZN(t)&&n.has(t)}var cl={};cn(cl,{en:()=>Ud});var wM=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(s){return e[s]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function o(s,i){return s==="number"&&typeof i=="number"&&!Number.isFinite(i)?String(i):r[s]??s}return s=>{switch(s.code){case"invalid_type":{let i=o(s.expected),a=rg(s.input),u=o(a,s.input);return`Invalid input: expected ${i}, received ${u}`}case"invalid_value":return s.values.length===1?`Invalid input: expected ${Yu(s.values[0])}`:`Invalid option: expected one of ${ju(s.values,"|")}`;case"too_big":{let i=s.exact?"exactly ":s.inclusive?"<=":"<",a=t(s.origin);return a?`Too big: expected ${s.origin??"value"} to have ${i}${s.maximum.toString()} ${a.unit??"elements"}`:`Too big: expected ${s.origin??"value"} to be ${i}${s.maximum.toString()}`}case"too_small":{let i=s.exact?"exactly ":s.inclusive?">=":">",a=t(s.origin);return a?`Too small: expected ${s.origin} to have ${i}${s.minimum.toString()} ${a.unit}`:`Too small: expected ${s.origin} to be ${i}${s.minimum.toString()}`}case"invalid_format":{let i=s;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${n[i.format]??s.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${s.divisor}`;case"unrecognized_keys":return`Unrecognized key${s.keys.length>1?"s":""}: ${ju(s.keys,", ")}`;case"invalid_key":return`Invalid key in ${s.origin}`;case"invalid_union":return s.options&&Array.isArray(s.options)&&s.options.length>0?`Invalid discriminator value. Expected ${s.options.map(a=>`'${a}'`).join(" | ")}`:s.inclusive===!1?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${s.origin}`;default:return"Invalid input"}}};function Ud(){return{localeError:wM()}}var jN,Ix=Symbol("ZodOutput"),Px=Symbol("ZodInput"),Hd=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){let r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){let n=t._zod.parent;if(n){let r={...this.get(n)??{}};delete r.id;let o={...r,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function Vd(){return new Hd}(jN=globalThis).__zod_globalRegistry??(jN.__zod_globalRegistry=Vd());var at=globalThis.__zod_globalRegistry;var kt=Symbol.for("zod.compile.invalid"),QN=Symbol.for("zod.compile.fallback"),an=class extends Error{constructor(t="z.compile does not support async refinements, transforms, or checks"){super(t),this.name="ZodCompileAsyncError"}},Se=class extends Error{constructor(t,n=!0){super(`z.compile does not support ${t}; this schema must use the runtime parser`),this.name="ZodCompileUnsupportedError",this.islandable=n}};function SM(e,t){try{return Wd(e,{assertOnly:!0})}catch{return t}}function Dx(e,t){try{let n=Wd(e),r=Zd(e,n);return r._zod.bag.validator=SM(e,n),r}catch(n){if(t?.strict)throw n;return e}}function Zd(e,t){if(Xd(e))throw new Se("a schema whose subtree contains a reference cycle");let n=Te(e),r=e._zod.run,o=r.__originalRun??r,s=(i,a)=>{if(a?.async||a?.direction==="backward"||a?.skipChecks||a?.[QN]||a&&Bd(a,i.value))return o(i,a);let u=t(i.value);return u!==kt?(i.value=u,i):(a&&(a[QN]=!0),o(i,a))};return s.__originalRun=o,n._zod.bag.fallbackRun=o,n._zod.bag.validator=t,n._zod.run=s,r.__originalRun||EM(n,e,t),n}function EM(e,t,n){let r=e,o=t;if(typeof o.safeParse=="function"){let s=o.safeParse;r.safeParse=(i,a)=>{let u=n(i);return u!==kt?{success:!0,data:u}:s(i,a)}}if(typeof o.parse=="function"){let s=o.parse;r.parse=(i,a)=>{let u=n(i);return u!==kt?u:s(i,a)}}}function Wd(e,t){let n=!0;try{n=Xd(e)}catch{}if(n)throw new Se("a schema whose subtree contains a reference cycle");let r={constants:new Map,constantCounter:0,varCounter:0,definite:!0},o=new ho(["input"]),s=Be(o,r,e,"input",!t?.assertOnly);o.write(s===null?"return true;":`return ${s};`);let i=["INVALID",...r.constants.keys()],a=[kt,...r.constants.values()],u=o.content.join(`
204
+ `)}return b.write("payload.value = newResult;"),b.write("return payload;"),b.compile()},i,a=po,u=!ot.jitless,d=u&&tg.value,p=t.catchall,f;e._zod.parse=(h,g)=>{f??(f=r.value);let x=h.value;return a(x)?u&&d&&g?.async===!1&&g.jitless!==!0?(i||(i=s(t.shape)),h=i(h,g),p?VN([],x,h,g,f,e,g?.abortEarly===!0):h):n(h,g):(h.issues.push({expected:"object",code:"invalid_type",input:x,inst:e}),h)}});function CN(e,t,n,r){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter(s=>!wt(s));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(s=>s.issues.map(i=>$t(i,r,He())))}),t)}var ol=I("$ZodUnion",(e,t)=>{me.init(e,t),ve(e,"optin",r=>r.def.options.some(o=>o._zod.optin==="defaulted")?"defaulted":r.def.options.some(o=>o._zod.optin!==void 0)?"optional":void 0),ve(e,"optout",r=>r.def.options.some(o=>o._zod.optout==="optional")?"optional":void 0),ve(e,"values",r=>{if(r.def.options.every(o=>o._zod.values))return new Set(r.def.options.flatMap(o=>Array.from(o._zod.values)))}),ve(e,"pattern",r=>{if(r.def.options.every(o=>o._zod.pattern)){let o=r.def.options.map(s=>s._zod.pattern);return new RegExp(`^(${o.map(s=>Vn(s.source)).join("|")})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let s=!1,i=[];for(let a of t.options){let u=a._zod.run({value:r.value,issues:[]},o);if(u instanceof Promise)i.push(u),s=!0;else{if(u.issues.length===0)return u;i.push(u)}}return s?Promise.all(i).then(a=>CN(a,r,e,o)):CN(i,r,e,o)}});function TN(e,t,n,r){let o=[];for(let s=0;s<e.length;s++)e[s].issues.length===0&&o.push(s);return o.length===1?(t.value=e[o[0]].value,t):(o.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(s=>s.issues.map(i=>$t(i,r,He())))}):t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:[],inclusive:!1,matches:o}),t)}var ax=I("$ZodXor",(e,t)=>{ol.init(e,t),t.inclusive=!1;let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let s=!1,i=[];for(let a of t.options){let u=a._zod.run({value:r.value,issues:[]},o);u instanceof Promise?(i.push(u),s=!0):i.push(u)}return s?Promise.all(i).then(a=>TN(a,r,e,o)):TN(i,r,e,o)}});function lx(e,t){let n=e._zod,r=n.bag.optionsMap;r||(r=WN(n.def),n.bag.optionsMap=r);let o=r.get(t);if(o===null)throw new Error(`Ambiguous discriminator value "${String(t)}"`);return o}function WN(e){let t=new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let o of r)if(t.has(o)){if(o!==void 0)throw new Error(`Duplicate discriminator value "${String(o)}"`);t.set(o,null)}else t.set(o,n)}return t}var cx=I("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,ol.init(e,t);let n=e._zod.parse;ve(e,"propValues",o=>{let s={},i=0;for(let a of o.def.options){let u=a._zod.propValues;if(!u||Object.keys(u).length===0)throw new Error(`Invalid discriminated union option at index "${o.def.options.indexOf(a)}"`);u[o.def.discriminator]?.has(void 0)&&i++;for(let[c,d]of Object.entries(u)){Object.prototype.hasOwnProperty.call(s,c)||it(s,c,new Set);for(let p of d)s[c].add(p)}}return!o.def.unionFallback&&i>1&&s[o.def.discriminator]?.delete(void 0),s}),t.options.forEach((o,s)=>{let i=Xs(o._zod.def);if(i&&!Object.prototype.hasOwnProperty.call(i,t.discriminator))throw new Error(`Invalid discriminated union option at index "${s}"`)});let r=Ks(()=>WN(t));e._zod.parse=(o,s)=>{let i=o.value;if(!po(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let a=i?.[t.discriminator],u=r.value.get(a);return u&&(a!==void 0||s.direction!=="backward")?u._zod.run(o,s):t.unionFallback||s.direction==="backward"?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(c=>r.value.get(c)!==null),input:i,path:[t.discriminator],inst:e}),o)}}),ux=I("$ZodIntersection",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>{let o=n.value,s=t.left._zod.run({value:o,issues:[]},r),i=t.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([u,c])=>RN(n,u,c)):RN(n,s,i)}});function js(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Vt(e)&&Vt(t)){let n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),o={...e,...t};Object.prototype.hasOwnProperty.call(o,"__proto__")&&delete o.__proto__;for(let s of r){if(s==="__proto__")continue;let i=js(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let o=e[r],s=t[r],i=js(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function RN(e,t,n){let r=new Map,o,s=new Map,i=(c,d)=>{let p;if(c.code==="unrecognized_keys"&&!c.path?.length)o??(o=c),p=c.keys;else if(c.code==="invalid_key"&&c.origin==="record"&&c.path?.length===1){let f=String(c.path[0]);s.has(f)||s.set(f,c),p=[f]}else return!1;for(let f of p)r.has(f)||r.set(f,{}),r.get(f)[d]=!0;return!0};for(let c of t.issues)i(c,"l")||e.issues.push(c);for(let c of n.issues)i(c,"r")||e.issues.push(c);let a=[...r].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(a.length){let c=o?a.filter(d=>o.keys.includes(d)):[];c.length&&e.issues.push({...o,keys:c});for(let d of a)!c.includes(d)&&s.has(d)&&e.issues.push(s.get(d))}let u=js(t.value,n.value);if(!u.valid){if(wt(e))return e;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`)}return e.value=u.data,e}var Md=I("$ZodTuple",(e,t)=>{me.init(e,t);let n=t.items,r=ot.memoizer;r?.attach(e),e._zod.parse=(o,s)=>{let i=o.value;if(!Array.isArray(i))return o.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),o;o.value=r?r.alloc(e,o,[],s):[];let a=[],u=$N(n,"optin"),c=$N(n,"optout");if(!t.rest){if(i.length<u)return o.issues.push({code:"too_small",minimum:u,inclusive:!0,input:i,inst:e,origin:"array"}),o;i.length>n.length&&o.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:i,inst:e,origin:"array"})}let d=new Array(n.length),p=t.rest?s?.abortEarly:void 0,f=!1;for(let h=0;h<n.length;h++){let g=n[h]._zod.run({value:i[h],issues:[]},s);g instanceof Promise?a.push(g.then(x=>{d[h]=x})):(d[h]=g,p&&!f&&g.issues.length&&(f=wt(g)))}if(t.rest&&!f){let h=n.length-1,g=i.slice(n.length),x=o.issues.length;for(let b of g){if(p&&o.issues.length!==x){if(wt(o,x))break;x=o.issues.length}h++;let _=t.rest._zod.run({value:b,issues:[]},s);_ instanceof Promise?a.push(_.then(w=>IN(w,o,h))):IN(_,o,h)}}return a.length?Promise.all(a).then(()=>PN(d,o,n,i,c)):PN(d,o,n,i,c)}});function $N(e,t){for(let n=e.length-1;n>=0;n--)if(!(t==="optin"?e[n]._zod.optin!==void 0:e[n]._zod.optout==="optional"))return n+1;return 0}function IN(e,t,n){e.issues.length&&t.issues.push(...Rt(n,e.issues)),t.value[n]=e.value}function PN(e,t,n,r,o){for(let s=0;s<n.length;s++){let i=e[s],a=s<r.length;if(!a&&s>=o&&n[s]._zod.optin==="optional"){t.value.length=s;break}if(i.issues.length){if(!a&&s>=o){t.value.length=s;break}t.issues.push(...Rt(s,i.issues))}t.value[s]=i.value}for(let s=t.value.length-1;s>=r.length&&(n[s]._zod.optout==="optional"&&t.value[s]===void 0);s--)t.value.length=s;return t}var dx=I("$ZodRecord",(e,t)=>{me.init(e,t);let n=ot.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let s=r.value;if(!Vt(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),r;let i=[],a=t.keyType._zod.values;if(a&&!t.partial){r.value=n?n.alloc(e,r,{},o):{};let u=new Set;for(let d of a)if(typeof d=="string"||typeof d=="number"||typeof d=="symbol"){if(u.add(typeof d=="number"?d.toString():d),d==="__proto__")continue;let p=t.keyType._zod.run({value:d,issues:[]},o);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(p.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map(g=>$t(g,o,He())),input:d,path:[d],inst:e});continue}let f=p.value;if(f==="__proto__")continue;let h=t.valueType._zod.run({value:s[d],issues:[]},o);h instanceof Promise?i.push(h.then(g=>{g.issues.length&&r.issues.push(...Rt(d,g.issues)),r.value[f]=g.value})):(h.issues.length&&r.issues.push(...Rt(d,h.issues)),r.value[f]=h.value)}let c;for(let d in s)if(!u.has(d))if(t.mode==="loose"){if(d==="__proto__")continue;r.value[d]=s[d]}else c=c??[],c.push(d);c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:c,continue:!0})}else{r.value=n?n.alloc(e,r,{},o):{};let u;for(let c of Reflect.ownKeys(s)){if(c==="__proto__"||!Object.prototype.propertyIsEnumerable.call(s,c))continue;let d=t.keyType._zod.run({value:c,issues:[]},o);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof c=="string"&&Zn.test(c)&&d.issues.length){let g=t.keyType._zod.run({value:Number(c),issues:[]},o);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");g.issues.length===0&&(d=g)}if(d.issues.length){t.mode==="loose"?r.value[c]=s[c]:a?(u=u??[],u.push(c)):r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(g=>$t(g,o,He())),input:c,path:[c],inst:e});continue}let f=d.value;if(f==="__proto__")continue;let h=t.valueType._zod.run({value:s[c],issues:[]},o);h instanceof Promise?i.push(h.then(g=>{g.issues.length&&r.issues.push(...Rt(c,g.issues)),r.value[f]=g.value})):(h.issues.length&&r.issues.push(...Rt(c,h.issues)),r.value[f]=h.value)}u&&u.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:u,continue:!0})}return i.length?Promise.all(i).then(()=>r):r}}),px=I("$ZodMap",(e,t)=>{me.init(e,t);let n=ot.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let s=r.value;if(!(s instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:s,inst:e}),r;let i=[];r.value=n?n.alloc(e,r,new Map,o):new Map;let a=o?.abortEarly,u=r.issues.length;for(let[c,d]of s){if(a&&r.issues.length!==u){if(wt(r,u))break;u=r.issues.length}let p=t.keyType._zod.run({value:c,issues:[]},o),f=t.valueType._zod.run({value:d,issues:[]},o);p instanceof Promise||f instanceof Promise?i.push(Promise.all([p,f]).then(([h,g])=>{ON(h,g,r,c,s,e,o)})):ON(p,f,r,c,s,e,o)}return i.length?Promise.all(i).then(()=>r):r}});function ON(e,t,n,r,o,s,i){e.issues.length&&(Fa.has(typeof r)?n.issues.push(...Rt(r,e.issues)):n.issues.push({code:"invalid_key",origin:"map",input:o,inst:s,issues:e.issues.map(a=>$t(a,i,He()))})),t.issues.length&&(Fa.has(typeof r)?n.issues.push(...Rt(r,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:o,inst:s,key:r,issues:t.issues.map(a=>$t(a,i,He()))})),n.value.set(e.value,t.value)}var fx=I("$ZodSet",(e,t)=>{me.init(e,t);let n=ot.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let s=r.value;if(!(s instanceof Set))return r.issues.push({input:s,inst:e,expected:"set",code:"invalid_type"}),r;let i=[];r.value=n?n.alloc(e,r,new Set,o):new Set;let a=o?.abortEarly,u=r.issues.length;for(let c of s){if(a&&r.issues.length!==u){if(wt(r,u))break;u=r.issues.length}let d=t.valueType._zod.run({value:c,issues:[]},o);d instanceof Promise?i.push(d.then(p=>LN(p,r))):LN(d,r)}return i.length?Promise.all(i).then(()=>r):r}});function LN(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}var hx=I("$ZodEnum",(e,t)=>{me.init(e,t);let n=Fs(t.entries),r=new Set(n);e._zod.values=r,ve(e,"pattern",o=>{let s=Fs(o.def.entries).filter(i=>Fa.has(typeof i));return new RegExp(s.length?`^(${s.map(i=>Zt(i.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,s)=>{let i=o.value;return r.has(i)||o.issues.push({code:"invalid_value",values:n,input:i,inst:e}),o}}),mx=I("$ZodLiteral",(e,t)=>{me.init(e,t);let n=new Set(t.values);e._zod.values=n,ve(e,"pattern",r=>{let o=r.def.values;return new RegExp(o.length?`^(${o.map(s=>typeof s=="string"?Zt(s):s?Zt(s.toString()):String(s)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,o)=>{let s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),r}}),gx=I("$ZodFile",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;return o instanceof File||n.issues.push({expected:"file",code:"invalid_type",input:o,inst:e}),n}}),xx=I("$ZodTransform",(e,t)=>{me.init(e,t),e._zod.optin="optional",ot.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new br(e.constructor.name);let o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n));if(o instanceof Promise)throw new It;return n.value=o,n}});function MN(e,t){return e.value=t.issues.length?void 0:t.value,e}var Dd=I("$ZodOptional",(e,t)=>{me.init(e,t),ve(e,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",ve(e,"values",n=>{let r=n.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),ve(e,"pattern",n=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${Vn(r.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;let o=t.innerType._zod.run({value:n.value,issues:[]},r);return o instanceof Promise?o.then(s=>MN(n,s)):MN(n,o)}return t.innerType._zod.run(n,r)}}),bx=I("$ZodExactOptional",(e,t)=>{Dd.init(e,t),ve(e,"values",n=>n.def.innerType._zod.values),ve(e,"pattern",n=>n.def.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),yx=I("$ZodNullable",(e,t)=>{me.init(e,t),ve(e,"optin",n=>n.def.innerType._zod.optin),ve(e,"optout",n=>n.def.innerType._zod.optout),ve(e,"pattern",n=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${Vn(r.source)}|null)$`):void 0}),ve(e,"values",n=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),_x=I("$ZodDefault",(e,t)=>{me.init(e,t),e._zod.optin="defaulted",ve(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>DN(s,t)):DN(o,t)}});function DN(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var vx=I("$ZodPrefault",(e,t)=>{me.init(e,t),e._zod.optin="defaulted",ve(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),wx=I("$ZodNonOptional",(e,t)=>{me.init(e,t),ve(e,"values",n=>{let r=n.def.innerType._zod.values;return r?new Set([...r].filter(o=>o!==void 0)):void 0}),e._zod.parse=(n,r)=>{let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>FN(s,e)):FN(o,e)}});function FN(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var kx=I("$ZodSuccess",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new br("ZodSuccess");let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.issues.length===0,n)):(n.value=o.issues.length===0,n)}});function zN(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(o=>$t(o,r,He()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var Sx=I("$ZodCatch",(e,t)=>{me.init(e,t),ve(e,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),ve(e,"optout",n=>n.def.innerType._zod.optout),ve(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run({value:n.value,issues:[]},r);return o instanceof Promise?o.then(s=>zN(n,s,t,r)):zN(n,o,t,r)}}),Ex=I("$ZodNaN",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>((typeof n.value!="number"||!Number.isNaN(n.value))&&n.issues.push({input:n.value,inst:e,expected:"nan",code:"invalid_type"}),n)}),Fd=I("$ZodPipe",(e,t)=>{me.init(e,t),ve(e,"values",n=>n.def.in._zod.values),ve(e,"optin",n=>n.def.in._zod.optin),ve(e,"optout",n=>n.def.out._zod.optout),ve(e,"propValues",n=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let s=t.out._zod.run(n,r);return s instanceof Promise?s.then(i=>_d(i,t.in,r)):_d(s,t.in,r)}let o=t.in._zod.run(n,r);return o instanceof Promise?o.then(s=>_d(s,t.out,r)):_d(o,t.out,r)}});function _d(e,t,n){return e.issues.some(r=>r.code!=="unrecognized_keys")?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var sl=I("$ZodCodec",(e,t)=>{me.init(e,t),ve(e,"values",n=>n.def.in._zod.values),ve(e,"optin",n=>n.def.in._zod.optin),ve(e,"optout",n=>n.def.out._zod.optout),ve(e,"propValues",n=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if((r.direction||"forward")==="forward"){let s=t.in._zod.run(n,r);return s instanceof Promise?s.then(i=>vd(i,t,r)):vd(s,t,r)}else{let s=t.out._zod.run(n,r);return s instanceof Promise?s.then(i=>vd(i,t,r)):vd(s,t,r)}}});function vd(e,t,n){if(e.issues.length)return e.aborted=!0,e;if((n.direction||"forward")==="forward"){let o=t.transform(e.value,e);return o instanceof Promise?o.then(s=>wd(e,s,t.out,n)):wd(e,o,t.out,n)}else{let o=t.reverseTransform(e.value,e);return o instanceof Promise?o.then(s=>wd(e,s,t.in,n)):wd(e,o,t.in,n)}}function wd(e,t,n,r){return e.issues.length?(e.aborted=!0,e):n._zod.run({value:t,issues:e.issues},r)}var Nx=I("$ZodPreprocess",(e,t)=>{Fd.init(e,t)}),Ax=I("$ZodReadonly",(e,t)=>{me.init(e,t),ve(e,"propValues",n=>n.def.innerType._zod.propValues),ve(e,"values",n=>n.def.innerType._zod.values),ve(e,"optin",n=>n.def.innerType?._zod?.optin),ve(e,"optout",n=>n.def.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(KN):KN(o)}});function KN(e){return e.memo||(e.value=Object.freeze(e.value)),e}function wM(e){let t=e._zod.def,n=t.pattern,r=!!t.format?.includes("int"),o,s;for(let a of t.checks??[]){let u=a._zod.def;u.pattern&&(n=u.pattern),r||(r=!!u.format?.includes("int"));let c=u.minimum??u.length,d=u.maximum??u.length;c!==void 0&&(o===void 0||c>o)&&(o=c),d!==void 0&&(s===void 0||d<s)&&(s=d)}if(n)return n.source;if(o!==void 0&&s!==void 0&&o>s)return"(?!)";if(o!==void 0||s!==void 0)return Ug({minimum:o,maximum:s}).source;let i=e._zod.pattern;return(r&&i===Zn?Qa:i)?.source}function y0(e){let t=e._zod.def,n=e._zod.pattern?.source,r=t.innerType??e._zod.innerType;if(r){let o=r._zod.pattern?.source,s=y0(r);return n&&o&&s&&s!==o?n.replace(Vn(o),()=>Vn(s)):n}if(t.options){let o=t.options.map(y0);if(o.every(Boolean))return`^(${o.map(s=>Vn(s)).join("|")})$`}return wM(e)}var Cx=I("$ZodTemplateLiteral",(e,t)=>{me.init(e,t);let n=[];for(let r of t.parts)if(typeof r=="object"&&r!==null){let o=y0(r);if(!o)throw new Error(`Invalid template literal part, no pattern found: ${[...r._zod.traits].shift()}`);n.push(Vn(o))}else if(r===null||ng.has(typeof r))n.push(Zt(`${r}`));else throw new Error(`Invalid template literal part: ${r}`);e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(r,o)=>typeof r.value!="string"?(r.issues.push({input:r.value,inst:e,expected:"string",code:"invalid_type"}),r):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(r.value)||r.issues.push({input:r.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),r)}),Tx=I("$ZodFunction",(e,t)=>(me.init(e,t),Object.defineProperty(e,"_def",{value:t}),e._zod.def=t,e.implement=n=>{if(typeof n!="function")throw new Error("implement() must be called with a function");return Object.defineProperty(function(...r){let o=e._def.input?od(e._def.input,r):r,s=Reflect.apply(n,this,o);return e._def.output?od(e._def.output,s):s},"_zod",{value:e._zod,enumerable:!1})},e.implementAsync=n=>{if(typeof n!="function")throw new Error("implementAsync() must be called with a function");return Object.defineProperty(async function(...r){let o=e._def.input?await sd(e._def.input,r):r,s=await Reflect.apply(n,this,o);return e._def.output?await sd(e._def.output,s):s},"_zod",{value:e._zod,enumerable:!1})},e._zod.parse=(n,r)=>typeof n.value!="function"?(n.issues.push({code:"invalid_type",expected:"function",input:n.value,inst:e}),n):(e._def.output&&e._def.output._zod.def.type==="promise"?n.value=e.implementAsync(n.value):n.value=e.implement(n.value),n),e.input=(...n)=>{let r=e.constructor;return Array.isArray(n[0])?new r({type:"function",input:new Md({type:"tuple",items:n[0],rest:n[1]}),output:e._def.output}):new r({type:"function",input:n[0],output:e._def.output})},e.output=n=>{let r=e.constructor;return new r({type:"function",input:e._def.input,output:n})},e)),Rx=I("$ZodPromise",(e,t)=>{me.init(e,t),e._zod.parse=(n,r)=>Promise.resolve(n.value).then(o=>t.innerType._zod.run({value:o,issues:[]},r))}),il=I("$ZodLazy",(e,t)=>{me.init(e,t),Jm(e._zod,"innerType",()=>{let n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),ve(e,"pattern",n=>n.innerType?._zod?.pattern),ve(e,"propValues",n=>n.innerType?._zod?.propValues),ve(e,"optin",n=>n.innerType?._zod?.optin??void 0),ve(e,"optout",n=>n.innerType?._zod?.optout??void 0),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),$x=I("$ZodCustom",(e,t)=>{Fe.init(e,t),me.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{let r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(s=>XN(s,n,r,e));XN(o,n,r,e)}});function XN(e,t,n,r){if(!e){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(Bs(o))}}var Bd=class extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}},Px="~memo",QN=[];function GN(e){return e!==null&&typeof e=="object"}function Ix(e){return e.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}var YN=new WeakMap,Qs=0,Xd=1,al=2;function ll(e,t,n){let r=YN.get(e);if(r!==void 0)return r?al:Qs;if(t.has(e))return al;t.add(e);let o=Qs,s=d=>{if(o!==al&&d?._zod){let p=ll(d,t,n);p>o&&(o=p)}},i=(d,p)=>{let f=Qs;for(let h of Reflect.ownKeys(d)){let g=Object.getOwnPropertyDescriptor(d,h);if(p&&!g.enumerable)continue;let x=g.get?Xd:g.value?._zod?ll(g.value,t,n):Qs;x>f&&(f=x)}return f},a=d=>{d>o&&(o=d)},u=e._zod.def,c=u.type;switch(c){case"object":{let d=Xs(u);a(d?i(d,!0):Xd),s(u.catchall);break}case"array":s(u.element);break;case"tuple":for(let d of u.items)s(d);s(u.rest);break;case"record":case"map":s(u.keyType),s(u.valueType);break;case"set":s(u.valueType);break;case"union":for(let d of u.options)s(d);break;case"intersection":s(u.left),s(u.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":s(u.innerType);break;case"pipe":s(u.in),s(u.out);break;case"function":s(u.input),s(u.output);break;case"lazy":{let d=u._cachedInner??(n?e._zod.innerType:void 0);a(d?ll(d,t,!1):Xd);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let d in u){let p=Object.getOwnPropertyDescriptor(u,d);if(!p||p.get)continue;let f=p.value;if(!(!f||typeof f!="object")){if(f._zod)s(f);else if(Array.isArray(f))for(let h of f)s(h)}}}return t.delete(e),kM(e,o)}function kM(e,t){return t!==Xd&&YN.set(e,t===al),t}function Ud(e){return ll(e,new Set,!0)!==Qs}function SM(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}var zd,Kd=[],EM={alloc(e,t,n){let r=zd;if(!r)return n;zd=void 0;let o={value:n,issues:null};return r.set(t.value,o),Kd.push(o),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let n=e._zod.parse,r=(o,s)=>{if(s.direction!=="backward"&&Hd(s,o.value))throw new Bd;return n(o,s)};e._zod.parse=r,e._zod.run===n&&(e._zod.run=r)})},attach(e){var t;let n,r=!1,o,s;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let i=e._zod.parse,a=(u,c)=>{if(n===void 0){let _=ll(e,new Set,!1);if(_===Qs)return e._zod.parse=i,e._zod.run===a&&(e._zod.run=i),i(u,c);_===al||r?n=!0:r=!0}let d=u.value;if(!GN(d))return i(u,c);let p=c[Px];p||(p={buckets:new WeakMap,backEdges:void 0},c[Px]=p);let f;o===c?f=s:(f=SM(p,e),o=c,s=f);let h=f.get(d);if(h)return u.value=h.value,h.issues?h.issues.length&&u.issues.push(...Ix(h.issues)):(u.memo=!0,p.backEdges??(p.backEdges=new WeakSet),p.backEdges.add(h.value)),u;zd=f;let g=Kd.length,x=i(u,c);zd=void 0;let b=Kd.length>g?Kd.pop():void 0;return x instanceof Promise?x.then(_=>(b&&(b.issues=_.issues.length?Ix(_.issues):QN),_)):(b&&(b.issues=x.issues.length?Ix(x.issues):QN),x)};e._zod.parse=a,e._zod.run===i&&(e._zod.run=a)})}};function cl(){return EM}function Hd(e,t){let n=e[Px]?.backEdges;return n!==void 0&&GN(t)&&n.has(t)}var ul={};un(ul,{en:()=>Vd});var NM=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(s){return e[s]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function o(s,i){return s==="number"&&typeof i=="number"&&!Number.isFinite(i)?String(i):r[s]??s}return s=>{switch(s.code){case"invalid_type":{let i=o(s.expected),a=sg(s.input),u=o(a,s.input);return`Invalid input: expected ${i}, received ${u}`}case"invalid_value":return s.values.length===1?`Invalid input: expected ${Ju(s.values[0])}`:`Invalid option: expected one of ${Gu(s.values,"|")}`;case"too_big":{let i=s.exact?"exactly ":s.inclusive?"<=":"<",a=t(s.origin);return a?`Too big: expected ${s.origin??"value"} to have ${i}${s.maximum.toString()} ${a.unit??"elements"}`:`Too big: expected ${s.origin??"value"} to be ${i}${s.maximum.toString()}`}case"too_small":{let i=s.exact?"exactly ":s.inclusive?">=":">",a=t(s.origin);return a?`Too small: expected ${s.origin} to have ${i}${s.minimum.toString()} ${a.unit}`:`Too small: expected ${s.origin} to be ${i}${s.minimum.toString()}`}case"invalid_format":{let i=s;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${n[i.format]??s.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${s.divisor}`;case"unrecognized_keys":return`Unrecognized key${s.keys.length>1?"s":""}: ${Gu(s.keys,", ")}`;case"invalid_key":return`Invalid key in ${s.origin}`;case"invalid_union":return s.options&&Array.isArray(s.options)&&s.options.length>0?`Invalid discriminator value. Expected ${s.options.map(a=>`'${a}'`).join(" | ")}`:s.inclusive===!1?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${s.origin}`;default:return"Invalid input"}}};function Vd(){return{localeError:NM()}}var qN,Ox=Symbol("ZodOutput"),Lx=Symbol("ZodInput"),Zd=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){let r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){let n=t._zod.parent;if(n){let r={...this.get(n)??{}};delete r.id;let o={...r,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function Wd(){return new Zd}(qN=globalThis).__zod_globalRegistry??(qN.__zod_globalRegistry=Wd());var at=globalThis.__zod_globalRegistry;var kt=Symbol.for("zod.compile.invalid"),JN=Symbol.for("zod.compile.fallback"),ln=class extends Error{constructor(t="z.compile does not support async refinements, transforms, or checks"){super(t),this.name="ZodCompileAsyncError"}},Se=class extends Error{constructor(t,n=!0){super(`z.compile does not support ${t}; this schema must use the runtime parser`),this.name="ZodCompileUnsupportedError",this.islandable=n}};function CM(e,t){try{return Qd(e,{assertOnly:!0})}catch{return t}}function zx(e,t){try{let n=Qd(e),r=jd(e,n);return r._zod.bag.validator=CM(e,n),r}catch(n){if(t?.strict)throw n;return e}}function jd(e,t){if(Ud(e))throw new Se("a schema whose subtree contains a reference cycle");let n=Te(e),r=e._zod.run,o=r.__originalRun??r,s=(i,a)=>{if(a?.async||a?.direction==="backward"||a?.skipChecks||a?.[JN]||a&&Hd(a,i.value))return o(i,a);let u=t(i.value);return u!==kt?(i.value=u,i):(a&&(a[JN]=!0),o(i,a))};return s.__originalRun=o,n._zod.bag.fallbackRun=o,n._zod.bag.validator=t,n._zod.run=s,r.__originalRun||TM(n,e,t),n}function TM(e,t,n){let r=e,o=t;if(typeof o.safeParse=="function"){let s=o.safeParse;r.safeParse=(i,a)=>{let u=n(i);return u!==kt?{success:!0,data:u}:s(i,a)}}if(typeof o.parse=="function"){let s=o.parse;r.parse=(i,a)=>{let u=n(i);return u!==kt?u:s(i,a)}}}function Qd(e,t){let n=!0;try{n=Ud(e)}catch{}if(n)throw new Se("a schema whose subtree contains a reference cycle");let r={constants:new Map,constantCounter:0,varCounter:0,definite:!0},o=new mo(["input"]),s=Be(o,r,e,"input",!t?.assertOnly);o.write(s===null?"return true;":`return ${s};`);let i=["INVALID",...r.constants.keys()],a=[kt,...r.constants.values()],u=o.content.join(`
205
205
  `),c=t?.debug?i.length>0?`// Constants: ${i.join(", ")}
206
206
  ${u}`:u:"",d=Function,p=`return (input) => {
207
207
  ${u}
208
- }`,f;try{f=new d(...i,p)(...a)}catch(h){throw new Se(`this schema (generated code failed to evaluate: ${h.message})`)}return t?.debug&&(f.code=c),f.definite=r.definite,f}function fe(e,t){for(let[r,o]of e.constants)if(o===t)return r;let n=`c${e.constantCounter++}`;return e.constants.set(n,t),n}function bo(e,t){return e.definite=!1,fe(e,t)}function ce(e){return`v${e.varCounter++}`}function NM(e,t){let n=e._zod.run({value:t,issues:[]},{});if(n&&typeof n.then=="function")return kt;let r=n;return r.issues.length===0?r.value:kt}function ht(e,t,n,r,o=!0){let s=e.content.length,i=t.constants.size,a=t.constantCounter,u=t.varCounter;try{return Be(e,t,n,r,o)}catch(c){if(!(c instanceof Se)||!c.islandable)throw c;if(e.content.length=s,t.constants.size>i){let d=Array.from(t.constants.keys()).slice(i);for(let p of d)t.constants.delete(p)}return t.constantCounter=a,t.varCounter=u,AM(e,t,n,r)}}function AM(e,t,n,r){t.definite=!1;let o=fe(t,n),s=fe(t,NM),i=ce(t);return e.write(`const ${i} = ${s}(${o}, ${r});`),e.write(`if (${i} === INVALID) return INVALID;`),i}var CM=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function TM(e,t,n,r){let o=n._zod.def.checks;if(!o||o.length===0)return r;let s=r;for(let i of o){let a=i._zod.def;if(a.when&&!CM.has(a.check))throw new Se('check with a custom "when" condition');switch(a.check){case"greater_than":RM(e,t,a,s);break;case"less_than":$M(e,t,a,s);break;case"multiple_of":IM(e,t,a,s);break;case"number_format":tA(e,a,s);break;case"min_length":{let u=go(a.minimum,"min_length"),c=Ox(e,t,s,`${s}.length >= ${u} && ${s}.length < ${a.minimum*2}`);e.write(`if (${c} < ${u}) return INVALID;`);break}case"max_length":{let u=go(a.maximum,"max_length"),c=Ox(e,t,s,`${s}.length > ${u}`);e.write(`if (${c} > ${u}) return INVALID;`);break}case"length_equals":{let u=go(a.length,"length_equals"),c=Ox(e,t,s,`${s}.length >= ${u} && ${s}.length <= ${a.length*2}`);e.write(`if (${c} !== ${u}) return INVALID;`);break}case"min_size":e.write(`if (${s}.size < ${go(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${s}.size > ${go(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${s}.size !== ${go(a.size,"size_equals")}) return INVALID;`);break;case"string_format":s=nA(e,t,a,s);break;case"custom":s=FM(e,t,i,s);break;case"bigint_format":PM(e,a,s);break;case"mime_type":OM(e,t,a,s);break;case"property":MM(e,t,a,s);break;case"properties":LM(e,t,a,s);break;case"overwrite":{let u=ce(t);DM(e,t,i,s,u),s=u;break}default:throw new Se(`check type ${a.check}`)}}return s}function Ox(e,t,n,r){let o=fe(t,po),s=ce(t);return e.write(`const ${s} = typeof ${n} === "string" && ${r} ? ${o}(${n}) : ${n}.length;`),s}function go(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new Se(`${t} bound of type ${typeof e}`);return`${e}`}function eA(e,t){if(typeof t=="bigint")return`${t}n`;if(typeof t=="number"){if(Number.isNaN(t))throw new Se("comparison check with NaN bound");return`${t}`}if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new Se("comparison check with Invalid Date bound");return fe(e,t)}throw new Se(`comparison check bound of type ${typeof t}`)}function RM(e,t,n,r){let o=n.inclusive?"<":"<=";e.write(`if (${r} ${o} ${eA(t,n.value)}) return INVALID;`)}function $M(e,t,n,r){let o=n.inclusive?">":">=";e.write(`if (${r} ${o} ${eA(t,n.value)}) return INVALID;`)}function IM(e,t,n,r){if(typeof n.value=="bigint"){if(n.value===BigInt(0))throw new Se("multiple_of check with a zero divisor");e.write(`if (${r} % ${n.value}n !== 0n) return INVALID;`)}else{let o=fe(t,La);e.write(`if (${o}(${r}, ${go(n.value,"multiple_of")}) !== 0) return INVALID;`)}}function tA(e,t,n){let r=t.format;switch(r){case"safeint":e.write(`if (!Number.isSafeInteger(${n})) return INVALID;`);break;case"int32":e.write(`if (!Number.isInteger(${n}) || ${n} < -2147483648 || ${n} > 2147483647) return INVALID;`);break;case"uint32":e.write(`if (!Number.isInteger(${n}) || ${n} < 0 || ${n} > 4294967295) return INVALID;`);break;case"float32":e.write(`if (!Number.isFinite(${n}) || ${n} < -3.4028234663852886e38 || ${n} > 3.4028234663852886e38) return INVALID;`);break;case"float64":e.write(`if (!Number.isFinite(${n})) return INVALID;`);break;default:throw new Se(`number format ${r}`)}}function PM(e,t,n){let r=t.format;if(r)switch(r){case"int64":e.write(`if (${n} < -9223372036854775808n || ${n} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${n} < 0n || ${n} > 18446744073709551615n) return INVALID;`);break;default:throw new Se(`bigint format ${r}`)}}function OM(e,t,n,r){let o=n.mime;if(o&&o.length>0){let s=fe(t,new Set(o));e.write(`if (!${s}.has(${r}.type)) return INVALID;`)}}function LM(e,t,n,r){if(n.when)throw new Se('check with a custom "when" condition');e.write(`if (${r} == null) return INVALID;`);let o=n.shape;for(let s of Reflect.ownKeys(o)){let i=typeof s=="symbol"?fe(t,s):vt(s),a=ce(t);e.write(`const ${a} = ${r}[${i}];`),ht(e,t,o[s],a,!1)}}function MM(e,t,n,r){let o=`${r}[${JSON.stringify(n.property)}]`;Be(e,t,n.schema,o)}function DM(e,t,n,r,o){let s=n._zod.def.tx;if(!s)throw new Se("overwrite check without a transform function");if(yo(s))throw new an("z.compile: async overwrite transforms are not supported");let i=fe(t,s);e.write(`const ${o} = ${i}(${r});`)}function Lx(){throw new It}function Fx(e){this.issues.push(e)}function FM(e,t,n,r){let o=n._zod.def;if(o.fn){if(yo(o.fn))throw new an("z.compile: async .refine() predicates are not supported");let s=bo(t,o.fn),i=fe(t,Lx),a=ce(t);return e.write(`const ${a} = ${s}(${r});`),e.write(`if (${a} instanceof Promise) ${i}();`),e.write(`if (!${a}) return INVALID;`),r}if(n._zod.check){if(yo(n._zod.check))throw new an("z.compile: async .superRefine() / check functions are not supported");let s=n._zod.check,a=bo(t,c=>{let d={value:c,issues:[],addIssue:Fx};return s(d)instanceof Promise&&Lx(),d.issues.length===0?d.value:kt}),u=ce(t);return e.write(`const ${u} = ${a}(${r});`),e.write(`if (${u} === INVALID) return INVALID;`),u}throw new Se("custom check without a predicate or check function")}var zM=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function nA(e,t,n,r,o=!0){let s=n.format;if(s==="base64"){let c=fe(t,el);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(s==="base64url"){let c=fe(t,Cd);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(s==="jwt"){let c=fe(t,$d),d=fe(t,n.alg??null);return e.write(`if (!${c}(${r}, ${d})) return INVALID;`),r}if(s==="ipv6"){let c=fe(t,Ja);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(s==="cidrv6"){let c=fe(t,Nd);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(s==="credit_card"){let c=fe(t,Td);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(s==="iban"){let c=fe(t,Rd);return e.write(`if (!${c}(${r})) return INVALID;`),r}let i=n;if(s==="url"||s==="httpurl"||i.normalize||i.hostname!==void 0||i.protocol!==void 0){let c=fe(t,kd),d=fe(t,n),p=ce(t),f=ce(t);if(e.write(`const ${p} = ${r}.trim();`),e.write(`const ${f} = ${c}(${p}, ${d});`),e.write(`if (typeof ${f} === "number") return INVALID;`),i.hostname!==void 0){let x=fe(t,Sd);e.write(`if (!${x}(${f}, ${d}.hostname)) return INVALID;`)}if(i.protocol!==void 0){let x=fe(t,Ed);e.write(`if (!${x}(${f}, ${d}.protocol)) return INVALID;`)}if(!o)return null;let h=ce(t),g=i.normalize?`${f}.href`:`${fe(t,qa)}(${p})`;return e.write(`const ${h} = ${g};`),h}let a=n.fn;if(a){if(yo(a))throw new Se(`async string format ${s}`);let c=fe(t,a);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(zM.has(s)&&n.pattern){let c=fe(t,n.pattern);return e.write(`${c}.lastIndex = 0;`),e.write(`if (!${c}.test(${r})) return INVALID;`),r}let u=n.format;switch(u){case"regex":throw new Se("regex format without a pattern");case"lowercase":e.write(`if (${r} !== ${r}.toLowerCase()) return INVALID;`);break;case"uppercase":e.write(`if (${r} !== ${r}.toUpperCase()) return INVALID;`);break;case"includes":e.write(`if (!${r}.includes(${vt(n.includes)})) return INVALID;`);break;case"starts_with":{let c=n.prefix;e.write(`if (${r}.slice(0, ${c.length}) !== ${vt(c)}) return INVALID;`);break}case"ends_with":{let c=n.suffix;e.write(`if (${r}.slice(-${c.length}) !== ${vt(c)}) return INVALID;`);break}default:throw new Se(`string format ${u}`)}return r}function Be(e,t,n,r,o=!0){let s=n._zod.def,i=s.type;if(s.coerce)throw new Se(`coercion (z.coerce.${i}())`);let a=o||!!s.checks?.length,u;switch(i){case"string":u=KM(e,t,n,r,a);break;case"number":u=XM(e,n,r);break;case"boolean":u=BM(e,r);break;case"bigint":u=UM(e,n,r);break;case"symbol":u=HM(e,r);break;case"undefined":u=VM(e,r);break;case"null":u=ZM(e,r);break;case"any":case"unknown":u=r;break;case"never":e.write("return INVALID;"),u=r;break;case"void":u=WM(e,r);break;case"nan":u=jM(e,r);break;case"date":u=QM(e,r);break;case"object":u=GM(e,t,n,r,a);break;case"optional":u=YM(e,t,n,r,a);break;case"nullable":u=eD(e,t,n,r,a);break;case"array":u=tD(e,t,n,r,a);break;case"literal":u=nD(e,t,n,r);break;case"enum":u=rD(e,t,n,r);break;case"readonly":{let c=YN(e,t,n,r),d=ce(t);e.write(`const ${d} = Object.freeze(${c});`),u=d;break}case"success":YN(e,t,n,r),u="true";break;case"default":case"prefault":u=oD(e,t,n,r);break;case"nonoptional":u=sD(e,t,n,r);break;case"tuple":u=iD(e,t,n,r);break;case"union":u=aD(e,t,n,r);break;case"intersection":u=uD(e,t,n,r);break;case"record":u=dD(e,t,n,r);break;case"map":u=fD(e,t,n,r);break;case"set":u=hD(e,t,n,r);break;case"file":u=mD(e,r);break;case"template_literal":u=gD(e,t,n,r);break;case"lazy":u=xD(e,t,n,r);break;case"pipe":u=bD(e,t,n,r);break;case"custom":u=yD(e,t,n,r);break;case"transform":u=wD(e,t,n,r);break;case"catch":u=vD(e,t,n,r);break;default:throw new Se(`schema type ${i}`)}return u===null?null:TM(e,t,n,u)}function KM(e,t,n,r,o=!0){e.write(`if (typeof ${r} !== "string") return INVALID;`);let s=n._zod.def;return s.format===void 0?r:nA(e,t,s,r,o)}function XM(e,t,n){e.write(`if (typeof ${n} !== "number" || !Number.isFinite(${n})) return INVALID;`);let r=t._zod.def;return r.check==="number_format"&&r.format&&tA(e,{format:r.format},n),n}function BM(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function UM(e,t,n){e.write(`if (typeof ${n} !== "bigint") return INVALID;`);let r=t._zod.def;if(r.format)switch(r.format){case"int64":e.write(`if (${n} < -9223372036854775808n || ${n} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${n} < 0n || ${n} > 18446744073709551615n) return INVALID;`);break}return n}function HM(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function VM(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function ZM(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function WM(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function jM(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function QM(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function GM(e,t,n,r,o=!0){let s=n._zod.def;e.write(`if (typeof ${r} !== "object" || ${r} === null || Array.isArray(${r})) return INVALID;`);let i=s.shape,a=Object.keys(i),u=Object.getOwnPropertySymbols(i),c=u.length?[...a,...u]:a,d=w=>typeof w=="symbol"?fe(t,w):vt(w),p=w=>typeof w=="symbol"?`[${d(w)}]`:vt(w),f=i;if(a.includes("__proto__"))throw new Se('object shape key "__proto__"');let h=new Map;for(let w of c){let C=f[w],y=d(w),T=ce(t);if(e.write(`const ${T} = ${r}[${y}];`),C._zod.optin!==void 0){let N=ce(t);e.write(`let ${N} = (() => {`),e.indented(S=>{let $=ht(S,t,C,T);S.write(`return ${$};`)}),e.write("})();"),C._zod.optout==="optional"?(e.write(`if (${N} === INVALID) {`),e.indented(S=>{S.write(`if (${y} in ${r}) return INVALID;`),S.write(`${N} = undefined;`)}),e.write("}")):e.write(`if (${N} === INVALID) return INVALID;`),h.set(w,N)}else{JM(C)&&e.write(`if (!(${y} in ${r})) return INVALID;`);let N=ht(e,t,C,T,o);N!==null&&h.set(w,N)}}let g=s.catchall,x="none";if(g){let w=g._zod.def.type;if(w==="never"){let C=a.map(y=>`k !== ${vt(y)}`).join(" && ")||"true";e.write(`for (const k in ${r}) {`),e.indented(y=>{y.write(`if (${C}) return INVALID;`)}),e.write("}")}else(w==="unknown"||w==="any")&&!g._zod.def.checks?.length?x="passthrough":x="schema"}let b=ce(t),v=c.some(w=>GN(f[w])||Mx(f[w]));if(!o){if(x==="schema"){let w=a.length>0?fe(t,new Set(a)):null;e.write(`for (const k in ${r}) {`),e.indented(C=>{C.write('if (k === "__proto__") continue;'),w&&C.write(`if (${w}.has(k)) continue;`);let y=ce(t);C.write(`const ${y} = ${r}[k];`),ht(C,t,g,y,!1)}),e.write("}")}return null}if(v){e.write(`const ${b} = {};`);for(let w of c){let C=d(w),y=h.get(w);Mx(f[w])?e.write(`if (${C} in ${r}) ${b}[${C}] = ${y};`):GN(f[w])?e.write(`if (${y} !== undefined || ${C} in ${r}) ${b}[${C}] = ${y};`):e.write(`${b}[${C}] = ${y};`)}}else{let w=c.map(C=>`${p(C)}: ${h.get(C)}`).join(", ");e.write(`const ${b} = { ${w} };`)}if(x!=="none"){let w=a.length>0?fe(t,new Set(a)):null;e.write(`for (const k in ${r}) {`),e.indented(C=>{if(C.write('if (k === "__proto__") continue;'),w&&C.write(`if (${w}.has(k)) continue;`),x==="passthrough")C.write(`${b}[k] = ${r}[k];`);else{let y=ce(t);C.write(`const ${y} = ${r}[k];`);let T=ht(C,t,g,y);C.write(`${b}[k] = ${T};`)}}),e.write("}")}return b}function YM(e,t,n,r,o=!0){let s=n._zod.def;if(qM(n))return Be(e,t,s.innerType,r,o);if(s.innerType._zod.optin==="defaulted"){let a=ce(t),u=ce(t);return e.write(`let ${a};`),e.write(`if (${r} === undefined) {`),e.indented(c=>{c.write(`const ${u} = (() => {`),c.indented(d=>{let p=Be(d,t,s.innerType,r);d.write(`return ${p};`)}),c.write("})();"),c.write(`if (${u} !== INVALID) ${a} = ${u};`)}),e.write("} else {"),e.indented(c=>{let d=Be(c,t,s.innerType,r);c.write(`${a} = ${d};`)}),e.write("}"),a}let i=o?ce(t):null;return i&&e.write(`let ${i};`),e.write(`if (${r} !== undefined) {`),e.indented(a=>{let u=Be(a,t,s.innerType,r,o);i&&u!==null&&a.write(`${i} = ${u};`)}),e.write("}"),i}function qM(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function JM(e){return e._zod.optin===void 0&&xo(e)}function xo(e){if(e._zod.def.coerce)return!0;let t=e._zod.def;switch(t.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return t.innerType?xo(t.innerType):!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return t.innerType?xo(t.innerType):!0;case"catch":return!0;case"union":return t.options?t.options.some(xo):!0;case"intersection":return!t.left||!t.right?!0:xo(t.left)&&xo(t.right);case"pipe":return t.in?xo(t.in):!0;default:return!0}}function Mx(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function GN(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&Qs(e)}function Qs(e){let t=e._zod.def;switch(t.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return t.innerType?Qs(t.innerType):!0;case"union":return t.options?t.options.some(Qs):!0;case"intersection":return!t.left||!t.right||Qs(t.left)||Qs(t.right);case"pipe":return t.out?Qs(t.out):!0;default:return!0}}function eD(e,t,n,r,o=!0){let s=n._zod.def,i=o?ce(t):null;return i&&e.write(`let ${i} = null;`),e.write(`if (${r} !== null) {`),e.indented(a=>{let u=Be(a,t,s.innerType,r,o);i&&u!==null&&a.write(`${i} = ${u};`)}),e.write("}"),i}function tD(e,t,n,r,o=!0){let s=n._zod.def;e.write(`if (!Array.isArray(${r})) return INVALID;`);let i=o?ce(t):null,a=ce(t),u=ce(t);return i&&e.write(`const ${i} = new Array(${r}.length);`),e.write(`for (let ${a} = 0; ${a} < ${r}.length; ${a}++) {`),e.indented(c=>{c.write(`const ${u} = ${r}[${a}];`);let d=ht(c,t,s.element,u,o);i&&d!==null&&c.write(`${i}[${a}] = ${d};`)}),e.write("}"),i}function nD(e,t,n,r){let s=n._zod.def.values;if(s.length!==1){let a=fe(t,new Set(s));return e.write(`if (!${a}.has(${r})) return INVALID;`),r}let i=s[0];if(typeof i=="number"&&Number.isNaN(i)){let a=fe(t,new Set(s));return e.write(`if (!${a}.has(${r})) return INVALID;`),r}if(typeof i=="string")e.write(`if (${r} !== ${vt(i)}) return INVALID;`);else if(typeof i=="number"||typeof i=="boolean")e.write(`if (${r} !== ${i}) return INVALID;`);else if(i===null)e.write(`if (${r} !== null) return INVALID;`);else if(i===void 0)e.write(`if (${r} !== undefined) return INVALID;`);else if(typeof i=="bigint")e.write(`if (${r} !== ${i}n) return INVALID;`);else throw new Se(`literal type ${typeof i}`);return r}function rD(e,t,n,r){let o=n._zod.values;if(!o)throw new Se("enum schema without enumerated values");let s=fe(t,o);return e.write(`if (!${s}.has(${r})) return INVALID;`),r}function YN(e,t,n,r){let o=n._zod.def;return Be(e,t,o.innerType,r)}function oD(e,t,n,r){let o=n._zod.def,i=Object.getOwnPropertyDescriptor(n._zod.def,"defaultValue")?()=>n._zod.def.defaultValue:void 0;if(n._zod.def.type==="prefault"){if(!i)return Be(e,t,o.innerType,r);let u=fe(t,i),c=ce(t);return e.write(`let ${c} = ${r};`),e.write(`if (${r} === undefined) ${c} = ${u}();`),Be(e,t,o.innerType,c)}let a=ce(t);if(i){let u=fe(t,i),c=fe(t,Ma);e.write(`let ${a};`),e.write(`if (${r} === undefined) {`),e.indented(d=>{d.write(`${a} = ${c}(${u}());`)}),e.write("} else {"),e.indented(d=>{let p=Be(d,t,o.innerType,r);d.write(`${a} = ${p} === undefined ? ${c}(${u}()) : ${p};`)}),e.write("}")}else e.write(`let ${a};`),e.write(`if (${r} !== undefined) {`),e.indented(u=>{let c=Be(u,t,o.innerType,r);u.write(`${a} = ${c};`)}),e.write("}");return a}function sD(e,t,n,r){let o=n._zod.def,s=Be(e,t,o.innerType,r),i=ce(t);return e.write(`const ${i} = ${s};`),e.write(`if (${i} === undefined) return INVALID;`),i}function iD(e,t,n,r){let o=n._zod.def,s=o.items,i=o.rest;e.write(`if (!Array.isArray(${r})) return INVALID;`);let a=qN(s,"optin"),u=qN(s,"optout");i?e.write(`if (${r}.length < ${a}) return INVALID;`):e.write(`if (${r}.length < ${a} || ${r}.length > ${s.length}) return INVALID;`);let c=ce(t);e.write(`const ${c} = [];`);for(let d=0;d<s.length;d++){let p=s[d];if(d>=u)e.write(`if (${c}.length === ${d}) {`),e.indented(f=>{f.write(`if (${d} < ${r}.length) {`),f.indented(h=>{let g=ce(t);h.write(`const ${g} = ${r}[${d}];`);let x=ht(h,t,p,g);h.write(`${c}[${d}] = ${x};`)}),f.write("} else {"),f.indented(h=>{if(Mx(p)){h.write(`${c}.length = ${d};`);return}let g=ce(t),x=ce(t);h.write(`const ${g} = undefined;`),h.write(`const ${x} = (() => {`),h.indented(b=>{let v=ht(b,t,p,g);b.write(`return ${v};`)}),h.write("})();"),h.write(`if (${x} === INVALID || ${x} === undefined) ${c}.length = ${d};`),h.write(`else ${c}[${d}] = ${x};`)}),f.write("}")}),e.write("}");else{let f=ce(t);e.write(`const ${f} = ${r}[${d}];`);let h=ht(e,t,p,f);e.write(`${c}[${d}] = ${h};`)}}if(i){let d=ce(t),p=ce(t);e.write(`for (let ${d} = ${s.length}; ${d} < ${r}.length; ${d}++) {`),e.indented(f=>{f.write(`const ${p} = ${r}[${d}];`);let h=ht(f,t,i,p);f.write(`${c}[${d}] = ${h};`)}),e.write("}")}return c}function qN(e,t){for(let n=e.length-1;n>=0;n--)if(!(t==="optin"?e[n]._zod.optin!==void 0:e[n]._zod.optout==="optional"))return n+1;return 0}function aD(e,t,n,r){let o=n._zod.def,s=o.options;if(o.discriminator)return lD(e,t,o,r);if(o.inclusive===!1)throw new Se("exclusive unions (z.xor)");if(s.length===0)return e.write("return INVALID;"),r;if(s.length===1)return Be(e,t,s[0],r);if(s.every(u=>u._zod.def.type==="literal"&&!u._zod.def.checks?.length)){let u=new Set(s.flatMap(d=>d._zod.def.values)),c=fe(t,u);return e.write(`if (!${c}.has(${r})) return INVALID;`),r}let a=ce(t);e.write(`let ${a};`);for(let u=0;u<s.length;u++){let c=s[u];u===0?e.write(`${a} = (() => {`):e.write(`if (${a} === INVALID) ${a} = (() => {`),e.indented(d=>{let p=Be(d,t,c,r);d.write(`return ${p};`)}),e.write("})();")}return e.write(`if (${a} === INVALID) return INVALID;`),a}function lD(e,t,n,r){if(n.unionFallback)throw new Se("discriminated union with unionFallback");if(n.options.length===0)return e.write("return INVALID;"),r;let o=ce(t),s=ce(t);e.write(`const ${o} = ${r}?.[${vt(n.discriminator)}];`),e.write(`let ${s};`);let i=!0,a=new Set;for(let u of n.options){let c=u._zod.propValues?.[n.discriminator];if(!c||c.size===0)throw new Se("discriminated union option without static discriminator values");for(let f of c){if(a.has(f))throw new Se(`duplicate discriminator value ${String(f)}`);a.add(f)}let d=Array.from(c,f=>cD(t,o,f)),p=i?"if":"else if";e.write(`${p} (${d.join(" || ")}) {`),e.indented(f=>{let h=Be(f,t,u,r);f.write(`${s} = ${h};`)}),e.write("}"),i=!1}return e.write("else { return INVALID; }"),s}function cD(e,t,n){if(typeof n=="string")return`${t} === ${vt(n)}`;if(typeof n=="number")return Number.isNaN(n)?`Number.isNaN(${t})`:`${t} === ${n}`;if(typeof n=="boolean")return`${t} === ${n}`;if(n===null)return`${t} === null`;if(n===void 0)return`${t} === undefined`;if(typeof n=="bigint")return`${t} === ${n}n`;if(typeof n=="symbol"){let r=fe(e,n);return`${t} === ${r}`}throw new Se(`literal discriminator value ${String(n)}`)}function uD(e,t,n,r){let o=n._zod.def;t.definite=!1;let s=ht(e,t,o.left,r),i=ht(e,t,o.right,r),a=fe(t,Ws),u=ce(t);return e.write(`const ${u} = ${a}(${s}, ${i});`),e.write(`if (!${u}.valid) return INVALID;`),`${u}.data`}function dD(e,t,n,r){let o=n._zod.def,s=fe(t,Vt);e.write(`if (!${s}(${r})) return INVALID;`);let i=ce(t),a=ce(t),u=ce(t);e.write(`const ${i} = {};`);let c=o,d=c.partial?void 0:o.keyType._zod.values;if(d){let h=[];for(let x of d){if(!(typeof x=="string"||typeof x=="number"||typeof x=="symbol"))throw new Se(`record key value ${String(x)}`);let b=typeof x=="number"?x.toString():x;if(b==="__proto__")throw new Se('record key "__proto__"');h.push(b);let v=fe(t,x),w=Be(e,t,o.keyType,v),C=ce(t);e.write(`const ${C} = ${r}[${pD(t,b)}];`);let y=ht(e,t,o.valueType,C);e.write(`${i}[${w}] = ${y};`)}let g=fe(t,new Set(h));return e.write(`for (const ${a} in ${r}) {`),e.indented(x=>{x.write(`if (${g}.has(${a})) continue;`),c.mode==="loose"?x.write(`if (${a} !== "__proto__") ${i}[${a}] = ${r}[${a}];`):x.write("return INVALID;")}),e.write("}"),i}let p=o.keyType._zod.def;if(!(p.type==="string"&&p.format===void 0&&!p.coerce&&(p.checks?.length??0)===0)){let h=o.mode==="loose",g=Wd(o.keyType);g.definite===!1&&(t.definite=!1);let x=fe(t,g),b=fe(t,Vn),v=ce(t);return JN(e,t,r,a,w=>{w.write(`let ${v} = ${x}(${a});`),w.write(`if (${v} === INVALID && typeof ${a} === "string" && ${b}.test(${a})) ${v} = ${x}(Number(${a}));`),h?w.write(`if (${v} === INVALID) { ${i}[${a}] = ${r}[${a}]; continue; }`):w.write(`if (${v} === INVALID) return INVALID;`),w.write(`if (${v} === "__proto__") continue;`);let C=ce(t);w.write(`const ${C} = ${r}[${a}];`);let y=ht(w,t,o.valueType,C);w.write(`${i}[${v}] = ${y};`)}),i}return JN(e,t,r,a,h=>{h.write(`const ${u} = ${r}[${a}];`);let g=ht(h,t,o.valueType,u);h.write(`${i}[${a}] = ${g};`)},"return INVALID;"),i}function JN(e,t,n,r,o,s){let i=fe(t,Object.prototype.propertyIsEnumerable),a=ce(t),u=ce(t),c=ce(t);e.write(`const ${a} = Object.getOwnPropertySymbols(${n});`),e.write(`const ${u} = Object.getOwnPropertyNames(${n});`),e.write(`for (let ${c} = 0; ${c} < ${u}.length; ${c}++) {`),e.indented(d=>{d.write(`const ${r} = ${u}[${c}];`),d.write(`if (${r} === "__proto__" || !${i}.call(${n}, ${r})) continue;`),o(d)}),e.write("}"),e.write(`for (let ${c} = 0; ${c} < ${a}.length; ${c}++) {`),e.indented(d=>{d.write(`const ${r} = ${a}[${c}];`),d.write(`if (!${i}.call(${n}, ${r})) continue;`),s?d.write(s):o(d)}),e.write("}")}function pD(e,t){return typeof t=="string"?vt(t):fe(e,t)}function fD(e,t,n,r){let o=n._zod.def;e.write(`if (!(${r} instanceof Map)) return INVALID;`);let s=ce(t),i=ce(t),a=ce(t);return e.write(`const ${s} = new Map();`),e.write(`for (const [${i}, ${a}] of ${r}) {`),e.indented(u=>{let c=Be(u,t,o.keyType,i),d=Be(u,t,o.valueType,a);u.write(`${s}.set(${c}, ${d});`)}),e.write("}"),s}function hD(e,t,n,r){let o=n._zod.def;e.write(`if (!(${r} instanceof Set)) return INVALID;`);let s=ce(t),i=ce(t);return e.write(`const ${s} = new Set();`),e.write(`for (const ${i} of ${r}) {`),e.indented(a=>{let u=Be(a,t,o.valueType,i);a.write(`${s}.add(${u});`)}),e.write("}"),s}function mD(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function gD(e,t,n,r){e.write(`if (typeof ${r} !== "string") return INVALID;`);let o=n._zod.pattern;if(o){let s=fe(t,o);e.write(`${s}.lastIndex = 0;`),e.write(`if (!${s}.test(${r})) return INVALID;`)}return r}function xD(e,t,n,r){let o=n._zod.def,s=bo(t,o.getter),i=fe(t,{parser:null});e.write(`if (!${i}.parser) {`),e.indented(u=>{u.write(`const inner = ${s}();`),u.write(`${i}.parser = function(input) {`),u.indented(c=>{c.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),c.write("return result.issues.length === 0 ? result.value : INVALID;")}),u.write("};")}),e.write("}");let a=ce(t);return e.write(`const ${a} = ${i}.parser(${r});`),e.write(`if (${a} === INVALID) return INVALID;`),a}function bD(e,t,n,r){let o=n._zod.def,s=Be(e,t,o.in,r);if(o.transform){if(yo(o.transform))throw new an("z.compile: async transforms in pipes are not supported");let i=o.transform,u=bo(t,d=>{let p={value:d,issues:[],addIssue:Fx},f=i(d,p);return f instanceof Promise?kt:p.issues.length===0?f:kt}),c=ce(t);return e.write(`const ${c} = ${u}(${s});`),e.write(`if (${c} === INVALID) return INVALID;`),Be(e,t,o.out,c)}else return Be(e,t,o.out,s)}function yo(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function yD(e,t,n,r){let o=n._zod.def;if(o.fn){if(yo(o.fn))throw new an("z.compile: async custom predicates are not supported");let s=bo(t,o.fn),i=fe(t,Lx),a=ce(t);e.write(`const ${a} = ${s}(${r});`),e.write(`if (${a} instanceof Promise) ${i}();`),e.write(`if (!${a}) return INVALID;`)}else throw new Se("custom schema without a predicate function");return r}function _D(e,t,n){let r=e._zod.run({value:n,issues:[]},{});if(r&&typeof r.then=="function")return kt;let o=r;return o.issues.length===0?o.value:t()}function vD(e,t,n,r){let o=n._zod.def;if(!o.catchValue[ed])throw new Se("catch with a callback (only a constant catch value compiles)",!1);let s=ce(t);e.write(`let ${s} = (() => {`),e.indented(c=>{let d=ht(c,t,o.innerType,r);c.write(`return ${d};`)}),e.write("})();");let i=fe(t,o.innerType),a=bo(t,o.catchValue),u=fe(t,_D);return e.write(`if (${s} === INVALID) {`),e.indented(c=>{c.write(`${s} = ${u}(${i}, ${a}, ${r});`),c.write(`if (${s} === INVALID) return INVALID;`)}),e.write("}"),s}function wD(e,t,n,r){let o=n._zod.def;if(o.transform){if(yo(o.transform))throw new an("z.compile: async transforms are not supported");let s=o.transform,a=bo(t,c=>{let d={value:c,issues:[],addIssue:Fx},p=s(c,d);return p instanceof Promise?kt:d.issues.length===0?p:kt}),u=ce(t);return e.write(`const ${u} = ${a}(${r});`),e.write(`if (${u} === INVALID) return INVALID;`),u}return r}function jd(e){return e.checks&&(e.checks=[...e.checks]),e}function zx(e,t){return new e(jd({type:"string",...W(t)}))}function Kx(e,t){return new e(jd({type:"string",coerce:!0,...W(t)}))}function Qd(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...W(t)})}function Gd(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...W(t)})}function Yd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...W(t)})}function qd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...W(t)})}function Jd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...W(t)})}function ep(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...W(t)})}function ul(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...W(t)})}function tp(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...W(t)})}function np(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...W(t)})}function rp(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...W(t)})}function op(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...W(t)})}function sp(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...W(t)})}function ip(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...W(t)})}function ap(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...W(t)})}function lp(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...W(t)})}function cp(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...W(t)})}function Xx(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...W(t)})}function up(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...W(t)})}function dp(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...W(t)})}function pp(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...W(t)})}function fp(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...W(t)})}function hp(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...W(t)})}function Bx(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...W(t)})}function Ux(e,t){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...W(t)})}function mp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...W(t)})}var Hx={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function dl(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...W(t)})}function pl(e,t){return new e({type:"string",format:"date",check:"string_format",...W(t)})}function fl(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...W(t)})}function hl(e,t){return new e({type:"string",format:"duration",check:"string_format",...W(t)})}function Vx(e,t){return new e(jd({type:"number",checks:[],...W(t)}))}function Zx(e,t){return new e(jd({type:"number",coerce:!0,checks:[],...W(t)}))}function Wx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...W(t)})}function jx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...W(t)})}function Qx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...W(t)})}function Gx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...W(t)})}function Yx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...W(t)})}function qx(e,t){return new e({type:"boolean",...W(t)})}function Jx(e,t){return new e({type:"boolean",coerce:!0,...W(t)})}function eb(e,t){return new e({type:"bigint",...W(t)})}function tb(e,t){return new e({type:"bigint",coerce:!0,...W(t)})}function nb(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...W(t)})}function rb(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...W(t)})}function ob(e,t){return new e({type:"symbol",...W(t)})}function sb(e,t){return new e({type:"undefined",...W(t)})}function ib(e,t){return new e({type:"null",...W(t)})}function ab(e){return new e({type:"any"})}function lb(e){return new e({type:"unknown"})}function cb(e,t){return new e({type:"never",...W(t)})}function ub(e,t){return new e({type:"void",...W(t)})}function db(e,t){return new e({type:"date",...W(t)})}function pb(e,t){return new e({type:"date",coerce:!0,...W(t)})}function fb(e,t){return new e({type:"nan",...W(t)})}function wn(e,t){return new gd({check:"less_than",...W(t),value:e,inclusive:!1})}function Dt(e,t){return new gd({check:"less_than",...W(t),value:e,inclusive:!0})}function kn(e,t){return new xd({check:"greater_than",...W(t),value:e,inclusive:!1})}function Ft(e,t){return new xd({check:"greater_than",...W(t),value:e,inclusive:!0})}function gp(e){return kn(0,e)}function xp(e){return wn(0,e)}function bp(e){return Dt(0,e)}function yp(e){return Ft(0,e)}function br(e,t){return new Yg({check:"multiple_of",...W(t),value:e})}function yr(e,t){return new e0({check:"max_size",...W(t),maximum:e})}function Sn(e,t){return new t0({check:"min_size",...W(t),minimum:e})}function _o(e,t){return new n0({check:"size_equals",...W(t),size:e})}function vo(e,t){return new r0({check:"max_length",...W(t),maximum:e})}function Zn(e,t){return new o0({check:"min_length",...W(t),minimum:e})}function wo(e,t){return new s0({check:"length_equals",...W(t),length:e})}function Gs(e,t){return new i0({check:"string_format",format:"regex",...W(t),pattern:e})}function Ys(e){return new a0({check:"string_format",format:"lowercase",...W(e)})}function qs(e){return new l0({check:"string_format",format:"uppercase",...W(e)})}function Js(e,t){return new c0({check:"string_format",format:"includes",...W(t),includes:e})}function ei(e,t){return new u0({check:"string_format",format:"starts_with",...W(t),prefix:e})}function ti(e,t){return new d0({check:"string_format",format:"ends_with",...W(t),suffix:e})}function _p(e,t,n){return new p0({check:"property",property:e,schema:t,...W(n)})}function ni(e,t){return new f0({check:"properties",shape:e,...W(t)})}function ri(e,t){return new h0({check:"mime_type",mime:e,...W(t)})}function ln(e){return new m0({check:"overwrite",tx:e})}function oi(e){return ln(t=>t.normalize(e))}function si(){return ln(e=>e.trim())}function ii(){return ln(e=>e.toLowerCase())}function ai(){return ln(e=>e.toUpperCase())}function li(){return ln(e=>qm(e))}function hb(e,t,n){return new e({type:"array",element:t,...W(n)})}function kD(e,t,n){return new e({type:"union",options:t,...W(n)})}function SD(e,t,n){return new e({type:"union",options:t,inclusive:!1,...W(n)})}function ED(e,t,n,r){return new e({type:"union",options:n,discriminator:t,...W(r)})}function ND(e,t,n){return new e({type:"intersection",left:t,right:n})}function AD(e,t,n,r){let o=n instanceof me,s=o?r:n,i=o?n:null;return new e({type:"tuple",items:t,rest:i,...W(s)})}function CD(e,t,n,r){return new e({type:"record",keyType:t,valueType:n,...W(r)})}function TD(e,t,n,r){return new e({type:"map",keyType:t,valueType:n,...W(r)})}function RD(e,t,n){return new e({type:"set",valueType:t,...W(n)})}function $D(e,t,n){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new e({type:"enum",entries:r,...W(n)})}function ID(e,t,n){return new e({type:"enum",entries:t,...W(n)})}function PD(e,t,n){return new e({type:"literal",values:Array.isArray(t)?t:[t],...W(n)})}function mb(e,t){return new e({type:"file",...W(t)})}function OD(e,t){return new e({type:"transform",transform:t})}function LD(e,t){return new e({type:"optional",innerType:t})}function MD(e,t){return new e({type:"nullable",innerType:t})}function DD(e,t,n){return new e({type:"default",innerType:t,get defaultValue(){return typeof n=="function"?n():Ma(n)}})}function FD(e,t,n){return new e({type:"nonoptional",innerType:t,...W(n)})}function zD(e,t){return new e({type:"success",innerType:t})}function KD(e,t,n){return new e({type:"catch",innerType:t,catchValue:typeof n=="function"?n:sg(n)})}function XD(e,t,n){return new e({type:"pipe",in:t,out:n})}function BD(e,t){return new e({type:"readonly",innerType:t})}function UD(e,t,n){return new e({type:"template_literal",parts:t,...W(n)})}function HD(e,t){return new e({type:"lazy",getter:t})}function VD(e,t){return new e({type:"promise",innerType:t})}function gb(e,t,n){let r=W(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function xb(e,t,n){return new e({type:"custom",check:"custom",fn:t,...W(n)})}function bb(e,t){let n=rA(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(Xs(o,r.value,n._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),r.issues.push(Xs(s))}},e(r.value,r)),t);return n}function rA(e,t){let n=new Fe({check:"custom",...W(t)});return n._zod.check=e,n}function yb(e){let t=new Fe({check:"describe"});return t._zod.onattach=[n=>{let r=at.get(n)??{};at.add(n,{...r,description:e})}],t._zod.check=()=>{},t}function _b(e){let t=new Fe({check:"meta"});return t._zod.onattach=[n=>{let r=at.get(n)??{};at.add(n,{...r,...e})}],t._zod.check=()=>{},t}function vb(e,t){let n=W(t),r=n.truthy??["true","1","yes","on","y","enabled"],o=n.falsy??["false","0","no","off","n","disabled"];n.case!=="sensitive"&&(r=r.map(h=>typeof h=="string"?h.toLowerCase():h),o=o.map(h=>typeof h=="string"?h.toLowerCase():h));let s=new Set(r),i=new Set(o),a=e.Codec??ol,u=e.Boolean??nl,c=e.String??mo,d=new c({type:"string",error:n.error}),p=new u({type:"boolean",error:n.error}),f=new a({type:"pipe",in:d,out:p,transform:((h,g)=>{let x=h;return n.case!=="sensitive"&&(x=x.toLowerCase()),s.has(x)?!0:i.has(x)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...s,...i],input:g.value,inst:f,continue:!1}),{})}),reverseTransform:((h,g)=>h===!0?r[0]||"true":o[0]||"false"),error:n.error});return f._zod.bag.truthy=r,f._zod.bag.falsy=o,f._zod.bag.case=n.case??"insensitive",f}function ko(e,t,n,r={}){let o=W(r),s={check:"string_format",type:"string",format:t,fn:typeof n=="function"?n:a=>n.test(a),...o};return n instanceof RegExp&&(s.pattern=n),new e(s)}function ml(e,...t){for(let n of t)for(let r of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,r)&&it(e,r,n[r]);return e}function _r(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??at,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function Je(e,t,n,r,o){let s=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:r.path,message:o}):t.unrepresentable;if(s==="any")return!1;if(s===void 0||s==="throw")throw new Error(o);return Object.assign(n,s),!0}function $e(e,t,n={path:[],schemaPath:[]}){var r;let o=e._zod.def,s=t.seen.get(e);if(s)return s.count++,n.schemaPath.includes(e)&&(s.cycle=n.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,i),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,d);else{let f=i.schema,h=t.processors[o.type];if(!h)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);h(e,t,f,d)}let p=e._zod.parent;p&&(i.ref||(i.ref=p),$e(p,t,d),t.seen.get(p).isParent=!0)}let u=t.metadataRegistry.get(e);return u&&ml(i.schema,u),t.io==="input"&&St(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function oA(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function vr(e,t){let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let u=r.get(a);if(u&&u!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,i[0])}}let o=i=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(i[0])?.id,f=e.external.uri??(g=>g);if(p)return{ref:f(p)};let h=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=h,{defId:h,ref:`${f("__shared")}#/${a}/${oA(h)}`}}let u="#",c=`${u}/${a}/`;if(i[1]===n&&!i[1].schema.id)return{ref:u};let d=i[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:c+oA(d)}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:u,defId:c}=o(i);a.def={...a.schema},c&&(a.defId=c);let d=a.schema;for(let p in d)delete d[p];d.$ref=u};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
208
+ }`,f;try{f=new d(...i,p)(...a)}catch(h){throw new Se(`this schema (generated code failed to evaluate: ${h.message})`)}return t?.debug&&(f.code=c),f.definite=r.definite,f}function fe(e,t){for(let[r,o]of e.constants)if(o===t)return r;let n=`c${e.constantCounter++}`;return e.constants.set(n,t),n}function yo(e,t){return e.definite=!1,fe(e,t)}function ce(e){return`v${e.varCounter++}`}function RM(e,t){let n=e._zod.run({value:t,issues:[]},{});if(n&&typeof n.then=="function")return kt;let r=n;return r.issues.length===0?r.value:kt}function ht(e,t,n,r,o=!0){let s=e.content.length,i=t.constants.size,a=t.constantCounter,u=t.varCounter;try{return Be(e,t,n,r,o)}catch(c){if(!(c instanceof Se)||!c.islandable)throw c;if(e.content.length=s,t.constants.size>i){let d=Array.from(t.constants.keys()).slice(i);for(let p of d)t.constants.delete(p)}return t.constantCounter=a,t.varCounter=u,$M(e,t,n,r)}}function $M(e,t,n,r){t.definite=!1;let o=fe(t,n),s=fe(t,RM),i=ce(t);return e.write(`const ${i} = ${s}(${o}, ${r});`),e.write(`if (${i} === INVALID) return INVALID;`),i}var IM=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function PM(e,t,n,r){let o=n._zod.def.checks;if(!o||o.length===0)return r;let s=r;for(let i of o){let a=i._zod.def;if(a.when&&!IM.has(a.check))throw new Se('check with a custom "when" condition');switch(a.check){case"greater_than":OM(e,t,a,s);break;case"less_than":LM(e,t,a,s);break;case"multiple_of":MM(e,t,a,s);break;case"number_format":sA(e,a,s);break;case"min_length":{let u=xo(a.minimum,"min_length"),c=Mx(e,t,s,`${s}.length >= ${u} && ${s}.length < ${a.minimum*2}`);e.write(`if (${c} < ${u}) return INVALID;`);break}case"max_length":{let u=xo(a.maximum,"max_length"),c=Mx(e,t,s,`${s}.length > ${u}`);e.write(`if (${c} > ${u}) return INVALID;`);break}case"length_equals":{let u=xo(a.length,"length_equals"),c=Mx(e,t,s,`${s}.length >= ${u} && ${s}.length <= ${a.length*2}`);e.write(`if (${c} !== ${u}) return INVALID;`);break}case"min_size":e.write(`if (${s}.size < ${xo(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":e.write(`if (${s}.size > ${xo(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":e.write(`if (${s}.size !== ${xo(a.size,"size_equals")}) return INVALID;`);break;case"string_format":s=iA(e,t,a,s);break;case"custom":s=BM(e,t,i,s);break;case"bigint_format":DM(e,a,s);break;case"mime_type":FM(e,t,a,s);break;case"property":KM(e,t,a,s);break;case"properties":zM(e,t,a,s);break;case"overwrite":{let u=ce(t);XM(e,t,i,s,u),s=u;break}default:throw new Se(`check type ${a.check}`)}}return s}function Mx(e,t,n,r){let o=fe(t,fo),s=ce(t);return e.write(`const ${s} = typeof ${n} === "string" && ${r} ? ${o}(${n}) : ${n}.length;`),s}function xo(e,t){if(typeof e!="number"||!Number.isFinite(e))throw new Se(`${t} bound of type ${typeof e}`);return`${e}`}function oA(e,t){if(typeof t=="bigint")return`${t}n`;if(typeof t=="number"){if(Number.isNaN(t))throw new Se("comparison check with NaN bound");return`${t}`}if(t instanceof Date){if(Number.isNaN(t.getTime()))throw new Se("comparison check with Invalid Date bound");return fe(e,t)}throw new Se(`comparison check bound of type ${typeof t}`)}function OM(e,t,n,r){let o=n.inclusive?"<":"<=";e.write(`if (${r} ${o} ${oA(t,n.value)}) return INVALID;`)}function LM(e,t,n,r){let o=n.inclusive?">":">=";e.write(`if (${r} ${o} ${oA(t,n.value)}) return INVALID;`)}function MM(e,t,n,r){if(typeof n.value=="bigint"){if(n.value===BigInt(0))throw new Se("multiple_of check with a zero divisor");e.write(`if (${r} % ${n.value}n !== 0n) return INVALID;`)}else{let o=fe(t,Ma);e.write(`if (${o}(${r}, ${xo(n.value,"multiple_of")}) !== 0) return INVALID;`)}}function sA(e,t,n){let r=t.format;switch(r){case"safeint":e.write(`if (!Number.isSafeInteger(${n})) return INVALID;`);break;case"int32":e.write(`if (!Number.isInteger(${n}) || ${n} < -2147483648 || ${n} > 2147483647) return INVALID;`);break;case"uint32":e.write(`if (!Number.isInteger(${n}) || ${n} < 0 || ${n} > 4294967295) return INVALID;`);break;case"float32":e.write(`if (!Number.isFinite(${n}) || ${n} < -3.4028234663852886e38 || ${n} > 3.4028234663852886e38) return INVALID;`);break;case"float64":e.write(`if (!Number.isFinite(${n})) return INVALID;`);break;default:throw new Se(`number format ${r}`)}}function DM(e,t,n){let r=t.format;if(r)switch(r){case"int64":e.write(`if (${n} < -9223372036854775808n || ${n} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${n} < 0n || ${n} > 18446744073709551615n) return INVALID;`);break;default:throw new Se(`bigint format ${r}`)}}function FM(e,t,n,r){let o=n.mime;if(o&&o.length>0){let s=fe(t,new Set(o));e.write(`if (!${s}.has(${r}.type)) return INVALID;`)}}function zM(e,t,n,r){if(n.when)throw new Se('check with a custom "when" condition');e.write(`if (${r} == null) return INVALID;`);let o=n.shape;for(let s of Reflect.ownKeys(o)){let i=typeof s=="symbol"?fe(t,s):vt(s),a=ce(t);e.write(`const ${a} = ${r}[${i}];`),ht(e,t,o[s],a,!1)}}function KM(e,t,n,r){let o=`${r}[${JSON.stringify(n.property)}]`;Be(e,t,n.schema,o)}function XM(e,t,n,r,o){let s=n._zod.def.tx;if(!s)throw new Se("overwrite check without a transform function");if(_o(s))throw new ln("z.compile: async overwrite transforms are not supported");let i=fe(t,s);e.write(`const ${o} = ${i}(${r});`)}function Dx(){throw new It}function Kx(e){this.issues.push(e)}function BM(e,t,n,r){let o=n._zod.def;if(o.fn){if(_o(o.fn))throw new ln("z.compile: async .refine() predicates are not supported");let s=yo(t,o.fn),i=fe(t,Dx),a=ce(t);return e.write(`const ${a} = ${s}(${r});`),e.write(`if (${a} instanceof Promise) ${i}();`),e.write(`if (!${a}) return INVALID;`),r}if(n._zod.check){if(_o(n._zod.check))throw new ln("z.compile: async .superRefine() / check functions are not supported");let s=n._zod.check,a=yo(t,c=>{let d={value:c,issues:[],addIssue:Kx};return s(d)instanceof Promise&&Dx(),d.issues.length===0?d.value:kt}),u=ce(t);return e.write(`const ${u} = ${a}(${r});`),e.write(`if (${u} === INVALID) return INVALID;`),u}throw new Se("custom check without a predicate or check function")}var UM=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function iA(e,t,n,r,o=!0){let s=n.format;if(s==="base64"){let c=fe(t,tl);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(s==="base64url"){let c=fe(t,Rd);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(s==="jwt"){let c=fe(t,Pd),d=fe(t,n.alg??null);return e.write(`if (!${c}(${r}, ${d})) return INVALID;`),r}if(s==="ipv6"){let c=fe(t,el);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(s==="cidrv6"){let c=fe(t,Cd);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(s==="credit_card"){let c=fe(t,$d);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(s==="iban"){let c=fe(t,Id);return e.write(`if (!${c}(${r})) return INVALID;`),r}let i=n;if(s==="url"||s==="httpurl"||i.normalize||i.hostname!==void 0||i.protocol!==void 0){let c=fe(t,Ed),d=fe(t,n),p=ce(t),f=ce(t);if(e.write(`const ${p} = ${r}.trim();`),e.write(`const ${f} = ${c}(${p}, ${d});`),e.write(`if (typeof ${f} === "number") return INVALID;`),i.hostname!==void 0){let x=fe(t,Nd);e.write(`if (!${x}(${f}, ${d}.hostname)) return INVALID;`)}if(i.protocol!==void 0){let x=fe(t,Ad);e.write(`if (!${x}(${f}, ${d}.protocol)) return INVALID;`)}if(!o)return null;let h=ce(t),g=i.normalize?`${f}.href`:`${fe(t,Ja)}(${p})`;return e.write(`const ${h} = ${g};`),h}let a=n.fn;if(a){if(_o(a))throw new Se(`async string format ${s}`);let c=fe(t,a);return e.write(`if (!${c}(${r})) return INVALID;`),r}if(UM.has(s)&&n.pattern){let c=fe(t,n.pattern);return e.write(`${c}.lastIndex = 0;`),e.write(`if (!${c}.test(${r})) return INVALID;`),r}let u=n.format;switch(u){case"regex":throw new Se("regex format without a pattern");case"lowercase":e.write(`if (${r} !== ${r}.toLowerCase()) return INVALID;`);break;case"uppercase":e.write(`if (${r} !== ${r}.toUpperCase()) return INVALID;`);break;case"includes":e.write(`if (!${r}.includes(${vt(n.includes)})) return INVALID;`);break;case"starts_with":{let c=n.prefix;e.write(`if (${r}.slice(0, ${c.length}) !== ${vt(c)}) return INVALID;`);break}case"ends_with":{let c=n.suffix;e.write(`if (${r}.slice(-${c.length}) !== ${vt(c)}) return INVALID;`);break}default:throw new Se(`string format ${u}`)}return r}function Be(e,t,n,r,o=!0){let s=n._zod.def,i=s.type;if(s.coerce)throw new Se(`coercion (z.coerce.${i}())`);let a=o||!!s.checks?.length,u;switch(i){case"string":u=HM(e,t,n,r,a);break;case"number":u=VM(e,n,r);break;case"boolean":u=ZM(e,r);break;case"bigint":u=WM(e,n,r);break;case"symbol":u=jM(e,r);break;case"undefined":u=QM(e,r);break;case"null":u=GM(e,r);break;case"any":case"unknown":u=r;break;case"never":e.write("return INVALID;"),u=r;break;case"void":u=YM(e,r);break;case"nan":u=qM(e,r);break;case"date":u=JM(e,r);break;case"object":u=eD(e,t,n,r,a);break;case"optional":u=tD(e,t,n,r,a);break;case"nullable":u=oD(e,t,n,r,a);break;case"array":u=sD(e,t,n,r,a);break;case"literal":u=iD(e,t,n,r);break;case"enum":u=aD(e,t,n,r);break;case"readonly":{let c=tA(e,t,n,r),d=ce(t);e.write(`const ${d} = Object.freeze(${c});`),u=d;break}case"success":tA(e,t,n,r),u="true";break;case"default":case"prefault":u=lD(e,t,n,r);break;case"nonoptional":u=cD(e,t,n,r);break;case"tuple":u=uD(e,t,n,r);break;case"union":u=dD(e,t,n,r);break;case"intersection":u=hD(e,t,n,r);break;case"record":u=mD(e,t,n,r);break;case"map":u=xD(e,t,n,r);break;case"set":u=bD(e,t,n,r);break;case"file":u=yD(e,r);break;case"template_literal":u=_D(e,t,n,r);break;case"lazy":u=vD(e,t,n,r);break;case"pipe":u=wD(e,t,n,r);break;case"custom":u=kD(e,t,n,r);break;case"transform":u=ND(e,t,n,r);break;case"catch":u=ED(e,t,n,r);break;default:throw new Se(`schema type ${i}`)}return u===null?null:PM(e,t,n,u)}function HM(e,t,n,r,o=!0){e.write(`if (typeof ${r} !== "string") return INVALID;`);let s=n._zod.def;return s.format===void 0?r:iA(e,t,s,r,o)}function VM(e,t,n){e.write(`if (typeof ${n} !== "number" || !Number.isFinite(${n})) return INVALID;`);let r=t._zod.def;return r.check==="number_format"&&r.format&&sA(e,{format:r.format},n),n}function ZM(e,t){return e.write(`if (typeof ${t} !== "boolean") return INVALID;`),t}function WM(e,t,n){e.write(`if (typeof ${n} !== "bigint") return INVALID;`);let r=t._zod.def;if(r.format)switch(r.format){case"int64":e.write(`if (${n} < -9223372036854775808n || ${n} > 9223372036854775807n) return INVALID;`);break;case"uint64":e.write(`if (${n} < 0n || ${n} > 18446744073709551615n) return INVALID;`);break}return n}function jM(e,t){return e.write(`if (typeof ${t} !== "symbol") return INVALID;`),t}function QM(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function GM(e,t){return e.write(`if (${t} !== null) return INVALID;`),t}function YM(e,t){return e.write(`if (${t} !== undefined) return INVALID;`),t}function qM(e,t){return e.write(`if (typeof ${t} !== "number" || !Number.isNaN(${t})) return INVALID;`),t}function JM(e,t){return e.write(`if (!(${t} instanceof Date) || Number.isNaN(${t}.getTime())) return INVALID;`),t}function eD(e,t,n,r,o=!0){let s=n._zod.def;e.write(`if (typeof ${r} !== "object" || ${r} === null || Array.isArray(${r})) return INVALID;`);let i=s.shape,a=Object.keys(i),u=Object.getOwnPropertySymbols(i),c=u.length?[...a,...u]:a,d=w=>typeof w=="symbol"?fe(t,w):vt(w),p=w=>typeof w=="symbol"?`[${d(w)}]`:vt(w),f=i;if(a.includes("__proto__"))throw new Se('object shape key "__proto__"');let h=new Map;for(let w of c){let T=f[w],y=d(w),E=ce(t);if(e.write(`const ${E} = ${r}[${y}];`),T._zod.optin!==void 0){let k=ce(t);e.write(`let ${k} = (() => {`),e.indented(N=>{let $=ht(N,t,T,E);N.write(`return ${$};`)}),e.write("})();"),T._zod.optout==="optional"?(e.write(`if (${k} === INVALID) {`),e.indented(N=>{N.write(`if (${y} in ${r}) return INVALID;`),N.write(`${k} = undefined;`)}),e.write("}")):e.write(`if (${k} === INVALID) return INVALID;`),h.set(w,k)}else{rD(T)&&e.write(`if (!(${y} in ${r})) return INVALID;`);let k=ht(e,t,T,E,o);k!==null&&h.set(w,k)}}let g=s.catchall,x="none";if(g){let w=g._zod.def.type;if(w==="never"){let T=a.map(y=>`k !== ${vt(y)}`).join(" && ")||"true";e.write(`for (const k in ${r}) {`),e.indented(y=>{y.write(`if (${T}) return INVALID;`)}),e.write("}")}else(w==="unknown"||w==="any")&&!g._zod.def.checks?.length?x="passthrough":x="schema"}let b=ce(t),_=c.some(w=>eA(f[w])||Fx(f[w]));if(!o){if(x==="schema"){let w=a.length>0?fe(t,new Set(a)):null;e.write(`for (const k in ${r}) {`),e.indented(T=>{T.write('if (k === "__proto__") continue;'),w&&T.write(`if (${w}.has(k)) continue;`);let y=ce(t);T.write(`const ${y} = ${r}[k];`),ht(T,t,g,y,!1)}),e.write("}")}return null}if(_){e.write(`const ${b} = {};`);for(let w of c){let T=d(w),y=h.get(w);Fx(f[w])?e.write(`if (${T} in ${r}) ${b}[${T}] = ${y};`):eA(f[w])?e.write(`if (${y} !== undefined || ${T} in ${r}) ${b}[${T}] = ${y};`):e.write(`${b}[${T}] = ${y};`)}}else{let w=c.map(T=>`${p(T)}: ${h.get(T)}`).join(", ");e.write(`const ${b} = { ${w} };`)}if(x!=="none"){let w=a.length>0?fe(t,new Set(a)):null;e.write(`for (const k in ${r}) {`),e.indented(T=>{if(T.write('if (k === "__proto__") continue;'),w&&T.write(`if (${w}.has(k)) continue;`),x==="passthrough")T.write(`${b}[k] = ${r}[k];`);else{let y=ce(t);T.write(`const ${y} = ${r}[k];`);let E=ht(T,t,g,y);T.write(`${b}[k] = ${E};`)}}),e.write("}")}return b}function tD(e,t,n,r,o=!0){let s=n._zod.def;if(nD(n))return Be(e,t,s.innerType,r,o);if(s.innerType._zod.optin==="defaulted"){let a=ce(t),u=ce(t);return e.write(`let ${a};`),e.write(`if (${r} === undefined) {`),e.indented(c=>{c.write(`const ${u} = (() => {`),c.indented(d=>{let p=Be(d,t,s.innerType,r);d.write(`return ${p};`)}),c.write("})();"),c.write(`if (${u} !== INVALID) ${a} = ${u};`)}),e.write("} else {"),e.indented(c=>{let d=Be(c,t,s.innerType,r);c.write(`${a} = ${d};`)}),e.write("}"),a}let i=o?ce(t):null;return i&&e.write(`let ${i};`),e.write(`if (${r} !== undefined) {`),e.indented(a=>{let u=Be(a,t,s.innerType,r,o);i&&u!==null&&a.write(`${i} = ${u};`)}),e.write("}"),i}function nD(e){return e._zod.traits?.has("$ZodExactOptional")===!0}function rD(e){return e._zod.optin===void 0&&bo(e)}function bo(e){if(e._zod.def.coerce)return!0;let t=e._zod.def;switch(t.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return t.innerType?bo(t.innerType):!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return t.innerType?bo(t.innerType):!0;case"catch":return!0;case"union":return t.options?t.options.some(bo):!0;case"intersection":return!t.left||!t.right?!0:bo(t.left)&&bo(t.right);case"pipe":return t.in?bo(t.in):!0;default:return!0}}function Fx(e){return e._zod.optin==="optional"&&e._zod.optout==="optional"}function eA(e){return(e._zod.optin!=="defaulted"||e._zod.optout==="optional")&&Gs(e)}function Gs(e){let t=e._zod.def;switch(t.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!t.values?.includes(void 0);case"enum":return!!e._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return t.innerType?Gs(t.innerType):!0;case"union":return t.options?t.options.some(Gs):!0;case"intersection":return!t.left||!t.right||Gs(t.left)||Gs(t.right);case"pipe":return t.out?Gs(t.out):!0;default:return!0}}function oD(e,t,n,r,o=!0){let s=n._zod.def,i=o?ce(t):null;return i&&e.write(`let ${i} = null;`),e.write(`if (${r} !== null) {`),e.indented(a=>{let u=Be(a,t,s.innerType,r,o);i&&u!==null&&a.write(`${i} = ${u};`)}),e.write("}"),i}function sD(e,t,n,r,o=!0){let s=n._zod.def;e.write(`if (!Array.isArray(${r})) return INVALID;`);let i=o?ce(t):null,a=ce(t),u=ce(t);return i&&e.write(`const ${i} = new Array(${r}.length);`),e.write(`for (let ${a} = 0; ${a} < ${r}.length; ${a}++) {`),e.indented(c=>{c.write(`const ${u} = ${r}[${a}];`);let d=ht(c,t,s.element,u,o);i&&d!==null&&c.write(`${i}[${a}] = ${d};`)}),e.write("}"),i}function iD(e,t,n,r){let s=n._zod.def.values;if(s.length!==1){let a=fe(t,new Set(s));return e.write(`if (!${a}.has(${r})) return INVALID;`),r}let i=s[0];if(typeof i=="number"&&Number.isNaN(i)){let a=fe(t,new Set(s));return e.write(`if (!${a}.has(${r})) return INVALID;`),r}if(typeof i=="string")e.write(`if (${r} !== ${vt(i)}) return INVALID;`);else if(typeof i=="number"||typeof i=="boolean")e.write(`if (${r} !== ${i}) return INVALID;`);else if(i===null)e.write(`if (${r} !== null) return INVALID;`);else if(i===void 0)e.write(`if (${r} !== undefined) return INVALID;`);else if(typeof i=="bigint")e.write(`if (${r} !== ${i}n) return INVALID;`);else throw new Se(`literal type ${typeof i}`);return r}function aD(e,t,n,r){let o=n._zod.values;if(!o)throw new Se("enum schema without enumerated values");let s=fe(t,o);return e.write(`if (!${s}.has(${r})) return INVALID;`),r}function tA(e,t,n,r){let o=n._zod.def;return Be(e,t,o.innerType,r)}function lD(e,t,n,r){let o=n._zod.def,i=Object.getOwnPropertyDescriptor(n._zod.def,"defaultValue")?()=>n._zod.def.defaultValue:void 0;if(n._zod.def.type==="prefault"){if(!i)return Be(e,t,o.innerType,r);let u=fe(t,i),c=ce(t);return e.write(`let ${c} = ${r};`),e.write(`if (${r} === undefined) ${c} = ${u}();`),Be(e,t,o.innerType,c)}let a=ce(t);if(i){let u=fe(t,i),c=fe(t,Da);e.write(`let ${a};`),e.write(`if (${r} === undefined) {`),e.indented(d=>{d.write(`${a} = ${c}(${u}());`)}),e.write("} else {"),e.indented(d=>{let p=Be(d,t,o.innerType,r);d.write(`${a} = ${p} === undefined ? ${c}(${u}()) : ${p};`)}),e.write("}")}else e.write(`let ${a};`),e.write(`if (${r} !== undefined) {`),e.indented(u=>{let c=Be(u,t,o.innerType,r);u.write(`${a} = ${c};`)}),e.write("}");return a}function cD(e,t,n,r){let o=n._zod.def,s=Be(e,t,o.innerType,r),i=ce(t);return e.write(`const ${i} = ${s};`),e.write(`if (${i} === undefined) return INVALID;`),i}function uD(e,t,n,r){let o=n._zod.def,s=o.items,i=o.rest;e.write(`if (!Array.isArray(${r})) return INVALID;`);let a=nA(s,"optin"),u=nA(s,"optout");i?e.write(`if (${r}.length < ${a}) return INVALID;`):e.write(`if (${r}.length < ${a} || ${r}.length > ${s.length}) return INVALID;`);let c=ce(t);e.write(`const ${c} = [];`);for(let d=0;d<s.length;d++){let p=s[d];if(d>=u)e.write(`if (${c}.length === ${d}) {`),e.indented(f=>{f.write(`if (${d} < ${r}.length) {`),f.indented(h=>{let g=ce(t);h.write(`const ${g} = ${r}[${d}];`);let x=ht(h,t,p,g);h.write(`${c}[${d}] = ${x};`)}),f.write("} else {"),f.indented(h=>{if(Fx(p)){h.write(`${c}.length = ${d};`);return}let g=ce(t),x=ce(t);h.write(`const ${g} = undefined;`),h.write(`const ${x} = (() => {`),h.indented(b=>{let _=ht(b,t,p,g);b.write(`return ${_};`)}),h.write("})();"),h.write(`if (${x} === INVALID || ${x} === undefined) ${c}.length = ${d};`),h.write(`else ${c}[${d}] = ${x};`)}),f.write("}")}),e.write("}");else{let f=ce(t);e.write(`const ${f} = ${r}[${d}];`);let h=ht(e,t,p,f);e.write(`${c}[${d}] = ${h};`)}}if(i){let d=ce(t),p=ce(t);e.write(`for (let ${d} = ${s.length}; ${d} < ${r}.length; ${d}++) {`),e.indented(f=>{f.write(`const ${p} = ${r}[${d}];`);let h=ht(f,t,i,p);f.write(`${c}[${d}] = ${h};`)}),e.write("}")}return c}function nA(e,t){for(let n=e.length-1;n>=0;n--)if(!(t==="optin"?e[n]._zod.optin!==void 0:e[n]._zod.optout==="optional"))return n+1;return 0}function dD(e,t,n,r){let o=n._zod.def,s=o.options;if(o.discriminator)return pD(e,t,o,r);if(o.inclusive===!1)throw new Se("exclusive unions (z.xor)");if(s.length===0)return e.write("return INVALID;"),r;if(s.length===1)return Be(e,t,s[0],r);if(s.every(u=>u._zod.def.type==="literal"&&!u._zod.def.checks?.length)){let u=new Set(s.flatMap(d=>d._zod.def.values)),c=fe(t,u);return e.write(`if (!${c}.has(${r})) return INVALID;`),r}let a=ce(t);e.write(`let ${a};`);for(let u=0;u<s.length;u++){let c=s[u];u===0?e.write(`${a} = (() => {`):e.write(`if (${a} === INVALID) ${a} = (() => {`),e.indented(d=>{let p=Be(d,t,c,r);d.write(`return ${p};`)}),e.write("})();")}return e.write(`if (${a} === INVALID) return INVALID;`),a}function pD(e,t,n,r){if(n.unionFallback)throw new Se("discriminated union with unionFallback");if(n.options.length===0)return e.write("return INVALID;"),r;let o=ce(t),s=ce(t);e.write(`const ${o} = ${r}?.[${vt(n.discriminator)}];`),e.write(`let ${s};`);let i=!0,a=new Set;for(let u of n.options){let c=u._zod.propValues?.[n.discriminator];if(!c||c.size===0)throw new Se("discriminated union option without static discriminator values");for(let f of c){if(a.has(f))throw new Se(`duplicate discriminator value ${String(f)}`);a.add(f)}let d=Array.from(c,f=>fD(t,o,f)),p=i?"if":"else if";e.write(`${p} (${d.join(" || ")}) {`),e.indented(f=>{let h=Be(f,t,u,r);f.write(`${s} = ${h};`)}),e.write("}"),i=!1}return e.write("else { return INVALID; }"),s}function fD(e,t,n){if(typeof n=="string")return`${t} === ${vt(n)}`;if(typeof n=="number")return Number.isNaN(n)?`Number.isNaN(${t})`:`${t} === ${n}`;if(typeof n=="boolean")return`${t} === ${n}`;if(n===null)return`${t} === null`;if(n===void 0)return`${t} === undefined`;if(typeof n=="bigint")return`${t} === ${n}n`;if(typeof n=="symbol"){let r=fe(e,n);return`${t} === ${r}`}throw new Se(`literal discriminator value ${String(n)}`)}function hD(e,t,n,r){let o=n._zod.def;t.definite=!1;let s=ht(e,t,o.left,r),i=ht(e,t,o.right,r),a=fe(t,js),u=ce(t);return e.write(`const ${u} = ${a}(${s}, ${i});`),e.write(`if (!${u}.valid) return INVALID;`),`${u}.data`}function mD(e,t,n,r){let o=n._zod.def,s=fe(t,Vt);e.write(`if (!${s}(${r})) return INVALID;`);let i=ce(t),a=ce(t),u=ce(t);e.write(`const ${i} = {};`);let c=o,d=c.partial?void 0:o.keyType._zod.values;if(d){let h=[];for(let x of d){if(!(typeof x=="string"||typeof x=="number"||typeof x=="symbol"))throw new Se(`record key value ${String(x)}`);let b=typeof x=="number"?x.toString():x;if(b==="__proto__")throw new Se('record key "__proto__"');h.push(b);let _=fe(t,x),w=Be(e,t,o.keyType,_),T=ce(t);e.write(`const ${T} = ${r}[${gD(t,b)}];`);let y=ht(e,t,o.valueType,T);e.write(`${i}[${w}] = ${y};`)}let g=fe(t,new Set(h));return e.write(`for (const ${a} in ${r}) {`),e.indented(x=>{x.write(`if (${g}.has(${a})) continue;`),c.mode==="loose"?x.write(`if (${a} !== "__proto__") ${i}[${a}] = ${r}[${a}];`):x.write("return INVALID;")}),e.write("}"),i}let p=o.keyType._zod.def;if(!(p.type==="string"&&p.format===void 0&&!p.coerce&&(p.checks?.length??0)===0)){let h=o.mode==="loose",g=Qd(o.keyType);g.definite===!1&&(t.definite=!1);let x=fe(t,g),b=fe(t,Zn),_=ce(t);return rA(e,t,r,a,w=>{w.write(`let ${_} = ${x}(${a});`),w.write(`if (${_} === INVALID && typeof ${a} === "string" && ${b}.test(${a})) ${_} = ${x}(Number(${a}));`),h?w.write(`if (${_} === INVALID) { ${i}[${a}] = ${r}[${a}]; continue; }`):w.write(`if (${_} === INVALID) return INVALID;`),w.write(`if (${_} === "__proto__") continue;`);let T=ce(t);w.write(`const ${T} = ${r}[${a}];`);let y=ht(w,t,o.valueType,T);w.write(`${i}[${_}] = ${y};`)}),i}return rA(e,t,r,a,h=>{h.write(`const ${u} = ${r}[${a}];`);let g=ht(h,t,o.valueType,u);h.write(`${i}[${a}] = ${g};`)},"return INVALID;"),i}function rA(e,t,n,r,o,s){let i=fe(t,Object.prototype.propertyIsEnumerable),a=ce(t),u=ce(t),c=ce(t);e.write(`const ${a} = Object.getOwnPropertySymbols(${n});`),e.write(`const ${u} = Object.getOwnPropertyNames(${n});`),e.write(`for (let ${c} = 0; ${c} < ${u}.length; ${c}++) {`),e.indented(d=>{d.write(`const ${r} = ${u}[${c}];`),d.write(`if (${r} === "__proto__" || !${i}.call(${n}, ${r})) continue;`),o(d)}),e.write("}"),e.write(`for (let ${c} = 0; ${c} < ${a}.length; ${c}++) {`),e.indented(d=>{d.write(`const ${r} = ${a}[${c}];`),d.write(`if (!${i}.call(${n}, ${r})) continue;`),s?d.write(s):o(d)}),e.write("}")}function gD(e,t){return typeof t=="string"?vt(t):fe(e,t)}function xD(e,t,n,r){let o=n._zod.def;e.write(`if (!(${r} instanceof Map)) return INVALID;`);let s=ce(t),i=ce(t),a=ce(t);return e.write(`const ${s} = new Map();`),e.write(`for (const [${i}, ${a}] of ${r}) {`),e.indented(u=>{let c=Be(u,t,o.keyType,i),d=Be(u,t,o.valueType,a);u.write(`${s}.set(${c}, ${d});`)}),e.write("}"),s}function bD(e,t,n,r){let o=n._zod.def;e.write(`if (!(${r} instanceof Set)) return INVALID;`);let s=ce(t),i=ce(t);return e.write(`const ${s} = new Set();`),e.write(`for (const ${i} of ${r}) {`),e.indented(a=>{let u=Be(a,t,o.valueType,i);a.write(`${s}.add(${u});`)}),e.write("}"),s}function yD(e,t){return e.write(`if (!(${t} instanceof File)) return INVALID;`),t}function _D(e,t,n,r){e.write(`if (typeof ${r} !== "string") return INVALID;`);let o=n._zod.pattern;if(o){let s=fe(t,o);e.write(`${s}.lastIndex = 0;`),e.write(`if (!${s}.test(${r})) return INVALID;`)}return r}function vD(e,t,n,r){let o=n._zod.def,s=yo(t,o.getter),i=fe(t,{parser:null});e.write(`if (!${i}.parser) {`),e.indented(u=>{u.write(`const inner = ${s}();`),u.write(`${i}.parser = function(input) {`),u.indented(c=>{c.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),c.write("return result.issues.length === 0 ? result.value : INVALID;")}),u.write("};")}),e.write("}");let a=ce(t);return e.write(`const ${a} = ${i}.parser(${r});`),e.write(`if (${a} === INVALID) return INVALID;`),a}function wD(e,t,n,r){let o=n._zod.def,s=Be(e,t,o.in,r);if(o.transform){if(_o(o.transform))throw new ln("z.compile: async transforms in pipes are not supported");let i=o.transform,u=yo(t,d=>{let p={value:d,issues:[],addIssue:Kx},f=i(d,p);return f instanceof Promise?kt:p.issues.length===0?f:kt}),c=ce(t);return e.write(`const ${c} = ${u}(${s});`),e.write(`if (${c} === INVALID) return INVALID;`),Be(e,t,o.out,c)}else return Be(e,t,o.out,s)}function _o(e){return typeof e=="function"&&(e.constructor.name==="AsyncFunction"||e[Symbol.toStringTag]==="AsyncFunction")}function kD(e,t,n,r){let o=n._zod.def;if(o.fn){if(_o(o.fn))throw new ln("z.compile: async custom predicates are not supported");let s=yo(t,o.fn),i=fe(t,Dx),a=ce(t);e.write(`const ${a} = ${s}(${r});`),e.write(`if (${a} instanceof Promise) ${i}();`),e.write(`if (!${a}) return INVALID;`)}else throw new Se("custom schema without a predicate function");return r}function SD(e,t,n){let r=e._zod.run({value:n,issues:[]},{});if(r&&typeof r.then=="function")return kt;let o=r;return o.issues.length===0?o.value:t()}function ED(e,t,n,r){let o=n._zod.def;if(!o.catchValue[nd])throw new Se("catch with a callback (only a constant catch value compiles)",!1);let s=ce(t);e.write(`let ${s} = (() => {`),e.indented(c=>{let d=ht(c,t,o.innerType,r);c.write(`return ${d};`)}),e.write("})();");let i=fe(t,o.innerType),a=yo(t,o.catchValue),u=fe(t,SD);return e.write(`if (${s} === INVALID) {`),e.indented(c=>{c.write(`${s} = ${u}(${i}, ${a}, ${r});`),c.write(`if (${s} === INVALID) return INVALID;`)}),e.write("}"),s}function ND(e,t,n,r){let o=n._zod.def;if(o.transform){if(_o(o.transform))throw new ln("z.compile: async transforms are not supported");let s=o.transform,a=yo(t,c=>{let d={value:c,issues:[],addIssue:Kx},p=s(c,d);return p instanceof Promise?kt:d.issues.length===0?p:kt}),u=ce(t);return e.write(`const ${u} = ${a}(${r});`),e.write(`if (${u} === INVALID) return INVALID;`),u}return r}function Gd(e){return e.checks&&(e.checks=[...e.checks]),e}function Xx(e,t){return new e(Gd({type:"string",...W(t)}))}function Bx(e,t){return new e(Gd({type:"string",coerce:!0,...W(t)}))}function Yd(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...W(t)})}function qd(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...W(t)})}function Jd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...W(t)})}function ep(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...W(t)})}function tp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...W(t)})}function np(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...W(t)})}function dl(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...W(t)})}function rp(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...W(t)})}function op(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...W(t)})}function sp(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...W(t)})}function ip(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...W(t)})}function ap(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...W(t)})}function lp(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...W(t)})}function cp(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...W(t)})}function up(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...W(t)})}function dp(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...W(t)})}function Ux(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...W(t)})}function pp(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...W(t)})}function fp(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...W(t)})}function hp(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...W(t)})}function mp(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...W(t)})}function gp(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...W(t)})}function Hx(e,t){return new e({type:"string",format:"credit_card",check:"string_format",abort:!1,...W(t)})}function Vx(e,t){return new e({type:"string",format:"iban",check:"string_format",abort:!1,...W(t)})}function xp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...W(t)})}var Zx={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function pl(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...W(t)})}function fl(e,t){return new e({type:"string",format:"date",check:"string_format",...W(t)})}function hl(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...W(t)})}function ml(e,t){return new e({type:"string",format:"duration",check:"string_format",...W(t)})}function Wx(e,t){return new e(Gd({type:"number",checks:[],...W(t)}))}function jx(e,t){return new e(Gd({type:"number",coerce:!0,checks:[],...W(t)}))}function Qx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...W(t)})}function Gx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...W(t)})}function Yx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...W(t)})}function qx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...W(t)})}function Jx(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...W(t)})}function eb(e,t){return new e({type:"boolean",...W(t)})}function tb(e,t){return new e({type:"boolean",coerce:!0,...W(t)})}function nb(e,t){return new e({type:"bigint",...W(t)})}function rb(e,t){return new e({type:"bigint",coerce:!0,...W(t)})}function ob(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...W(t)})}function sb(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...W(t)})}function ib(e,t){return new e({type:"symbol",...W(t)})}function ab(e,t){return new e({type:"undefined",...W(t)})}function lb(e,t){return new e({type:"null",...W(t)})}function cb(e){return new e({type:"any"})}function ub(e){return new e({type:"unknown"})}function db(e,t){return new e({type:"never",...W(t)})}function pb(e,t){return new e({type:"void",...W(t)})}function fb(e,t){return new e({type:"date",...W(t)})}function hb(e,t){return new e({type:"date",coerce:!0,...W(t)})}function mb(e,t){return new e({type:"nan",...W(t)})}function kn(e,t){return new bd({check:"less_than",...W(t),value:e,inclusive:!1})}function Dt(e,t){return new bd({check:"less_than",...W(t),value:e,inclusive:!0})}function Sn(e,t){return new yd({check:"greater_than",...W(t),value:e,inclusive:!1})}function Ft(e,t){return new yd({check:"greater_than",...W(t),value:e,inclusive:!0})}function bp(e){return Sn(0,e)}function yp(e){return kn(0,e)}function _p(e){return Dt(0,e)}function vp(e){return Ft(0,e)}function yr(e,t){return new Jg({check:"multiple_of",...W(t),value:e})}function _r(e,t){return new n0({check:"max_size",...W(t),maximum:e})}function En(e,t){return new r0({check:"min_size",...W(t),minimum:e})}function vo(e,t){return new o0({check:"size_equals",...W(t),size:e})}function wo(e,t){return new s0({check:"max_length",...W(t),maximum:e})}function Wn(e,t){return new i0({check:"min_length",...W(t),minimum:e})}function ko(e,t){return new a0({check:"length_equals",...W(t),length:e})}function Ys(e,t){return new l0({check:"string_format",format:"regex",...W(t),pattern:e})}function qs(e){return new c0({check:"string_format",format:"lowercase",...W(e)})}function Js(e){return new u0({check:"string_format",format:"uppercase",...W(e)})}function ei(e,t){return new d0({check:"string_format",format:"includes",...W(t),includes:e})}function ti(e,t){return new p0({check:"string_format",format:"starts_with",...W(t),prefix:e})}function ni(e,t){return new f0({check:"string_format",format:"ends_with",...W(t),suffix:e})}function wp(e,t,n){return new h0({check:"property",property:e,schema:t,...W(n)})}function ri(e,t){return new m0({check:"properties",shape:e,...W(t)})}function oi(e,t){return new g0({check:"mime_type",mime:e,...W(t)})}function cn(e){return new x0({check:"overwrite",tx:e})}function si(e){return cn(t=>t.normalize(e))}function ii(){return cn(e=>e.trim())}function ai(){return cn(e=>e.toLowerCase())}function li(){return cn(e=>e.toUpperCase())}function ci(){return cn(e=>eg(e))}function gb(e,t,n){return new e({type:"array",element:t,...W(n)})}function AD(e,t,n){return new e({type:"union",options:t,...W(n)})}function CD(e,t,n){return new e({type:"union",options:t,inclusive:!1,...W(n)})}function TD(e,t,n,r){return new e({type:"union",options:n,discriminator:t,...W(r)})}function RD(e,t,n){return new e({type:"intersection",left:t,right:n})}function $D(e,t,n,r){let o=n instanceof me,s=o?r:n,i=o?n:null;return new e({type:"tuple",items:t,rest:i,...W(s)})}function ID(e,t,n,r){return new e({type:"record",keyType:t,valueType:n,...W(r)})}function PD(e,t,n,r){return new e({type:"map",keyType:t,valueType:n,...W(r)})}function OD(e,t,n){return new e({type:"set",valueType:t,...W(n)})}function LD(e,t,n){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new e({type:"enum",entries:r,...W(n)})}function MD(e,t,n){return new e({type:"enum",entries:t,...W(n)})}function DD(e,t,n){return new e({type:"literal",values:Array.isArray(t)?t:[t],...W(n)})}function xb(e,t){return new e({type:"file",...W(t)})}function FD(e,t){return new e({type:"transform",transform:t})}function zD(e,t){return new e({type:"optional",innerType:t})}function KD(e,t){return new e({type:"nullable",innerType:t})}function XD(e,t,n){return new e({type:"default",innerType:t,get defaultValue(){return typeof n=="function"?n():Da(n)}})}function BD(e,t,n){return new e({type:"nonoptional",innerType:t,...W(n)})}function UD(e,t){return new e({type:"success",innerType:t})}function HD(e,t,n){return new e({type:"catch",innerType:t,catchValue:typeof n=="function"?n:ag(n)})}function VD(e,t,n){return new e({type:"pipe",in:t,out:n})}function ZD(e,t){return new e({type:"readonly",innerType:t})}function WD(e,t,n){return new e({type:"template_literal",parts:t,...W(n)})}function jD(e,t){return new e({type:"lazy",getter:t})}function QD(e,t){return new e({type:"promise",innerType:t})}function bb(e,t,n){let r=W(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function yb(e,t,n){return new e({type:"custom",check:"custom",fn:t,...W(n)})}function _b(e,t){let n=aA(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(Bs(o,r.value,n._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),r.issues.push(Bs(s))}},e(r.value,r)),t);return n}function aA(e,t){let n=new Fe({check:"custom",...W(t)});return n._zod.check=e,n}function vb(e){let t=new Fe({check:"describe"});return t._zod.onattach=[n=>{let r=at.get(n)??{};at.add(n,{...r,description:e})}],t._zod.check=()=>{},t}function wb(e){let t=new Fe({check:"meta"});return t._zod.onattach=[n=>{let r=at.get(n)??{};at.add(n,{...r,...e})}],t._zod.check=()=>{},t}function kb(e,t){let n=W(t),r=n.truthy??["true","1","yes","on","y","enabled"],o=n.falsy??["false","0","no","off","n","disabled"];n.case!=="sensitive"&&(r=r.map(h=>typeof h=="string"?h.toLowerCase():h),o=o.map(h=>typeof h=="string"?h.toLowerCase():h));let s=new Set(r),i=new Set(o),a=e.Codec??sl,u=e.Boolean??rl,c=e.String??go,d=new c({type:"string",error:n.error}),p=new u({type:"boolean",error:n.error}),f=new a({type:"pipe",in:d,out:p,transform:((h,g)=>{let x=h;return n.case!=="sensitive"&&(x=x.toLowerCase()),s.has(x)?!0:i.has(x)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...s,...i],input:g.value,inst:f,continue:!1}),{})}),reverseTransform:((h,g)=>h===!0?r[0]||"true":o[0]||"false"),error:n.error});return f._zod.bag.truthy=r,f._zod.bag.falsy=o,f._zod.bag.case=n.case??"insensitive",f}function So(e,t,n,r={}){let o=W(r),s={check:"string_format",type:"string",format:t,fn:typeof n=="function"?n:a=>n.test(a),...o};return n instanceof RegExp&&(s.pattern=n),new e(s)}function gl(e,...t){for(let n of t)for(let r of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,r)&&it(e,r,n[r]);return e}function vr(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??at,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function et(e,t,n,r,o){let s=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:r.path,message:o}):t.unrepresentable;if(s==="any")return!1;if(s===void 0||s==="throw")throw new Error(o);return Object.assign(n,s),!0}function $e(e,t,n={path:[],schemaPath:[]}){var r;let o=e._zod.def,s=t.seen.get(e);if(s)return s.count++,n.schemaPath.includes(e)&&(s.cycle=n.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,i),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,d);else{let f=i.schema,h=t.processors[o.type];if(!h)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);h(e,t,f,d)}let p=e._zod.parent;p&&(i.ref||(i.ref=p),$e(p,t,d),t.seen.get(p).isParent=!0)}let u=t.metadataRegistry.get(e);return u&&gl(i.schema,u),t.io==="input"&&St(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function lA(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function wr(e,t){let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let u=r.get(a);if(u&&u!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,i[0])}}let o=i=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(i[0])?.id,f=e.external.uri??(g=>g);if(p)return{ref:f(p)};let h=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=h,{defId:h,ref:`${f("__shared")}#/${a}/${lA(h)}`}}let u="#",c=`${u}/${a}/`;if(i[1]===n&&!i[1].schema.id)return{ref:u};let d=i[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:c+lA(d)}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:u,defId:c}=o(i);a.def={...a.schema},c&&(a.defId=c);let d=a.schema;for(let p in d)delete d[p];d.$ref=u};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
209
209
 
210
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let c=e.external.registry.get(i[0])?.id;if(t!==i[0]&&c){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}a.count>1&&e.reused==="ref"&&s(i)}e.external&&(e.sharedDefsExtractedFor=e.external)}function aA(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let r of t){if(!r||typeof r!="object")return;aA(r);let o=Object.keys(r);if(o.length!==1||o[0]!=="type")return;let s=r.type;for(let i of Array.isArray(s)?s:[s]){if(typeof i!="string")return;n.includes(i)||n.push(i)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var lA=new Set(["type","properties","required","additionalProperties"]),sA=["oneOf","anyOf"];function iA(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function wb(e){let t=[];for(let s of e){if(typeof s!="object"||s.type!=="object")return null;for(let i in s)if(!lA.has(i))return null;t.push(s)}let n={},r=new Set;for(let s of t){for(let i in s.properties){if(Object.prototype.hasOwnProperty.call(n,i))continue;let a=[];for(let c of t){let d=c.properties?.[i]??iA(c);d!=null&&(a.some(p=>JSON.stringify(p)===JSON.stringify(d))||a.push(d))}let u=a.length===1?a[0]:wb(a)??{allOf:a};it(n,i,u)}for(let i of s.required??[])r.add(i)}let o={type:"object",properties:n};if(r.size&&(o.required=[...r]),t.every(s=>s.additionalProperties===!1))o.additionalProperties=!1;else{let s=[];for(let i of t){let a=iA(i);a&&!s.some(u=>JSON.stringify(u)===JSON.stringify(a))&&s.push(a)}s.length===1?o.additionalProperties=s[0]:s.length>1&&(o.additionalProperties={allOf:s})}return o}function ZD(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let o of lA)if(o in e)return;let n=t.filter(o=>sA.some(s=>Array.isArray(o[s]))),r=null;if(!n.length)r=wb(t);else{let o=n[0],s=sA.find(u=>Array.isArray(o[u]));if(Object.keys(o).length!==1)return;let i=t.filter(u=>u!==o),a=o[s].map(u=>wb([...i,u]));if(a.some(u=>!u))return;r={[s]:a}}r&&(delete e.allOf,ml(e,r))}function wr(e,t){let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=a=>{let u=e.seen.get(a);if(u.ref===null)return;let c=u.def??u.schema,d={...c},p=u.ref;if(u.ref=null,p){r(p);let h=e.seen.get(p),g=h.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(g)):ml(c,g),ml(c,d),a._zod.parent===p)for(let b in c)b==="$ref"||b==="allOf"||b in d||delete c[b];if(g.$ref&&h.def)for(let b in c)b==="$ref"||b==="allOf"||b in h.def&&JSON.stringify(c[b])===JSON.stringify(h.def[b])&&delete c[b]}let f=a._zod.parent;if(f&&f!==p){r(f);let h=e.seen.get(f);if(h?.schema.$ref&&(c.$ref=h.schema.$ref,h.def))for(let g in c)g==="$ref"||g==="allOf"||g in h.def&&JSON.stringify(c[g])===JSON.stringify(h.def[g])&&delete c[g]}e.override({zodSchema:a,jsonSchema:c,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())r(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())aA(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let u of e.seen.values())for(let c of[u.schema,u.def]){let d=c?.allOf;if(!Array.isArray(d))continue;let p=a.get(d);p?p.push(c):a.set(d,[c])}for(let u of e.intersections)for(let c of a.get(u)??[])ZD(c)}}let o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}ml(o,n.defId?n.schema:n.def??n.schema);let s=e.metadataRegistry.get(t)?.id;s!==void 0&&o.id===s&&delete o.id;let i=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let u=a[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,it(i,u.defId,u.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:ci(t,"input",e.processors),output:ci(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function St(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return St(r.element,n);if(r.type==="set")return St(r.valueType,n);if(r.type==="lazy")return St(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault"||r.type==="catch")return St(r.innerType,n);if(r.type==="intersection")return St(r.left,n)||St(r.right,n);if(r.type==="record"||r.type==="map")return St(r.keyType,n)||St(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:St(r.in,n)||St(r.out,n);if(r.type==="object"){for(let o in r.shape)if(St(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(St(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(St(o,n))return!0;return!!(r.rest&&St(r.rest,n))}return!1}var kb=(e,t={})=>n=>{let r=_r({...n,processors:t});return $e(e,r),vr(r,e),wr(r,e)},ci=(e,t,n={})=>r=>{let{libraryOptions:o,target:s}=r??{},i=_r({...o??{},target:s,io:t,processors:n});return $e(e,i),vr(i,e),wr(i,e)};var ui=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},di=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},cA=(e,t)=>{ui(e,"minimum",t),di(e,"maximum",t)},fA=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},hA=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},mA=(e,t)=>{e.mime=e.mime?e.mime.filter(n=>t.includes(n)):[...t]},gA=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},uA=(e,t)=>ui(e,"minimum",t.minimum),dA=(e,t)=>di(e,"maximum",t.maximum),pA=e=>(t,n)=>{gA(t,n.format);let[r,o]=e[n.format];ui(t,"minimum",r),di(t,"maximum",o)},WD={greater_than:(e,t)=>ui(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>di(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>fA(e,t.value),number_format:pA(Fa),bigint_format:pA(za),min_length:uA,max_length:dA,length_equals:(e,t)=>cA(e,t.length),min_size:uA,max_size:dA,size_equals:(e,t)=>cA(e,t.size),string_format:(e,t)=>{gA(e,t.format),t.pattern&&hA(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>mA(e,t.mime)};function et(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let s of r)WD[s._zod.def.check]?.(t,s._zod.def);let o=e._zod.bag;o.minimum!==void 0&&ui(t,"minimum",o.minimum),o.exclusiveMinimum!==void 0&&ui(t,"exclusiveMinimum",o.exclusiveMinimum),o.maximum!==void 0&&di(t,"maximum",o.maximum),o.exclusiveMaximum!==void 0&&di(t,"exclusiveMaximum",o.exclusiveMaximum),o.multipleOf!==void 0&&fA(t,o.multipleOf),o.format!==void 0&&(t.format??(t.format=o.format),o.format.includes("int")&&(t.isInt=!0)),o.mime&&mA(t,o.mime);for(let s of o.patterns??[])hA(t,s);return t}var jD={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},QD=new Map([[Ad,$g],[tl,Ig]]),xA=e=>QD.get(e)??e,Nb=(e,t,n,r)=>{let o=n;o.type="string";let{minimum:s,maximum:i,format:a,patterns:u,contentEncoding:c,laxFormat:d}=et(e);if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=jD[a]??a,o.format===""&&delete o.format,(a==="time"||d)&&delete o.format),c&&(o.contentEncoding=c),u&&u.size>0){let p=[...u].map(xA);p.length===1?o.pattern=p[0].source:p.length>1&&(o.allOf=[...p.map(f=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},Ab=(e,t,n,r)=>{let o=n,{minimum:s,maximum:i,multipleOf:a,exclusiveMaximum:u,exclusiveMinimum:c,isInt:d}=et(e);o.type=d?"integer":"number";let p=typeof c=="number"&&c>=(s??Number.NEGATIVE_INFINITY),f=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),h=t.target==="draft-04"||t.target==="openapi-3.0";if(p?h?(o.minimum=c,o.exclusiveMinimum=!0):o.exclusiveMinimum=c:typeof s=="number"&&(o.minimum=s),f?h?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),a){let g=new Set;for(let v of a)Number.isFinite(v)&&v!==0?g.add(Math.abs(v)):Je(e,t,o,r,`A multipleOf divisor of ${v} cannot be represented in JSON Schema`);let[x,...b]=g;x!==void 0&&(o.multipleOf=x),b.length&&(o.allOf=[...o.allOf??[],...b.map(v=>({multipleOf:v}))])}},Cb=(e,t,n,r)=>{n.type="boolean"},Tb=(e,t,n,r)=>{Je(e,t,n,r,"BigInt cannot be represented in JSON Schema")},Rb=(e,t,n,r)=>{Je(e,t,n,r,"Symbols cannot be represented in JSON Schema")},$b=(e,t,n,r)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},Ib=(e,t,n,r)=>{Je(e,t,n,r,"Undefined cannot be represented in JSON Schema")},Pb=(e,t,n,r)=>{Je(e,t,n,r,"Void cannot be represented in JSON Schema")},Ob=(e,t,n,r)=>{n.not={}},Lb=(e,t,n,r)=>{},Mb=(e,t,n,r)=>{},Db=(e,t,n,r)=>{Je(e,t,n,r,"Date cannot be represented in JSON Schema")},Fb=(e,t,n,r)=>{let o=e._zod.def,s=Ds(o.entries);if(s.length===0){n.not={};return}s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},zb=(e,t,n,r)=>{let o=e._zod.def;if(o.values.length===0){n.not={};return}let s=[];for(let i of o.values)if(i===void 0){if(Je(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof i=="bigint"){if(Je(e,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];n.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[i]:n.const=i}else s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),s.every(i=>typeof i=="boolean")&&(n.type="boolean"),s.every(i=>i===null)&&(n.type="null"),n.enum=s},Kb=(e,t,n,r)=>{Je(e,t,n,r,"NaN cannot be represented in JSON Schema")},Xb=(e,t,n,r)=>{let o=n,s=e._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=s.source},Bb=(e,t,n,r)=>{let o=n;o.type="string",o.format="binary",o.contentEncoding="binary";let{minimum:s,maximum:i,mime:a}=et(e);s!==void 0&&(o.minLength=s),i!==void 0&&(o.maxLength=i),a&&(a.length===0?o.not={}:a.length===1?o.contentMediaType=a[0]:o.anyOf=a.map(u=>({contentMediaType:u})))},Ub=(e,t,n,r)=>{n.type="boolean"},Hb=(e,t,n,r)=>{Je(e,t,n,r,"Custom types cannot be represented in JSON Schema")},Vb=(e,t,n,r)=>{Je(e,t,n,r,"Function types cannot be represented in JSON Schema")},Zb=(e,t,n,r)=>{Je(e,t,n,r,"Transforms cannot be represented in JSON Schema")},Wb=(e,t,n,r)=>{Je(e,t,n,r,"Map cannot be represented in JSON Schema")},jb=(e,t,n,r)=>{Je(e,t,n,r,"Set cannot be represented in JSON Schema")},Qb=(e,t,n,r)=>{let o=n,s=e._zod.def,{minimum:i,maximum:a}=et(e);typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=$e(s.element,t,{...r,path:[...r.path,"items"]})};function gl(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?gl(t.out):t.type==="catch"?gl(t.innerType):e._zod.optin}var Gb=(e,t,n,r)=>{let o=n,s=e._zod.def,i=s.shape;if(Object.getOwnPropertySymbols(i).length&&Je(e,t,o,r,"Symbol keys cannot be represented in JSON Schema"))return;o.type="object",o.properties={};for(let c in i)it(o.properties,c,$e(i[c],t,{...r,path:[...r.path,"properties",c]}));let u=[];for(let c of Object.keys(i)){let d=s.shape[c];(t.io==="input"?gl(d)===void 0:d._zod.optout===void 0)&&u.push(c)}u.length>0&&(o.required=u),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=$e(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},wp=(e,t,n,r)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((a,u)=>$e(a,t,{...r,path:[...r.path,s?"oneOf":"anyOf",u]}));s?n.oneOf=i:n.anyOf=i},Yb=(e,t,n,r)=>{let o=e._zod.def,s=$e(o.left,t,{...r,path:[...r.path,"allOf",0]}),i=$e(o.right,t,{...r,path:[...r.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1,u=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];n.allOf=u,t.intersections.push(u)},qb=(e,t,n,r)=>{let o=n,s=e._zod.def;o.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=s.items.map((x,b)=>$e(x,t,{...r,path:[...r.path,i,b]})),c=s.rest?$e(s.rest,t,{...r,path:[...r.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null,d=s.items.length;for(;d>0;){let x=s.items[d-1];if(!(t.io==="input"?gl(x)!==void 0:x._zod.optout==="optional"))break;d--}let p=s.items.length,f=!s.rest;t.target==="draft-2020-12"?(o.prefixItems=u,f?o.items=!1:c&&(o.items=c),d>0&&(o.minItems=d),f&&(o.maxItems=p)):t.target==="openapi-3.0"?(o.items={anyOf:u},c&&o.items.anyOf.push(c),d>0&&(o.minItems=d),f&&(o.maxItems=p)):(o.items=u,f?o.additionalItems=!1:c&&(o.additionalItems=c),d>0&&(o.minItems=d),f&&(o.maxItems=p));let{minimum:h,maximum:g}=et(e);typeof h=="number"&&(o.minItems=h),typeof g=="number"&&(o.maxItems=g)};function Sb(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let g=e.get(t)?.def;if(!g)return t;let x=Sb(e,g,n);return x===g?t:x}for(let g of["anyOf","oneOf"]){let x=t[g];if(!Array.isArray(x))continue;let b=x.map(v=>Sb(e,v,n));b.some((v,w)=>v!==x[w])&&(t={...t,[g]:b})}let r=Array.isArray(t.type)?t.type:[t.type],o=!r.includes("string")&&r.some(g=>g==="number"||g==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!o&&!s?.some(g=>typeof g=="number"))return t;let{minimum:i,maximum:a,exclusiveMinimum:u,exclusiveMaximum:c,multipleOf:d,format:p,id:f,...h}=t;return h.enum?h.enum=h.enum.map(g=>typeof g=="number"?String(g):g):typeof h.const=="number"&&(h.const=String(h.const)),o&&(h.type="string",s||(h.pattern=(r.includes("number")?Vn:ja).source)),h}var Eb=new WeakMap;function GD(e){let t=new Map;for(let r of e.seen.values())r.def&&!t.has(r.schema)&&t.set(r.schema,r);let n=new Map;for(let r of Eb.get(e)??[]){let o=e.seen.get(r),s=(o?.def??o?.schema)?.propertyNames;if(!s||s===!0||n.has(s))continue;let i=Sb(t,s,new Set);i!==s&&n.set(s,i)}if(n.size)for(let r of e.seen.values())for(let o of[r.schema,r.def]){let s=o&&n.get(o.propertyNames);s&&(o.propertyNames=s)}}var Jb=(e,t,n,r)=>{let o=n,s=e._zod.def;o.type="object";let i=s.keyType,a=et(i).patterns;if(s.mode==="loose"&&a&&a.size>0){let d=$e(s.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let p of a)it(o.patternProperties,xA(p).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){o.propertyNames=$e(s.keyType,t,{...r,path:[...r.path,"propertyNames"]});let d=Eb.get(t);d||(d=[],Eb.set(t,d),t.deferred.push(()=>GD(t))),d.push(e)}o.additionalProperties=$e(s.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let u=i._zod.values,c=t.io==="input"&&gl(s.valueType)!==void 0;if(u&&!s.partial&&!c){let d=[...u].filter(p=>typeof p=="string"||typeof p=="number");d.length>0&&(o.required=d.map(String))}},ey=(e,t,n,r)=>{let o=e._zod.def,s=$e(o.innerType,t,r),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=o.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},ty=(e,t,n,r)=>{let o=e._zod.def;$e(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType},ny=Symbol();function bA(e,t,n,r,o){let s=!1,i=JSON.stringify(e,(a,u)=>typeof u!="bigint"?u:(s=!0,null));return s?(Je(t,n,r,o,"BigInt defaults cannot be represented in JSON Schema"),ny):JSON.parse(i)}var ry=(e,t,n,r)=>{let o=e._zod.def;$e(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType;let i=bA(o.defaultValue,e,t,n,r);i!==ny&&(n.default=i)},oy=(e,t,n,r)=>{let o=e._zod.def;$e(o.innerType,t,r);let s=t.seen.get(e);if(s.ref=o.innerType,t.io!=="input")return;let i=bA(o.defaultValue,e,t,n,r);i!==ny&&(n._prefault=i)},sy=(e,t,n,r)=>{let o=e._zod.def;$e(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{Je(e,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=i},iy=(e,t,n,r)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;$e(i,t,r);let a=t.seen.get(e);a.ref=i},ay=(e,t,n,r)=>{let o=e._zod.def;$e(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType,n.readOnly=!0},ly=(e,t,n,r)=>{let o=e._zod.def;$e(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType},kp=(e,t,n,r)=>{let o=e._zod.def;$e(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType},cy=(e,t,n,r)=>{let o=e._zod.innerType;$e(o,t,r);let s=t.seen.get(e);s.ref=o},vp={string:Nb,number:Ab,boolean:Cb,bigint:Tb,symbol:Rb,null:$b,undefined:Ib,void:Pb,never:Ob,any:Lb,unknown:Mb,date:Db,enum:Fb,literal:zb,nan:Kb,template_literal:Xb,file:Bb,success:Ub,custom:Hb,function:Vb,transform:Zb,map:Wb,set:jb,array:Qb,object:Gb,union:wp,intersection:Yb,tuple:qb,record:Jb,nullable:ey,nonoptional:ty,default:ry,prefault:oy,catch:sy,pipe:iy,readonly:ay,promise:ly,optional:kp,lazy:cy};function Sp(e,t){if("_idmap"in e){let r=e,o=_r({...t,processors:vp}),s={};for(let u of r._idmap.entries()){let[c,d]=u;$e(d,o)}let i={},a={registry:r,uri:t?.uri,defs:s};o.external=a;for(let u of r._idmap.entries()){let[c,d]=u;vr(o,d),it(i,c,wr(o,d))}if(Object.keys(s).length>0){let u=o.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[u]:s}}return{schemas:i}}let n=_r({...t,processors:vp});return $e(e,n),vr(n,e),wr(n,e)}var Ep=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let n=t?.target??"draft-2020-12";n==="draft-4"&&(n="draft-04"),n==="draft-7"&&(n="draft-07"),this.ctx=_r({processors:vp,target:n,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,n={path:[],schemaPath:[]}){return $e(t,this.ctx,n)}emit(t,n){n&&(n.cycles&&(this.ctx.cycles=n.cycles),n.reused&&(this.ctx.reused=n.reused),n.external&&(this.ctx.external=n.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,vr(this.ctx,t);let r=wr(this.ctx,t),{"~standard":o,...s}=r;return s}};var yA={};var yi={};cn(yi,{ZodAny:()=>$y,ZodArray:()=>Ly,ZodBase64:()=>Hp,ZodBase64URL:()=>Vp,ZodBigInt:()=>xi,ZodBigIntFormat:()=>jp,ZodBoolean:()=>gi,ZodCIDRv4:()=>Bp,ZodCIDRv6:()=>Up,ZodCUID:()=>Lp,ZodCUID2:()=>Mp,ZodCatch:()=>n_,ZodCodec:()=>Nl,ZodCreditCard:()=>ky,ZodCustom:()=>Al,ZodCustomStringFormat:()=>Ao,ZodDate:()=>_l,ZodDefault:()=>Gy,ZodDiscriminatedUnion:()=>Dy,ZodE164:()=>Zp,ZodEmail:()=>$p,ZodEmoji:()=>Pp,ZodEnum:()=>fi,ZodExactOptional:()=>qp,ZodFile:()=>Zy,ZodFunction:()=>p_,ZodGUID:()=>Ip,ZodIBAN:()=>Sy,ZodIPv4:()=>Kp,ZodIPv6:()=>Xp,ZodISODate:()=>Sr,ZodISODateTime:()=>kr,ZodISODuration:()=>Nr,ZodISOTime:()=>Er,ZodInstanceOf:()=>m_,ZodIntersection:()=>Fy,ZodJWT:()=>Wp,ZodKSUID:()=>zp,ZodLazy:()=>c_,ZodLiteral:()=>Vy,ZodMAC:()=>wy,ZodMap:()=>Uy,ZodNaN:()=>o_,ZodNanoID:()=>Op,ZodNever:()=>Py,ZodNonOptional:()=>Jp,ZodNull:()=>Ty,ZodNullable:()=>Qy,ZodNumber:()=>mi,ZodNumberFormat:()=>Co,ZodObject:()=>wl,ZodOptional:()=>Sl,ZodPipe:()=>El,ZodPrefault:()=>qy,ZodPreprocess:()=>s_,ZodPromise:()=>d_,ZodReadonly:()=>i_,ZodRecord:()=>pi,ZodSet:()=>Hy,ZodString:()=>hi,ZodStringFormat:()=>Le,ZodSuccess:()=>t_,ZodSymbol:()=>Ay,ZodTemplateLiteral:()=>l_,ZodTransform:()=>Wy,ZodTuple:()=>Ky,ZodType:()=>ye,ZodULID:()=>Dp,ZodURL:()=>yl,ZodUUID:()=>En,ZodUndefined:()=>Cy,ZodUnion:()=>kl,ZodUnknown:()=>Iy,ZodVoid:()=>Oy,ZodXID:()=>Fp,ZodXor:()=>My,_ZodString:()=>Rp,_default:()=>Yy,_function:()=>$C,any:()=>lC,array:()=>vl,base64:()=>BA,base64url:()=>UA,bigint:()=>rC,boolean:()=>Ny,catch:()=>r_,check:()=>IC,cidrv4:()=>KA,cidrv6:()=>XA,codec:()=>AC,creditCard:()=>VA,cuid:()=>IA,cuid2:()=>PA,currencyCode:()=>YA,custom:()=>PC,date:()=>uC,describe:()=>OC,discriminatedUnion:()=>gC,e164:()=>HA,email:()=>wA,emoji:()=>RA,enum:()=>Gp,exactOptional:()=>jy,file:()=>kC,float32:()=>JA,float64:()=>eC,function:()=>$C,guid:()=>kA,hash:()=>qA,hex:()=>GA,hostname:()=>QA,httpUrl:()=>TA,iban:()=>ZA,instanceof:()=>MC,int:()=>Cp,int32:()=>tC,int64:()=>oC,intersection:()=>zy,invertCodec:()=>CC,ipv4:()=>DA,ipv6:()=>zA,json:()=>FC,jwt:()=>WA,keyof:()=>dC,ksuid:()=>MA,lazy:()=>u_,literal:()=>wC,looseObject:()=>hC,looseRecord:()=>bC,mac:()=>FA,map:()=>yC,meta:()=>LC,nan:()=>NC,nanoid:()=>$A,nativeEnum:()=>vC,never:()=>Qp,nonoptional:()=>e_,null:()=>Ry,nullable:()=>bl,nullish:()=>SC,number:()=>Ey,object:()=>pC,optional:()=>Eo,partialRecord:()=>xC,pipe:()=>Tp,prefault:()=>Jy,preprocess:()=>zC,promise:()=>RC,readonly:()=>a_,record:()=>By,refine:()=>f_,set:()=>_C,strictObject:()=>fC,string:()=>xl,stringFormat:()=>jA,stringbool:()=>DC,success:()=>EC,superRefine:()=>h_,symbol:()=>iC,templateLiteral:()=>TC,transform:()=>Yp,tuple:()=>Xy,uint32:()=>nC,uint64:()=>sC,ulid:()=>OA,undefined:()=>aC,union:()=>bi,unknown:()=>So,url:()=>CA,uuid:()=>SA,uuidv4:()=>EA,uuidv6:()=>NA,uuidv7:()=>AA,void:()=>cC,xid:()=>LA,xor:()=>mC});var Np={};cn(Np,{endsWith:()=>ti,gt:()=>kn,gte:()=>Ft,includes:()=>Js,length:()=>wo,lowercase:()=>Ys,lt:()=>wn,lte:()=>Dt,maxLength:()=>vo,maxSize:()=>yr,mime:()=>ri,minLength:()=>Zn,minSize:()=>Sn,multipleOf:()=>br,negative:()=>xp,nonnegative:()=>yp,nonpositive:()=>bp,normalize:()=>oi,overwrite:()=>ln,positive:()=>gp,properties:()=>ni,property:()=>_p,regex:()=>Gs,size:()=>_o,slugify:()=>li,startsWith:()=>ei,toLowerCase:()=>ii,toUpperCase:()=>ai,trim:()=>si,uppercase:()=>qs});var _A=new WeakSet([Object.prototype,Error.prototype]);function Ap(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let r=n(this);return Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0})}})}var vA=(e,t)=>{dg.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);_A.has(n)||(_A.add(n),Ap(n,"format",r=>o=>Ha(r,o)),Ap(n,"flatten",r=>o=>Ua(r,o)),Ap(n,"addIssue",r=>o=>{r.issues.push(o),r.message=JSON.stringify(r.issues,Fs,2)}),Ap(n,"addIssues",r=>o=>{r.issues.push(...o),r.message=JSON.stringify(r.issues,Fs,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},qD=I("ZodError",vA),Ot=I("ZodError",vA,void 0,{Parent:Error});var uy=Bs(Ot),dy=Us(Ot),py=Hs(Ot),fy=Vs(Ot),hy=od(Ot),my=sd(Ot),gy=id(Ot),xy=ad(Ot),by=ld(Ot),yy=cd(Ot),_y=ud(Ot),vy=dd(Ot);function e3(){rt.localeError||He(Ud())}function No(){rt.memoizer||He({memoizer:ll()})}var ye=I("ZodType",(e,t)=>(e3(),me.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(oe.mergeDefs(t,{checks:[...t.checks??[],...e.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Te(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(f_(e,t))},superRefine(e,t){return this.check(h_(e,t))},overwrite(e){return this.check(ln(e))},optional(){return Eo(this)},exactOptional(){return jy(this)},nullable(){return bl(this)},nullish(){return Eo(bl(this))},nonoptional(e){return e_(this,e)},array(){return vl(this)},or(e){return bi([this,e])},and(e){return zy(this,e)},transform(e){return Tp(this,Yp(e))},default(e){return Yy(this,e)},prefault(e){return Jy(this,e)},catch(e){return r_(this,e)},pipe(e){return Tp(this,e)},readonly(){return a_(this)},describe(e){let t=this.clone();return at.add(t,{description:e}),t},meta(...e){if(e.length===0)return at.get(this);let t=this.clone();return at.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return oe.hide(this,"~standard",{...wd(this),jsonSchema:{input:ci(this,"input"),output:ci(this,"output")}})},set"~standard"(e){oe.own(this,"~standard",e)},parse:function e(t,n){return uy(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await dy(this,t,n,{callee:e})},safeParse(e,t){return py(this,e,t)},async safeParseAsync(e,t){return fy(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){oe.own(this,"spa",e)},validate(e,t){return Va(this,e,t)},validateAsync(e,t){return Za(this,e,t)},encode:function e(t,n){return hy(this,t,n,{callee:e})},decode:function e(t,n){return my(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await gy(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await xy(this,t,n,{callee:e})},safeEncode(e,t){return by(this,e,t)},safeDecode(e,t){return yy(this,e,t)},async safeEncodeAsync(e,t){return _y(this,e,t)},async safeDecodeAsync(e,t){return vy(this,e,t)},toJSONSchema(e){return kb(this,{})(e)},get description(){return at.get(this)?.description},get _def(){return this._zod.def}}),Rp=I("_ZodString",(e,t)=>{mo.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Nb(e,n,r,o)},oe.derived({format:e=>et(e).format??null,minLength:e=>et(e).minimum??null,maxLength:e=>et(e).maximum??null},{regex(...e){return this.check(Gs(...e))},includes(...e){return this.check(Js(...e))},startsWith(...e){return this.check(ei(...e))},endsWith(...e){return this.check(ti(...e))},min(...e){return this.check(Zn(...e))},max(...e){return this.check(vo(...e))},length(...e){return this.check(wo(...e))},nonempty(...e){return this.check(Zn(1,...e))},lowercase(e){return this.check(Ys(e))},uppercase(e){return this.check(qs(e))},trim(){return this.check(si())},normalize(...e){return this.check(oi(...e))},toLowerCase(){return this.check(ii())},toUpperCase(){return this.check(ai())},slugify(){return this.check(li())}})),hi=I("ZodString",(e,t)=>{mo.init(e,t),Rp.init(e,t)},{email(e){return this.check(Qd($p,e))},url(e){return this.check(ul(yl,e))},jwt(e){return this.check(mp(Wp,e))},emoji(e){return this.check(tp(Pp,e))},guid(e){return this.check(Gd(Ip,e))},uuid(e){return this.check(Yd(En,e))},uuidv4(e){return this.check(qd(En,e))},uuidv6(e){return this.check(Jd(En,e))},uuidv7(e){return this.check(ep(En,e))},nanoid(e){return this.check(np(Op,e))},cuid(e){return this.check(rp(Lp,e))},cuid2(e){return this.check(op(Mp,e))},ulid(e){return this.check(sp(Dp,e))},base64(e){return this.check(pp(Hp,e))},base64url(e){return this.check(fp(Vp,e))},xid(e){return this.check(ip(Fp,e))},ksuid(e){return this.check(ap(zp,e))},ipv4(e){return this.check(lp(Kp,e))},ipv6(e){return this.check(cp(Xp,e))},cidrv4(e){return this.check(up(Bp,e))},cidrv6(e){return this.check(dp(Up,e))},e164(e){return this.check(hp(Zp,e))},datetime(e){return this.check(dl(kr,e))},date(e){return this.check(pl(Sr,e))},time(e){return this.check(fl(Er,e))},duration(e){return this.check(hl(Nr,e))}});function xl(e){return zx(hi,e)}var Le=I("ZodStringFormat",(e,t)=>{Re.init(e,t),Rp.init(e,t)}),kr=I("ZodISODateTime",(e,t)=>{$0.init(e,t),Le.init(e,t)}),Sr=I("ZodISODate",(e,t)=>{I0.init(e,t),Le.init(e,t)}),Er=I("ZodISOTime",(e,t)=>{P0.init(e,t),Le.init(e,t)}),Nr=I("ZodISODuration",(e,t)=>{O0.init(e,t),Le.init(e,t)}),$p=I("ZodEmail",(e,t)=>{_0.init(e,t),Le.init(e,t)});function wA(e){return Qd($p,e)}var Ip=I("ZodGUID",(e,t)=>{b0.init(e,t),Le.init(e,t)});function kA(e){return Gd(Ip,e)}var En=I("ZodUUID",(e,t)=>{y0.init(e,t),Le.init(e,t)});function SA(e){return Yd(En,e)}function EA(e){return qd(En,e)}function NA(e){return Jd(En,e)}function AA(e){return ep(En,e)}var yl=I("ZodURL",(e,t)=>{k0.init(e,t),Le.init(e,t)});function CA(e){return ul(yl,e)}function TA(e){return ul(yl,{protocol:Wa,hostname:Og,...oe.normalizeParams(e)})}var Pp=I("ZodEmoji",(e,t)=>{S0.init(e,t),Le.init(e,t)});function RA(e){return tp(Pp,e)}var Op=I("ZodNanoID",(e,t)=>{E0.init(e,t),Le.init(e,t)});function $A(e){return np(Op,e)}var Lp=I("ZodCUID",(e,t)=>{N0.init(e,t),Le.init(e,t)});function IA(e){return rp(Lp,e)}var Mp=I("ZodCUID2",(e,t)=>{A0.init(e,t),Le.init(e,t)});function PA(e){return op(Mp,e)}var Dp=I("ZodULID",(e,t)=>{C0.init(e,t),Le.init(e,t)});function OA(e){return sp(Dp,e)}var Fp=I("ZodXID",(e,t)=>{T0.init(e,t),Le.init(e,t)});function LA(e){return ip(Fp,e)}var zp=I("ZodKSUID",(e,t)=>{R0.init(e,t),Le.init(e,t)});function MA(e){return ap(zp,e)}var Kp=I("ZodIPv4",(e,t)=>{L0.init(e,t),Le.init(e,t)});function DA(e){return lp(Kp,e)}var wy=I("ZodMAC",(e,t)=>{D0.init(e,t),Le.init(e,t)});function FA(e){return Xx(wy,e)}var Xp=I("ZodIPv6",(e,t)=>{M0.init(e,t),Le.init(e,t)});function zA(e){return cp(Xp,e)}var Bp=I("ZodCIDRv4",(e,t)=>{F0.init(e,t),Le.init(e,t)});function KA(e){return up(Bp,e)}var Up=I("ZodCIDRv6",(e,t)=>{z0.init(e,t),Le.init(e,t)});function XA(e){return dp(Up,e)}var Hp=I("ZodBase64",(e,t)=>{K0.init(e,t),Le.init(e,t)});function BA(e){return pp(Hp,e)}var Vp=I("ZodBase64URL",(e,t)=>{X0.init(e,t),Le.init(e,t)});function UA(e){return fp(Vp,e)}var Zp=I("ZodE164",(e,t)=>{B0.init(e,t),Le.init(e,t)});function HA(e){return hp(Zp,e)}var ky=I("ZodCreditCard",(e,t)=>{U0.init(e,t),Le.init(e,t)});function VA(e){return Bx(ky,e)}var Sy=I("ZodIBAN",(e,t)=>{H0.init(e,t),Le.init(e,t)});function ZA(e){return Ux(Sy,e)}var Wp=I("ZodJWT",(e,t)=>{V0.init(e,t),Le.init(e,t)});function WA(e){return mp(Wp,e)}var Ao=I("ZodCustomStringFormat",(e,t)=>{Z0.init(e,t),Le.init(e,t)});function jA(e,t,n={}){return ko(Ao,e,t,n)}function QA(e){return ko(Ao,"hostname",Pg,e)}function GA(e){return ko(Ao,"hex",jg,e)}function YA(e){return ko(Ao,"currency_code",Mg,e)}function qA(e,t){let n=t?.enc??"hex",r=`${e}_${n}`,o=Wt[r];if(!o)throw new Error(`Unrecognized hash format: ${r}`);return ko(Ao,r,o,t)}var mi=I("ZodNumber",(e,t)=>{Id.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ab(e,n,r,o),e.isFinite=!0},oe.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=et(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=et(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:n}=et(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>et(e).format??null},{gt(e,t){return this.check(kn(e,t))},gte(e,t){return this.check(Ft(e,t))},min(e,t){return this.check(Ft(e,t))},lt(e,t){return this.check(wn(e,t))},lte(e,t){return this.check(Dt(e,t))},max(e,t){return this.check(Dt(e,t))},int(e){return this.check(Cp(e))},safe(e){return this.check(Cp(e))},positive(e){return this.check(kn(0,e))},nonnegative(e){return this.check(Ft(0,e))},negative(e){return this.check(wn(0,e))},nonpositive(e){return this.check(Dt(0,e))},multipleOf(e,t){return this.check(br(e,t))},step(e,t){return this.check(br(e,t))},finite(){return this}}));function Ey(e){return Vx(mi,e)}var Co=I("ZodNumberFormat",(e,t)=>{W0.init(e,t),mi.init(e,t)});function Cp(e){return Wx(Co,e)}function JA(e){return jx(Co,e)}function eC(e){return Qx(Co,e)}function tC(e){return Gx(Co,e)}function nC(e){return Yx(Co,e)}var gi=I("ZodBoolean",(e,t)=>{nl.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Cb(e,n,r,o)});function Ny(e){return qx(gi,e)}var xi=I("ZodBigInt",(e,t)=>{Pd.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Tb(e,n,r,o)},oe.derived({minValue:e=>et(e).minimum??null,maxValue:e=>et(e).maximum??null,format:e=>et(e).format??null},{gte(e,t){return this.check(Ft(e,t))},min(e,t){return this.check(Ft(e,t))},gt(e,t){return this.check(kn(e,t))},lt(e,t){return this.check(wn(e,t))},lte(e,t){return this.check(Dt(e,t))},max(e,t){return this.check(Dt(e,t))},positive(e){return this.check(kn(BigInt(0),e))},negative(e){return this.check(wn(BigInt(0),e))},nonpositive(e){return this.check(Dt(BigInt(0),e))},nonnegative(e){return this.check(Ft(BigInt(0),e))},multipleOf(e,t){return this.check(br(e,t))}}));function rC(e){return eb(xi,e)}var jp=I("ZodBigIntFormat",(e,t)=>{j0.init(e,t),xi.init(e,t)});function oC(e){return nb(jp,e)}function sC(e){return rb(jp,e)}var Ay=I("ZodSymbol",(e,t)=>{Q0.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Rb(e,n,r,o)});function iC(e){return ob(Ay,e)}var Cy=I("ZodUndefined",(e,t)=>{G0.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ib(e,n,r,o)});function aC(e){return sb(Cy,e)}var Ty=I("ZodNull",(e,t)=>{Y0.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>$b(e,n,r,o)});function Ry(e){return ib(Ty,e)}var $y=I("ZodAny",(e,t)=>{q0.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Lb(e,n,r,o)});function lC(){return ab($y)}var Iy=I("ZodUnknown",(e,t)=>{J0.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Mb(e,n,r,o)});function So(){return lb(Iy)}var Py=I("ZodNever",(e,t)=>{ex.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ob(e,n,r,o)});function Qp(e){return cb(Py,e)}var Oy=I("ZodVoid",(e,t)=>{tx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Pb(e,n,r,o)});function cC(e){return ub(Oy,e)}var _l=I("ZodDate",(e,t)=>{nx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Db(e,n,r,o),e.min=(n,r)=>e.check(Ft(n,r)),e.max=(n,r)=>e.check(Dt(n,r))},oe.derived({minDate:e=>{let{minimum:t}=et(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=et(e);return t?new Date(t):null}},{}));function uC(e){return db(_l,e)}var Ly=I("ZodArray",(e,t)=>{No(),rx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Qb(e,n,r,o),e.element=t.element},{min(e,t){return this.check(Zn(e,t))},nonempty(e){return this.check(Zn(1,e))},max(e,t){return this.check(vo(e,t))},length(e,t){return this.check(wo(e,t))},unwrap(){return this.element}});function vl(e,t){return hb(Ly,e,t)}function dC(e){let t=e._zod.def.shape;return Gp(Object.keys(t))}var wl=I("ZodObject",(e,t)=>{No(),ox.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Gb(e,n,r,o),oe.installLazyProp(e,"shape",n=>n._zod.def.shape,!1)},{keyof(){return Gp(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(oe.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(oe.mergeDefs(this._zod.def,{catchall:So()}))},loose(){return this.clone(oe.mergeDefs(this._zod.def,{catchall:So()}))},strict(){return this.clone(oe.mergeDefs(this._zod.def,{catchall:Qp()}))},strip(){return this.clone(oe.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return oe.extend(this,e)},safeExtend(e){return oe.safeExtend(this,e)},merge(e){return oe.merge(this,e)},pick(e){return oe.pick(this,e)},omit(e){return oe.omit(this,e)},partial(...e){return oe.partial(Sl,this,e[0])},exactPartial(...e){return oe.partial(qp,this,e[0],"exactPartial")},required(...e){return oe.required(Jp,this,e[0])}});function pC(e,t){let n={type:"object",shape:e??{},...oe.normalizeParams(t)};return new wl(n)}function fC(e,t){return new wl({type:"object",shape:e,catchall:Qp(),...oe.normalizeParams(t)})}function hC(e,t){return new wl({type:"object",shape:e,catchall:So(),...oe.normalizeParams(t)})}var kl=I("ZodUnion",(e,t)=>{rl.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>wp(e,n,r,o),e.options=t.options});function bi(e,t){return new kl({type:"union",options:e,...oe.normalizeParams(t)})}var My=I("ZodXor",(e,t)=>{kl.init(e,t),sx.init(e,t),e._zod.processJSONSchema=(n,r,o)=>wp(e,n,r,o),e.options=t.options});function mC(e,t){return new My({type:"union",options:e,inclusive:!1,...oe.normalizeParams(t)})}var Dy=I("ZodDiscriminatedUnion",(e,t)=>{kl.init(e,t),ax.init(e,t)});function gC(e,t,n){return new Dy({type:"union",options:t,discriminator:e,...oe.normalizeParams(n)})}var Fy=I("ZodIntersection",(e,t)=>{lx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Yb(e,n,r,o)});function zy(e,t){return new Fy({type:"intersection",left:e,right:t})}var Ky=I("ZodTuple",(e,t)=>{No(),Od.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>qb(e,n,r,o)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new Sl({type:"optional",innerType:t}))})}});function Xy(e,t,n){let r=t instanceof me,o=r?n:t,s=r?t:null;return new Ky({type:"tuple",items:e,rest:s,...oe.normalizeParams(o)})}var pi=I("ZodRecord",(e,t)=>{No(),cx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Jb(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType});function By(e,t,n){return!t||!t._zod?new pi({type:"record",keyType:xl(),valueType:e,...oe.normalizeParams(t)}):new pi({type:"record",keyType:e,valueType:t,...oe.normalizeParams(n)})}function xC(e,t,n){return new pi({type:"record",keyType:e,valueType:t,...oe.normalizeParams(n),partial:!0})}function bC(e,t,n){return new pi({type:"record",keyType:e,valueType:t,mode:"loose",...oe.normalizeParams(n)})}var Uy=I("ZodMap",(e,t)=>{No(),ux.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Wb(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...n)=>e.check(Sn(...n)),e.nonempty=n=>e.check(Sn(1,n)),e.max=(...n)=>e.check(yr(...n)),e.size=(...n)=>e.check(_o(...n))});function yC(e,t,n){return new Uy({type:"map",keyType:e,valueType:t,...oe.normalizeParams(n)})}var Hy=I("ZodSet",(e,t)=>{No(),dx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>jb(e,n,r,o),e.min=(...n)=>e.check(Sn(...n)),e.nonempty=n=>e.check(Sn(1,n)),e.max=(...n)=>e.check(yr(...n)),e.size=(...n)=>e.check(_o(...n))});function _C(e,t){return new Hy({type:"set",valueType:e,...oe.normalizeParams(t)})}var fi=I("ZodEnum",(e,t)=>{px.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,o,s)=>Fb(e,r,o,s),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new fi({...t,checks:[],...oe.normalizeParams(o),entries:s})},e.exclude=(r,o)=>{let s={...t.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new fi({...t,checks:[],...oe.normalizeParams(o),entries:s})}});function Gp(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new fi({type:"enum",entries:n,...oe.normalizeParams(t)})}function vC(e,t){return new fi({type:"enum",entries:e,...oe.normalizeParams(t)})}var Vy=I("ZodLiteral",(e,t)=>{fx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>zb(e,n,r,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function wC(e,t){return new Vy({type:"literal",values:Array.isArray(e)?e:[e],...oe.normalizeParams(t)})}var Zy=I("ZodFile",(e,t)=>{hx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Bb(e,n,r,o),e.min=(n,r)=>e.check(Sn(n,r)),e.max=(n,r)=>e.check(yr(n,r)),e.mime=(n,r)=>e.check(ri(Array.isArray(n)?n:[n],r))});function kC(e){return mb(Zy,e)}var Wy=I("ZodTransform",(e,t)=>{No(),mx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Zb(e,n,r,o),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new xr(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(oe.issue(s,n.value,t));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=n.value),i.inst??(i.inst=e),n.issues.push(oe.issue(i))}};let o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function Yp(e){return new Wy({type:"transform",transform:e})}var Sl=I("ZodOptional",(e,t)=>{Ld.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>kp(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Eo(e){return new Sl({type:"optional",innerType:e})}var qp=I("ZodExactOptional",(e,t)=>{gx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>kp(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function jy(e){return new qp({type:"optional",innerType:e})}var Qy=I("ZodNullable",(e,t)=>{xx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ey(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function bl(e){return new Qy({type:"nullable",innerType:e})}function SC(e){return Eo(bl(e))}var Gy=I("ZodDefault",(e,t)=>{bx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ry(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Yy(e,t){return new Gy({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():oe.shallowClone(t)}})}var qy=I("ZodPrefault",(e,t)=>{yx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>oy(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Jy(e,t){return new qy({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():oe.shallowClone(t)}})}var Jp=I("ZodNonOptional",(e,t)=>{_x.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ty(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function e_(e,t){return new Jp({type:"nonoptional",innerType:e,...oe.normalizeParams(t)})}var t_=I("ZodSuccess",(e,t)=>{vx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ub(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function EC(e){return new t_({type:"success",innerType:e})}var n_=I("ZodCatch",(e,t)=>{wx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>sy(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function r_(e,t){return new n_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:oe.constantCatch(t)})}var o_=I("ZodNaN",(e,t)=>{kx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Kb(e,n,r,o)});function NC(e){return fb(o_,e)}var El=I("ZodPipe",(e,t)=>{Md.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>iy(e,n,r,o),e.in=t.in,e.out=t.out});function Tp(e,t){return new El({type:"pipe",in:e,out:t})}var Nl=I("ZodCodec",(e,t)=>{El.init(e,t),ol.init(e,t)});function AC(e,t,n){return new Nl({type:"pipe",in:e,out:t,transform:n.decode,reverseTransform:n.encode})}function CC(e){let t=e._zod.def;return new Nl({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var s_=I("ZodPreprocess",(e,t)=>{El.init(e,t),Sx.init(e,t)}),i_=I("ZodReadonly",(e,t)=>{Ex.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ay(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function a_(e){return new i_({type:"readonly",innerType:e})}var l_=I("ZodTemplateLiteral",(e,t)=>{Nx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Xb(e,n,r,o)});function TC(e,t){return new l_({type:"template_literal",parts:e,...oe.normalizeParams(t)})}var c_=I("ZodLazy",(e,t)=>{sl.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>cy(e,n,r,o),e.unwrap=()=>e._zod.def.getter()});function u_(e){return new c_({type:"lazy",getter:e})}var d_=I("ZodPromise",(e,t)=>{Cx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ly(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function RC(e){return new d_({type:"promise",innerType:e})}var p_=I("ZodFunction",(e,t)=>{Ax.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Vb(e,n,r,o)});function $C(e){return new p_({type:"function",input:Array.isArray(e?.input)?Xy(e?.input):e?.input??vl(So()),output:e?.output??So()})}var Al=I("ZodCustom",(e,t)=>{Tx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Hb(e,n,r,o)});function IC(e){let t=new Fe({check:"custom"});return t._zod.check=e,t}function PC(e,t){return gb(Al,e??(()=>!0),t)}function f_(e,t={}){return xb(Al,e,t)}function h_(e,t){return bb(e,t)}var OC=yb,LC=_b,m_=I("ZodInstanceOf",(e,t)=>{Al.init(e,t)},{properties(e,t){return this.check(ni(e,t))}});function MC(e,t={}){let n=new m_({type:"custom",check:"custom",fn:r=>r instanceof e,abort:!0,...oe.normalizeParams(t)});return n._zod.bag.Class=e,n._zod.check=r=>{r.value instanceof e||r.issues.push({code:"invalid_type",expected:e.name,input:r.value,inst:n,path:[...n._zod.def.path??[]]})},n}var DC=(...e)=>vb({Codec:Nl,Boolean:gi,String:hi},...e);function FC(e){let t=u_(()=>bi([xl(e),Ey(),Ny(),Ry(),vl(t),By(xl(),t)]));return t}function zC(e,t){return new s_({type:"pipe",in:Yp(e),out:t})}var t3={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function n3(e){He({customError:e})}function r3(){return He().customError}var g_;g_||(g_={});var Cl={};cn(Cl,{ZodISODate:()=>Sr,ZodISODateTime:()=>kr,ZodISODuration:()=>Nr,ZodISOTime:()=>Er,date:()=>s3,datetime:()=>o3,duration:()=>a3,time:()=>i3});function o3(e){return dl(kr,e)}function s3(e){return pl(Sr,e)}function i3(e){return fl(Er,e)}function a3(e){return hl(Nr,e)}var te={...yi,...Np,iso:Cl},l3=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function c3(e,t){let n=e.$schema;return n==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":n==="http://json-schema.org/draft-07/schema#"?"draft-7":n==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function KC(e,t){return e.map((n,r)=>r<t?n:n.optional())}function u3(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function d3(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let n=e.slice(1).split("/").filter(Boolean);if(n.length===0)return t.rootSchema;let r=t.version==="draft-2020-12"?"$defs":"definitions";if(n[0]===r){let o=n[1]===void 0?void 0:u3(n[1]);if(!o||!t.defs[o])throw new Error(`Reference not found: ${e}`);return t.defs[o]}throw new Error(`Reference not found: ${e}`)}function p3(e,t){return te.transform(r=>r).check(r=>{let o=r.value;if(typeof o!="object"||o===null||Array.isArray(o))return;let s=Object.getOwnPropertyNames(o);if(t.minProperties!==void 0&&s.length<t.minProperties&&r.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:o,inst:e,continue:!0}),t.maxProperties!==void 0&&s.length>t.maxProperties&&r.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:o,inst:e,continue:!0}),t.keySchema)for(let i of s){let a=t.keySchema.safeParse(i);a.success||r.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:i,path:[i],continue:!0})}}).pipe(e)}function x_(e,t){if(e===null)return"z";let n=typeof e;if(n!=="object"){if(n==="number"&&Number.isNaN(e))return null;let r=String(e);return`${n[0]}${r.length}:${r}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let s=[];for(let i of e){let a=x_(i,t);if(a===null)return null;s.push(a)}return`a${s.length}:[${s.join(",")}]`}let r=Object.keys(e).sort(),o=[];for(let s of r){let i=x_(e[s],t);if(i===null)return null;o.push(`${s.length}:${s}=${i}`)}return`o${o.length}:{${o.join(",")}}`}finally{t.delete(e)}}var f3=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),h3=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function Tl(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(Tl):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,n])=>f3.has(t)?Tl(n):!h3.has(t)||typeof n!="object"||n===null?!1:Object.values(n).some(Tl))}function XC(e){return e===1?"element":"elements"}function m3(e,t){return te.transform(r=>r).check(r=>{let o=r.value;if(Array.isArray(o)){if(t.uniqueItems===!0){let s=new Map;for(let i=0;i<o.length;i++){let a=x_(o[i],new Set);if(a===null)continue;let u=s.get(a);if(u===void 0){s.set(a,i);continue}r.issues.push({code:"custom",message:`Array items must be unique: element at index ${i} duplicates the one at index ${u}`,input:o,path:[i],continue:!0})}}if(t.containsSchema){let s=t.minContains??1,i=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let u of o)if(t.containsSchema.safeParse(u).success&&++a>=i)break;a<s&&r.issues.push({code:"custom",message:`Array must contain at least ${s} matching ${XC(s)}; found ${a}`,input:o,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&r.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${XC(t.maxContains)}`,input:o,continue:!0})}}}).pipe(e)}function BC(e,t){if(e!==!1)return e===void 0||e===!0?te.any():Et(e,t)}var g3=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function UC(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return te.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let o=e.$ref;if(t.refs.has(o))return t.refs.get(o);if(t.processing.has(o))return te.lazy(()=>{if(!t.refs.has(o))throw new Error(`Circular reference not resolved: ${o}`);return t.refs.get(o)});t.processing.add(o);let s=d3(o,t),i=Et(s,t);return t.refs.set(o,i),t.processing.delete(o),i}if(e.enum!==void 0){let o=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&o.length===1&&o[0]===null)return te.null();if(o.length===0)return te.never();if(o.length===1)return te.literal(o[0]);if(o.every(i=>typeof i=="string"))return te.enum(o);let s=o.map(i=>te.literal(i));return s.length<2?s[0]:te.union([s[0],s[1],...s.slice(2)])}if(e.const!==void 0)return te.literal(e.const);let n=e.type;if(Array.isArray(n)){let o=n.map(s=>{let i={...e,type:s};return UC(i,t)});return o.length===0?te.never():o.length===1?o[0]:te.union(o)}if(!n)return te.any();let r;switch(n){case"string":{let o=te.string();if(e.format){let s=e.format;s==="email"?o=o.check(te.email()):s==="uri"||s==="uri-reference"?o=o.check(te.url()):s==="uuid"||s==="guid"?o=o.check(te.uuid()):s==="date-time"?o=o.check(te.iso.datetime({offset:!0})):s==="date"?o=o.check(te.iso.date()):s==="time"?o=o.check(te.regex(g3)):s==="duration"?o=o.check(te.iso.duration()):s==="hostname"?o=o.check(te.hostname()):s==="ipv4"?o=o.check(te.ipv4()):s==="ipv6"?o=o.check(te.ipv6()):s==="mac"?o=o.check(te.mac()):s==="cidr"?o=o.check(te.cidrv4()):s==="cidr-v6"?o=o.check(te.cidrv6()):s==="base64"?o=o.check(te.base64()):s==="base64url"?o=o.check(te.base64url()):s==="e164"?o=o.check(te.e164()):s==="credit_card"?o=o.check(te.creditCard()):s==="iban"?o=o.check(te.iban()):s==="jwt"?o=o.check(te.jwt()):s==="emoji"?o=o.check(te.emoji()):s==="nanoid"?o=o.check(te.nanoid()):s==="cuid"?o=o.check(te.cuid()):s==="cuid2"?o=o.check(te.cuid2()):s==="ulid"?o=o.check(te.ulid()):s==="xid"?o=o.check(te.xid()):s==="ksuid"&&(o=o.check(te.ksuid()))}typeof e.minLength=="number"&&(o=o.min(e.minLength)),typeof e.maxLength=="number"&&(o=o.max(e.maxLength)),e.pattern&&(o=o.regex(new RegExp(e.pattern))),r=o;break}case"number":case"integer":{let o=n==="integer"?te.number().int():te.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(o=o.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(o=o.max(e.maximum)),typeof e.exclusiveMinimum=="number"?o=o.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(o=o.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?o=o.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(o=o.lt(e.maximum)),typeof e.multipleOf=="number"&&(o=o.multipleOf(e.multipleOf)),r=o;break}case"boolean":{r=te.boolean();break}case"null":{r=te.null();break}case"object":{let o={},s=e.properties||{},i=new Set(e.required||[]),a=typeof e.additionalProperties=="object"?Et(e.additionalProperties,t):void 0;for(let[p,f]of Object.entries(s)){let h=Et(f,t);it(o,p,i.has(p)?h:h.optional())}if(e.patternProperties){let p=e.patternProperties,f=Object.keys(p),h=[];for(let x of f){let b=Et(p[x],t),v=te.string().regex(new RegExp(x));h.push(te.looseRecord(v,b))}let g=[];if(Object.keys(o).length>0&&g.push(te.object(o).passthrough()),g.push(...h),g.length===0)r=te.object({}).passthrough();else if(g.length===1)r=g[0];else{let x=te.intersection(g[0],g[1]);for(let b=2;b<g.length;b++)x=te.intersection(x,g[b]);r=x}if(e.additionalProperties===!1){let x=Object.keys(o),b=f.map(w=>new RegExp(w)),v=r;r=r.check(w=>{if(!Vt(w.value))return;let C=[];for(let y of Object.keys(w.value))x.includes(y)||b.some(T=>T.test(y))||C.push(y);C.length&&w.issues.push({code:"unrecognized_keys",keys:C,input:w.value,inst:v})})}}else{let p=te.object(o);e.additionalProperties===!1?r=p.strict():a?r=p.catchall(a):r=p.passthrough()}let u=e.propertyNames!==void 0&&e.propertyNames!==!0,c=typeof e.minProperties=="number"?e.minProperties:void 0,d=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(u||c!==void 0||d!==void 0){let p;if(u){let f=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;p=Et(f,t)}r=p3(r,{keySchema:p,minProperties:c,maxProperties:d})}break}case"array":{let o=e.prefixItems,s=e.items;if(o&&Array.isArray(o)){let i=typeof e.minItems=="number"?e.minItems:0,a=o.map(p=>Et(p,t)),u=KC(a,i),c=Array.isArray(s)?void 0:BC(s,t),d=te.tuple(u);r=c?d.rest(c):d,typeof e.minItems=="number"&&(r=r.check(te.minLength(e.minItems))),typeof e.maxItems=="number"&&(r=r.check(te.maxLength(e.maxItems)))}else if(Array.isArray(s)){let i=typeof e.minItems=="number"?e.minItems:0,a=s.map(p=>Et(p,t)),u=KC(a,i),c=BC(e.additionalItems,t),d=te.tuple(u);r=c?d.rest(c):d,typeof e.minItems=="number"&&(r=r.check(te.minLength(e.minItems))),typeof e.maxItems=="number"&&(r=r.check(te.maxLength(e.maxItems)))}else if(s!==void 0){let i=Et(s,t),a=te.array(i);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),r=a}else r=te.array(te.any());(e.uniqueItems===!0||e.contains!==void 0)&&(r=m3(r,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?Et(e.contains,t):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${n}`)}return r}function Et(e,t){if(typeof e=="boolean")return e?te.any():te.never();let n=UC(e,t),r=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let a=e.anyOf.map(c=>Et(c,t)),u=te.union(a);n=r?te.intersection(n,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){let a=e.oneOf.map(c=>Et(c,t)),u=te.xor(a);n=r?te.intersection(n,u):u}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)n=r?n:te.any();else{let a=r?n:Et(e.allOf[0],t),u=r?0:1;for(let c=u;c<e.allOf.length;c++)a=te.intersection(a,Et(e.allOf[c],t));n=a}e.nullable===!0&&t.version==="openapi-3.0"&&(n=te.nullable(n)),e.readOnly===!0&&(n=te.readonly(n)),e.default!==void 0&&(n=n.default(e.default));let o={},s=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of s)a in e&&(o[a]=e[a]);let i=["contentEncoding","contentMediaType","contentSchema"];for(let a of i)a in e&&(o[a]=e[a]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!Tl(e.propertyNames)&&(o.propertyNames=e.propertyNames);for(let a of["minProperties","maxProperties"])e[a]!==void 0&&(o[a]=e[a])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!Tl(e.contains)&&(o.contains=e.contains);for(let a of["uniqueItems","minContains","maxContains"])e[a]!==void 0&&(o[a]=e[a])}for(let a of Object.keys(e))l3.has(a)||it(o,a,e[a]);return Object.keys(o).length>0&&t.registry.add(n,o),e.description&&(n=n.describe(e.description)),n}function HC(e,t){if(typeof e=="boolean")return e?te.any():te.never();let n;try{n=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let r=c3(n,t?.defaultTarget),o=n.$defs||n.definitions||{},s={version:r,defs:o,refs:new Map,processing:new Set,rootSchema:n,registry:t?.registry??at};return Et(n,s)}var VC=Symbol("z.visit/resolving");function Rl(e,t){let n=typeof t=="function"?t:(i,a)=>{let u=t[i._zod.def.type];return u?u(i,a):i},r=new Map;function o(i){let a=r.get(i);if(a===VC)return new sl({type:"lazy",getter:()=>r.get(i)});if(a!==void 0)return a;r.set(i,VC);let u=s(i),c=n(u,u!==i);return r.set(i,c),c}function s(i){let a=i._zod.def,u=a.type;switch(u){case"object":{let c=a.shape,d=Object.keys(c),p=!1,f={};for(let g of d){let x=o(c[g]);x!==c[g]&&(p=!0),f[g]=x}let h=a.catchall;return a.catchall&&(h=o(a.catchall),h!==a.catchall&&(p=!0)),p?Te(i,{...a,shape:f,catchall:h}):i}case"array":{let c=o(a.element);return c===a.element?i:Te(i,{...a,element:c})}case"tuple":{let c=a.items,d=!1,p=[];for(let h of c){let g=o(h);g!==h&&(d=!0),p.push(g)}let f=a.rest;return a.rest&&(f=o(a.rest),f!==a.rest&&(d=!0)),d?Te(i,{...a,items:p,rest:f}):i}case"record":case"map":{let c=o(a.keyType),d=o(a.valueType);return c===a.keyType&&d===a.valueType?i:Te(i,{...a,keyType:c,valueType:d})}case"set":{let c=o(a.valueType);return c===a.valueType?i:Te(i,{...a,valueType:c})}case"union":{let c=a.options,d=!1,p=[];for(let f of c){let h=o(f);h!==f&&(d=!0),p.push(h)}return d?Te(i,{...a,options:p}):i}case"intersection":{let c=o(a.left),d=o(a.right);return c===a.left&&d===a.right?i:Te(i,{...a,left:c,right:d})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let c=o(a.innerType);return c===a.innerType?i:Te(i,{...a,innerType:c})}case"pipe":{let c=o(a.in),d=o(a.out);return c===a.in&&d===a.out?i:Te(i,{...a,in:c,out:d})}case"function":{let c=o(a.input),d=o(a.output);return c===a.input&&d===a.output?i:Te(i,{...a,input:c,output:d})}case"lazy":{let c=a.getter,{_cachedInner:d,...p}=a;return Te(i,{...p,getter:()=>o(c())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return i;default:return i}}return o(e)}function ZC(e){return Rl(e,{object:t=>t.partial(),union:t=>{let n=t._zod.def;return n.discriminator===void 0?t:bi(n.options)}})}function x3(e,t){if(!t?.length)return e;let n=e._zod.def;return Te(e,sn(n,{checks:[...n.checks??[],...t]}),{parent:!0})}function WC(e){return x3(e.out,e.checks)}function b3(e){return e.in._zod.traits.has("$ZodTransform")?WC(e):e.in}function jC(e){return Rl(e,{pipe:t=>b3(t._zod.def),default:(t,n)=>n?Eo(t._zod.def.innerType):t,catch:(t,n)=>n?t._zod.def.innerType:t})}function QC(e){return Rl(e,{pipe:t=>WC(t._zod.def),prefault:(t,n)=>n?t._zod.def.innerType:t})}var b_={};cn(b_,{bigint:()=>w3,boolean:()=>v3,date:()=>k3,number:()=>_3,string:()=>y3});function y3(e){return Kx(hi,e)}function _3(e){return Zx(mi,e)}function v3(e){return Jx(gi,e)}function w3(e){return tb(xi,e)}function k3(e){return pb(_l,e)}var S3=/^([01]\d|2[0-3]):[0-5]\d$/,$l=re.string().regex(S3,"a time like 07:00"),E3=["mon","tue","wed","thu","fri","sat","sun"];var Nn=e=>re.string().trim().max(e).regex(/^[^\u0000-\u001f\u007f-\u009f<>]*$/,"one line, without < or >"),y_=re.string().trim().max(200).regex(/^[^\s@<>]+@[^\s@<>]+$/,"an email address"),N3=re.object({name:Nn(80).min(1),email:y_.optional(),emails:re.array(y_).max(9).optional(),phone:Nn(40).optional(),org:Nn(80).optional(),relation:Nn(60).optional()}).strict(),A3=re.object({name:Nn(80).min(1),admin:Nn(80).optional(),country:Nn(80).optional(),latitude:re.number().min(-90).max(90),longitude:re.number().min(-180).max(180),timezone:re.string().trim().min(1).max(64).regex(/^[A-Za-z0-9_+-]+(\/[A-Za-z0-9_+-]+)*$/,"a time zone name like America/Los_Angeles")}).strict();var GC=["you","reach","touchpoints","connections","library"],C3=re.object({version:re.literal(1).default(1),you:re.object({name:Nn(60).optional(),city:Nn(80).optional(),place:A3.optional(),email:y_.optional()}).strict().default({}),reach:re.object({inbox:re.boolean().default(!0),mail:re.boolean().default(!1),quiet_from:$l.optional(),quiet_to:$l.optional(),other:re.array(Nn(60).min(1)).max(10).default([])}).strict().default({inbox:!0,mail:!1,other:[]}),touchpoints:re.object({morning:re.object({on:re.boolean().default(!0),at:$l.default("07:00"),weather:re.boolean().default(!0),calendar:re.boolean().default(!0),mail:re.boolean().default(!0),loops:re.boolean().default(!0)}).strict().default({on:!0,at:"07:00",weather:!0,calendar:!0,mail:!0,loops:!0}),evening:re.object({on:re.boolean().default(!0),at:$l.default("17:30")}).strict().default({on:!0,at:"17:30"}),weekly:re.object({on:re.boolean().default(!1),day:re.enum(E3).default("fri"),at:$l.default("16:00")}).strict().default({on:!1,day:"fri",at:"16:00"})}).strict().prefault({}),contacts:re.array(N3).max(2e3).default([]),schedules:re.object({morning:re.string().optional(),evening:re.string().optional(),weekly:re.string().optional()}).strict().default({}),saved:re.preprocess(e=>typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).filter(([t])=>GC.includes(t))):e,re.partialRecord(re.enum(GC),re.number()).default({})),finished_at:re.number().optional(),untold:re.literal(!0).optional()}).strict();var NZ=C3.parse({});var T3=2e3;function YC(e,t){let n=e.filter(c=>c.name.trim()||c.email||c.relation),r=new Map,o=new Map,s=(c,d)=>{for(let p of[c.email,...c.emails??[]])p&&r.set(p.toLowerCase(),d);c.name.trim()&&o.set(c.name.trim().toLowerCase(),d)};n.forEach(s);let i=0,a=0,u=0;for(let c of t){let d=[c.email,...c.emails??[]].filter(v=>!!v),p=d.map(v=>r.get(v.toLowerCase())).find(v=>v!==void 0)??o.get(c.name.trim().toLowerCase());if(p===void 0){if(n.length>=T3){u++;continue}n.push(c),s(c,n.length-1),i++;continue}let f=n[p],h=[...new Set([...f.email?[f.email]:[],...f.emails??[],...d])],[g,...x]=h,b={...f,name:f.name.trim()||c.name,...g?{email:g}:{},...x.length?{emails:x.slice(0,9)}:{},...f.phone||c.phone?{phone:f.phone??c.phone}:{},...f.org||c.org?{org:f.org??c.org}:{}};JSON.stringify(b)!==JSON.stringify(f)&&a++,n[p]=b,s(b,p)}return{contacts:n,added:i,updated:a,dropped:u}}var qC={vcard:"a vCard","google-csv":"Google Contacts' CSV","outlook-csv":"Outlook's CSV",csv:"a CSV"},JC=[{source:"Apple Contacts (Mac, iPhone)",how:"On the Mac, select the contacts (\u2318A for all), then File \u2192 Export \u2192 Export vCard\u2026. On an iPhone, Contacts \u2192 Lists \u2192 press and hold a list \u2192 Export."},{source:"Google Contacts (Android, Gmail)",how:"At contacts.google.com, Export \u2192 vCard (for iOS Contacts) or Google CSV. Android phones sync to the same place."},{source:"Outlook",how:"File \u2192 Open & Export \u2192 Import/Export \u2192 Export to a file \u2192 Comma Separated Values, with Contacts chosen."},{source:"Anything else",how:"A vCard (.vcf) file, or a CSV with a name column (or first and last name) and an email column."}];var R3=8e6;function tT(e){return e instanceof Error?e.message:String(e)}function eT(e){return[e.emails?.length?`also ${e.emails.join(", ")}`:"",e.phone??"",e.org??""].filter(Boolean).join(" \xB7 ")}function __(e){return e.filter(t=>t.name.trim()).map(t=>({name:t.name.trim(),...t.email?.trim()?{email:t.email.trim()}:{},...t.emails?.length?{emails:t.emails}:{},...t.phone?{phone:t.phone}:{},...t.org?{org:t.org}:{},...t.relation?.trim()?{relation:t.relation.trim()}:{}}))}function $3({rpc:e,onImported:t}){let n=Y(null),[r,o]=_(!1),[s,i]=_(null),[a,u]=_(null),[c,d]=_(!1),[p,f]=_(!1),h=async g=>{let x=Array.from(g)[0];if(x){o(!0),u(null),i(null);try{if(x.size>R3)throw new Error("that file is over 8 MB");let b=await e.call("welcome.importContacts",{name:x.name,text:await x.text()});t(b.contacts),i(`${b.contacts.length} ${b.contacts.length===1?"person":"people"} from ${qC[b.format]}${b.skipped?` (${b.skipped} entries with nothing to know them by, or repeats, left out)`:""}. Add who they are to you where it matters.`)}catch(b){u(tT(b))}finally{o(!1),n.current&&(n.current.value="")}}};return m("div",{className:"flex flex-col gap-2",children:[l("input",{ref:n,type:"file","aria-label":"Contacts export file",accept:".vcf,.csv,text/vcard,text/csv,text/plain",className:"hidden",onChange:g=>g.target.files&&void h(g.target.files)}),m("button",{type:"button",className:V("flex w-full flex-col items-center gap-1 rounded-md border-2 border-dashed px-4 py-5 text-sm transition-colors",p?"border-foreground bg-muted":"border-input hover:border-foreground/50",r&&"pointer-events-none opacity-60"),onClick:()=>n.current?.click(),onDragOver:g=>{g.preventDefault(),f(!0)},onDragLeave:()=>f(!1),onDrop:g=>{g.preventDefault(),f(!1),g.dataTransfer.files.length&&h(g.dataTransfer.files)},children:[l("span",{className:"font-medium",children:r?"Reading\u2026":"Import from a file: drop it here, or click to choose"}),l("span",{className:"text-xs text-muted-foreground",children:"A vCard (.vcf) from Apple Contacts, Google Contacts or any phone; a CSV from Google Contacts or Outlook; any CSV with names and emails."})]}),m("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[l("button",{type:"button",className:"text-muted-foreground underline",onClick:()=>d(!c),children:c?"Hide":"Where do I export from?"}),a?l("span",{role:"alert",className:"text-destructive",children:a}):s&&l("span",{className:"text-muted-foreground",children:s})]}),c&&l("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 rounded-md border p-3 text-xs",children:JC.map(({source:g,how:x})=>m("div",{className:"contents",children:[l("dt",{className:"font-medium",children:g}),l("dd",{className:"text-muted-foreground",children:x})]},g))})]})}function I3({rpc:e,contacts:t,setContacts:n}){let[r,o]=_(""),s=(u,c,d)=>n(p=>p.map((f,h)=>h===u?{...f,[c]:d.trim()||c==="name"?d:void 0}:f)),i=r.trim().toLowerCase(),a=t.map((u,c)=>[u,c]).filter(([u])=>!i||`${u.name} ${u.email??""} ${u.org??""} ${u.relation??""}`.toLowerCase().includes(i));return m("div",{className:"flex flex-col gap-2",children:[l($3,{rpc:e,onImported:u=>n(c=>YC(c,u).contacts)}),t.length>8&&m("div",{className:"flex items-center gap-2 text-xs",children:[l(le,{className:"h-8 max-w-xs",placeholder:"Find someone","aria-label":"Find someone",value:r,onChange:u=>o(u.target.value)}),m("span",{className:"text-muted-foreground",children:[a.length," of ",t.length]})]}),m("ul",{className:"flex max-h-96 flex-col gap-2 overflow-y-auto pr-1",children:[a.slice(0,200).map(([u,c])=>m("li",{className:"flex flex-col gap-1",children:[m("div",{className:"flex flex-wrap items-center gap-2",children:[l(le,{className:"w-full sm:w-44",placeholder:"Name","aria-label":"Name",value:u.name,onChange:d=>s(c,"name",d.target.value)}),l(le,{className:"w-full sm:w-56",placeholder:"Email (optional)","aria-label":"Email",value:u.email??"",onChange:d=>s(c,"email",d.target.value)}),l(le,{className:"w-full sm:w-44",placeholder:"Who they are: partner, my accountant","aria-label":"Who they are",value:u.relation??"",onChange:d=>s(c,"relation",d.target.value)}),l(R,{size:"sm",variant:"ghost",onClick:()=>n(d=>d.filter((p,f)=>f!==c)),children:"Remove"})]}),eT(u)&&l("span",{className:"pl-1 text-xs text-muted-foreground",children:eT(u)})]},c)),a.length>200&&m("li",{className:"text-xs text-muted-foreground",children:["And ",a.length-200," more; find them by name above."]})]}),l("div",{children:l(R,{size:"sm",variant:"secondary",onClick:()=>n(u=>[...u,{name:""}]),children:"Add a person"})})]})}function nT(){let{rpc:e,state:t,error:n,refetch:r}=vn(),o=t?.record.contacts??null,[s,i]=_({contacts:null,conflict:!1}),a=s.contacts,u=s.conflict,c=Y(o),d=Y(!1);K(()=>{let S=c.current,$=d.current;i(P=>{let L=P.contacts===null||S!==null&&JSON.stringify(P.contacts)===JSON.stringify(S);return{contacts:L&&!$?null:P.contacts,conflict:!L&&(P.conflict||o!==null&&S!==null&&JSON.stringify(o)!==JSON.stringify(S))}}),c.current=o},[o]);let[p,f]=_(!1),[h,g]=_(!1),[x,b]=_(null),[v,w]=_(null),C=a??o,y=async S=>{d.current=!0,f(!0),w(null),b(null);try{b(await S()),r()}catch($){w(tT($))}finally{d.current=!1,f(!1)}},T=S=>y(async()=>{let $=await e.call("welcome.save",{step:"connections",values:{contacts:S}});return c.current=$.record.contacts,i(P=>({contacts:P.contacts===a?$.record.contacts:P.contacts,conflict:!1})),g(!1),$.lines.join(" ")}),N=C!==null&&o!==null&&JSON.stringify(__(C))!==JSON.stringify(__(o));return m("div",{className:"flex max-w-3xl flex-col gap-3 text-sm",children:[l("p",{children:"Optional. Who's who: the people you mention and who they are to you, so your moonlet can say who wrote. Mail from anyone else stays unknown until you say. Import an export from Apple Contacts, Google Contacts or Outlook, or add people by hand."}),l("p",{children:"The list stays on your Moonlet server. Machines enabled for assistant work get a private copy for the inbox check. It is a starting list, separate from your moonlet's protected record of people, which nothing here changes."}),l("p",{role:"status",children:o===null?"Loading contacts\u2026":o.length===0?"Off. No contacts saved; nothing is imported until you add some.":`${o.length} ${o.length===1?"person":"people"} saved.`}),C!==null&&l(I3,{rpc:e,contacts:C,setContacts:S=>i($=>({...$,contacts:S($.contacts??c.current??o??[])}))}),m("div",{className:"flex flex-wrap gap-2",children:[N&&l(R,{disabled:p,onClick:()=>C&&void T(__(C)),children:"Save contacts"}),N&&l(R,{variant:"ghost",disabled:p,onClick:()=>i({contacts:null,conflict:!1}),children:"Discard changes"}),o!==null&&o.length>0&&!h&&l(R,{variant:"secondary",disabled:p,onClick:()=>g(!0),children:"Remove all contacts"}),o!==null&&o.length>0&&h&&m(R,{variant:"destructive",disabled:p,onClick:()=>{T([])},children:["Remove all ",o.length]}),o!==null&&l(R,{variant:"secondary",disabled:p,onClick:()=>{y(async()=>(await e.call("welcome.handover",null)).lines.join(" "))},children:"Refresh contacts on machines"})]}),h&&l("p",{className:"text-muted-foreground",children:"Removing clears the saved list and the machines' copies. It does not touch your moonlet's protected record of people or anything it keeps in memory."}),u&&l("p",{role:"status",className:"text-muted-foreground",children:"The saved contacts changed. Your edits are kept. Discard changes to load the saved list, or save to replace it with your edits."}),x&&l("p",{role:"status",children:x}),(n||v)&&l("p",{role:"alert",className:"text-destructive",children:v||n})]})}async function rT(e,t,n){let r=await e({...t,expectedSha256:null});if(r.outcome==="written")return"added";if(r.currentSha256===null)throw new Error("the station reported a clash but no file there; nothing was written");if(!await n())return"kept";if((await e({...t,expectedSha256:r.currentSha256})).outcome==="written")return"replaced";throw new Error("the file there changed while you were asked, so it was kept as it is; drop yours again to replace it")}var P3=/^[a-z][a-z0-9-]{0,47}$/,oT=`[library]
210
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let c=e.external.registry.get(i[0])?.id;if(t!==i[0]&&c){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}a.count>1&&e.reused==="ref"&&s(i)}e.external&&(e.sharedDefsExtractedFor=e.external)}function dA(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let r of t){if(!r||typeof r!="object")return;dA(r);let o=Object.keys(r);if(o.length!==1||o[0]!=="type")return;let s=r.type;for(let i of Array.isArray(s)?s:[s]){if(typeof i!="string")return;n.includes(i)||n.push(i)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var pA=new Set(["type","properties","required","additionalProperties"]),cA=["oneOf","anyOf"];function uA(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function Sb(e){let t=[];for(let s of e){if(typeof s!="object"||s.type!=="object")return null;for(let i in s)if(!pA.has(i))return null;t.push(s)}let n={},r=new Set;for(let s of t){for(let i in s.properties){if(Object.prototype.hasOwnProperty.call(n,i))continue;let a=[];for(let c of t){let d=c.properties?.[i]??uA(c);d!=null&&(a.some(p=>JSON.stringify(p)===JSON.stringify(d))||a.push(d))}let u=a.length===1?a[0]:Sb(a)??{allOf:a};it(n,i,u)}for(let i of s.required??[])r.add(i)}let o={type:"object",properties:n};if(r.size&&(o.required=[...r]),t.every(s=>s.additionalProperties===!1))o.additionalProperties=!1;else{let s=[];for(let i of t){let a=uA(i);a&&!s.some(u=>JSON.stringify(u)===JSON.stringify(a))&&s.push(a)}s.length===1?o.additionalProperties=s[0]:s.length>1&&(o.additionalProperties={allOf:s})}return o}function GD(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let o of pA)if(o in e)return;let n=t.filter(o=>cA.some(s=>Array.isArray(o[s]))),r=null;if(!n.length)r=Sb(t);else{let o=n[0],s=cA.find(u=>Array.isArray(o[u]));if(Object.keys(o).length!==1)return;let i=t.filter(u=>u!==o),a=o[s].map(u=>Sb([...i,u]));if(a.some(u=>!u))return;r={[s]:a}}r&&(delete e.allOf,gl(e,r))}function kr(e,t){let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=a=>{let u=e.seen.get(a);if(u.ref===null)return;let c=u.def??u.schema,d={...c},p=u.ref;if(u.ref=null,p){r(p);let h=e.seen.get(p),g=h.schema;if(g.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(g)):gl(c,g),gl(c,d),a._zod.parent===p)for(let b in c)b==="$ref"||b==="allOf"||b in d||delete c[b];if(g.$ref&&h.def)for(let b in c)b==="$ref"||b==="allOf"||b in h.def&&JSON.stringify(c[b])===JSON.stringify(h.def[b])&&delete c[b]}let f=a._zod.parent;if(f&&f!==p){r(f);let h=e.seen.get(f);if(h?.schema.$ref&&(c.$ref=h.schema.$ref,h.def))for(let g in c)g==="$ref"||g==="allOf"||g in h.def&&JSON.stringify(c[g])===JSON.stringify(h.def[g])&&delete c[g]}e.override({zodSchema:a,jsonSchema:c,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())r(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())dA(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let u of e.seen.values())for(let c of[u.schema,u.def]){let d=c?.allOf;if(!Array.isArray(d))continue;let p=a.get(d);p?p.push(c):a.set(d,[c])}for(let u of e.intersections)for(let c of a.get(u)??[])GD(c)}}let o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}gl(o,n.defId?n.schema:n.def??n.schema);let s=e.metadataRegistry.get(t)?.id;s!==void 0&&o.id===s&&delete o.id;let i=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let u=a[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,it(i,u.defId,u.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:ui(t,"input",e.processors),output:ui(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function St(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return St(r.element,n);if(r.type==="set")return St(r.valueType,n);if(r.type==="lazy")return St(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault"||r.type==="catch")return St(r.innerType,n);if(r.type==="intersection")return St(r.left,n)||St(r.right,n);if(r.type==="record"||r.type==="map")return St(r.keyType,n)||St(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:St(r.in,n)||St(r.out,n);if(r.type==="object"){for(let o in r.shape)if(St(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(St(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(St(o,n))return!0;return!!(r.rest&&St(r.rest,n))}return!1}var Eb=(e,t={})=>n=>{let r=vr({...n,processors:t});return $e(e,r),wr(r,e),kr(r,e)},ui=(e,t,n={})=>r=>{let{libraryOptions:o,target:s}=r??{},i=vr({...o??{},target:s,io:t,processors:n});return $e(e,i),wr(i,e),kr(i,e)};var di=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},pi=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},fA=(e,t)=>{di(e,"minimum",t),pi(e,"maximum",t)},xA=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},bA=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},yA=(e,t)=>{e.mime=e.mime?e.mime.filter(n=>t.includes(n)):[...t]},_A=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},hA=(e,t)=>di(e,"minimum",t.minimum),mA=(e,t)=>pi(e,"maximum",t.maximum),gA=e=>(t,n)=>{_A(t,n.format);let[r,o]=e[n.format];di(t,"minimum",r),pi(t,"maximum",o)},YD={greater_than:(e,t)=>di(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>pi(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>xA(e,t.value),number_format:gA(za),bigint_format:gA(Ka),min_length:hA,max_length:mA,length_equals:(e,t)=>fA(e,t.length),min_size:hA,max_size:mA,size_equals:(e,t)=>fA(e,t.size),string_format:(e,t)=>{_A(e,t.format),t.pattern&&bA(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>yA(e,t.mime)};function tt(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let s of r)YD[s._zod.def.check]?.(t,s._zod.def);let o=e._zod.bag;o.minimum!==void 0&&di(t,"minimum",o.minimum),o.exclusiveMinimum!==void 0&&di(t,"exclusiveMinimum",o.exclusiveMinimum),o.maximum!==void 0&&pi(t,"maximum",o.maximum),o.exclusiveMaximum!==void 0&&pi(t,"exclusiveMaximum",o.exclusiveMaximum),o.multipleOf!==void 0&&xA(t,o.multipleOf),o.format!==void 0&&(t.format??(t.format=o.format),o.format.includes("int")&&(t.isInt=!0)),o.mime&&yA(t,o.mime);for(let s of o.patterns??[])bA(t,s);return t}var qD={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},JD=new Map([[Td,Pg],[nl,Og]]),vA=e=>JD.get(e)??e,Cb=(e,t,n,r)=>{let o=n;o.type="string";let{minimum:s,maximum:i,format:a,patterns:u,contentEncoding:c,laxFormat:d}=tt(e);if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=qD[a]??a,o.format===""&&delete o.format,(a==="time"||d)&&delete o.format),c&&(o.contentEncoding=c),u&&u.size>0){let p=[...u].map(vA);p.length===1?o.pattern=p[0].source:p.length>1&&(o.allOf=[...p.map(f=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},Tb=(e,t,n,r)=>{let o=n,{minimum:s,maximum:i,multipleOf:a,exclusiveMaximum:u,exclusiveMinimum:c,isInt:d}=tt(e);o.type=d?"integer":"number";let p=typeof c=="number"&&c>=(s??Number.NEGATIVE_INFINITY),f=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),h=t.target==="draft-04"||t.target==="openapi-3.0";if(p?h?(o.minimum=c,o.exclusiveMinimum=!0):o.exclusiveMinimum=c:typeof s=="number"&&(o.minimum=s),f?h?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),a){let g=new Set;for(let _ of a)Number.isFinite(_)&&_!==0?g.add(Math.abs(_)):et(e,t,o,r,`A multipleOf divisor of ${_} cannot be represented in JSON Schema`);let[x,...b]=g;x!==void 0&&(o.multipleOf=x),b.length&&(o.allOf=[...o.allOf??[],...b.map(_=>({multipleOf:_}))])}},Rb=(e,t,n,r)=>{n.type="boolean"},$b=(e,t,n,r)=>{et(e,t,n,r,"BigInt cannot be represented in JSON Schema")},Ib=(e,t,n,r)=>{et(e,t,n,r,"Symbols cannot be represented in JSON Schema")},Pb=(e,t,n,r)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},Ob=(e,t,n,r)=>{et(e,t,n,r,"Undefined cannot be represented in JSON Schema")},Lb=(e,t,n,r)=>{et(e,t,n,r,"Void cannot be represented in JSON Schema")},Mb=(e,t,n,r)=>{n.not={}},Db=(e,t,n,r)=>{},Fb=(e,t,n,r)=>{},zb=(e,t,n,r)=>{et(e,t,n,r,"Date cannot be represented in JSON Schema")},Kb=(e,t,n,r)=>{let o=e._zod.def,s=Fs(o.entries);if(s.length===0){n.not={};return}s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},Xb=(e,t,n,r)=>{let o=e._zod.def;if(o.values.length===0){n.not={};return}let s=[];for(let i of o.values)if(i===void 0){if(et(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof i=="bigint"){if(et(e,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];n.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[i]:n.const=i}else s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),s.every(i=>typeof i=="boolean")&&(n.type="boolean"),s.every(i=>i===null)&&(n.type="null"),n.enum=s},Bb=(e,t,n,r)=>{et(e,t,n,r,"NaN cannot be represented in JSON Schema")},Ub=(e,t,n,r)=>{let o=n,s=e._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=s.source},Hb=(e,t,n,r)=>{let o=n;o.type="string",o.format="binary",o.contentEncoding="binary";let{minimum:s,maximum:i,mime:a}=tt(e);s!==void 0&&(o.minLength=s),i!==void 0&&(o.maxLength=i),a&&(a.length===0?o.not={}:a.length===1?o.contentMediaType=a[0]:o.anyOf=a.map(u=>({contentMediaType:u})))},Vb=(e,t,n,r)=>{n.type="boolean"},Zb=(e,t,n,r)=>{et(e,t,n,r,"Custom types cannot be represented in JSON Schema")},Wb=(e,t,n,r)=>{et(e,t,n,r,"Function types cannot be represented in JSON Schema")},jb=(e,t,n,r)=>{et(e,t,n,r,"Transforms cannot be represented in JSON Schema")},Qb=(e,t,n,r)=>{et(e,t,n,r,"Map cannot be represented in JSON Schema")},Gb=(e,t,n,r)=>{et(e,t,n,r,"Set cannot be represented in JSON Schema")},Yb=(e,t,n,r)=>{let o=n,s=e._zod.def,{minimum:i,maximum:a}=tt(e);typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=$e(s.element,t,{...r,path:[...r.path,"items"]})};function xl(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?xl(t.out):t.type==="catch"?xl(t.innerType):e._zod.optin}var qb=(e,t,n,r)=>{let o=n,s=e._zod.def,i=s.shape;if(Object.getOwnPropertySymbols(i).length&&et(e,t,o,r,"Symbol keys cannot be represented in JSON Schema"))return;o.type="object",o.properties={};for(let c in i)it(o.properties,c,$e(i[c],t,{...r,path:[...r.path,"properties",c]}));let u=[];for(let c of Object.keys(i)){let d=s.shape[c];(t.io==="input"?xl(d)===void 0:d._zod.optout===void 0)&&u.push(c)}u.length>0&&(o.required=u),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=$e(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},Sp=(e,t,n,r)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((a,u)=>$e(a,t,{...r,path:[...r.path,s?"oneOf":"anyOf",u]}));s?n.oneOf=i:n.anyOf=i},Jb=(e,t,n,r)=>{let o=e._zod.def,s=$e(o.left,t,{...r,path:[...r.path,"allOf",0]}),i=$e(o.right,t,{...r,path:[...r.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1,u=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];n.allOf=u,t.intersections.push(u)},ey=(e,t,n,r)=>{let o=n,s=e._zod.def;o.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",u=s.items.map((x,b)=>$e(x,t,{...r,path:[...r.path,i,b]})),c=s.rest?$e(s.rest,t,{...r,path:[...r.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null,d=s.items.length;for(;d>0;){let x=s.items[d-1];if(!(t.io==="input"?xl(x)!==void 0:x._zod.optout==="optional"))break;d--}let p=s.items.length,f=!s.rest;t.target==="draft-2020-12"?(o.prefixItems=u,f?o.items=!1:c&&(o.items=c),d>0&&(o.minItems=d),f&&(o.maxItems=p)):t.target==="openapi-3.0"?(o.items={anyOf:u},c&&o.items.anyOf.push(c),d>0&&(o.minItems=d),f&&(o.maxItems=p)):(o.items=u,f?o.additionalItems=!1:c&&(o.additionalItems=c),d>0&&(o.minItems=d),f&&(o.maxItems=p));let{minimum:h,maximum:g}=tt(e);typeof h=="number"&&(o.minItems=h),typeof g=="number"&&(o.maxItems=g)};function Nb(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let g=e.get(t)?.def;if(!g)return t;let x=Nb(e,g,n);return x===g?t:x}for(let g of["anyOf","oneOf"]){let x=t[g];if(!Array.isArray(x))continue;let b=x.map(_=>Nb(e,_,n));b.some((_,w)=>_!==x[w])&&(t={...t,[g]:b})}let r=Array.isArray(t.type)?t.type:[t.type],o=!r.includes("string")&&r.some(g=>g==="number"||g==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!o&&!s?.some(g=>typeof g=="number"))return t;let{minimum:i,maximum:a,exclusiveMinimum:u,exclusiveMaximum:c,multipleOf:d,format:p,id:f,...h}=t;return h.enum?h.enum=h.enum.map(g=>typeof g=="number"?String(g):g):typeof h.const=="number"&&(h.const=String(h.const)),o&&(h.type="string",s||(h.pattern=(r.includes("number")?Zn:Qa).source)),h}var Ab=new WeakMap;function e3(e){let t=new Map;for(let r of e.seen.values())r.def&&!t.has(r.schema)&&t.set(r.schema,r);let n=new Map;for(let r of Ab.get(e)??[]){let o=e.seen.get(r),s=(o?.def??o?.schema)?.propertyNames;if(!s||s===!0||n.has(s))continue;let i=Nb(t,s,new Set);i!==s&&n.set(s,i)}if(n.size)for(let r of e.seen.values())for(let o of[r.schema,r.def]){let s=o&&n.get(o.propertyNames);s&&(o.propertyNames=s)}}var ty=(e,t,n,r)=>{let o=n,s=e._zod.def;o.type="object";let i=s.keyType,a=tt(i).patterns;if(s.mode==="loose"&&a&&a.size>0){let d=$e(s.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let p of a)it(o.patternProperties,vA(p).source,d)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){o.propertyNames=$e(s.keyType,t,{...r,path:[...r.path,"propertyNames"]});let d=Ab.get(t);d||(d=[],Ab.set(t,d),t.deferred.push(()=>e3(t))),d.push(e)}o.additionalProperties=$e(s.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let u=i._zod.values,c=t.io==="input"&&xl(s.valueType)!==void 0;if(u&&!s.partial&&!c){let d=[...u].filter(p=>typeof p=="string"||typeof p=="number");d.length>0&&(o.required=d.map(String))}},ny=(e,t,n,r)=>{let o=e._zod.def,s=$e(o.innerType,t,r),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=o.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},ry=(e,t,n,r)=>{let o=e._zod.def;$e(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType},oy=Symbol();function wA(e,t,n,r,o){let s=!1,i=JSON.stringify(e,(a,u)=>typeof u!="bigint"?u:(s=!0,null));return s?(et(t,n,r,o,"BigInt defaults cannot be represented in JSON Schema"),oy):JSON.parse(i)}var sy=(e,t,n,r)=>{let o=e._zod.def;$e(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType;let i=wA(o.defaultValue,e,t,n,r);i!==oy&&(n.default=i)},iy=(e,t,n,r)=>{let o=e._zod.def;$e(o.innerType,t,r);let s=t.seen.get(e);if(s.ref=o.innerType,t.io!=="input")return;let i=wA(o.defaultValue,e,t,n,r);i!==oy&&(n._prefault=i)},ay=(e,t,n,r)=>{let o=e._zod.def;$e(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{et(e,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=i},ly=(e,t,n,r)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;$e(i,t,r);let a=t.seen.get(e);a.ref=i},cy=(e,t,n,r)=>{let o=e._zod.def;$e(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType,n.readOnly=!0},uy=(e,t,n,r)=>{let o=e._zod.def;$e(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType},Ep=(e,t,n,r)=>{let o=e._zod.def;$e(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType},dy=(e,t,n,r)=>{let o=e._zod.innerType;$e(o,t,r);let s=t.seen.get(e);s.ref=o},kp={string:Cb,number:Tb,boolean:Rb,bigint:$b,symbol:Ib,null:Pb,undefined:Ob,void:Lb,never:Mb,any:Db,unknown:Fb,date:zb,enum:Kb,literal:Xb,nan:Bb,template_literal:Ub,file:Hb,success:Vb,custom:Zb,function:Wb,transform:jb,map:Qb,set:Gb,array:Yb,object:qb,union:Sp,intersection:Jb,tuple:ey,record:ty,nullable:ny,nonoptional:ry,default:sy,prefault:iy,catch:ay,pipe:ly,readonly:cy,promise:uy,optional:Ep,lazy:dy};function Np(e,t){if("_idmap"in e){let r=e,o=vr({...t,processors:kp}),s={};for(let u of r._idmap.entries()){let[c,d]=u;$e(d,o)}let i={},a={registry:r,uri:t?.uri,defs:s};o.external=a;for(let u of r._idmap.entries()){let[c,d]=u;wr(o,d),it(i,c,kr(o,d))}if(Object.keys(s).length>0){let u=o.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[u]:s}}return{schemas:i}}let n=vr({...t,processors:kp});return $e(e,n),wr(n,e),kr(n,e)}var Ap=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let n=t?.target??"draft-2020-12";n==="draft-4"&&(n="draft-04"),n==="draft-7"&&(n="draft-07"),this.ctx=vr({processors:kp,target:n,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,n={path:[],schemaPath:[]}){return $e(t,this.ctx,n)}emit(t,n){n&&(n.cycles&&(this.ctx.cycles=n.cycles),n.reused&&(this.ctx.reused=n.reused),n.external&&(this.ctx.external=n.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,wr(this.ctx,t);let r=kr(this.ctx,t),{"~standard":o,...s}=r;return s}};var kA={};var _i={};un(_i,{ZodAny:()=>Py,ZodArray:()=>Dy,ZodBase64:()=>Zp,ZodBase64URL:()=>Wp,ZodBigInt:()=>bi,ZodBigIntFormat:()=>Gp,ZodBoolean:()=>xi,ZodCIDRv4:()=>Hp,ZodCIDRv6:()=>Vp,ZodCUID:()=>Dp,ZodCUID2:()=>Fp,ZodCatch:()=>o_,ZodCodec:()=>Al,ZodCreditCard:()=>Ey,ZodCustom:()=>Cl,ZodCustomStringFormat:()=>Co,ZodDate:()=>vl,ZodDefault:()=>qy,ZodDiscriminatedUnion:()=>zy,ZodE164:()=>jp,ZodEmail:()=>Pp,ZodEmoji:()=>Lp,ZodEnum:()=>hi,ZodExactOptional:()=>ef,ZodFile:()=>jy,ZodFunction:()=>h_,ZodGUID:()=>Op,ZodIBAN:()=>Ny,ZodIPv4:()=>Bp,ZodIPv6:()=>Up,ZodISODate:()=>Er,ZodISODateTime:()=>Sr,ZodISODuration:()=>Ar,ZodISOTime:()=>Nr,ZodInstanceOf:()=>x_,ZodIntersection:()=>Ky,ZodJWT:()=>Qp,ZodKSUID:()=>Xp,ZodLazy:()=>d_,ZodLiteral:()=>Wy,ZodMAC:()=>Sy,ZodMap:()=>Vy,ZodNaN:()=>i_,ZodNanoID:()=>Mp,ZodNever:()=>Ly,ZodNonOptional:()=>tf,ZodNull:()=>$y,ZodNullable:()=>Yy,ZodNumber:()=>gi,ZodNumberFormat:()=>To,ZodObject:()=>kl,ZodOptional:()=>El,ZodPipe:()=>Nl,ZodPrefault:()=>e_,ZodPreprocess:()=>a_,ZodPromise:()=>f_,ZodReadonly:()=>l_,ZodRecord:()=>fi,ZodSet:()=>Zy,ZodString:()=>mi,ZodStringFormat:()=>Le,ZodSuccess:()=>r_,ZodSymbol:()=>Ty,ZodTemplateLiteral:()=>u_,ZodTransform:()=>Qy,ZodTuple:()=>By,ZodType:()=>ye,ZodULID:()=>zp,ZodURL:()=>_l,ZodUUID:()=>Nn,ZodUndefined:()=>Ry,ZodUnion:()=>Sl,ZodUnknown:()=>Oy,ZodVoid:()=>My,ZodXID:()=>Kp,ZodXor:()=>Fy,_ZodString:()=>Ip,_default:()=>Jy,_function:()=>LC,any:()=>pC,array:()=>wl,base64:()=>ZA,base64url:()=>WA,bigint:()=>aC,boolean:()=>Cy,catch:()=>s_,check:()=>MC,cidrv4:()=>HA,cidrv6:()=>VA,codec:()=>$C,creditCard:()=>QA,cuid:()=>MA,cuid2:()=>DA,currencyCode:()=>tC,custom:()=>DC,date:()=>hC,describe:()=>FC,discriminatedUnion:()=>_C,e164:()=>jA,email:()=>NA,emoji:()=>OA,enum:()=>qp,exactOptional:()=>Gy,file:()=>AC,float32:()=>rC,float64:()=>oC,function:()=>LC,guid:()=>AA,hash:()=>nC,hex:()=>eC,hostname:()=>JA,httpUrl:()=>PA,iban:()=>GA,instanceof:()=>KC,int:()=>Rp,int32:()=>sC,int64:()=>lC,intersection:()=>Xy,invertCodec:()=>IC,ipv4:()=>XA,ipv6:()=>UA,json:()=>BC,jwt:()=>YA,keyof:()=>mC,ksuid:()=>KA,lazy:()=>p_,literal:()=>NC,looseObject:()=>bC,looseRecord:()=>wC,mac:()=>BA,map:()=>kC,meta:()=>zC,nan:()=>RC,nanoid:()=>LA,nativeEnum:()=>EC,never:()=>Yp,nonoptional:()=>n_,null:()=>Iy,nullable:()=>yl,nullish:()=>CC,number:()=>Ay,object:()=>gC,optional:()=>No,partialRecord:()=>vC,pipe:()=>$p,prefault:()=>t_,preprocess:()=>UC,promise:()=>OC,readonly:()=>c_,record:()=>Hy,refine:()=>m_,set:()=>SC,strictObject:()=>xC,string:()=>bl,stringFormat:()=>qA,stringbool:()=>XC,success:()=>TC,superRefine:()=>g_,symbol:()=>uC,templateLiteral:()=>PC,transform:()=>Jp,tuple:()=>Uy,uint32:()=>iC,uint64:()=>cC,ulid:()=>FA,undefined:()=>dC,union:()=>yi,unknown:()=>Eo,url:()=>IA,uuid:()=>CA,uuidv4:()=>TA,uuidv6:()=>RA,uuidv7:()=>$A,void:()=>fC,xid:()=>zA,xor:()=>yC});var Cp={};un(Cp,{endsWith:()=>ni,gt:()=>Sn,gte:()=>Ft,includes:()=>ei,length:()=>ko,lowercase:()=>qs,lt:()=>kn,lte:()=>Dt,maxLength:()=>wo,maxSize:()=>_r,mime:()=>oi,minLength:()=>Wn,minSize:()=>En,multipleOf:()=>yr,negative:()=>yp,nonnegative:()=>vp,nonpositive:()=>_p,normalize:()=>si,overwrite:()=>cn,positive:()=>bp,properties:()=>ri,property:()=>wp,regex:()=>Ys,size:()=>vo,slugify:()=>ci,startsWith:()=>ti,toLowerCase:()=>ai,toUpperCase:()=>li,trim:()=>ii,uppercase:()=>Js});var SA=new WeakSet([Object.prototype,Error.prototype]);function Tp(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let r=n(this);return Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0})}})}var EA=(e,t)=>{fg.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);SA.has(n)||(SA.add(n),Tp(n,"format",r=>o=>Va(r,o)),Tp(n,"flatten",r=>o=>Ha(r,o)),Tp(n,"addIssue",r=>o=>{r.issues.push(o),r.message=JSON.stringify(r.issues,zs,2)}),Tp(n,"addIssues",r=>o=>{r.issues.push(...o),r.message=JSON.stringify(r.issues,zs,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},n3=I("ZodError",EA),Ot=I("ZodError",EA,void 0,{Parent:Error});var py=Us(Ot),fy=Hs(Ot),hy=Vs(Ot),my=Zs(Ot),gy=id(Ot),xy=ad(Ot),by=ld(Ot),yy=cd(Ot),_y=ud(Ot),vy=dd(Ot),wy=pd(Ot),ky=fd(Ot);function o3(){ot.localeError||He(Vd())}function Ao(){ot.memoizer||He({memoizer:cl()})}var ye=I("ZodType",(e,t)=>(o3(),me.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(oe.mergeDefs(t,{checks:[...t.checks??[],...e.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Te(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(m_(e,t))},superRefine(e,t){return this.check(g_(e,t))},overwrite(e){return this.check(cn(e))},optional(){return No(this)},exactOptional(){return Gy(this)},nullable(){return yl(this)},nullish(){return No(yl(this))},nonoptional(e){return n_(this,e)},array(){return wl(this)},or(e){return yi([this,e])},and(e){return Xy(this,e)},transform(e){return $p(this,Jp(e))},default(e){return Jy(this,e)},prefault(e){return t_(this,e)},catch(e){return s_(this,e)},pipe(e){return $p(this,e)},readonly(){return c_(this)},describe(e){let t=this.clone();return at.add(t,{description:e}),t},meta(...e){if(e.length===0)return at.get(this);let t=this.clone();return at.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return oe.hide(this,"~standard",{...Sd(this),jsonSchema:{input:ui(this,"input"),output:ui(this,"output")}})},set"~standard"(e){oe.own(this,"~standard",e)},parse:function e(t,n){return py(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await fy(this,t,n,{callee:e})},safeParse(e,t){return hy(this,e,t)},async safeParseAsync(e,t){return my(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){oe.own(this,"spa",e)},validate(e,t){return Za(this,e,t)},validateAsync(e,t){return Wa(this,e,t)},encode:function e(t,n){return gy(this,t,n,{callee:e})},decode:function e(t,n){return xy(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await by(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await yy(this,t,n,{callee:e})},safeEncode(e,t){return _y(this,e,t)},safeDecode(e,t){return vy(this,e,t)},async safeEncodeAsync(e,t){return wy(this,e,t)},async safeDecodeAsync(e,t){return ky(this,e,t)},toJSONSchema(e){return Eb(this,{})(e)},get description(){return at.get(this)?.description},get _def(){return this._zod.def}}),Ip=I("_ZodString",(e,t)=>{go.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Cb(e,n,r,o)},oe.derived({format:e=>tt(e).format??null,minLength:e=>tt(e).minimum??null,maxLength:e=>tt(e).maximum??null},{regex(...e){return this.check(Ys(...e))},includes(...e){return this.check(ei(...e))},startsWith(...e){return this.check(ti(...e))},endsWith(...e){return this.check(ni(...e))},min(...e){return this.check(Wn(...e))},max(...e){return this.check(wo(...e))},length(...e){return this.check(ko(...e))},nonempty(...e){return this.check(Wn(1,...e))},lowercase(e){return this.check(qs(e))},uppercase(e){return this.check(Js(e))},trim(){return this.check(ii())},normalize(...e){return this.check(si(...e))},toLowerCase(){return this.check(ai())},toUpperCase(){return this.check(li())},slugify(){return this.check(ci())}})),mi=I("ZodString",(e,t)=>{go.init(e,t),Ip.init(e,t)},{email(e){return this.check(Yd(Pp,e))},url(e){return this.check(dl(_l,e))},jwt(e){return this.check(xp(Qp,e))},emoji(e){return this.check(rp(Lp,e))},guid(e){return this.check(qd(Op,e))},uuid(e){return this.check(Jd(Nn,e))},uuidv4(e){return this.check(ep(Nn,e))},uuidv6(e){return this.check(tp(Nn,e))},uuidv7(e){return this.check(np(Nn,e))},nanoid(e){return this.check(op(Mp,e))},cuid(e){return this.check(sp(Dp,e))},cuid2(e){return this.check(ip(Fp,e))},ulid(e){return this.check(ap(zp,e))},base64(e){return this.check(hp(Zp,e))},base64url(e){return this.check(mp(Wp,e))},xid(e){return this.check(lp(Kp,e))},ksuid(e){return this.check(cp(Xp,e))},ipv4(e){return this.check(up(Bp,e))},ipv6(e){return this.check(dp(Up,e))},cidrv4(e){return this.check(pp(Hp,e))},cidrv6(e){return this.check(fp(Vp,e))},e164(e){return this.check(gp(jp,e))},datetime(e){return this.check(pl(Sr,e))},date(e){return this.check(fl(Er,e))},time(e){return this.check(hl(Nr,e))},duration(e){return this.check(ml(Ar,e))}});function bl(e){return Xx(mi,e)}var Le=I("ZodStringFormat",(e,t)=>{Re.init(e,t),Ip.init(e,t)}),Sr=I("ZodISODateTime",(e,t)=>{P0.init(e,t),Le.init(e,t)}),Er=I("ZodISODate",(e,t)=>{O0.init(e,t),Le.init(e,t)}),Nr=I("ZodISOTime",(e,t)=>{L0.init(e,t),Le.init(e,t)}),Ar=I("ZodISODuration",(e,t)=>{M0.init(e,t),Le.init(e,t)}),Pp=I("ZodEmail",(e,t)=>{w0.init(e,t),Le.init(e,t)});function NA(e){return Yd(Pp,e)}var Op=I("ZodGUID",(e,t)=>{_0.init(e,t),Le.init(e,t)});function AA(e){return qd(Op,e)}var Nn=I("ZodUUID",(e,t)=>{v0.init(e,t),Le.init(e,t)});function CA(e){return Jd(Nn,e)}function TA(e){return ep(Nn,e)}function RA(e){return tp(Nn,e)}function $A(e){return np(Nn,e)}var _l=I("ZodURL",(e,t)=>{E0.init(e,t),Le.init(e,t)});function IA(e){return dl(_l,e)}function PA(e){return dl(_l,{protocol:ja,hostname:Mg,...oe.normalizeParams(e)})}var Lp=I("ZodEmoji",(e,t)=>{N0.init(e,t),Le.init(e,t)});function OA(e){return rp(Lp,e)}var Mp=I("ZodNanoID",(e,t)=>{A0.init(e,t),Le.init(e,t)});function LA(e){return op(Mp,e)}var Dp=I("ZodCUID",(e,t)=>{C0.init(e,t),Le.init(e,t)});function MA(e){return sp(Dp,e)}var Fp=I("ZodCUID2",(e,t)=>{T0.init(e,t),Le.init(e,t)});function DA(e){return ip(Fp,e)}var zp=I("ZodULID",(e,t)=>{R0.init(e,t),Le.init(e,t)});function FA(e){return ap(zp,e)}var Kp=I("ZodXID",(e,t)=>{$0.init(e,t),Le.init(e,t)});function zA(e){return lp(Kp,e)}var Xp=I("ZodKSUID",(e,t)=>{I0.init(e,t),Le.init(e,t)});function KA(e){return cp(Xp,e)}var Bp=I("ZodIPv4",(e,t)=>{D0.init(e,t),Le.init(e,t)});function XA(e){return up(Bp,e)}var Sy=I("ZodMAC",(e,t)=>{z0.init(e,t),Le.init(e,t)});function BA(e){return Ux(Sy,e)}var Up=I("ZodIPv6",(e,t)=>{F0.init(e,t),Le.init(e,t)});function UA(e){return dp(Up,e)}var Hp=I("ZodCIDRv4",(e,t)=>{K0.init(e,t),Le.init(e,t)});function HA(e){return pp(Hp,e)}var Vp=I("ZodCIDRv6",(e,t)=>{X0.init(e,t),Le.init(e,t)});function VA(e){return fp(Vp,e)}var Zp=I("ZodBase64",(e,t)=>{B0.init(e,t),Le.init(e,t)});function ZA(e){return hp(Zp,e)}var Wp=I("ZodBase64URL",(e,t)=>{U0.init(e,t),Le.init(e,t)});function WA(e){return mp(Wp,e)}var jp=I("ZodE164",(e,t)=>{H0.init(e,t),Le.init(e,t)});function jA(e){return gp(jp,e)}var Ey=I("ZodCreditCard",(e,t)=>{V0.init(e,t),Le.init(e,t)});function QA(e){return Hx(Ey,e)}var Ny=I("ZodIBAN",(e,t)=>{Z0.init(e,t),Le.init(e,t)});function GA(e){return Vx(Ny,e)}var Qp=I("ZodJWT",(e,t)=>{W0.init(e,t),Le.init(e,t)});function YA(e){return xp(Qp,e)}var Co=I("ZodCustomStringFormat",(e,t)=>{j0.init(e,t),Le.init(e,t)});function qA(e,t,n={}){return So(Co,e,t,n)}function JA(e){return So(Co,"hostname",Lg,e)}function eC(e){return So(Co,"hex",Gg,e)}function tC(e){return So(Co,"currency_code",Fg,e)}function nC(e,t){let n=t?.enc??"hex",r=`${e}_${n}`,o=Wt[r];if(!o)throw new Error(`Unrecognized hash format: ${r}`);return So(Co,r,o,t)}var gi=I("ZodNumber",(e,t)=>{Od.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Tb(e,n,r,o),e.isFinite=!0},oe.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=tt(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=tt(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:n}=tt(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>tt(e).format??null},{gt(e,t){return this.check(Sn(e,t))},gte(e,t){return this.check(Ft(e,t))},min(e,t){return this.check(Ft(e,t))},lt(e,t){return this.check(kn(e,t))},lte(e,t){return this.check(Dt(e,t))},max(e,t){return this.check(Dt(e,t))},int(e){return this.check(Rp(e))},safe(e){return this.check(Rp(e))},positive(e){return this.check(Sn(0,e))},nonnegative(e){return this.check(Ft(0,e))},negative(e){return this.check(kn(0,e))},nonpositive(e){return this.check(Dt(0,e))},multipleOf(e,t){return this.check(yr(e,t))},step(e,t){return this.check(yr(e,t))},finite(){return this}}));function Ay(e){return Wx(gi,e)}var To=I("ZodNumberFormat",(e,t)=>{Q0.init(e,t),gi.init(e,t)});function Rp(e){return Qx(To,e)}function rC(e){return Gx(To,e)}function oC(e){return Yx(To,e)}function sC(e){return qx(To,e)}function iC(e){return Jx(To,e)}var xi=I("ZodBoolean",(e,t)=>{rl.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Rb(e,n,r,o)});function Cy(e){return eb(xi,e)}var bi=I("ZodBigInt",(e,t)=>{Ld.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>$b(e,n,r,o)},oe.derived({minValue:e=>tt(e).minimum??null,maxValue:e=>tt(e).maximum??null,format:e=>tt(e).format??null},{gte(e,t){return this.check(Ft(e,t))},min(e,t){return this.check(Ft(e,t))},gt(e,t){return this.check(Sn(e,t))},lt(e,t){return this.check(kn(e,t))},lte(e,t){return this.check(Dt(e,t))},max(e,t){return this.check(Dt(e,t))},positive(e){return this.check(Sn(BigInt(0),e))},negative(e){return this.check(kn(BigInt(0),e))},nonpositive(e){return this.check(Dt(BigInt(0),e))},nonnegative(e){return this.check(Ft(BigInt(0),e))},multipleOf(e,t){return this.check(yr(e,t))}}));function aC(e){return nb(bi,e)}var Gp=I("ZodBigIntFormat",(e,t)=>{G0.init(e,t),bi.init(e,t)});function lC(e){return ob(Gp,e)}function cC(e){return sb(Gp,e)}var Ty=I("ZodSymbol",(e,t)=>{Y0.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ib(e,n,r,o)});function uC(e){return ib(Ty,e)}var Ry=I("ZodUndefined",(e,t)=>{q0.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ob(e,n,r,o)});function dC(e){return ab(Ry,e)}var $y=I("ZodNull",(e,t)=>{J0.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Pb(e,n,r,o)});function Iy(e){return lb($y,e)}var Py=I("ZodAny",(e,t)=>{ex.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Db(e,n,r,o)});function pC(){return cb(Py)}var Oy=I("ZodUnknown",(e,t)=>{tx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Fb(e,n,r,o)});function Eo(){return ub(Oy)}var Ly=I("ZodNever",(e,t)=>{nx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Mb(e,n,r,o)});function Yp(e){return db(Ly,e)}var My=I("ZodVoid",(e,t)=>{rx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Lb(e,n,r,o)});function fC(e){return pb(My,e)}var vl=I("ZodDate",(e,t)=>{ox.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>zb(e,n,r,o),e.min=(n,r)=>e.check(Ft(n,r)),e.max=(n,r)=>e.check(Dt(n,r))},oe.derived({minDate:e=>{let{minimum:t}=tt(e);return t?new Date(t):null},maxDate:e=>{let{maximum:t}=tt(e);return t?new Date(t):null}},{}));function hC(e){return fb(vl,e)}var Dy=I("ZodArray",(e,t)=>{Ao(),sx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Yb(e,n,r,o),e.element=t.element},{min(e,t){return this.check(Wn(e,t))},nonempty(e){return this.check(Wn(1,e))},max(e,t){return this.check(wo(e,t))},length(e,t){return this.check(ko(e,t))},unwrap(){return this.element}});function wl(e,t){return gb(Dy,e,t)}function mC(e){let t=e._zod.def.shape;return qp(Object.keys(t))}var kl=I("ZodObject",(e,t)=>{Ao(),ix.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>qb(e,n,r,o),oe.installLazyProp(e,"shape",n=>n._zod.def.shape,!1)},{keyof(){return qp(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(oe.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(oe.mergeDefs(this._zod.def,{catchall:Eo()}))},loose(){return this.clone(oe.mergeDefs(this._zod.def,{catchall:Eo()}))},strict(){return this.clone(oe.mergeDefs(this._zod.def,{catchall:Yp()}))},strip(){return this.clone(oe.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return oe.extend(this,e)},safeExtend(e){return oe.safeExtend(this,e)},merge(e){return oe.merge(this,e)},pick(e){return oe.pick(this,e)},omit(e){return oe.omit(this,e)},partial(...e){return oe.partial(El,this,e[0])},exactPartial(...e){return oe.partial(ef,this,e[0],"exactPartial")},required(...e){return oe.required(tf,this,e[0])}});function gC(e,t){let n={type:"object",shape:e??{},...oe.normalizeParams(t)};return new kl(n)}function xC(e,t){return new kl({type:"object",shape:e,catchall:Yp(),...oe.normalizeParams(t)})}function bC(e,t){return new kl({type:"object",shape:e,catchall:Eo(),...oe.normalizeParams(t)})}var Sl=I("ZodUnion",(e,t)=>{ol.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Sp(e,n,r,o),e.options=t.options});function yi(e,t){return new Sl({type:"union",options:e,...oe.normalizeParams(t)})}var Fy=I("ZodXor",(e,t)=>{Sl.init(e,t),ax.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Sp(e,n,r,o),e.options=t.options});function yC(e,t){return new Fy({type:"union",options:e,inclusive:!1,...oe.normalizeParams(t)})}var zy=I("ZodDiscriminatedUnion",(e,t)=>{Sl.init(e,t),cx.init(e,t)});function _C(e,t,n){return new zy({type:"union",options:t,discriminator:e,...oe.normalizeParams(n)})}var Ky=I("ZodIntersection",(e,t)=>{ux.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Jb(e,n,r,o)});function Xy(e,t){return new Ky({type:"intersection",left:e,right:t})}var By=I("ZodTuple",(e,t)=>{Ao(),Md.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ey(e,n,r,o)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new El({type:"optional",innerType:t}))})}});function Uy(e,t,n){let r=t instanceof me,o=r?n:t,s=r?t:null;return new By({type:"tuple",items:e,rest:s,...oe.normalizeParams(o)})}var fi=I("ZodRecord",(e,t)=>{Ao(),dx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ty(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType});function Hy(e,t,n){return!t||!t._zod?new fi({type:"record",keyType:bl(),valueType:e,...oe.normalizeParams(t)}):new fi({type:"record",keyType:e,valueType:t,...oe.normalizeParams(n)})}function vC(e,t,n){return new fi({type:"record",keyType:e,valueType:t,...oe.normalizeParams(n),partial:!0})}function wC(e,t,n){return new fi({type:"record",keyType:e,valueType:t,mode:"loose",...oe.normalizeParams(n)})}var Vy=I("ZodMap",(e,t)=>{Ao(),px.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Qb(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...n)=>e.check(En(...n)),e.nonempty=n=>e.check(En(1,n)),e.max=(...n)=>e.check(_r(...n)),e.size=(...n)=>e.check(vo(...n))});function kC(e,t,n){return new Vy({type:"map",keyType:e,valueType:t,...oe.normalizeParams(n)})}var Zy=I("ZodSet",(e,t)=>{Ao(),fx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Gb(e,n,r,o),e.min=(...n)=>e.check(En(...n)),e.nonempty=n=>e.check(En(1,n)),e.max=(...n)=>e.check(_r(...n)),e.size=(...n)=>e.check(vo(...n))});function SC(e,t){return new Zy({type:"set",valueType:e,...oe.normalizeParams(t)})}var hi=I("ZodEnum",(e,t)=>{hx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(r,o,s)=>Kb(e,r,o,s),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new hi({...t,checks:[],...oe.normalizeParams(o),entries:s})},e.exclude=(r,o)=>{let s={...t.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new hi({...t,checks:[],...oe.normalizeParams(o),entries:s})}});function qp(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new hi({type:"enum",entries:n,...oe.normalizeParams(t)})}function EC(e,t){return new hi({type:"enum",entries:e,...oe.normalizeParams(t)})}var Wy=I("ZodLiteral",(e,t)=>{mx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Xb(e,n,r,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function NC(e,t){return new Wy({type:"literal",values:Array.isArray(e)?e:[e],...oe.normalizeParams(t)})}var jy=I("ZodFile",(e,t)=>{gx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Hb(e,n,r,o),e.min=(n,r)=>e.check(En(n,r)),e.max=(n,r)=>e.check(_r(n,r)),e.mime=(n,r)=>e.check(oi(Array.isArray(n)?n:[n],r))});function AC(e){return xb(jy,e)}var Qy=I("ZodTransform",(e,t)=>{Ao(),xx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>jb(e,n,r,o),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new br(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(oe.issue(s,n.value,t));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=n.value),i.inst??(i.inst=e),n.issues.push(oe.issue(i))}};let o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function Jp(e){return new Qy({type:"transform",transform:e})}var El=I("ZodOptional",(e,t)=>{Dd.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ep(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function No(e){return new El({type:"optional",innerType:e})}var ef=I("ZodExactOptional",(e,t)=>{bx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ep(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Gy(e){return new ef({type:"optional",innerType:e})}var Yy=I("ZodNullable",(e,t)=>{yx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ny(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function yl(e){return new Yy({type:"nullable",innerType:e})}function CC(e){return No(yl(e))}var qy=I("ZodDefault",(e,t)=>{_x.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>sy(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Jy(e,t){return new qy({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():oe.shallowClone(t)}})}var e_=I("ZodPrefault",(e,t)=>{vx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>iy(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function t_(e,t){return new e_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():oe.shallowClone(t)}})}var tf=I("ZodNonOptional",(e,t)=>{wx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ry(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function n_(e,t){return new tf({type:"nonoptional",innerType:e,...oe.normalizeParams(t)})}var r_=I("ZodSuccess",(e,t)=>{kx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Vb(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function TC(e){return new r_({type:"success",innerType:e})}var o_=I("ZodCatch",(e,t)=>{Sx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ay(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function s_(e,t){return new o_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:oe.constantCatch(t)})}var i_=I("ZodNaN",(e,t)=>{Ex.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Bb(e,n,r,o)});function RC(e){return mb(i_,e)}var Nl=I("ZodPipe",(e,t)=>{Fd.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ly(e,n,r,o),e.in=t.in,e.out=t.out});function $p(e,t){return new Nl({type:"pipe",in:e,out:t})}var Al=I("ZodCodec",(e,t)=>{Nl.init(e,t),sl.init(e,t)});function $C(e,t,n){return new Al({type:"pipe",in:e,out:t,transform:n.decode,reverseTransform:n.encode})}function IC(e){let t=e._zod.def;return new Al({type:"pipe",in:t.out,out:t.in,transform:t.reverseTransform,reverseTransform:t.transform})}var a_=I("ZodPreprocess",(e,t)=>{Nl.init(e,t),Nx.init(e,t)}),l_=I("ZodReadonly",(e,t)=>{Ax.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>cy(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function c_(e){return new l_({type:"readonly",innerType:e})}var u_=I("ZodTemplateLiteral",(e,t)=>{Cx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ub(e,n,r,o)});function PC(e,t){return new u_({type:"template_literal",parts:e,...oe.normalizeParams(t)})}var d_=I("ZodLazy",(e,t)=>{il.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>dy(e,n,r,o),e.unwrap=()=>e._zod.def.getter()});function p_(e){return new d_({type:"lazy",getter:e})}var f_=I("ZodPromise",(e,t)=>{Rx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>uy(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function OC(e){return new f_({type:"promise",innerType:e})}var h_=I("ZodFunction",(e,t)=>{Tx.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Wb(e,n,r,o)});function LC(e){return new h_({type:"function",input:Array.isArray(e?.input)?Uy(e?.input):e?.input??wl(Eo()),output:e?.output??Eo()})}var Cl=I("ZodCustom",(e,t)=>{$x.init(e,t),ye.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Zb(e,n,r,o)});function MC(e){let t=new Fe({check:"custom"});return t._zod.check=e,t}function DC(e,t){return bb(Cl,e??(()=>!0),t)}function m_(e,t={}){return yb(Cl,e,t)}function g_(e,t){return _b(e,t)}var FC=vb,zC=wb,x_=I("ZodInstanceOf",(e,t)=>{Cl.init(e,t)},{properties(e,t){return this.check(ri(e,t))}});function KC(e,t={}){let n=new x_({type:"custom",check:"custom",fn:r=>r instanceof e,abort:!0,...oe.normalizeParams(t)});return n._zod.bag.Class=e,n._zod.check=r=>{r.value instanceof e||r.issues.push({code:"invalid_type",expected:e.name,input:r.value,inst:n,path:[...n._zod.def.path??[]]})},n}var XC=(...e)=>kb({Codec:Al,Boolean:xi,String:mi},...e);function BC(e){let t=p_(()=>yi([bl(e),Ay(),Cy(),Iy(),wl(t),Hy(bl(),t)]));return t}function UC(e,t){return new a_({type:"pipe",in:Jp(e),out:t})}var s3={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function i3(e){He({customError:e})}function a3(){return He().customError}var b_;b_||(b_={});var Tl={};un(Tl,{ZodISODate:()=>Er,ZodISODateTime:()=>Sr,ZodISODuration:()=>Ar,ZodISOTime:()=>Nr,date:()=>c3,datetime:()=>l3,duration:()=>d3,time:()=>u3});function l3(e){return pl(Sr,e)}function c3(e){return fl(Er,e)}function u3(e){return hl(Nr,e)}function d3(e){return ml(Ar,e)}var te={..._i,...Cp,iso:Tl},p3=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function f3(e,t){let n=e.$schema;return n==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":n==="http://json-schema.org/draft-07/schema#"?"draft-7":n==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function HC(e,t){return e.map((n,r)=>r<t?n:n.optional())}function h3(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function m3(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let n=e.slice(1).split("/").filter(Boolean);if(n.length===0)return t.rootSchema;let r=t.version==="draft-2020-12"?"$defs":"definitions";if(n[0]===r){let o=n[1]===void 0?void 0:h3(n[1]);if(!o||!t.defs[o])throw new Error(`Reference not found: ${e}`);return t.defs[o]}throw new Error(`Reference not found: ${e}`)}function g3(e,t){return te.transform(r=>r).check(r=>{let o=r.value;if(typeof o!="object"||o===null||Array.isArray(o))return;let s=Object.getOwnPropertyNames(o);if(t.minProperties!==void 0&&s.length<t.minProperties&&r.issues.push({origin:"object",code:"too_small",minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:o,inst:e,continue:!0}),t.maxProperties!==void 0&&s.length>t.maxProperties&&r.issues.push({origin:"object",code:"too_big",maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:o,inst:e,continue:!0}),t.keySchema)for(let i of s){let a=t.keySchema.safeParse(i);a.success||r.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:i,path:[i],continue:!0})}}).pipe(e)}function y_(e,t){if(e===null)return"z";let n=typeof e;if(n!=="object"){if(n==="number"&&Number.isNaN(e))return null;let r=String(e);return`${n[0]}${r.length}:${r}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let s=[];for(let i of e){let a=y_(i,t);if(a===null)return null;s.push(a)}return`a${s.length}:[${s.join(",")}]`}let r=Object.keys(e).sort(),o=[];for(let s of r){let i=y_(e[s],t);if(i===null)return null;o.push(`${s.length}:${s}=${i}`)}return`o${o.length}:{${o.join(",")}}`}finally{t.delete(e)}}var x3=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),b3=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function Rl(e){return typeof e!="object"||e===null?!1:Array.isArray(e)?e.some(Rl):typeof e.$ref=="string"?!0:Object.entries(e).some(([t,n])=>x3.has(t)?Rl(n):!b3.has(t)||typeof n!="object"||n===null?!1:Object.values(n).some(Rl))}function VC(e){return e===1?"element":"elements"}function y3(e,t){return te.transform(r=>r).check(r=>{let o=r.value;if(Array.isArray(o)){if(t.uniqueItems===!0){let s=new Map;for(let i=0;i<o.length;i++){let a=y_(o[i],new Set);if(a===null)continue;let u=s.get(a);if(u===void 0){s.set(a,i);continue}r.issues.push({code:"custom",message:`Array items must be unique: element at index ${i} duplicates the one at index ${u}`,input:o,path:[i],continue:!0})}}if(t.containsSchema){let s=t.minContains??1,i=t.maxContains!==void 0?t.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let u of o)if(t.containsSchema.safeParse(u).success&&++a>=i)break;a<s&&r.issues.push({code:"custom",message:`Array must contain at least ${s} matching ${VC(s)}; found ${a}`,input:o,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&r.issues.push({code:"custom",message:`Array must contain at most ${t.maxContains} matching ${VC(t.maxContains)}`,input:o,continue:!0})}}}).pipe(e)}function ZC(e,t){if(e!==!1)return e===void 0||e===!0?te.any():Et(e,t)}var _3=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function WC(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return te.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let o=e.$ref;if(t.refs.has(o))return t.refs.get(o);if(t.processing.has(o))return te.lazy(()=>{if(!t.refs.has(o))throw new Error(`Circular reference not resolved: ${o}`);return t.refs.get(o)});t.processing.add(o);let s=m3(o,t),i=Et(s,t);return t.refs.set(o,i),t.processing.delete(o),i}if(e.enum!==void 0){let o=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&o.length===1&&o[0]===null)return te.null();if(o.length===0)return te.never();if(o.length===1)return te.literal(o[0]);if(o.every(i=>typeof i=="string"))return te.enum(o);let s=o.map(i=>te.literal(i));return s.length<2?s[0]:te.union([s[0],s[1],...s.slice(2)])}if(e.const!==void 0)return te.literal(e.const);let n=e.type;if(Array.isArray(n)){let o=n.map(s=>{let i={...e,type:s};return WC(i,t)});return o.length===0?te.never():o.length===1?o[0]:te.union(o)}if(!n)return te.any();let r;switch(n){case"string":{let o=te.string();if(e.format){let s=e.format;s==="email"?o=o.check(te.email()):s==="uri"||s==="uri-reference"?o=o.check(te.url()):s==="uuid"||s==="guid"?o=o.check(te.uuid()):s==="date-time"?o=o.check(te.iso.datetime({offset:!0})):s==="date"?o=o.check(te.iso.date()):s==="time"?o=o.check(te.regex(_3)):s==="duration"?o=o.check(te.iso.duration()):s==="hostname"?o=o.check(te.hostname()):s==="ipv4"?o=o.check(te.ipv4()):s==="ipv6"?o=o.check(te.ipv6()):s==="mac"?o=o.check(te.mac()):s==="cidr"?o=o.check(te.cidrv4()):s==="cidr-v6"?o=o.check(te.cidrv6()):s==="base64"?o=o.check(te.base64()):s==="base64url"?o=o.check(te.base64url()):s==="e164"?o=o.check(te.e164()):s==="credit_card"?o=o.check(te.creditCard()):s==="iban"?o=o.check(te.iban()):s==="jwt"?o=o.check(te.jwt()):s==="emoji"?o=o.check(te.emoji()):s==="nanoid"?o=o.check(te.nanoid()):s==="cuid"?o=o.check(te.cuid()):s==="cuid2"?o=o.check(te.cuid2()):s==="ulid"?o=o.check(te.ulid()):s==="xid"?o=o.check(te.xid()):s==="ksuid"&&(o=o.check(te.ksuid()))}typeof e.minLength=="number"&&(o=o.min(e.minLength)),typeof e.maxLength=="number"&&(o=o.max(e.maxLength)),e.pattern&&(o=o.regex(new RegExp(e.pattern))),r=o;break}case"number":case"integer":{let o=n==="integer"?te.number().int():te.number();typeof e.minimum=="number"&&e.exclusiveMinimum!==!0&&(o=o.min(e.minimum)),typeof e.maximum=="number"&&e.exclusiveMaximum!==!0&&(o=o.max(e.maximum)),typeof e.exclusiveMinimum=="number"?o=o.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(o=o.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?o=o.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(o=o.lt(e.maximum)),typeof e.multipleOf=="number"&&(o=o.multipleOf(e.multipleOf)),r=o;break}case"boolean":{r=te.boolean();break}case"null":{r=te.null();break}case"object":{let o={},s=e.properties||{},i=new Set(e.required||[]),a=typeof e.additionalProperties=="object"?Et(e.additionalProperties,t):void 0;for(let[p,f]of Object.entries(s)){let h=Et(f,t);it(o,p,i.has(p)?h:h.optional())}if(e.patternProperties){let p=e.patternProperties,f=Object.keys(p),h=[];for(let x of f){let b=Et(p[x],t),_=te.string().regex(new RegExp(x));h.push(te.looseRecord(_,b))}let g=[];if(Object.keys(o).length>0&&g.push(te.object(o).passthrough()),g.push(...h),g.length===0)r=te.object({}).passthrough();else if(g.length===1)r=g[0];else{let x=te.intersection(g[0],g[1]);for(let b=2;b<g.length;b++)x=te.intersection(x,g[b]);r=x}if(e.additionalProperties===!1){let x=Object.keys(o),b=f.map(w=>new RegExp(w)),_=r;r=r.check(w=>{if(!Vt(w.value))return;let T=[];for(let y of Object.keys(w.value))x.includes(y)||b.some(E=>E.test(y))||T.push(y);T.length&&w.issues.push({code:"unrecognized_keys",keys:T,input:w.value,inst:_})})}}else{let p=te.object(o);e.additionalProperties===!1?r=p.strict():a?r=p.catchall(a):r=p.passthrough()}let u=e.propertyNames!==void 0&&e.propertyNames!==!0,c=typeof e.minProperties=="number"?e.minProperties:void 0,d=typeof e.maxProperties=="number"?e.maxProperties:void 0;if(u||c!==void 0||d!==void 0){let p;if(u){let f=typeof e.propertyNames=="object"&&e.propertyNames.type===void 0?{type:"string",...e.propertyNames}:e.propertyNames;p=Et(f,t)}r=g3(r,{keySchema:p,minProperties:c,maxProperties:d})}break}case"array":{let o=e.prefixItems,s=e.items;if(o&&Array.isArray(o)){let i=typeof e.minItems=="number"?e.minItems:0,a=o.map(p=>Et(p,t)),u=HC(a,i),c=Array.isArray(s)?void 0:ZC(s,t),d=te.tuple(u);r=c?d.rest(c):d,typeof e.minItems=="number"&&(r=r.check(te.minLength(e.minItems))),typeof e.maxItems=="number"&&(r=r.check(te.maxLength(e.maxItems)))}else if(Array.isArray(s)){let i=typeof e.minItems=="number"?e.minItems:0,a=s.map(p=>Et(p,t)),u=HC(a,i),c=ZC(e.additionalItems,t),d=te.tuple(u);r=c?d.rest(c):d,typeof e.minItems=="number"&&(r=r.check(te.minLength(e.minItems))),typeof e.maxItems=="number"&&(r=r.check(te.maxLength(e.maxItems)))}else if(s!==void 0){let i=Et(s,t),a=te.array(i);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),r=a}else r=te.array(te.any());(e.uniqueItems===!0||e.contains!==void 0)&&(r=y3(r,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains!==void 0?Et(e.contains,t):void 0,minContains:typeof e.minContains=="number"?e.minContains:void 0,maxContains:typeof e.maxContains=="number"?e.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${n}`)}return r}function Et(e,t){if(typeof e=="boolean")return e?te.any():te.never();let n=WC(e,t),r=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let a=e.anyOf.map(c=>Et(c,t)),u=te.union(a);n=r?te.intersection(n,u):u}if(e.oneOf&&Array.isArray(e.oneOf)){let a=e.oneOf.map(c=>Et(c,t)),u=te.xor(a);n=r?te.intersection(n,u):u}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)n=r?n:te.any();else{let a=r?n:Et(e.allOf[0],t),u=r?0:1;for(let c=u;c<e.allOf.length;c++)a=te.intersection(a,Et(e.allOf[c],t));n=a}e.nullable===!0&&t.version==="openapi-3.0"&&(n=te.nullable(n)),e.readOnly===!0&&(n=te.readonly(n)),e.default!==void 0&&(n=n.default(e.default));let o={},s=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of s)a in e&&(o[a]=e[a]);let i=["contentEncoding","contentMediaType","contentSchema"];for(let a of i)a in e&&(o[a]=e[a]);if(e.type==="object"&&e.$ref===void 0){e.propertyNames!==void 0&&!Rl(e.propertyNames)&&(o.propertyNames=e.propertyNames);for(let a of["minProperties","maxProperties"])e[a]!==void 0&&(o[a]=e[a])}if(e.type==="array"&&e.$ref===void 0){e.contains!==void 0&&!Rl(e.contains)&&(o.contains=e.contains);for(let a of["uniqueItems","minContains","maxContains"])e[a]!==void 0&&(o[a]=e[a])}for(let a of Object.keys(e))p3.has(a)||it(o,a,e[a]);return Object.keys(o).length>0&&t.registry.add(n,o),e.description&&(n=n.describe(e.description)),n}function jC(e,t){if(typeof e=="boolean")return e?te.any():te.never();let n;try{n=JSON.parse(JSON.stringify(e))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let r=f3(n,t?.defaultTarget),o=n.$defs||n.definitions||{},s={version:r,defs:o,refs:new Map,processing:new Set,rootSchema:n,registry:t?.registry??at};return Et(n,s)}var QC=Symbol("z.visit/resolving");function $l(e,t){let n=typeof t=="function"?t:(i,a)=>{let u=t[i._zod.def.type];return u?u(i,a):i},r=new Map;function o(i){let a=r.get(i);if(a===QC)return new il({type:"lazy",getter:()=>r.get(i)});if(a!==void 0)return a;r.set(i,QC);let u=s(i),c=n(u,u!==i);return r.set(i,c),c}function s(i){let a=i._zod.def,u=a.type;switch(u){case"object":{let c=a.shape,d=Object.keys(c),p=!1,f={};for(let g of d){let x=o(c[g]);x!==c[g]&&(p=!0),f[g]=x}let h=a.catchall;return a.catchall&&(h=o(a.catchall),h!==a.catchall&&(p=!0)),p?Te(i,{...a,shape:f,catchall:h}):i}case"array":{let c=o(a.element);return c===a.element?i:Te(i,{...a,element:c})}case"tuple":{let c=a.items,d=!1,p=[];for(let h of c){let g=o(h);g!==h&&(d=!0),p.push(g)}let f=a.rest;return a.rest&&(f=o(a.rest),f!==a.rest&&(d=!0)),d?Te(i,{...a,items:p,rest:f}):i}case"record":case"map":{let c=o(a.keyType),d=o(a.valueType);return c===a.keyType&&d===a.valueType?i:Te(i,{...a,keyType:c,valueType:d})}case"set":{let c=o(a.valueType);return c===a.valueType?i:Te(i,{...a,valueType:c})}case"union":{let c=a.options,d=!1,p=[];for(let f of c){let h=o(f);h!==f&&(d=!0),p.push(h)}return d?Te(i,{...a,options:p}):i}case"intersection":{let c=o(a.left),d=o(a.right);return c===a.left&&d===a.right?i:Te(i,{...a,left:c,right:d})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let c=o(a.innerType);return c===a.innerType?i:Te(i,{...a,innerType:c})}case"pipe":{let c=o(a.in),d=o(a.out);return c===a.in&&d===a.out?i:Te(i,{...a,in:c,out:d})}case"function":{let c=o(a.input),d=o(a.output);return c===a.input&&d===a.output?i:Te(i,{...a,input:c,output:d})}case"lazy":{let c=a.getter,{_cachedInner:d,...p}=a;return Te(i,{...p,getter:()=>o(c())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return i;default:return i}}return o(e)}function GC(e){return $l(e,{object:t=>t.partial(),union:t=>{let n=t._zod.def;return n.discriminator===void 0?t:yi(n.options)}})}function v3(e,t){if(!t?.length)return e;let n=e._zod.def;return Te(e,an(n,{checks:[...n.checks??[],...t]}),{parent:!0})}function YC(e){return v3(e.out,e.checks)}function w3(e){return e.in._zod.traits.has("$ZodTransform")?YC(e):e.in}function qC(e){return $l(e,{pipe:t=>w3(t._zod.def),default:(t,n)=>n?No(t._zod.def.innerType):t,catch:(t,n)=>n?t._zod.def.innerType:t})}function JC(e){return $l(e,{pipe:t=>YC(t._zod.def),prefault:(t,n)=>n?t._zod.def.innerType:t})}var __={};un(__,{bigint:()=>N3,boolean:()=>E3,date:()=>A3,number:()=>S3,string:()=>k3});function k3(e){return Bx(mi,e)}function S3(e){return jx(gi,e)}function E3(e){return tb(xi,e)}function N3(e){return rb(bi,e)}function A3(e){return hb(vl,e)}var C3=/^([01]\d|2[0-3]):[0-5]\d$/,Il=re.string().regex(C3,"a time like 07:00"),T3=["mon","tue","wed","thu","fri","sat","sun"];var An=e=>re.string().trim().max(e).regex(/^[^\u0000-\u001f\u007f-\u009f<>]*$/,"one line, without < or >"),v_=re.string().trim().max(200).regex(/^[^\s@<>]+@[^\s@<>]+$/,"an email address"),R3=re.object({name:An(80).min(1),email:v_.optional(),emails:re.array(v_).max(9).optional(),phone:An(40).optional(),org:An(80).optional(),relation:An(60).optional()}).strict(),$3=re.object({name:An(80).min(1),admin:An(80).optional(),country:An(80).optional(),latitude:re.number().min(-90).max(90),longitude:re.number().min(-180).max(180),timezone:re.string().trim().min(1).max(64).regex(/^[A-Za-z0-9_+-]+(\/[A-Za-z0-9_+-]+)*$/,"a time zone name like America/Los_Angeles")}).strict();var eT=["you","reach","touchpoints","connections","library"],I3=re.object({version:re.literal(1).default(1),you:re.object({name:An(60).optional(),city:An(80).optional(),place:$3.optional(),email:v_.optional()}).strict().default({}),reach:re.object({inbox:re.boolean().default(!0),mail:re.boolean().default(!1),quiet_from:Il.optional(),quiet_to:Il.optional(),other:re.array(An(60).min(1)).max(10).default([])}).strict().default({inbox:!0,mail:!1,other:[]}),touchpoints:re.object({morning:re.object({on:re.boolean().default(!0),at:Il.default("07:00"),weather:re.boolean().default(!0),calendar:re.boolean().default(!0),mail:re.boolean().default(!0),loops:re.boolean().default(!0)}).strict().default({on:!0,at:"07:00",weather:!0,calendar:!0,mail:!0,loops:!0}),evening:re.object({on:re.boolean().default(!0),at:Il.default("17:30")}).strict().default({on:!0,at:"17:30"}),weekly:re.object({on:re.boolean().default(!1),day:re.enum(T3).default("fri"),at:Il.default("16:00")}).strict().default({on:!1,day:"fri",at:"16:00"})}).strict().prefault({}),contacts:re.array(R3).max(2e3).default([]),schedules:re.object({morning:re.string().optional(),evening:re.string().optional(),weekly:re.string().optional()}).strict().default({}),saved:re.preprocess(e=>typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).filter(([t])=>eT.includes(t))):e,re.partialRecord(re.enum(eT),re.number()).default({})),finished_at:re.number().optional(),untold:re.literal(!0).optional()}).strict();var OZ=I3.parse({});var P3=2e3;function tT(e,t){let n=e.filter(c=>c.name.trim()||c.email||c.relation),r=new Map,o=new Map,s=(c,d)=>{for(let p of[c.email,...c.emails??[]])p&&r.set(p.toLowerCase(),d);c.name.trim()&&o.set(c.name.trim().toLowerCase(),d)};n.forEach(s);let i=0,a=0,u=0;for(let c of t){let d=[c.email,...c.emails??[]].filter(_=>!!_),p=d.map(_=>r.get(_.toLowerCase())).find(_=>_!==void 0)??o.get(c.name.trim().toLowerCase());if(p===void 0){if(n.length>=P3){u++;continue}n.push(c),s(c,n.length-1),i++;continue}let f=n[p],h=[...new Set([...f.email?[f.email]:[],...f.emails??[],...d])],[g,...x]=h,b={...f,name:f.name.trim()||c.name,...g?{email:g}:{},...x.length?{emails:x.slice(0,9)}:{},...f.phone||c.phone?{phone:f.phone??c.phone}:{},...f.org||c.org?{org:f.org??c.org}:{}};JSON.stringify(b)!==JSON.stringify(f)&&a++,n[p]=b,s(b,p)}return{contacts:n,added:i,updated:a,dropped:u}}var nT={vcard:"a vCard","google-csv":"Google Contacts' CSV","outlook-csv":"Outlook's CSV",csv:"a CSV"},rT=[{source:"Apple Contacts (Mac, iPhone)",how:"On the Mac, select the contacts (\u2318A for all), then File \u2192 Export \u2192 Export vCard\u2026. On an iPhone, Contacts \u2192 Lists \u2192 press and hold a list \u2192 Export."},{source:"Google Contacts (Android, Gmail)",how:"At contacts.google.com, Export \u2192 vCard (for iOS Contacts) or Google CSV. Android phones sync to the same place."},{source:"Outlook",how:"File \u2192 Open & Export \u2192 Import/Export \u2192 Export to a file \u2192 Comma Separated Values, with Contacts chosen."},{source:"Anything else",how:"A vCard (.vcf) file, or a CSV with a name column (or first and last name) and an email column."}];var O3=8e6;function sT(e){return e instanceof Error?e.message:String(e)}function oT(e){return[e.emails?.length?`also ${e.emails.join(", ")}`:"",e.phone??"",e.org??""].filter(Boolean).join(" \xB7 ")}function w_(e){return e.filter(t=>t.name.trim()).map(t=>({name:t.name.trim(),...t.email?.trim()?{email:t.email.trim()}:{},...t.emails?.length?{emails:t.emails}:{},...t.phone?{phone:t.phone}:{},...t.org?{org:t.org}:{},...t.relation?.trim()?{relation:t.relation.trim()}:{}}))}function L3({rpc:e,onImported:t}){let n=G(null),[r,o]=v(!1),[s,i]=v(null),[a,u]=v(null),[c,d]=v(!1),[p,f]=v(!1),h=async g=>{let x=Array.from(g)[0];if(x){o(!0),u(null),i(null);try{if(x.size>O3)throw new Error("that file is over 8 MB");let b=await e.call("welcome.importContacts",{name:x.name,text:await x.text()});t(b.contacts),i(`${b.contacts.length} ${b.contacts.length===1?"person":"people"} from ${nT[b.format]}${b.skipped?` (${b.skipped} entries with nothing to know them by, or repeats, left out)`:""}. Add who they are to you where it matters.`)}catch(b){u(sT(b))}finally{o(!1),n.current&&(n.current.value="")}}};return m("div",{className:"flex flex-col gap-2",children:[l("input",{ref:n,type:"file","aria-label":"Contacts export file",accept:".vcf,.csv,text/vcard,text/csv,text/plain",className:"hidden",onChange:g=>g.target.files&&void h(g.target.files)}),m("button",{type:"button",className:V("flex w-full flex-col items-center gap-1 rounded-md border-2 border-dashed px-4 py-5 text-sm transition-colors",p?"border-foreground bg-muted":"border-input hover:border-foreground/50",r&&"pointer-events-none opacity-60"),onClick:()=>n.current?.click(),onDragOver:g=>{g.preventDefault(),f(!0)},onDragLeave:()=>f(!1),onDrop:g=>{g.preventDefault(),f(!1),g.dataTransfer.files.length&&h(g.dataTransfer.files)},children:[l("span",{className:"font-medium",children:r?"Reading\u2026":"Import from a file: drop it here, or click to choose"}),l("span",{className:"text-xs text-muted-foreground",children:"A vCard (.vcf) from Apple Contacts, Google Contacts or any phone; a CSV from Google Contacts or Outlook; any CSV with names and emails."})]}),m("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[l("button",{type:"button",className:"text-muted-foreground underline",onClick:()=>d(!c),children:c?"Hide":"Where do I export from?"}),a?l("span",{role:"alert",className:"text-destructive",children:a}):s&&l("span",{className:"text-muted-foreground",children:s})]}),c&&l("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 rounded-md border p-3 text-xs",children:rT.map(({source:g,how:x})=>m("div",{className:"contents",children:[l("dt",{className:"font-medium",children:g}),l("dd",{className:"text-muted-foreground",children:x})]},g))})]})}function M3({rpc:e,contacts:t,setContacts:n}){let[r,o]=v(""),s=(u,c,d)=>n(p=>p.map((f,h)=>h===u?{...f,[c]:d.trim()||c==="name"?d:void 0}:f)),i=r.trim().toLowerCase(),a=t.map((u,c)=>[u,c]).filter(([u])=>!i||`${u.name} ${u.email??""} ${u.org??""} ${u.relation??""}`.toLowerCase().includes(i));return m("div",{className:"flex flex-col gap-2",children:[l(L3,{rpc:e,onImported:u=>n(c=>tT(c,u).contacts)}),t.length>8&&m("div",{className:"flex items-center gap-2 text-xs",children:[l(le,{className:"h-8 max-w-xs",placeholder:"Find someone","aria-label":"Find someone",value:r,onChange:u=>o(u.target.value)}),m("span",{className:"text-muted-foreground",children:[a.length," of ",t.length]})]}),m("ul",{className:"flex max-h-96 flex-col gap-2 overflow-y-auto pr-1",children:[a.slice(0,200).map(([u,c])=>m("li",{className:"flex flex-col gap-1",children:[m("div",{className:"flex flex-wrap items-center gap-2",children:[l(le,{className:"w-full sm:w-44",placeholder:"Name","aria-label":"Name",value:u.name,onChange:d=>s(c,"name",d.target.value)}),l(le,{className:"w-full sm:w-56",placeholder:"Email (optional)","aria-label":"Email",value:u.email??"",onChange:d=>s(c,"email",d.target.value)}),l(le,{className:"w-full sm:w-44",placeholder:"Who they are: partner, my accountant","aria-label":"Who they are",value:u.relation??"",onChange:d=>s(c,"relation",d.target.value)}),l(R,{size:"sm",variant:"ghost",onClick:()=>n(d=>d.filter((p,f)=>f!==c)),children:"Remove"})]}),oT(u)&&l("span",{className:"pl-1 text-xs text-muted-foreground",children:oT(u)})]},c)),a.length>200&&m("li",{className:"text-xs text-muted-foreground",children:["And ",a.length-200," more; find them by name above."]})]}),l("div",{children:l(R,{size:"sm",variant:"secondary",onClick:()=>n(u=>[...u,{name:""}]),children:"Add a person"})})]})}function iT(){let{rpc:e,state:t,error:n,refetch:r}=wn(),o=t?.record.contacts??null,[s,i]=v({contacts:null,conflict:!1}),a=s.contacts,u=s.conflict,c=G(o),d=G(!1);M(()=>{let N=c.current,$=d.current;i(P=>{let L=P.contacts===null||N!==null&&JSON.stringify(P.contacts)===JSON.stringify(N);return{contacts:L&&!$?null:P.contacts,conflict:!L&&(P.conflict||o!==null&&N!==null&&JSON.stringify(o)!==JSON.stringify(N))}}),c.current=o},[o]);let[p,f]=v(!1),[h,g]=v(!1),[x,b]=v(null),[_,w]=v(null),T=a??o,y=async N=>{d.current=!0,f(!0),w(null),b(null);try{b(await N()),r()}catch($){w(sT($))}finally{d.current=!1,f(!1)}},E=N=>y(async()=>{let $=await e.call("welcome.save",{step:"connections",values:{contacts:N}});return c.current=$.record.contacts,i(P=>({contacts:P.contacts===a?$.record.contacts:P.contacts,conflict:!1})),g(!1),$.lines.join(" ")}),k=T!==null&&o!==null&&JSON.stringify(w_(T))!==JSON.stringify(w_(o));return m("div",{className:"flex max-w-3xl flex-col gap-3 text-sm",children:[l("p",{children:"Optional. Who's who: the people you mention and who they are to you, so your moonlet can say who wrote. Mail from anyone else stays unknown until you say. Import an export from Apple Contacts, Google Contacts or Outlook, or add people by hand."}),l("p",{children:"The list stays on your Moonlet server. Machines enabled for assistant work get a private copy for the inbox check. It is a starting list, separate from your moonlet's protected record of people, which nothing here changes."}),l("p",{role:"status",children:o===null?"Loading contacts\u2026":o.length===0?"Off. No contacts saved; nothing is imported until you add some.":`${o.length} ${o.length===1?"person":"people"} saved.`}),T!==null&&l(M3,{rpc:e,contacts:T,setContacts:N=>i($=>({...$,contacts:N($.contacts??c.current??o??[])}))}),m("div",{className:"flex flex-wrap gap-2",children:[k&&l(R,{disabled:p,onClick:()=>T&&void E(w_(T)),children:"Save contacts"}),k&&l(R,{variant:"ghost",disabled:p,onClick:()=>i({contacts:null,conflict:!1}),children:"Discard changes"}),o!==null&&o.length>0&&!h&&l(R,{variant:"secondary",disabled:p,onClick:()=>g(!0),children:"Remove all contacts"}),o!==null&&o.length>0&&h&&m(R,{variant:"destructive",disabled:p,onClick:()=>{E([])},children:["Remove all ",o.length]}),o!==null&&l(R,{variant:"secondary",disabled:p,onClick:()=>{y(async()=>(await e.call("welcome.handover",null)).lines.join(" "))},children:"Refresh contacts on machines"})]}),h&&l("p",{className:"text-muted-foreground",children:"Removing clears the saved list and the machines' copies. It does not touch your moonlet's protected record of people or anything it keeps in memory."}),u&&l("p",{role:"status",className:"text-muted-foreground",children:"The saved contacts changed. Your edits are kept. Discard changes to load the saved list, or save to replace it with your edits."}),x&&l("p",{role:"status",children:x}),(n||_)&&l("p",{role:"alert",className:"text-destructive",children:_||n})]})}async function aT(e,t,n){let r=await e({...t,expectedSha256:null});if(r.outcome==="written")return"added";if(r.currentSha256===null)throw new Error("the station reported a clash but no file there; nothing was written");if(!await n())return"kept";if((await e({...t,expectedSha256:r.currentSha256})).outcome==="written")return"replaced";throw new Error("the file there changed while you were asked, so it was kept as it is; drop yours again to replace it")}var D3=/^[a-z][a-z0-9-]{0,47}$/,lT=`[library]
211
211
  type = "s3"
212
212
  path = "example-bucket/library"
213
213
  options = { provider = "AWS", region = "us-east-1" }
214
214
  item = "Library store"
215
- `;function O3(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result).replace(/^data:[^,]*,/,"")),r.onerror=()=>n(r.error),r.readAsDataURL(e)})}function L3(e){return e instanceof Error?e.message:String(e)}function M3({machines:e}){let t=un(),n=e.filter(C=>C.connected),[r,o]=_(n[0]?.id??""),[s,i]=_("documents"),[a,u]=_([]),[c,d]=_(null),[p,f]=_(null),[h,g]=_(!1),x=Y(null),b=n.find(C=>C.id===r)??n[0],v=P3.test(s),w=async C=>{if(!b)return;if(!v)return d("A collection's name is lowercase letters, digits and dashes, like insurance or meeting-notes.");d(null);let y=b.library;for(let T of Array.from(C)){let N=T.name;if(!N||N.includes("/")||N.startsWith(".")){d(`${N}: a plain file name, not hidden`);continue}try{f(N);let S=await O3(T),$=await rT(P=>t.files.write(P),{hostId:b.id,rootPath:y,path:`${y}/${s}/${N}`,content:S,contentEncoding:"base64",createParents:!0,mode:420},()=>window.confirm(`${N} is already in ${s}. Replace it?`));if($==="kept")continue;u(P=>[...P,`${N} \u2192 ${b.name}, ${s}${$==="replaced"?" (replaced)":""}`])}catch(S){d(`${N}: ${L3(S)}`)}finally{f(null)}}};return n.length===0?l("p",{className:"text-sm text-muted-foreground",children:"No machine is connected right now. Add documents when one is, or use the Library page."}):m("div",{className:"flex flex-col gap-3",children:[m("div",{className:"grid grid-cols-2 gap-3",children:[m("label",{className:"flex flex-col gap-1 text-sm",children:[l("span",{className:"font-medium",children:"Machine"}),l("select",{className:"h-9 rounded-md border border-input bg-background px-2 text-sm",value:b?.id??"",onChange:C=>o(C.target.value),children:n.map(C=>l("option",{value:C.id,children:C.name},C.id))})]}),m("label",{className:"flex flex-col gap-1 text-sm",children:[l("span",{className:"font-medium",children:"Collection"}),l(le,{className:V("h-9",!v&&"border-destructive"),value:s,onChange:C=>i(C.target.value)}),l("span",{className:"text-xs text-muted-foreground",children:"Lowercase, dashes: insurance, meeting-notes."})]})]}),l("input",{ref:x,type:"file",multiple:!0,className:"hidden",onChange:C=>C.target.files&&void w(C.target.files)}),m("button",{type:"button",className:V("flex w-full flex-col items-center gap-2 rounded-md border-2 border-dashed px-4 py-8 text-sm transition-colors",h?"border-foreground bg-muted":"border-input hover:border-foreground/50",p!==null&&"pointer-events-none opacity-60"),onClick:()=>x.current?.click(),onDragOver:C=>{C.preventDefault(),g(!0)},onDragLeave:()=>g(!1),onDrop:C=>{C.preventDefault(),g(!1),C.dataTransfer.files.length&&w(C.dataTransfer.files)},children:[l("span",{className:"font-medium",children:p?`Sending ${p}\u2026`:"Drop files here, or click to choose"}),m("span",{className:"text-xs text-muted-foreground",children:["Into ",v?s:"\u2026"," on ",b?.name,". PDFs, Word and text files, Markdown; anything readable."]})]}),c&&l("p",{className:"text-xs text-destructive",children:c}),a.length>0&&l("ul",{className:"flex flex-col gap-1 text-xs text-muted-foreground",children:a.map((C,y)=>m("li",{className:"flex items-center gap-2",children:[l("span",{children:"\u2713"}),C]},y))})]})}function D3({source:e}){if(!e)return l("p",{role:"status",children:"No source. The library works without one: files arrive through this page, the Library page in the sidebar, or the assistant."});let t=Object.entries(e.options);return m("div",{role:"status",className:"flex flex-col gap-1",children:[m("p",{children:["Source: ",e.type,", ",l("code",{children:e.path}),". Each machine mirrors it read-only every minute and searches what it holds alongside its own files."]}),t.length>0&&m("p",{children:["Settings: ",t.map(([n,r])=>`${n} = ${r}`).join(", "),"."]}),l("p",{children:e.item?`Secret settings come from the vault item ${e.item}, read on the machine at each pull.`:"No vault item: the source needs no secret settings."}),l("p",{children:"The policy names the source, so changing it goes through the policy's approval."})]})}function F3({state:e}){let[t,n]=_(!1);return m("section",{className:"flex max-w-xl flex-col gap-3 text-sm",children:[l("p",{children:"On by default. Your documents go into a library on each machine the assistant works on, and it finds them by meaning. The library needs no outside account; a source is optional."}),e.stations.length===0?l("p",{children:"No machine enabled for assistant work yet. Choose a prepared machine in Settings \u2192 Machines; its library is made when it is set up."}):l("ul",{className:"list-disc pl-5",children:e.stations.map(r=>m("li",{children:[r.name,": ",l("code",{children:r.library}),r.connected?"":" (machine offline)"]},r.id))}),l("p",{children:"Each folder under the library is a collection. A file is searchable within a minute or two of arriving and leaves the search when it leaves the folder. The Library page in the sidebar lists everything there."}),l(M3,{machines:e.stations}),l(D3,{source:e.librarySource}),m("details",{className:"rounded-md border p-3",children:[l("summary",{className:"cursor-pointer font-medium",children:e.librarySource?"Change the source":"Add a source"}),m("div",{className:"mt-2 flex flex-col gap-2",children:[l("p",{children:"A source is a store you own that rclone can reach: S3, Google Drive, Dropbox, OneDrive, WebDAV, SFTP and others. Each machine keeps a read-only copy of it beside its own files, so the store stays the place to add or remove those files."}),m("p",{children:["Propose a ",l("code",{children:"[library]"})," entry in Settings \u2192 Permissions \u2192 Advanced \u2192 Policy file. ",l("code",{children:"type"})," is rclone's backend, ",l("code",{children:"path"})," ","what to mirror, and ",l("code",{children:"options"})," its settings that aren't secret. ",l("code",{children:"item"})," is optional: a vault item whose fields hold the secret settings in rclone's names, such as ",l("code",{children:"access_key_id"}),". This example does not grant access:"]}),l("pre",{className:"overflow-x-auto rounded-md bg-muted p-2 text-xs",children:oT}),l(R,{variant:"secondary",onClick:async()=>{try{await navigator.clipboard.writeText(oT),n(!0)}catch{n(!1)}},children:t?"Copied example":"Copy library source example"}),l("p",{children:"Saving the policy does not pull anything. The normal approved machine update starts the pull. Removing the entry stops the pull and empties each machine's copy; the store keeps its files, and the machines keep their own."})]})]})]})}function sT(){let{state:e,error:t}=vn();return t?l("p",{role:"alert",className:"text-destructive",children:t}):e?l(F3,{state:e}):l("p",{role:"status",children:"Loading library\u2026"})}var iT=`[[login]]
215
+ `;function F3(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result).replace(/^data:[^,]*,/,"")),r.onerror=()=>n(r.error),r.readAsDataURL(e)})}function z3(e){return e instanceof Error?e.message:String(e)}function K3({machines:e}){let t=dn(),n=e.filter(T=>T.connected),[r,o]=v(n[0]?.id??""),[s,i]=v("documents"),[a,u]=v([]),[c,d]=v(null),[p,f]=v(null),[h,g]=v(!1),x=G(null),b=n.find(T=>T.id===r)??n[0],_=D3.test(s),w=async T=>{if(!b)return;if(!_)return d("A collection's name is lowercase letters, digits and dashes, like insurance or meeting-notes.");d(null);let y=b.library;for(let E of Array.from(T)){let k=E.name;if(!k||k.includes("/")||k.startsWith(".")){d(`${k}: a plain file name, not hidden`);continue}try{f(k);let N=await F3(E),$=await aT(P=>t.files.write(P),{hostId:b.id,rootPath:y,path:`${y}/${s}/${k}`,content:N,contentEncoding:"base64",createParents:!0,mode:420},()=>window.confirm(`${k} is already in ${s}. Replace it?`));if($==="kept")continue;u(P=>[...P,`${k} \u2192 ${b.name}, ${s}${$==="replaced"?" (replaced)":""}`])}catch(N){d(`${k}: ${z3(N)}`)}finally{f(null)}}};return n.length===0?l("p",{className:"text-sm text-muted-foreground",children:"No machine is connected right now. Add documents when one is, or use the Library page."}):m("div",{className:"flex flex-col gap-3",children:[m("div",{className:"grid grid-cols-2 gap-3",children:[m("label",{className:"flex flex-col gap-1 text-sm",children:[l("span",{className:"font-medium",children:"Machine"}),l("select",{className:"h-9 rounded-md border border-input bg-background px-2 text-sm",value:b?.id??"",onChange:T=>o(T.target.value),children:n.map(T=>l("option",{value:T.id,children:T.name},T.id))})]}),m("label",{className:"flex flex-col gap-1 text-sm",children:[l("span",{className:"font-medium",children:"Collection"}),l(le,{className:V("h-9",!_&&"border-destructive"),value:s,onChange:T=>i(T.target.value)}),l("span",{className:"text-xs text-muted-foreground",children:"Lowercase, dashes: insurance, meeting-notes."})]})]}),l("input",{ref:x,type:"file",multiple:!0,className:"hidden",onChange:T=>T.target.files&&void w(T.target.files)}),m("button",{type:"button",className:V("flex w-full flex-col items-center gap-2 rounded-md border-2 border-dashed px-4 py-8 text-sm transition-colors",h?"border-foreground bg-muted":"border-input hover:border-foreground/50",p!==null&&"pointer-events-none opacity-60"),onClick:()=>x.current?.click(),onDragOver:T=>{T.preventDefault(),g(!0)},onDragLeave:()=>g(!1),onDrop:T=>{T.preventDefault(),g(!1),T.dataTransfer.files.length&&w(T.dataTransfer.files)},children:[l("span",{className:"font-medium",children:p?`Sending ${p}\u2026`:"Drop files here, or click to choose"}),m("span",{className:"text-xs text-muted-foreground",children:["Into ",_?s:"\u2026"," on ",b?.name,". PDFs, Word and text files, Markdown; anything readable."]})]}),c&&l("p",{className:"text-xs text-destructive",children:c}),a.length>0&&l("ul",{className:"flex flex-col gap-1 text-xs text-muted-foreground",children:a.map((T,y)=>m("li",{className:"flex items-center gap-2",children:[l("span",{children:"\u2713"}),T]},y))})]})}function X3({source:e}){if(!e)return l("p",{role:"status",children:"No source. The library works without one: files arrive through this page, the Library page in the sidebar, or the assistant."});let t=Object.entries(e.options);return m("div",{role:"status",className:"flex flex-col gap-1",children:[m("p",{children:["Source: ",e.type,", ",l("code",{children:e.path}),". Each machine mirrors it read-only every minute and searches what it holds alongside its own files."]}),t.length>0&&m("p",{children:["Settings: ",t.map(([n,r])=>`${n} = ${r}`).join(", "),"."]}),l("p",{children:e.item?`Secret settings come from the vault item ${e.item}, read on the machine at each pull.`:"No vault item: the source needs no secret settings."}),l("p",{children:"The policy names the source, so changing it goes through the policy's approval."})]})}function B3({state:e}){let[t,n]=v(!1);return m("section",{className:"flex max-w-xl flex-col gap-3 text-sm",children:[l("p",{children:"On by default. Your documents go into a library on each machine the assistant works on, and it finds them by meaning. The library needs no outside account; a source is optional."}),e.stations.length===0?l("p",{children:"No machine enabled for assistant work yet. Choose a prepared machine in Settings \u2192 Machines; its library is made when it is set up."}):l("ul",{className:"list-disc pl-5",children:e.stations.map(r=>m("li",{children:[r.name,": ",l("code",{children:r.library}),r.connected?"":" (machine offline)"]},r.id))}),l("p",{children:"Each folder under the library is a collection. A file is searchable within a minute or two of arriving and leaves the search when it leaves the folder. The Library page in the sidebar lists everything there."}),l(K3,{machines:e.stations}),l(X3,{source:e.librarySource}),m("details",{className:"rounded-md border p-3",children:[l("summary",{className:"cursor-pointer font-medium",children:e.librarySource?"Change the source":"Add a source"}),m("div",{className:"mt-2 flex flex-col gap-2",children:[l("p",{children:"A source is a store you own that rclone can reach: S3, Google Drive, Dropbox, OneDrive, WebDAV, SFTP and others. Each machine keeps a read-only copy of it beside its own files, so the store stays the place to add or remove those files."}),m("p",{children:["Propose a ",l("code",{children:"[library]"})," entry in Settings \u2192 Permissions \u2192 Advanced \u2192 Policy file. ",l("code",{children:"type"})," is rclone's backend, ",l("code",{children:"path"})," ","what to mirror, and ",l("code",{children:"options"})," its settings that aren't secret. ",l("code",{children:"item"})," is optional: a vault item whose fields hold the secret settings in rclone's names, such as ",l("code",{children:"access_key_id"}),". This example does not grant access:"]}),l("pre",{className:"overflow-x-auto rounded-md bg-muted p-2 text-xs",children:lT}),l(R,{variant:"secondary",onClick:async()=>{try{await navigator.clipboard.writeText(lT),n(!0)}catch{n(!1)}},children:t?"Copied example":"Copy library source example"}),l("p",{children:"Saving the policy does not pull anything. The normal approved machine update starts the pull. Removing the entry stops the pull and empties each machine's copy; the store keeps its files, and the machines keep their own."})]})]})]})}function cT(){let{state:e,error:t}=wn();return t?l("p",{role:"alert",className:"text-destructive",children:t}):e?l(B3,{state:e}):l("p",{role:"status",children:"Loading library\u2026"})}var uT=`[[login]]
216
216
  name = "bridge"
217
217
  item = "Assistant Proton"
218
218
  bridge = true
219
- `;function z3({state:e}){let t=Ie(),[n,r]=_(!1);return m("section",{className:"flex max-w-xl flex-col gap-3 text-sm",children:[l("p",{children:"Optional. Set up the assistant's own mailbox, separate from your account. The assistant reads and sends from that mailbox only through its existing mail controls."}),l("p",{children:"Mail runs on a prepared machine. Settings \u2192 Machines keeps all saved machines; the list below shows only machines enabled for assistant work."}),e.stations.length===0?l("p",{role:"status",children:"No machine enabled for assistant work yet. Choose a prepared machine in Settings \u2192 Machines, then ask the assistant to set up mail on it."}):l("ul",{className:"list-disc pl-5",children:e.stations.map(o=>m("li",{children:[o.name,":"," ",o.mail==="none"?"mail disabled in record":o.mail==="proton"?"Proton Mail enabled in record":"mail enabled in record",o.connected?"":" (machine offline)"]},o.id))}),l("p",{children:"The machine mail setting enables Proton Mail and Bridge. New machine records start with mail off; existing and imported machines keep their settings. Saving a selection does not install software or sign in. The normal approved machine update applies it."}),m("p",{children:["Protected vault access:"," ",e.secrets.onepassword?"service-account key saved.":"not set up. Add the 1Password key under 1Password on this page, or in first run's Machine sign-ins step."," ","Mailbox credentials stay in the configured vault and are read by protected tools."]}),m("p",{children:["Protected mailbox sign-in entries: ",e.mailLogins.length?e.mailLogins.join(", "):"none configured",". Saved entries and machine configuration do not confirm a successful sign-in or mail connection."]}),m("details",{className:"rounded-md border p-3",open:e.stations.some(o=>o.mail==="proton"),children:[l("summary",{className:"cursor-pointer font-medium",children:"Set up Proton Mail"}),m("div",{className:"mt-2 flex flex-col gap-2",children:[l("p",{children:"Store the assistant's Proton username and password in its vault item, including its mailbox password if used. Proton Mail Bridge requires a paid Proton plan."}),l("p",{children:"Ask the assistant to prepare the machine and propose enabling mail. The normal approved machine update applies it."}),l("p",{children:"In the existing policy editor, propose a Bridge login naming that vault item. Keep existing item titles and login names. This example does not grant access:"}),l("pre",{className:"overflow-x-auto rounded-md bg-muted p-2 text-xs",children:iT}),l(R,{variant:"secondary",onClick:async()=>{try{await navigator.clipboard.writeText(iT),r(!0)}catch{r(!1)}},children:n?"Copied example":"Copy Proton Mail policy example"}),m("p",{children:["After the protected login is approved, ask the assistant to sign in to its mailbox. It uses ",l("code",{children:"orbit-login fill bridge"})," with the existing owner confirmation. This page does not sign in or send mail."]})]})]}),m("details",{className:"rounded-md border p-3",children:[l("summary",{className:"cursor-pointer font-medium",children:"Gmail connection"}),m("div",{className:"mt-2 flex flex-col gap-2",children:[l("p",{children:"Gmail uses its existing protected connection, separate from the machine's Proton Mail setting. Ask the assistant to propose setup through the existing policy and approval controls. Keep any existing Gmail connection and saved vault item."}),l("p",{children:"Keep the Gmail address and Google app password in the protected vault. Google requires 2-Step Verification for app passwords. Do not put passwords in chat."})]})]}),e.orbitThread&&l(R,{variant:"secondary",onClick:()=>t.experimental_toHome(),children:"Open the assistant's conversation"})]})}function aT(){let{state:e,error:t}=vn();return t?l("p",{role:"alert",className:"text-destructive",children:t}):e?l(z3,{state:e}):l("p",{role:"status",children:"Loading mail setup\u2026"})}function lT(){let e=J(),[t,n]=_(""),[r,o]=_(""),[s,i]=_(""),[a,u]=_(!1),[c,d]=_("");return m("form",{className:"flex max-w-xl flex-col gap-3",onSubmit:async p=>{p.preventDefault(),u(!0);try{let f=await e.call("reviews.skip",{repository:t,number:Number(r),head:s});d(f.message)}catch(f){d(f instanceof Error?f.message:String(f))}finally{u(!1)}},children:[l("p",{className:"text-sm text-muted-foreground",children:"Optional. To set up automatic reviews, allow repositories in the GitHub ability in the policy, then list them above. Without that ability, no repositories are watched. Pausing keeps your list for later. Manual review records stay available below."}),l("h3",{className:"font-medium",children:"Record a manual review"}),l("p",{className:"text-sm",children:"Mark one pull request commit as already reviewed. This prevents another automatic review of that commit and settles its queued notice. A later commit can still be reviewed. It posts nothing on GitHub and cannot cancel a review that has started."}),m("label",{children:["Repository",l(le,{required:!0,value:t,onChange:p=>n(p.target.value),placeholder:"owner/repository"})]}),m("label",{children:["Pull request number",l(le,{required:!0,type:"number",min:"1",max:"999999999",value:r,onChange:p=>o(p.target.value)})]}),m("label",{children:["Full commit",l(le,{required:!0,pattern:"[a-f0-9]{40}",value:s,onChange:p=>i(p.target.value)})]}),l(R,{type:"submit",disabled:a,children:"Mark as manually reviewed"}),c&&l("p",{role:"status",className:"text-sm",children:c})]})}function cT(){let{rpc:e,state:t,error:n,refetch:r}=vn(),[o,s]=_(!1),[i,a]=_(null),[u,c]=_(null);return m("div",{className:"flex max-w-xl flex-col gap-3 text-sm",children:[l("p",{children:"Optional. Use Tailscale only for services on your private tailnet. Moonlet works without it."}),m("p",{children:["Create an OAuth client in your Tailscale admin console with Auth Keys write access and the existing ",l("code",{children:"tag:orbit"})," tag. Paste its client secret into the masked field above. Keep the secret out of chat."]}),l("p",{children:"Prepared machines use the existing enrollment or sync flow to join the tailnet. Saving here does not run that flow or confirm a connection."}),l("a",{className:"underline",href:"https://tailscale.com/docs/features/oauth-clients",target:"_blank",rel:"noreferrer",children:"Tailscale OAuth setup guide"}),l("p",{role:"status",children:t?t.secrets.tailscale?"Tailscale credential saved.":"No Tailscale credential saved. Add a client secret above when you need tailnet services.":"Loading Tailscale status\u2026"}),t?.secrets.tailscale&&m(he,{children:[l("p",{children:"Removing the stored credential does not disconnect devices already on the tailnet or revoke the OAuth client. Manage those separately in your Tailscale admin console."}),l(R,{variant:"secondary",disabled:o,onClick:async()=>{s(!0),c(null);try{let d=await e.call("welcome.secret",{which:"tailscale",value:null});a(d.line),r()}catch(d){c(d instanceof Error?d.message:String(d))}finally{s(!1)}},children:"Remove stored Tailscale credential"})]}),i&&l("p",{role:"status",children:i}),(n||u)&&l("p",{role:"alert",className:"text-destructive",children:u||n})]})}var Ar={section:"integrations",title:"Integrations",group:"connections",icon:"Link"};function uT(e){e.slots.settingsSection({id:"integration-tailscale",title:"Tailscale",experimental_placement:Ar,experimental_fields:["tailscaleSecret"],component:cT}),e.slots.settingsSection({id:"integration-mail",title:"Mail",experimental_placement:Ar,component:aT}),e.slots.settingsSection({id:"integration-library",title:"Library",experimental_placement:Ar,component:sT}),e.slots.settingsSection({id:"integration-calendar",title:"Calendar",experimental_placement:Ar,experimental_fields:["calendarLink"],component:aN}),e.slots.settingsSection({id:"integration-contacts",title:"Contacts",experimental_placement:Ar,component:nT}),e.slots.settingsSection({id:"integration-backup",title:"Backup",experimental_placement:Ar,component:iN}),e.slots.settingsSection({id:"integration-onepassword",title:"1Password",description:"Vault access for the station's keys. Your moonlet never sees the token.",experimental_placement:Ar,experimental_fields:["onePasswordToken"],component:()=>null}),e.slots.settingsSection({id:"integration-reviews",title:"GitHub reviews",description:"Optional connections. Set up only the services you want the assistant to use.",experimental_placement:Ar,experimental_fields:["autoReviewRepositories","autoReviewPaused"],component:lT})}var dT=["none","low","medium","high","xhigh","max","ultracode","ultra"];var pT=4;var fT={memoryEnabled:!0,disable1MContext:!1,chromeEnabled:!0,artifactsEnabled:!1,sandboxEnabled:!0},hT={memoryEnabled:!0},vW={"claude-code":{plugin:"provider-claude-code",conversation:{...fT,subagentsDisabled:!0,workflowsDisabled:!0},work:{...fT,subagentsDisabled:!1,workflowsDisabled:!1}},codex:{plugin:"provider-codex",conversation:{...hT,subagentsDisabled:!0},work:{...hT,subagentsDisabled:!1}}};var mT=["claude-code","codex"],K3=["claude-code"];function X3(e){return e==="xhigh"?"Extra high":`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function gT(e,t){let n=e?.providers.find(r=>r.provider===t.provider)?.models.find(r=>r.id===t.model)?.efforts??[];return n.length?n:dT.map(r=>({id:r,label:X3(r)}))}function xT(e,t,n){let r=e?.providers.find(o=>o.provider===t.provider)?.models.find(o=>o.id===t.model);return!r?.efforts.length||r.efforts.some(o=>o.id===n)?n:r.defaultEffort}var bT="claude-code";function ef(e,t){return`${e} ${t}`}function yT(e){let t=e.indexOf(" ");return{provider:e.slice(0,t),model:e.slice(t+1)}}function v_(e,t,n=!1){return t==="orbit"?K3.includes(e)?null:"the Moonlet conversation needs Claude Code: the station's managed settings, command filter and guide are Claude Code's":t==="station"?e===bT?null:e!=="codex"?"station work runs on Claude Code or Codex":n?null:"station work on Codex needs Codex installed on a station":mT.includes(e)?null:`Moonlet starts assistants only on ${mT.join(" or ")}`}function _T(e,t,n,r=!1){let o=e.providers.map(i=>{let a=v_(i.provider,t,r),u=t==="agents"&&i.provider!==bT&&!a?`${i.hosts.join(", ")}; your listed machines only`:i.hosts.join(", ");return{label:`${i.name} (on ${u})${a?`: ${a}`:""}`,disabled:a,options:i.models.map(c=>({value:ef(i.provider,c.id),label:`${c.name} (${c.id})${c.isDefault?`, ${i.name}'s default`:""}`}))}}),s=e.providers.some(i=>i.provider===n.provider&&i.models.some(a=>a.id===n.model));return n.model&&!s&&o.unshift({label:"Saved",disabled:null,options:[{value:ef(n.provider,n.model),label:`${n.model} on ${n.provider} (not offered now)`}]}),o}function B3(){let e=J(),[t,n]=_(null);return K(()=>{e.call("config.models",null).then(n,r=>n({providers:[],error:r instanceof Error?r.message:String(r)}))},[e]),t}var k_="h-9 min-w-0 max-w-full rounded-md border border-input bg-background px-2 text-sm";function U3({which:e,list:t,value:n,onChange:r,hasCodex:o,label:s}){let i=a=>r({...a,effort:xT(t,a,n.effort)});return t&&t.providers.some(a=>a.models.length>0)?l("select",{"aria-label":s,className:k_,value:ef(n.provider,n.model),onChange:a=>i(yT(a.target.value)),children:_T(t,e,n,o).map(a=>l("optgroup",{label:a.label,disabled:a.disabled!==null,children:a.options.map(u=>l("option",{value:u.value,children:u.label},u.value))},a.label))}):l(le,{"aria-label":s,value:n.model,disabled:!t,onChange:a=>r({...n,model:a.target.value})})}function H3({list:e,value:t,onChange:n,label:r}){let o=gT(e,t),s=o.some(i=>i.id===t.effort)?o:[{id:t.effort,label:`${t.effort} (not offered now)`},...o];return l("select",{"aria-label":r,className:k_,value:t.effort,onChange:i=>n(i.target.value),children:s.map(i=>l("option",{value:i.id,children:i.label},i.id))})}function Pl({which:e,list:t,value:n,onChange:r,hasCodex:o,label:s,children:i}){return m("div",{className:"flex flex-wrap items-center gap-2",children:[l(U3,{which:e,list:t,value:n,onChange:r,hasCodex:o,label:`${s} model`}),l(H3,{list:t,value:n,onChange:a=>r({...n,effort:a}),label:`${s} effort`}),i]})}function V3(e,t,n,r){let o=(e?.providers??[]).filter(s=>v_(s.provider,t,r)===null).flatMap(s=>s.models.map(i=>({provider:s.provider,model:i.id,effort:i.defaultEffort}))).filter(s=>!n.some(i=>i.provider===s.provider&&i.model===s.model));return o.find(s=>s.provider!==n[0]?.provider)??o[0]??null}function vT({which:e,list:t,main:n,backups:r,mode:o,onChange:s,onMode:i,hasCodex:a}){let u=V3(t,e,[n,...r],a);return m("div",{className:"flex flex-col gap-2",children:[r.map((c,d)=>l(Pl,{which:e,list:t,value:c,hasCodex:a,label:`Backup ${d+1}`,onChange:p=>s(r.map((f,h)=>h===d?p:f)),children:l(R,{variant:"ghost",size:"sm",onClick:()=>s(r.filter((p,f)=>f!==d)),children:"Remove"})},`${d}-${c.provider}-${c.model}`)),r.length<pT&&u&&l(R,{className:"self-start",variant:"outline",size:"sm",onClick:()=>s([...r,u]),children:"Add a backup model"}),r.length>0&&m("label",{className:"flex flex-col gap-1 text-xs text-muted-foreground",children:["New work starts on",m("select",{className:`${k_} text-foreground`,value:o,onChange:c=>i(c.target.value==="spread"?"spread":"in-order"),children:[l("option",{value:"in-order",children:"The first model with usage left, in order"}),l("option",{value:"spread",children:"The model whose provider has the most usage left"})]})]})]})}function tf({title:e,hint:t,children:n}){return m("section",{className:"flex flex-col gap-2","aria-label":e,children:[m("div",{children:[l("h3",{className:"font-medium",children:e}),l("p",{className:"text-xs text-muted-foreground",children:t})]}),n]})}function Z3({list:e,codexStations:t}){if(!e)return l("span",{className:"text-xs text-muted-foreground",children:"Loading the models your machines offer\u2026"});let n=e.providers.filter(r=>r.error);return e.providers.some(r=>r.models.length>0)?m("span",{className:"text-xs text-muted-foreground",children:["The models each provider offers on your connected stations and listed machines, with the efforts each model takes. Work on a station runs on Claude Code, or on Codex",t.length?` (on ${t.join(", ")})`:" once a station has it installed",".",n.length>0&&` Not listed: ${n.map(r=>`${r.name} (${r.error})`).join("; ")}.`]}):m("span",{className:"text-xs text-muted-foreground",children:["Your moonlet couldn't list its models",e.error?` (${e.error})`:n.length?` (${n.map(r=>`${r.name}: ${r.error}`).join("; ")})`:"",". Type a model id, like claude-sonnet-5-5."]})}var Il=(e,t)=>({provider:e[`${t}_provider`],model:e[t],effort:e[`${t}_effort`]}),w_=(e,t,n)=>({...e,[t]:n.model,[`${t}_provider`]:n.provider,[`${t}_effort`]:n.effort});function wT(){let{rpc:e,state:t,error:n,refetch:r}=Is(),o=B3(),[s,i]=_(null),[a,u]=_(null),[c,d]=_(null);if(n)return l("p",{className:"text-sm text-destructive",children:n});if(!t)return l("p",{className:"text-sm text-muted-foreground",children:"Loading\u2026"});let p=s??t.prefs.models,f=t.codexStations.length>0,h=w=>{u(C=>C??t.prefsBase),i(w)},g=()=>{i(null),u(null)},x=s!==null&&JSON.stringify(s)!==JSON.stringify(t.prefs.models),b=()=>{e.call("config.savePrefs",{prefs:{...t.prefs,models:p},base:a??t.prefsBase}).then(()=>{g(),d("Saved. New work starts on these, and the conversation switches now."),r()},w=>d(w instanceof Error?w.message:String(w)))},v=$s(t.prefs.identity);return m("div",{className:"flex flex-col gap-6 text-sm",children:[m("p",{className:"text-xs text-muted-foreground",children:["Every model ",v," uses, and how hard each one thinks. New work starts on these; work already running keeps the model it started on."]}),l(tf,{title:`${v.charAt(0).toUpperCase()}${v.slice(1)}'s conversation`,hint:"Its main chat and background conversation. They run on Claude Code and switch as soon as you save.",children:l(Pl,{which:"orbit",list:o,value:Il(p,"orbit"),hasCodex:f,label:"Conversation",onChange:w=>h(w_(p,"orbit",w))})}),l(tf,{title:"Reading your messages",hint:`Before ${v} answers, this reads each of your messages and decides where it goes: ${v} answers it, it starts as work of its own beside the chat, or it goes to work already under way. It runs on Claude Code.`,children:l(Pl,{which:"orbit",list:o,value:{provider:"claude-code",model:p.router,effort:p.router_effort},hasCodex:f,label:"Reading",onChange:w=>h({...p,router:w.model,router_effort:w.effort})})}),m(tf,{title:"Work on your stations",hint:"Every assistant and chat it starts on a station, including the work it does for you.",children:[l(Pl,{which:"station",list:o,value:Il(p,"station"),hasCodex:f,label:"Station work",onChange:w=>h(w_(p,"station",w))}),l(vT,{which:"station",list:o,hasCodex:f,main:Il(p,"station"),backups:p.station_backups,mode:p.station_mode,onChange:w=>h({...p,station_backups:w}),onMode:w=>h({...p,station_mode:w})})]}),m(tf,{title:"Assistants and chats on your listed machines",hint:"Work it starts on a machine of yours that its policy lists.",children:[l(Pl,{which:"agents",list:o,value:Il(p,"agents"),hasCodex:f,label:"Listed machines",onChange:w=>h(w_(p,"agents",w))}),l(vT,{which:"agents",list:o,hasCodex:f,main:Il(p,"agents"),backups:p.agents_backups,mode:p.agents_mode,onChange:w=>h({...p,agents_backups:w}),onMode:w=>h({...p,agents_mode:w})})]}),m("div",{className:"flex flex-col gap-1",children:[l("span",{className:"text-xs text-muted-foreground",children:"Models on one provider share its usage. Your moonlet reads each provider's usage on the machine at most once a minute and marks a provider as full the moment work stops at its limit, until it resets. Work already running stays on its model; new work starts on the next one. Spread stays on one provider until another has 10 points more usage left, so new work keeps reusing what that provider has cached."}),l(Z3,{list:o,codexStations:t.codexStations})]}),m("div",{className:"flex flex-wrap items-center gap-2",children:[l(R,{size:"sm",disabled:!x,onClick:b,children:"Save"}),l(R,{size:"sm",variant:"ghost",disabled:!x,onClick:g,children:"Revert"}),l(zE,{at:t.prefsUpdatedAt})]}),c&&l("p",{className:"text-xs",children:c})]})}var jn=6e4,W3=["release","drain","install","activate","confirm"],j3=re.enum(W3),BW={release:{label:"Get the release ready",usualMs:10*jn},drain:{label:"Wait for the station's work to finish",usualMs:15*jn},install:{label:"Install programs",usualMs:10*jn},activate:{label:"Turn the pieces back on",usualMs:5*jn},confirm:{label:"Confirm the installed version",usualMs:2*jn}},UW=10*jn;var HW=2*jn,VW=3*jn;var Q3=500,G3=re.enum(["running","slow","stuck","interrupted","failed","succeeded"]),Y3=re.enum(["done","running","failed","stopped","waiting"]),ZW=re.object({station:re.string(),attempt:re.string().nullable(),revision:re.string().nullable(),from:re.string().nullable(),startedAt:re.number().int(),endedAt:re.number().int().nullable(),lastActivityAt:re.number().int(),awaySince:re.number().int().nullable(),state:G3,headline:re.string(),reasons:re.array(re.string()),steps:re.array(re.object({id:j3,label:re.string(),state:Y3,startedAt:re.number().int().nullable(),endedAt:re.number().int().nullable(),usualMs:re.number().int(),usualFrom:re.number().int(),detail:re.string().nullable()}).strict())}).strict(),WW=re.object({at:re.number().int(),text:re.string().max(Q3)}).strict();function An(e){let t=Math.floor(Math.max(0,e)/jn);if(t<1)return"under a minute";if(t<60)return`${t} min`;let n=Math.floor(t/60),r=t%60;return r?`${n} h ${r} min`:`${n} h`}var kT=e=>e?e.slice(0,12):null;var ST=e=>e!==null&&(e.state==="running"||e.state==="slow"||e.state==="stuck"),q3={done:"\u2713",running:"\u2026",failed:"\u2717",stopped:"\u25A0",waiting:"\xB7"};function ET(e,t,n){if(!e)return[`Update on ${t}: none recorded yet.`];let r=e.revision?` to ${kT(e.revision)}${e.from?` from ${kT(e.from)}`:""}`:"",o=e.endedAt===null?`started ${An(n-e.startedAt)} ago`:`ended ${An(n-e.endedAt)} ago, took ${An(e.endedAt-e.startedAt)}`,s=[`Update on ${t}${r}: ${e.headline.toLowerCase()}; ${o}.`];for(let i of e.reasons)s.push(` ${i}`);for(let i of e.steps){let a=i.startedAt===null?"":i.state==="running"||i.state==="stopped"?` (${An((i.state==="stopped"?e.lastActivityAt:n)-i.startedAt)} so far)`:i.endedAt!==null?` (${An(i.endedAt-i.startedAt)})`:"";s.push(` ${q3[i.state]} ${i.label}${a}${i.detail?` \u2014 ${i.detail}`:""}`)}return s}var _i=e=>new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),J3=e=>new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit",second:"2-digit"}),NT=e=>e?e.slice(0,7):null,eF={running:{icon:"Spinner",tone:"bg-muted text-muted-foreground",label:"Updating"},slow:{icon:"Clock",tone:"bg-warning/15 text-warning-text",label:"Taking longer than usual"},stuck:{icon:"AlertTriangle",tone:"bg-warning/15 text-warning-text",label:"Looks stuck"},interrupted:{icon:"AlertTriangle",tone:"bg-warning/15 text-warning-text",label:"Interrupted"},failed:{icon:"CircleX",tone:"bg-surface-destructive text-destructive-text",label:"Update failed"},succeeded:{icon:"Check",tone:"bg-muted text-muted-foreground",label:"Up to date"}},tF={done:{name:"CircleCheck",tone:"text-success",label:"Done"},running:{name:"Spinner",tone:"text-foreground",label:"In progress"},failed:{name:"CircleX",tone:"text-destructive-text",label:"Failed"},stopped:{name:"CircleX",tone:"text-warning-text",label:"Stopped"},waiting:{name:"Circle",tone:"text-muted-foreground",label:"Not started"}};function nF({state:e}){let{icon:t,tone:n,label:r}=eF[e];return m("span",{className:V("inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-md px-2 py-1 text-xs",n),children:[l(pe,{name:t,"aria-hidden":!0,className:"size-3.5"}),r]})}function rF(e,t){let n=NT(e.revision),r=e.endedAt===null&&e.state!=="interrupted",o=n?`${r?"Updating to":"To"} ${n}${e.from?` from ${NT(e.from)}`:""}`:null,s=e.endedAt!==null?`ended ${_i(e.endedAt)} \xB7 took ${An(e.endedAt-e.startedAt)}`:r?`started ${_i(e.startedAt)} \xB7 ${An(t-e.startedAt)}`:`started ${_i(e.startedAt)} \xB7 last heard from ${_i(e.lastActivityAt)}`;return[o,s].filter(Boolean).join(" \xB7 ")}function oF({update:e,now:t}){let n=e.state==="slow"||e.state==="stuck";return l("ol",{className:"flex flex-col","aria-label":`Update steps on ${e.station}`,children:e.steps.map(r=>{let o=tF[r.state],s=r.state==="running"?t:r.state==="stopped"?e.lastActivityAt:r.endedAt,i=r.startedAt===null?null:`${_i(r.startedAt)}${s===null?"":` \xB7 ${An(s-r.startedAt)}`}`,u=[r.state==="running"&&n?`Usually under ${An(r.usualMs)}`:null,r.detail].filter(Boolean).join(" \xB7 ");return m("li",{className:"grid grid-cols-[1rem_minmax(0,1fr)_auto] items-baseline gap-x-2.5 py-1.5",children:[l(pe,{name:o.name,"aria-label":o.label,className:V("size-4 self-center",o.tone)}),l("span",{className:V(r.state==="waiting"&&"text-muted-foreground",r.state==="running"&&"font-medium"),children:r.label}),l("span",{className:V("whitespace-nowrap text-xs text-muted-foreground",r.state==="running"&&n&&"text-warning-text"),children:i}),u&&l("span",{className:"col-start-2 col-end-4 text-xs text-muted-foreground",children:u})]},r.id)})})}function sF({lines:e}){return e===null?l("p",{className:"mt-2 text-xs text-muted-foreground",children:"Loading\u2026"}):e.length?l("pre",{className:"mt-2 max-h-72 overflow-auto whitespace-pre rounded-md border bg-muted/40 p-3 font-mono text-xs text-muted-foreground","aria-label":"Installer output",children:e.map(t=>`${J3(t.at)} ${t.text}`).join(`
220
- `)}):l("p",{className:"mt-2 text-xs text-muted-foreground",children:"No output from the installer yet."})}function iF(e,t,n,r){let o=ET(t,e,r);return n?.length&&o.push("","Installer output:",...n.map(s=>`${new Date(s.at).toISOString()} ${s.text}`)),o.join(`
221
- `)}function AT({name:e,summary:t,update:n,now:r,output:o,outputOpen:s,onOutputOpen:i,loadOutput:a}){let[u,c]=_("idle"),d=n===null||n.state==="succeeded",[p,f]=_(!1);if(d&&!p)return m("li",{className:"flex items-start justify-between gap-3 py-3",children:[m("div",{className:"flex min-w-0 flex-col gap-0.5",children:[l("span",{className:"font-medium",children:e}),l("span",{className:"text-xs text-muted-foreground",children:t})]}),n&&l("button",{type:"button",className:"shrink-0 text-xs text-muted-foreground hover:text-foreground",onClick:()=>f(!0),children:"Last update"})]});if(!n)return null;let h=o?.at(-1);return m("li",{className:"flex flex-col gap-3 py-3",children:[m("div",{className:"flex items-start justify-between gap-3",children:[m("div",{className:"flex min-w-0 flex-col gap-0.5",children:[l("span",{className:"font-medium",children:e}),l("span",{className:"text-xs text-muted-foreground",children:rF(n,r)})]}),l(nF,{state:n.state})]}),n.reasons.length>0&&l("div",{role:"status",className:V("flex flex-col gap-1 rounded-md px-3 py-2 text-xs",n.state==="failed"?"bg-surface-destructive text-destructive-text":n.state==="running"?"bg-muted text-muted-foreground":"bg-warning/15 text-warning-text"),children:n.reasons.map(g=>l("p",{children:g},g))}),l(oF,{update:n,now:r}),m("div",{className:"border-t pt-2",children:[m("div",{className:"flex items-center justify-between gap-3",children:[m("button",{type:"button","aria-expanded":s,className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>i(!s),children:[l(pe,{name:s?"ChevronDown":"ChevronRight","aria-hidden":!0,className:"size-3.5"}),"Installer output",h?` \xB7 last line ${_i(h.at)}`:""]}),m("div",{className:"flex items-center gap-1",children:[d&&l(R,{size:"sm",variant:"ghost",onClick:()=>f(!1),children:"Hide"}),m(R,{size:"sm",variant:"ghost",onClick:()=>{a().catch(()=>o).then(g=>Z_({text:iF(e,n,g,r)})).then(g=>{c(g?"copied":"failed"),setTimeout(()=>c("idle"),2e3)})},children:[l(pe,{name:"Copy","aria-hidden":!0}),u==="copied"?"Copied":u==="failed"?"Couldn't copy":"Copy details"]})]})]}),s&&l(sF,{lines:o})]})]})}var CT=e=>e instanceof Error?e.message:String(e),aF=15e3,TT=(e,t,n)=>e[t]??(n!==null&&(n.state==="stuck"||n.state==="failed"||n.state==="interrupted"));function RT(){let e=J(),[t,n]=_(null),[r,o]=_(!1),[s,i]=_(null),[a,u]=_(()=>Date.now()),[c,d]=_({}),[p,f]=_({}),h=Y(c);h.current=c;let g=q(async y=>{let{lines:T}=await e.call("delivery.output",{station:y});return f(N=>({...N,[y]:T})),T},[e]),x=q(y=>{g(y).catch(()=>f(T=>({...T,[y]:[]})))},[g]),b=q(y=>{n(y),u(Date.now());for(let T of y.stations)TT(h.current,T.name,T.update)&&x(T.name)},[x]),v=q(()=>{e.call("delivery.stations",null).then(y=>{b(y),i(null)},y=>i(CT(y)))},[e,b]);K(v,[v]),ke("delivery",v);let w=t?.stations.some(y=>ST(y.update))??!1;K(()=>{if(!w)return;let y=setInterval(v,aF);return()=>clearInterval(y)},[w,v]);let C=t?.installing===!0;return m("div",{className:"flex flex-col gap-3 text-sm",children:[t===null?!s&&l("p",{className:"text-muted-foreground",children:"Loading\u2026"}):t.stations.length===0?l("p",{className:"text-muted-foreground",children:"There's no station to update."}):l("ul",{className:"divide-y","aria-label":"Stations",children:t.stations.map(y=>l(AT,{name:y.name,summary:y.summary,update:y.update,now:a,output:p[y.name]??null,outputOpen:TT(c,y.name,y.update),onOutputOpen:T=>{d(N=>({...N,[y.name]:T})),T&&x(y.name)},loadOutput:()=>g(y.name)},y.name))}),l("div",{children:l(R,{size:"sm",disabled:t===null||r||C,onClick:async()=>{o(!0),i(null);try{b(await e.call("delivery.now",null))}catch(y){i(CT(y))}finally{o(!1)}},children:C?"Updating\u2026":r?"Checking\u2026":"Update now"})}),s&&l("p",{role:"alert",className:"text-destructive",children:s})]})}var lF="Your moonlet";function Ol(e,t,n){return{section:e,title:t,group:lF,icon:n}}function $T(e){e.slots.settingsSection({id:"models",experimental_placement:{section:"models",title:"Models",icon:"AiBrain01"},component:wT}),e.slots.settingsSection({id:"orbit",experimental_placement:Ol("assistant","Profile","UserRound"),experimental_useGroupTitle:Ia,component:HE}),e.slots.settingsSection({id:"personality",experimental_placement:Ol("assistant-personality","Personality","MessageSquare"),experimental_useGroupTitle:Ia,component:jE}),e.slots.settingsSection({id:"rhythm",experimental_placement:Ol("assistant-rhythm","Rhythm","Clock"),experimental_useGroupTitle:Ia,component:eN}),e.slots.settingsSection({id:"conversation",title:"Your conversation",experimental_placement:Ol("assistant-rhythm","Rhythm","Clock"),experimental_fields:["backgroundThread","mainChatCompactionPercent"],component:()=>null}),e.slots.settingsSection({id:"history",experimental_placement:Ol("assistant-history","History","ClockArrowDown"),experimental_useGroupTitle:Ia,component:nN}),e.slots.settingsSection({id:"event-service",title:"Background work",description:"The station's event service, which runs mail, notices and routine work.",experimental_placement:{section:"machines",title:"Machines"},component:rN}),e.slots.settingsSection({id:"set-up-again",title:"Your moonlet's setup",experimental_placement:{section:"general",title:"General"},component:oN}),e.slots.settingsSection({id:"station-sign-in",title:"Claude Code on stations",experimental_placement:{section:"providers",title:"Providers"},experimental_fields:["claudeToken"],component:()=>null}),e.slots.settingsSection({id:"station-delivery",title:"Station programs",description:"The broker, guard, launcher and check runner on each station follow the app's commit. Moonlet checks when the app starts, when a station connects and every 10 minutes, and drains the station's work before it installs. While a station updates, this page shows each step, the installer's output, and why it looks stuck if it does. Update now does it at once, even with automatic updates off.",experimental_placement:{section:"updates",title:"Updates"},component:RT}),uT(e)}function IT(){return Q_(wh)}function PT(e){let t=os();return t===void 0?null:t===null?l("p",{className:"p-3 text-sm text-muted-foreground",children:"There's no conversation with your moonlet yet, so there are no notifications to show."}):l(Vl,{name:wh,params:{threadId:t}})}function OT(){return null}var Gj=V_(e=>{e.slots.pendingInteraction({id:"approval",component:tc}),e.slots.pendingInteraction({id:"policy-proposal",component:rc}),e.slots.experimental_timelineRenderer({kind:"orbit/policy-proposal",component:iv}),e.slots.pendingInteraction({id:"station-manager",component:nc}),e.slots.pendingInteraction({id:"owner-changes",component:sc}),e.slots.experimental_tab({id:"desktop",title:"Desktop",icon:"Monitor",context:{kind:"thread"},availability:"action",component:Mh,layout:"flush"}),e.slots.experimental_tab({id:Jc,title:"Artifacts",icon:"FileText",context:{kind:"thread"},availability:"action",component:_1,layout:"flush"}),e.slots.messageDirective({id:Uh,component:V1}),e.slots.navPanel({id:"artifacts",title:"Artifacts",icon:"FileText",path:"artifacts",component:TE,experimental_sidebar:yE,headerContent:CE}),e.slots.navPanel({id:Aa,title:"Activity",icon:"Activity",path:Aa,component:rE,experimental_sidebar:oE}),e.slots.navPanel({id:"orbit",title:"Moonlet",icon:"Orbit",path:"orbit",component:Q1,experimental_useNavigationVisible:()=>!1});for(let n of qE)e.slots.experimental_firstRunStep({id:n.id,title:n.title,description:n.lead,component:JE[n.id]});e.slots.navPanel({id:At,title:"Chat",icon:"MessageSquare",path:At,component:Zk}),e.slots.navPanel({id:fu,title:"Tasks",icon:"ListTodo",path:fu,component:OE,experimental_sidebar:LE}),e.slots.experimental_home({id:"home",title:"Your moonlet chat",description:"One conversation with your moonlet, with threads.",panelPath:At,conversations:"hidden"}),e.slots.experimental_threadList({id:"threads",title:"Moonlet",description:"Your moonlet\u2019s threads live in its chat, so the sidebar shows only where to go.",component:OT});let t=()=>Yo()!==null;e.commands.register({id:"thread-full-screen",title:"Thread full screen on or off",defaultShortcut:{key:".",mod:!0},isAvailable:t,run:()=>Yo()?.toggleFull()}),e.commands.register({id:"threads-list",title:"Show or hide the threads list",defaultShortcut:{key:"\\",mod:!0,shift:!0},isAvailable:t,run:()=>Yo()?.toggleList()}),e.commands.register({id:"thread-next",title:"Next thread",defaultShortcut:{key:"ArrowDown",alt:!0},isAvailable:t,run:()=>Yo()?.cycle(1)}),e.commands.register({id:"thread-previous",title:"Previous thread",defaultShortcut:{key:"ArrowUp",alt:!0},isAvailable:t,run:()=>Yo()?.cycle(-1)}),e.slots.experimental_tab({id:_h,title:"Desktop",icon:"Monitor",layout:"flush",context:{kind:"nav-panel",panelId:At},availability:"action",component:Wk}),e.slots.experimental_tab({id:qc,title:"Artifacts",icon:"FileText",layout:"flush",context:{kind:"nav-panel",panelId:At},availability:"action",component:v1}),e.slots.experimental_tab({id:"home-tasks",title:"Tasks",icon:"ListTodo",context:{kind:"nav-panel",panelId:At},availability:"action",component:ME}),e.slots.experimental_tab({id:vh,title:"Notifications",icon:"Bell",context:{kind:"nav-panel",panelId:At},availability:"action",useVisible:IT,component:PT}),e.composer.customize({id:"pending-work",scopes:["thread"],banners:[{id:"pending-work",chrome:"bare",component:j1}]}),$T(e),e.slots.experimental_appOverlay({id:"chat-avatar",component:jc})});export{Gj as default};
219
+ `;function U3({state:e}){let t=Ie(),[n,r]=v(!1);return m("section",{className:"flex max-w-xl flex-col gap-3 text-sm",children:[l("p",{children:"Optional. Set up the assistant's own mailbox, separate from your account. The assistant reads and sends from that mailbox only through its existing mail controls."}),l("p",{children:"Mail runs on a prepared machine. Settings \u2192 Machines keeps all saved machines; the list below shows only machines enabled for assistant work."}),e.stations.length===0?l("p",{role:"status",children:"No machine enabled for assistant work yet. Choose a prepared machine in Settings \u2192 Machines, then ask the assistant to set up mail on it."}):l("ul",{className:"list-disc pl-5",children:e.stations.map(o=>m("li",{children:[o.name,":"," ",o.mail==="none"?"mail disabled in record":o.mail==="proton"?"Proton Mail enabled in record":"mail enabled in record",o.connected?"":" (machine offline)"]},o.id))}),l("p",{children:"The machine mail setting enables Proton Mail and Bridge. New machine records start with mail off; existing and imported machines keep their settings. Saving a selection does not install software or sign in. The normal approved machine update applies it."}),m("p",{children:["Protected vault access:"," ",e.secrets.onepassword?"service-account key saved.":"not set up. Add the 1Password key under 1Password on this page, or in first run's Machine sign-ins step."," ","Mailbox credentials stay in the configured vault and are read by protected tools."]}),m("p",{children:["Protected mailbox sign-in entries: ",e.mailLogins.length?e.mailLogins.join(", "):"none configured",". Saved entries and machine configuration do not confirm a successful sign-in or mail connection."]}),m("details",{className:"rounded-md border p-3",open:e.stations.some(o=>o.mail==="proton"),children:[l("summary",{className:"cursor-pointer font-medium",children:"Set up Proton Mail"}),m("div",{className:"mt-2 flex flex-col gap-2",children:[l("p",{children:"Store the assistant's Proton username and password in its vault item, including its mailbox password if used. Proton Mail Bridge requires a paid Proton plan."}),l("p",{children:"Ask the assistant to prepare the machine and propose enabling mail. The normal approved machine update applies it."}),l("p",{children:"In the existing policy editor, propose a Bridge login naming that vault item. Keep existing item titles and login names. This example does not grant access:"}),l("pre",{className:"overflow-x-auto rounded-md bg-muted p-2 text-xs",children:uT}),l(R,{variant:"secondary",onClick:async()=>{try{await navigator.clipboard.writeText(uT),r(!0)}catch{r(!1)}},children:n?"Copied example":"Copy Proton Mail policy example"}),m("p",{children:["After the protected login is approved, ask the assistant to sign in to its mailbox. It uses ",l("code",{children:"orbit-login fill bridge"})," with the existing owner confirmation. This page does not sign in or send mail."]})]})]}),m("details",{className:"rounded-md border p-3",children:[l("summary",{className:"cursor-pointer font-medium",children:"Gmail connection"}),m("div",{className:"mt-2 flex flex-col gap-2",children:[l("p",{children:"Gmail uses its existing protected connection, separate from the machine's Proton Mail setting. Ask the assistant to propose setup through the existing policy and approval controls. Keep any existing Gmail connection and saved vault item."}),l("p",{children:"Keep the Gmail address and Google app password in the protected vault. Google requires 2-Step Verification for app passwords. Do not put passwords in chat."})]})]}),e.orbitThread&&l(R,{variant:"secondary",onClick:()=>t.experimental_toHome(),children:"Open the assistant's conversation"})]})}function dT(){let{state:e,error:t}=wn();return t?l("p",{role:"alert",className:"text-destructive",children:t}):e?l(U3,{state:e}):l("p",{role:"status",children:"Loading mail setup\u2026"})}function pT(){let e=J(),[t,n]=v(""),[r,o]=v(""),[s,i]=v(""),[a,u]=v(!1),[c,d]=v("");return m("form",{className:"flex max-w-xl flex-col gap-3",onSubmit:async p=>{p.preventDefault(),u(!0);try{let f=await e.call("reviews.skip",{repository:t,number:Number(r),head:s});d(f.message)}catch(f){d(f instanceof Error?f.message:String(f))}finally{u(!1)}},children:[l("p",{className:"text-sm text-muted-foreground",children:"Optional. To set up automatic reviews, allow repositories in the GitHub ability in the policy, then list them above. Without that ability, no repositories are watched. Pausing keeps your list for later. Manual review records stay available below."}),l("h3",{className:"font-medium",children:"Record a manual review"}),l("p",{className:"text-sm",children:"Mark one pull request commit as already reviewed. This prevents another automatic review of that commit and settles its queued notice. A later commit can still be reviewed. It posts nothing on GitHub and cannot cancel a review that has started."}),m("label",{children:["Repository",l(le,{required:!0,value:t,onChange:p=>n(p.target.value),placeholder:"owner/repository"})]}),m("label",{children:["Pull request number",l(le,{required:!0,type:"number",min:"1",max:"999999999",value:r,onChange:p=>o(p.target.value)})]}),m("label",{children:["Full commit",l(le,{required:!0,pattern:"[a-f0-9]{40}",value:s,onChange:p=>i(p.target.value)})]}),l(R,{type:"submit",disabled:a,children:"Mark as manually reviewed"}),c&&l("p",{role:"status",className:"text-sm",children:c})]})}function fT(){let{rpc:e,state:t,error:n,refetch:r}=wn(),[o,s]=v(!1),[i,a]=v(null),[u,c]=v(null);return m("div",{className:"flex max-w-xl flex-col gap-3 text-sm",children:[l("p",{children:"Optional. Use Tailscale only for services on your private tailnet. Moonlet works without it."}),m("p",{children:["Create an OAuth client in your Tailscale admin console with Auth Keys write access and the existing ",l("code",{children:"tag:orbit"})," tag. Paste its client secret into the masked field above. Keep the secret out of chat."]}),l("p",{children:"Prepared machines use the existing enrollment or sync flow to join the tailnet. Saving here does not run that flow or confirm a connection."}),l("a",{className:"underline",href:"https://tailscale.com/docs/features/oauth-clients",target:"_blank",rel:"noreferrer",children:"Tailscale OAuth setup guide"}),l("p",{role:"status",children:t?t.secrets.tailscale?"Tailscale credential saved.":"No Tailscale credential saved. Add a client secret above when you need tailnet services.":"Loading Tailscale status\u2026"}),t?.secrets.tailscale&&m(he,{children:[l("p",{children:"Removing the stored credential does not disconnect devices already on the tailnet or revoke the OAuth client. Manage those separately in your Tailscale admin console."}),l(R,{variant:"secondary",disabled:o,onClick:async()=>{s(!0),c(null);try{let d=await e.call("welcome.secret",{which:"tailscale",value:null});a(d.line),r()}catch(d){c(d instanceof Error?d.message:String(d))}finally{s(!1)}},children:"Remove stored Tailscale credential"})]}),i&&l("p",{role:"status",children:i}),(n||u)&&l("p",{role:"alert",className:"text-destructive",children:u||n})]})}var Cr={section:"integrations",title:"Integrations",group:"connections",icon:"Link"};function hT(e){e.slots.settingsSection({id:"integration-tailscale",title:"Tailscale",experimental_placement:Cr,experimental_fields:["tailscaleSecret"],component:fT}),e.slots.settingsSection({id:"integration-mail",title:"Mail",experimental_placement:Cr,component:dT}),e.slots.settingsSection({id:"integration-library",title:"Library",experimental_placement:Cr,component:cT}),e.slots.settingsSection({id:"integration-calendar",title:"Calendar",experimental_placement:Cr,experimental_fields:["calendarLink"],component:dN}),e.slots.settingsSection({id:"integration-contacts",title:"Contacts",experimental_placement:Cr,component:iT}),e.slots.settingsSection({id:"integration-backup",title:"Backup",experimental_placement:Cr,component:uN}),e.slots.settingsSection({id:"integration-onepassword",title:"1Password",description:"Vault access for the station's keys. Your moonlet never sees the token.",experimental_placement:Cr,experimental_fields:["onePasswordToken"],component:()=>null}),e.slots.settingsSection({id:"integration-reviews",title:"GitHub reviews",description:"Optional connections. Set up only the services you want the assistant to use.",experimental_placement:Cr,experimental_fields:["autoReviewRepositories","autoReviewPaused"],component:pT})}var mT=["none","low","medium","high","xhigh","max","ultracode","ultra"];var gT=4;var xT={memoryEnabled:!0,disable1MContext:!1,chromeEnabled:!0,artifactsEnabled:!1,sandboxEnabled:!0},bT={memoryEnabled:!0},TW={"claude-code":{plugin:"provider-claude-code",conversation:{...xT,subagentsDisabled:!0,workflowsDisabled:!0},work:{...xT,subagentsDisabled:!1,workflowsDisabled:!1}},codex:{plugin:"provider-codex",conversation:{...bT,subagentsDisabled:!0},work:{...bT,subagentsDisabled:!1}}};var yT=["claude-code","codex"],H3=["claude-code"];function V3(e){return e==="xhigh"?"Extra high":`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function _T(e,t){let n=e?.providers.find(r=>r.provider===t.provider)?.models.find(r=>r.id===t.model)?.efforts??[];return n.length?n:mT.map(r=>({id:r,label:V3(r)}))}function vT(e,t,n){let r=e?.providers.find(o=>o.provider===t.provider)?.models.find(o=>o.id===t.model);return!r?.efforts.length||r.efforts.some(o=>o.id===n)?n:r.defaultEffort}var wT="claude-code";function nf(e,t){return`${e} ${t}`}function kT(e){let t=e.indexOf(" ");return{provider:e.slice(0,t),model:e.slice(t+1)}}function k_(e,t,n=!1){return t==="orbit"?H3.includes(e)?null:"the Moonlet conversation needs Claude Code: the station's managed settings, command filter and guide are Claude Code's":t==="station"?e===wT?null:e!=="codex"?"station work runs on Claude Code or Codex":n?null:"station work on Codex needs Codex installed on a station":yT.includes(e)?null:`Moonlet starts assistants only on ${yT.join(" or ")}`}function ST(e,t,n,r=!1){let o=e.providers.map(i=>{let a=k_(i.provider,t,r),u=t==="agents"&&i.provider!==wT&&!a?`${i.hosts.join(", ")}; your listed machines only`:i.hosts.join(", ");return{label:`${i.name} (on ${u})${a?`: ${a}`:""}`,disabled:a,options:i.models.map(c=>({value:nf(i.provider,c.id),label:`${c.name} (${c.id})${c.isDefault?`, ${i.name}'s default`:""}`}))}}),s=e.providers.some(i=>i.provider===n.provider&&i.models.some(a=>a.id===n.model));return n.model&&!s&&o.unshift({label:"Saved",disabled:null,options:[{value:nf(n.provider,n.model),label:`${n.model} on ${n.provider} (not offered now)`}]}),o}function Z3(){let e=J(),[t,n]=v(null);return M(()=>{e.call("config.models",null).then(n,r=>n({providers:[],error:r instanceof Error?r.message:String(r)}))},[e]),t}var E_="h-9 min-w-0 max-w-full rounded-md border border-input bg-background px-2 text-sm";function W3({which:e,list:t,value:n,onChange:r,hasCodex:o,label:s}){let i=a=>r({...a,effort:vT(t,a,n.effort)});return t&&t.providers.some(a=>a.models.length>0)?l("select",{"aria-label":s,className:E_,value:nf(n.provider,n.model),onChange:a=>i(kT(a.target.value)),children:ST(t,e,n,o).map(a=>l("optgroup",{label:a.label,disabled:a.disabled!==null,children:a.options.map(u=>l("option",{value:u.value,children:u.label},u.value))},a.label))}):l(le,{"aria-label":s,value:n.model,disabled:!t,onChange:a=>r({...n,model:a.target.value})})}function j3({list:e,value:t,onChange:n,label:r}){let o=_T(e,t),s=o.some(i=>i.id===t.effort)?o:[{id:t.effort,label:`${t.effort} (not offered now)`},...o];return l("select",{"aria-label":r,className:E_,value:t.effort,onChange:i=>n(i.target.value),children:s.map(i=>l("option",{value:i.id,children:i.label},i.id))})}function Ol({which:e,list:t,value:n,onChange:r,hasCodex:o,label:s,children:i}){return m("div",{className:"flex flex-wrap items-center gap-2",children:[l(W3,{which:e,list:t,value:n,onChange:r,hasCodex:o,label:`${s} model`}),l(j3,{list:t,value:n,onChange:a=>r({...n,effort:a}),label:`${s} effort`}),i]})}function Q3(e,t,n,r){let o=(e?.providers??[]).filter(s=>k_(s.provider,t,r)===null).flatMap(s=>s.models.map(i=>({provider:s.provider,model:i.id,effort:i.defaultEffort}))).filter(s=>!n.some(i=>i.provider===s.provider&&i.model===s.model));return o.find(s=>s.provider!==n[0]?.provider)??o[0]??null}function ET({which:e,list:t,main:n,backups:r,mode:o,onChange:s,onMode:i,hasCodex:a}){let u=Q3(t,e,[n,...r],a);return m("div",{className:"flex flex-col gap-2",children:[r.map((c,d)=>l(Ol,{which:e,list:t,value:c,hasCodex:a,label:`Backup ${d+1}`,onChange:p=>s(r.map((f,h)=>h===d?p:f)),children:l(R,{variant:"ghost",size:"sm",onClick:()=>s(r.filter((p,f)=>f!==d)),children:"Remove"})},`${d}-${c.provider}-${c.model}`)),r.length<gT&&u&&l(R,{className:"self-start",variant:"outline",size:"sm",onClick:()=>s([...r,u]),children:"Add a backup model"}),r.length>0&&m("label",{className:"flex flex-col gap-1 text-xs text-muted-foreground",children:["New work starts on",m("select",{className:`${E_} text-foreground`,value:o,onChange:c=>i(c.target.value==="spread"?"spread":"in-order"),children:[l("option",{value:"in-order",children:"The first model with usage left, in order"}),l("option",{value:"spread",children:"The model whose provider has the most usage left"})]})]})]})}function rf({title:e,hint:t,children:n}){return m("section",{className:"flex flex-col gap-2","aria-label":e,children:[m("div",{children:[l("h3",{className:"font-medium",children:e}),l("p",{className:"text-xs text-muted-foreground",children:t})]}),n]})}function G3({list:e,codexStations:t}){if(!e)return l("span",{className:"text-xs text-muted-foreground",children:"Loading the models your machines offer\u2026"});let n=e.providers.filter(r=>r.error);return e.providers.some(r=>r.models.length>0)?m("span",{className:"text-xs text-muted-foreground",children:["The models each provider offers on your connected stations and listed machines, with the efforts each model takes. Work on a station runs on Claude Code, or on Codex",t.length?` (on ${t.join(", ")})`:" once a station has it installed",".",n.length>0&&` Not listed: ${n.map(r=>`${r.name} (${r.error})`).join("; ")}.`]}):m("span",{className:"text-xs text-muted-foreground",children:["Your moonlet couldn't list its models",e.error?` (${e.error})`:n.length?` (${n.map(r=>`${r.name}: ${r.error}`).join("; ")})`:"",". Type a model id, like claude-sonnet-5-5."]})}var Pl=(e,t)=>({provider:e[`${t}_provider`],model:e[t],effort:e[`${t}_effort`]}),S_=(e,t,n)=>({...e,[t]:n.model,[`${t}_provider`]:n.provider,[`${t}_effort`]:n.effort});function NT(){let{rpc:e,state:t,error:n,refetch:r}=Ps(),o=Z3(),[s,i]=v(null),[a,u]=v(null),[c,d]=v(null);if(n)return l("p",{className:"text-sm text-destructive",children:n});if(!t)return l("p",{className:"text-sm text-muted-foreground",children:"Loading\u2026"});let p=s??t.prefs.models,f=t.codexStations.length>0,h=w=>{u(T=>T??t.prefsBase),i(w)},g=()=>{i(null),u(null)},x=s!==null&&JSON.stringify(s)!==JSON.stringify(t.prefs.models),b=()=>{e.call("config.savePrefs",{prefs:{...t.prefs,models:p},base:a??t.prefsBase}).then(()=>{g(),d("Saved. New work starts on these, and the conversation switches now."),r()},w=>d(w instanceof Error?w.message:String(w)))},_=Is(t.prefs.identity);return m("div",{className:"flex flex-col gap-6 text-sm",children:[m("p",{className:"text-xs text-muted-foreground",children:["Every model ",_," uses, and how hard each one thinks. New work starts on these; work already running keeps the model it started on."]}),l(rf,{title:`${_.charAt(0).toUpperCase()}${_.slice(1)}'s conversation`,hint:"Its main chat and background conversation. They run on Claude Code and switch as soon as you save.",children:l(Ol,{which:"orbit",list:o,value:Pl(p,"orbit"),hasCodex:f,label:"Conversation",onChange:w=>h(S_(p,"orbit",w))})}),l(rf,{title:"Reading your messages",hint:`Before ${_} answers, this reads each of your messages and decides where it goes: ${_} answers it, it starts as work of its own beside the chat, or it goes to work already under way. It runs on Claude Code.`,children:l(Ol,{which:"orbit",list:o,value:{provider:"claude-code",model:p.router,effort:p.router_effort},hasCodex:f,label:"Reading",onChange:w=>h({...p,router:w.model,router_effort:w.effort})})}),m(rf,{title:"Work on your stations",hint:"Every assistant and chat it starts on a station, including the work it does for you.",children:[l(Ol,{which:"station",list:o,value:Pl(p,"station"),hasCodex:f,label:"Station work",onChange:w=>h(S_(p,"station",w))}),l(ET,{which:"station",list:o,hasCodex:f,main:Pl(p,"station"),backups:p.station_backups,mode:p.station_mode,onChange:w=>h({...p,station_backups:w}),onMode:w=>h({...p,station_mode:w})})]}),m(rf,{title:"Assistants and chats on your listed machines",hint:"Work it starts on a machine of yours that its policy lists.",children:[l(Ol,{which:"agents",list:o,value:Pl(p,"agents"),hasCodex:f,label:"Listed machines",onChange:w=>h(S_(p,"agents",w))}),l(ET,{which:"agents",list:o,hasCodex:f,main:Pl(p,"agents"),backups:p.agents_backups,mode:p.agents_mode,onChange:w=>h({...p,agents_backups:w}),onMode:w=>h({...p,agents_mode:w})})]}),m("div",{className:"flex flex-col gap-1",children:[l("span",{className:"text-xs text-muted-foreground",children:"Models on one provider share its usage. Your moonlet reads each provider's usage on the machine at most once a minute and marks a provider as full the moment work stops at its limit, until it resets. Work already running stays on its model; new work starts on the next one. Spread stays on one provider until another has 10 points more usage left, so new work keeps reusing what that provider has cached."}),l(G3,{list:o,codexStations:t.codexStations})]}),m("div",{className:"flex flex-wrap items-center gap-2",children:[l(R,{size:"sm",disabled:!x,onClick:b,children:"Save"}),l(R,{size:"sm",variant:"ghost",disabled:!x,onClick:g,children:"Revert"}),l(UE,{at:t.prefsUpdatedAt})]}),c&&l("p",{className:"text-xs",children:c})]})}var Qn=6e4,Y3=["release","drain","install","activate","confirm"],q3=re.enum(Y3),GW={release:{label:"Get the release ready",usualMs:10*Qn},drain:{label:"Wait for the station's work to finish",usualMs:15*Qn},install:{label:"Install programs",usualMs:10*Qn},activate:{label:"Turn the pieces back on",usualMs:5*Qn},confirm:{label:"Confirm the installed version",usualMs:2*Qn}},YW=10*Qn;var qW=2*Qn,JW=3*Qn;var J3=500,eF=re.enum(["running","slow","stuck","interrupted","failed","succeeded"]),tF=re.enum(["done","running","failed","stopped","waiting"]),ej=re.object({station:re.string(),attempt:re.string().nullable(),revision:re.string().nullable(),from:re.string().nullable(),startedAt:re.number().int(),endedAt:re.number().int().nullable(),lastActivityAt:re.number().int(),awaySince:re.number().int().nullable(),state:eF,headline:re.string(),reasons:re.array(re.string()),steps:re.array(re.object({id:q3,label:re.string(),state:tF,startedAt:re.number().int().nullable(),endedAt:re.number().int().nullable(),usualMs:re.number().int(),usualFrom:re.number().int(),detail:re.string().nullable()}).strict())}).strict(),tj=re.object({at:re.number().int(),text:re.string().max(J3)}).strict();function Cn(e){let t=Math.floor(Math.max(0,e)/Qn);if(t<1)return"under a minute";if(t<60)return`${t} min`;let n=Math.floor(t/60),r=t%60;return r?`${n} h ${r} min`:`${n} h`}var AT=e=>e?e.slice(0,12):null;var CT=e=>e!==null&&(e.state==="running"||e.state==="slow"||e.state==="stuck"),nF={done:"\u2713",running:"\u2026",failed:"\u2717",stopped:"\u25A0",waiting:"\xB7"};function TT(e,t,n){if(!e)return[`Update on ${t}: none recorded yet.`];let r=e.revision?` to ${AT(e.revision)}${e.from?` from ${AT(e.from)}`:""}`:"",o=e.endedAt===null?`started ${Cn(n-e.startedAt)} ago`:`ended ${Cn(n-e.endedAt)} ago, took ${Cn(e.endedAt-e.startedAt)}`,s=[`Update on ${t}${r}: ${e.headline.toLowerCase()}; ${o}.`];for(let i of e.reasons)s.push(` ${i}`);for(let i of e.steps){let a=i.startedAt===null?"":i.state==="running"||i.state==="stopped"?` (${Cn((i.state==="stopped"?e.lastActivityAt:n)-i.startedAt)} so far)`:i.endedAt!==null?` (${Cn(i.endedAt-i.startedAt)})`:"";s.push(` ${nF[i.state]} ${i.label}${a}${i.detail?` \u2014 ${i.detail}`:""}`)}return s}var vi=e=>new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),rF=e=>new Date(e).toLocaleTimeString([],{hour:"numeric",minute:"2-digit",second:"2-digit"}),RT=e=>e?e.slice(0,7):null,oF={running:{icon:"Spinner",tone:"bg-muted text-muted-foreground",label:"Updating"},slow:{icon:"Clock",tone:"bg-warning/15 text-warning-text",label:"Taking longer than usual"},stuck:{icon:"AlertTriangle",tone:"bg-warning/15 text-warning-text",label:"Looks stuck"},interrupted:{icon:"AlertTriangle",tone:"bg-warning/15 text-warning-text",label:"Interrupted"},failed:{icon:"CircleX",tone:"bg-surface-destructive text-destructive-text",label:"Update failed"},succeeded:{icon:"Check",tone:"bg-muted text-muted-foreground",label:"Up to date"}},sF={done:{name:"CircleCheck",tone:"text-success",label:"Done"},running:{name:"Spinner",tone:"text-foreground",label:"In progress"},failed:{name:"CircleX",tone:"text-destructive-text",label:"Failed"},stopped:{name:"CircleX",tone:"text-warning-text",label:"Stopped"},waiting:{name:"Circle",tone:"text-muted-foreground",label:"Not started"}};function iF({state:e}){let{icon:t,tone:n,label:r}=oF[e];return m("span",{className:V("inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-md px-2 py-1 text-xs",n),children:[l(pe,{name:t,"aria-hidden":!0,className:"size-3.5"}),r]})}function aF(e,t){let n=RT(e.revision),r=e.endedAt===null&&e.state!=="interrupted",o=n?`${r?"Updating to":"To"} ${n}${e.from?` from ${RT(e.from)}`:""}`:null,s=e.endedAt!==null?`ended ${vi(e.endedAt)} \xB7 took ${Cn(e.endedAt-e.startedAt)}`:r?`started ${vi(e.startedAt)} \xB7 ${Cn(t-e.startedAt)}`:`started ${vi(e.startedAt)} \xB7 last heard from ${vi(e.lastActivityAt)}`;return[o,s].filter(Boolean).join(" \xB7 ")}function lF({update:e,now:t}){let n=e.state==="slow"||e.state==="stuck";return l("ol",{className:"flex flex-col","aria-label":`Update steps on ${e.station}`,children:e.steps.map(r=>{let o=sF[r.state],s=r.state==="running"?t:r.state==="stopped"?e.lastActivityAt:r.endedAt,i=r.startedAt===null?null:`${vi(r.startedAt)}${s===null?"":` \xB7 ${Cn(s-r.startedAt)}`}`,u=[r.state==="running"&&n?`Usually under ${Cn(r.usualMs)}`:null,r.detail].filter(Boolean).join(" \xB7 ");return m("li",{className:"grid grid-cols-[1rem_minmax(0,1fr)_auto] items-baseline gap-x-2.5 py-1.5",children:[l(pe,{name:o.name,"aria-label":o.label,className:V("size-4 self-center",o.tone)}),l("span",{className:V(r.state==="waiting"&&"text-muted-foreground",r.state==="running"&&"font-medium"),children:r.label}),l("span",{className:V("whitespace-nowrap text-xs text-muted-foreground",r.state==="running"&&n&&"text-warning-text"),children:i}),u&&l("span",{className:"col-start-2 col-end-4 text-xs text-muted-foreground",children:u})]},r.id)})})}function cF({lines:e}){return e===null?l("p",{className:"mt-2 text-xs text-muted-foreground",children:"Loading\u2026"}):e.length?l("pre",{className:"mt-2 max-h-72 overflow-auto whitespace-pre rounded-md border bg-muted/40 p-3 font-mono text-xs text-muted-foreground","aria-label":"Installer output",children:e.map(t=>`${rF(t.at)} ${t.text}`).join(`
220
+ `)}):l("p",{className:"mt-2 text-xs text-muted-foreground",children:"No output from the installer yet."})}function uF(e,t,n,r){let o=TT(t,e,r);return n?.length&&o.push("","Installer output:",...n.map(s=>`${new Date(s.at).toISOString()} ${s.text}`)),o.join(`
221
+ `)}function $T({name:e,summary:t,update:n,now:r,output:o,outputOpen:s,onOutputOpen:i,loadOutput:a}){let[u,c]=v("idle"),d=n===null||n.state==="succeeded",[p,f]=v(!1);if(d&&!p)return m("li",{className:"flex items-start justify-between gap-3 py-3",children:[m("div",{className:"flex min-w-0 flex-col gap-0.5",children:[l("span",{className:"font-medium",children:e}),l("span",{className:"text-xs text-muted-foreground",children:t})]}),n&&l("button",{type:"button",className:"shrink-0 text-xs text-muted-foreground hover:text-foreground",onClick:()=>f(!0),children:"Last update"})]});if(!n)return null;let h=o?.at(-1);return m("li",{className:"flex flex-col gap-3 py-3",children:[m("div",{className:"flex items-start justify-between gap-3",children:[m("div",{className:"flex min-w-0 flex-col gap-0.5",children:[l("span",{className:"font-medium",children:e}),l("span",{className:"text-xs text-muted-foreground",children:aF(n,r)})]}),l(iF,{state:n.state})]}),n.reasons.length>0&&l("div",{role:"status",className:V("flex flex-col gap-1 rounded-md px-3 py-2 text-xs",n.state==="failed"?"bg-surface-destructive text-destructive-text":n.state==="running"?"bg-muted text-muted-foreground":"bg-warning/15 text-warning-text"),children:n.reasons.map(g=>l("p",{children:g},g))}),l(lF,{update:n,now:r}),m("div",{className:"border-t pt-2",children:[m("div",{className:"flex items-center justify-between gap-3",children:[m("button",{type:"button","aria-expanded":s,className:"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:()=>i(!s),children:[l(pe,{name:s?"ChevronDown":"ChevronRight","aria-hidden":!0,className:"size-3.5"}),"Installer output",h?` \xB7 last line ${vi(h.at)}`:""]}),m("div",{className:"flex items-center gap-1",children:[d&&l(R,{size:"sm",variant:"ghost",onClick:()=>f(!1),children:"Hide"}),m(R,{size:"sm",variant:"ghost",onClick:()=>{a().catch(()=>o).then(g=>j_({text:uF(e,n,g,r)})).then(g=>{c(g?"copied":"failed"),setTimeout(()=>c("idle"),2e3)})},children:[l(pe,{name:"Copy","aria-hidden":!0}),u==="copied"?"Copied":u==="failed"?"Couldn't copy":"Copy details"]})]})]}),s&&l(cF,{lines:o})]})]})}var IT=e=>e instanceof Error?e.message:String(e),dF=15e3,PT=(e,t,n)=>e[t]??(n!==null&&(n.state==="stuck"||n.state==="failed"||n.state==="interrupted"));function OT(){let e=J(),[t,n]=v(null),[r,o]=v(!1),[s,i]=v(null),[a,u]=v(()=>Date.now()),[c,d]=v({}),[p,f]=v({}),h=G(c);h.current=c;let g=q(async y=>{let{lines:E}=await e.call("delivery.output",{station:y});return f(k=>({...k,[y]:E})),E},[e]),x=q(y=>{g(y).catch(()=>f(E=>({...E,[y]:[]})))},[g]),b=q(y=>{n(y),u(Date.now());for(let E of y.stations)PT(h.current,E.name,E.update)&&x(E.name)},[x]),_=q(()=>{e.call("delivery.stations",null).then(y=>{b(y),i(null)},y=>i(IT(y)))},[e,b]);M(_,[_]),ke("delivery",_);let w=t?.stations.some(y=>CT(y.update))??!1;M(()=>{if(!w)return;let y=setInterval(_,dF);return()=>clearInterval(y)},[w,_]);let T=t?.installing===!0;return m("div",{className:"flex flex-col gap-3 text-sm",children:[t===null?!s&&l("p",{className:"text-muted-foreground",children:"Loading\u2026"}):t.stations.length===0?l("p",{className:"text-muted-foreground",children:"There's no station to update."}):l("ul",{className:"divide-y","aria-label":"Stations",children:t.stations.map(y=>l($T,{name:y.name,summary:y.summary,update:y.update,now:a,output:p[y.name]??null,outputOpen:PT(c,y.name,y.update),onOutputOpen:E=>{d(k=>({...k,[y.name]:E})),E&&x(y.name)},loadOutput:()=>g(y.name)},y.name))}),l("div",{children:l(R,{size:"sm",disabled:t===null||r||T,onClick:async()=>{o(!0),i(null);try{b(await e.call("delivery.now",null))}catch(y){i(IT(y))}finally{o(!1)}},children:T?"Updating\u2026":r?"Checking\u2026":"Update now"})}),s&&l("p",{role:"alert",className:"text-destructive",children:s})]})}var pF="Your moonlet";function Ll(e,t,n){return{section:e,title:t,group:pF,icon:n}}function LT(e){e.slots.settingsSection({id:"models",experimental_placement:{section:"models",title:"Models",icon:"AiBrain01"},component:NT}),e.slots.settingsSection({id:"orbit",experimental_placement:Ll("assistant","Profile","UserRound"),experimental_useGroupTitle:Pa,component:jE}),e.slots.settingsSection({id:"personality",experimental_placement:Ll("assistant-personality","Personality","MessageSquare"),experimental_useGroupTitle:Pa,component:qE}),e.slots.settingsSection({id:"rhythm",experimental_placement:Ll("assistant-rhythm","Rhythm","Clock"),experimental_useGroupTitle:Pa,component:oN}),e.slots.settingsSection({id:"conversation",title:"Your conversation",experimental_placement:Ll("assistant-rhythm","Rhythm","Clock"),experimental_fields:["backgroundThread","mainChatCompactionPercent"],component:()=>null}),e.slots.settingsSection({id:"history",experimental_placement:Ll("assistant-history","History","ClockArrowDown"),experimental_useGroupTitle:Pa,component:iN}),e.slots.settingsSection({id:"event-service",title:"Background work",description:"The station's event service, which runs mail, notices and routine work.",experimental_placement:{section:"machines",title:"Machines"},component:aN}),e.slots.settingsSection({id:"set-up-again",title:"Your moonlet's setup",experimental_placement:{section:"general",title:"General"},component:lN}),e.slots.settingsSection({id:"station-sign-in",title:"Claude Code on stations",experimental_placement:{section:"providers",title:"Providers"},experimental_fields:["claudeToken"],component:()=>null}),e.slots.settingsSection({id:"station-delivery",title:"Station programs",description:"The broker, guard, launcher and check runner on each station follow the app's commit. Moonlet checks when the app starts, when a station connects and every 10 minutes, and drains the station's work before it installs. While a station updates, this page shows each step, the installer's output, and why it looks stuck if it does. Update now does it at once, even with automatic updates off.",experimental_placement:{section:"updates",title:"Updates"},component:OT}),hT(e)}function MT(){return Y_(Sh)}function DT(e){let t=ss();return t===void 0?null:t===null?l("p",{className:"p-3 text-sm text-muted-foreground",children:"There's no conversation with your moonlet yet, so there are no notifications to show."}):l(Zl,{name:Sh,params:{threadId:t}})}function FT(){return null}var oQ=W_(e=>{e.slots.pendingInteraction({id:"approval",component:nc}),e.slots.pendingInteraction({id:"policy-proposal",component:oc}),e.slots.experimental_timelineRenderer({kind:"orbit/policy-proposal",component:lv}),e.slots.pendingInteraction({id:"station-manager",component:rc}),e.slots.pendingInteraction({id:"owner-changes",component:ic}),e.slots.experimental_tab({id:"desktop",title:"Desktop",icon:"Monitor",context:{kind:"thread"},availability:"action",component:Fh,layout:"flush"}),e.slots.experimental_tab({id:tu,title:"Artifacts",icon:"FileText",context:{kind:"thread"},availability:"action",component:S1,layout:"flush"}),e.slots.messageDirective({id:Vh,component:Q1}),e.slots.navPanel({id:"artifacts",title:"Artifacts",icon:"FileText",path:"artifacts",component:PE,experimental_sidebar:kE,headerContent:IE}),e.slots.navPanel({id:Ca,title:"Activity",icon:"Activity",path:Ca,component:aE,experimental_sidebar:lE}),e.slots.navPanel({id:"orbit",title:"Moonlet",icon:"Orbit",path:"orbit",component:J1,experimental_useNavigationVisible:()=>!1});for(let n of nN)e.slots.experimental_firstRunStep({id:n.id,title:n.title,description:n.lead,component:rN[n.id]});e.slots.navPanel({id:At,title:"Chat",icon:"MessageSquare",path:At,component:Gk}),e.slots.navPanel({id:mu,title:"Tasks",icon:"ListTodo",path:mu,component:FE,experimental_sidebar:zE}),e.slots.experimental_home({id:"home",title:"Your moonlet chat",description:"One conversation with your moonlet, with threads.",panelPath:At,conversations:"hidden"}),e.slots.experimental_threadList({id:"threads",title:"Moonlet",description:"Your moonlet\u2019s threads live in its chat, so the sidebar shows only where to go.",component:FT});let t=()=>qo()!==null;e.commands.register({id:"thread-full-screen",title:"Thread full screen on or off",defaultShortcut:{key:".",mod:!0},isAvailable:t,run:()=>qo()?.toggleFull()}),e.commands.register({id:"threads-list",title:"Show or hide the threads list",defaultShortcut:{key:"\\",mod:!0,shift:!0},isAvailable:t,run:()=>qo()?.toggleList()}),e.commands.register({id:"thread-next",title:"Next thread",defaultShortcut:{key:"ArrowDown",alt:!0},isAvailable:t,run:()=>qo()?.cycle(1)}),e.commands.register({id:"thread-previous",title:"Previous thread",defaultShortcut:{key:"ArrowUp",alt:!0},isAvailable:t,run:()=>qo()?.cycle(-1)}),e.slots.experimental_tab({id:wh,title:"Desktop",icon:"Monitor",layout:"flush",context:{kind:"nav-panel",panelId:At},availability:"action",component:Yk}),e.slots.experimental_tab({id:eu,title:"Artifacts",icon:"FileText",layout:"flush",context:{kind:"nav-panel",panelId:At},availability:"action",component:E1}),e.slots.experimental_tab({id:"home-tasks",title:"Tasks",icon:"ListTodo",context:{kind:"nav-panel",panelId:At},availability:"action",component:KE}),e.slots.experimental_tab({id:kh,title:"Notifications",icon:"Bell",context:{kind:"nav-panel",panelId:At},availability:"action",useVisible:MT,component:DT}),e.composer.customize({id:"pending-work",scopes:["thread"],banners:[{id:"pending-work",chrome:"bare",component:q1}]}),LT(e),e.slots.experimental_appOverlay({id:"chat-avatar",component:Qc})});export{oQ as default};