@augmentd-labs/canvas-web 2.26.19 → 2.26.20

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.
Files changed (155) hide show
  1. package/dist/assets/DocumentBodyEditor-CE2S2X6g.js +1 -0
  2. package/dist/assets/DocumentIcon-BS10SIP6.js +1 -0
  3. package/dist/assets/EditorOverlay-BUToR_av.js +1 -0
  4. package/dist/assets/FileForm-BxTixeDm.js +1 -0
  5. package/dist/assets/FiltersApplet-BpqITV13.js +1 -0
  6. package/dist/assets/HomeFab-BAKOAkpE.js +3 -0
  7. package/dist/assets/IdentityFields-C2MPM-Ab.js +1 -0
  8. package/dist/assets/LensApplet-DNTGwgZs.js +1 -0
  9. package/dist/assets/LinkToCard-BZwwE-Dv.js +1 -0
  10. package/dist/assets/LinkToSidePanel-eCy3nW4R.js +1 -0
  11. package/dist/assets/{LocationTab-BONJQfYM.js → LocationTab-DAtqAQ3l.js} +1 -1
  12. package/dist/assets/{MarkdownEditor-CkobBLtI.js → MarkdownEditor-7OqSDr7E.js} +1 -1
  13. package/dist/assets/MessageComposerDialog-DzLhkHyh.js +4 -0
  14. package/dist/assets/{NextShell-Byg6OtC2.js → NextShell-D9gvlKY2.js} +1 -1
  15. package/dist/assets/NotesApplet-gMAMneRi.js +1 -0
  16. package/dist/assets/ObjectPropertiesCard-C3jt40tM.css +1 -0
  17. package/dist/assets/ObjectPropertiesCard-DDcRLpsW.js +8 -0
  18. package/dist/assets/PathPickerField-cVs5sZuG.js +1 -0
  19. package/dist/assets/PickDocumentsCard-BlicxMqC.js +1 -0
  20. package/dist/assets/SketchApplet-D8mkYmK9.js +1 -0
  21. package/dist/assets/{SketchEditor-C9_lu3Ot.js → SketchEditor-zMrm1npg.js} +4 -4
  22. package/dist/assets/TerminalApplet-BO2HRp0z.js +20 -0
  23. package/dist/assets/TerminalApplet-BrP-ENHg.css +1 -0
  24. package/dist/assets/TextDocumentEditor-7V4aFL8i.js +1 -0
  25. package/dist/assets/TodosApplet-swdaBT-2.js +1 -0
  26. package/dist/assets/TodosWidget-BXF8fYer.js +1 -0
  27. package/dist/assets/UploadProgressList-B2xCVzFR.js +1 -0
  28. package/dist/assets/_agentId_-Ci4j4UYy.js +0 -0
  29. package/dist/assets/_contextId_-DDFyhgV2.js +1 -0
  30. package/dist/assets/_workspaceName_-DO9ZBx7N.js +1 -0
  31. package/dist/assets/about-B1_n4Iu8.js +1 -0
  32. package/dist/assets/add-BnwWcDlO.js +1 -0
  33. package/dist/assets/admin-Bhg9QBHL.js +5 -0
  34. package/dist/assets/agents-ClK3Y2x0.js +1 -0
  35. package/dist/assets/agents-DquOfkFX.js +1 -0
  36. package/dist/assets/alert-dialog-DIA-tAP5.js +1 -0
  37. package/dist/assets/api-CA6WiiYM.js +1 -0
  38. package/dist/assets/api-tokens-O5iFESo0.js +1 -0
  39. package/dist/assets/appearance-C2vu3ALt.js +1 -0
  40. package/dist/assets/applet-target-DnTa2VAT.js +1 -0
  41. package/dist/assets/apps-BZrw8Cqo.js +1 -0
  42. package/dist/assets/auth-Bx9fAZmz.js +1 -0
  43. package/dist/assets/auth-CUdpxbLV.js +1 -0
  44. package/dist/assets/backend-sync-progress-DU-e9TWi.css +1 -0
  45. package/dist/assets/backend-sync-progress-DWR42uQV.js +7 -0
  46. package/dist/assets/blobs-WiXP9QRi.js +1 -0
  47. package/dist/assets/button-Bv4zA1qr.js +1 -0
  48. package/dist/assets/chunk-62JRHF6Z-vspAGgtK.js +3 -0
  49. package/dist/assets/{chunk-K2UTITRG-zQFDOW3Q.js → chunk-K2UTITRG-BvHe9UPk.js} +3 -3
  50. package/dist/assets/code-editor-BOIngd5F.js +40 -0
  51. package/dist/assets/color-DFEH4BfK.js +1 -0
  52. package/dist/assets/content-app-view-C33Ip_rx.js +1 -0
  53. package/dist/assets/context-D_K4g9SQ.js +1 -0
  54. package/dist/assets/contexts-B6d6Axza.js +1 -0
  55. package/dist/assets/contexts-CgydYDn-2.js +1 -0
  56. package/dist/assets/date-time-picker-BZaA3M9_.js +1 -0
  57. package/dist/assets/desk-dI_FvLsK.js +1 -0
  58. package/dist/assets/devices-CAa1bRxk.js +1 -0
  59. package/dist/assets/devices-D3-_UWM0.js +1 -0
  60. package/dist/assets/document-BG_mODBn.js +1 -0
  61. package/dist/assets/document-list-BiogH4tf.js +2 -0
  62. package/dist/assets/document-list-DAYdk5vh.css +1 -0
  63. package/dist/assets/document-open-mode-DoImW-xs.js +1 -0
  64. package/dist/assets/embedding-Cjrxh6MN.js +1 -0
  65. package/dist/assets/embedding-m8SZH4oN.js +1 -0
  66. package/dist/assets/form-panel-Dz96K7Lv.js +1 -0
  67. package/dist/assets/geo-CZfs0E-x.js +1 -0
  68. package/dist/assets/home-pS7q4Wl4.js +1 -0
  69. package/dist/assets/image-GAAHSSAO-CI-0hUck.js +1 -0
  70. package/dist/assets/index-C10UNpew.css +2 -0
  71. package/dist/assets/index-exXolIqD.js +16 -0
  72. package/dist/assets/inferd-config-editor-DagMmwW4.js +1 -0
  73. package/dist/assets/input-BOtCd4HP.js +1 -0
  74. package/dist/assets/key-bindings-BOtykyXR.js +1 -0
  75. package/dist/assets/label-CNoJOoe0.js +1 -0
  76. package/dist/assets/last-path-BbXWC3b3.js +1 -0
  77. package/dist/assets/layer-style-Byl5LNFR.js +1 -0
  78. package/dist/assets/lazy-editor-Cbva8Pe2.js +2 -0
  79. package/dist/assets/logs-CdbfY8_H.js +1 -0
  80. package/dist/assets/{markdown-html-XoABNf32.js → markdown-html-CZMGihx6.js} +1 -1
  81. package/dist/assets/markdown-view-BBBZtNSR.js +2 -0
  82. package/dist/assets/note-save-status-DPz4VzL6.js +1 -0
  83. package/dist/assets/offline-BjMpUv3N.js +1 -0
  84. package/dist/assets/page-header-GtTr9Ff_.js +1 -0
  85. package/dist/assets/public-share-DT9Tgn_Y.js +1 -0
  86. package/dist/assets/query-debug-tVbB_8Z6.js +1 -0
  87. package/dist/assets/react-BHzhHVTZ.js +164 -0
  88. package/dist/assets/registry-6tE_1KPV.js +2 -0
  89. package/dist/assets/relation-events-CKio19hE.js +1 -0
  90. package/dist/assets/remotes-DR_iJClb.js +1 -0
  91. package/dist/assets/role-C5I0Plgn.js +1 -0
  92. package/dist/assets/roles-DERIgujv.js +2 -0
  93. package/dist/assets/roles-DswT1Lv0.js +2 -0
  94. package/dist/assets/settings-Cc6OMCOX.js +14 -0
  95. package/dist/assets/settings-D7K7z_JD.js +1 -0
  96. package/dist/assets/settings-Du8r1SXC.js +1 -0
  97. package/dist/assets/settings-vosK_LI-.js +1 -0
  98. package/dist/assets/share-target-Df10J5JB.js +1 -0
  99. package/dist/assets/shared-1dpCuibu.js +1 -0
  100. package/dist/assets/shared-C7b3QOUP.js +1 -0
  101. package/dist/assets/sketch-lazy-Q58-vPF-.js +2 -0
  102. package/dist/assets/socket-CtH3EU9m.js +1 -0
  103. package/dist/assets/subtree-transfer-dialog-B7s4r78T.js +1 -0
  104. package/dist/assets/tags-YamdPoBK.js +1 -0
  105. package/dist/assets/text-documents-D_zDMyhB.js +2 -0
  106. package/dist/assets/{ui-BqHBdBU4.js → ui-BSqPn1LJ.js} +2 -2
  107. package/dist/assets/url-params-n7kU_WZ-.js +1 -0
  108. package/dist/assets/use-applet-docs-Cry2SFsG.js +1 -0
  109. package/dist/assets/use-applet-target-mkjQujx6.js +1 -0
  110. package/dist/assets/use-canvas-pins-C57Vbkrq.css +1 -0
  111. package/dist/assets/use-canvas-pins-CZBfEB5E.js +3 -0
  112. package/dist/assets/use-create-panel-DhSNIGtr.js +1 -0
  113. package/dist/assets/use-document-modal-PG8bQyIB.js +1 -0
  114. package/dist/assets/use-menu-BVkqNEIx.js +1 -0
  115. package/dist/assets/use-mobile-Db-vWu9Y.js +1 -0
  116. package/dist/assets/use-settings-back-Dk-DJEUO.js +1 -0
  117. package/dist/assets/use-sortable-data-DYIDDI8c.js +1 -0
  118. package/dist/assets/{use-theme-Bd8sb5Ox.js → use-theme-DaxpiICf.js} +1 -1
  119. package/dist/assets/use-toast-BlLDqSUO.js +1 -0
  120. package/dist/assets/use-toolbox-Ck_cLGgf.js +1 -0
  121. package/dist/assets/use-workspace-identity-BVpGHkZq.js +1 -0
  122. package/dist/assets/useAddTarget-CVRPElxz.js +1 -0
  123. package/dist/assets/useAgentModels-DI41aFY3.js +3 -0
  124. package/dist/assets/useDocumentThumbnail-C_rq2rXs.js +1 -0
  125. package/dist/assets/useEditNoteFields-Bigs9ZG8.js +1 -0
  126. package/dist/assets/useEscapeClose-DR_xKT_k.js +1 -0
  127. package/dist/assets/useSocketSubscription-ifW-vnlb.js +1 -0
  128. package/dist/assets/useToastHelpers-CRrpIIdY.js +1 -0
  129. package/dist/assets/users-C9N-O1QA.js +1 -0
  130. package/dist/assets/workspace-BydSRtST.js +1 -0
  131. package/dist/assets/workspace-CJ1PWQ29.js +1 -0
  132. package/dist/assets/workspace-access-C9nZlBBZ.js +1 -0
  133. package/dist/assets/workspace-area-menu-Ba_9bGKs.js +1 -0
  134. package/dist/assets/workspace-content-gate-D8bzGD9i.js +1 -0
  135. package/dist/assets/workspace-import-form-D5JA8gzx.js +1 -0
  136. package/dist/assets/workspaces-C9Wtka2V.js +1 -0
  137. package/dist/assets/workspaces-Dx5_N57M.js +1 -0
  138. package/dist/index.html +69 -14
  139. package/dist/sw.js +1 -1
  140. package/package.json +2 -2
  141. package/dist/assets/EditorOverlay-B384ALjA.js +0 -1
  142. package/dist/assets/TextDocumentEditor-DBVWuJaR.js +0 -1
  143. package/dist/assets/alert-dialog-BC58hyW-.js +0 -1
  144. package/dist/assets/blobs-CtDkR2hC.js +0 -1
  145. package/dist/assets/code-editor-BQnKd3jw.js +0 -40
  146. package/dist/assets/document-list-BmUv3zzK.js +0 -19
  147. package/dist/assets/document-list-r-TfV16D.css +0 -1
  148. package/dist/assets/image-GAAHSSAO-BoD-NvEF.js +0 -1
  149. package/dist/assets/index-BhcdilCi.css +0 -2
  150. package/dist/assets/index-DRji5GQn.js +0 -61
  151. package/dist/assets/react-BzqgEMSQ.js +0 -164
  152. package/dist/assets/subtree-transfer-dialog-DRz8kLqY.js +0 -1
  153. package/dist/assets/text-documents-BvR9-zf4.js +0 -3
  154. package/dist/assets/useAddTarget-CgZfKokT.js +0 -1
  155. package/dist/assets/workspace-BSXnX2Me.js +0 -1
@@ -0,0 +1,7 @@
1
+ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{An as r,Ct as i,Gn as a,L as o,Mr as s,Mt as c,Q as l,Qr as u,Rn as d,Rt as f,Vr as ee,X as p,Xr as m,Y as h,Z as te,ci as ne,dn as g,gr as _,ni as re,on as v,qn as ie,st as ae}from"./ui-BSqPn1LJ.js";import{t as y}from"./utils-2pl1SbIp.js";import{t as b}from"./button-Bv4zA1qr.js";import{t as x}from"./input-BOtCd4HP.js";import{c as oe,t as S}from"./api-CA6WiiYM.js";import{t as C}from"./socket-CtH3EU9m.js";import{n as se}from"./use-toast-BlLDqSUO.js";import{t as ce}from"./LinkToCard-BZwwE-Dv.js";import{W as le,bt as ue,gn as de,gt as fe,hn as w}from"./workspace-CJ1PWQ29.js";import{i as pe}from"./MessageComposerDialog-DzLhkHyh.js";import{n as me}from"./LinkToSidePanel-eCy3nW4R.js";import{t as he}from"./PathPickerField-cVs5sZuG.js";var T=e(n(),1);function E(e){return`/workspaces/${e}/hooks`}async function D(e){return await S.get(E(e))||[]}async function O(e,t){return(await S.get(`${E(e)}/${t}`))?.content??``}async function k(e,t,n){await S.put(`${E(e)}/${t}`,{content:n})}async function A(e,t){await S.delete(`${E(e)}/${t}`)}var ge=[`example-`,`disabled-`,`_`];function j(e){let t=e.lastIndexOf(`/`);return{dir:t===-1?``:e.slice(0,t+1),base:t===-1?e:e.slice(t+1)}}function M(e){return ge.find(t=>e.startsWith(t))??null}function _e(e){return M(j(e).base)===null}function ve(e){return j(e).base.startsWith(`example-`)}function ye(e){let{dir:t,base:n}=j(e),r=M(n);return t+(r?n.slice(r.length):`disabled-${n}`)}async function be(e,t,n){if(_e(t)===n)return t;let r=ye(t);return await k(e,r,await O(e,t)),await A(e,t),r}function xe(e){let t={};for(let n of e){let e;e=n.path.includes(`/`)?n.path.split(`/`)[0]:/^(?:example-|disabled-|_)?rules\.json$/.test(n.path)?`rules`:n.path.replace(/\.js$/,``),(t[e]||=[]).push(n)}return t}function Se(e){let t=e.when?.event;return Array.isArray(t)?t.map(String):t?[String(t)]:[]}function Ce(e){let t=e.when?.eventPathExact??e.when?.pathExact??e.when?.path;return Array.isArray(t)?t.map(String):typeof t==`string`?[t]:[]}function we(e){let t=String(e||``).split(`/`).filter(Boolean);return t[0]===`workspace`&&t.length>=2?{backend:`workspace:${t[1]}`,rel:t.slice(2).join(`/`)}:t[0]===`device`?t.length>=3?{backend:t[2],rel:t.slice(3).join(`/`)}:null:t.length>=2?{backend:t[1],rel:t.slice(2).join(`/`)}:null}function Te(e){let t=new URLSearchParams;return e.kind&&e.kind!==`mirror`&&t.set(`addRuleKind`,e.kind),e.path&&t.set(`addRulePath`,e.path),e.target&&t.set(`addRuleTarget`,e.target),e.storeTo&&t.set(`addRuleStoreTo`,e.storeTo),e.storeFolder&&t.set(`addRuleStoreFolder`,e.storeFolder),t}function Ee(e){return String(e||``).replace(/^[a-z]+:/i,``).split(`/`).filter(Boolean).join(`/`)}var N=`rules.json`;async function De(e){try{let t=await O(e,N),n=JSON.parse(t||`{}`);return Array.isArray(n.rules)?n.rules:[]}catch{return[]}}async function Oe(e,t){await k(e,N,JSON.stringify({$schema:`canvas.hook-rules/v1`,rules:t},null,2)+`
2
+ `)}async function ke(e,t={}){let n=new URLSearchParams;t.status&&n.set(`status`,t.status),t.handler&&n.set(`handler`,t.handler),t.limit&&n.set(`limit`,String(t.limit));let r=n.toString();return await S.get(`${E(e)}/pending${r?`?${r}`:``}`)||[]}async function Ae(e,t){return await S.post(`${E(e)}/pending/decisions`,t)}async function je(e,t){return await S.get(`${E(e)}/runs/${encodeURIComponent(t)}`)}async function Me(e,t={}){let n=new URLSearchParams;t.limit&&n.set(`limit`,String(t.limit)),t.handler&&n.set(`handler`,t.handler),t.event&&n.set(`event`,t.event),t.failed&&n.set(`failed`,`true`);let r=n.toString();return await S.get(`${E(e)}/runs${r?`?${r}`:``}`)||[]}var P=1e4,Ne=`canvas.hooks.backfillLimit`;function Pe(e){let t=Math.floor(Number(e));return!Number.isFinite(t)||t<1?500:Math.min(t,P)}function Fe(){try{let e=localStorage.getItem(Ne);return e?Pe(e):500}catch{return 500}}function Ie(e){let t=Pe(e);try{localStorage.setItem(Ne,String(t))}catch{}return t}function Le(e){if(e.includes(`/`)){let t=e.split(`/`)[0];return t===`lib`||t===`rules`?null:t}return e.endsWith(`.js`)?e.replace(/\.js$/,``).replace(/^(?:example-|disabled-|_)/,``):null}async function Re(e,t){return await S.post(`${E(e)}/backfill`,t)}function ze(e,t){return S.post(`${E(e)}/backfill/jobs`,t)}function F(e,t){return S.get(`${E(e)}/backfill/jobs/${t}`)}function Be(e,t){return S.delete(`${E(e)}/backfill/jobs/${t}`)}function Ve(e){return S.get(`${E(e)}/backfill/jobs`)}async function I(e,t){return await S.post(`${E(e)}/run`,t)}async function L(e,t){return await S.post(`${E(e)}/runs/${t}/replay`,{})}async function He(e){return await S.get(`${E(e)}/meta`)}async function Ue(e,t){return await S.post(`${E(e)}/generate`,t)}async function We(e,t){let n=await O(e,N),r=JSON.parse(n),i=Array.isArray(r)?r:r?.rules;if(!Array.isArray(i))throw Error(`The workspace rules file is invalid. Fix it in Rules before adding a rule.`);let a=(Array.isArray(t)?t:[t]).filter(e=>!i.some(t=>t.id===e.id));if(!a.length)return;let o=Array.isArray(r)?[...i,...a]:{...r,rules:[...i,...a]};await k(e,N,JSON.stringify(o,null,2)+`
3
+ `)}var Ge=We;function Ke(e,t,n,r=new Date){let i=e=>String(e).padStart(2,`0`),a={YYYY:String(r.getFullYear()),YY:i(r.getFullYear()%100),MM:i(r.getMonth()+1),DD:i(r.getDate()),HH:i(r.getHours()),mm:i(r.getMinutes()),ss:i(r.getSeconds())},o=e=>e.replace(/\{\{\s*([A-Za-z]+)\s*\}\}/g,(e,t)=>a[t]??e),s=e=>e.split(/[\\/]+/).filter(e=>e&&e!==`.`&&e!==`..`).join(`/`),c=[e,s(o(t.trim()))].filter(Boolean).join(`/`),l=s(o(n.trim()));return{root:c,added:l,result:[c,l,`<attachment filename>`].filter(Boolean).join(`/`),date:`${a.YYYY}-${a.MM}-${a.DD}`}}var R=`Applying rules to existing documents…`,z=new Map;function B(e){return`${e.ruleIds.length>1?`Rule ${e.ruleIndex+1}/${e.ruleIds.length}: `:``}${e.processed}${e.total===null?``:` / ${e.total}`} documents · ${e.applied} applied`}function qe(e,t){let n=`${t.checked} checked, ${t.applied} applied${t.skipped?`, ${t.skipped} already there`:``}`;t.status===`cancelled`?e.done({title:`Cancelled`,description:n}):t.status===`failed`?e.fail({title:`Stopped before finishing`,description:`${n}: ${t.error}. The rule stays enabled; rerun it from Rules to finish.`,variant:`destructive`}):t.failed?e.done({title:`Finished with errors`,description:`${n}, ${t.failed} failed. Details in the rule’s run log.`,variant:`destructive`}):e.done({title:`Rule applied`,description:n})}function V(e,t,n){let r=z.get(n.id);if(r)return r;let i=new Promise(r=>{let i={channel:`workspace:${t}`},a=e({title:R,description:B(n),action:{label:`Cancel`,onClick:()=>{a.update({title:`Cancelling…`,description:B(n)}),Be(t,n.id).catch(()=>a.update({title:R,description:`Could not cancel. Try again.`}))}}}),o=()=>{u?.(),C.off(`job.progress`,c),C.off(`job.finished`,c),r()},s=e=>{if(e.status===`running`)return a.update({title:R,description:B(e)});qe(a,e),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`)),o()},c=e=>{let t=e?.job;t?.id===n.id&&s(t)},l=()=>{C.emit(`subscribe`,i),F(t,n.id).then(s,()=>{})},u=C.on(`connect`,l);C.on(`job.progress`,c),C.on(`job.finished`,c),l()});return z.set(n.id,i),i.finally(()=>z.delete(n.id)),i}async function Je(e,t,n){let r;try{r=await ze(t,{ruleIds:n,limit:Fe()})}catch(t){e({title:R}).fail({title:`Could not start`,description:`${t instanceof Error?t.message:String(t)}. The rule stays enabled; rerun it from Rules.`,variant:`destructive`});return}return V(e,t,r)}async function Ye(e,t){let n=await Ve(t).catch(()=>[]);for(let r of n)r.status===`running`&&V(e,t,r)}function H(e){return`/workspaces/${e}/scripts`}async function Xe(e){return await S.get(H(e))||[]}async function Ze(e,t){return(await S.get(`${H(e)}/${t}`))?.content??``}async function Qe(e,t,n){await S.put(`${H(e)}/${t}`,{content:n})}async function $e(e,t){await S.delete(`${H(e)}/${t}`)}var U=t(),et=[{value:``,label:`any item`},{value:`email`,label:`an email`},{value:`message`,label:`a message`},{value:`tab`,label:`a browser tab / link`},{value:`note`,label:`a note`},{value:`file`,label:`a file`},{value:`todo`,label:`a todo / task`}],tt=[{value:`document.inserted`,label:`is added`,hint:`Fires when the item is created or uploaded.`},{value:`document.updated`,label:`is updated`,hint:`Fires on every edit of the item.`},{value:`document.linked`,label:`is filed into a folder`,hint:`Fires when the item is (re)filed into a tree path — the usual pair with "is added" for folder rules.`},{value:`document.unlinked`,label:`is removed from a folder`,hint:`Fires when the item leaves a tree path.`}],nt=[{key:`toExact`,label:`recipient (To/Cc) is`,hint:`accounting@example.com`},{key:`fromExact`,label:`email sender is`,hint:`person@example.com`},{key:`senderExact`,label:`message sender is`,hint:`Sender ID`},{key:`sender`,label:`message sender contains`,hint:`Sender ID or name`},{key:`senderRegex`,label:`message sender matches regex`,hint:`Sender ID or name pattern`},{key:`body`,label:`body / text contains`,hint:`Words in the email preview or message text`},{key:`bodyRegex`,label:`body / text matches regex`,hint:`invoice\\s+\\d+`},{key:`threadExact`,label:`thread is`,hint:`Thread ID`},{key:`channelExact`,label:`channel / conversation is`,hint:`Channel or conversation ID`},{key:`platformExact`,label:`platform is`,hint:`slack, whatsapp, teams`},{key:`pathExact`,label:`is directly in the folder`,hint:`Current folder membership`},{key:`eventPathExact`,label:`is inserted / linked directly into`,hint:`Exact event destination, e.g. ctx:/foo/bar/baz. Descendant inserts do not match.`},{key:`path`,label:`is under the folder`,hint:`/projects/canvas/UI or backends:/workspace/home/foo`},{key:`mime`,label:`file type is`,hint:`image/*, application/pdf`},{key:`from`,label:`sender contains`,hint:`boss@company.tld`},{key:`to`,label:`recipient (To/Cc) contains`,hint:`invoice@my-company.tld`},{key:`subject`,label:`subject contains`,hint:`invoice`},{key:`fromRegex`,label:`sender matches regex`,hint:`@(acme|example)\\.com$`},{key:`toRegex`,label:`recipient (To/Cc) matches regex`,hint:`^(billing|accounts)@`},{key:`subjectRegex`,label:`subject matches regex`,hint:`^invoice\\s+\\d+`},{key:`urlRegex`,label:`URL matches regex`,hint:`/(invoice|receipt)/`},{key:`urlHost`,label:`website is`,hint:`youtube.com`},{key:`urlContains`,label:`URL contains`,hint:`/watch?v=`},{key:`attachment`,label:`has an attachment of type`,hint:`application/pdf, or * for any`}],rt=new Set([`toExact`,`fromExact`,`senderExact`,`threadExact`,`channelExact`,`platformExact`]),it=e=>rt.has(e)?e.replace(/Exact$/,``):e.replace(/Regex$/,``),at=[{key:`sendFile`,label:`Send file(s) via a channel`,icon:v,tone:`text-blue-600 dark:text-blue-400 bg-blue-500/10`},{key:`extractAttachments`,label:`Extract email attachments to a folder`,icon:v,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`moveMessage`,label:`Move the email to a mail folder`,icon:v,tone:`text-teal-600 dark:text-teal-400 bg-teal-500/10`},{key:`store`,label:`Copy/Move file(s) to a storage backend`,icon:d,tone:`text-sky-600 dark:text-sky-400 bg-sky-500/10`},{key:`download`,label:`download what the link points at`,icon:_,tone:`text-rose-600 dark:text-rose-400 bg-rose-500/10`},{key:`link`,label:`file it into a folder`,icon:ie,tone:`text-emerald-600 dark:text-emerald-400 bg-emerald-500/10`},{key:`unlink`,label:`remove it from a folder`,icon:ie,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`tag`,label:`add tags`,icon:l,tone:`text-violet-600 dark:text-violet-400 bg-violet-500/10`},{key:`unstore`,label:`delete the file from a storage backend`,icon:h,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`notify`,label:`Send me a notification`,icon:re,tone:`text-pink-600 dark:text-pink-400 bg-pink-500/10`},{key:`agent`,label:`ask an agent`,icon:u,tone:`text-indigo-600 dark:text-indigo-400 bg-indigo-500/10`},{key:`script`,label:`run a script`,icon:te,tone:`text-slate-600 dark:text-slate-300 bg-slate-500/10`},{key:`delete`,label:`delete it from Canvas`,icon:p,tone:`text-destructive bg-destructive/10`},{key:`destroy`,label:`delete it everywhere`,icon:p,tone:`text-destructive bg-destructive/10`}],ot=e=>at.find(t=>t.key===e)||at[1],st=`{{title}}{{ext}}`,W=`{{YYYY}}/{{MM}}/{{YYYY}}{{MM}}{{DD}}_{{HH}}{{mm}}{{ss}}{{ext}}`,G=[{value:`auto`,label:`whatever it is (auto)`,hint:`arXiv → the PDF · YouTube, Vimeo, TikTok… → the video · image / video / PDF links → the file · anything else → the page.`},{value:`image`,label:`the file itself (image, PDF, …)`,hint:`Fetches the bytes the URL serves.`},{value:`video`,label:`the video (yt-dlp)`,hint:`Best video + audio, merged. Needs yt-dlp on the server.`},{value:`arxiv`,label:`the arXiv paper (PDF)`,hint:`Works for abs/ and pdf/ links.`},{value:`page`,label:`the page with its images & styles`,hint:`One page, offline-readable (wget --page-requisites).`},{value:`website`,label:`the whole website (mirror)`,hint:`Follows links on the same site up to the chosen depth.`}],ct=[{value:`keep`,label:`keep the original file name`},{value:`title`,label:`use the item title as file name`},{value:`dated`,label:`photo style: 2024/07/20240714_183012.jpg`},{value:`custom`,label:`custom template…`}],K=e=>({sendDriver:`imap`,sendSource:`document`,sendSubject:`{{file.name}}`,sendMessage:``,kind:e,a:``,b:``,recursive:!1,storeFrom:``,storeFolder:``,storeName:`keep`,storeMode:`copy`,storeConflict:`rename`,attachmentMime:`application/pdf`,attachmentName:``,attachmentPath:`{{YYYY}}/{{MM}}`,includeInline:!1,dlKind:`auto`,dlDepth:`2`,dlTags:``,keepLast:!0,notePath:``,noteTitle:``,filePath:``,fileBackend:`home`,fileInsert:``,notifyReply:!1}),q={id:null,description:``,events:[`document.inserted`],schema:``,cascade:!1,approval:!1,conditions:[],actions:[K(`link`)]},lt=e=>e.split(`|`).map(e=>e.trim()).filter(Boolean);function ut(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`rule-${Math.random().toString(36).slice(2,7)}`}var J=e=>e.split(`,`).map(e=>e.trim()).filter(Boolean),dt=[{id:`send-invoices`,title:`Send invoice PDFs to accounting`,icon:v,tone:`text-blue-600 dark:text-blue-400 bg-blue-500/10`,blurb:`Send matching PDF attachments to your accounting firm’s ingestion email, or to a Slack / WhatsApp conversation. Keep the original email and files.`,build:()=>({...q,description:`Send invoice PDFs to accounting`,schema:`email`,conditions:[{field:`toExact`,value:``}],actions:[{...K(`sendFile`),sendSource:`attachments`,sendSubject:`Invoice: {{file.name}}`}]})},{id:`attachments`,title:`File PDF email attachments by month`,icon:v,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`,blurb:`Choose a recipient and extract PDF attachments into Accounting / year / month, using the email date. Add a subject or filename filter to narrow it to invoices.`,build:()=>({...q,description:`File accounting PDF attachments by month`,schema:`email`,conditions:[{field:`toExact`,value:``}],actions:[{...K(`extractAttachments`),a:`workspace:home`,storeFolder:`Accounting`}]})},{id:`store`,title:`Copy/Move file(s) to a storage backend`,icon:d,tone:`text-sky-600 dark:text-sky-400 bg-sky-500/10`,blurb:`Uploads land in the managed blob store. Pick a folder in Canvas and a folder on a storage backend — copy or move matching files and optionally recreate their sub-folder paths.`,build:({backend:e})=>({...q,description:`Copy/Move file(s) to a storage backend`,schema:`file`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:``}],actions:[{...K(`store`),a:e,recursive:!0}]})},{id:`photos`,title:`Sort photos by date`,icon:r,tone:`text-emerald-600 dark:text-emerald-400 bg-emerald-500/10`,blurb:`Images filed into a folder are stored as Photos / 2024 / 07 / 20240714_183012.jpg — by the time the photo was taken (EXIF), not uploaded.`,build:({backend:e})=>({...q,description:`Sort photos by date`,schema:`file`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:``},{field:`mime`,value:`image/*`}],actions:[{...K(`store`),a:e,storeFolder:`Photos`,storeName:`dated`}]})},{id:`mirror`,title:`Mirror a storage folder`,icon:ie,tone:`text-violet-600 dark:text-violet-400 bg-violet-500/10`,blurb:`Everything that appears under a folder of a storage backend shows up 1:1 in the Directory tree.`,build:()=>({...q,description:`Mirror a storage folder`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:`backends:/workspace/home/`}],actions:[{...K(`link`),a:`dir:/`,recursive:!0}]})},{id:`mail`,title:`File mail from a sender`,icon:v,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`,blurb:`Emails from a person or domain are filed into a folder and you get a notification.`,build:()=>({...q,description:`Mail from …`,schema:`email`,conditions:[{field:`from`,value:``}],actions:[{...K(`link`),a:`/work/urgent`},{...K(`notify`),a:`New mail from {{doc.data.from}}: {{doc.data.subject}}`}]})},{id:`download`,title:`Download what links point at`,icon:_,tone:`text-rose-600 dark:text-rose-400 bg-rose-500/10`,blurb:`Bookmarks filed into a folder are fetched for real — images, videos (yt-dlp), arXiv papers, a page or a whole website — saved to a folder and filed next to the link.`,build:({backend:e})=>({...q,description:`Download what links point at`,schema:`tab`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:``}],actions:[{...K(`download`),a:e,storeFolder:`Downloads`,recursive:!0}]})},{id:`agent`,title:`Ask an agent`,icon:u,tone:`text-indigo-600 dark:text-indigo-400 bg-indigo-500/10`,blurb:`Hand new items to an agent with a prompt; save its reply as a note or get it as a notification.`,build:()=>({...q,description:`Summarize new items`,actions:[{...K(`agent`),b:`Read document #{{doc.id}} in full with canvas_get, then summarize it in three bullet points.`,notifyReply:!0}]})},{id:`blank`,title:`Start from scratch`,icon:ae,tone:`text-muted-foreground bg-muted`,blurb:`An empty rule: choose what it reacts to, add conditions and actions.`,build:()=>({...q})}];function Y(e){let t=e.filter(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field));if(t.length!==1||t[0].field!==`eventPathExact`)return null;let n=lt(t[0].value);return n.length===1&&/^(ctx|context):\//.test(n[0])?n[0].replace(/^(ctx|context):/,``).replace(/\/+$/,``)||`/`:null}function ft(e){if(Y(e)!==null)return!0;let t=e.filter(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field)).flatMap(e=>lt(e.value));return t.length>0&&t.every(e=>/^(dir|directory|backends):\//.test(e))}function pt(e,t,n){let r=e=>e.replace(/\\/g,`/`).split(`/`).filter(e=>e&&e!==`.`&&e!==`..`).join(`/`),i=`${n?.treePath?`backends:${n.treePath}`:e.a}/${r(e.storeFolder.trim())}`.replace(/\/+$/,``),a=Y(t),o=e.recursive?a===null?`<sub-folders>`:r(a):``;return{root:i,recreated:o,result:[i,o,e.storeName===`keep`?`<original filename>`:e.storeName===`title`?`<title>.<ext>`:e.storeName===`dated`?W:e.b||`<filename>`].filter(Boolean).join(`/`)}}function mt(e,t=[]){let n={event:e.events.length===1?e.events[0]:e.events};e.schema&&(n.schema=e.schema);let r={},i={};for(let t of e.conditions){let e=t.field.endsWith(`Regex`),n=rt.has(t.field),a=e||n?t.value.trim()?[t.value]:[]:lt(t.value);if(e&&a.length)try{new RegExp(t.value,`i`)}catch{throw Error(`Invalid regular expression for ${nt.find(e=>e.key===t.field)?.label}: ${t.value}`)}if(!a.length)throw Error(`Enter a value for ${nt.find(e=>e.key===t.field)?.label||t.field}, or remove that condition.`);if(t.field===`urlHost`||t.field===`urlContains`||t.field===`urlRegex`){let e=t.field===`urlHost`?`host`:t.field===`urlRegex`?`regex`:`contains`,n=i[e],r=[...Array.isArray(n)?n:n==null?[]:[n],...a];i[e]=r.length===1?r[0]:r}else(r[it(t.field)]||=[]).push(...e?a.map(e=>({regex:e})):n?a.map(e=>({equals:e})):a)}for(let[e,t]of Object.entries(r))t?.length&&(n[e]=t.length===1?t[0]:t);Object.keys(i).length&&(n.url=i);let a=e=>{let t={};return e.notePath.trim()&&(t.note={path:e.notePath.trim(),...e.noteTitle.trim()?{title:e.noteTitle.trim()}:{}}),e.filePath.trim()&&(t.file={path:e.filePath.trim(),...e.fileBackend===`data`?{backend:`data`}:{},...e.fileInsert.trim()?{insert:e.fileInsert.trim()}:{}}),e.notifyReply&&(t.notify=!0),Object.keys(t).length?t:null},o=[];for(let n of e.actions){let r=n.a.trim(),i=n.b.trim(),s=n.recursive?{recursive:!0}:{};if(n.kind===`sendFile`){if(!r)throw Error(`Choose a sending account for the file.`);if(!i)throw Error(n.sendDriver===`imap`?`Enter the destination email address.`:`Enter a configured destination conversation.`);if(![`imap`,`slack`,`whatsapp`].includes(n.sendDriver))throw Error(`Choose email, Slack or WhatsApp.`);if(![`document`,`attachments`,`download`].includes(n.sendSource))throw Error(`Choose which files to send.`);if(n.sendSource===`download`&&!o.some(e=>e.action===`download`))throw Error(`Add a Download action before sending its files.`);let e=J(n.attachmentMime);if(n.sendSource===`attachments`&&(!e.length||e.some(e=>!/^(\*|[a-z0-9!#$&^_.+-]+\/(\*|[a-z0-9!#$&^_.+-]+)|\*\/\*)$/i.test(e))))throw Error(`Enter attachment MIME types, such as application/pdf.`);if(n.sendDriver===`whatsapp`&&n.sendMessage.length>1024)throw Error(`WhatsApp file captions must be at most 1,024 characters.`);o.push({action:`sendFile`,source:n.sendSource,driver:n.sendDriver,address:r,...n.sendDriver===`imap`?{to:J(i),subject:n.sendSubject}:{target:i},...n.sendMessage?{message:n.sendMessage}:{},...n.sendSource===`attachments`?{mime:e.length===1?e[0]:e,...n.attachmentName.trim()?{filename:n.attachmentName.trim()}:{},...n.includeInline?{includeInline:!0}:{}}:{}})}if(n.kind===`link`&&r&&o.push({action:`link`,paths:J(r),...s,...i?{tags:J(i)}:{}}),n.kind===`unlink`&&r&&o.push({action:`unlink`,paths:J(r),...s}),n.kind===`tag`&&r&&o.push({action:`tag`,tags:J(r)}),n.kind===`moveMessage`){if(!r)throw Error(`Enter the mail folder to move the email to, such as INBOX/Accounting/{{YYYY}}/Expenses.`);o.push({action:`moveMessage`,folder:r})}if(n.kind===`store`&&r){if(n.storeMode===`move`&&!n.storeFrom.trim())throw Error(`Choose the source backend whose copy should be moved.`);if(n.recursive&&!ft(e.conditions))throw Error(`Choose a Directory/Backends source path, or one exact Context insertion path, to recreate the path.`);if(n.recursive&&t.find(e=>e.address===r)?.capabilities?.paths!==!0)throw Error(`This destination has not reported support for folder paths. Choose a supported backend or turn off path recreation.`);let a=n.storeFolder.trim().replace(/^\/+|\/+$/g,``),c=n.storeName===`title`?st:n.storeName===`dated`?W:n.storeName===`custom`?i:``;o.push({action:`store`,to:r,...n.storeFrom.trim()?{from:n.storeFrom.trim()}:{},mode:n.storeMode,...a?{folder:a}:{},...s,...n.recursive&&Y(e.conditions)!==null?{pathMode:`full`}:{},...c?{key:c}:{},onConflict:n.storeConflict})}if(n.kind===`extractAttachments`){if(!r)throw Error(`Choose a destination backend for the attachments.`);if(t.find(e=>e.address===r)?.capabilities?.paths!==!0)throw Error(`Choose an attachment destination with support for folder paths.`);let e=J(n.attachmentMime);if(!e.length||e.some(e=>!/^(\*|[a-z0-9!#$&^_.+-]+\/(\*|[a-z0-9!#$&^_.+-]+)|\*\/\*)$/i.test(e)))throw Error(`Enter attachment MIME types, such as application/pdf or image/*. Use * for all attachments.`);if(![`rename`,`error`].includes(n.storeConflict))throw Error(`Choose rename or skip for attachment filename conflicts.`);o.push({action:`extractAttachments`,to:r,mime:e.length===1?e[0]:e,...n.storeFolder.trim()?{folder:n.storeFolder.trim()}:{},...n.attachmentPath.trim()?{subfolder:n.attachmentPath.trim()}:{},...n.attachmentName.trim()?{filename:n.attachmentName.trim()}:{},...n.includeInline?{includeInline:!0}:{},onConflict:n.storeConflict})}if(n.kind===`download`){let e=n.storeFolder.trim().replace(/^\/+|\/+$/g,``),t=Number(n.dlDepth);o.push({action:`download`,to:r||`workspace:home`,...e?{folder:e}:{},...s,...n.dlKind===`auto`?{}:{kind:n.dlKind},...i?{insert:J(i)}:{},...n.dlTags.trim()?{tags:J(n.dlTags)}:{},...n.dlKind===`website`&&Number.isFinite(t)&&t>0&&t!==2?{depth:t}:{}})}if(n.kind===`unstore`&&r&&o.push({action:`unstore`,from:r,...i?{ifOn:i}:{},...n.keepLast?{}:{keepLast:!1}}),n.kind===`notify`&&r&&o.push({action:`notify`,message:r}),n.kind===`delete`&&o.push({action:`delete`}),n.kind===`destroy`&&o.push({action:`destroy`}),n.kind===`agent`&&r&&i){let e=a(n);o.push({action:`agent`,slug:r,prompt:i,...e?{output:e}:{}})}if(n.kind===`script`&&r){let e=a(n);o.push({action:`script`,path:r,...e?{output:e}:{}})}}return{id:e.id||ut(e.description),enabled:!0,...e.description?{description:e.description}:{},...e.cascade?{cascade:!0}:{},...e.approval?{approval:!0}:{},...e.editable?.length?{editable:e.editable}:{},...e.ttl===void 0?{}:{ttl:e.ttl},when:n,then:o}}function ht(e){let{event:t,schema:n,from:r,to:i,subject:a,body:o,sender:s,thread:c,channel:l,platform:u,path:d,pathExact:f,eventPathExact:ee,mime:p,url:m,attachment:h,...te}=e.when;if(Object.keys(te).length>0)return null;let ne=Array.isArray(t)?t:[t];if(!ne.length||!ne.every(e=>typeof e==`string`&&tt.some(t=>t.value===e))||n!==void 0&&typeof n!=`string`)return null;let g=[],_=(e,t)=>{let n=Array.isArray(t)?t:[t];if(e.endsWith(`Regex`)){if(!n.every(e=>typeof e==`string`))return!1;for(let t of n)g.push({field:e,value:t})}else if(rt.has(e))for(let t of n){if(!t||typeof t!=`object`||Object.keys(t).length!==1||typeof t.equals!=`string`)return!1;g.push({field:e,value:t.equals})}else if([`from`,`to`,`subject`,`body`,`sender`].includes(e))for(let t of n)if(typeof t==`string`)g.push({field:e,value:t});else if([`from`,`to`,`sender`].includes(e)&&t&&typeof t==`object`&&Object.keys(t).length===1&&typeof t.equals==`string`)g.push({field:`${e}Exact`,value:t.equals});else if(t&&typeof t==`object`&&Object.keys(t).length===1&&typeof t.regex==`string`)g.push({field:`${e}Regex`,value:t.regex});else return!1;else{if(!n.every(e=>typeof e==`string`))return!1;g.push({field:e,value:n.join(` | `)})}return!0};if(d!==void 0&&!_(`path`,d)||f!==void 0&&!_(`pathExact`,f)||ee!==void 0&&!_(`eventPathExact`,ee)||p!==void 0&&!_(`mime`,p)||r!==void 0&&!_(`from`,r)||i!==void 0&&!_(`to`,i)||a!==void 0&&!_(`subject`,a)||o!==void 0&&!_(`body`,o)||s!==void 0&&!_(`sender`,s)||c!==void 0&&!_(`threadExact`,c)||l!==void 0&&!_(`channelExact`,l)||u!==void 0&&!_(`platformExact`,u)||h!==void 0&&!_(`attachment`,h))return null;if(m!==void 0){if(typeof m==`string`)g.push({field:`urlContains`,value:m});else if(m&&typeof m==`object`){let e=m;if(Object.keys(e).filter(e=>e!==`host`&&e!==`contains`&&e!==`regex`).length||e.host!==void 0&&!_(`urlHost`,e.host)||e.contains!==void 0&&!_(`urlContains`,e.contains)||e.regex!==void 0&&!_(`urlRegex`,e.regex))return null}else return null}let re=e=>{let t=e.output&&typeof e.output==`object`?e.output:{};if(Object.keys(t).filter(e=>e!==`note`&&e!==`file`&&e!==`notify`).length)return null;let n=t.note&&typeof t.note==`object`?t.note:{},r=t.file&&typeof t.file==`object`?t.file:{};return Object.keys(r).filter(e=>e!==`path`&&e!==`backend`&&e!==`insert`).length?null:{notePath:typeof n.path==`string`?n.path:``,noteTitle:typeof n.title==`string`?n.title:``,filePath:typeof r.path==`string`?r.path:``,fileBackend:r.backend===`data`?`data`:`home`,fileInsert:typeof r.insert==`string`?r.insert:``,notifyReply:t.notify===!0}},v=[];for(let t of e.then||[]){if(t.approval!==void 0)return null;if(t.action===`link`&&Array.isArray(t.paths))v.push({...K(`link`),a:t.paths.join(`, `),b:Array.isArray(t.tags)?t.tags.join(`, `):``,recursive:t.recursive===!0});else if(t.action===`unlink`&&Array.isArray(t.paths))v.push({...K(`unlink`),a:t.paths.join(`, `),recursive:t.recursive===!0});else if(t.action===`tag`&&Array.isArray(t.tags))v.push({...K(`tag`),a:t.tags.join(`, `)});else if(t.action===`moveMessage`){if(Object.keys(t).some(e=>e!==`action`&&e!==`folder`)||typeof t.folder!=`string`)return null;v.push({...K(`moveMessage`),a:t.folder})}else if(t.action===`notify`&&typeof t.message==`string`)v.push({...K(`notify`),a:t.message});else if(t.action===`store`&&typeof t.to==`string`){if(t.pathMode!==void 0&&(t.pathMode!==`full`||t.recursive!==!0||Y(g)===null)||t.recursive===!0&&Y(g)!==null&&t.pathMode!==`full`||t.folder!==void 0&&typeof t.folder!=`string`||t.key!==void 0&&typeof t.key!=`string`)return null;let e=typeof t.key==`string`?t.key:``;v.push({...K(`store`),a:t.to,b:e===st||e===W?``:e,storeFolder:typeof t.folder==`string`?t.folder:``,recursive:t.recursive===!0,storeName:e?e===st?`title`:e===W?`dated`:`custom`:`keep`,storeFrom:typeof t.from==`string`?t.from:Array.isArray(t.from)?String(t.from[0]??``):``,storeMode:t.mode===`move`?`move`:`copy`,storeConflict:t.onConflict===`error`||t.onConflict===`overwrite`?t.onConflict:`rename`})}else if(t.action===`sendFile`){let e=new Set([`action`,`source`,`driver`,`address`,`to`,`target`,`subject`,`message`,`mime`,`filename`,`includeInline`]);if(Object.keys(t).some(t=>!e.has(t))||![`imap`,`slack`,`whatsapp`].includes(String(t.driver))||typeof t.address!=`string`||t.source!==void 0&&![`document`,`attachments`,`download`].includes(String(t.source))||[`target`,`subject`,`message`,`filename`].some(e=>t[e]!==void 0&&typeof t[e]!=`string`)||t.includeInline!==void 0&&typeof t.includeInline!=`boolean`)return null;let n=Array.isArray(t.to)?t.to:t.to===void 0?[]:[t.to],r=Array.isArray(t.mime)?t.mime:[t.mime??`*`];if(!n.every(e=>typeof e==`string`)||!r.every(e=>typeof e==`string`)||(t.driver===`imap`?t.target!==void 0:t.to!==void 0||t.subject!==void 0))return null;v.push({...K(`sendFile`),a:t.address,b:t.driver===`imap`?n.join(`, `):String(t.target||``),sendDriver:t.driver,sendSource:t.source||`document`,sendSubject:String(t.subject??`{{file.name}}`),sendMessage:String(t.message||``),attachmentMime:r.join(`, `),attachmentName:String(t.filename||``),includeInline:t.includeInline===!0})}else if(t.action===`extractAttachments`){let e=new Set([`action`,`to`,`folder`,`subfolder`,`mime`,`filename`,`includeInline`,`onConflict`]);if(Object.keys(t).some(t=>!e.has(t))||typeof t.to!=`string`||[`folder`,`subfolder`,`filename`].some(e=>t[e]!==void 0&&typeof t[e]!=`string`)||t.includeInline!==void 0&&typeof t.includeInline!=`boolean`||t.onConflict!==void 0&&t.onConflict!==`rename`&&t.onConflict!==`error`)return null;let n=Array.isArray(t.mime)?t.mime:[t.mime??`*`];if(!n.every(e=>typeof e==`string`))return null;v.push({...K(`extractAttachments`),a:t.to,storeFolder:typeof t.folder==`string`?t.folder:``,attachmentPath:typeof t.subfolder==`string`?t.subfolder:``,attachmentMime:n.join(`, `),attachmentName:typeof t.filename==`string`?t.filename:``,includeInline:t.includeInline===!0,storeConflict:t.onConflict===`error`?`error`:`rename`})}else if(t.action===`download`){let e=new Set([`action`,`to`,`folder`,`recursive`,`kind`,`insert`,`tags`,`depth`]);if(Object.keys(t).some(t=>!e.has(t)))return null;let n=typeof t.kind==`string`?t.kind:`auto`;if(!G.some(e=>e.value===n))return null;let r=Array.isArray(t.insert)?t.insert:typeof t.insert==`string`?[t.insert]:[];if(!r.every(e=>typeof e==`string`))return null;v.push({...K(`download`),a:typeof t.to==`string`?t.to:`workspace:home`,b:r.join(`, `),storeFolder:typeof t.folder==`string`?t.folder:``,recursive:t.recursive===!0,dlKind:n,dlDepth:typeof t.depth==`number`?String(t.depth):`2`,dlTags:Array.isArray(t.tags)?t.tags.join(`, `):``})}else if(t.action===`unstore`&&(typeof t.from==`string`||Array.isArray(t.from))){let e=e=>Array.isArray(e)?String(e[0]??``):typeof e==`string`?e:``;v.push({...K(`unstore`),a:e(t.from),b:e(t.ifOn),keepLast:t.keepLast!==!1})}else if(t.action===`delete`)v.push(K(`delete`));else if(t.action===`destroy`)v.push(K(`destroy`));else if(t.action===`agent`&&typeof t.slug==`string`&&typeof t.prompt==`string`){let e=re(t);if(!e)return null;v.push({...K(`agent`),a:t.slug,b:t.prompt,...e})}else if(t.action===`script`&&typeof t.path==`string`){let e=re(t);if(!e)return null;v.push({...K(`script`),a:t.path,...e})}else return null}return{id:e.id,description:e.description||``,events:ne,schema:typeof n==`string`?n:``,cascade:e.cascade===!0,approval:e.approval===!0,...e.editable?.length?{editable:e.editable}:{},...e.ttl===void 0?{}:{ttl:e.ttl},conditions:g,actions:v.length?v:[K(`link`)]}}var gt=(e,t)=>t.find(t=>t.value===e)?.label?.replace(/\s\(\d+\)$/,``)||(e?String(e).replace(/^data\/schema\//,``):`any item`);function _t(e,t=et){let n=e.when,r=Se(e).map(e=>tt.find(t=>t.value===e)?.label||e).join(` or `),i=[`When ${gt(n.schema,t)} ${r}`],a=e=>Array.isArray(e)?e.join(` or `):typeof e==`object`&&e?JSON.stringify(e):String(e),o={path:`under`,pathExact:`directly in`,eventPathExact:`inserted / linked directly into`,mime:`type`,from:`from`,to:`to`,subject:`subject`,body:`body / text`,sender:`sender`,thread:`thread`,channel:`conversation`,platform:`platform`,url:`url`,attachment:`attachment`};for(let e of Object.keys(o))n[e]!==void 0&&i.push(`${o[e]} ${a(n[e])}`);return i.join(` · `)}function vt(e){let t=e.output||{},n=t.note||{},r=t.file||{};return[n.path?`reply → note ${n.path}`:``,r.path?`reply → file ${r.backend===`data`?`data:`:`home/`}${r.path}${r.insert?` (indexed at ${r.insert})`:``}`:``,t.notify?`reply → notify`:``].filter(Boolean).join(`, `)}function yt(e){if(e.action===`link`)return`file into ${e.paths?.join(`, `)}${e.recursive===!0?` (sub-folders kept)`:``}`;if(e.action===`unlink`)return`remove from ${e.paths?.join(`, `)}${e.recursive===!0?` (sub-folders kept)`:``}`;if(e.action===`tag`)return`tag ${e.tags?.join(`, `)}`;if(e.action===`store`){let t=typeof e.folder==`string`&&e.folder?`/${e.folder}`:``,n=e.key===st?`, named by title`:e.key===W?`, by date`:typeof e.key==`string`&&e.key?`, as ${e.key}`:``;return`${e.mode===`move`?`move`:`copy`} the file to ${e.to}${t}${e.recursive===!0?e.pathMode===`full`?` (full directory path recreated)`:` (sub-folder path recreated)`:``}${n}`}if(e.action===`extractAttachments`){let t=[e.to,e.folder,e.subfolder].filter(Boolean).join(`/`);return`extract ${Array.isArray(e.mime)?e.mime.join(`, `):e.mime||`all`} attachments to ${t}${e.filename?` (filename contains ${e.filename})`:``}`}if(e.action===`moveMessage`)return`move the email to mail folder ${e.folder}`;if(e.action===`download`){let t=G.find(t=>t.value===(e.kind||`auto`)),n=typeof e.folder==`string`&&e.folder?`/${e.folder}`:``,r=Array.isArray(e.insert)&&e.insert.length?`, filed at ${e.insert.join(`, `)}`:`, filed next to the link`;return`download ${t?.value===`auto`?`the link (auto-detected)`:t?.label||e.kind} to ${e.to||`workspace:home`}${n}${e.recursive===!0?` (sub-folders kept)`:``}${r}`}if(e.action===`unstore`)return`delete the file from ${Array.isArray(e.from)?e.from.join(`, `):e.from}${e.ifOn?` once it is on ${Array.isArray(e.ifOn)?e.ifOn.join(`, `):e.ifOn}`:``}`;if(e.action===`sendFile`)return`send ${e.source===`attachments`?`matching attachments`:e.source===`download`?`downloaded files`:`the file`} via ${e.driver===`imap`?`email`:e.driver} to ${Array.isArray(e.to)?e.to.join(`, `):e.to||e.target||`…`}`;if(e.action===`notify`)return`send me a notification`;if(e.action===`delete`)return`delete from Canvas (keeps stored files/mail)`;if(e.action===`destroy`)return`⚠ delete everywhere (index + storage)`;if(e.action===`agent`){let t=vt(e);return`ask agent "${e.slug}"${t?` (${t})`:``}`}if(e.action===`script`){let t=vt(e);return`run ${e.path}${t?` (${t})`:``}`}return e.action}function bt(e){return(e.then||[]).map(yt).join(` · `)||`(no actions)`}function xt(e){return Ce(e).length>0&&(e.then||[]).length>0&&(e.then||[]).every(e=>e.action===`link`||e.action===`unlink`||e.action===`store`||e.action===`unstore`)}function St(e){let t={};for(let n of e){if(n.handlerType!==`rule`)continue;let e=t[n.handler]||={count:0,errors:0,last:n};e.count++,n.status===`error`&&e.errors++,n.ts>e.last.ts&&(e.last=n)}return t}function Ct(e){let t=Date.now()-new Date(e).getTime();if(!Number.isFinite(t)||t<0)return``;let n=Math.floor(t/6e4);if(n<1)return`just now`;if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function wt(e){return e.some(e=>e.address===`workspace:home`)?`workspace:home`:e.find(e=>e.address!==`workspace:data`)?.address||e[0]?.address||``}function Tt(e){if(e.kind===`document`&&e.rule)return{...ht(e.rule)||q,id:null};if(e.kind===`download`){let t=e.path?` filed under ${e.path.replace(/^(ctx|dir):/,``)}`:``;return{...q,description:`Download links${t}`,schema:`tab`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:e.path||``}],actions:[{...K(`download`),a:e.storeTo||``,storeFolder:e.storeFolder||`Downloads`,recursive:!0}]}}if(e.kind===`store`){let t=e.path||``,n=/^(?:(?:ctx|context):)?\//.test(t),r=[{field:n?`eventPathExact`:`path`,value:n&&t.startsWith(`/`)?`ctx:${t}`:t}],i=e.path?`${n?` inserted / linked directly into`:` filed under`} ${e.path.replace(/^(ctx|context|dir|directory):/,``)}`:``;return{...q,description:e.storeTo?`Copy files${i} to ${e.storeTo}${e.storeFolder?`/${e.storeFolder}`:``}`:`Copy files${i} to a storage backend`,schema:`file`,events:[`document.inserted`,`document.linked`],conditions:r,actions:[{...K(`store`),a:e.storeTo||``,storeFolder:e.storeFolder||``,recursive:ft(r)}]}}return{...q,description:`Mirror ${e.path} into ${e.target}`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:e.path||``}],actions:[{...K(`link`),a:e.target||`dir:/`,recursive:!0}]}}var X=`h-10 w-full rounded-md border bg-background px-3 text-sm outline-none focus:ring-2 focus:ring-ring disabled:opacity-50`,Z=`h-10 text-sm`;function Q({label:e,hint:t,children:n,className:r}){return(0,U.jsxs)(`label`,{className:y(`flex min-w-0 flex-col gap-1.5`,r),children:[(0,U.jsx)(`span`,{className:`text-sm font-medium`,children:e}),n,t&&(0,U.jsx)(`span`,{className:`text-xs leading-relaxed text-muted-foreground`,children:t})]})}function $({checked:e,onChange:t,label:n,hint:r,disabled:i}){return(0,U.jsxs)(`button`,{type:`button`,role:`switch`,"aria-checked":e,disabled:i,onClick:()=>t(!e),className:y(`flex w-full items-start gap-3 rounded-lg border p-3 text-left transition-colors hover:bg-accent/40 disabled:cursor-not-allowed disabled:opacity-50`,e&&`border-primary/40 bg-primary/5`),children:[(0,U.jsx)(`span`,{className:y(`mt-0.5 inline-flex h-5 w-9 shrink-0 items-center rounded-full p-0.5 transition-colors`,e?`bg-primary`:`bg-muted-foreground/30`),children:(0,U.jsx)(`span`,{className:y(`h-4 w-4 rounded-full bg-background shadow transition-transform`,e&&`translate-x-4`)})}),(0,U.jsxs)(`span`,{className:`min-w-0`,children:[(0,U.jsx)(`span`,{className:`block text-sm font-medium`,children:n}),r&&(0,U.jsx)(`span`,{className:`block text-xs leading-relaxed text-muted-foreground`,children:r})]})]})}function Et({value:e,options:t,onChange:n}){return(0,U.jsx)(`div`,{className:`inline-flex h-10 rounded-md border bg-background p-1`,children:t.map(t=>(0,U.jsx)(`button`,{type:`button`,onClick:()=>n(t.value),className:y(`rounded px-3 text-sm transition-colors`,e===t.value?`bg-primary text-primary-foreground shadow-sm`:`text-muted-foreground hover:text-foreground`),children:t.label},t.value))})}function Dt({active:e,onClick:t,children:n,title:r}){return(0,U.jsx)(`button`,{type:`button`,title:r,onClick:t,"aria-pressed":e,className:y(`h-9 rounded-full border px-3.5 text-sm transition-colors`,e?`border-primary bg-primary/10 font-medium text-foreground`:`text-muted-foreground hover:bg-accent hover:text-foreground`),children:n})}function Ot({step:e,title:t,hint:n}){return(0,U.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,U.jsx)(`span`,{className:`mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-primary/10 text-sm font-semibold text-primary`,children:e}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`h3`,{className:`text-base font-semibold leading-7`,children:t}),n&&(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:n})]})]})}function kt({icon:e,tone:t,size:n=`md`}){return(0,U.jsx)(`span`,{className:y(`inline-flex shrink-0 items-center justify-center rounded-xl`,n===`lg`?`h-12 w-12`:`h-10 w-10`,t),children:(0,U.jsx)(e,{className:n===`lg`?`h-6 w-6`:`h-5 w-5`})})}function At({workspaceId:e,onOpenJson:t,onShowRuns:n,backfillLimit:r,prefill:l,onPrefillConsumed:u,createOnly:d=!1,onCreated:h,onCancel:te}){let{showToast:_,showProgress:re}=se(),[v,oe]=(0,T.useState)([]),[S,C]=(0,T.useState)({}),le=e=>{Me(e,{limit:500}).then(e=>C(St(e))).catch(()=>C({}))},[de,fe]=(0,T.useState)(!0),[w,E]=(0,T.useState)(null),[D,O]=(0,T.useState)(!1),[k,A]=(0,T.useState)(!1),[ge,j]=(0,T.useState)([]),[M,_e]=(0,T.useState)([]),[ve,ye]=(0,T.useState)([]),[be,xe]=(0,T.useState)(``),Se=(0,T.useRef)(null),[Te,Ee]=(0,T.useState)(e);e!==Te&&(Ee(e),fe(!0)),(0,T.useEffect)(()=>{De(e).then(e=>oe(e)).finally(()=>fe(!1)),le(e)},[e]);let[N,ke]=(0,T.useState)(null);l!==N&&(ke(l),l&&(E(Tt(l)),O(!1))),(0,T.useEffect)(()=>{l&&u?.()},[l,u]),(0,T.useEffect)(()=>{Xe(e).then(e=>j(e.map(e=>e.path))).catch(()=>j([]))},[e]),(0,T.useEffect)(()=>{let t=!1;return pe(e).then(e=>{t||(ye([...new Map(e.map(e=>[`${e.driver}:${e.address}`,e])).values()]),xe(``))}).catch(()=>{t||(ye([]),xe(`Sending accounts could not be loaded.`))}),()=>{t=!0}},[e]),(0,T.useEffect)(()=>{ue(e).then(e=>{let t=e.filter(e=>e.kind===`storage`&&e.enabled!==!1&&e.config?.supported!==!1&&e.config?.readOnly!==!0&&e.capabilities?.write!==!1);_e(t);let n=wt(t);n&&E(e=>e&&e.actions.some(e=>(e.kind===`store`||e.kind===`download`)&&!e.a)?{...e,actions:e.actions.map(e=>(e.kind===`store`||e.kind===`download`)&&!e.a?{...e,a:n}:e)}:e)}).catch(()=>_e([]))},[e]);let[Ae,je]=(0,T.useState)(et);(0,T.useEffect)(()=>{He(e).then(e=>{e.schemas?.length&&je([{value:``,label:`any item`},...e.schemas.map(e=>({value:e.id,label:`${e.name} (${e.count})`}))])}).catch(()=>{})},[e]);let P=async(t,n)=>{A(!0);try{return await Oe(e,t),oe(t),_({title:n,description:`rules.json updated (committed to workspace git)`}),!0}catch(e){return _({title:`Error`,description:e instanceof Error?e.message:`Failed to save rules`,variant:`destructive`}),!1}finally{A(!1)}},Ne=async()=>{if(!w||de||k)return;let t;try{t=mt(w,M)}catch(e){_({title:`Invalid rule`,description:e instanceof Error?e.message:`Check the rule conditions and actions`,variant:`destructive`});return}if(!t.then.length){_({title:`Add an action`,description:`Pick at least one "then" action and fill in its fields.`,variant:`destructive`});return}if(d){t.id=`${t.id}-${Math.random().toString(36).slice(2,10)}`,A(!0);try{await We(e,t),_({title:`Rule created`,description:`The rule will run for matching new items.`}),h?.()}catch(e){_({title:`Could not create rule`,description:e instanceof Error?e.message:`Failed to save rule`,variant:`destructive`})}finally{A(!1)}return}!w.id&&v.some(e=>e.id===t.id)&&(t.id=`${t.id}-${Math.random().toString(36).slice(2,10)}`);let n=w.id?v.map(e=>e.id===w.id?{...t,enabled:e.enabled!==!1}:e):[...v,t];await P(n,w.id?`Rule updated`:`Rule created`)&&(E(null),h?.())},Pe=e=>P(v.map(t=>t.id===e?{...t,enabled:t.enabled===!1}:t),`Rule toggled`),Fe=e=>{confirm(`Delete rule "${e}"?`)&&P(v.filter(t=>t.id!==e),`Rule deleted`)},[Ie,Le]=(0,T.useState)(null),ze=async t=>{Le(t);try{let n=await Re(e,{ruleId:t,dryRun:!0,limit:r}),i=n.results.filter(e=>e.matched).length;if(!i){_({title:`Apply to existing items`,description:`No matches among ${n.processed} existing documents (conditions evaluate against each document's current tree placements). Raise the batch size in the toolbar to cover more.`});return}if(!confirm(`Rule "${t}" matches ${i} of the first ${n.processed} of ${n.total??n.processed} existing documents. Run its actions on all of them now?`))return;await Je(re,e,[t])}catch(e){_({title:`Backfill failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{Le(null),le(e)}},F=(e,t)=>E(n=>n&&{...n,[e]:t}),Be=e=>{E(e.build({backend:wt(M)})),O(!1),requestAnimationFrame(()=>Se.current?.scrollIntoView({behavior:`smooth`,block:`start`}))},Ve=e=>{let n=ht(e);n?(E(n),O(!1),requestAnimationFrame(()=>Se.current?.scrollIntoView({behavior:`smooth`,block:`start`}))):t?.()},[I,L]=(0,T.useState)(null),Ue=(e,t)=>t.treeType===`context`?e:t.treeName===`directory`?`dir:${e}`:`${t.treeName}:${e}`,Ge=(e,t)=>{if(!I||!w||!e.length){L(null);return}if(I.target===`storeFolder`){let t=we(e[0]);F(`actions`,w.actions.map((e,n)=>n===I.index?{...e,storeFolder:t?.rel||``,...t?.backend&&M.some(e=>e.address===t.backend)?{a:t.backend}:{}}:e))}else if(I.target===`condition`){let n=e.map(e=>Ue(e,t)),r=t.treeType===`context`&&w.actions.some(e=>e.kind===`store`);F(`conditions`,w.conditions.map((e,t)=>t===I.index?{...e,...r?{field:`eventPathExact`}:{},value:n.join(` | `)}:e))}else{let n=e.map(e=>Ue(e,t));F(`actions`,w.actions.map((e,t)=>t===I.index?e.kind===`download`?{...e,b:n.join(`, `)}:{...e,a:n.join(`, `)}:e))}L(null)},R=(e,t,n=`Browse…`)=>(0,U.jsxs)(b,{type:`button`,size:`sm`,variant:`outline`,className:`h-10 shrink-0 px-3`,title:n,onClick:()=>L({target:e,index:t}),children:[(0,U.jsx)(a,{className:`h-4 w-4 sm:mr-1.5`}),(0,U.jsx)(`span`,{className:`hidden sm:inline`,children:`Browse`})]}),z=ft(w?.conditions||[]),B=!!w?.conditions.some(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field)&&e.value.trim()),qe=e=>`${e.address}${e.address===`workspace:data`?` — managed blob store (default)`:e.address===`workspace:home`?` — workspace home folder`:e.driver?` — ${e.driver}`:``}`,V=(e,t,n,r=`workspace:home`)=>M.length?(0,U.jsxs)(`select`,{className:X,value:e,onChange:e=>t(e.target.value),children:[(0,U.jsx)(`option`,{value:``,children:n}),M.map(e=>(0,U.jsx)(`option`,{value:e.address,children:qe(e)},e.address)),e&&!M.some(t=>t.address===e)&&(0,U.jsx)(`option`,{value:e,children:e})]}):(0,U.jsx)(x,{className:y(Z,`font-mono`),placeholder:r,value:e,onChange:e=>t(e.target.value)}),Ye=v.filter(xt),H=v.filter(e=>!xt(e)),Ze=({rule:e})=>{let t=e.enabled!==!1,r=ht(e)!==null,i=S[e.id],a=ot(e.then?.[0]?.action||`link`),o=Ce(e);return(0,U.jsxs)(`div`,{className:y(`rule-card rounded-xl border bg-card p-4 transition-opacity`,!t&&`opacity-60`),children:[(0,U.jsx)(kt,{icon:a.icon,tone:a.tone}),(0,U.jsxs)(`div`,{className:`rule-card-content min-w-0 space-y-1.5`,children:[(0,U.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,U.jsx)(`h3`,{className:`text-base font-semibold leading-6`,children:e.description||e.id}),e.approval===!0&&(0,U.jsx)(`span`,{className:`rounded-full bg-warning/15 px-2 py-0.5 text-xs font-medium text-warning`,children:`needs approval`}),e.cascade===!0&&(0,U.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:`incl. automation-created`}),!r&&(0,U.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,title:`This rule uses matchers the builder cannot show; edit it as JSON.`,children:`JSON only`})]}),(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:_t(e,Ae)}),(0,U.jsxs)(`p`,{className:`flex items-start gap-1.5 text-sm`,children:[(0,U.jsx)(ne,{className:`mt-1 h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,U.jsx)(`span`,{children:bt(e)})]}),o.length>0&&(0,U.jsx)(`p`,{className:`truncate font-mono text-xs text-muted-foreground`,title:o.join(` | `),children:o.join(` | `)}),(0,U.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i?(0,U.jsxs)(`button`,{type:`button`,className:y(`text-left underline-offset-2 hover:underline`,i.last.status===`error`&&`text-destructive`,!n&&`cursor-default hover:no-underline`),title:n?`Show this rule's run log`:i.last.error||i.last.skipReason||``,onClick:()=>n?.(e.id),children:[`ran `,i.count,`×`,i.errors?` (${i.errors} failed)`:``,` · last `,i.last.status,` `,Ct(i.last.ts)]}):`not run yet`})]}),(0,U.jsxs)(`div`,{className:`rule-card-actions`,children:[(0,U.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":t,disabled:k,title:t?`Enabled — click to pause`:`Paused — click to enable`,onClick:()=>Pe(e.id),className:y(`mr-1 inline-flex h-6 w-11 items-center rounded-full p-0.5 transition-colors`,t?`bg-primary`:`bg-muted-foreground/30`),children:(0,U.jsx)(`span`,{className:y(`h-5 w-5 rounded-full bg-background shadow transition-transform`,t&&`translate-x-5`)})}),(0,U.jsxs)(b,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5`,title:e.when.eventPathExact===void 0?`Apply this rule to existing items (dry-run first)`:`Requires an original insert/link event. Current folder membership cannot reconstruct its destination.`,disabled:Ie!==null||e.when.eventPathExact!==void 0,onClick:()=>ze(e.id),children:[Ie===e.id?(0,U.jsx)(g,{className:`h-4 w-4 animate-spin`}):(0,U.jsx)(s,{className:`h-4 w-4`}),(0,U.jsx)(`span`,{className:`rule-card-action-label ml-1.5`,children:`Apply`})]}),(0,U.jsxs)(b,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5`,title:r?`Edit rule`:`Edit as JSON`,onClick:()=>Ve(e),children:[r?(0,U.jsx)(f,{className:`h-4 w-4`}):(0,U.jsx)(m,{className:`h-4 w-4`}),(0,U.jsx)(`span`,{className:`rule-card-action-label ml-1.5`,children:`Edit`})]}),(0,U.jsx)(b,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5 text-destructive hover:text-destructive`,title:`Delete rule`,onClick:()=>Fe(e.id),children:(0,U.jsx)(p,{className:`h-4 w-4`})})]})]})},Qe=(0,U.jsxs)(`div`,{className:`space-y-3`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,U.jsx)(`h3`,{className:`text-base font-semibold`,children:`What should happen automatically?`}),D&&(0,U.jsxs)(b,{size:`sm`,variant:`ghost`,onClick:()=>O(!1),children:[(0,U.jsx)(o,{className:`mr-1 h-4 w-4`}),` Close`]})]}),(0,U.jsx)(`div`,{className:`grid min-w-0 grid-cols-[repeat(auto-fill,minmax(min(100%,17rem),1fr))] gap-3`,children:dt.map(e=>(0,U.jsxs)(`button`,{type:`button`,onClick:()=>Be(e),className:`flex min-w-0 items-start gap-3 rounded-xl border bg-card p-4 text-left transition-colors hover:border-primary/50 hover:bg-accent/40`,children:[(0,U.jsx)(kt,{icon:e.icon,tone:e.tone,size:`lg`}),(0,U.jsxs)(`span`,{className:`min-w-0`,children:[(0,U.jsx)(`span`,{className:`block text-base font-semibold leading-6`,children:e.title}),(0,U.jsx)(`span`,{className:`mt-1 block break-words text-sm leading-relaxed text-muted-foreground`,children:e.blurb})]})]},e.id))})]});return(0,U.jsxs)(`div`,{className:`rule-builder min-w-0 space-y-5`,children:[!d&&(0,U.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,U.jsxs)(`div`,{className:`min-w-0 flex-[1_1_20rem]`,children:[(0,U.jsx)(`h2`,{className:`text-lg font-semibold`,children:`Rules`}),(0,U.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Rules run automatically as items arrive or get filed — no code needed. Stored in`,` `,(0,U.jsx)(`span`,{className:`font-mono`,children:`rules.json`}),` in the workspace git.`]})]}),(0,U.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[t&&(0,U.jsxs)(b,{variant:`ghost`,onClick:t,title:`Edit rules.json directly`,children:[(0,U.jsx)(m,{className:`mr-1.5 h-4 w-4`}),` JSON`]}),(0,U.jsxs)(b,{onClick:()=>{E(null),O(!0)},disabled:D,children:[(0,U.jsx)(c,{className:`mr-1.5 h-4 w-4`}),` New rule`]})]})]}),D&&!w&&Qe,w&&(0,U.jsxs)(`div`,{ref:Se,className:`scroll-mt-4 space-y-6 rounded-xl border bg-card p-4 sm:p-6`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,U.jsx)(`h3`,{className:`text-lg font-semibold`,children:w.id?`Edit rule`:`New rule`}),(0,U.jsxs)(b,{variant:`ghost`,size:`sm`,onClick:()=>E(null),children:[(0,U.jsx)(o,{className:`mr-1 h-4 w-4`}),` Cancel`]})]}),(0,U.jsx)(Q,{label:`Name`,hint:`Shown in the list and the run log.`,children:(0,U.jsx)(x,{className:`h-11 text-base`,placeholder:`Keep UI designs in Projects/Canvas/UI`,value:w.description,onChange:e=>F(`description`,e.target.value)})}),(0,U.jsxs)(`section`,{className:`space-y-4`,children:[(0,U.jsx)(Ot,{step:1,title:`When…`,hint:`What the rule reacts to. All conditions must match; repeat a condition for either/or.`}),(0,U.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-[minmax(0,220px)_1fr]`,children:[(0,U.jsx)(Q,{label:`Item`,children:(0,U.jsxs)(`select`,{className:X,value:w.schema,onChange:e=>F(`schema`,e.target.value),children:[Ae.map(e=>(0,U.jsx)(`option`,{value:e.value,children:e.label},e.value)),w.schema&&!Ae.some(e=>e.value===w.schema)&&(0,U.jsx)(`option`,{value:w.schema,children:w.schema.replace(/^data\/schema\//,``)})]})}),(0,U.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,U.jsxs)(`span`,{className:`text-sm font-medium`,children:[`Event `,(0,U.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(any of)`})]}),(0,U.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:tt.map(e=>{let t=w.events.includes(e.value);return(0,U.jsx)(Dt,{active:t,title:e.hint,onClick:()=>{let n=t?w.events.filter(t=>t!==e.value):[...w.events,e.value];n.length&&F(`events`,n)},children:e.label},e.value)})})]})]}),w.conditions.length>0&&(0,U.jsx)(`div`,{className:`space-y-2`,children:w.conditions.map((e,t)=>{let n=nt.find(t=>t.key===e.field);return(0,U.jsxs)(`div`,{className:`grid grid-cols-[2.25rem_1fr_auto] items-center gap-2 sm:grid-cols-[2.25rem_minmax(0,240px)_1fr_auto]`,children:[(0,U.jsx)(`span`,{className:`text-xs font-medium uppercase tracking-wide text-muted-foreground`,title:`Same condition again = either may match (OR); different conditions must all match (AND)`,children:w.conditions.slice(0,t).some(t=>it(t.field)===it(e.field))?`or`:`and`}),(0,U.jsx)(`select`,{className:X,value:e.field,onChange:e=>F(`conditions`,w.conditions.map((n,r)=>r===t?{...n,field:e.target.value}:n)),children:nt.map(e=>(0,U.jsx)(`option`,{value:e.key,children:e.label},e.key))}),(0,U.jsxs)(`div`,{className:`order-4 col-span-3 flex gap-2 sm:order-3 sm:col-span-1`,children:[(0,U.jsx)(x,{className:y(Z,`font-mono`),placeholder:n?.hint,value:e.value,onChange:e=>F(`conditions`,w.conditions.map((n,r)=>r===t?{...n,value:e.target.value}:n))}),[`path`,`pathExact`,`eventPathExact`].includes(e.field)&&R(`condition`,t,`Browse the workspace trees`)]}),(0,U.jsx)(b,{size:`sm`,variant:`ghost`,className:`order-3 h-10 w-10 p-0 text-muted-foreground sm:order-4`,title:`Remove condition`,onClick:()=>F(`conditions`,w.conditions.filter((e,n)=>n!==t)),children:(0,U.jsx)(o,{className:`h-4 w-4`})})]},t)})}),(0,U.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,U.jsxs)(b,{size:`sm`,variant:`outline`,onClick:()=>F(`conditions`,[...w.conditions,{field:w.schema===`email`?`from`:`path`,value:``}]),children:[(0,U.jsx)(c,{className:`mr-1 h-4 w-4`}),` Add condition`]}),(0,U.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[`Contains matches literal text. Regex is case-insensitive: enter the pattern without /…/ delimiters; | stays part of the expression. For other filters, separate alternatives with `,(0,U.jsx)(`span`,{className:`font-mono`,children:`|`}),`, e.g. `,(0,U.jsx)(`span`,{className:`font-mono`,children:`image/* | video/*`}),`.`]})]})]}),(0,U.jsxs)(`section`,{className:`space-y-4`,children:[(0,U.jsx)(Ot,{step:2,title:`Then…`,hint:`Actions run in order. The item keeps its id, tags and folders unless an action says otherwise.`}),w.actions.map((t,n)=>{let r=e=>F(`actions`,w.actions.map((t,r)=>r===n?{...t,...e}:t)),i=M.find(e=>e.address===t.a),a=i?.capabilities?.paths===!0,s=z&&a,c=ot(t.kind),l=n=>(0,U.jsxs)(`div`,{className:`space-y-3 rounded-lg border border-dashed p-3`,children:[(0,U.jsxs)(`p`,{className:`text-sm font-medium`,children:[`What to do with the `,n]}),(0,U.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,U.jsx)(Q,{label:`Save as a note at`,hint:`Context path by default, dir:/path for the directory tree.`,children:(0,U.jsx)(he,{inputClassName:Z,placeholder:`/notes/summaries (optional)`,value:t.notePath,onChange:e=>r({notePath:e}),fixedWorkspaceName:e,pickerTitle:`Save note under…`,onPickTarget:(e,t)=>r({notePath:t.treeType===`directory`?`dir:${e}`:e})})}),t.notePath.trim()&&(0,U.jsx)(Q,{label:`Note title`,children:(0,U.jsx)(x,{className:Z,placeholder:`Summary: {{doc.data.subject}}`,value:t.noteTitle,onChange:e=>r({noteTitle:e.target.value})})}),(0,U.jsx)(Q,{label:`Save as a file at`,hint:`Relative path under the workspace home folder or in the data blob store.`,children:(0,U.jsx)(x,{className:y(Z,`font-mono`),placeholder:`logs/agent.log (optional)`,value:t.filePath,onChange:e=>r({filePath:e.target.value})})}),t.filePath.trim()&&(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(Q,{label:`File lives in`,children:(0,U.jsxs)(`select`,{className:X,value:t.fileBackend,onChange:e=>r({fileBackend:e.target.value}),children:[(0,U.jsx)(`option`,{value:`home`,children:`the workspace home folder`}),(0,U.jsx)(`option`,{value:`data`,children:`the data blob store`})]})}),(0,U.jsx)(Q,{label:`Also file the saved file under`,hint:`Index it as a document at this tree path.`,children:(0,U.jsx)(he,{inputClassName:Z,placeholder:`/path (optional)`,value:t.fileInsert,onChange:e=>r({fileInsert:e}),fixedWorkspaceName:e,tabs:[`context`],pickerTitle:`File under…`,onPickTarget:e=>r({fileInsert:e})})})]})]}),(0,U.jsx)($,{checked:t.notifyReply,onChange:e=>r({notifyReply:e}),label:`Send me a notification with the result`})]}),u=Y(w.conditions),d=t.kind===`store`&&t.a&&(!t.recursive||s)?pt(t,w.conditions,i):null,f=t.kind===`extractAttachments`&&t.a?Ke(t.a,t.storeFolder,t.attachmentPath):null;return(0,U.jsxs)(`div`,{className:`space-y-4 rounded-xl border bg-background p-4`,children:[(0,U.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,U.jsx)(kt,{icon:c.icon,tone:c.tone}),(0,U.jsx)(`select`,{className:y(X,`flex-1 font-medium`),value:t.kind,onChange:e=>r(K(e.target.value)),children:at.map(e=>(0,U.jsx)(`option`,{value:e.key,children:e.label},e.key))}),(0,U.jsx)(b,{size:`sm`,variant:`ghost`,className:`h-10 w-10 shrink-0 p-0 text-muted-foreground`,title:`Remove action`,disabled:w.actions.length===1,onClick:()=>F(`actions`,w.actions.filter((e,t)=>t!==n)),children:(0,U.jsx)(o,{className:`h-4 w-4`})})]}),(t.kind===`link`||t.kind===`unlink`)&&(0,U.jsxs)(`div`,{className:`space-y-3`,children:[(0,U.jsx)(Q,{label:t.kind===`link`?`Folder(s)`:`Remove from folder(s)`,hint:`Context-tree path by default; dir:/path for the directory tree. Comma-separate several.`,children:(0,U.jsxs)(`div`,{className:`flex gap-2`,children:[(0,U.jsx)(x,{className:y(Z,`font-mono`),placeholder:t.kind===`link`?`/work/urgent or dir:/projects/x`:`/inbox or dir:/staging`,value:t.a,onChange:e=>r({a:e.target.value})}),R(`action`,n)]})}),t.kind===`link`&&(0,U.jsx)(Q,{label:`Tags`,hint:`Optional, comma-separated.`,children:(0,U.jsx)(x,{className:y(Z,`font-mono`),placeholder:`custom/design, ui`,value:t.b,onChange:e=>r({b:e.target.value})})}),(0,U.jsx)($,{checked:t.recursive,onChange:e=>r({recursive:e}),label:`Recreate sub-folder path in destination`,hint:B?`The part of the item's path below the "is under the folder" prefix is appended to the target: …/foo/a/b → target/a/b.`:`Needs an "is under the folder" condition to know where sub-folders start.`,disabled:!B})]}),t.kind===`moveMessage`&&(0,U.jsxs)(`div`,{className:`space-y-2`,children:[(0,U.jsx)(Q,{label:`Mail folder`,hint:`The folder on the email's own IMAP account, with / between levels (works for servers that use . too). {{YYYY}}, {{MM}}, {{DD}} = the email's date.`,children:(0,U.jsx)(x,{className:y(Z,`font-mono`),placeholder:`INBOX/Accounting/{{YYYY}}/Expenses`,value:t.a,onChange:e=>r({a:e.target.value})})}),(0,U.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Moves the message on the mail server, like dragging it in a mail client. Put this after Extract attachments so the files are copied first. The folder must already exist on the server; subscribe to it in the mailbox settings to see the moved mail in Canvas.`})]}),t.kind===`tag`&&(0,U.jsx)(Q,{label:`Tags`,hint:`Comma-separated.`,children:(0,U.jsx)(x,{className:y(Z,`font-mono`),placeholder:`urgent, follow-up`,value:t.a,onChange:e=>r({a:e.target.value})})}),t.kind===`store`&&(0,U.jsxs)(`div`,{className:`space-y-4`,children:[(0,U.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,U.jsx)(Q,{label:`Storage backend`,hint:`Where the file's bytes should live. Only writable backends are listed.`,children:V(t.a,e=>r({a:e}),`pick a backend…`)}),(0,U.jsx)(Q,{label:`Destination root folder`,hint:`Choose the folder beneath which the path will be recreated. Leave empty to use the backend root.`,children:(0,U.jsxs)(`div`,{className:`flex gap-2`,children:[(0,U.jsx)(x,{className:y(Z,`font-mono`),placeholder:`Projects/Canvas/UI`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),R(`storeFolder`,n,`Browse storage backends`)]})}),(0,U.jsx)(Q,{label:`File name`,children:(0,U.jsx)(`select`,{className:X,value:t.storeName,onChange:e=>r({storeName:e.target.value}),children:ct.map(e=>(0,U.jsx)(`option`,{value:e.value,children:e.label},e.value))})}),(0,U.jsx)(Q,{label:`Move or copy`,hint:t.storeMode===`move`?`Remove only the selected source copy after the destination is safely stored.`:`Preserve every existing copy.`,children:(0,U.jsx)(Et,{value:t.storeMode,onChange:e=>r({storeMode:e}),options:[{value:`copy`,label:`Copy`},{value:`move`,label:`Move`}]})}),t.storeMode===`move`&&(0,U.jsx)(Q,{className:`sm:col-span-2`,label:`Move bytes from (required)`,hint:`Context membership does not identify a source copy. If the file is absent here, nothing is moved. Multiple locations on this backend make the move ambiguous; use copy.`,children:V(t.storeFrom,e=>r({storeFrom:e}),`choose a source backend…`,`workspace:data`)}),t.storeName===`custom`&&(0,U.jsx)(Q,{className:`sm:col-span-2`,label:`Name template`,hint:`Tokens: {{YYYY}} {{MM}} {{DD}} {{HH}} {{mm}} {{ss}} (photo capture time when present), {{ext}} {{basename}} {{filename}} {{title}} {{id}}, plus {{doc.…}} fields. Slashes create sub-folders.`,children:(0,U.jsx)(x,{className:y(Z,`font-mono`),placeholder:`{{YYYY}}-{{MM}}-{{DD}} {{title}}{{ext}}`,value:t.b,onChange:e=>r({b:e.target.value})})})]}),(0,U.jsx)($,{checked:t.recursive,onChange:e=>r({recursive:e}),label:u===null?`Recreate sub-folder path in destination`:`Recreate directory path in destination`,hint:a?z?u===null?`The path below the source folder is appended beneath the destination root: …/UI/mobile → Root/mobile. Missing destination folders are created.`:`Only inserts or links directly into ctx:${u} trigger this rule. Its full path is appended beneath the destination root; descendant inserts do not match.`:`For Context, choose one folder with “is inserted / linked directly into”. Directory and Backends sources can include sub-folders.`:`Choose a destination that reports support for folder paths. Content-addressed blob stores cannot recreate sub-folder paths.`,disabled:!s&&!t.recursive}),d&&(0,U.jsxs)(`div`,{className:`space-y-1.5 rounded-lg bg-muted/60 px-3 py-3 text-sm`,"aria-live":`polite`,children:[(0,U.jsx)(`p`,{className:`font-medium`,children:`Destination preview`}),(0,U.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Root folder: `,(0,U.jsxs)(`span`,{className:`break-all font-mono`,children:[d.root,`/`]})]}),t.recursive&&(0,U.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Path added beneath it: `,(0,U.jsxs)(`span`,{className:`break-all font-mono`,children:[d.recreated||`(root)`,`/`]})]}),(0,U.jsx)(`p`,{className:`break-all font-mono`,children:d.result})]}),(0,U.jsxs)(`details`,{className:`group rounded-lg border`,children:[(0,U.jsxs)(`summary`,{className:`flex cursor-pointer select-none items-center gap-2 px-3 py-2 text-sm font-medium`,children:[(0,U.jsx)(ee,{className:`h-4 w-4 transition-transform group-open:rotate-180`}),` More options`]}),(0,U.jsxs)(`div`,{className:`grid gap-4 border-t p-3 sm:grid-cols-2`,children:[t.storeMode===`copy`&&(0,U.jsx)(Q,{label:`Copy bytes from`,hint:`Optional source restriction. Default: any readable copy outside the destination backend.`,children:V(t.storeFrom,e=>r({storeFrom:e}),`any readable source`,`workspace:data (optional)`)}),(0,U.jsx)(Q,{label:`If the name is already taken`,children:(0,U.jsxs)(`select`,{className:X,value:t.storeConflict,onChange:e=>r({storeConflict:e.target.value}),children:[(0,U.jsx)(`option`,{value:`rename`,children:`add -1, -2, … to the name`}),(0,U.jsx)(`option`,{value:`error`,children:`skip the file`}),(0,U.jsx)(`option`,{value:`overwrite`,children:`overwrite the existing file`})]})})]})]}),(0,U.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The item keeps its id and virtual tree memberships. A move removes the chosen physical source location from the backend tree.`})]}),t.kind===`extractAttachments`&&(0,U.jsxs)(`div`,{className:`space-y-4`,children:[(0,U.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,U.jsx)(Q,{label:`Attachment types`,hint:`MIME types, comma-separated. application/pdf for PDFs, image/* for images, or * for all.`,children:(0,U.jsx)(x,{className:y(Z,`font-mono`),placeholder:`application/pdf`,value:t.attachmentMime,onChange:e=>r({attachmentMime:e.target.value})})}),(0,U.jsx)(Q,{label:`Attachment filename contains`,hint:`Optional: invoice, faktura, or another literal filename fragment. Every selected attachment must also match its type.`,children:(0,U.jsx)(x,{className:Z,placeholder:`Any matching filename`,value:t.attachmentName,onChange:e=>r({attachmentName:e.target.value})})}),(0,U.jsx)(Q,{label:`Storage backend`,hint:`Choose a writable backend that supports folder paths.`,children:V(t.a,e=>r({a:e}),`pick a backend…`)}),(0,U.jsx)(Q,{label:`Destination root folder`,hint:`Choose the folder beneath which date subfolders will be created. Leave empty to use the backend root.`,children:(0,U.jsxs)(`div`,{className:`flex gap-2`,children:[(0,U.jsx)(x,{className:y(Z,`font-mono`),placeholder:`Accounting`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),R(`storeFolder`,n,`Browse storage backends`)]})}),(0,U.jsx)(Q,{label:`Sub-folder path template`,hint:`Appended beneath the root folder. {{YYYY}} = year, {{MM}} = month, {{DD}} = day of the email. Leave empty to file directly in the root folder.`,children:(0,U.jsx)(x,{className:y(Z,`font-mono`),placeholder:`No subfolders`,value:t.attachmentPath,onChange:e=>r({attachmentPath:e.target.value})})}),(0,U.jsx)(Q,{label:`If the attachment name is already taken`,children:(0,U.jsxs)(`select`,{className:X,value:t.storeConflict,onChange:e=>r({storeConflict:e.target.value}),children:[(0,U.jsx)(`option`,{value:`rename`,children:`add -1, -2, … to the name`}),(0,U.jsx)(`option`,{value:`error`,children:`skip the file and report the conflict`})]})})]}),!a&&(0,U.jsx)(`p`,{className:`text-sm text-amber-700 dark:text-amber-400`,children:`This destination has not reported support for folder paths. Select a supported backend before saving.`}),f&&(0,U.jsxs)(`div`,{className:`space-y-1.5 rounded-lg bg-muted/60 px-3 py-3 text-sm`,"aria-live":`polite`,children:[(0,U.jsx)(`p`,{className:`font-medium`,children:`Destination preview`}),(0,U.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Example email dated `,f.date,`. Each email supplies its own date.`]}),(0,U.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Root folder: `,(0,U.jsxs)(`span`,{className:`break-all font-mono`,children:[f.root,`/`]})]}),(0,U.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Path added beneath it: `,(0,U.jsx)(`span`,{className:`break-all font-mono`,children:f.added?`${f.added}/`:`(none)`})]}),(0,U.jsx)(`p`,{className:`break-all font-mono`,children:f.result})]}),(0,U.jsx)($,{checked:t.includeInline,onChange:e=>r({includeInline:e}),label:`Include inline attachments`,hint:`Off by default, so signature images and embedded resources are excluded.`}),(0,U.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Copies matching attachments and keeps the email and its original files. Missing folders are created on the backend. Dates use the email's sent date (received/content date, then creation date if absent), in the server's timezone. This does not read the invoice date from the PDF.`}),(0,U.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Use Apply on the saved rule to process existing mail within the selected batch size. Add a subject or attachment filename condition if you need to distinguish invoices from other PDFs.`})]}),t.kind===`download`&&(0,U.jsxs)(`div`,{className:`space-y-4`,children:[(0,U.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,U.jsx)(Q,{label:`Download`,hint:G.find(e=>e.value===t.dlKind)?.hint,children:(0,U.jsx)(`select`,{className:X,value:t.dlKind,onChange:e=>r({dlKind:e.target.value}),children:G.map(e=>(0,U.jsx)(`option`,{value:e.value,children:e.label},e.value))})}),t.dlKind===`website`?(0,U.jsx)(Q,{label:`Mirror depth`,hint:`How many link hops to follow on the same site (1–5).`,children:(0,U.jsx)(x,{type:`number`,min:1,max:5,className:y(Z,`sm:max-w-32`),value:t.dlDepth,onChange:e=>r({dlDepth:e.target.value})})}):(0,U.jsx)(`div`,{className:`hidden sm:block`}),(0,U.jsx)(Q,{label:`Storage backend`,hint:`Where the downloaded file's bytes should live.`,children:V(t.a,e=>r({a:e}),`workspace:home (default)`)}),(0,U.jsx)(Q,{label:`Folder on that backend`,hint:`Relative to the backend root.`,children:(0,U.jsxs)(`div`,{className:`flex gap-2`,children:[(0,U.jsx)(x,{className:y(Z,`font-mono`),placeholder:`Downloads`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),R(`storeFolder`,n,`Browse storage backends`)]})}),(0,U.jsx)(Q,{label:`File the download under`,hint:`Leave empty to file it in the same folder(s) as the link. Comma-separate several.`,children:(0,U.jsxs)(`div`,{className:`flex gap-2`,children:[(0,U.jsx)(x,{className:y(Z,`font-mono`),placeholder:`same folders as the link`,value:t.b,onChange:e=>r({b:e.target.value})}),R(`action`,n)]})}),(0,U.jsx)(Q,{label:`Tags for the download`,hint:`Optional, comma-separated.`,children:(0,U.jsx)(x,{className:y(Z,`font-mono`),placeholder:`downloaded, custom/paper`,value:t.dlTags,onChange:e=>r({dlTags:e.target.value})})})]}),(0,U.jsx)($,{checked:t.recursive,onChange:e=>r({recursive:e}),label:`Recreate sub-folder path in destination`,hint:B?`A link filed under …/folder/a/b is downloaded into Folder/a/b.`:`Add an "is under the folder" condition to mirror sub-folders.`,disabled:!B}),(0,U.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`The link stays as it is; the download becomes a new file item next to it. Each link is downloaded once per rule. Videos need `,(0,U.jsx)(`span`,{className:`font-mono`,children:`yt-dlp`}),`, pages and websites `,(0,U.jsx)(`span`,{className:`font-mono`,children:`wget`}),` on the server.`]})]}),t.kind===`unstore`&&(0,U.jsxs)(`div`,{className:`space-y-4`,children:[(0,U.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,U.jsx)(Q,{label:`Delete the file from`,children:V(t.a,e=>r({a:e}),`pick a backend…`,`workspace:data`)}),(0,U.jsx)(Q,{label:`…but only once it is also on`,hint:`Safety: the copy is dropped only after another backend holds the file.`,children:V(t.b,e=>r({b:e}),`anywhere else`,`workspace:home (optional)`)})]}),(0,U.jsx)($,{checked:t.keepLast,onChange:e=>r({keepLast:e}),label:`Never delete the last copy`,hint:`Off means the rule may delete the only remaining copy of a file. Leave it on unless you mean exactly that.`}),(0,U.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Deletes the stored bytes on that backend only — copies elsewhere and the item itself are kept.`})]}),t.kind===`sendFile`&&(0,U.jsxs)(`div`,{className:`space-y-4`,children:[(0,U.jsx)(Q,{label:`Files to send`,children:(0,U.jsxs)(`select`,{className:X,value:t.sendSource,onChange:e=>r({sendSource:e.target.value}),children:[(0,U.jsx)(`option`,{value:`document`,children:`The file that triggered this rule`}),(0,U.jsx)(`option`,{value:`attachments`,children:`Matching attachments from the email`}),(0,U.jsx)(`option`,{value:`download`,children:`Files from an earlier Download action`})]})}),t.sendSource===`attachments`&&(0,U.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,U.jsx)(Q,{label:`Attachment types`,hint:`application/pdf for invoices; * for all files.`,children:(0,U.jsx)(x,{className:Z,value:t.attachmentMime,onChange:e=>r({attachmentMime:e.target.value})})}),(0,U.jsx)(Q,{label:`Attachment filename contains`,hint:`Optional literal filename fragment.`,children:(0,U.jsx)(x,{className:Z,placeholder:`invoice`,value:t.attachmentName,onChange:e=>r({attachmentName:e.target.value})})})]}),t.sendSource===`attachments`&&(0,U.jsx)($,{checked:t.includeInline,onChange:e=>r({includeInline:e}),label:`Include inline attachments`,hint:`Signature images are excluded by default.`}),(0,U.jsx)(Q,{label:`Sending account`,hint:`Enable sending for the account in Connected services.`,children:(0,U.jsxs)(`select`,{className:X,value:t.a?`${t.sendDriver}:${t.a}`:``,onChange:e=>{let t=ve.find(t=>`${t.driver}:${t.address}`===e.target.value);t&&r({a:t.address,sendDriver:t.driver,b:``})},children:[(0,U.jsx)(`option`,{value:``,disabled:!0,children:`Choose email, WhatsApp or Slack…`}),t.a&&!ve.some(e=>e.driver===t.sendDriver&&e.address===t.a)&&(0,U.jsxs)(`option`,{value:`${t.sendDriver}:${t.a}`,disabled:!0,children:[t.sendDriver,`: `,t.a,` (unavailable)`]}),ve.map(e=>(0,U.jsxs)(`option`,{value:`${e.driver}:${e.address}`,disabled:!e.canSend,children:[e.driver===`imap`?`Email (SMTP)`:e.driver===`whatsapp`?`WhatsApp`:`Slack`,` · `,e.from||e.address,e.canSend?``:` — sending disabled`]},`${e.driver}:${e.address}`))]})}),be&&(0,U.jsx)(`p`,{className:`text-xs text-destructive`,role:`status`,children:be}),(0,U.jsx)(Q,{label:t.sendDriver===`imap`?`Destination email address`:`Destination conversation`,hint:t.sendDriver===`imap`?`The accounting ingestion address; separate multiple recipients with commas.`:t.sendDriver===`slack`?`A configured Slack channel ID or name. The account needs files:write permission.`:`A configured WhatsApp chat ID, e.g. 421…@s.whatsapp.net or …@g.us.`,children:(0,U.jsx)(x,{className:Z,value:t.b,placeholder:t.sendDriver===`imap`?`invoices@accounting-firm.example`:t.sendDriver===`slack`?`C0123456789`:`421…@s.whatsapp.net`,onChange:e=>r({b:e.target.value})})}),t.sendDriver===`imap`&&(0,U.jsx)(Q,{label:`Email subject`,hint:`{{file.name}} inserts the attachment filename.`,children:(0,U.jsx)(x,{className:Z,value:t.sendSubject,onChange:e=>r({sendSubject:e.target.value})})}),(0,U.jsx)(Q,{label:t.sendDriver===`imap`?`Email body (optional)`:`Message / caption (optional)`,hint:`Templates: {{file.name}}, {{doc.data.subject}}, {{doc.data.title}}.`,children:(0,U.jsx)(`textarea`,{className:`min-h-20 w-full rounded-md border bg-background p-3 text-sm`,value:t.sendMessage,onChange:e=>r({sendMessage:e.target.value})})}),(0,U.jsxs)(`div`,{className:`rounded-lg border bg-muted/30 p-3 text-sm`,"aria-label":`File delivery preview`,children:[t.sendSource===`attachments`?`Each matching email attachment`:t.sendSource===`download`?`Each downloaded file`:`The triggering file`,` → `,t.sendDriver===`imap`?`email attachment`:t.sendDriver===`slack`?`Slack file upload`:`WhatsApp document`,` → `,t.b||`choose a destination`]}),(0,U.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Sends each file in a separate message and keeps the original. Maximum 18 MB per file. Replaying this rule does not resend the same file version to the same destination. Unconfirmed deliveries are recorded for review, not retried automatically.`}),t.sendSource===`document`&&(0,U.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`For files created by another automation, enable this rule’s option to also run on automation events.`})]}),t.kind===`notify`&&(0,U.jsx)(Q,{label:`Notification`,hint:`Notifies you through your bound channel, or in Canvas. Templates: {{doc.data.subject}}, {{doc.data.from}}, {{doc.data.title}}…`,children:(0,U.jsx)(x,{className:Z,placeholder:`New mail from {{doc.data.from}}: {{doc.data.subject}}`,value:t.a,onChange:e=>r({a:e.target.value})})}),t.kind===`delete`&&(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Removes the item from the Canvas index. Files, blobs and mail on storage backends stay untouched.`}),t.kind===`destroy`&&(0,U.jsx)(`p`,{className:`rounded-lg border border-destructive/40 bg-destructive/5 p-3 text-sm text-destructive`,children:`⚠ Irreversible: deletes the stored bytes too (blobs, workspace files, mail on the server), then removes the item from the index.`}),t.kind===`agent`&&(0,U.jsxs)(`div`,{className:`space-y-3`,children:[(0,U.jsx)(Q,{label:`Agent`,hint:`The agent's slug.`,children:(0,U.jsx)(x,{className:y(Z,`font-mono sm:max-w-xs`),placeholder:`assistant`,value:t.a,onChange:e=>r({a:e.target.value})})}),(0,U.jsx)(Q,{label:`Prompt`,hint:`Templates use indexed fields: {{doc.id}}, {{doc.data.subject}}, {{doc.data.bodyPreview}} (emails), {{doc.data.url}}… Ask the agent to use canvas_get for full email content. Objects are inserted as JSON.`,children:(0,U.jsx)(`textarea`,{className:`min-h-28 w-full rounded-md border bg-background p-3 text-sm outline-none focus:ring-2 focus:ring-ring`,placeholder:`Read email #{{doc.id}} in full with canvas_get and summarize it in plain markdown.
4
+
5
+ Subject: {{doc.data.subject}}
6
+ Preview: {{doc.data.bodyPreview}}`,value:t.b,onChange:e=>r({b:e.target.value})})}),l(`reply`)]}),t.kind===`script`&&(0,U.jsxs)(`div`,{className:`space-y-3`,children:[(0,U.jsx)(Q,{label:`Script`,hint:`From the Scripts section of this workspace.`,children:ge.length?(0,U.jsxs)(`select`,{className:y(X,`font-mono sm:max-w-md`),value:t.a,onChange:e=>r({a:e.target.value}),children:[(0,U.jsx)(`option`,{value:``,children:`pick a script…`}),ge.map(e=>(0,U.jsx)(`option`,{value:`scripts/${e}`,children:e},e))]}):(0,U.jsx)(x,{className:y(Z,`font-mono sm:max-w-md`),placeholder:`scripts/my-script.sh`,value:t.a,onChange:e=>r({a:e.target.value})})}),l(`output`)]})]},n)}),(0,U.jsxs)(b,{size:`sm`,variant:`outline`,onClick:()=>F(`actions`,[...w.actions,K(`tag`)]),children:[(0,U.jsx)(c,{className:`mr-1 h-4 w-4`}),` Add another action`]})]}),(0,U.jsxs)(`section`,{className:`space-y-3`,children:[(0,U.jsx)(Ot,{step:3,title:`Options`}),(0,U.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,U.jsx)($,{checked:w.approval,onChange:e=>F(`approval`,e),label:`Ask me before running`,hint:`Actions are held in the Pending queue for review — approve (optionally amended) or decline — instead of running automatically.`}),(0,U.jsx)($,{checked:w.cascade,onChange:e=>F(`cascade`,e),label:`Also react to items created by automation`,hint:`Off by default so rules, hooks and agents cannot trigger each other in a loop. A server-side depth limit still stops runaway chains.`})]})]}),(0,U.jsxs)(`div`,{className:`flex flex-wrap gap-2 border-t pt-4`,children:[(0,U.jsxs)(b,{className:`h-10 px-5`,onClick:Ne,disabled:k||de,children:[k?(0,U.jsx)(g,{className:`mr-1.5 h-4 w-4 animate-spin`}):(0,U.jsx)(i,{className:`mr-1.5 h-4 w-4`}),` `,w.id?`Save changes`:`Create rule`]}),(0,U.jsx)(b,{className:`h-10`,variant:`outline`,onClick:()=>{E(null),te?.()},children:`Cancel`})]})]}),I&&(0,U.jsx)(me,{onClose:()=>L(null),children:(0,U.jsx)(ce,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,fixedWorkspaceName:e,multiple:I.target!==`storeFolder`&&!(I.target===`condition`&&w?.actions.some(e=>e.kind===`store`)),tabs:I.target===`condition`?[`context`,`directory`,`backends`]:I.target===`storeFolder`?[`backends`]:[`context`,`directory`],title:I.target===`condition`?`Choose source folder…`:I.target===`storeFolder`?`Store files under…`:`File into…`,confirmLabel:I.target===`storeFolder`?`Use folder`:`Use path`,onConfirm:Ge,onClose:()=>L(null)})}),!d&&(de?(0,U.jsx)(`p`,{className:`rounded-xl border p-6 text-center text-sm text-muted-foreground`,children:`Loading…`}):v.length===0?!D&&!w&&(0,U.jsxs)(`div`,{className:`space-y-4`,children:[(0,U.jsxs)(`div`,{className:`rounded-xl border border-dashed p-6 text-center`,children:[(0,U.jsx)(`p`,{className:`text-base font-medium`,children:`No rules yet`}),(0,U.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:`Pick a starting point below, or right-click a folder in the tree and choose “Create rule…”.`})]}),Qe]}):(0,U.jsxs)(`div`,{className:`space-y-6`,children:[Ye.length>0&&(0,U.jsxs)(`section`,{className:`space-y-3`,children:[(0,U.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-sm text-muted-foreground`,children:[(0,U.jsxs)(`h3`,{className:`flex items-center gap-2 font-semibold uppercase tracking-wide`,children:[(0,U.jsx)(ie,{className:`h-4 w-4 shrink-0`}),` Folder & storage rules`]}),(0,U.jsx)(`p`,{children:`Right-click a folder in the tree to add one`})]}),(0,U.jsx)(`div`,{className:`space-y-3`,children:Ye.map(e=>(0,U.jsx)(Ze,{rule:e},e.id))})]}),H.length>0&&(0,U.jsxs)(`section`,{className:`space-y-3`,children:[Ye.length>0&&(0,U.jsxs)(`h3`,{className:`flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-muted-foreground`,children:[(0,U.jsx)(ae,{className:`h-4 w-4`}),` Other rules`]}),(0,U.jsx)(`div`,{className:`space-y-3`,children:H.map(e=>(0,U.jsx)(Ze,{rule:e},e.id))})]})]}))]})}function jt(e,t){let n=t.split(`/`).filter(Boolean);if(e!==`backends`||n[0]!==`Trash`)return null;try{return{backend:n[1]?decodeURIComponent(n[1]):null,prefix:n.slice(2).join(`/`)}}catch{return null}}function Mt(e,t=``){return`/Trash${e?`/${encodeURIComponent(e)}`:``}${t?`/${t}`:``}`}function Nt(e,t=``){let n=new Map,r=[],i=t?`${t}/`:``;for(let t of e){if(!t.key.startsWith(i))continue;let e=t.key.slice(i.length);if(!e)continue;let a=e.indexOf(`/`);if(a>=0){let r=e.slice(0,a),o=i+r,s=n.get(o)??{id:`folder:${o}`,name:r,key:o,directory:!0,navigable:!0,items:[]};s.items.push(t),n.set(o,s)}else r.push({id:t.id,name:e,key:t.key,directory:t.type===`directory`,navigable:!1,items:[t]})}return[...n.values(),...r].sort((e,t)=>Number(t.directory)-Number(e.directory)||e.name.localeCompare(t.name)||t.items[0].deletedAt-e.items[0].deletedAt||e.id.localeCompare(t.id))}var Pt=(e,t)=>`${oe.workspaces}/${encodeURIComponent(e)}/backends/file/${encodeURIComponent(t)}/trash`;async function Ft(e,t){let n=[],r=new Set,i=null,a=null;do{let o=new URLSearchParams({limit:`1000`,...i?{cursor:i}:{}}),s=await S.get(`${Pt(e,t)}?${o}`);if(n.push(...s.items),a=s.retention?.days??null,i=s.cursor,i&&r.has(i))throw Error(`Trash listing returned a repeated cursor`);i&&r.add(i)}while(i);return{items:n,days:a}}function It(e,t,n){return Rt(e,t,n,`restore`)}function Lt(e,t,n){return Rt(e,t,n,`discard`)}async function Rt(e,t,n,r){let i=[...new Set(n)],a=[];try{for(let n=0;n<i.length;n+=100){let o=await S.post(`${Pt(e,t)}/${r}`,{ids:i.slice(n,n+100)});a.push(...o.results)}return a}finally{fe(e,`backends`),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:`backends`}})),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e}})),window.dispatchEvent(new CustomEvent(`workspace:trash:refresh`,{detail:{workspaceName:e,backend:t}}))}}async function zt(e,t){let n=jt(`backends`,t);if(!n?.backend)return;let{items:r}=await Ft(e,n.backend),i=r.filter(e=>!n.prefix||e.key===n.prefix||e.key.startsWith(`${n.prefix}/`)).sort((e,t)=>t.deletedAt-e.deletedAt),a=await It(e,n.backend,i.map(e=>e.id)),o=a.filter(e=>!e.ok);if(o.length)throw Error(`${a.length-o.length} restored; ${o.length} remain in Trash. Existing paths were kept.`)}function Bt(e,t){if(!t.length)return!1;let n=[...new Set(t.map(e=>e.key))],r=n.slice(0,5).join(`
7
+ `)+(n.length>5?`\n…and ${n.length-5} more paths`:``);return window.confirm(`Permanently delete ${t.length} Trash item(s) from ${e}?\n\n${r}\n\nDeleted folders include all their contents. This cannot be undone. Files currently at the original paths are kept.`)}async function Vt(e,t){let n=jt(`backends`,t);if(!n?.backend)return;let{items:r}=await Ft(e,n.backend),i=r.filter(e=>!n.prefix||e.key===n.prefix||e.key.startsWith(`${n.prefix}/`));if(!Bt(n.backend,i))return;let a=await Lt(e,n.backend,i.map(e=>e.id)),o=a.filter(e=>!e.ok);if(o.length)throw Error(`${a.length-o.length} deleted; ${o.length} remain in Trash. ${o[0].message||o[0].reason||`Please retry.`}`)}var Ht=new Map;function Ut(e,t,n,r,i,a){let o=JSON.stringify([t,n,r,a]),s=Ht.get(o);if(s)return s;let c=(async()=>{let o=e({title:`Resyncing…`,description:r});try{for(a?await de(t,n,r,a):await w(t,n,r);;){let e=await le(t,n,r);i?.(e);let s=a?e.containers?.find(e=>e.name===a):void 0;if(a?s?.status!==`syncing`:!e.resyncing&&e.status!==`syncing`){let i=s?s.lastError:e.lastError;if(i)throw Error(i);o.done({title:e.resyncCancelledAt?`Resync stopped`:`Resync complete`,description:`${r}${n!==`imap`&&e.progress?` · ${e.progress.scanned} files scanned`:``}`}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:t,treeName:`backends`}}));return}let c=n===`imap`?void 0:e.progress;o.update({title:`Resyncing…`,description:`${r}${c?` · ${c.scanned}${c.total==null?``:` / ${c.total}`} files scanned`:``}`}),await new Promise(e=>setTimeout(e,2e3))}}catch(e){throw o.fail({title:`Resync needs attention`,description:`${r}: ${e instanceof Error?e.message:String(e)}`,variant:`destructive`}),e}})();return Ht.set(o,c),c.finally(()=>{Ht.get(o)===c&&Ht.delete(o)}).catch(()=>{}),c}export{je as A,I as B,Ee as C,O as D,Fe as E,D as F,Ie as H,ke as I,Me as L,Le as M,ve as N,He as O,_e as P,L as R,Ae as S,Ue as T,be as U,k as V,we as W,Je as _,Ft as a,Re as b,jt as c,At as d,$e as f,Ye as g,Qe as h,Vt as i,xe as j,De as k,Mt as l,Xe as m,Bt as n,It as o,Ze as p,Lt as r,zt as s,Ut as t,Nt as u,P as v,A as w,Pe as x,Ge as y,Te as z};
@@ -0,0 +1 @@
1
+ import{c as e,t}from"./api-CA6WiiYM.js";async function n(n,r){return t.post(`${e.workspaces}/${n}/blobs`,r,{headers:{"Content-Type":`application/octet-stream`}})}async function r(n,r){return t.post(`${e.workspaces}/${n}/blobs/exists`,{checksums:r})}async function i(n,r,i,{ifMatch:a,contentType:o}={}){let s=r.key.split(`/`).map(encodeURIComponent).join(`/`),c=`${e.workspaces}/${encodeURIComponent(n)}/backends/${encodeURIComponent(r.driver)}/${encodeURIComponent(r.address)}/objects/${s}`;return t.put(c,i,{headers:{"Content-Type":o||`application/octet-stream`,"X-Canvas-Mtime":String(Date.now()),...a?{"If-Match":`"${a}"`}:{"If-None-Match":`*`}}})}function a(t,n,{onProgress:r,signal:i,sha256:a}={}){return n.size>=8388608?d(t,n,{sha256:a,onProgress:r,signal:i}):f(`${e.workspaces}/${t}/blobs`,`POST`,n,{onProgress:r,signal:i})}function o(t,n,r,i={}){if(r.size>=8388608)return d(t,r,{...i,target:{type:`object`,...n,ifNoneMatch:`*`,mtime:r.lastModified,...r.type?{mimeType:r.type}:{}}});let a=n.key.split(`/`).map(encodeURIComponent).join(`/`);return f(`${e.workspaces}/${encodeURIComponent(t)}/backends/${encodeURIComponent(n.driver)}/${encodeURIComponent(n.address)}/objects/${a}`,`PUT`,r,i,{"If-None-Match":`*`,"X-Canvas-Mtime":String(r.lastModified)})}var s=8388608,c=10,l=(e,t)=>new Promise((n,r)=>{if(t?.aborted){r(new DOMException(`Upload aborted`,`AbortError`));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(new DOMException(`Upload aborted`,`AbortError`))};t?.addEventListener(`abort`,a,{once:!0})});function u(e){return`${e.name}:${e.size}:${e.lastModified}`}async function d(n,r,{sha256:i,target:a={type:`blob`},onProgress:o,signal:s}){let d=`${e.workspaces}/${encodeURIComponent(n)}/uploads`,p=await t.post(d,{size:r.size,...i?{sha256:i}:{fingerprint:u(r)},target:a}),m=`${d}/${p.id}`,h=0,g=!1;for(;p.state===`open`||p.state===`finalizing`||p.state===`failed`&&p.error?.retryable&&h===0;){if(s?.aborted)throw new DOMException(`Upload aborted`,`AbortError`);try{if(g){p=await t.get(m),g=!1;continue}if(p.state===`finalizing`){await l(1e3,s),g=!0;continue}let e=p.offset,n=p.offset;p=await f(m,`PATCH`,r.slice(e),{signal:s,onProgress:o?t=>o(e+t,r.size):void 0},{"Content-Type":`application/offset+octet-stream`,"Upload-Offset":String(e)}),p.state===`failed`?h++:(p.offset>n||p.state!==`open`)&&(h=0)}catch(e){if(e instanceof DOMException&&e.name===`AbortError`||++h>=c)throw e;await l(Math.min(3e4,1e3*2**(h-1)),s),g=!0}}if(p.state!==`complete`)throw Error(p.error?.message||`Upload failed`);return p.result}function f(e,t,n,{onProgress:r,signal:i},a={}){return new Promise((o,s)=>{if(i?.aborted){s(new DOMException(`Upload aborted`,`AbortError`));return}let c=new XMLHttpRequest;c.open(t,e),c.withCredentials=!0,c.responseType=`json`;for(let[e,t]of Object.entries({"Content-Type":`application/octet-stream`,...a}))c.setRequestHeader(e,t);let l=localStorage.getItem(`authToken`);l&&c.setRequestHeader(`Authorization`,`Bearer ${l}`),r&&c.upload.addEventListener(`progress`,e=>{e.lengthComputable&&r(e.loaded,e.total)});let u=()=>c.abort();i?.addEventListener(`abort`,u,{once:!0}),c.addEventListener(`load`,()=>{i?.removeEventListener(`abort`,u);let e=c.response;c.status>=200&&c.status<300&&e?.payload?o(e.payload):s(Error(c.status===412?`A file with this name already exists. Rename the file before uploading; nothing was overwritten.`:e?.message||`Upload failed (HTTP ${c.status})`))}),c.addEventListener(`error`,()=>{i?.removeEventListener(`abort`,u),s(Error(`Network error during upload`))}),c.addEventListener(`abort`,()=>{i?.removeEventListener(`abort`,u),s(new DOMException(`Upload aborted`,`AbortError`))}),c.send(n)})}export{a,n as i,r as n,i as o,o as r,s as t};
@@ -0,0 +1 @@
1
+ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{l as t,u as n}from"./code-editor-BOIngd5F.js";import{yi as r}from"./ui-BSqPn1LJ.js";import{i}from"./utils-BxVxyehK.js";import{t as a}from"./utils-2pl1SbIp.js";var o=e(n(),1),s=i([`inline-flex items-center justify-center gap-2 whitespace-nowrap`,`text-sm transition-colors`,`rounded-(--btn-radius) font-(number:--btn-font-weight)`,`focus-ring`,`disabled:pointer-events-none disabled:opacity-50`,`[&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0`],{variants:{variant:{default:`bg-primary text-primary-foreground shadow-elevation-1 hover:bg-primary/90`,destructive:`bg-destructive text-destructive-foreground shadow-elevation-1 hover:bg-destructive/90`,outline:`border-(length:--btn-border-width) border-input bg-background shadow-elevation-1 hover:bg-accent hover:text-accent-foreground`,secondary:`bg-secondary text-secondary-foreground shadow-elevation-1 hover:bg-secondary/80`,ghost:`hover:bg-accent hover:text-accent-foreground`,link:`text-primary underline-offset-4 hover:underline`},size:{default:`h-(--btn-height) px-(--btn-padding-x)`,sm:`h-control-sm rounded-(--btn-radius) px-3 text-xs`,lg:`h-control-lg rounded-(--btn-radius) px-8`,icon:`h-(--btn-height) w-(--btn-height)`}},defaultVariants:{variant:`default`,size:`default`}}),c=t(),l=o.forwardRef(({className:e,variant:t,size:n,asChild:i=!1,...o},l)=>(0,c.jsx)(i?r:`button`,{className:a(s({variant:t,size:n,className:e})),ref:l,...o}));l.displayName=`Button`;export{s as n,l as t};
@@ -0,0 +1,3 @@
1
+ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{u as t}from"./code-editor-BOIngd5F.js";import{t as n}from"./preload-helper-Czpn1I53.js";var r=e(t(),1),i=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,a=/^[\\/]{2}/;function o(e,t){return t+e.replace(/\\/g,`/`)}var s=(e=>(e.Pop=`POP`,e.Push=`PUSH`,e.Replace=`REPLACE`,e))(s||{}),c=`popstate`;function l(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function u(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return h(``,{pathname:r,search:i,hash:a},t.state&&t.state.usr||null,t.state&&t.state.key||`default`,n?{pathname:e.location.pathname,search:e.location.search,hash:e.location.hash}:void 0)}function n(e,t){return typeof t==`string`?t:g(t)}return v(t,n,null,e)}function d(e,t){if(e===!1||e==null)throw Error(t)}function f(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function p(){return Math.random().toString(36).substring(2,10)}function m(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function h(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?_(t):t,state:n,key:t&&t.key||r||p(),mask:i}}function g({pathname:e=`/`,search:t=``,hash:n=``}){return t&&t!==`?`&&(e+=t.charAt(0)===`?`?t:`?`+t),n&&n!==`#`&&(e+=n.charAt(0)===`#`?n:`#`+n),e}function _(e){let t={};if(e){let n=e.indexOf(`#`);n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf(`?`);r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function v(e,t,n,r={}){let{window:i=document.defaultView,v5Compat:a=!1}=r,o=i.history,s=`POP`,u=null,d=f();d??(d=0,o.replaceState({...o.state,idx:d},``));function f(){return(o.state||{idx:null}).idx}function p(){s=`POP`;let e=f(),t=e==null?null:e-d;d=e,u&&u({action:s,location:b.location,delta:t})}function g(e,t){s=`PUSH`;let r=l(e)?e:h(b.location,e,t);n&&n(r,e),d=f()+1;let c=m(r,d),p=b.createHref(r.mask||r);try{o.pushState(c,``,p)}catch(e){if(e instanceof DOMException&&e.name===`DataCloneError`)throw e;i.location.assign(p)}a&&u&&u({action:s,location:b.location,delta:1})}function _(e,t){s=`REPLACE`;let r=l(e)?e:h(b.location,e,t);n&&n(r,e),d=f();let i=m(r,d),c=b.createHref(r.mask||r);o.replaceState(i,``,c),a&&u&&u({action:s,location:b.location,delta:0})}function v(e){return y(i,e)}let b={get action(){return s},get location(){return e(i,o)},listen(e){if(u)throw Error(`A history only accepts one active listener`);return i.addEventListener(c,p),u=e,()=>{i.removeEventListener(c,p),u=null}},createHref(e){return t(i,e)},createURL:v,encodeLocation(e){let t=v(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:g,replace:_,go(e){return o.go(e)}};return b}function y(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),d(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:g(t);return i=i.replace(/ $/,`%20`),!n&&a.test(i)&&(i=r+i),new URL(i,r)}function b(e,t,n=`/`){return x(e,t,n,!1)}function x(e,t,n,r,i){let a=A((typeof t==`string`?_(t):t).pathname||`/`,n);if(a==null)return null;let o=i??S(e),s=null,c=le(a);for(let e=0;s==null&&e<o.length;++e)s=oe(o[e],c,r);return s}function S(e){let t=C(e);return T(t),t}function C(e,t=[],n=[],r=``,i=!1){let a=(e,a,o=i,s)=>{let c={relativePath:s===void 0?e.path||``:s,caseSensitive:e.caseSensitive===!0,childrenIndex:a,route:e};if(c.relativePath.startsWith(`/`)){if(!c.relativePath.startsWith(r)&&o)return;d(c.relativePath.startsWith(r),`Absolute route path "${c.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),c.relativePath=c.relativePath.slice(r.length)}let l=P([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(d(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),C(e.children,t,u,l,o)),!(e.path==null&&!e.index)&&t.push({path:l,score:ie(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=ce(e.relativePath,e.caseSensitive,t===u.length-1);return{...e,matcher:n,compiledParams:r}})})};return e.forEach((e,t)=>{if(e.path===``||!e.path?.includes(`?`))a(e,t);else for(let n of w(e.path))a(e,t,!0,n)}),t}function w(e){let t=e.split(`/`);if(t.length===0)return[];let[n,...r]=t,i=n.endsWith(`?`),a=n.replace(/\?$/,``);if(r.length===0)return i?[a,``]:[a];let o=w(r.join(`/`)),s=[];return s.push(...o.map(e=>e===``?a:[a,e].join(`/`))),i&&s.push(...o),s.map(t=>e.startsWith(`/`)&&t===``?`/`:t)}function T(e){e.sort((e,t)=>e.score===t.score?ae(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var E=/^:[\w-]+$/,ee=3,te=2,ne=1,D=10,O=-2,re=e=>e===`*`;function ie(e,t){let n=e.split(`/`),r=n.length;return n.some(re)&&(r+=O),t&&(r+=te),n.filter(e=>!re(e)).reduce((e,t)=>e+(E.test(t)?ee:t===``?ne:D),r)}function ae(e,t){return e.length===t.length&&e.slice(0,-1).every((e,n)=>e===t[n])?e[e.length-1]-t[t.length-1]:0}function oe(e,t,n=!1){let{routesMeta:r}=e,i={},a=`/`,o=[];for(let e=0;e<r.length;++e){let s=r[e],c=e===r.length-1,l=a===`/`?t:t.slice(a.length)||`/`,u={path:s.relativePath,caseSensitive:s.caseSensitive,end:c},d=s.matcher&&s.compiledParams?se(u,l,s.matcher,s.compiledParams):k(u,l),f=s.route;if(!d&&c&&n&&!r[r.length-1].route.index&&(d=k({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!d)return null;Object.assign(i,d.params),o.push({params:i,pathname:P([a,d.pathname]),pathnameBase:me(P([a,d.pathnameBase])),route:f}),d.pathnameBase!==`/`&&(a=P([a,d.pathnameBase]))}return o}function k(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=ce(e.path,e.caseSensitive,e.end);return se(e,t,n,r)}function se(e,t,n,r){let i=t.match(n);if(!i)return null;let a=i[0],o=a.replace(/(.)\/+$/,`$1`),s=i.slice(1);return{params:r.reduce((e,{paramName:t,isOptional:n},r)=>{if(t===`*`){let e=s[r]||``;o=a.slice(0,a.length-e.length).replace(/(.)\/+$/,`$1`)}let i=s[r];return e[t]=n&&!i?void 0:(i||``).replace(/%2F/g,`/`),e},{}),pathname:a,pathnameBase:o,pattern:e}}function ce(e,t=!1,n=!0){f(e===`*`||!e.endsWith(`*`)||e.endsWith(`/*`),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,`/*`)}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,`/*`)}".`);let r=[],i=`^`+e.replace(/\/*\*?$/,``).replace(/^\/*/,`/`).replace(/[\\.*+^${}|()[\]]/g,`\\$&`).replace(/\/:([\w-]+)(\?)?/g,(e,t,n,i,a)=>{if(r.push({paramName:t,isOptional:n!=null}),n){let t=a.charAt(i+e.length);return t&&t!==`/`?`/([^\\/]*)`:`(?:/([^\\/]*))?`}return`/([^\\/]+)`}).replace(/\/([\w-]+)\?(\/|$)/g,`(/$1)?$2`);return e.endsWith(`*`)?(r.push({paramName:`*`}),i+=e===`*`||e===`/*`?`(.*)$`:`(?:\\/(.+)|\\/*)$`):n?i+=`\\/*$`:e!==``&&e!==`/`&&(i+=`(?:(?=\\/|$))`),[new RegExp(i,t?void 0:`i`),r]}function le(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return f(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function A(e,t){if(t===`/`)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith(`/`)?t.length-1:t.length,r=e.charAt(n);return r&&r!==`/`?null:e.slice(n)||`/`}function ue(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?_(e):e,a;return n?(n=pe(n),a=n.startsWith(`/`)?de(n.substring(1),`/`):de(n,t)):a=t,{pathname:a,search:he(r),hash:ge(i)}}function de(e,t){let n=F(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function j(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function fe(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function M(e){let t=fe(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function N(e,t,n,r=!1){let i;typeof e==`string`?i=_(e):(i={...e},d(!i.pathname||!i.pathname.includes(`?`),j(`?`,`pathname`,`search`,i)),d(!i.pathname||!i.pathname.includes(`#`),j(`#`,`pathname`,`hash`,i)),d(!i.search||!i.search.includes(`#`),j(`#`,`search`,`hash`,i)));let a=e===``||i.pathname===``,o=a?`/`:i.pathname,s;if(o==null)s=n;else{let e=t.length-1;if(!r&&o.startsWith(`..`)){let t=o.split(`/`);for(;t[0]===`..`;)t.shift(),--e;i.pathname=t.join(`/`)}s=e>=0?t[e]:`/`}let c=ue(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var pe=e=>e.replace(/[\\/]{2,}/g,`/`),P=e=>pe(e.join(`/`)),F=e=>e.replace(/\/+$/,``),me=e=>F(e).replace(/^\/*/,`/`),he=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,ge=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,_e=class{constructor(e,t,n,r=!1){this.status=e,this.statusText=t||``,this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function ve(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function ye(e){return P(e.map(e=>e.route.path).filter(Boolean))||`/`}var be=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function xe(e,t){let n=e;if(typeof n!=`string`||!i.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,s=!1;if(be)try{let e=new URL(window.location.href),r=a.test(n)?new URL(o(n,e.protocol)):new URL(n),i=A(r.pathname,t);r.origin===e.origin&&i!=null?n=i+r.search+r.hash:s=!0}catch{f(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:s,to:n}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);var Se=[`POST`,`PUT`,`PATCH`,`DELETE`];new Set(Se);var Ce=[`GET`,...Se];new Set(Ce);var we=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function Te(e){try{return we.includes(new URL(e).protocol)}catch{return!1}}var I=r.createContext(null);I.displayName=`DataRouter`;var L=r.createContext(null);L.displayName=`DataRouterState`;var Ee=r.createContext(!1);function De(){return r.useContext(Ee)}var Oe=r.createContext({isTransitioning:!1});Oe.displayName=`ViewTransition`;var ke=r.createContext(new Map);ke.displayName=`Fetchers`;var Ae=r.createContext(null);Ae.displayName=`Await`;var R=r.createContext(null);R.displayName=`Navigation`;var z=r.createContext(null);z.displayName=`Location`;var B=r.createContext({outlet:null,matches:[],isDataRoute:!1});B.displayName=`Route`;var V=r.createContext(null);V.displayName=`RouteError`;var je=`REACT_ROUTER_ERROR`,Me=`REDIRECT`,Ne=`ROUTE_ERROR_RESPONSE`;function Pe(e){if(e.startsWith(`${je}:${Me}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`&&typeof t.location==`string`&&typeof t.reloadDocument==`boolean`&&typeof t.replace==`boolean`)return t}catch{}}function Fe(e){if(e.startsWith(`${je}:${Ne}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new _e(t.status,t.statusText,t.data)}catch{}}function Ie(e,{relative:t}={}){d(H(),`useHref() may be used only in the context of a <Router> component.`);let{basename:n,navigator:i}=r.useContext(R),{hash:a,pathname:o,search:s}=G(e,{relative:t}),c=o;return n!==`/`&&(c=o===`/`?n:P([n,o])),i.createHref({pathname:c,search:s,hash:a})}function H(){return r.useContext(z)!=null}function U(){return d(H(),`useLocation() may be used only in the context of a <Router> component.`),r.useContext(z).location}var Le=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function Re(e){r.useContext(R).static||r.useLayoutEffect(e)}function W(){let{isDataRoute:e}=r.useContext(B);return e?at():ze()}function ze(){d(H(),`useNavigate() may be used only in the context of a <Router> component.`);let e=r.useContext(I),{basename:t,navigator:n}=r.useContext(R),{matches:i}=r.useContext(B),{pathname:a}=U(),o=JSON.stringify(M(i)),s=r.useRef(!1);return Re(()=>{s.current=!0}),r.useCallback((r,i={})=>{if(f(s.current,Le),!s.current)return;if(typeof r==`number`){n.go(r);return}let c=N(r,JSON.parse(o),a,i.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:P([t,c.pathname])),(i.replace?n.replace:n.push)(c,i.state,i)},[t,n,o,a,e])}var Be=r.createContext(null);function Ve(e){let t=r.useContext(B).outlet;return r.useMemo(()=>t&&r.createElement(Be.Provider,{value:e},t),[t,e])}function He(){let{matches:e}=r.useContext(B);return e[e.length-1]?.params??{}}function G(e,{relative:t}={}){let{matches:n}=r.useContext(B),{pathname:i}=U(),a=JSON.stringify(M(n));return r.useMemo(()=>N(e,JSON.parse(a),i,t===`path`),[e,a,i,t])}function Ue(e,t){return We(e,t)}function We(e,t,n){d(H(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:i}=r.useContext(R),{matches:a}=r.useContext(B),o=a[a.length-1],s=o?o.params:{},c=o?o.pathname:`/`,l=o?o.pathnameBase:`/`,u=o&&o.route;{let e=u&&u.path||``;st(c,!u||e.endsWith(`*`)||e.endsWith(`*?`),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${c}" (under <Route path="${e}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
2
+
3
+ Please change the parent <Route path="${e}"> to <Route path="${e===`/`?`*`:`${e}/*`}">.`)}let p=U(),m;if(t){let e=typeof t==`string`?_(t):t;d(l===`/`||e.pathname?.startsWith(l),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${l}" but pathname "${e.pathname}" was given in the \`location\` prop.`),m=e}else m=p;let h=m.pathname||`/`,g=h;if(l!==`/`){let e=l.replace(/^\//,``).split(`/`);g=`/`+h.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let v=n&&n.state.matches.length?n.state.matches.map(e=>Object.assign(e,{route:n.manifest[e.route.id]||e.route})):b(e,{pathname:g});f(u||v!=null,`No routes matched location "${m.pathname}${m.search}${m.hash}" `),f(v==null||v[v.length-1].route.element!==void 0||v[v.length-1].route.Component!==void 0||v[v.length-1].route.lazy!==void 0,`Matched leaf route at location "${m.pathname}${m.search}${m.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let y=Ze(v&&v.map(e=>Object.assign({},e,{params:Object.assign({},s,e.params),pathname:P([l,i.encodeLocation?i.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?l:P([l,i.encodeLocation?i.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),a,n);return t&&y?r.createElement(z.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...m},navigationType:`POP`}},y):y}function Ge(){let e=it(),t=ve(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,i=`rgba(200,200,200, 0.5)`,a={padding:`0.5rem`,backgroundColor:i},o={padding:`2px 4px`,backgroundColor:i},s=null;return console.error(`Error handled by React Router default ErrorBoundary:`,e),s=r.createElement(r.Fragment,null,r.createElement(`p`,null,`💿 Hey developer 👋`),r.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,r.createElement(`code`,{style:o},`ErrorBoundary`),` or`,` `,r.createElement(`code`,{style:o},`errorElement`),` prop on your route.`)),r.createElement(r.Fragment,null,r.createElement(`h2`,null,`Unexpected Application Error!`),r.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?r.createElement(`pre`,{style:a},n):null,s)}var Ke=r.createElement(Ge,null),qe=class extends r.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=Fe(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:r.createElement(B.Provider,{value:this.props.routeContext},r.createElement(V.Provider,{value:e,children:this.props.component}));return this.context?r.createElement(Ye,{error:e},t):t}};qe.contextType=Ee;var Je=new WeakMap;function Ye({children:e,error:t}){let{basename:n}=r.useContext(R);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=Pe(t.digest);if(e){let i=Je.get(t);if(i)throw i;let a=xe(e.location,n),o=a.absoluteURL||a.to;if(Te(o))throw Error(`Invalid redirect location`);if(be&&!Je.get(t)){if(a.isExternal||e.reloadDocument)window.location.href=o;else{let n=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(a.to,{replace:e.replace}));throw Je.set(t,n),n}}return r.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${o}`})}}return e}function Xe({routeContext:e,match:t,children:n}){let i=r.useContext(I);return i&&i.static&&i.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=t.route.id),r.createElement(B.Provider,{value:e},n)}function Ze(e,t=[],n){let i=n?.state;if(e==null){if(!i)return null;if(i.errors)e=i.matches;else if(t.length===0&&!i.initialized&&i.matches.length>0)e=i.matches;else return null}let a=e,o=i?.errors;if(o!=null){let e=a.findIndex(e=>e.route.id&&o?.[e.route.id]!==void 0);d(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(o).join(`,`)}`),a=a.slice(0,Math.min(a.length,e+1))}let s=!1,c=-1;if(n&&i){s=i.renderFallback;for(let e=0;e<a.length;e++){let t=a[e];if((t.route.HydrateFallback||t.route.hydrateFallbackElement)&&(c=e),t.route.id){let{loaderData:e,errors:r}=i,o=t.route.loader&&!e.hasOwnProperty(t.route.id)&&(!r||r[t.route.id]===void 0);if(t.route.lazy||o){n.isStatic&&(s=!0),a=c>=0?a.slice(0,c+1):[a[0]];break}}}}let l=n?.onError,u=i&&l?(e,t)=>{l(e,{location:i.location,params:i.matches?.[0]?.params??{},pattern:ye(i.matches),errorInfo:t})}:void 0;return a.reduceRight((e,n,l)=>{let d,f=!1,p=null,m=null;i&&(d=o&&n.route.id?o[n.route.id]:void 0,p=n.route.errorElement||Ke,s&&(c<0&&l===0?(st(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),f=!0,m=null):c===l&&(f=!0,m=n.route.hydrateFallbackElement||null)));let h=t.concat(a.slice(0,l+1)),g=()=>{let t;return t=d?p:f?m:n.route.Component?r.createElement(n.route.Component,null):n.route.element?n.route.element:e,r.createElement(Xe,{match:n,routeContext:{outlet:e,matches:h,isDataRoute:i!=null},children:t})};return i&&(n.route.ErrorBoundary||n.route.errorElement||l===0)?r.createElement(qe,{location:i.location,revalidation:i.revalidation,component:p,error:d,children:g(),routeContext:{outlet:null,matches:h,isDataRoute:!0},onError:u}):g()},null)}function Qe(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function $e(e){let t=r.useContext(I);return d(t,Qe(e)),t}function et(e){let t=r.useContext(L);return d(t,Qe(e)),t}function tt(e){let t=r.useContext(B);return d(t,Qe(e)),t}function nt(e){let t=tt(e),n=t.matches[t.matches.length-1];return d(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function rt(){return nt(`useRouteId`)}function it(){let e=r.useContext(V),t=et(`useRouteError`),n=nt(`useRouteError`);return e===void 0?t.errors?.[n]:e}function at(){let{router:e}=$e(`useNavigate`),t=nt(`useNavigate`),n=r.useRef(!1);return Re(()=>{n.current=!0}),r.useCallback(async(r,i={})=>{f(n.current,Le),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var ot={};function st(e,t,n){!t&&!ot[e]&&(ot[e]=!0,f(!1,n))}r.memo(ct);function ct({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return We(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function lt({to:e,replace:t,state:n,relative:i}){d(H(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:a}=r.useContext(R);f(!a,`<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`);let{matches:o}=r.useContext(B),{pathname:s}=U(),c=W(),l=N(e,M(o),s,i===`path`),u=JSON.stringify(l);return r.useEffect(()=>{c(JSON.parse(u),{replace:t,state:n,relative:i})},[c,u,i,t,n]),null}function ut(e){return Ve(e.context)}function dt(e){d(!1,`A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`)}function ft({basename:e=`/`,children:t=null,location:n,navigationType:i=`POP`,navigator:a,static:o=!1,useTransitions:s}){d(!H(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let c=e.replace(/^\/*/,`/`),l=r.useMemo(()=>({basename:c,navigator:a,static:o,useTransitions:s,future:{}}),[c,a,o,s]);typeof n==`string`&&(n=_(n));let{pathname:u=`/`,search:p=``,hash:m=``,state:h=null,key:g=`default`,mask:v}=n,y=r.useMemo(()=>{let e=A(u,c);return e==null?null:{location:{pathname:e,search:p,hash:m,state:h,key:g,mask:v},navigationType:i}},[c,u,p,m,h,g,i,v]);return f(y!=null,`<Router basename="${c}"> is not able to match the URL "${u}${p}${m}" because it does not start with the basename, so the <Router> won't render anything.`),y==null?null:r.createElement(R.Provider,{value:l},r.createElement(z.Provider,{children:t,value:y}))}function pt({children:e,location:t}){return Ue(K(e),t)}r.Component;function K(e,t=[]){let n=[];return r.Children.forEach(e,(e,i)=>{if(!r.isValidElement(e))return;let a=[...t,i];if(e.type===r.Fragment){n.push.apply(n,K(e.props.children,a));return}d(e.type===dt,`[${typeof e.type==`string`?e.type:e.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),d(!e.props.index||!e.props.children,`An index route cannot have child routes.`);let o={id:e.props.id||a.join(`-`),caseSensitive:e.props.caseSensitive,element:e.props.element,Component:e.props.Component,index:e.props.index,path:e.props.path,middleware:e.props.middleware,loader:e.props.loader,action:e.props.action,hydrateFallbackElement:e.props.hydrateFallbackElement,HydrateFallback:e.props.HydrateFallback,errorElement:e.props.errorElement,ErrorBoundary:e.props.ErrorBoundary,hasErrorBoundary:e.props.hasErrorBoundary===!0||e.props.ErrorBoundary!=null||e.props.errorElement!=null,shouldRevalidate:e.props.shouldRevalidate,handle:e.props.handle,lazy:e.props.lazy};e.props.children&&(o.children=K(e.props.children,a)),n.push(o)}),n}var q=`get`,J=`application/x-www-form-urlencoded`;function Y(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function mt(e){return Y(e)&&e.tagName.toLowerCase()===`button`}function ht(e){return Y(e)&&e.tagName.toLowerCase()===`form`}function gt(e){return Y(e)&&e.tagName.toLowerCase()===`input`}function _t(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function vt(e,t){return e.button===0&&(!t||t===`_self`)&&!_t(e)}function yt(e=``){return new URLSearchParams(typeof e==`string`||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}function bt(e,t){let n=yt(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var X=null;function xt(){if(X===null)try{new FormData(document.createElement(`form`),0),X=!1}catch{X=!0}return X}var St=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function Ct(e){return e!=null&&!St.has(e)?(f(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${J}"`),null):e}function wt(e,t){let n,r,i,a,o;if(ht(e)){let o=e.getAttribute(`action`);r=o?A(o,t):null,n=e.getAttribute(`method`)||q,i=Ct(e.getAttribute(`enctype`))||J,a=new FormData(e)}else if(mt(e)||gt(e)&&(e.type===`submit`||e.type===`image`)){let o=e.form;if(o==null)throw Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);let s=e.getAttribute(`formaction`)||o.getAttribute(`action`);if(r=s?A(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||q,i=Ct(e.getAttribute(`formenctype`))||Ct(o.getAttribute(`enctype`))||J,a=new FormData(o,e),!xt()){let{name:t,type:n,value:r}=e;if(n===`image`){let e=t?`${t}.`:``;a.append(`${e}x`,`0`),a.append(`${e}y`,`0`)}else t&&a.append(t,r)}}else if(Y(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=q,r=null,i=J,o=e;return a&&i===`text/plain`&&(o=a,a=void 0),{action:r,method:n.toLowerCase(),encType:i,formData:a,body:o}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);function Tt(e,t){if(e===!1||e==null)throw Error(t)}function Et(e,t,n,r){let i=typeof e==`string`?new URL(e,typeof window>`u`?`server://singlefetch/`:window.location.origin):e;return i.pathname=n?i.pathname.endsWith(`/`)?`${i.pathname}_.${r}`:`${i.pathname}.${r}`:i.pathname===`/`?`_root.${r}`:t&&A(i.pathname,t)===`/`?`${F(t)}/_root.${r}`:`${F(i.pathname)}.${r}`,i}async function Dt(e,t){if(e.id in t)return t[e.id];try{let r=await n(()=>import(e.module),[]);return t[e.id]=r,r}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function Ot(e){return e!=null&&typeof e.page==`string`}function kt(e){return e==null?!1:e.href==null?e.rel===`preload`&&typeof e.imageSrcSet==`string`&&typeof e.imageSizes==`string`:typeof e.rel==`string`&&typeof e.href==`string`}async function At(e,t,n){return Ft((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await Dt(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(kt).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function jt(e,t,n,r,i,a){let o=(e,t)=>!n[t]||e.route.id!==n[t].route.id,s=(e,t)=>n[t].pathname!==e.pathname||n[t].route.path?.endsWith(`*`)&&n[t].params[`*`]!==e.params[`*`];return a===`assets`?t.filter((e,t)=>o(e,t)||s(e,t)):a===`data`?t.filter((t,a)=>{let c=r.routes[t.route.id];if(!c||!c.hasLoader)return!1;if(o(t,a)||s(t,a))return!0;if(t.route.shouldRevalidate){let r=t.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:t.params,defaultShouldRevalidate:!0});if(typeof r==`boolean`)return r}return!0}):[]}function Mt(e,t,{includeHydrateFallback:n}={}){return Nt(e.map(e=>{let r=t.routes[e.route.id];if(!r)return[];let i=[r.module];return r.clientActionModule&&(i=i.concat(r.clientActionModule)),r.clientLoaderModule&&(i=i.concat(r.clientLoaderModule)),n&&r.hydrateFallbackModule&&(i=i.concat(r.hydrateFallbackModule)),r.imports&&(i=i.concat(r.imports)),i}).flat(1))}function Nt(e){return[...new Set(e)]}function Pt(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function Ft(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!Ot(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(Pt(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function It(){let e=r.useContext(I);return Tt(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function Lt(){let e=r.useContext(L);return Tt(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var Rt=r.createContext(void 0);Rt.displayName=`FrameworkContext`;function Z(){let e=r.useContext(Rt);return Tt(e,`You must render this element inside a <HydratedRouter> element`),e}function zt(e,t){let n=r.useContext(Rt),[i,a]=r.useState(!1),[o,s]=r.useState(!1),{onFocus:c,onBlur:l,onMouseEnter:u,onMouseLeave:d,onTouchStart:f}=t,p=r.useRef(null);r.useEffect(()=>{if(e===`render`&&s(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{s(e.isIntersecting)})},{threshold:.5});return p.current&&e.observe(p.current),()=>{e.disconnect()}}},[e]),r.useEffect(()=>{if(i){let e=setTimeout(()=>{s(!0)},100);return()=>{clearTimeout(e)}}},[i]);let m=()=>{a(!0)},h=()=>{a(!1),s(!1)};return n?e===`intent`?[o,p,{onFocus:Q(c,m),onBlur:Q(l,h),onMouseEnter:Q(u,m),onMouseLeave:Q(d,h),onTouchStart:Q(f,m)}]:[o,p,{}]:[!1,p,{}]}function Q(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function Bt({page:e,...t}){let n=De(),{nonce:i}=Z(),{router:a}=It(),o=r.useMemo(()=>b(a.routes,e,a.basename),[a.routes,e,a.basename]);return o?(t.nonce==null&&i&&(t={...t,nonce:i}),n?r.createElement(Ht,{page:e,matches:o,...t}):r.createElement(Ut,{page:e,matches:o,...t})):null}function Vt(e){let{manifest:t,routeModules:n}=Z(),[i,a]=r.useState([]);return r.useEffect(()=>{let r=!1;return At(e,t,n).then(e=>{r||a(e)}),()=>{r=!0}},[e,t,n]),i}function Ht({page:e,matches:t,...n}){let i=U(),{future:a}=Z(),{basename:o}=It(),s=r.useMemo(()=>{if(e===i.pathname+i.search+i.hash)return[];let n=Et(e,o,a.v8_trailingSlashAwareDataRequests,`rsc`),r=!1,s=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?r=!0:s.push(e.route.id);return r&&s.length>0&&n.searchParams.set(`_routes`,s.join(`,`)),[n.pathname+n.search]},[o,a.v8_trailingSlashAwareDataRequests,e,i,t]);return r.createElement(r.Fragment,null,s.map(e=>r.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function Ut({page:e,matches:t,...n}){let i=U(),{future:a,manifest:o,routeModules:s}=Z(),{basename:c}=It(),{loaderData:l,matches:u}=Lt(),d=r.useMemo(()=>jt(e,t,u,o,i,`data`),[e,t,u,o,i]),f=r.useMemo(()=>jt(e,t,u,o,i,`assets`),[e,t,u,o,i]),p=r.useMemo(()=>{if(e===i.pathname+i.search+i.hash)return[];let n=new Set,r=!1;if(t.forEach(e=>{let t=o.routes[e.route.id];!t||!t.hasLoader||(!d.some(t=>t.route.id===e.route.id)&&e.route.id in l&&s[e.route.id]?.shouldRevalidate||t.hasClientLoader?r=!0:n.add(e.route.id))}),n.size===0)return[];let u=Et(e,c,a.v8_trailingSlashAwareDataRequests,`data`);return r&&n.size>0&&u.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[u.pathname+u.search]},[c,a.v8_trailingSlashAwareDataRequests,l,i,o,d,t,e,s]),m=r.useMemo(()=>Mt(f,o),[f,o]),h=Vt(f);return r.createElement(r.Fragment,null,p.map(e=>r.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),m.map(e=>r.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),h.map(({key:e,link:t})=>r.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function Wt(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}r.Component;var Gt=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{Gt&&(window.__reactRouterVersion=`7.18.2`)}catch{}function Kt({basename:e,children:t,useTransitions:n,window:i}){let a=r.useRef();a.current??=u({window:i,v5Compat:!0});let o=a.current,[s,c]=r.useState({action:o.action,location:o.location}),l=r.useCallback(e=>{n===!1?c(e):r.startTransition(()=>c(e))},[n]);return r.useLayoutEffect(()=>o.listen(l),[o,l]),r.createElement(ft,{basename:e,children:t,location:s.location,navigationType:s.action,navigator:o,useTransitions:n})}var $=r.forwardRef(function({onClick:e,discover:t=`render`,prefetch:n=`none`,relative:a,reloadDocument:o,replace:s,mask:c,state:l,target:u,to:d,preventScrollReset:f,viewTransition:p,defaultShouldRevalidate:m,...h},g){let{basename:_,navigator:v,useTransitions:y}=r.useContext(R),b=typeof d==`string`&&i.test(d),x=xe(d,_);d=x.to;let S=Ie(d,{relative:a}),C=U(),w=null;if(c){let e=N(c,[],C.mask?C.mask.pathname:`/`,!0);_!==`/`&&(e.pathname=e.pathname===`/`?_:P([_,e.pathname])),w=v.createHref(e)}let[T,E,ee]=zt(n,h),te=Zt(d,{replace:s,mask:c,state:l,target:u,preventScrollReset:f,relative:a,viewTransition:p,defaultShouldRevalidate:m,useTransitions:y});function ne(t){e&&e(t),t.defaultPrevented||te(t)}let D=!(x.isExternal||o),O=r.createElement(`a`,{...h,...ee,href:(D?w:void 0)||x.absoluteURL||S,onClick:D?ne:e,ref:Wt(g,E),target:u,"data-discover":!b&&t===`render`?`true`:void 0});return T&&!b?r.createElement(r.Fragment,null,O,r.createElement(Bt,{page:S})):O});$.displayName=`Link`;var qt=r.forwardRef(function({"aria-current":e=`page`,caseSensitive:t=!1,className:n=``,end:i=!1,style:a,to:o,viewTransition:s,children:c,...l},u){let d=G(o,{relative:l.relative}),f=U(),p=r.useContext(L),{navigator:m,basename:h}=r.useContext(R),g=p!=null&&rn(d)&&s===!0,_=m.encodeLocation?m.encodeLocation(d).pathname:d.pathname,v=f.pathname,y=p&&p.navigation&&p.navigation.location?p.navigation.location.pathname:null;t||(v=v.toLowerCase(),y=y?y.toLowerCase():null,_=_.toLowerCase()),y&&h&&(y=A(y,h)||y);let b=_!==`/`&&_.endsWith(`/`)?_.length-1:_.length,x=v===_||!i&&v.startsWith(_)&&v.charAt(b)===`/`,S=y!=null&&(y===_||!i&&y.startsWith(_)&&y.charAt(_.length)===`/`),C={isActive:x,isPending:S,isTransitioning:g},w=x?e:void 0,T;T=typeof n==`function`?n(C):[n,x?`active`:null,S?`pending`:null,g?`transitioning`:null].filter(Boolean).join(` `);let E=typeof a==`function`?a(C):a;return r.createElement($,{...l,"aria-current":w,className:T,ref:u,style:E,to:o,viewTransition:s},typeof c==`function`?c(C):c)});qt.displayName=`NavLink`;var Jt=r.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:a,replace:o,state:s,method:c=q,action:l,onSubmit:u,relative:d,preventScrollReset:f,viewTransition:p,defaultShouldRevalidate:m,...h},g)=>{let{useTransitions:_}=r.useContext(R),v=tn(),y=nn(l,{relative:d}),b=c.toLowerCase()===`get`?`get`:`post`,x=typeof l==`string`&&i.test(l);return r.createElement(`form`,{ref:g,method:b,action:y,onSubmit:a?u:e=>{if(u&&u(e),e.defaultPrevented)return;e.preventDefault();let i=e.nativeEvent.submitter,a=i?.getAttribute(`formmethod`)||c,l=()=>v(i||e.currentTarget,{fetcherKey:t,method:a,navigate:n,replace:o,state:s,relative:d,preventScrollReset:f,viewTransition:p,defaultShouldRevalidate:m});_&&n!==!1?r.startTransition(()=>l()):l()},...h,"data-discover":!x&&e===`render`?`true`:void 0})});Jt.displayName=`Form`;function Yt(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Xt(e){let t=r.useContext(I);return d(t,Yt(e)),t}function Zt(e,{target:t,replace:n,mask:i,state:a,preventScrollReset:o,relative:s,viewTransition:c,defaultShouldRevalidate:l,useTransitions:u}={}){let d=W(),f=U(),p=G(e,{relative:s});return r.useCallback(m=>{if(vt(m,t)){m.preventDefault();let t=n===void 0?g(f)===g(p):n,h=()=>d(e,{replace:t,mask:i,state:a,preventScrollReset:o,relative:s,viewTransition:c,defaultShouldRevalidate:l});u?r.startTransition(()=>h()):h()}},[f,d,p,n,i,a,t,e,o,s,c,l,u])}function Qt(e){f(typeof URLSearchParams<`u`,"You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=r.useRef(yt(e)),n=r.useRef(!1),i=U(),a=r.useMemo(()=>bt(i.search,n.current?null:t.current),[i.search]),o=W();return[a,r.useCallback((e,t)=>{let r=yt(typeof e==`function`?e(new URLSearchParams(a)):e);n.current=!0,o(`?`+r,t)},[o,a])]}var $t=0,en=()=>`__${String(++$t)}__`;function tn(){let{router:e}=Xt(`useSubmit`),{basename:t}=r.useContext(R),n=rt(),i=e.fetch,a=e.navigate;return r.useCallback(async(e,r={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=wt(e,t);if(r.navigate===!1){let e=r.fetcherKey||en();await i(e,n,r.action||o,{defaultShouldRevalidate:r.defaultShouldRevalidate,preventScrollReset:r.preventScrollReset,formData:l,body:u,formMethod:r.method||s,formEncType:r.encType||c,flushSync:r.flushSync})}else await a(r.action||o,{defaultShouldRevalidate:r.defaultShouldRevalidate,preventScrollReset:r.preventScrollReset,formData:l,body:u,formMethod:r.method||s,formEncType:r.encType||c,replace:r.replace,state:r.state,fromRouteId:n,flushSync:r.flushSync,viewTransition:r.viewTransition})},[i,a,t,n])}function nn(e,{relative:t}={}){let{basename:n}=r.useContext(R),i=r.useContext(B);d(i,`useFormAction must be used inside a RouteContext`);let[a]=i.matches.slice(-1),o={...G(e||`.`,{relative:t})},s=U();if(e==null){o.search=s.search;let e=new URLSearchParams(o.search),t=e.getAll(`index`);if(t.some(e=>e===``)){e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();o.search=n?`?${n}`:``}}return(!e||e===`.`)&&a.route.index&&(o.search=o.search?o.search.replace(/^\?/,`?index&`):`?index`),n!==`/`&&(o.pathname=o.pathname===`/`?n:P([n,o.pathname])),g(o)}function rn(e,{relative:t}={}){let n=r.useContext(Oe);d(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:i}=Xt(`useViewTransitionState`),a=G(e,{relative:t});if(!n.isTransitioning)return!1;let o=A(n.currentLocation.pathname,i)||n.currentLocation.pathname,s=A(n.nextLocation.pathname,i)||n.nextLocation.pathname;return k(a.pathname,s)!=null||k(a.pathname,o)!=null}export{He as _,lt as a,dt as c,g as d,K as f,W as g,U as h,z as i,B as l,_ as m,Kt as n,R as o,b as p,$ as r,ut as s,s as t,pt as u,Qt as v};