@cmmd-center/forge 0.13.82 → 0.13.84
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.
- package/dist/bin.cjs +158 -134
- package/dist/bin.mjs +242 -213
- package/dist/client/assets/{CanvasPanel-AjtGwv2H.js → CanvasPanel-Dyho_JDo.js} +2 -2
- package/dist/client/assets/{CompositeItem-B_Qce_Zi.js → CompositeItem-DeDhuBZB.js} +2 -2
- package/dist/client/assets/{DiffPanel-B47H2Ztq.js → DiffPanel-B4iZmA47.js} +3 -3
- package/dist/client/assets/{DiffPanel.logic-DT4FolWZ.js → DiffPanel.logic-BpahIUC5.js} +4 -4
- package/dist/client/assets/{DiffWorkerPoolProvider-BrgXjqS5.js → DiffWorkerPoolProvider-CZ4RyCYi.js} +30 -30
- package/dist/client/assets/PullRequestCodePanel-CKRAtq2X.js +5 -0
- package/dist/client/assets/Virtualizer-CDLGfmSn.js +2 -0
- package/dist/client/assets/WorkerPoolContext--cbYuhHG.js +2537 -0
- package/dist/client/assets/{canvasStateStore-BpKdB-dM.js → canvasStateStore-DJ_OzrrC.js} +2 -2
- package/dist/client/assets/cmmdAuthRedirect-Bqx90tp9.js +3 -0
- package/dist/client/assets/index-pi7gtd2m.js +153 -0
- package/dist/client/assets/{popover-RLwH5jQy.js → popover-D20eY2oM.js} +2 -2
- package/dist/client/assets/{src-IM0FnQax.js → src-CoTxmdk3.js} +2 -2
- package/dist/client/assets/{toggle-BUzYChlq.js → toggle-AqC0QUc1.js} +2 -2
- package/dist/client/index.html +10 -10
- package/dist/forge-build.json +1 -1
- package/dist/{open-2-reBrpv.mjs → open-yHTUkd2Y.mjs} +3 -3
- package/package.json +1 -1
- package/dist/client/assets/DiffPanelShell-DYfYdx6r.js +0 -2537
- package/dist/client/assets/PullRequestCodePanel-3MHkasTp.js +0 -5
- package/dist/client/assets/Virtualizer-BF72qd4z.js +0 -2
- package/dist/client/assets/cmmdAuthRedirect-lzr9SGGx.js +0 -2
- package/dist/client/assets/index-jjmPqZtL.js +0 -154
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{fn as e,on as t}from"./CompositeItem-B_Qce_Zi.js";var n=t(`arrow-down`,[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]),r=t(`arrow-up`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),i=t(`chevrons-down`,[[`path`,{d:`m7 6 5 5 5-5`,key:`1lc07p`}],[`path`,{d:`m7 13 5 5 5-5`,key:`1d48rs`}]]),a=t(`chevrons-up`,[[`path`,{d:`m17 11-5-5-5 5`,key:`e8nh98`}],[`path`,{d:`m17 18-5-5-5 5`,key:`2avn1x`}]]),o=t(`circle`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]),s=t(`download`,[[`path`,{d:`M12 15V3`,key:`m9g1x1`}],[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`path`,{d:`m7 10 5 5 5-5`,key:`brsn70`}]]),c=t(`eye-off`,[[`path`,{d:`M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49`,key:`ct8e1f`}],[`path`,{d:`M14.084 14.158a3 3 0 0 1-4.242-4.242`,key:`151rxh`}],[`path`,{d:`M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143`,key:`13bj9a`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}]]),l=t(`eye`,[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`,key:`1nclc0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),u=t(`file-text`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),d=t(`minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),f=t(`palette`,[[`path`,{d:`M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z`,key:`e79jfc`}],[`circle`,{cx:`13.5`,cy:`6.5`,r:`.5`,fill:`currentColor`,key:`1okk4w`}],[`circle`,{cx:`17.5`,cy:`10.5`,r:`.5`,fill:`currentColor`,key:`f64h9f`}],[`circle`,{cx:`6.5`,cy:`12.5`,r:`.5`,fill:`currentColor`,key:`qy21gx`}],[`circle`,{cx:`8.5`,cy:`7.5`,r:`.5`,fill:`currentColor`,key:`fotxhn`}]]),p=t(`save`,[[`path`,{d:`M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z`,key:`1c8476`}],[`path`,{d:`M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7`,key:`1ydtos`}],[`path`,{d:`M7 3v4a1 1 0 0 0 1 1h7`,key:`t51u73`}]]),m=t(`square`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}]]),h=t(`undo-2`,[[`path`,{d:`M9 14 4 9l5-5`,key:`102s5s`}],[`path`,{d:`M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11`,key:`f3b9sd`}]]),g={primaryColor:`#6366f1`,secondaryColor:`#8b5cf6`,accentColor:`#f59e0b`,backgroundColor:`#ffffff`,textColor:`#1f2937`,fontFamily:`Inter, sans-serif`,headingFontFamily:`Inter, sans-serif`},_={bold:{bg:`#1f2937`,accent:`#f59e0b`,text:`#ffffff`},minimal:{bg:`#ffffff`,accent:`#6366f1`,text:`#1f2937`},gradient:{bg:`#4f46e5`,accent:`#818cf8`,text:`#ffffff`},split:{bg:`#f8fafc`,accent:`#0ea5e9`,text:`#0f172a`},centered:{bg:`#fef3c7`,accent:`#d97706`,text:`#78350f`}},v=[`bold`,`minimal`,`gradient`,`split`,`centered`];function y(e){let t=e.toLowerCase();return t.includes(`bold`)||t.includes(`sale`)||t.includes(`announcement`)?`bold`:t.includes(`minimal`)||t.includes(`clean`)||t.includes(`simple`)?`minimal`:t.includes(`gradient`)||t.includes(`modern`)||t.includes(`tech`)?`gradient`:t.includes(`split`)||t.includes(`compare`)||t.includes(`versus`)?`split`:t.includes(`warm`)||t.includes(`friendly`)||t.includes(`welcome`)?`centered`:v[Math.floor(Math.random()*v.length)]??`bold`}function b(e){let t=e.replace(/^(create|make|design|generate)\s+(a|an|me)?\s*/i,``).replace(/\s*(instagram|facebook|twitter|linkedin|youtube|social media|post|story|banner|cover|thumbnail)\s*/gi,``).replace(/\s*(about|for|with|featuring)\s*/i,`|`).trim().split(`|`).map(e=>e.trim()).filter(Boolean),n=t[0]??``;if(t.length>=2)return{heading:x(n),subtext:x(t.slice(1).join(` `))};if(n.length>30){let e=n.split(` `),t=Math.ceil(e.length/2);return{heading:x(e.slice(0,t).join(` `)),subtext:x(e.slice(t).join(` `))}}return{heading:n?x(n):`Your Title Here`,subtext:`Add your message`}}function x(e){return e.charAt(0).toUpperCase()+e.slice(1)}function S(e,t,n,r=g){let i=y(e),a=_[i],{heading:o,subtext:s}=b(e),c=t>n;Math.abs(t-n);let l=[];switch(l.push({type:`rect`,left:0,top:0,width:t,height:n,fill:a.bg,selectable:!1,customId:`__bg__`,customName:`Background`}),i){case`bold`:l.push(...C(t,n,a,o,s,r));break;case`minimal`:l.push(...w(t,n,a,o,s,r));break;case`gradient`:l.push(...T(t,n,a,o,s,r));break;case`split`:l.push(...E(t,n,a,o,s,c,r));break;case`centered`:l.push(...D(t,n,a,o,s,r))}return{objects:l}}function C(e,t,n,r,i,a){let o=Math.min(e,t)*.08,s=Math.min(e,t)*.1,c=s*.4;return[{type:`rect`,left:0,top:0,width:e,height:t*.06,fill:n.accent,customName:`Accent Bar`},{type:`textbox`,left:o,top:t*.3,width:e-o*2,text:r.toUpperCase(),fontSize:s,fontFamily:a.headingFontFamily,fontWeight:`900`,fill:n.text,textAlign:`left`,customName:`Heading`},{type:`textbox`,left:o,top:t*.55,width:e-o*2,text:i,fontSize:c,fontFamily:a.fontFamily,fontWeight:`400`,fill:n.accent,textAlign:`left`,customName:`Subtext`},{type:`rect`,left:o,top:t*.85,width:e*.3,height:4,fill:n.accent,customName:`Accent Line`}]}function w(e,t,n,r,i,a){let o=Math.min(e,t)*.08,s=o*.45;return[{type:`rect`,left:e*.04,top:t*.04,width:e*.92,height:t*.92,fill:`transparent`,stroke:n.accent,strokeWidth:2,customName:`Frame`},{type:`textbox`,left:e*.1,top:t*.35,width:e*.8,text:r,fontSize:o,fontFamily:a.headingFontFamily,fontWeight:`600`,fill:n.text,textAlign:`center`,customName:`Heading`},{type:`rect`,left:e*.4,top:t*.52,width:e*.2,height:2,fill:n.accent,customName:`Divider`},{type:`textbox`,left:e*.15,top:t*.58,width:e*.7,text:i,fontSize:s,fontFamily:a.fontFamily,fontWeight:`400`,fill:`#6b7280`,textAlign:`center`,customName:`Subtext`}]}function T(e,t,n,r,i,a){let o=Math.min(e,t)*.09,s=o*.4;return[{type:`rect`,left:0,top:t*.6,width:e,height:t*.4,fill:`rgba(0,0,0,0.3)`,customName:`Overlay`},{type:`ellipse`,left:e*.7,top:-t*.15,rx:e*.25,ry:e*.25,fill:n.accent,opacity:.3,customName:`Deco Circle`},{type:`textbox`,left:e*.08,top:t*.35,width:e*.84,text:r,fontSize:o,fontFamily:a.headingFontFamily,fontWeight:`700`,fill:n.text,textAlign:`center`,customName:`Heading`},{type:`textbox`,left:e*.12,top:t*.65,width:e*.76,text:i,fontSize:s,fontFamily:a.fontFamily,fontWeight:`400`,fill:`rgba(255,255,255,0.85)`,textAlign:`center`,customName:`Subtext`}]}function E(e,t,n,r,i,a,o){let s=Math.min(e,t)*.08,c=s*.45;return a?[{type:`rect`,left:0,top:0,width:e*.45,height:t,fill:n.accent,customName:`Color Panel`},{type:`textbox`,left:e*.52,top:t*.3,width:e*.42,text:r,fontSize:s,fontFamily:o.headingFontFamily,fontWeight:`700`,fill:n.text,textAlign:`left`,customName:`Heading`},{type:`textbox`,left:e*.52,top:t*.55,width:e*.42,text:i,fontSize:c,fontFamily:o.fontFamily,fontWeight:`400`,fill:`#64748b`,textAlign:`left`,customName:`Subtext`}]:[{type:`rect`,left:0,top:0,width:e,height:t*.45,fill:n.accent,customName:`Color Panel`},{type:`textbox`,left:e*.08,top:t*.52,width:e*.84,text:r,fontSize:s,fontFamily:o.headingFontFamily,fontWeight:`700`,fill:n.text,textAlign:`center`,customName:`Heading`},{type:`textbox`,left:e*.12,top:t*.72,width:e*.76,text:i,fontSize:c,fontFamily:o.fontFamily,fontWeight:`400`,fill:`#64748b`,textAlign:`center`,customName:`Subtext`}]}function D(e,t,n,r,i,a){let o=Math.min(e,t)*.09,s=o*.4;return[{type:`rect`,left:e*.1,top:t*.15,width:e*.8,height:t*.7,fill:`rgba(255,255,255,0.7)`,rx:20,ry:20,customName:`Card`},{type:`textbox`,left:e*.15,top:t*.3,width:e*.7,text:r,fontSize:o,fontFamily:a.headingFontFamily,fontWeight:`700`,fill:n.text,textAlign:`center`,customName:`Heading`},{type:`textbox`,left:e*.18,top:t*.55,width:e*.64,text:i,fontSize:s,fontFamily:a.fontFamily,fontWeight:`400`,fill:n.text,textAlign:`center`,opacity:.7,customName:`Subtext`},{type:`rect`,left:e*.3,top:t*.72,width:e*.4,height:Math.min(e,t)*.07,fill:n.accent,rx:8,ry:8,customName:`CTA Button`},{type:`textbox`,left:e*.3,top:t*.725,width:e*.4,text:`Learn More`,fontSize:s*.9,fontFamily:a.fontFamily,fontWeight:`600`,fill:`#ffffff`,textAlign:`center`,customName:`CTA Text`}]}var O=[{id:`ig-post-bold`,name:`Bold Announcement`,category:`social`,presetId:`instagram-post`,style:`bold`,description:`High-impact Instagram post with bold typography`,previewPrompt:`New Product Launch`},{id:`ig-post-minimal`,name:`Clean & Minimal`,category:`social`,presetId:`instagram-post`,style:`minimal`,description:`Minimalist Instagram post with elegant framing`,previewPrompt:`Mindful Living`},{id:`ig-story-gradient`,name:`Gradient Story`,category:`social`,presetId:`instagram-story`,style:`gradient`,description:`Modern gradient Instagram story`,previewPrompt:`Summer Vibes`},{id:`fb-cover-split`,name:`Split Cover`,category:`social`,presetId:`facebook-cover`,style:`split`,description:`Two-tone Facebook cover photo`,previewPrompt:`Welcome to Our Community`},{id:`linkedin-minimal`,name:`Professional Banner`,category:`business`,presetId:`linkedin-banner`,style:`minimal`,description:`Clean LinkedIn banner for professionals`,previewPrompt:`Innovation & Strategy`},{id:`twitter-bold`,name:`Tweet Graphic`,category:`social`,presetId:`twitter-post`,style:`bold`,description:`Eye-catching Twitter/X post graphic`,previewPrompt:`Breaking News`},{id:`yt-gradient`,name:`YouTube Thumbnail`,category:`social`,presetId:`youtube-thumbnail`,style:`gradient`,description:`Vibrant YouTube thumbnail`,previewPrompt:`Top 10 Tips`},{id:`presentation-centered`,name:`Title Slide`,category:`presentation`,presetId:`presentation`,style:`centered`,description:`Warm presentation title slide`,previewPrompt:`Quarterly Review`},{id:`bcard-minimal`,name:`Business Card`,category:`business`,presetId:`business-card`,style:`minimal`,description:`Elegant business card layout`,previewPrompt:`Jane Smith | Designer`},{id:`invoice-split`,name:`Invoice Header`,category:`business`,presetId:`invoice`,style:`split`,description:`Professional invoice header layout`,previewPrompt:`Invoice #1234`},{id:`sale-bold`,name:`Flash Sale`,category:`marketing`,presetId:`instagram-post`,style:`bold`,description:`High-energy sale promotion post`,previewPrompt:`50% Off Everything`},{id:`launch-gradient`,name:`Product Launch`,category:`marketing`,presetId:`instagram-post`,style:`gradient`,description:`Modern product launch announcement`,previewPrompt:`Introducing Our New Product`}];function k(){let e=new Map;for(let t of O){let n=e.get(t.category)??[];n.push(t),e.set(t.category,n)}return e}var A=`forge:canvas-state:v1`;function j(){if(typeof window>`u`)return{};try{let e=localStorage.getItem(A);if(!e)return{};let t=JSON.parse(e),n={savedDesigns:t.savedDesigns??{},artboardPresetId:t.artboardPresetId??null,activeTool:t.activeTool??`select`};return t.brandKit&&(n.brandKit=t.brandKit),n}catch{return{}}}function M(e){if(!(typeof window>`u`))try{let t={savedDesigns:e.savedDesigns,artboardPresetId:e.artboardPresetId,activeTool:e.activeTool,brandKit:e.brandKit};localStorage.setItem(A,JSON.stringify(t))}catch{}}var N=j(),P={activeTool:N.activeTool??`select`,artboardPresetId:N.artboardPresetId??`instagram-post`,artboardWidth:1080,artboardHeight:1080,selectedObjectIds:[],selectedObjectProperties:null,propertiesPanelOpen:!1,historyStack:[],historyIndex:-1,layers:[],zoomLevel:1,savedDesigns:N.savedDesigns??{},brandKit:N.brandKit??g,pendingGeneratePrompt:null},F=e()((e,t)=>({...P,setActiveTool:n=>{e({activeTool:n}),M(t())},setArtboard:(n,r,i)=>{e({artboardPresetId:n,artboardWidth:r,artboardHeight:i}),M(t())},setSelectedObjects:(t,n)=>{e({selectedObjectIds:t,selectedObjectProperties:n,propertiesPanelOpen:t.length>0})},clearSelection:()=>{e({selectedObjectIds:[],selectedObjectProperties:null})},setPropertiesPanelOpen:t=>{e({propertiesPanelOpen:t})},pushHistorySnapshot:t=>{e(e=>{let n=[...e.historyStack.slice(0,e.historyIndex+1),t].slice(-50);return{historyStack:n,historyIndex:n.length-1}})},undo:()=>{let n=t();if(n.historyIndex<=0)return null;let r=n.historyIndex-1;return e({historyIndex:r}),n.historyStack[r]??null},redo:()=>{let n=t();if(n.historyIndex>=n.historyStack.length-1)return null;let r=n.historyIndex+1;return e({historyIndex:r}),n.historyStack[r]??null},setLayers:t=>{e({layers:t})},setZoomLevel:t=>{e({zoomLevel:t})},saveDesign:(n,r,i)=>{e(e=>({savedDesigns:{...e.savedDesigns,[n]:{json:i,name:r,updatedAt:new Date().toISOString()}}})),M(t())},loadDesign:e=>t().savedDesigns[e]?.json??null,deleteDesign:n=>{e(e=>{let{[n]:t,...r}=e.savedDesigns;return{savedDesigns:r}}),M(t())},resetHistory:()=>{e({historyStack:[],historyIndex:-1})},setBrandKit:n=>{e({brandKit:n}),M(t())},updateBrandKit:n=>{e(e=>({brandKit:{...e.brandKit,...n}})),M(t())},requestCanvasGenerate:t=>{e({pendingGeneratePrompt:t})},consumePendingGenerate:()=>{let n=t().pendingGeneratePrompt;return n&&e({pendingGeneratePrompt:null}),n}}));export{i as _,k as a,p as c,u as d,l as f,a as g,o as h,S as i,f as l,s as m,O as n,h as o,c as p,g as r,m as s,F as t,d as u,r as v,n as y};
|
|
2
|
-
//# sourceMappingURL=canvasStateStore-
|
|
1
|
+
import{fn as e,on as t}from"./CompositeItem-DeDhuBZB.js";var n=t(`arrow-down`,[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]),r=t(`arrow-up`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),i=t(`chevrons-down`,[[`path`,{d:`m7 6 5 5 5-5`,key:`1lc07p`}],[`path`,{d:`m7 13 5 5 5-5`,key:`1d48rs`}]]),a=t(`chevrons-up`,[[`path`,{d:`m17 11-5-5-5 5`,key:`e8nh98`}],[`path`,{d:`m17 18-5-5-5 5`,key:`2avn1x`}]]),o=t(`circle`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]),s=t(`download`,[[`path`,{d:`M12 15V3`,key:`m9g1x1`}],[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`path`,{d:`m7 10 5 5 5-5`,key:`brsn70`}]]),c=t(`eye-off`,[[`path`,{d:`M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49`,key:`ct8e1f`}],[`path`,{d:`M14.084 14.158a3 3 0 0 1-4.242-4.242`,key:`151rxh`}],[`path`,{d:`M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143`,key:`13bj9a`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}]]),l=t(`eye`,[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`,key:`1nclc0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),u=t(`file-text`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),d=t(`minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),f=t(`palette`,[[`path`,{d:`M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z`,key:`e79jfc`}],[`circle`,{cx:`13.5`,cy:`6.5`,r:`.5`,fill:`currentColor`,key:`1okk4w`}],[`circle`,{cx:`17.5`,cy:`10.5`,r:`.5`,fill:`currentColor`,key:`f64h9f`}],[`circle`,{cx:`6.5`,cy:`12.5`,r:`.5`,fill:`currentColor`,key:`qy21gx`}],[`circle`,{cx:`8.5`,cy:`7.5`,r:`.5`,fill:`currentColor`,key:`fotxhn`}]]),p=t(`save`,[[`path`,{d:`M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z`,key:`1c8476`}],[`path`,{d:`M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7`,key:`1ydtos`}],[`path`,{d:`M7 3v4a1 1 0 0 0 1 1h7`,key:`t51u73`}]]),m=t(`square`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}]]),h=t(`undo-2`,[[`path`,{d:`M9 14 4 9l5-5`,key:`102s5s`}],[`path`,{d:`M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11`,key:`f3b9sd`}]]),g={primaryColor:`#6366f1`,secondaryColor:`#8b5cf6`,accentColor:`#f59e0b`,backgroundColor:`#ffffff`,textColor:`#1f2937`,fontFamily:`Inter, sans-serif`,headingFontFamily:`Inter, sans-serif`},_={bold:{bg:`#1f2937`,accent:`#f59e0b`,text:`#ffffff`},minimal:{bg:`#ffffff`,accent:`#6366f1`,text:`#1f2937`},gradient:{bg:`#4f46e5`,accent:`#818cf8`,text:`#ffffff`},split:{bg:`#f8fafc`,accent:`#0ea5e9`,text:`#0f172a`},centered:{bg:`#fef3c7`,accent:`#d97706`,text:`#78350f`}},v=[`bold`,`minimal`,`gradient`,`split`,`centered`];function y(e){let t=e.toLowerCase();return t.includes(`bold`)||t.includes(`sale`)||t.includes(`announcement`)?`bold`:t.includes(`minimal`)||t.includes(`clean`)||t.includes(`simple`)?`minimal`:t.includes(`gradient`)||t.includes(`modern`)||t.includes(`tech`)?`gradient`:t.includes(`split`)||t.includes(`compare`)||t.includes(`versus`)?`split`:t.includes(`warm`)||t.includes(`friendly`)||t.includes(`welcome`)?`centered`:v[Math.floor(Math.random()*v.length)]??`bold`}function b(e){let t=e.replace(/^(create|make|design|generate)\s+(a|an|me)?\s*/i,``).replace(/\s*(instagram|facebook|twitter|linkedin|youtube|social media|post|story|banner|cover|thumbnail)\s*/gi,``).replace(/\s*(about|for|with|featuring)\s*/i,`|`).trim().split(`|`).map(e=>e.trim()).filter(Boolean),n=t[0]??``;if(t.length>=2)return{heading:x(n),subtext:x(t.slice(1).join(` `))};if(n.length>30){let e=n.split(` `),t=Math.ceil(e.length/2);return{heading:x(e.slice(0,t).join(` `)),subtext:x(e.slice(t).join(` `))}}return{heading:n?x(n):`Your Title Here`,subtext:`Add your message`}}function x(e){return e.charAt(0).toUpperCase()+e.slice(1)}function S(e,t,n,r=g){let i=y(e),a=_[i],{heading:o,subtext:s}=b(e),c=t>n;Math.abs(t-n);let l=[];switch(l.push({type:`rect`,left:0,top:0,width:t,height:n,fill:a.bg,selectable:!1,customId:`__bg__`,customName:`Background`}),i){case`bold`:l.push(...C(t,n,a,o,s,r));break;case`minimal`:l.push(...w(t,n,a,o,s,r));break;case`gradient`:l.push(...T(t,n,a,o,s,r));break;case`split`:l.push(...E(t,n,a,o,s,c,r));break;case`centered`:l.push(...D(t,n,a,o,s,r))}return{objects:l}}function C(e,t,n,r,i,a){let o=Math.min(e,t)*.08,s=Math.min(e,t)*.1,c=s*.4;return[{type:`rect`,left:0,top:0,width:e,height:t*.06,fill:n.accent,customName:`Accent Bar`},{type:`textbox`,left:o,top:t*.3,width:e-o*2,text:r.toUpperCase(),fontSize:s,fontFamily:a.headingFontFamily,fontWeight:`900`,fill:n.text,textAlign:`left`,customName:`Heading`},{type:`textbox`,left:o,top:t*.55,width:e-o*2,text:i,fontSize:c,fontFamily:a.fontFamily,fontWeight:`400`,fill:n.accent,textAlign:`left`,customName:`Subtext`},{type:`rect`,left:o,top:t*.85,width:e*.3,height:4,fill:n.accent,customName:`Accent Line`}]}function w(e,t,n,r,i,a){let o=Math.min(e,t)*.08,s=o*.45;return[{type:`rect`,left:e*.04,top:t*.04,width:e*.92,height:t*.92,fill:`transparent`,stroke:n.accent,strokeWidth:2,customName:`Frame`},{type:`textbox`,left:e*.1,top:t*.35,width:e*.8,text:r,fontSize:o,fontFamily:a.headingFontFamily,fontWeight:`600`,fill:n.text,textAlign:`center`,customName:`Heading`},{type:`rect`,left:e*.4,top:t*.52,width:e*.2,height:2,fill:n.accent,customName:`Divider`},{type:`textbox`,left:e*.15,top:t*.58,width:e*.7,text:i,fontSize:s,fontFamily:a.fontFamily,fontWeight:`400`,fill:`#6b7280`,textAlign:`center`,customName:`Subtext`}]}function T(e,t,n,r,i,a){let o=Math.min(e,t)*.09,s=o*.4;return[{type:`rect`,left:0,top:t*.6,width:e,height:t*.4,fill:`rgba(0,0,0,0.3)`,customName:`Overlay`},{type:`ellipse`,left:e*.7,top:-t*.15,rx:e*.25,ry:e*.25,fill:n.accent,opacity:.3,customName:`Deco Circle`},{type:`textbox`,left:e*.08,top:t*.35,width:e*.84,text:r,fontSize:o,fontFamily:a.headingFontFamily,fontWeight:`700`,fill:n.text,textAlign:`center`,customName:`Heading`},{type:`textbox`,left:e*.12,top:t*.65,width:e*.76,text:i,fontSize:s,fontFamily:a.fontFamily,fontWeight:`400`,fill:`rgba(255,255,255,0.85)`,textAlign:`center`,customName:`Subtext`}]}function E(e,t,n,r,i,a,o){let s=Math.min(e,t)*.08,c=s*.45;return a?[{type:`rect`,left:0,top:0,width:e*.45,height:t,fill:n.accent,customName:`Color Panel`},{type:`textbox`,left:e*.52,top:t*.3,width:e*.42,text:r,fontSize:s,fontFamily:o.headingFontFamily,fontWeight:`700`,fill:n.text,textAlign:`left`,customName:`Heading`},{type:`textbox`,left:e*.52,top:t*.55,width:e*.42,text:i,fontSize:c,fontFamily:o.fontFamily,fontWeight:`400`,fill:`#64748b`,textAlign:`left`,customName:`Subtext`}]:[{type:`rect`,left:0,top:0,width:e,height:t*.45,fill:n.accent,customName:`Color Panel`},{type:`textbox`,left:e*.08,top:t*.52,width:e*.84,text:r,fontSize:s,fontFamily:o.headingFontFamily,fontWeight:`700`,fill:n.text,textAlign:`center`,customName:`Heading`},{type:`textbox`,left:e*.12,top:t*.72,width:e*.76,text:i,fontSize:c,fontFamily:o.fontFamily,fontWeight:`400`,fill:`#64748b`,textAlign:`center`,customName:`Subtext`}]}function D(e,t,n,r,i,a){let o=Math.min(e,t)*.09,s=o*.4;return[{type:`rect`,left:e*.1,top:t*.15,width:e*.8,height:t*.7,fill:`rgba(255,255,255,0.7)`,rx:20,ry:20,customName:`Card`},{type:`textbox`,left:e*.15,top:t*.3,width:e*.7,text:r,fontSize:o,fontFamily:a.headingFontFamily,fontWeight:`700`,fill:n.text,textAlign:`center`,customName:`Heading`},{type:`textbox`,left:e*.18,top:t*.55,width:e*.64,text:i,fontSize:s,fontFamily:a.fontFamily,fontWeight:`400`,fill:n.text,textAlign:`center`,opacity:.7,customName:`Subtext`},{type:`rect`,left:e*.3,top:t*.72,width:e*.4,height:Math.min(e,t)*.07,fill:n.accent,rx:8,ry:8,customName:`CTA Button`},{type:`textbox`,left:e*.3,top:t*.725,width:e*.4,text:`Learn More`,fontSize:s*.9,fontFamily:a.fontFamily,fontWeight:`600`,fill:`#ffffff`,textAlign:`center`,customName:`CTA Text`}]}var O=[{id:`ig-post-bold`,name:`Bold Announcement`,category:`social`,presetId:`instagram-post`,style:`bold`,description:`High-impact Instagram post with bold typography`,previewPrompt:`New Product Launch`},{id:`ig-post-minimal`,name:`Clean & Minimal`,category:`social`,presetId:`instagram-post`,style:`minimal`,description:`Minimalist Instagram post with elegant framing`,previewPrompt:`Mindful Living`},{id:`ig-story-gradient`,name:`Gradient Story`,category:`social`,presetId:`instagram-story`,style:`gradient`,description:`Modern gradient Instagram story`,previewPrompt:`Summer Vibes`},{id:`fb-cover-split`,name:`Split Cover`,category:`social`,presetId:`facebook-cover`,style:`split`,description:`Two-tone Facebook cover photo`,previewPrompt:`Welcome to Our Community`},{id:`linkedin-minimal`,name:`Professional Banner`,category:`business`,presetId:`linkedin-banner`,style:`minimal`,description:`Clean LinkedIn banner for professionals`,previewPrompt:`Innovation & Strategy`},{id:`twitter-bold`,name:`Tweet Graphic`,category:`social`,presetId:`twitter-post`,style:`bold`,description:`Eye-catching Twitter/X post graphic`,previewPrompt:`Breaking News`},{id:`yt-gradient`,name:`YouTube Thumbnail`,category:`social`,presetId:`youtube-thumbnail`,style:`gradient`,description:`Vibrant YouTube thumbnail`,previewPrompt:`Top 10 Tips`},{id:`presentation-centered`,name:`Title Slide`,category:`presentation`,presetId:`presentation`,style:`centered`,description:`Warm presentation title slide`,previewPrompt:`Quarterly Review`},{id:`bcard-minimal`,name:`Business Card`,category:`business`,presetId:`business-card`,style:`minimal`,description:`Elegant business card layout`,previewPrompt:`Jane Smith | Designer`},{id:`invoice-split`,name:`Invoice Header`,category:`business`,presetId:`invoice`,style:`split`,description:`Professional invoice header layout`,previewPrompt:`Invoice #1234`},{id:`sale-bold`,name:`Flash Sale`,category:`marketing`,presetId:`instagram-post`,style:`bold`,description:`High-energy sale promotion post`,previewPrompt:`50% Off Everything`},{id:`launch-gradient`,name:`Product Launch`,category:`marketing`,presetId:`instagram-post`,style:`gradient`,description:`Modern product launch announcement`,previewPrompt:`Introducing Our New Product`}];function k(){let e=new Map;for(let t of O){let n=e.get(t.category)??[];n.push(t),e.set(t.category,n)}return e}var A=`forge:canvas-state:v1`;function j(){if(typeof window>`u`)return{};try{let e=localStorage.getItem(A);if(!e)return{};let t=JSON.parse(e),n={savedDesigns:t.savedDesigns??{},artboardPresetId:t.artboardPresetId??null,activeTool:t.activeTool??`select`};return t.brandKit&&(n.brandKit=t.brandKit),n}catch{return{}}}function M(e){if(!(typeof window>`u`))try{let t={savedDesigns:e.savedDesigns,artboardPresetId:e.artboardPresetId,activeTool:e.activeTool,brandKit:e.brandKit};localStorage.setItem(A,JSON.stringify(t))}catch{}}var N=j(),P={activeTool:N.activeTool??`select`,artboardPresetId:N.artboardPresetId??`instagram-post`,artboardWidth:1080,artboardHeight:1080,selectedObjectIds:[],selectedObjectProperties:null,propertiesPanelOpen:!1,historyStack:[],historyIndex:-1,layers:[],zoomLevel:1,savedDesigns:N.savedDesigns??{},brandKit:N.brandKit??g,pendingGeneratePrompt:null},F=e()((e,t)=>({...P,setActiveTool:n=>{e({activeTool:n}),M(t())},setArtboard:(n,r,i)=>{e({artboardPresetId:n,artboardWidth:r,artboardHeight:i}),M(t())},setSelectedObjects:(t,n)=>{e({selectedObjectIds:t,selectedObjectProperties:n,propertiesPanelOpen:t.length>0})},clearSelection:()=>{e({selectedObjectIds:[],selectedObjectProperties:null})},setPropertiesPanelOpen:t=>{e({propertiesPanelOpen:t})},pushHistorySnapshot:t=>{e(e=>{let n=[...e.historyStack.slice(0,e.historyIndex+1),t].slice(-50);return{historyStack:n,historyIndex:n.length-1}})},undo:()=>{let n=t();if(n.historyIndex<=0)return null;let r=n.historyIndex-1;return e({historyIndex:r}),n.historyStack[r]??null},redo:()=>{let n=t();if(n.historyIndex>=n.historyStack.length-1)return null;let r=n.historyIndex+1;return e({historyIndex:r}),n.historyStack[r]??null},setLayers:t=>{e({layers:t})},setZoomLevel:t=>{e({zoomLevel:t})},saveDesign:(n,r,i)=>{e(e=>({savedDesigns:{...e.savedDesigns,[n]:{json:i,name:r,updatedAt:new Date().toISOString()}}})),M(t())},loadDesign:e=>t().savedDesigns[e]?.json??null,deleteDesign:n=>{e(e=>{let{[n]:t,...r}=e.savedDesigns;return{savedDesigns:r}}),M(t())},resetHistory:()=>{e({historyStack:[],historyIndex:-1})},setBrandKit:n=>{e({brandKit:n}),M(t())},updateBrandKit:n=>{e(e=>({brandKit:{...e.brandKit,...n}})),M(t())},requestCanvasGenerate:t=>{e({pendingGeneratePrompt:t})},consumePendingGenerate:()=>{let n=t().pendingGeneratePrompt;return n&&e({pendingGeneratePrompt:null}),n}}));export{i as _,k as a,p as c,u as d,l as f,a as g,o as h,S as i,f as l,s as m,O as n,h as o,c as p,g as r,m as s,F as t,d as u,r as v,n as y};
|
|
2
|
+
//# sourceMappingURL=canvasStateStore-DJ_OzrrC.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/__vite-browser-external-2W3EstLn.js","assets/rolldown-runtime-hePW80VL.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{n as e,r as t}from"./rolldown-runtime-hePW80VL.js";import{$ as n,At as r,B as i,Bn as a,Bt as o,C as s,Cn as c,Di as l,Dn as u,Dt as d,Et as f,F as p,Fa as m,Fn as h,Fr as g,Ft as ee,Gn as _,Ia as v,Ir as te,J as ne,Jn as y,K as b,Kn as x,La as S,Ln as C,Lr as w,Lt as T,Mi as E,Mt as D,N as O,Nt as k,O as A,On as j,Ot as M,P as N,Pa as P,Pn as F,Pt as re,Qn as ie,Qt as ae,R as oe,Rn as se,Sn as ce,T as le,Tr as ue,Tt as de,U as fe,Vr as pe,Vt as me,W as he,Wa as ge,Xn as _e,Y as ve,Yi as ye,Yn as be,Z as xe,Zn as Se,Zt as Ce,_a as we,_n as Te,_r as Ee,at as De,bt as Oe,ci as ke,cn as Ae,ct as je,di as Me,dr as Ne,dt as Pe,ei as Fe,en as Ie,er as Le,fi as Re,fr as ze,ft as Be,gi as Ve,gn as I,gt as He,hn as Ue,hr as We,ht as Ge,in as Ke,j as qe,jn as Je,jt as Ye,ki as Xe,kt as Ze,li as Qe,mn as $e,mt as et,nr as tt,nt,on as rt,pi as it,pt as at,q as ot,qn as st,ri as ct,rn as lt,s as ut,si as dt,st as ft,ui as pt,un as mt,ut as ht,vn as gt,vt as _t,w as vt,x as yt,xn as bt,yn as xt,yt as St,z as Ct,zn as wt}from"./Stream-mUTFnSY9.js";import{a as Tt,c as Et,l as Dt,n as Ot,o as kt,r as At,s as jt}from"./atomRegistry-C1yW8tyM.js";import{B as Mt,Dn as Nt,En as Pt,Ft,Ht as It,In as Lt,Ln as Rt,Nt as zt,On as Bt,Pn as Vt,Pt as Ht,Vt as Ut,Wt,Y as Gt,_n as Kt,c as qt,cn as Jt,d as Yt,f as Xt,fn as Zt,g as Qt,hn as $t,kn as en,ln as tn,m as nn,nn as rn,nt as an,o as on,p as sn,pn as cn,s as L,u as ln,wn as un,xn as dn,yn as fn,z as pn}from"./src-CoTxmdk3.js";import{t as mn}from"./preload-helper-Czpn1I53.js";var hn=t(ge(),1),gn={[Symbol.iterator](){return _n}},_n={next(){return{done:!0,value:void 0}}},vn=()=>gn,yn=new WeakMap;function bn(e,t){let n=yn.get(e);n===void 0&&(n=new WeakMap,yn.set(e,n));let r=n.get(t);if(r!==void 0)return r;let i={subscribe(n){return e.subscribe(t,n)},snapshot(){return e.get(t)},getServerSnapshot(){return Tt(t,e)}};return n.set(t,i),i}function xn(e,t){let n=bn(e,t);return hn.useSyncExternalStore(n.subscribe,n.snapshot,n.getServerSnapshot)}var Sn=(e,t)=>{let n=hn.useContext(At);return t?xn(n,hn.useMemo(()=>Et(e,t),[e,t])):xn(n,e)},Cn=(e,t,n)=>{let r=hn.useContext(At);hn.useEffect(()=>r.subscribe(e,t,n),[r,e,t,n?.immediate])},wn=`~effect/FiberSet`,Tn=e=>we(e,wn),En={[wn]:wn,[Symbol.iterator](){return this.state._tag===`Closed`?vn():this.state.backing[Symbol.iterator]()},...ye,toJSON(){return{_id:`FiberMap`,state:this.state}}},Dn=(e,t)=>{let n=Object.create(En);return n.state={_tag:`Open`,backing:e},n.deferred=t,n},On=()=>oe(Ke(()=>Dn(new Set,be())),e=>lt(()=>{let t=e.state;if(t._tag===`Closed`)return I;e.state={_tag:`Closed`};let n=t.backing;return p(n).pipe(y(e.deferred))})),kn=-1,An=w(g(Ne,te(kn))),jn=m(e=>Tn(e[0]),(e,t,n)=>{if(e.state._tag===`Closed`){t.interruptUnsafe(kn);return}e.state.backing.has(t)||(e.state.backing.add(t),t.addObserver(r=>{e.state._tag!==`Closed`&&(e.state.backing.delete(t),tt(r)&&(n?.propagateInterruption===!0?!An(r.cause):!We(r.cause))&&st(e.deferred,r))}))}),Mn=function(){let e;return()=>(e===void 0&&(e=o(et)),e)}(),Nn=e=>()=>Oe(ot(),t=>{let n=me(t);return(t,r)=>{if(e.state._tag===`Closed`)return Mn();let i=n(t,r);return jn(e,i),i}}),Pn=e=>x(e.deferred),Fn=`~effect/socket/Socket`,In=Qe(`effect/socket/Socket`),Ln=`~effect/socket/Socket/CloseEvent`,Rn=e=>we(e,Ln),zn=`~effect/socket/Socket/SocketError`,Bn=e=>we(e,zn),Vn=class extends tn(`effect/socket/Socket/SocketReadError`)({_tag:Lt(`SocketReadError`),cause:Jt}){message=`An error occurred during Read`},Hn=class extends tn(`effect/socket/Socket/SocketWriteError`)({_tag:Lt(`SocketWriteError`),cause:Jt}){message=`An error occurred during Write`},Un=class extends tn(`effect/socket/Socket/SocketOpenError`)({_tag:Lt(`SocketOpenError`),kind:Zt([`Unknown`,`Timeout`]),cause:Jt}){get message(){return this.kind===`Timeout`?`timeout waiting for "open"`:`An error occurred during Open`}},Wn=class extends tn(`effect/socket/Socket/SocketCloseError`)({_tag:Lt(`SocketCloseError`),code:$t,closeReason:Vt(Kt)}){static filterClean(e){return function(t){return Kn.is(t)&&t.reason._tag===`SocketCloseError`&&e(t.reason.code)?dt(t.reason):Fe(t)}}get message(){return this.closeReason?`${this.code}: ${this.closeReason}`:`${this.code}`}},Gn=dn([Vn,Hn,Un,Wn]),Kn=class extends fn(zn)(`SocketError`,{_tag:Lt(`SocketError`),reason:Gn}){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[zn]=zn;static is(e){return Bn(e)}message=this.reason.message},qn=e=>!0,Jn=class extends Qe()(`~effect/socket/Socket/WebSocket`){},Yn=class extends Qe()(`@effect/platform/Socket/WebSocketConstructor`){},Xn=(e,t)=>Yn.use(n=>Zn(oe((typeof e==`string`?Ie(e):e).pipe(Oe(e=>n(e,t?.protocols))),e=>Ke(()=>e.close(1e3))),t)),Zn=(e,t)=>gt(r=>{let i,a=qe(!1),o=r.context,s=t?.closeCodeIsError??qn,c=(r,c)=>Ce(De(function*(o){let l=yield*On().pipe(_(o)),u=yield*_(e,o),d=yield*re(Nn(l)(),Jn,u),f=!1;function p(e){if(e.data instanceof Blob){let t=nt(Ye(()=>e.data.arrayBuffer()),e=>{let t=r(new Uint8Array(e));return He(t)?t:I});return d(t)}let t=r(e.data);He(t)&&d(t)}function m(e){u.removeEventListener(`message`,p),u.removeEventListener(`close`,h),st(l.deferred,n(new Kn({reason:f?new Vn({cause:e}):new Un({kind:`Unknown`,cause:e})})))}function h(e){let t=typeof e.code==`number`?e.code:1001;u.removeEventListener(`message`,p),u.removeEventListener(`error`,m),st(l.deferred,n(new Kn({reason:new Wn({code:t,closeReason:e.reason})})))}if(u.addEventListener(`close`,h,{once:!0}),u.addEventListener(`error`,m,{once:!0}),u.addEventListener(`message`,p),u.readyState!==1){let e=be();u.addEventListener(`open`,()=>{f=!0,st(e,I)},{once:!0}),yield*x(e).pipe(mt({duration:t?.openTimeout??1e4,orElse:()=>n(new Kn({reason:new Un({kind:`Timeout`,cause:Error(`timeout waiting for "open"`)})}))}),ee(Pn(l)))}return f=!0,i=u,a.openUnsafe(),c?.onOpen&&(yield*c.onOpen),yield*b(Pn(l),Wn.filterClean(e=>!s(e)),()=>I)})).pipe($e(e=>Ve(o,e)),xe(Ke(()=>{a.closeUnsafe(),i=void 0}))),l=new TextEncoder,u=(e,t)=>c(t=>typeof t==`string`?e(l.encode(t)):t instanceof Uint8Array?e(t):e(new Uint8Array(t)),t),d=Ie(e=>a.whenOpen(Ke(()=>{let t=i;Rn(e)?t.close(e.code,e.reason):t.send(e)})));return Ie(In.of({[Fn]:Fn,run:u,runRaw:c,writer:d}))}),Qn=v(Xn,Je(In)),$n=class extends Qe()(`effect/workers/Transferable/Collector`){},er=()=>{let e=[],t=t=>{e.push(...t)},n=()=>e,r=()=>{let t=e;return e=[],t};return $n.of({addAllUnsafe:t,addAll:e=>Ke(()=>t(e)),readUnsafe:n,read:Ke(n),clearUnsafe:r,clear:Ke(r)})},tr=`~effect/workers/WorkerError`,nr=class extends tn(`effect/workers/WorkerError/WorkerSpawnError`)({_tag:Lt(`WorkerSpawnError`),message:Kt,cause:Vt(Jt)}){},rr=class extends tn(`effect/workers/WorkerError/WorkerSendError`)({_tag:Lt(`WorkerSendError`),message:Kt,cause:Vt(Jt)}){},ir=class extends tn(`effect/workers/WorkerError/WorkerReceiveError`)({_tag:Lt(`WorkerReceiveError`),message:Kt,cause:Vt(Jt)}){},ar=class extends tn(`effect/workers/WorkerError/WorkerUnknownError`)({_tag:Lt(`WorkerUnknownError`),message:Kt,cause:Vt(Jt)}){},or=dn([nr,rr,ir,ar]);tn(tr)({_tag:Lt(`WorkerError`),reason:or});var sr=`~effect/rpc/RpcClientError`,cr=class extends tn(`effect/rpc/RpcClientError/RpcClientDefect`)({_tag:Lt(`RpcClientDefect`),message:Kt,cause:Jt}){},lr=class extends tn(sr)({_tag:Lt(`RpcClientError`),reason:dn([or,Gn,rn,cr])}){[sr]=sr;get message(){return`${this.reason._tag}: ${this.reason.message}`}},ur=e=>typeof e==`bigint`?e:BigInt(e),dr={_tag:`Ping`},fr;try{fr=new TextDecoder}catch{}var R,pr,z=0,mr=[],hr=mr,gr=0,B={},V,_r,vr=0,yr=0,br,xr,Sr=[],H,Cr={useRecords:!1,mapsAsObjects:!0},wr=class{},Tr=new wr;Tr.name=`MessagePack 0xC1`;var Er=!1,Dr=2,Or,kr,Ar;try{Function(``)}catch{Dr=1/0}var jr=class e{constructor(e){e&&(e.useRecords===!1&&e.mapsAsObjects===void 0&&(e.mapsAsObjects=!0),e.sequential&&e.trusted!==!1&&(e.trusted=!0,!e.structures&&e.useRecords!=0&&(e.structures=[],e.maxSharedStructures||=0)),e.structures?e.structures.sharedLength=e.structures.length:e.getStructures&&((e.structures=[]).uninitialized=!0,e.structures.sharedLength=0),e.int64AsNumber&&(e.int64AsType=`number`)),Object.assign(this,e)}unpack(t,n){if(R)return ii(()=>(ai(),this?this.unpack(t,n):e.prototype.unpack.call(Cr,t,n)));!t.buffer&&t.constructor===ArrayBuffer&&(t=typeof Buffer<`u`?Buffer.from(t):new Uint8Array(t)),typeof n==`object`?(pr=n.end||t.length,z=n.start||0):(z=0,pr=n>-1?n:t.length),gr=0,yr=0,_r=null,hr=mr,br=null,R=t;try{H=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))}catch(e){throw R=null,t instanceof Uint8Array?e:Error(`Source must be a Uint8Array or Buffer but was a `+(t&&typeof t==`object`?t.constructor.name:typeof t))}if(this instanceof e){if(B=this,this.structures)return V=this.structures,Mr(n);(!V||V.length>0)&&(V=[])}else B=Cr,(!V||V.length>0)&&(V=[]);return Mr(n)}unpackMultiple(e,t){let n,r=0;try{Er=!0;let i=e.length,a=this?this.unpack(e,i):si.unpack(e,i);if(t){if(t(a,r,z)===!1)return;for(;z<i;)if(r=z,t(Mr(),r,z)===!1)return}else{for(n=[a];z<i;)r=z,n.push(Mr());return n}}catch(e){throw e.lastPosition=r,e.values=n,e}finally{Er=!1,ai()}}_mergeStructures(e,t){kr&&(e=kr.call(this,e)),e||=[],Object.isFrozen(e)&&(e=e.map(e=>e.slice(0)));for(let t=0,n=e.length;t<n;t++){let n=e[t];n&&(n.isShared=!0,t>=32&&(n.highByte=t-32>>5))}e.sharedLength=e.length;for(let n in t||[])if(n>=0){let r=e[n],i=t[n];i&&(r&&((e.restoreStructures||(e.restoreStructures=[]))[n]=r),e[n]=i)}return this.structures=e}decode(e,t){return this.unpack(e,t)}};function Mr(e){try{if(!B.trusted&&!Er){let e=V.sharedLength||0;e<V.length&&(V.length=e)}let t;if(B.randomAccessStructure&&R[z]<64&&R[z]>=32&&Or?(t=Or(R,z,pr,B),R=null,!(e&&e.lazy)&&t&&(t=t.toJSON()),z=pr):t=U(),br&&=(z=br.postBundlePosition,null),Er&&(V.restoreStructures=null),z==pr)V&&V.restoreStructures&&Nr(),V=null,R=null,xr&&=null;else if(z>pr)throw Error(`Unexpected end of MessagePack data`);else if(!Er){let e;try{e=JSON.stringify(t,(e,t)=>typeof t==`bigint`?`${t}n`:t).slice(0,100)}catch(t){e=`(JSON view not available `+t+`)`}throw Error(`Data read, but end of buffer not reached `+e)}return t}catch(e){throw V&&V.restoreStructures&&Nr(),ai(),(e instanceof RangeError||e.message.startsWith(`Unexpected end of buffer`)||z>pr)&&(e.incomplete=!0),e}}function Nr(){for(let e in V.restoreStructures)V[e]=V.restoreStructures[e];V.restoreStructures=null}function U(){let e=R[z++];if(e<160)if(e<128){if(e<64)return e;{let t=V[e&63]||B.getStructures&&Lr()[e&63];return t?(t.read||=Fr(t,e&63),t.read()):e}}else if(e<144){if(e-=128,B.mapsAsObjects){let t={};for(let n=0;n<e;n++){let e=Zr();e===`__proto__`&&(e=`__proto_`),t[e]=U()}return t}{let t=new Map;for(let n=0;n<e;n++)t.set(U(),U());return t}}else{e-=144;let t=Array(e);for(let n=0;n<e;n++)t[n]=U();return B.freezeData?Object.freeze(t):t}if(e<192){let t=e-160;if(yr>=z)return _r.slice(z-vr,(z+=t)-vr);if(yr==0&&pr<140){let e=t<16?Kr(t):Gr(t);if(e!=null)return e}return Rr(t)}{let t;switch(e){case 192:return null;case 193:return br?(t=U(),t>0?br[1].slice(br.position1,br.position1+=t):br[0].slice(br.position0,br.position0-=t)):Tr;case 194:return!1;case 195:return!0;case 196:if(t=R[z++],t===void 0)throw Error(`Unexpected end of buffer`);return Jr(t);case 197:return t=H.getUint16(z),z+=2,Jr(t);case 198:return t=H.getUint32(z),z+=4,Jr(t);case 199:return Yr(R[z++]);case 200:return t=H.getUint16(z),z+=2,Yr(t);case 201:return t=H.getUint32(z),z+=4,Yr(t);case 202:if(t=H.getFloat32(z),B.useFloat32>2){let e=oi[(R[z]&127)<<1|R[z+1]>>7];return z+=4,(e*t+(t>0?.5:-.5)>>0)/e}return z+=4,t;case 203:return t=H.getFloat64(z),z+=8,t;case 204:return R[z++];case 205:return t=H.getUint16(z),z+=2,t;case 206:return t=H.getUint32(z),z+=4,t;case 207:return B.int64AsType===`number`?(t=H.getUint32(z)*4294967296,t+=H.getUint32(z+4)):B.int64AsType===`string`?t=H.getBigUint64(z).toString():B.int64AsType===`auto`?(t=H.getBigUint64(z),t<=BigInt(2)<<BigInt(52)&&(t=Number(t))):t=H.getBigUint64(z),z+=8,t;case 208:return H.getInt8(z++);case 209:return t=H.getInt16(z),z+=2,t;case 210:return t=H.getInt32(z),z+=4,t;case 211:return B.int64AsType===`number`?(t=H.getInt32(z)*4294967296,t+=H.getUint32(z+4)):B.int64AsType===`string`?t=H.getBigInt64(z).toString():B.int64AsType===`auto`?(t=H.getBigInt64(z),t>=BigInt(-2)<<BigInt(52)&&t<=BigInt(2)<<BigInt(52)&&(t=Number(t))):t=H.getBigInt64(z),z+=8,t;case 212:if(t=R[z++],t==114)return $r(R[z++]&63);{let e=Sr[t];if(e)return e.read?(z++,e.read(U())):e.noBuffer?(z++,e()):e(R.subarray(z,++z));throw Error(`Unknown extension `+t)}case 213:return t=R[z],t==114?(z++,$r(R[z++]&63,R[z++])):Yr(2);case 214:return Yr(4);case 215:return Yr(8);case 216:return Yr(16);case 217:return t=R[z++],yr>=z?_r.slice(z-vr,(z+=t)-vr):zr(t);case 218:return t=H.getUint16(z),z+=2,yr>=z?_r.slice(z-vr,(z+=t)-vr):Br(t);case 219:return t=H.getUint32(z),z+=4,yr>=z?_r.slice(z-vr,(z+=t)-vr):Vr(t);case 220:return t=H.getUint16(z),z+=2,Ur(t);case 221:return t=H.getUint32(z),z+=4,Ur(t);case 222:return t=H.getUint16(z),z+=2,Wr(t);case 223:return t=H.getUint32(z),z+=4,Wr(t);default:if(e>=224)return e-256;if(e===void 0){let e=Error(`Unexpected end of MessagePack data`);throw e.incomplete=!0,e}throw Error(`Unknown MessagePack token `+e)}}}var Pr=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function Fr(e,t){function n(){if(n.count++>Dr){let n=e.read=Function(`r`,`return function(){return `+(B.freezeData?`Object.freeze`:``)+`({`+e.map(e=>e===`__proto__`?`__proto_:r()`:Pr.test(e)?e+`:r()`:`[`+JSON.stringify(e)+`]:r()`).join(`,`)+`})}`)(U);return e.highByte===0&&(e.read=Ir(t,e.read)),n()}let r={};for(let t=0,n=e.length;t<n;t++){let n=e[t];n===`__proto__`&&(n=`__proto_`),r[n]=U()}return B.freezeData?Object.freeze(r):r}return n.count=0,e.highByte===0?Ir(t,n):n}var Ir=(e,t)=>function(){let n=R[z++];if(n===0)return t();let r=e<32?-(e+(n<<5)):e+(n<<5),i=V[r]||Lr()[r];if(!i)throw Error(`Record id is not defined for `+r);return i.read||=Fr(i,e),i.read()};function Lr(){let e=ii(()=>(R=null,B.getStructures()));return V=B._mergeStructures(e,V)}var Rr=Hr,zr=Hr,Br=Hr,Vr=Hr;function Hr(e){let t;if(e<16&&(t=Kr(e)))return t;if(e>64&&fr)return fr.decode(R.subarray(z,z+=e));let n=z+e,r=[];for(t=``;z<n;){let e=R[z++];if(!(e&128))r.push(e);else if((e&224)==192){let t=R[z++]&63,n=(e&31)<<6|t;n<128?r.push(65533):r.push(n)}else if((e&240)==224){let t=R[z++]&63,n=R[z++]&63,i=(e&31)<<12|t<<6|n;i<2048||i>=55296&&i<=57343?r.push(65533):r.push(i)}else if((e&248)==240){let t=R[z++]&63,n=R[z++]&63,i=R[z++]&63,a=(e&7)<<18|t<<12|n<<6|i;a<65536||a>1114111?r.push(65533):a>65535?(a-=65536,r.push(a>>>10&1023|55296),a=56320|a&1023,r.push(a)):r.push(a)}else r.push(65533);r.length>=4096&&(t+=W.apply(String,r),r.length=0)}return r.length>0&&(t+=W.apply(String,r)),t}function Ur(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=U();return B.freezeData?Object.freeze(t):t}function Wr(e){if(B.mapsAsObjects){let t={};for(let n=0;n<e;n++){let e=Zr();e===`__proto__`&&(e=`__proto_`),t[e]=U()}return t}{let t=new Map;for(let n=0;n<e;n++)t.set(U(),U());return t}}var W=String.fromCharCode;function Gr(e){let t=z,n=Array(e);for(let r=0;r<e;r++){let e=R[z++];if((e&128)>0){z=t;return}n[r]=e}return W.apply(String,n)}function Kr(e){if(e<4)if(e<2){if(e===0)return``;{let e=R[z++];if((e&128)>1){--z;return}return W(e)}}else{let t=R[z++],n=R[z++];if((t&128)>0||(n&128)>0){z-=2;return}if(e<3)return W(t,n);let r=R[z++];if((r&128)>0){z-=3;return}return W(t,n,r)}{let t=R[z++],n=R[z++],r=R[z++],i=R[z++];if((t&128)>0||(n&128)>0||(r&128)>0||(i&128)>0){z-=4;return}if(e<6){if(e===4)return W(t,n,r,i);{let e=R[z++];if((e&128)>0){z-=5;return}return W(t,n,r,i,e)}}if(e<8){let a=R[z++],o=R[z++];if((a&128)>0||(o&128)>0){z-=6;return}if(e<7)return W(t,n,r,i,a,o);let s=R[z++];if((s&128)>0){z-=7;return}return W(t,n,r,i,a,o,s)}{let a=R[z++],o=R[z++],s=R[z++],c=R[z++];if((a&128)>0||(o&128)>0||(s&128)>0||(c&128)>0){z-=8;return}if(e<10){if(e===8)return W(t,n,r,i,a,o,s,c);{let e=R[z++];if((e&128)>0){z-=9;return}return W(t,n,r,i,a,o,s,c,e)}}if(e<12){let l=R[z++],u=R[z++];if((l&128)>0||(u&128)>0){z-=10;return}if(e<11)return W(t,n,r,i,a,o,s,c,l,u);let d=R[z++];if((d&128)>0){z-=11;return}return W(t,n,r,i,a,o,s,c,l,u,d)}{let l=R[z++],u=R[z++],d=R[z++],f=R[z++];if((l&128)>0||(u&128)>0||(d&128)>0||(f&128)>0){z-=12;return}if(e<14){if(e===12)return W(t,n,r,i,a,o,s,c,l,u,d,f);{let e=R[z++];if((e&128)>0){z-=13;return}return W(t,n,r,i,a,o,s,c,l,u,d,f,e)}}{let p=R[z++],m=R[z++];if((p&128)>0||(m&128)>0){z-=14;return}if(e<15)return W(t,n,r,i,a,o,s,c,l,u,d,f,p,m);let h=R[z++];if((h&128)>0){z-=15;return}return W(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}}}}}function qr(){let e=R[z++],t;if(e<192)t=e-160;else switch(e){case 217:t=R[z++];break;case 218:t=H.getUint16(z),z+=2;break;case 219:t=H.getUint32(z),z+=4;break;default:throw Error(`Expected string`)}return Hr(t)}function Jr(e){return B.copyBuffers?Uint8Array.prototype.slice.call(R,z,z+=e):R.subarray(z,z+=e)}function Yr(e){let t=R[z++];if(Sr[t]){let n;return Sr[t](R.subarray(z,n=z+=e),e=>{z=e;try{return U()}finally{z=n}})}throw Error(`Unknown extension type `+t)}var Xr=Array(4096);function Zr(){let e=R[z++];if(e>=160&&e<192){if(e-=160,yr>=z)return _r.slice(z-vr,(z+=e)-vr);if(!(yr==0&&pr<180))return Rr(e)}else return z--,Qr(U());let t=(e<<5^(e>1?H.getUint16(z):e>0?R[z]:0))&4095,n=Xr[t],r=z,i=z+e-3,a,o=0;if(n&&n.bytes==e){for(;r<i;){if(a=H.getUint32(r),a!=n[o++]){r=1879048192;break}r+=4}for(i+=3;r<i;)if(a=R[r++],a!=n[o++]){r=1879048192;break}if(r===i)return z=r,n.string;i-=3,r=z}for(n=[],Xr[t]=n,n.bytes=e;r<i;)a=H.getUint32(r),n.push(a),r+=4;for(i+=3;r<i;)a=R[r++],n.push(a);let s=e<16?Kr(e):Gr(e);return s==null?n.string=Rr(e):n.string=s}function Qr(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return e.toString();if(e==null)return e+``;if(B.allowArraysInMapKeys&&Array.isArray(e)&&e.flat().every(e=>[`string`,`number`,`boolean`,`bigint`].includes(typeof e)))return e.flat().toString();throw Error(`Invalid property type for record: ${typeof e}`)}var $r=(e,t)=>{let n=U().map(Qr),r=e;t!==void 0&&(e=e<32?-((t<<5)+e):(t<<5)+e,n.highByte=t);let i=V[e];return i&&(i.isShared||Er)&&((V.restoreStructures||(V.restoreStructures=[]))[e]=i),V[e]=n,n.read=Fr(n,r),n.read()};Sr[0]=()=>{},Sr[0].noBuffer=!0,Sr[66]=e=>{let t=e.byteLength%8||8,n=BigInt(e[0]&128?e[0]-256:e[0]);for(let r=1;r<t;r++)n<<=BigInt(8),n+=BigInt(e[r]);if(e.byteLength!==t){let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=(e,t)=>{let n=t-e;if(n<=40){let n=r.getBigUint64(e);for(let i=e+8;i<t;i+=8)n<<=64n,n|=r.getBigUint64(i);return n}let a=e+(n>>4<<3),o=i(e,a),s=i(a,t);return o<<BigInt((t-a)*8)|s};n=n<<BigInt((r.byteLength-t)*8)|i(t,r.byteLength)}return n};var ei={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError:typeof AggregateError==`function`?AggregateError:null};Sr[101]=()=>{let e=U();if(!ei[e[0]]){let t=Error(e[1],{cause:e[2]});return t.name=e[0],t}return ei[e[0]](e[1],{cause:e[2]})},Sr[105]=e=>{if(B.structuredClone===!1)throw Error(`Structured clone extension is disabled`);let t=H.getUint32(z-4);xr||=new Map;let n=R[z],r;r=n>=144&&n<160||n==220||n==221?[]:n>=128&&n<144||n==222||n==223?new Map:(n>=199&&n<=201||n>=212&&n<=216)&&R[z+1]===115?new Set:{};let i={target:r};xr.set(t,i);let a=U();if(i.used)Object.assign(r,a);else return i.target=a;if(r instanceof Map)for(let[e,t]of a.entries())r.set(e,t);if(r instanceof Set)for(let e of Array.from(a))r.add(e);return r},Sr[112]=e=>{if(B.structuredClone===!1)throw Error(`Structured clone extension is disabled`);let t=H.getUint32(z-4),n=xr.get(t);return n.used=!0,n.target},Sr[115]=()=>new Set(U());var ti=[`Int8`,`Uint8`,`Uint8Clamped`,`Int16`,`Uint16`,`Int32`,`Uint32`,`Float32`,`Float64`,`BigInt64`,`BigUint64`].map(e=>e+`Array`),ni=typeof globalThis==`object`?globalThis:window;Sr[116]=e=>{let t=e[0],n=Uint8Array.prototype.slice.call(e,1).buffer,r=ti[t];if(!r){if(t===16)return n;if(t===17)return new DataView(n);throw Error(`Could not find typed array for code `+t)}return new ni[r](n)},Sr[120]=()=>{let e=U();return new RegExp(e[0],e[1])};var ri=[];Sr[98]=e=>{let t=(e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3],n=z;return z+=t-e.length,br=ri,br=[qr(),qr()],br.position0=0,br.position1=0,br.postBundlePosition=z,z=n,U()},Sr[255]=e=>e.length==4?new Date((e[0]*16777216+(e[1]<<16)+(e[2]<<8)+e[3])*1e3):e.length==8?new Date(((e[0]<<22)+(e[1]<<14)+(e[2]<<6)+(e[3]>>2))/1e6+((e[3]&3)*4294967296+e[4]*16777216+(e[5]<<16)+(e[6]<<8)+e[7])*1e3):e.length==12?new Date(((e[0]<<24)+(e[1]<<16)+(e[2]<<8)+e[3])/1e6+((e[4]&128?-281474976710656:0)+e[6]*1099511627776+e[7]*4294967296+e[8]*16777216+(e[9]<<16)+(e[10]<<8)+e[11])*1e3):new Date(`invalid`);function ii(e){Ar&&Ar();let t=pr,n=z,r=gr,i=vr,a=yr,o=_r,s=hr,c=xr,l=br,u=new Uint8Array(R.slice(0,pr)),d=V,f=V.slice(0,V.length),p=B,m=Er,h=e();return pr=t,z=n,gr=r,vr=i,yr=a,_r=o,hr=s,xr=c,br=l,R=u,Er=m,V=d,V.splice(0,V.length,...f),B=p,H=new DataView(R.buffer,R.byteOffset,R.byteLength),h}function ai(){R=null,xr=null,V=null}var oi=Array(147);for(let e=0;e<256;e++)oi[e]=+(`1e`+Math.floor(45.15-e*.30103));var si=new jr({useRecords:!1});si.unpack,si.unpackMultiple,si.unpack;var ci={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4};new Uint8Array(new Float32Array(1).buffer,0,4);var li;try{li=new TextEncoder}catch{}var ui,di,fi=typeof Buffer<`u`,pi=fi?function(e){return Buffer.allocUnsafeSlow(e)}:Uint8Array,mi=fi?Buffer:Uint8Array,hi=fi?4294967296:2144337920,G,gi,K,q=0,_i,J=null,vi,yi=21760,bi=/[\u0080-\uFFFF]/,xi=Symbol(`record-id`),Si=class extends jr{constructor(e){super(e),this.offset=0;let t,n,r,i,a=mi.prototype.utf8Write?function(e,t){return G.utf8Write(e,t,G.byteLength-t)}:li&&li.encodeInto?function(e,t){return li.encodeInto(e,G.subarray(t)).written}:!1,o=this;e||={};let s=e&&e.sequential,c=e.structures||e.saveStructures,l=e.maxSharedStructures;if(l??=c?32:0,l>8160)throw Error(`Maximum maxSharedStructure is 8160`);e.structuredClone&&e.moreTypes==null&&(this.moreTypes=!0);let u=e.maxOwnStructures;u??=c?32:64,!this.structures&&e.useRecords!=0&&(this.structures=[]);let d=l>32||u+l>64,f=l+64,p=l+u+64;if(p>8256)throw Error(`Maximum maxSharedStructure + maxOwnStructure is 8192`);let m=[],h=0,g=0;this.pack=this.encode=function(e,a){if(G||(G=new pi(8192),K=G.dataView||(G.dataView=new DataView(G.buffer,0,8192)),q=0),_i=G.length-10,_i-q<2048?(G=new pi(G.length),K=G.dataView||(G.dataView=new DataView(G.buffer,0,G.length)),_i=G.length-10,q=0):q=q+7&2147483640,t=q,a&2048&&(q+=a&255),i=o.structuredClone?new Map:null,o.bundleStrings&&typeof e!=`string`?(J=[],J.size=1/0):J=null,r=o.structures,r){r.uninitialized&&(r=o._mergeStructures(o.getStructures()));let e=r.sharedLength||0;if(e>l)throw Error(`Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to `+r.sharedLength);if(!r.transitions){r.transitions=Object.create(null);for(let t=0;t<e;t++){let e=r[t];if(!e)continue;let n,i=r.transitions;for(let t=0,r=e.length;t<r;t++){let r=e[t];n=i[r],n||=i[r]=Object.create(null),i=n}i[xi]=t+64}this.lastNamedStructuresLength=e}s||(r.nextId=e+64)}n&&=!1;let c;try{o.randomAccessStructure&&e&&typeof e==`object`?e.constructor===Object?w(e):e.constructor!==Map&&!Array.isArray(e)&&!di.some(t=>e instanceof t)?w(e.toJSON?e.toJSON():e):v(e):v(e);let n=J;if(J&&Di(t,v,0),i&&i.idsToInsert){let e=i.idsToInsert.sort((e,t)=>e.offset>t.offset?1:-1),r=e.length,a=-1;for(;n&&r>0;){let i=e[--r].offset+t;i<n.stringsPosition+t&&a===-1&&(a=0),i>n.position+t?a>=0&&(a+=6):(a>=0&&(K.setUint32(n.position+t,K.getUint32(n.position+t)+a),a=-1),n=n.previous,r++)}a>=0&&n&&K.setUint32(n.position+t,K.getUint32(n.position+t)+a),q+=e.length*6,q>_i&&x(q),o.offset=q;let s=Ei(G.subarray(t,q),e);return i=null,s}return o.offset=q,a&512?(G.start=t,G.end=q,G):G.subarray(t,q)}catch(e){throw c=e,e}finally{if(r&&(ee(),n&&o.saveStructures)){let n=r.sharedLength||0,i=G.subarray(t,q),s=Oi(r,o);if(!c)return o.saveStructures(s,s.isCompatible)===!1?o.pack(e,a):(o.lastNamedStructuresLength=n,G.length>1073741824&&(G=null),i)}G.length>1073741824&&(G=null),a&1024&&(q=t)}};let ee=()=>{g<10&&g++;let e=r.sharedLength||0;if(r.length>e&&!s&&(r.length=e),h>1e4)r.transitions=null,g=0,h=0,m.length>0&&(m=[]);else if(m.length>0&&!s){for(let e=0,t=m.length;e<t;e++)m[e][xi]=0;m=[]}},_=e=>{var t=e.length;t<16?G[q++]=144|t:t<65536?(G[q++]=220,G[q++]=t>>8,G[q++]=t&255):(G[q++]=221,K.setUint32(q,t),q+=4);for(let n=0;n<t;n++)v(e[n])},v=e=>{q>_i&&(G=x(q));var n=typeof e,r;if(n===`string`){let n=e.length;if(J&&n>=4&&n<4096){if((J.size+=n)>yi){let e,n=(J[0]?J[0].length*3+J[1].length:0)+10;q+n>_i&&(G=x(q+n));let r;J.position?(r=J,G[q]=200,q+=3,G[q++]=98,e=q-t,q+=4,Di(t,v,0),K.setUint16(e+t-3,q-t-e)):(G[q++]=214,G[q++]=98,e=q-t,q+=4),J=[``,``],J.previous=r,J.size=0,J.position=e}let r=bi.test(e);J[+!r]+=e,G[q++]=193,v(r?-n:n);return}let i;i=n<32?1:n<256?2:n<65536?3:5;let o=n*3;if(q+o>_i&&(G=x(q+o)),n<64||!a){let t,a,o,s=q+i;for(t=0;t<n;t++)a=e.charCodeAt(t),a<128?G[s++]=a:a<2048?(G[s++]=a>>6|192,G[s++]=a&63|128):(a&64512)==55296&&((o=e.charCodeAt(t+1))&64512)==56320?(a=65536+((a&1023)<<10)+(o&1023),t++,G[s++]=a>>18|240,G[s++]=a>>12&63|128,G[s++]=a>>6&63|128,G[s++]=a&63|128):(G[s++]=a>>12|224,G[s++]=a>>6&63|128,G[s++]=a&63|128);r=s-q-i}else r=a(e,q+i);r<32?G[q++]=160|r:r<256?(i<2&&G.copyWithin(q+2,q+1,q+1+r),G[q++]=217,G[q++]=r):r<65536?(i<3&&G.copyWithin(q+3,q+2,q+2+r),G[q++]=218,G[q++]=r>>8,G[q++]=r&255):(i<5&&G.copyWithin(q+5,q+3,q+3+r),G[q++]=219,K.setUint32(q,r),q+=4),q+=r}else if(n===`number`)if(e>>>0===e)e<32||e<128&&this.useRecords===!1||e<64&&!this.randomAccessStructure?G[q++]=e:e<256?(G[q++]=204,G[q++]=e):e<65536?(G[q++]=205,G[q++]=e>>8,G[q++]=e&255):(G[q++]=206,K.setUint32(q,e),q+=4);else if(e>>0===e)e>=-32?G[q++]=256+e:e>=-128?(G[q++]=208,G[q++]=e+256):e>=-32768?(G[q++]=209,K.setInt16(q,e),q+=2):(G[q++]=210,K.setInt32(q,e),q+=4);else{let t;if((t=this.useFloat32)>0&&e<4294967296&&e>=-2147483648){G[q++]=202,K.setFloat32(q,e);let n;if(t<4||(n=e*oi[(G[q]&127)<<1|G[q+1]>>7])>>0===n){q+=4;return}q--}G[q++]=203,K.setFloat64(q,e),q+=8}else if(n===`object`||n===`function`)if(!e)G[q++]=192;else{if(i){let n=i.get(e);if(n){n.id||=(i.idsToInsert||(i.idsToInsert=[])).push(n),G[q++]=214,G[q++]=112,K.setUint32(q,n.id),q+=4;return}i.set(e,{offset:q-t})}let a=e.constructor;if(a===Object)b(e);else if(a===Array)_(e);else if(a===Map)if(this.mapAsEmptyObject)G[q++]=128;else{r=e.size,r<16?G[q++]=128|r:r<65536?(G[q++]=222,G[q++]=r>>8,G[q++]=r&255):(G[q++]=223,K.setUint32(q,r),q+=4);for(let[t,n]of e)v(t),v(n)}else{for(let t=0,n=ui.length;t<n;t++){let n=di[t];if(e instanceof n){let n=ui[t];if(n.write){n.type&&(G[q++]=212,G[q++]=n.type,G[q++]=0);let t=n.write.call(this,e);t===e?Array.isArray(e)?_(e):b(e):v(t);return}let r=G,i=K,a=q;G=null;let o;try{o=n.pack.call(this,e,e=>(G=r,r=null,q+=e,q>_i&&x(q),{target:G,targetView:K,position:q-e}),v)}finally{r&&(G=r,K=i,q=a,_i=G.length-10)}o&&(o.length+q>_i&&x(o.length+q),q=Ti(o,G,q,n.type));return}}if(Array.isArray(e))_(e);else{if(e.toJSON){let t=e.toJSON();if(t!==e)return v(t)}if(n===`function`)return v(this.writeFunction&&this.writeFunction(e));b(e)}}}else if(n===`boolean`)G[q++]=e?195:194;else if(n===`bigint`){if(e<0x8000000000000000&&e>=-0x8000000000000000)G[q++]=211,K.setBigInt64(q,e);else if(e<0x10000000000000000&&e>0)G[q++]=207,K.setBigUint64(q,e);else if(this.largeBigIntToFloat)G[q++]=203,K.setFloat64(q,Number(e));else if(this.largeBigIntToString)return v(e.toString());else if(this.useBigIntExtension||this.moreTypes){let t=BigInt(e<0?-1:0),n;if(e>>BigInt(65536)===t){let r=BigInt(0x10000000000000000)-BigInt(1),i=[];for(;i.push(e&r),e>>BigInt(63)!==t;)e>>=BigInt(64);n=new Uint8Array(new BigUint64Array(i).buffer),n.reverse()}else{let t=e<0,r=(t?~e:e).toString(16);if(r.length%2?r=`0`+r:parseInt(r.charAt(0),16)>=8&&(r=`00`+r),fi)n=Buffer.from(r,`hex`);else{n=new Uint8Array(r.length/2);for(let e=0;e<n.length;e++)n[e]=parseInt(r.slice(e*2,e*2+2),16)}if(t)for(let e=0;e<n.length;e++)n[e]=~n[e]}n.length+q>_i&&x(n.length+q),q=Ti(n,G,q,66);return}else throw RangeError(e+` was too large to fit in MessagePack 64-bit integer format, use useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set largeBigIntToString to convert to string`);q+=8}else if(n===`undefined`)this.encodeUndefinedAsNil?G[q++]=192:(G[q++]=212,G[q++]=0,G[q++]=0);else throw Error(`Unknown type: `+n)},te=this.variableMapSize||this.coercibleKeyAsNumber||this.skipValues?e=>{let t;if(this.skipValues){t=[];for(let n in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(n))&&!this.skipValues.includes(e[n])&&t.push(n)}else t=Object.keys(e);let n=t.length;n<16?G[q++]=128|n:n<65536?(G[q++]=222,G[q++]=n>>8,G[q++]=n&255):(G[q++]=223,K.setUint32(q,n),q+=4);let r;if(this.coercibleKeyAsNumber)for(let i=0;i<n;i++){r=t[i];let n=Number(r);v(isNaN(n)?r:n),v(e[r])}else for(let i=0;i<n;i++)v(r=t[i]),v(e[r])}:e=>{G[q++]=222;let n=q-t;q+=2;let r=0;for(let t in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(t))&&(v(t),v(e[t]),r++);if(r>65535)throw Error(`Object is too large to serialize with fast 16-bit map size, use the "variableMapSize" option to serialize this object`);G[n+++t]=r>>8,G[n+t]=r&255},ne=this.useRecords===!1?te:e.progressiveRecords&&!d?e=>{let n,i=r.transitions||(r.transitions=Object.create(null)),a=q++-t,o;for(let s in e)if(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(s)){if(n=i[s],n)i=n;else{let c=Object.keys(e),l=i;i=r.transitions;let u=0;for(let e=0,t=c.length;e<t;e++){let t=c[e];n=i[t],n||(n=i[t]=Object.create(null),u++),i=n}a+t+1==q?(q--,S(i,c,u)):C(i,c,a,u),o=!0,i=l[s]}v(e[s])}if(!o){let n=i[xi];n?G[a+t]=n:C(i,Object.keys(e),a,0)}}:e=>{let t,n=r.transitions||(r.transitions=Object.create(null)),i=0;for(let r in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(r))&&(t=n[r],t||(t=n[r]=Object.create(null),i++),n=t);let a=n[xi];a?a>=96&&d?(G[q++]=((a-=96)&31)+96,G[q++]=a>>5):G[q++]=a:S(n,n.__keys__||Object.keys(e),i);for(let t in e)(typeof e.hasOwnProperty!=`function`||e.hasOwnProperty(t))&&v(e[t])},y=typeof this.useRecords==`function`&&this.useRecords,b=y?e=>{y(e)?ne(e):te(e)}:ne,x=e=>{let n;if(e>16777216){if(e-t>hi)throw Error(`Packed buffer would be larger than maximum buffer size`);n=Math.min(hi,Math.round(Math.max((e-t)*(e>67108864?1.25:2),4194304)/4096)*4096)}else n=(Math.max(e-t<<2,G.length-1)>>12)+1<<12;let r=new pi(n);return K=r.dataView||=new DataView(r.buffer,0,n),e=Math.min(e,G.length),G.copy?G.copy(r,0,t,e):r.set(G.slice(t,e)),q-=t,t=0,_i=r.length-10,G=r},S=(e,t,i)=>{let a=r.nextId;a||=64,a<f&&this.shouldShareStructure&&!this.shouldShareStructure(t)?(a=r.nextOwnId,a<p||(a=f),r.nextOwnId=a+1):(a>=p&&(a=f),r.nextId=a+1);let o=t.highByte=a>=96&&d?a-96>>5:-1;e[xi]=a,e.__keys__=t,r[a-64]=t,a<f?(t.isShared=!0,r.sharedLength=a-63,n=!0,o>=0?(G[q++]=(a&31)+96,G[q++]=o):G[q++]=a):(o>=0?(G[q++]=213,G[q++]=114,G[q++]=(a&31)+96,G[q++]=o):(G[q++]=212,G[q++]=114,G[q++]=a),i&&(h+=g*i),m.length>=u&&(m.shift()[xi]=0),m.push(e),v(t))},C=(e,n,r,i)=>{let a=G,o=q,s=_i,c=t;G=gi,q=0,t=0,G||(gi=G=new pi(8192)),_i=G.length-10,S(e,n,i),gi=G;let l=q;if(G=a,q=o,_i=s,t=c,l>1){let e=q+l-1;e>_i&&x(e);let n=r+t;G.copyWithin(n+l,n+1,q),G.set(gi.slice(0,l),n),q=e}else G[r+t]=gi[0]},w=e=>{let i=vi(e,G,t,q,r,x,(e,t,r)=>{if(r)return n=!0;q=t;let i=G;return v(e),ee(),i===G?q:{position:q,targetView:K,target:G}},this);if(i===0)return b(e);q=i}}useBuffer(e){G=e,G.dataView||(G.dataView=new DataView(G.buffer,G.byteOffset,G.byteLength)),K=G.dataView,q=0}set position(e){q=e}get position(){return q}clearSharedData(){this.structures&&=[],this.typedStructs&&=[]}};di=[Date,Set,Error,RegExp,ArrayBuffer,Object.getPrototypeOf(Uint8Array.prototype).constructor,DataView,wr],ui=[{pack(e,t,n){let r=e.getTime()/1e3;if((this.useTimestamp32||e.getMilliseconds()===0)&&r>=0&&r<4294967296){let{target:e,targetView:n,position:i}=t(6);e[i++]=214,e[i++]=255,n.setUint32(i,r)}else if(r>0&&r<4294967296){let{target:n,targetView:i,position:a}=t(10);n[a++]=215,n[a++]=255,i.setUint32(a,e.getMilliseconds()*4e6+(r/1e3/4294967296>>0)),i.setUint32(a+4,r)}else if(isNaN(r)){if(this.onInvalidDate)return t(0),n(this.onInvalidDate());let{target:e,targetView:r,position:i}=t(3);e[i++]=212,e[i++]=255,e[i++]=255}else{let{target:n,targetView:i,position:a}=t(15);n[a++]=199,n[a++]=12,n[a++]=255,i.setUint32(a,e.getMilliseconds()*1e6),i.setBigInt64(a+4,BigInt(Math.floor(r)))}}},{pack(e,t,n){if(this.setAsEmptyObject)return t(0),n({});let r=Array.from(e),{target:i,position:a}=t(this.moreTypes?3:0);this.moreTypes&&(i[a++]=212,i[a++]=115,i[a++]=0),n(r)}},{pack(e,t,n){let{target:r,position:i}=t(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=101,r[i++]=0),n([e.name,e.message,e.cause])}},{pack(e,t,n){let{target:r,position:i}=t(this.moreTypes?3:0);this.moreTypes&&(r[i++]=212,r[i++]=120,r[i++]=0),n([e.source,e.flags])}},{pack(e,t){this.moreTypes?Ci(e,16,t):wi(fi?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let n=e.constructor;n!==mi&&this.moreTypes?Ci(e,ti.indexOf(n.name),t):wi(e,t)}},{pack(e,t){this.moreTypes?Ci(e,17,t):wi(fi?Buffer.from(e):new Uint8Array(e),t)}},{pack(e,t){let{target:n,position:r}=t(1);n[r]=193}}];function Ci(e,t,n,r){let i=e.byteLength;if(i+1<256){var{target:a,position:o}=n(4+i);a[o++]=199,a[o++]=i+1}else if(i+1<65536){var{target:a,position:o}=n(5+i);a[o++]=200,a[o++]=i+1>>8,a[o++]=i+1&255}else{var{target:a,position:o,targetView:s}=n(7+i);a[o++]=201,s.setUint32(o,i+1),o+=4}a[o++]=116,a[o++]=t,e.buffer||(e=new Uint8Array(e)),a.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),o)}function wi(e,t){let n=e.byteLength;var r,i;if(n<256){var{target:r,position:i}=t(n+2);r[i++]=196,r[i++]=n}else if(n<65536){var{target:r,position:i}=t(n+3);r[i++]=197,r[i++]=n>>8,r[i++]=n&255}else{var{target:r,position:i,targetView:a}=t(n+5);r[i++]=198,a.setUint32(i,n),i+=4}r.set(e,i)}function Ti(e,t,n,r){let i=e.length;switch(i){case 1:t[n++]=212;break;case 2:t[n++]=213;break;case 4:t[n++]=214;break;case 8:t[n++]=215;break;case 16:t[n++]=216;break;default:i<256?(t[n++]=199,t[n++]=i):i<65536?(t[n++]=200,t[n++]=i>>8,t[n++]=i&255):(t[n++]=201,t[n++]=i>>24,t[n++]=i>>16&255,t[n++]=i>>8&255,t[n++]=i&255)}return t[n++]=r,t.set(e,n),n+=i,n}function Ei(e,t){let n,r=t.length*6,i=e.length-r;for(;n=t.pop();){let t=n.offset,a=n.id;e.copyWithin(t+r,t,i),r-=6;let o=t+r;e[o++]=214,e[o++]=105,e[o++]=a>>24,e[o++]=a>>16&255,e[o++]=a>>8&255,e[o++]=a&255,i=t}return e}function Di(e,t,n){if(J.length>0){K.setUint32(J.position+e,q+n-J.position-e),J.stringsPosition=q-e;let r=J;J=null,t(r[0]),t(r[1])}}function Oi(e,t){return e.isCompatible=e=>{let n=!e||(t.lastNamedStructuresLength||0)===e.length;return n||t._mergeStructures(e),n},e}var ki=new Si({useRecords:!1});ki.pack,ki.pack;var{NEVER:Ai,ALWAYS:ji,DECIMAL_ROUND:Mi,DECIMAL_FIT:Ni}=ci,Pi=class extends Qe()(`effect/rpc/RpcSerialization`){},Fi=Pi.of({contentType:`application/json`,includesFraming:!1,makeUnsafe:()=>{let e=new TextDecoder;return{decode:t=>{let n=JSON.parse(typeof t==`string`?t:e.decode(t));return Array.isArray(n)?n:[n]},encode:e=>JSON.stringify(e)}}}),Ii=C(Pi)(Fi),Li=e=>lt(()=>{let t=new Set,n=new Map,r=new Map,i=(e,t)=>ne(r=>{let i=n.get(e);return i||(i=[],n.set(e,i)),i.push([t,r]),I});return Oe(e((e,t)=>{let n=r.get(e);return n?n(t):i(e,t)},t),e=>({...e,run(e,i){return Be(function*(){t.add(e),r.set(e,i);let a=n.get(e);if(a){n.delete(e);for(let[e,t]of a)yield*k(lt(()=>i(e)),t)}return yield*M(f,()=>(t.delete(e),r.delete(e),I))})}}))}),Ri=BigInt(0),zi=De(function*(e,t){let n=t?.spanPrefix??`RpcClient`,r=t?.supportsAck??!0,i=t?.disableTracing??!1,o=t?.generateRequestId??(()=>Ri++),c=yield*ot(),l=Re(c,se),u=new Map,d=!1;yield*wt(l,gt(e=>(d=!0,f(Le(e.id)))));let f=De(function*(e){for(let[t,n]of u)u.delete(t),n._tag===`Queue`?yield*e._tag===`Success`?vt(n.queue):le(n.queue,e.cause):n.resume(e)}),p=e=>{let r=Ft(e.successSchema),a=g(e);return(o,s)=>{let c=s?.headers?It(s.headers):Ut,l=s?.context??Me();if(!r){let r=t=>m(e,a,t,e.payloadSchema.make(o),c,l,s?.discard??!1);return i?r(void 0):Ue(`${n}.${e._tag}`,{attributes:t.spanAttributes},r)}let u=h(e,a,e.payloadSchema.make(o),c,s?.streamBufferSize??16,l);return s?.asQueue?u:yt(Oe(u,ut))}},m=(e,n,r,i,a,s,c)=>gt(l=>{if(d)return et;let f=o(),p=n(e=>t.onFromClient({message:e,context:s,discard:c}),{_tag:`Request`,id:f,tag:e._tag,payload:i,...r?{traceId:r.traceId,spanId:r.spanId,sampled:r.sampled}:{},headers:Wt(l.getRef(Wi),a)});if(c)return p;let m;return Ze(fe(t=>{let n={_tag:`Effect`,rpc:e,context:s,resume(e){t(e),m&&!m.pollUnsafe()&&l.currentDispatcher.scheduleTask(()=>{m.interruptUnsafe(l.id)},0)}};u.set(f,n),m=p.pipe(r?xt(r,{captureStackTrace:!1}):S,me(l.context)),m.addObserver(e=>{if(e._tag===`Failure`)return t(e)})}),e=>(u.delete(f),Ct(N(m),ee(f,Array.from(e),s))))}),h=De(function*(e,r,c,l,f,p){if(d)return yield*et;let m=i?void 0:yield*St(`${n}.${e._tag}`,{attributes:t.spanAttributes}),h=O(),g=o(),_=it(h.context,se);yield*a(_,e=>u.has(g)?(u.delete(g),ee(g,tt(e)?Array.from(Ee(e.cause)):[],p)):I);let v=yield*s(f);return u.set(g,{_tag:`Queue`,rpc:e,queue:v,scope:_,context:p}),yield*r(e=>t.onFromClient({message:e,context:p,discard:!1}),{_tag:`Request`,id:g,tag:e._tag,payload:c,...m?{traceId:m.traceId,spanId:m.spanId,sampled:m.sampled}:{},headers:Wt(h.getRef(Wi),l)}).pipe(m?xt(m,{captureStackTrace:!1}):S,he(e=>le(v,e)),Ge,ht(_,{startImmediately:!0})),v}),g=e=>{let t=[];for(let n of e.middlewares.values()){let e=c.mapUnsafe.get(`${n.key}/Client`);e&&t.push(e)}return t.length===0?(e,t)=>e(t):function n(r,i,a=t.length-1){return a===-1?r(i):t[a]({rpc:e,request:i,next(e){return n(r,e,a-1)}})}},ee=(e,n,r)=>fe(i=>{let a=O();t.onFromClient({message:{_tag:`Interrupt`,requestId:e,interruptors:n},context:r,discard:!1}).pipe(Ae(1e3),me(a.context)).addObserver(()=>{i(I)})}),_=e=>{switch(e._tag){case`Chunk`:{let n=e.requestId,i=u.get(n);return!i||i._tag!==`Queue`?I:A(i.queue,e.values).pipe(r?nt(()=>t.onFromClient({message:{_tag:`Ack`,requestId:e.requestId},context:i.context,discard:!1})):S,he(e=>le(i.queue,e)))}case`Exit`:{let t=e.requestId,n=u.get(t);return n?(u.delete(t),n._tag===`Effect`?(n.resume(e.exit),I):e.exit._tag===`Success`?vt(n.queue):le(n.queue,e.exit.cause)):I}case`Defect`:return f(_e(e.defect));case`ClientEnd`:return I}},v;if(t.flatten){let t=new Map;v=function(n,r,i){let a=t.get(n);return a||(a=p(e.requests.get(n)),t.set(n,a)),a(r,i)}}else v={},e.requests.forEach(e=>{v[e._tag]=p(e)});return{client:v,write:_}}),Bi=0,Vi=De(function*(e,t){let n=Bi++,{run:i,send:a,supportsAck:o,supportsTransferables:s}=yield*Gi,c=new Map,{client:u,write:f}=yield*zi(e,{...t,supportsAck:o,onFromClient({message:t}){switch(t._tag){case`Request`:{let i=e.requests.get(t.tag),o=s?er():void 0,l=O(),u={rpc:i,context:o?pt(l.context,$n,o):l.context,schemas:Ui(i)};return c.set(t.id,u),u.schemas.encodePayload(t.payload).pipe(k(u.context),r,nt(e=>a(n,{...t,id:String(t.id),payload:e,headers:Object.entries(t.headers)},o&&o.readUnsafe())))}case`Ack`:return c.get(t.requestId)?a(n,{_tag:`Ack`,requestId:String(t.requestId)}):I;case`Interrupt`:return c.get(t.requestId)?(c.delete(t.requestId),a(n,{_tag:`Interrupt`,requestId:String(t.requestId)})):I;case`Eof`:return I}}});return yield*i(n,e=>{switch(e._tag){case`Chunk`:{let t=ur(e.requestId),n=c.get(t);return!n||l(n.schemas.decodeChunk)?I:n.schemas.decodeChunk.value(e.values).pipe(k(n.context),r,nt(t=>f({_tag:`Chunk`,clientId:0,requestId:ur(e.requestId),values:t})),d(t=>f({_tag:`Exit`,clientId:0,requestId:ur(e.requestId),exit:ie(t)})))}case`Exit`:{let t=ur(e.requestId),n=c.get(t);return n?(c.delete(t),n.schemas.decodeExit(e.exit).pipe(k(n.context),r,de({onSuccess:e=>f({_tag:`Exit`,clientId:0,requestId:t,exit:e}),onFailure:e=>f({_tag:`Exit`,clientId:0,requestId:t,exit:ie(e)})}))):I}case`Defect`:return f({_tag:`Defect`,clientId:0,defect:Xi(e.defect)});case`ClientProtocolError`:{let t=Se(e.error);return ft(c.keys(),e=>f({_tag:`Exit`,clientId:0,requestId:e,exit:t}))}default:return I}}).pipe(he(_t),Ge,Pe),u}),Hi=new WeakMap,Ui=e=>{let t=Hi.get(e);if(t!==void 0)return t;let n=Ht(e.successSchema);return t={decodeChunk:E(n,e=>Pt(Rt(cn(e.success)))),encodePayload:en(Rt(e.payloadSchema)),decodeExit:Pt(Rt(zt(e)))},Hi.set(e,t),t},Wi=ke(`effect/rpc/RpcClient/CurrentHeaders`,{defaultValue:()=>Ut}),Gi=class extends Qe()(`effect/rpc/RpcClient/Protocol`){static make=Li},Ki=e=>Gi.make(De(function*(t,a){let o=yield*In,s=yield*Pi,c=yield*ae(Yi),l=new Map,u=yield*o.writer,d=s.makeUnsafe(),f=yield*Ji(u(d.encode(dr))),p,m=lt(()=>(p=void 0,Xe(c)?c.value.onConnect:I)),h=e=>ft(a,n=>t(n,e));return yield*lt(()=>(d=s.makeUnsafe(),f.reset(),o.runRaw(e=>{try{let n=d.decode(e);if(n.length===0)return;let r=0;return Te({while:()=>r<n.length,body:()=>{let e=n[r++];if(e._tag===`Pong`)return f.onPong(),I;if(`requestId`in e){let n=l.get(e.requestId);if(n!==void 0)return e._tag===`Exit`&&l.delete(e.requestId),t(n,e)}return h(e)},step:P})}catch(e){return h({_tag:`ClientProtocolError`,error:new lr({reason:new cr({message:`Error decoding message`,cause:e})})})}},{onOpen:m}).pipe(ee(nt(f.timeout,()=>n(new Kn({reason:new Un({kind:`Timeout`,cause:Error(`ping timeout`)})}))))))).pipe(nt(()=>n(new Kn({reason:new Wn({code:1e3})}))),Xe(c)?xe(c.value.onDisconnect):S,rt(t=>{let n=ze(t),r=ct(n);return e?.retryTransientErrors&&r&&n.success.reason._tag===`SocketOpenError`?I:(p=new lr({reason:r?n.success.reason:new cr({message:`Unknown socket error`,cause:ue(t)})}),h({_tag:`ClientProtocolError`,error:p}))}),T(e?.retryPolicy??qi),i({module:`RpcClient`,method:`makeProtocolSocket`}),Pe),{send(e,t){if(p)return n(p);t._tag===`Request`&&l.set(t.id,e);let i=d.encode(t);return i===void 0?I:r(u(i))},supportsAck:!0,supportsTransferables:!1}})),qi=c(500,1.5).pipe(ce(j(5e3))),Ji=De(function*(e){let t=!0,n=0,r=qe();return yield*lt(()=>t?(t=!1,n=0,e):(n+=1,n>=3?r.open:e)).pipe(ve(`5 seconds`),at,je,Ge,Pe),{timeout:r.await,reset:()=>{t=!0,n=0,r.closeUnsafe()},onPong:()=>{t=!0,n=0}}}),Yi=class extends Qe()(`effect/rpc/RpcClient/ConnectionHooks`){},Xi=un(Jt),Zi=1e3,Qi=64e3;Vi(qt);function $i(e){return!Number.isInteger(e)||e<0||e>=10?null:Math.min(Math.round(Zi*2**e),Qi)}var Y=class extends Error{code;retryable;name=`RelayProtocolFailure`;constructor(e,t,n){super(t),this.code=e,this.retryable=n}};function ea(e){return Array.isArray(e)?e.map(ea):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,ea(t)])):e}function ta(e){let t=JSON.stringify(ea(e));if(t===void 0)throw Error(`Relay payload is not JSON serializable.`);return t}var na={requestId:`@effect/rpc/Ping`,correlationId:`@effect/rpc/Ping`,method:`@effect/rpc/Ping`,requiredScope:null,deliveryClass:`read`,journalPersistence:`none`};function ra(e){return e._tag===`Ping`?na:null}function ia(e){if(e.policy===null||e.policy.method!==e.method)throw new Y(`method_not_remotable`,`Relay method has no exact dispatch policy: ${e.method}`,!1);if(e.policy.requiredScope!==null&&!e.grantedScopes.includes(e.policy.requiredScope))throw new Y(`scope_denied`,`Relay method ${e.method} requires scope ${e.policy.requiredScope}`,!1);return{requiredScope:e.policy.requiredScope,deliveryClass:e.policy.deliveryClass,journalPersistence:e.policy.journalPersistence}}function aa(e){let t=new Set(e.registeredMethods),n=new Map;for(let r of e.policies){if(n.has(r.method))throw new Y(`method_not_remotable`,`Relay method has duplicate dispatch policies: ${r.method}`,!1);if(!t.has(r.method))throw new Y(`method_not_remotable`,`Relay dispatch policy targets an unregistered method: ${r.method}`,!1);if((r.deliveryClass===`idempotent-command`||r.deliveryClass===`create-command`)==(r.journalPersistence===`none`))throw new Y(`method_not_remotable`,`Relay dispatch policy has incompatible journal persistence: ${r.method}`,!1);n.set(r.method,r)}for(let t of e.registeredMethods)if(!n.has(t))throw new Y(`method_not_remotable`,`Remotely registered method has no dispatch policy: ${t}`,!1);return n}var oa=[{method:L.projectsSearchContents,requiredScope:`workspace.read`,deliveryClass:`read`},{method:L.projectsSearchEntries,requiredScope:`workspace.read`,deliveryClass:`read`},{method:L.projectsListEntries,requiredScope:`workspace.read`,deliveryClass:`read`},{method:L.serverDiscoverSourceControl,requiredScope:`runtime.read`,deliveryClass:`read`},{method:L.serverReportClientActivity,requiredScope:`runtime.read`,deliveryClass:`read`},{method:L.projectsWriteFile,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:L.projectCheckoutDeletionPreview,requiredScope:`workspace.write`,deliveryClass:`read`},{method:L.projectCheckoutDeletionExecute,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:L.reviewGetDiffPreview,requiredScope:`diff.read`,deliveryClass:`read`},{method:L.projectsReadFile,requiredScope:`workspace.read`,deliveryClass:`read`},{method:L.cloudListRuntimes,requiredScope:`runtime.read`,deliveryClass:`read`},{method:L.filesystemBrowse,requiredScope:`workspace.read`,deliveryClass:`read`},{method:L.workspaceReadFile,requiredScope:`workspace.read`,deliveryClass:`bulk-transfer`},{method:L.workspaceBeginWriteFile,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:L.workspaceWriteFileChunk,requiredScope:`workspace.write`,deliveryClass:`bulk-transfer`},{method:L.workspaceCommitWriteFile,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:L.workspaceCancelWriteFile,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:L.shellOpenInEditor,requiredScope:`shell.open`,deliveryClass:`idempotent-command`},{method:L.gitPull,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:L.gitRefreshStatus,requiredScope:`git.read`,deliveryClass:`read`},{method:L.gitRunStackedAction,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:L.gitListBranches,requiredScope:`git.read`,deliveryClass:`read`},{method:L.vcsListRefs,requiredScope:`git.read`,deliveryClass:`read`},{method:L.vcsRefreshStatus,requiredScope:`git.read`,deliveryClass:`read`},{method:L.vcsPull,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:L.vcsCreateWorktree,requiredScope:`git.write`,deliveryClass:`create-command`},{method:L.vcsRemoveWorktree,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:L.vcsCreateRef,requiredScope:`git.write`,deliveryClass:`create-command`},{method:L.vcsSwitchRef,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:L.vcsInit,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:L.gitCreateWorktree,requiredScope:`git.write`,deliveryClass:`create-command`},{method:L.gitRemoveWorktree,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:L.gitCreateBranch,requiredScope:`git.write`,deliveryClass:`create-command`},{method:L.gitCheckout,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:L.gitInit,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:L.gitResolvePullRequest,requiredScope:`git.read`,deliveryClass:`read`},{method:L.gitPreparePullRequestThread,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:L.terminalOpen,requiredScope:`terminal.write`,deliveryClass:`create-command`},{method:L.terminalAttach,requiredScope:`terminal.write`,deliveryClass:`terminal-output`},{method:L.terminalWrite,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:L.terminalResize,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:L.terminalSignal,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:L.terminalClear,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:L.terminalRestart,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:L.terminalClose,requiredScope:`terminal.write`,deliveryClass:`idempotent-command`},{method:L.browserOpenSession,requiredScope:`browser.control`,deliveryClass:`create-command`},{method:L.browserListSessions,requiredScope:`browser.read`,deliveryClass:`read`},{method:L.browserCloseSession,requiredScope:`browser.control`,deliveryClass:`browser-control`},{method:L.browserGetSession,requiredScope:`browser.read`,deliveryClass:`read`},{method:L.browserCommand,requiredScope:`browser.control`,deliveryClass:`browser-control`},{method:L.browserClearBrowsingData,requiredScope:`browser.control`,deliveryClass:`browser-control`},{method:L.browserAttachDisplay,requiredScope:`browser.read`,deliveryClass:`subscription`},{method:L.computerInput,requiredScope:`browser.control`,deliveryClass:`browser-control`},{method:L.browserAddDisplayIceCandidate,requiredScope:`browser.read`,deliveryClass:`browser-control`},{method:L.devTunnelRegister,requiredScope:`browser.control`,deliveryClass:`idempotent-command`},{method:L.devTunnelUnregister,requiredScope:`browser.control`,deliveryClass:`idempotent-command`},{method:L.devTunnelList,requiredScope:`browser.read`,deliveryClass:`read`},{method:L.threadDevRuntimeGet,requiredScope:`runtime.read`,deliveryClass:`read`},{method:L.threadDevRuntimeAllocatePort,requiredScope:`runtime.manage`,deliveryClass:`idempotent-command`},{method:L.threadDevRuntimeRelease,requiredScope:`runtime.manage`,deliveryClass:`idempotent-command`},{method:L.workspaceEnvironmentPreflight,requiredScope:`workspace.read`,deliveryClass:`read`},{method:L.workspaceEnsureScratch,requiredScope:`workspace.write`,deliveryClass:`idempotent-command`},{method:L.serverGetConfig,requiredScope:`runtime.read`,deliveryClass:`read`},{method:L.serverRefreshProviders,requiredScope:`provider.read`,deliveryClass:`read`},{method:L.serverStartProviderAuth,requiredScope:`provider.manage`,deliveryClass:`create-command`},{method:L.serverRepairProviderAuthRuntime,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:L.serverDisconnectProviderAuth,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:L.serverGetProviderAuthSession,requiredScope:`provider.read`,deliveryClass:`read`},{method:L.serverCancelProviderAuth,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:L.serverSubmitProviderAuthCode,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:L.serverSyncPersonalCodexToCloud,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:L.serverSyncPersonalClaudeToCloud,requiredScope:`provider.manage`,deliveryClass:`idempotent-command`},{method:L.serverUpsertKeybinding,requiredScope:`settings.write`,deliveryClass:`idempotent-command`},{method:L.serverRemoveKeybinding,requiredScope:`settings.write`,deliveryClass:`idempotent-command`},{method:L.serverGetSettings,requiredScope:`settings.read`,deliveryClass:`read`},{method:L.serverUpdateSettings,requiredScope:`settings.write`,deliveryClass:`idempotent-command`},{method:L.serverUpdateEnvironmentDisplayName,requiredScope:`settings.write`,deliveryClass:`idempotent-command`},{method:L.serverGetTraceDiagnostics,requiredScope:`settings.read`,deliveryClass:`read`},{method:L.serverHeartbeat,requiredScope:`runtime.read`,deliveryClass:`read`},{method:L.usageGetSummary,requiredScope:`runtime.read`,deliveryClass:`read`},{method:L.pullRequestsList,requiredScope:`git.read`,deliveryClass:`read`},{method:L.pullRequestsListStats,requiredScope:`git.read`,deliveryClass:`read`},{method:L.pullRequestsDetail,requiredScope:`git.read`,deliveryClass:`read`},{method:L.pullRequestsActivity,requiredScope:`git.read`,deliveryClass:`read`},{method:L.pullRequestsThreadComments,requiredScope:`git.read`,deliveryClass:`read`},{method:L.pullRequestsDiffFileContents,requiredScope:`git.read`,deliveryClass:`read`},{method:L.pullRequestsRunAction,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:L.pullRequestsUpdate,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:L.pullRequestsComment,requiredScope:`git.write`,deliveryClass:`create-command`},{method:L.pullRequestsUpdateComment,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:L.pullRequestsSubmitReview,requiredScope:`git.write`,deliveryClass:`create-command`},{method:L.pullRequestsReplyToThread,requiredScope:`git.write`,deliveryClass:`create-command`},{method:L.pullRequestsSetThreadResolution,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:L.pullRequestsSetReaction,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:L.pullRequestsInvalidate,requiredScope:`git.read`,deliveryClass:`read`},{method:L.pullRequestsReviewerCandidates,requiredScope:`git.read`,deliveryClass:`read`},{method:L.pullRequestsRequestReviewers,requiredScope:`git.write`,deliveryClass:`idempotent-command`},{method:L.subscribeGitStatus,requiredScope:`git.read`,deliveryClass:`subscription`},{method:L.subscribeVcsStatus,requiredScope:`git.read`,deliveryClass:`subscription`},{method:L.subscribeTerminalEvents,requiredScope:`terminal.read`,deliveryClass:`terminal-output`},{method:L.subscribeTerminalMetadata,requiredScope:`terminal.read`,deliveryClass:`read`},{method:L.subscribeBrowserEvents,requiredScope:`browser.read`,deliveryClass:`browser-frame`},{method:L.subscribeServerConfig,requiredScope:`runtime.read`,deliveryClass:`subscription`},{method:L.subscribeServerLifecycle,requiredScope:`runtime.read`,deliveryClass:`subscription`},{method:L.subscribeAuthAccess,requiredScope:`provider.read`,deliveryClass:`subscription`},{method:L.subscribeWorkspaceReadiness,requiredScope:`runtime.read`,deliveryClass:`subscription`},{method:an.dispatchCommand,requiredScope:null,deliveryClass:`idempotent-command`},{method:an.getTurnDiff,requiredScope:`diff.read`,deliveryClass:`read`},{method:an.getFullThreadDiff,requiredScope:`diff.read`,deliveryClass:`read`},{method:an.streamTurnDiff,requiredScope:`diff.read`,deliveryClass:`bulk-transfer`},{method:an.streamFullThreadDiff,requiredScope:`diff.read`,deliveryClass:`bulk-transfer`},{method:an.replayEvents,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:an.getArchivedShellSnapshot,requiredScope:`thread.read`,deliveryClass:`read`},{method:an.subscribeShell,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:an.subscribeThread,requiredScope:`thread.read`,deliveryClass:`subscription`},{method:an.getThreadDetailPage,requiredScope:`thread.read`,deliveryClass:`read`},{method:L.assetsCreateUrl,requiredScope:`thread.read`,deliveryClass:`read`},{method:L.attachmentsCreateUploadUrl,requiredScope:`turn.dispatch`,deliveryClass:`create-command`},{method:L.attachmentsDelete,requiredScope:`turn.dispatch`,deliveryClass:`idempotent-command`},{method:an.searchThreads,requiredScope:`thread.read`,deliveryClass:`read`},{method:L.providerUploadFeedback,requiredScope:`thread.read`,deliveryClass:`create-command`},{method:L.sourceControlLookupRepository,requiredScope:`git.read`,deliveryClass:`read`},{method:L.sourceControlCloneRepository,requiredScope:`project.write`,deliveryClass:`idempotent-command`}],sa=new Set([L.gitPull,L.gitRunStackedAction,L.gitCreateWorktree,L.gitRemoveWorktree,L.gitCreateBranch,L.gitCheckout,L.gitInit,L.gitPreparePullRequestThread,L.threadDevRuntimeAllocatePort,L.threadDevRuntimeRelease,L.serverUpsertKeybinding,L.serverRemoveKeybinding,L.serverUpdateEnvironmentDisplayName,an.dispatchCommand]),ca=oa.map(e=>{let t=e.deliveryClass===`idempotent-command`||e.deliveryClass===`create-command`;return{method:e.method,requiredScope:e.requiredScope,deliveryClass:e.deliveryClass,journalPersistence:t?sa.has(e.method)?`frame`:`metadata-only`:`none`}}),la=aa({registeredMethods:[...qt.requests.keys()],policies:ca}),ua={"project.create":{requiredScope:`project.write`,deliveryClass:`create-command`},"project.meta.update":{requiredScope:`project.write`,deliveryClass:`idempotent-command`},"project.script.update":{requiredScope:`project.write`,deliveryClass:`idempotent-command`},"project.delete":{requiredScope:`project.write`,deliveryClass:`idempotent-command`},"thread.create":{requiredScope:`thread.create`,deliveryClass:`create-command`},"thread.delete":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.archive":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.settle":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.unsettle":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.unarchive":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.meta.update":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.runtime-mode.set":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.interaction-mode.set":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.turn.start":{requiredScope:`turn.dispatch`,deliveryClass:`create-command`},"thread.turn.interrupt":{requiredScope:`turn.stop`,deliveryClass:`idempotent-command`},"thread.approval.respond":{requiredScope:`approval.respond`,deliveryClass:`idempotent-command`},"thread.user-input.respond":{requiredScope:`approval.respond`,deliveryClass:`idempotent-command`},"thread.checkpoint.revert":{requiredScope:`thread.mutate`,deliveryClass:`idempotent-command`},"thread.session.stop":{requiredScope:`turn.stop`,deliveryClass:`idempotent-command`},"thread.plan-approval.respond":{requiredScope:`approval.respond`,deliveryClass:`idempotent-command`}},da=new Set([`thread.approval.respond`,`thread.user-input.respond`,`thread.plan-approval.respond`]);function fa(e){if(e.method!==an.dispatchCommand||!e.payload||typeof e.payload!=`object`||Array.isArray(e.payload))return null;let t=e.payload;if(typeof t.type!=`string`||!da.has(t.type))return null;let n=t.type===`thread.plan-approval.respond`?t.promptId:t.requestId;if(typeof t.commandId!=`string`||t.commandId.length===0||typeof n!=`string`||n.length===0)throw new Y(`action_grant_invalid`,`Relay sensitive action metadata is incomplete`,!1);return{commandType:t.type,commandId:t.commandId,targetId:n}}function pa(e){let t=la.get(e.method)??null,n=ia({method:e.method,grantedScopes:e.grantedScopes,policy:t});if(e.method!==an.dispatchCommand)return n;if(!e.payload||typeof e.payload!=`object`||!(`type`in e.payload))throw new Y(`method_not_remotable`,`Relay orchestration dispatch payload has no command policy`,!1);let r=e.payload.type;if(typeof r!=`string`||!(r in ua))throw new Y(`method_not_remotable`,`Relay orchestration command has no dispatch policy: ${String(r)}`,!1);let i=ua[r];if(!e.grantedScopes.includes(i.requiredScope))throw new Y(`scope_denied`,`Relay orchestration command ${r} requires scope ${i.requiredScope}`,!1);return{requiredScope:i.requiredScope,deliveryClass:i.deliveryClass,journalPersistence:n.journalPersistence}}var ma=class extends Error{constructor(e){let t;t=e instanceof Error?e.message:typeof e==`string`?e:``,super(t),this.name=this.constructor.name}},ha=class extends ma{},ga=class extends ma{},_a=class extends ma{},va=class extends ma{},ya=class extends ma{},ba=class extends ma{},xa=class extends ma{},Sa=class extends ma{},Ca=class extends ma{},wa=class extends ma{},Ta=class extends ma{},Ea=Da(globalThis,{});function Da(e,t){return new Proxy(e,{get(n,r,i){return r in t?t[r]:e[r]},set(n,r,i){return r in t&&delete t[r],e[r]=i,!0},deleteProperty(n,r){let i=!1;return r in t&&(delete t[r],i=!0),r in e&&(delete e[r],i=!0),i},ownKeys(n){let r=Reflect.ownKeys(e),i=Reflect.ownKeys(t),a=new Set(i);return[...r.filter(e=>!a.has(e)),...i]},defineProperty(n,r,i){return r in t&&delete t[r],Reflect.defineProperty(e,r,i),!0},getOwnPropertyDescriptor(n,r){return r in t?Reflect.getOwnPropertyDescriptor(t,r):Reflect.getOwnPropertyDescriptor(e,r)},has(n,r){return r in t||r in e}})}async function Oa(){if(Ea!==void 0&&globalThis.crypto!==void 0)return globalThis.crypto.subtle;try{let{webcrypto:e}=await mn(async()=>{let{webcrypto:e}=await import(`./__vite-browser-external-2W3EstLn.js`).then(e=>t(e.default));return{webcrypto:e}},__vite__mapDeps([0,1]));return e.subtle}catch(e){throw new Ta(e)}}var ka=class{constructor(){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async _setup(){this._api===void 0&&(this._api=await Oa())}},Aa={Base:0,Psk:1,Auth:2,AuthPsk:3},ja={NotAssigned:0,DhkemP256HkdfSha256:16,DhkemP384HkdfSha384:17,DhkemP521HkdfSha512:18,DhkemSecp256k1HkdfSha256:19,DhkemX25519HkdfSha256:32,DhkemX448HkdfSha512:33,HybridkemX25519Kyber768:48,MlKem512:64,MlKem768:65,MlKem1024:66,XWing:25722},Ma={HkdfSha256:1,HkdfSha384:2,HkdfSha512:3,Sha3256:4,Sha3384:5,Sha3512:6,Shake128:16,Shake256:17,TurboShake128:18,TurboShake256:19},Na={Aes128Gcm:1,Aes256Gcm:2,Chacha20Poly1305:3,ExportOnly:65535},Pa=new Uint8Array,Fa=0n,Ia=1n,La=2n,Ra=new Uint8Array([75,69,77,0,0]),za=new Uint8Array([72,80,75,69,45,118,49]);function Ba(e){return new Uint8Array(X(e))}function X(e){return e instanceof ArrayBuffer?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer:new Uint8Array(e).slice().buffer}var Va=class extends ka{constructor(){super(),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:Ma.HkdfSha256}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:Pa}),Object.defineProperty(this,"algHash",{enumerable:!0,configurable:!0,writable:!0,value:{name:`HMAC`,hash:`SHA-256`,length:256}})}init(e){this._suiteId=e}buildLabeledIkm(e,t){this._checkInit();let n=new Uint8Array(7+this._suiteId.byteLength+e.byteLength+t.byteLength);return n.set(za,0),n.set(this._suiteId,7),n.set(e,7+this._suiteId.byteLength),n.set(t,7+this._suiteId.byteLength+e.byteLength),n}buildLabeledInfo(e,t,n){this._checkInit();let r=new Uint8Array(9+this._suiteId.byteLength+e.byteLength+t.byteLength);return r.set(new Uint8Array([0,n]),0),r.set(za,2),r.set(this._suiteId,9),r.set(e,9+this._suiteId.byteLength),r.set(t,9+this._suiteId.byteLength+e.byteLength),r}async extract(e,t){await this._setup();let n=e.byteLength===0?new ArrayBuffer(this.hashSize):X(e);if(n.byteLength!==this.hashSize)throw new ha(`The salt length must be the same as the hashSize`);let r=X(t),i=await this._api.importKey(`raw`,n,this.algHash,!1,[`sign`]);return await this._api.sign(`HMAC`,i,r)}async expand(e,t,n){await this._setup();let r=X(e),i=await this._api.importKey(`raw`,r,this.algHash,!1,[`sign`]),a=new ArrayBuffer(n),o=new Uint8Array(a),s=Pa,c=Ba(t),l=new Uint8Array(1);if(n>255*this.hashSize)throw Error(`Entropy limit reached`);let u=new Uint8Array(this.hashSize+c.length+1);for(let e=1,t=0;t<o.length;e++)l[0]=e,u.set(s,0),u.set(c,s.length),u.set(l,s.length+c.length),s=new Uint8Array(await this._api.sign(`HMAC`,i,u.slice(0,s.length+c.length+1))),o.length-t>=s.length?(o.set(s,t),t+=s.length):(o.set(s.slice(0,o.length-t),t),t+=o.length-t);return a}async extractAndExpand(e,t,n,r){await this._setup();let i=X(t),a=await this._api.importKey(`raw`,i,`HKDF`,!1,[`deriveBits`]);return await this._api.deriveBits({name:`HKDF`,hash:this.algHash.hash,salt:X(e),info:X(n)},a,r*8)}async labeledExtract(e,t,n){return await this.extract(e,this.buildLabeledIkm(t,n))}async labeledExpand(e,t,n,r){return await this.expand(e,this.buildLabeledInfo(t,n,r),r)}_checkInit(){if(this._suiteId===Pa)throw Error(`Not initialized. Call init()`)}},Ha=class extends Va{constructor(){super(...arguments),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:Ma.HkdfSha256}),Object.defineProperty(this,"hashSize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"algHash",{enumerable:!0,configurable:!0,writable:!0,value:{name:`HMAC`,hash:`SHA-256`,length:256}})}},Ua=e=>typeof e==`object`&&!!e&&typeof e.privateKey==`object`&&typeof e.publicKey==`object`;function Wa(e,t){if(t<=0)throw Error(`i2Osp: too small size`);if(e>=256**t)throw Error(`i2Osp: too large integer`);let n=new Uint8Array(t);for(let r=0;r<t&&e;r++)n[t-(r+1)]=e%256,e=Math.floor(e/256);return n}function Ga(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function Ka(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}async function qa(){if(Ea!==void 0&&globalThis.crypto!==void 0)return globalThis.crypto;try{let{webcrypto:e}=await mn(async()=>{let{webcrypto:e}=await import(`./__vite-browser-external-2W3EstLn.js`).then(e=>t(e.default));return{webcrypto:e}},__vite__mapDeps([0,1]));return e}catch{throw Error(`failed to load Crypto`)}}function Ja(e,t){if(e.byteLength!==t.byteLength)throw Error(`xor: different length inputs`);let n=new Uint8Array(e.byteLength);for(let r=0;r<e.byteLength;r++)n[r]=e[r]^t[r];return n}var Ya=new Uint8Array([101,97,101,95,112,114,107]),Xa=new Uint8Array([115,104,97,114,101,100,95,115,101,99,114,101,116]);function Za(e,t,n){let r=new Uint8Array(e.length+t.length+n.length);return r.set(e,0),r.set(t,e.length),r.set(n,e.length+t.length),r}var Qa=class{constructor(e,t,n){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"secretSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"encSize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"publicKeySize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"privateKeySize",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_prim",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.id=e,this._prim=t,this._kdf=n;let r=new Uint8Array(Ra);r.set(Wa(this.id,2),3),this._kdf.init(r)}async serializePublicKey(e){return await this._prim.serializePublicKey(e)}async deserializePublicKey(e){return await this._prim.deserializePublicKey(X(e))}async serializePrivateKey(e){return await this._prim.serializePrivateKey(e)}async deserializePrivateKey(e){return await this._prim.deserializePrivateKey(X(e))}async importKey(e,t,n=!0){return await this._prim.importKey(e,t,n)}async generateKeyPair(){return await this._prim.generateKeyPair()}async deriveKeyPair(e){let t=X(e);if(t.byteLength>8192)throw new ha(`Too long ikm`);return await this._prim.deriveKeyPair(t)}async encap(e){let t;t=e.ekm===void 0?await this.generateKeyPair():Ua(e.ekm)?e.ekm:await this.deriveKeyPair(e.ekm);let n=await this._prim.serializePublicKey(t.publicKey),r=await this._prim.serializePublicKey(e.recipientPublicKey);try{let i;if(e.senderKey===void 0)i=new Uint8Array(await this._prim.dh(t.privateKey,e.recipientPublicKey));else{let n=Ua(e.senderKey)?e.senderKey.privateKey:e.senderKey;i=Ga(new Uint8Array(await this._prim.dh(t.privateKey,e.recipientPublicKey)),new Uint8Array(await this._prim.dh(n,e.recipientPublicKey)))}let a;if(e.senderKey===void 0)a=Ga(new Uint8Array(n),new Uint8Array(r));else{let t=Ua(e.senderKey)?e.senderKey.publicKey:await this._prim.derivePublicKey(e.senderKey),i=await this._prim.serializePublicKey(t);a=Za(new Uint8Array(n),new Uint8Array(r),new Uint8Array(i))}return{enc:n,sharedSecret:await this._generateSharedSecret(i,a)}}catch(e){throw new va(e)}}async decap(e){let t=X(e.enc),n=await this._prim.deserializePublicKey(t),r=Ua(e.recipientKey)?e.recipientKey.privateKey:e.recipientKey,i=Ua(e.recipientKey)?e.recipientKey.publicKey:await this._prim.derivePublicKey(e.recipientKey),a=await this._prim.serializePublicKey(i);try{let i;i=e.senderPublicKey===void 0?new Uint8Array(await this._prim.dh(r,n)):Ga(new Uint8Array(await this._prim.dh(r,n)),new Uint8Array(await this._prim.dh(r,e.senderPublicKey)));let o;if(e.senderPublicKey===void 0)o=Ga(new Uint8Array(t),new Uint8Array(a));else{let n=await this._prim.serializePublicKey(e.senderPublicKey);o=new Uint8Array(t.byteLength+a.byteLength+n.byteLength),o.set(new Uint8Array(t),0),o.set(new Uint8Array(a),t.byteLength),o.set(new Uint8Array(n),t.byteLength+a.byteLength)}return await this._generateSharedSecret(i,o)}catch(e){throw new ya(e)}}async _generateSharedSecret(e,t){let n=this._kdf.buildLabeledIkm(Ya,e),r=this._kdf.buildLabeledInfo(Xa,t,this.secretSize);return await this._kdf.extractAndExpand(Pa,n,r,this.secretSize)}},$a=[`deriveBits`],eo=new Uint8Array([100,107,112,95,112,114,107]),to=new Uint8Array([115,107]),no=class{constructor(e,t,n,r=[]){Object.defineProperty(this,"key",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extractable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"algorithm",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"usages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.key=t,this.type=n,this.algorithm={name:e},this.usages=r,n===`public`&&(this.usages=[])}},ro=class{constructor(e,t,n,r){Object.defineProperty(this,"_algName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_curve",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_hkdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nPk",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nSk",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._algName=e,this._nPk=t,this._nSk=t,this._curve=n,this._hkdf=r}serializePublicKey(e){try{return Promise.resolve(e.key.buffer)}catch(e){return Promise.reject(new ga(e))}}async deserializePublicKey(e){try{return await this._importRawKey(X(e),!0)}catch(e){throw new _a(e)}}serializePrivateKey(e){try{return Promise.resolve(e.key.buffer)}catch(e){return Promise.reject(new ga(e))}}async deserializePrivateKey(e){try{return await this._importRawKey(X(e),!1)}catch(e){throw new _a(e)}}async importKey(e,t,n){try{if(e===`raw`)return await this._importRawKey(t,n);if(t instanceof ArrayBuffer)throw Error(`Invalid jwk key format`);return await this._importJWK(t,n)}catch(e){throw new _a(e)}}async generateKeyPair(){try{let e=await this._curve.utils.randomSecretKey(),t=new no(this._algName,e,`private`,$a);return{publicKey:await this.derivePublicKey(t),privateKey:t}}catch(e){throw new Ta(e)}}async deriveKeyPair(e){try{let t=X(e),n=await this._hkdf.labeledExtract(Pa.buffer,eo,new Uint8Array(t)),r=await this._hkdf.labeledExpand(n,to,Pa,this._nSk),i=new no(this._algName,new Uint8Array(r),`private`,$a);return{privateKey:i,publicKey:await this.derivePublicKey(i)}}catch(e){throw new wa(e)}}derivePublicKey(e){try{let t=this._curve.getPublicKey(e.key);return Promise.resolve(new no(this._algName,t,`public`))}catch(e){return Promise.reject(new _a(e))}}dh(e,t){try{return Promise.resolve(this._curve.getSharedSecret(e.key,t.key).buffer)}catch(e){return Promise.reject(new ga(e))}}_importRawKey(e,t){return new Promise((n,r)=>{t&&e.byteLength!==this._nPk&&r(Error(`Invalid length of the key`)),!t&&e.byteLength!==this._nSk&&r(Error(`Invalid length of the key`)),n(new no(this._algName,new Uint8Array(e),t?`public`:`private`,t?[]:$a))})}_importJWK(e,t){return new Promise((n,r)=>{e.kty!==`OKP`&&r(Error(`Invalid kty: ${e.kty}`)),e.crv!==this._algName&&r(Error(`Invalid crv: ${e.crv}`)),t?(e.d!==void 0&&r(Error("Invalid key: `d` should not be set")),typeof e.x!=`string`&&r(Error("Invalid key: `x` not found")),n(new no(this._algName,Ka(e.x),`public`))):(typeof e.d!=`string`&&r(Error("Invalid key: `d` not found")),n(new no(this._algName,Ka(e.d),`private`,$a)))})}};function io(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function ao(e,t=``){if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw Error(`${n}expected integer >0, got ${e}`)}}function Z(e,t,n=``){let r=io(e),i=e?.length,a=t!==void 0;if(!r||a&&i!==t){let o=n&&`"${n}" `,s=a?` of length ${t}`:``,c=r?`length=${i}`:`type=${typeof e}`;throw Error(o+`expected Uint8Array`+s+`, got `+c)}return e}function oo(e,t=!0){if(e.destroyed)throw Error(`Hash instance has been destroyed`);if(t&&e.finished)throw Error(`Hash#digest() has already been called`)}function so(e,t){Z(e,void 0,`digestInto() output`);let n=t.outputLen;if(e.length<n)throw Error(`"digestInto() output" expected to be of length >=`+n)}function co(e){if(typeof e==`bigint`){if(!Oo(e))throw Error(`positive bigint expected, got `+e)}else ao(e);return e}function lo(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function uo(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var fo=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function po(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function mo(e,t){return e<<32-t|e>>>t}var ho=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,go=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`)),_o=[0n,1n,2n,3n,4n,5n,6n,7n,8n,9n,10n,11n,12n,13n,14n,15n];function vo(e){if(Z(e),ho)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=go[e[n]];return t}var yo={_0:48,_9:57,A:65,F:70,a:97,f:102};function bo(e){if(e>=yo._0&&e<=yo._9)return e-yo._0;if(e>=yo.A&&e<=yo.F)return e-(yo.A-10);if(e>=yo.a&&e<=yo.f)return e-(yo.a-10)}function xo(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);if(ho)return Uint8Array.fromHex(e);let t=e.length,n=t/2;if(t%2)throw Error(`hex string expected, got unpadded hex of length `+t);let r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){let n=bo(e.charCodeAt(i)),a=bo(e.charCodeAt(i+1));if(n===void 0||a===void 0){let t=e[i]+e[i+1];throw Error(`hex string expected, got non-hex character "`+t+`" at index `+i)}r[t]=n*16+a}return r}function So(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);let t=Fa;for(let n=0;n<e.length;n++){let r=bo(e.charCodeAt(n));if(r===void 0)throw Error(`hex string expected, got non-hex character "`+e[n]+`" at index `+n);t=t<<4n|_o[r]}return t}function Co(e){ao(e,`numberToBigint`);let t=e,n=Fa,r=1n;for(;t>0;)t%2==1&&(n+=r),t=Math.floor(t/2),r<<=1n;return n}function wo(e){return So(vo(Do(Z(e)).reverse()))}function To(e,t){ao(t),e=co(e);let n=xo(e.toString(16).padStart(t*2,`0`));if(n.length!==t)throw Error(`number too large`);return n}function Eo(e,t){return To(e,t).reverse()}function Do(e){return Uint8Array.from(e)}function Oo(e){return typeof e==`bigint`&&0n<=e}function ko(e,t,n){return Oo(e)&&Oo(t)&&Oo(n)&&t<=e&&e<n}function Ao(e,t,n,r){if(!ko(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function jo(e,t={},n={}){if(!e||typeof e!=`object`)throw Error(`expected valid options object`);function r(t,n,r){let i=e[t];if(r&&i===void 0)return;let a=typeof i;if(a!==n||i===null)throw Error(`param "${t}" is invalid: expected ${n}, got ${a}`)}let i=(e,t)=>Object.entries(e).forEach(([e,n])=>r(e,n,t));i(t,!1),i(n,!0)}async function Mo(e=32){let t=await qa(),n=new Uint8Array(e);return t.getRandomValues(n),n}function No(e){return{oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}}function Po(e){if(typeof e!=`function`||typeof e.create!=`function`)throw Error(`Hash must wrapped by utils.createHasher`);ao(e.outputLen),ao(e.blockLen)}function Fo(e,t={}){let n=(t,n)=>e(n).update(t).digest(),r=e(void 0),i=Object.assign(n,{outputLen:r.outputLen,blockLen:r.blockLen,create:t=>e(t),...t});return Object.freeze(i)}var Io=class{constructor(e,t){if(Object.defineProperty(this,"oHash",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"iHash",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockLen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputLen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"finished",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Po(e),Z(t,void 0,`key`),this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`Expected instance of class which extends utils.Hash`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),uo(r)}update(e){return oo(this),this.iHash.update(e),this}digestInto(e){oo(this),Z(e,this.outputLen,`output`),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Lo=(e,t,n)=>new Io(e,t).update(n).digest();Lo.create=(e,t)=>new Io(e,t);function Ro(e,t,n){return e&t^~e&n}function zo(e,t,n){return e&t^e&n^t&n}var Bo=class{constructor(e,t,n,r){Object.defineProperty(this,"blockLen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputLen",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"padOffset",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isLE",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"buffer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"view",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"finished",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"length",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"pos",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"destroyed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=po(this.buffer)}update(e){oo(this),Z(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){let t=po(e);for(;r<=i-a;a+=r)this.process(t,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){oo(this),so(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,uo(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let e=a;e<r;e++)t[e]=0;n.setBigUint64(r-8,Co(this.length*8),i),this.process(n,0);let o=po(e),s=this.outputLen;if(s%4)throw Error(`_sha2: outputLen must be aligned to 32bit`);let c=s/4,l=this.get();if(c>l.length)throw Error(`_sha2: outputLen bigger than state`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Vo=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ho=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Uo=new Uint32Array(64),Wo=class extends Bo{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}process(e,t){for(let n=0;n<16;n++,t+=4)Uo[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=Uo[e-15],n=Uo[e-2],r=mo(t,7)^mo(t,18)^t>>>3,i=mo(n,17)^mo(n,19)^n>>>10;Uo[e]=i+Uo[e-7]+r+Uo[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=mo(o,6)^mo(o,11)^mo(o,25),u=l+t+Ro(o,s,c)+Ho[e]+Uo[e]|0,d=(mo(n,2)^mo(n,13)^mo(n,22))+zo(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){uo(Uo)}destroy(){this.set(0,0,0,0,0,0,0,0),uo(this.buffer)}},Go=class extends Wo{constructor(){super(32),Object.defineProperty(this,"A",{enumerable:!0,configurable:!0,writable:!0,value:Vo[0]|0}),Object.defineProperty(this,"B",{enumerable:!0,configurable:!0,writable:!0,value:Vo[1]|0}),Object.defineProperty(this,"C",{enumerable:!0,configurable:!0,writable:!0,value:Vo[2]|0}),Object.defineProperty(this,"D",{enumerable:!0,configurable:!0,writable:!0,value:Vo[3]|0}),Object.defineProperty(this,"E",{enumerable:!0,configurable:!0,writable:!0,value:Vo[4]|0}),Object.defineProperty(this,"F",{enumerable:!0,configurable:!0,writable:!0,value:Vo[5]|0}),Object.defineProperty(this,"G",{enumerable:!0,configurable:!0,writable:!0,value:Vo[6]|0}),Object.defineProperty(this,"H",{enumerable:!0,configurable:!0,writable:!0,value:Vo[7]|0})}},Ko=Fo(()=>new Go,No(1));function qo(e,t){let n=e%t;return n>=0n?n:t+n}function Jo(e,t,n){let r=e;for(;t-->Fa;)r*=r,r%=n;return r}function Yo(e,t){return function(n){let r=e(n);return{secretKey:r,publicKey:t(r)}}}function Xo(e){return jo(e,{adjustScalarBytes:`function`,powPminus2:`function`}),Object.freeze({...e})}function Zo(e){let{P:t,type:n,adjustScalarBytes:r,powPminus2:i,randomBytes:a}=Xo(e),o=n===`x25519`;if(!o&&n!==`x448`)throw Error(`invalid type`);let s=a||Mo,c=o?255n:448n,l=o?32:56,u=o?9n:5n,d=o?121665n:39081n,f=o?La**254n:La**447n,p=f+(o?8n*La**251n-Ia:4n*La**445n-Ia)+Ia,m=e=>qo(e,t),h=g(u);function g(e){return Eo(m(e),l)}function ee(e){let t=Do(Z(e,l,`uCoordinate`));return o&&(t[31]&=127),m(wo(t))}function _(e){return wo(r(Do(Z(e,l,`scalar`))))}function v(e,t){let n=x(ee(t),_(e));if(n===0n)throw Error(`invalid private or public key received`);return g(n)}function te(e){return v(e,h)}let ne=te,y=v;function b(e,t,n){let r=m(e*(t-n));return t=m(t-r),n=m(n+r),{x_2:t,x_3:n}}function x(e,n){Ao(`u`,e,Fa,t),Ao(`scalar`,n,f,p);let r=n,a=e,o=Ia,s=Fa,l=e,u=Ia,h=Fa;for(let e=c-1n;e>=Fa;e--){let t=r>>e&Ia;h^=t,{x_2:o,x_3:l}=b(h,o,l),{x_2:s,x_3:u}=b(h,s,u),h=t;let n=o+s,i=m(n*n),c=o-s,f=m(c*c),p=i-f,g=l+u,ee=l-u,_=m(ee*n),v=m(g*c),te=_+v,ne=_-v;l=m(te*te),u=m(a*m(ne*ne)),o=m(i*f),s=m(p*(i+m(d*p)))}({x_2:o,x_3:l}=b(h,o,l)),{x_2:s,x_3:u}=b(h,s,u);let g=i(s);return m(o*g)}let S={secretKey:l,publicKey:l,seed:l},C=async e=>(e===void 0&&(e=await s(l)),Z(e,S.seed,`seed`),e),w={randomSecretKey:C};return Object.freeze({keygen:Yo(C,ne),getSharedSecret:y,getPublicKey:ne,scalarMult:v,scalarMultBase:te,utils:w,GuBytes:h.slice(),lengths:S})}function Qo(e){if(typeof e!=`boolean`)throw Error(`boolean expected, not ${e}`)}var $o=(e,t)=>{function n(n,...r){if(Z(n,void 0,`key`),!fo)throw Error(`Non little-endian hardware is not yet supported`);if(e.nonceLength!==void 0){let t=r[0];Z(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength;i&&r[1]!==void 0&&Z(r[1],void 0,`AAD`);let a=t(n,...r),o=(e,t)=>{if(t!==void 0){if(e!==2)throw Error(`cipher output not supported`);Z(t,void 0,`output`)}},s=!1;return{encrypt(e,t){if(s)throw Error(`cannot encrypt() twice with same key + nonce`);return s=!0,Z(e),o(a.encrypt.length,t),a.encrypt(e,t)},decrypt(e,t){if(Z(e),i&&e.length<i)throw Error(`"ciphertext" expected length bigger than tagLength=`+i);return o(a.decrypt.length,t),a.decrypt(e,t)}}}return Object.assign(n,e),n};function es(e,t){if(typeof t!=`object`||!t)throw Error(`options must be defined`);return Object.assign(e,t)}function ts(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function ns(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(t.length!==e)throw Error(`"output" expected Uint8Array of length `+e+`, got: `+t.length);if(n&&!is(t))throw Error(`invalid output, must be aligned`);return t}function rs(e,t,n){Qo(n);let r=new Uint8Array(16),i=po(r);return i.setBigUint64(0,Co(t),n),i.setBigUint64(8,Co(e),n),r}function is(e){return e.byteOffset%4==0}var as=e=>Uint8Array.from(e.split(``).map(e=>e.charCodeAt(0))),os=as(`expand 16-byte k`),ss=as(`expand 32-byte k`),cs=lo(os),ls=lo(ss);function Q(e,t){return e<<t|e>>>32-t}function us(e){return e.byteOffset%4==0}var ds=64,fs=16,ps=2**32-1,ms=Uint32Array.of();function hs(e,t,n,r,i,a,o,s){let c=i.length,l=new Uint8Array(ds),u=lo(l),d=us(i)&&us(a),f=d?lo(i):ms,p=d?lo(a):ms;for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=ps)throw Error(`arx: counter overflow`);let h=Math.min(ds,c-m);if(d&&h===ds){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<fs;t++)n=e+t,p[n]=f[n]^u[t];m+=ds;continue}for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}function gs(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=es({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return ao(i),ao(o),Qo(a),Qo(n),(t,s,c,l,u=0)=>{Z(t,void 0,`key`),Z(s,void 0,`nonce`),Z(c,void 0,`data`);let d=c.length;if(l===void 0&&(l=new Uint8Array(d)),Z(l,void 0,`output`),ao(u),u<0||u>=ps)throw Error(`arx: counter overflow`);if(l.length<d)throw Error(`arx: output (${l.length}) is shorter than data (${d})`);let f=[],p=t.length,m,h;if(p===32)f.push(m=Do(t)),h=ls;else if(p===16&&n)m=new Uint8Array(32),m.set(t),m.set(t,16),h=cs,f.push(m);else throw Z(t,32,`arx key`),Error(`invalid key size`);us(s)||f.push(s=Do(s));let g=lo(m);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);r(h,g,lo(s.subarray(0,16)),g),s=s.subarray(16)}let ee=16-i;if(ee!==s.length)throw Error(`arx: nonce must be ${ee} or 16 bytes`);if(ee!==12){let e=new Uint8Array(12);e.set(s,a?0:12-s.length),s=e,f.push(s)}let _=lo(s);return hs(e,h,g,_,c,l,u,o),uo(...f),l}}function _s(e,t){return e[t++]&255|(e[t++]&255)<<8}var vs=class{constructor(e){Object.defineProperty(this,"blockLen",{enumerable:!0,configurable:!0,writable:!0,value:16}),Object.defineProperty(this,"outputLen",{enumerable:!0,configurable:!0,writable:!0,value:16}),Object.defineProperty(this,"buffer",{enumerable:!0,configurable:!0,writable:!0,value:new Uint8Array(16)}),Object.defineProperty(this,"r",{enumerable:!0,configurable:!0,writable:!0,value:new Uint16Array(10)}),Object.defineProperty(this,"h",{enumerable:!0,configurable:!0,writable:!0,value:new Uint16Array(10)}),Object.defineProperty(this,"pad",{enumerable:!0,configurable:!0,writable:!0,value:new Uint16Array(8)}),Object.defineProperty(this,"pos",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"finished",{enumerable:!0,configurable:!0,writable:!0,value:!1}),e=Do(Z(e,32,`key`));let t=_s(e,0),n=_s(e,2),r=_s(e,4),i=_s(e,6),a=_s(e,8),o=_s(e,10),s=_s(e,12),c=_s(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|o<<2)&8191,this.r[7]=(o>>>11|s<<5)&8065,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=_s(e,16+2*t)}process(e,t,n=!1){let r=n?0:2048,{h:i,r:a}=this,o=a[0],s=a[1],c=a[2],l=a[3],u=a[4],d=a[5],f=a[6],p=a[7],m=a[8],h=a[9],g=_s(e,t+0),ee=_s(e,t+2),_=_s(e,t+4),v=_s(e,t+6),te=_s(e,t+8),ne=_s(e,t+10),y=_s(e,t+12),b=_s(e,t+14),x=i[0]+(g&8191),S=i[1]+((g>>>13|ee<<3)&8191),C=i[2]+((ee>>>10|_<<6)&8191),w=i[3]+((_>>>7|v<<9)&8191),T=i[4]+((v>>>4|te<<12)&8191),E=i[5]+(te>>>1&8191),D=i[6]+((te>>>14|ne<<2)&8191),O=i[7]+((ne>>>11|y<<5)&8191),k=i[8]+((y>>>8|b<<8)&8191),A=i[9]+(b>>>5|r),j=0,M=j+x*o+5*h*S+5*m*C+5*p*w+5*f*T;j=M>>>13,M&=8191,M+=5*d*E+5*u*D+5*l*O+5*c*k+5*s*A,j+=M>>>13,M&=8191;let N=j+x*s+S*o+5*h*C+5*m*w+5*p*T;j=N>>>13,N&=8191,N+=5*f*E+5*d*D+5*u*O+5*l*k+5*c*A,j+=N>>>13,N&=8191;let P=j+x*c+S*s+C*o+5*h*w+5*m*T;j=P>>>13,P&=8191,P+=5*p*E+5*f*D+5*d*O+5*u*k+5*l*A,j+=P>>>13,P&=8191;let F=j+x*l+S*c+C*s+w*o+5*h*T;j=F>>>13,F&=8191,F+=5*m*E+5*p*D+5*f*O+5*d*k+5*u*A,j+=F>>>13,F&=8191;let re=j+x*u+S*l+C*c+w*s+T*o;j=re>>>13,re&=8191,re+=5*h*E+5*m*D+5*p*O+5*f*k+5*d*A,j+=re>>>13,re&=8191;let ie=j+x*d+S*u+C*l+w*c+T*s;j=ie>>>13,ie&=8191,ie+=E*o+5*h*D+5*m*O+5*p*k+5*f*A,j+=ie>>>13,ie&=8191;let ae=j+x*f+S*d+C*u+w*l+T*c;j=ae>>>13,ae&=8191,ae+=E*s+D*o+5*h*O+5*m*k+5*p*A,j+=ae>>>13,ae&=8191;let oe=j+x*p+S*f+C*d+w*u+T*l;j=oe>>>13,oe&=8191,oe+=E*c+D*s+O*o+5*h*k+5*m*A,j+=oe>>>13,oe&=8191;let se=j+x*m+S*p+C*f+w*d+T*u;j=se>>>13,se&=8191,se+=E*l+D*c+O*s+k*o+5*h*A,j+=se>>>13,se&=8191;let ce=j+x*h+S*m+C*p+w*f+T*d;j=ce>>>13,ce&=8191,ce+=E*u+D*l+O*c+k*s+A*o,j+=ce>>>13,ce&=8191,j=(j<<2)+j|0,j=j+M|0,M=j&8191,j>>>=13,N+=j,i[0]=M,i[1]=N,i[2]=P,i[3]=F,i[4]=re,i[5]=ie,i[6]=ae,i[7]=oe,i[8]=se,i[9]=ce}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let i=(r^1)-1;for(let e=0;e<10;e++)n[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|n[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let a=e[0]+t[0];e[0]=a&65535;for(let n=1;n<8;n++)a=(e[n]+t[n]|0)+(a>>>16)|0,e[n]=a&65535;uo(n)}update(e){oo(this),Z(e),e=Do(e);let{buffer:t,blockLen:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(n-this.pos,r-i);if(a===n){for(;n<=r-i;i+=n)this.process(e,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){uo(this.h,this.r,this.buffer,this.pad)}digestInto(e){oo(this),so(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=n[t]>>>0,e[i++]=n[t]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};function ys(e){let t=(t,n)=>e(n).update(t).digest(),n=e(new Uint8Array(32));return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t}var bs=ys(e=>new vs(e));function xs(e,t,n,r,i,a=20){let o=e[0],s=e[1],c=e[2],l=e[3],u=t[0],d=t[1],f=t[2],p=t[3],m=t[4],h=t[5],g=t[6],ee=t[7],_=i,v=n[0],te=n[1],ne=n[2],y=o,b=s,x=c,S=l,C=u,w=d,T=f,E=p,D=m,O=h,k=g,A=ee,j=_,M=v,N=te,P=ne;for(let e=0;e<a;e+=2)y=y+C|0,j=Q(j^y,16),D=D+j|0,C=Q(C^D,12),y=y+C|0,j=Q(j^y,8),D=D+j|0,C=Q(C^D,7),b=b+w|0,M=Q(M^b,16),O=O+M|0,w=Q(w^O,12),b=b+w|0,M=Q(M^b,8),O=O+M|0,w=Q(w^O,7),x=x+T|0,N=Q(N^x,16),k=k+N|0,T=Q(T^k,12),x=x+T|0,N=Q(N^x,8),k=k+N|0,T=Q(T^k,7),S=S+E|0,P=Q(P^S,16),A=A+P|0,E=Q(E^A,12),S=S+E|0,P=Q(P^S,8),A=A+P|0,E=Q(E^A,7),y=y+w|0,P=Q(P^y,16),k=k+P|0,w=Q(w^k,12),y=y+w|0,P=Q(P^y,8),k=k+P|0,w=Q(w^k,7),b=b+T|0,j=Q(j^b,16),A=A+j|0,T=Q(T^A,12),b=b+T|0,j=Q(j^b,8),A=A+j|0,T=Q(T^A,7),x=x+E|0,M=Q(M^x,16),D=D+M|0,E=Q(E^D,12),x=x+E|0,M=Q(M^x,8),D=D+M|0,E=Q(E^D,7),S=S+C|0,N=Q(N^S,16),O=O+N|0,C=Q(C^O,12),S=S+C|0,N=Q(N^S,8),O=O+N|0,C=Q(C^O,7);let F=0;r[F++]=o+y|0,r[F++]=s+b|0,r[F++]=c+x|0,r[F++]=l+S|0,r[F++]=u+C|0,r[F++]=d+w|0,r[F++]=f+T|0,r[F++]=p+E|0,r[F++]=m+D|0,r[F++]=h+O|0,r[F++]=g+k|0,r[F++]=ee+A|0,r[F++]=_+j|0,r[F++]=v+M|0,r[F++]=te+N|0,r[F++]=ne+P|0}var Ss=gs(xs,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Cs=new Uint8Array(16),ws=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(Cs.subarray(n))},Ts=new Uint8Array(32);function Es(e,t,n,r,i){i!==void 0&&Z(i,void 0,`AAD`);let a=e(t,n,Ts),o=rs(r.length,i?i.length:0,!0),s=bs.create(a);i&&ws(s,i),ws(s,r),s.update(o);let c=s.digest();return uo(a,o),c}var Ds=$o({blockSize:64,nonceLength:12,tagLength:16},(e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=ns(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=Es(e,t,n,s,r);return a.set(c,o),uo(c),a},decrypt(i,a){a=ns(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=Es(e,t,n,o,r);if(!ts(s,c))throw Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),uo(c),a}}))(Ss)),Os=class{constructor(e){Object.defineProperty(this,"_key",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._key=new Uint8Array(X(e))}async seal(e,t,n){return await this._seal(X(e),X(t),X(n))}async open(e,t,n){return await this._open(X(e),X(t),X(n))}_seal(e,t,n){return new Promise(r=>{r(Ds(this._key,new Uint8Array(e),new Uint8Array(n)).encrypt(new Uint8Array(t)).buffer)})}_open(e,t,n){return new Promise(r=>{r(Ds(this._key,new Uint8Array(e),new Uint8Array(n)).decrypt(new Uint8Array(t)).buffer)})}},ks=class{constructor(){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:Na.Chacha20Poly1305}),Object.defineProperty(this,"keySize",{enumerable:!0,configurable:!0,writable:!0,value:32}),Object.defineProperty(this,"nonceSize",{enumerable:!0,configurable:!0,writable:!0,value:12}),Object.defineProperty(this,"tagSize",{enumerable:!0,configurable:!0,writable:!0,value:16})}createEncryptionContext(e){return new Os(e)}};function As(){return new Promise((e,t)=>{t(new Ta(`Not supported`))})}var js=new Uint8Array([115,101,99]),Ms=class{constructor(e,t,n){Object.defineProperty(this,"_api",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exporterSecret",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._api=e,this._kdf=t,this.exporterSecret=n}async seal(e,t){return await As()}async open(e,t){return await As()}async export(e,t){let n=X(e);if(n.byteLength>8192)throw new ha(`Too long exporter context`);try{return await this._kdf.labeledExpand(this.exporterSecret,js,new Uint8Array(n),t)}catch(e){throw new ba(e)}}},Ns=class extends Ms{},Ps=class extends Ms{constructor(e,t,n,r){super(e,t,n),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.enc=r}},Fs=class extends Ms{constructor(e,t,n){if(super(e,t,n.exporterSecret),Object.defineProperty(this,"_aead",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nK",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nN",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_nT",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_ctx",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.key===void 0||n.baseNonce===void 0||n.seq===void 0)throw Error(`Required parameters are missing`);this._aead=n.aead,this._nK=this._aead.keySize,this._nN=this._aead.nonceSize,this._nT=this._aead.tagSize;let r=this._aead.createEncryptionContext(n.key);this._ctx={key:r,baseNonce:n.baseNonce,seq:n.seq}}computeNonce(e){let t=Wa(e.seq,e.baseNonce.byteLength);return Ja(e.baseNonce,t).buffer}incrementSeq(e){if(e.seq>2**53-1)throw new Ca(`Message limit reached`);e.seq+=1}},Is=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},Ls=function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},Rs,zs=class{constructor(){Rs.set(this,Promise.resolve())}async lock(){let e,t=new Promise(t=>{e=t}),n=Is(this,Rs,`f`);return Ls(this,Rs,t,`f`),await n,e}};Rs=new WeakMap;var Bs=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},Vs=function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},Hs,Us=class extends Fs{constructor(){super(...arguments),Hs.set(this,void 0)}async open(e,t=Pa.buffer){Vs(this,Hs,Bs(this,Hs,`f`)??new zs,`f`);let n=await Bs(this,Hs,`f`).lock(),r;try{r=await this._ctx.key.open(this.computeNonce(this._ctx),X(e),X(t))}catch(e){throw new Sa(e)}finally{n()}return this.incrementSeq(this._ctx),r}};Hs=new WeakMap;var Ws=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},Gs=function(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n},Ks,qs=class extends Fs{constructor(e,t,n,r){super(e,t,n),Object.defineProperty(this,"enc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Ks.set(this,void 0),this.enc=r}async seal(e,t=Pa.buffer){Gs(this,Ks,Ws(this,Ks,`f`)??new zs,`f`);let n=await Ws(this,Ks,`f`).lock(),r;try{r=await this._ctx.key.seal(this.computeNonce(this._ctx),X(e),X(t))}catch(e){throw new xa(e)}finally{n()}return this.incrementSeq(this._ctx),r}};Ks=new WeakMap;var Js=new Uint8Array([98,97,115,101,95,110,111,110,99,101]),Ys=new Uint8Array([101,120,112]),Xs=new Uint8Array([105,110,102,111,95,104,97,115,104]),Zs=new Uint8Array([107,101,121]),Qs=new Uint8Array([112,115,107,95,105,100,95,104,97,115,104]),$s=new Uint8Array([115,101,99,114,101,116]),ec=new Uint8Array([72,80,75,69,0,0,0,0,0,0]),tc=class extends ka{constructor(e){if(super(),Object.defineProperty(this,"_kem",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_kdf",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_aead",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_suiteId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof e.kem==`number`)throw new ha(`KemId cannot be used`);if(this._kem=e.kem,typeof e.kdf==`number`)throw new ha(`KdfId cannot be used`);if(this._kdf=e.kdf,typeof e.aead==`number`)throw new ha(`AeadId cannot be used`);this._aead=e.aead,this._suiteId=new Uint8Array(ec),this._suiteId.set(Wa(this._kem.id,2),4),this._suiteId.set(Wa(this._kdf.id,2),6),this._suiteId.set(Wa(this._aead.id,2),8),this._kdf.init(this._suiteId)}get kem(){return this._kem}get kdf(){return this._kdf}get aead(){return this._aead}async createSenderContext(e){this._validateInputLength(e),await this._setup();let t=await this._kem.encap(e),n;return n=e.psk===void 0?e.senderKey===void 0?Aa.Base:Aa.Auth:e.senderKey===void 0?Aa.Psk:Aa.AuthPsk,await this._keyScheduleS(n,t.sharedSecret,t.enc,e)}async createRecipientContext(e){this._validateInputLength(e),await this._setup();let t=await this._kem.decap(e),n;return n=e.psk===void 0?e.senderPublicKey===void 0?Aa.Base:Aa.Auth:e.senderPublicKey===void 0?Aa.Psk:Aa.AuthPsk,await this._keyScheduleR(n,t,e)}async seal(e,t,n=Pa.buffer){let r=await this.createSenderContext(e);return{ct:await r.seal(t,n),enc:r.enc}}async open(e,t,n=Pa.buffer){return await(await this.createRecipientContext(e)).open(t,n)}async _keySchedule(e,t,n){let r=n.psk===void 0?Pa:Ba(n.psk.id),i=await this._kdf.labeledExtract(Pa,Qs,r),a=n.info===void 0?Pa:Ba(n.info),o=await this._kdf.labeledExtract(Pa,Xs,a),s=new Uint8Array(1+i.byteLength+o.byteLength);s.set(new Uint8Array([e]),0),s.set(new Uint8Array(i),1),s.set(new Uint8Array(o),1+i.byteLength);let c=n.psk===void 0?Pa:Ba(n.psk.key),l=this._kdf.buildLabeledIkm($s,c),u=this._kdf.buildLabeledInfo(Ys,s,this._kdf.hashSize),d=await this._kdf.extractAndExpand(t,l,u,this._kdf.hashSize);if(this._aead.id===Na.ExportOnly)return{aead:this._aead,exporterSecret:d};let f=this._kdf.buildLabeledInfo(Zs,s,this._aead.keySize),p=await this._kdf.extractAndExpand(t,l,f,this._aead.keySize),m=this._kdf.buildLabeledInfo(Js,s,this._aead.nonceSize),h=await this._kdf.extractAndExpand(t,l,m,this._aead.nonceSize);return{aead:this._aead,exporterSecret:d,key:p,baseNonce:new Uint8Array(h),seq:0}}async _keyScheduleS(e,t,n,r){let i=await this._keySchedule(e,t,r);return i.key===void 0?new Ps(this._api,this._kdf,i.exporterSecret,n):new qs(this._api,this._kdf,i,n)}async _keyScheduleR(e,t,n){let r=await this._keySchedule(e,t,n);return r.key===void 0?new Ns(this._api,this._kdf,r.exporterSecret):new Us(this._api,this._kdf,r)}_validateInputLength(e){if(e.info!==void 0&&e.info.byteLength>268435456)throw new ha(`Too long info`);if(e.psk!==void 0){if(e.psk.key.byteLength<32)throw new ha(`PSK must have at least 32 bytes`);if(e.psk.key.byteLength>8192)throw new ha(`Too long psk.key`);if(e.psk.id.byteLength>8192)throw new ha(`Too long psk.id`)}}},nc=class extends tc{},rc=1n,ic=2n,ac=3n,oc=5n,sc=57896044618658097711785492504343953926634992332820282019728792003956564819949n;function cc(e){let t=10n,n=80n,r=sc,i=e*e%r*e%r,a=Jo(Jo(i,ic,r)*i%r,rc,r)*e%r,o=Jo(a,oc,r)*a%r,s=Jo(o,t,r)*o%r,c=Jo(s,20n,r)*s%r,l=Jo(c,40n,r)*c%r;return{pow_p_5_8:Jo(Jo(Jo(Jo(l,n,r)*l%r,n,r)*l%r,t,r)*o%r,ic,r)*e%r,b2:i}}function lc(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var uc=(()=>{let e=sc;return Zo({P:e,type:`x25519`,powPminus2:t=>{let{pow_p_5_8:n,b2:r}=cc(t);return qo(Jo(n,ac,e)*r,e)},adjustScalarBytes:lc})})(),dc=class extends ro{constructor(e){super(`X25519`,32,uc,e)}derive(e,t){try{return Promise.resolve(this._curve.getSharedSecret(e,t))}catch(e){return Promise.reject(new ga(e))}}},fc=`DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/CHACHA20_POLY1305/AUTH`,pc=2**31,mc=65536,hc=16,gc=32,_c=(1n<<255n)-19n,vc=new TextEncoder,yc=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`;function bc(e){let t=0n;for(let n=0;n<e.length;n+=2)t|=BigInt(Number.parseInt(e.slice(n,n+2),16))<<BigInt(n/2*8);return t}var xc=new Set([0n,1n,bc(`e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800`),bc(`5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157`),_c-1n]),Sc=new Uint8Array,Cc=class extends Ha{async extract(e,t){return X(Lo(Ko,e.byteLength===0?new Uint8Array(this.hashSize):Ba(e),Ba(t)))}async expand(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>255*this.hashSize)throw Error(`HKDF output length exceeds the RFC 5869 limit.`);let r=Ba(e),i=Ba(t),a=new Uint8Array(n),o=Sc;for(let e=1,t=0;t<a.byteLength;e+=1){let n=Dc([o,i,Uint8Array.of(e)]);o=new Uint8Array(Lo(Ko,r,n));let s=a.byteLength-t;a.set(o.subarray(0,Math.min(o.byteLength,s)),t),t+=Math.min(o.byteLength,s)}return X(a)}async extractAndExpand(e,t,n,r){return this.expand(await this.extract(e,t),n,r)}},wc=new nc({kem:new class extends Qa{secretSize=32;encSize=32;publicKeySize=32;privateKeySize=32;constructor(e){super(ja.DhkemX25519HkdfSha256,new dc(e),e)}}(new Cc),kdf:new Cc,aead:new ks}),$=class extends Error{code;name=`RelayPayloadChannelFailure`;constructor(e,t){super(t),this.code=e}};function Tc(e){return new Uint8Array(e.slice(0))}function Ec(e){let t=new Uint8Array(e.byteLength);return t.set(e),t.buffer}function Dc(e){let t=e.reduce((e,t)=>e+t.byteLength,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.byteLength;return n}function Oc(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new $(`channel_ticket_binding_invalid`,`Invalid uint32 value.`);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t}function kc(e){if(!Number.isSafeInteger(e)||e<0)throw new $(`channel_ticket_binding_invalid`,`Invalid uint64 value.`);let t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t}function Ac(e){return Dc([Oc(e.byteLength),e])}function jc(e){return Uint8Array.of(e===`control-to-runtime`?0:1)}function Mc(e){return e===`handshake`?Uint8Array.of(0):e===`application`?Uint8Array.of(1):Uint8Array.of(2)}function Nc(e){let t=``;for(let n=0;n<e.byteLength;n+=3){let r=e[n]??0,i=e[n+1]??0,a=e[n+2]??0,o=r<<16|i<<8|a;t+=yc[o>>>18&63],t+=yc[o>>>12&63],n+1<e.byteLength&&(t+=yc[o>>>6&63]),n+2<e.byteLength&&(t+=yc[o&63])}return t}function Pc(e){if(!/^[A-Za-z0-9_-]*$/.test(e)||e.length%4==1)throw new $(`channel_authentication_failed`,`Encrypted relay frame is not canonical base64url.`);let t=new Uint8Array(Math.floor(e.length*6/8)),n=0,r=0,i=0;for(let a of e){let e=yc.indexOf(a);n=n<<6|e,r+=6,r>=8&&(r-=8,t[i]=n>>>r&255,i+=1)}if(Nc(t)!==e)throw new $(`channel_authentication_failed`,`Encrypted relay frame has a non-canonical base64url encoding.`);return t}function Fc(e){let t=new Uint8Array(e);t[31]=(t[31]??0)&127;let n=0n;for(let e=0;e<t.byteLength;e+=1)n|=BigInt(t[e]??0)<<BigInt(e*8);return xc.has(n%_c)}var Ic={async sha256(e){if(globalThis.crypto?.subtle===void 0)throw new $(`channel_authentication_failed`,`SHA-256 is unavailable in this runtime.`);return Tc(await globalThis.crypto.subtle.digest(`SHA-256`,Ec(e)))}},Lc={randomBytes(e){if(globalThis.crypto?.getRandomValues===void 0)throw new $(`endpoint_key_invalid`,`A cryptographically secure random source is unavailable.`);return globalThis.crypto.getRandomValues(new Uint8Array(e))}};function Rc(e,t){let n=vc.encode(e).byteLength;if(n===0||n>256)throw new $(`channel_ticket_binding_invalid`,`${t} must contain between 1 and 256 UTF-8 bytes.`)}function zc(e){let t=vc.encode(e).byteLength;if(t===0||t>65536)throw new $(`channel_ticket_binding_invalid`,`Control ticket must contain between 1 and ${mc} UTF-8 bytes.`)}async function Bc(e,t=Ic){zc(e.exactCompactTicket),Rc(e.channelId,`Channel ID`),Rc(e.runtimeId,`Runtime ID`),kc(e.connectionEpoch);let n=await t.sha256(vc.encode(e.exactCompactTicket));if(n.byteLength!==32)throw new $(`channel_ticket_binding_invalid`,`The control ticket digest must be 32 bytes.`);return{...e,ticketDigest:new Uint8Array(n)}}function Vc(e){return Nc(e.ticketDigest)}async function Hc(e=Lc){let t=new Uint8Array(await e.randomBytes(gc));if(t.byteLength!==gc)throw new $(`endpoint_key_invalid`,`The endpoint random source must return ${gc} bytes.`);try{return Nc(t)}finally{t.fill(0)}}function Uc(e){return Dc([vc.encode(`forge-relay-v4`),Uint8Array.of(0),e.ticketDigest,jc(e.direction)])}function Wc(e){return Dc([vc.encode(`forge-relay`),Oc(4),e.binding.ticketDigest,vc.encode(e.binding.channelId),jc(e.binding.direction),Mc(e.frameClass),kc(e.sequence),vc.encode(e.binding.runtimeId),kc(e.binding.connectionEpoch),Oc(e.ciphertextLength)].map(Ac))}async function Gc(e=Lc){let t=new Uint8Array(await e.randomBytes(gc));if(t.byteLength!==gc)throw new $(`endpoint_key_invalid`,`The endpoint random source must return ${gc} bytes.`);try{return await wc.kem.deriveKeyPair(t)}catch(e){throw new $(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint key generation failed.`)}finally{t.fill(0)}}async function Kc(e){try{return Nc(Tc(await wc.kem.serializePublicKey(e)))}catch(e){throw new $(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint public-key serialization failed.`)}}function qc(e,t){if(!/^[A-Za-z0-9_-]{43}$/u.test(t))throw new $(`endpoint_key_invalid`,`The endpoint key ID requires a canonical X25519 public key.`);return`${e}:${t}`}async function Jc(e){try{let t=Pc(e);if(t.byteLength!==gc)throw Error(`Invalid endpoint key length.`);if(Fc(t))throw new $(`endpoint_key_invalid`,`Low-order X25519 endpoint public keys are not allowed.`);return await wc.kem.deserializePublicKey(t)}catch(e){throw e instanceof $?e:new $(`endpoint_key_invalid`,e instanceof Error?e.message:`Endpoint public-key deserialization failed.`)}}var Yc=class{tail=Promise.resolve();run(e){let t=this.tail.then(e,e);return this.tail=t.then(()=>void 0,()=>void 0),t}},Xc=class{startedAt=Date.now();records=0;bytes=0;assertAvailable(e){if(this.records>=pc||this.bytes+e>1073741824||Date.now()-this.startedAt>=18e5)throw new $(`channel_limit_reached`,`The encrypted relay channel must be renewed before another record is sent.`)}commit(e){this.records+=1,this.bytes+=e}};function Zc(e,t){if(e.type!==`relay.encrypted-frame`||e.protocolVersion!==4||e.channelId!==t.channelId||e.direction!==t.direction||![`handshake`,`application`,`close`].includes(e.frameClass))throw new $(`channel_ticket_binding_invalid`,`Encrypted relay frame does not match the CMMD-ticket-bound channel.`)}var Qc=class{binding;context;encapsulatedKey;queue=new Yc;budget=new Xc;sequence=0;constructor(e,t){this.binding=e,this.context=t,this.encapsulatedKey=Nc(Tc(t.enc))}seal(e){return this.queue.run(async()=>{if(e.plaintext.byteLength>16777216)throw new $(`channel_limit_reached`,`Encrypted relay plaintext exceeds the per-record byte limit.`);let t=e.plaintext.byteLength+hc;this.budget.assertAvailable(t);let n=this.sequence,r=Wc({binding:this.binding,frameClass:e.frameClass,sequence:n,ciphertextLength:t}),i;try{i=Tc(await this.context.seal(e.plaintext,r))}catch(e){throw new $(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload encryption failed.`)}if(i.byteLength!==t)throw new $(`channel_authentication_failed`,`Relay payload encryption returned an invalid ciphertext length.`);return this.sequence+=1,this.budget.commit(i.byteLength),{type:`relay.encrypted-frame`,protocolVersion:4,channelId:this.binding.channelId,direction:this.binding.direction,frameClass:e.frameClass,sequence:n,ciphertext:Nc(i)}})}},$c=class{binding;context;queue=new Yc;budget=new Xc;sequence=0;constructor(e,t){this.binding=e,this.context=t}open(e){return this.queue.run(async()=>{if(Zc(e,this.binding),!Number.isSafeInteger(e.sequence)||e.sequence!==this.sequence)throw new $(`channel_sequence_invalid`,`Expected encrypted relay sequence ${this.sequence}, received ${String(e.sequence)}.`);let t=Pc(e.ciphertext);this.budget.assertAvailable(t.byteLength);let n=Wc({binding:this.binding,frameClass:e.frameClass,sequence:e.sequence,ciphertextLength:t.byteLength}),r;try{r=Tc(await this.context.open(t,n))}catch(e){throw new $(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload authentication failed.`)}if(r.byteLength>16777216)throw new $(`channel_limit_reached`,`Decrypted relay plaintext exceeds the per-record byte limit.`);return this.sequence+=1,this.budget.commit(t.byteLength),r})}};async function el(e){let t=null;try{if(t=new Uint8Array(await(e.randomSource??Lc).randomBytes(gc)),t.byteLength!==gc)throw Error(`The endpoint random source must return ${gc} bytes.`);let n=await wc.createSenderContext({recipientPublicKey:e.recipientPublicKey,senderKey:e.senderKey,info:Uc(e.binding),ekm:t});return new Qc(e.binding,n)}catch(e){throw new $(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload sender setup failed.`)}finally{t?.fill(0)}}async function tl(e){try{let t=await wc.createRecipientContext({recipientKey:e.recipientKey,senderPublicKey:e.senderPublicKey,enc:Pc(e.encapsulatedKey),info:Uc(e.binding)});return new $c(e.binding,t)}catch(e){throw e instanceof $?e:new $(`channel_authentication_failed`,e instanceof Error?e.message:`Relay payload recipient setup failed.`)}}var nl=128,rl=2097152,il=864e5,al=class extends Error{constructor(e){super(e),this.name=`RelayControlJournalError`}};function ol(e){return typeof e==`string`&&e.length>0}function sl(e){return ol(e)&&Number.isFinite(Date.parse(e))}function cl(e){return e===`pending`||e===`retrying`||e===`outcome-unknown`||e===`failed`}function ll(e){return ol(e.transportRequestId)&&ol(e.runtimeId)&&ol(e.actorSessionId)&&ol(e.durableRequestId)&&ol(e.method)}function ul(e){return Number.isSafeInteger(e.sequence)&&Number(e.sequence)>0&&Number.isSafeInteger(e.attemptCount)&&Number(e.attemptCount)>=0}function dl(e){return e.persistence!==`frame`&&e.persistence!==`metadata-only`||e.frame!==null&&!ol(e.frame)?!1:e.persistence!==`metadata-only`||e.frame===null}function fl(e){return!cl(e.status)||e.errorCode!==null&&!ol(e.errorCode)?!1:e.status===`outcome-unknown`||e.status===`failed`?e.frame===null&&ol(e.errorCode):e.errorCode===null}function pl(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return ll(t)&&ul(t)&&dl(t)&&fl(t)&&sl(t.createdAt)&&sl(t.updatedAt)}function ml(e){try{return JSON.parse(e)}catch{throw new al(`Forge relay control journal is corrupt.`)}}function hl(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return t.version===1&&ol(t.controlSessionId)&&Number.isSafeInteger(t.nextSequence)&&Number(t.nextSequence)>=1&&Array.isArray(t.records)&&t.records.every(pl)}function gl(e){let t=new Set(e.map(yl)),n=new Set(e.map(e=>e.durableRequestId)),r=new Set(e.map(e=>e.sequence));return t.size===e.length&&n.size===e.length&&r.size===e.length}function _l(e){let t=ml(e);if(!hl(t))throw new al(`Forge relay control journal is corrupt.`);let n=t.records,r=n.reduce((e,t)=>Math.max(e,t.sequence),0);if(!gl(n)||t.nextSequence<=r)throw new al(`Forge relay control journal is corrupt.`);return{version:1,controlSessionId:t.controlSessionId,nextSequence:t.nextSequence,records:n}}function vl(){return crypto.randomUUID()}function yl(e){return`${e.runtimeId}\0${e.actorSessionId}\0${e.transportRequestId}`}var bl={pending:1,retrying:2,"outcome-unknown":3,failed:4};function xl(e,t){let n=e.filter(e=>e.runtimeId===t);if(n.length===0)return{state:`idle`,count:0};let r=n.reduce((e,t)=>bl[t.status]>bl[e]?t.status:e,`pending`);return{state:r,count:n.filter(e=>e.status===r).length}}function Sl(e){let t=e.randomUUID??vl,n=e.now??(()=>new Date),r=e.maxRecords??nl,i=e.maxBytes??rl,a=e.maxReplayAgeMs??il;if(r<1||i<1||a<1)throw new al(`Forge relay control journal limits must be positive.`);let o=e.storage.read(),s=n(),c=o?_l(o):{version:1,controlSessionId:t(),nextSequence:1,records:[]},l=new Map,u=new Set;function d(){return{controlSessionId:c.controlSessionId,records:[...c.records]}}function f(t){if(t.records.length>r)throw new al(`Forge relay control journal reached its record limit.`);let n=JSON.stringify(t);if(new TextEncoder().encode(n).byteLength>i)throw new al(`Forge relay control journal reached its storage limit.`);e.storage.write(n),c=t;let a=d();for(let e of u)e(a)}function p(e,t){return e.status!==`pending`&&e.status!==`retrying`?e:e.persistence===`metadata-only`||e.frame===null?{...e,frame:null,status:`outcome-unknown`,errorCode:`RELAY_COMMAND_OUTCOME_UNKNOWN`,updatedAt:t.toISOString()}:t.getTime()-Date.parse(e.createdAt)>a?{...e,frame:null,status:`outcome-unknown`,errorCode:`RELAY_RECOVERY_EXPIRED`,updatedAt:t.toISOString()}:e}let m=c.records.map(e=>p(e,s)),h=m.some((e,t)=>e!==c.records[t]);(o===null||h)&&f({...c,records:m});function g(e){let t=yl(e);return{key:t,existing:c.records.find(e=>yl(e)===t)??null}}function ee(e,t,n){if([e.method===t.method,e.persistence===t.persistence,n===void 0||n===t.frame,e.frame===null||e.frame===t.frame,t.durableRequestId===void 0||e.durableRequestId===t.durableRequestId].includes(!1))throw new al(`Relay transport request ${t.transportRequestId} was reused with different content.`);if(e.status===`failed`||e.status===`outcome-unknown`)throw new al(`Relay transport request ${t.transportRequestId} requires an explicit outcome acknowledgement.`)}function _(e){if(e.durableRequestId!==void 0&&c.records.some(t=>t.durableRequestId===e.durableRequestId))throw new al(`Relay durable request ${e.durableRequestId} was reused by another transport request.`)}function v(e){let r=n().toISOString();return{runtimeId:e.runtimeId,actorSessionId:e.actorSessionId,transportRequestId:e.transportRequestId,durableRequestId:e.durableRequestId??t(),sequence:c.nextSequence,method:e.method,persistence:e.persistence,frame:e.persistence===`frame`?e.frame:null,status:`pending`,attemptCount:0,errorCode:null,createdAt:r,updatedAt:r}}function te(e){let{key:t,existing:n}=g(e);if(n!==null)return ee(n,e,l.get(t)),l.set(t,e.frame),n;_(e);let r=v(e);return l.set(t,e.frame),f({...c,nextSequence:c.nextSequence+1,records:[...c.records,r]}),r}function ne(e,t,n){let r=c.records.find(r=>r.runtimeId===e&&r.actorSessionId===t&&r.transportRequestId===n);if(!r)throw new al(`Relay transport request ${n} is not journaled.`);return r}function y(e,t,r,i){ne(e,t,r);let a=n().toISOString();l.delete(yl({runtimeId:e,actorSessionId:t,transportRequestId:r})),f({...c,records:c.records.map(n=>n.runtimeId===e&&n.actorSessionId===t&&n.transportRequestId===r?{...n,frame:null,status:`failed`,errorCode:i,updatedAt:a}:n)})}function b(e,t,r){let i=ne(e,t,r);if(i.status===`failed`||i.status===`outcome-unknown`)throw new al(`Relay transport request ${r} has no replayable outcome.`);let a={...i,status:i.attemptCount>0?`retrying`:`pending`,attemptCount:i.attemptCount+1,errorCode:null,updatedAt:n().toISOString()};return f({...c,records:c.records.map(n=>n.runtimeId===e&&n.actorSessionId===t&&n.transportRequestId===r?a:n)}),a}function x(e,t,n){let r=c.records.filter(r=>r.runtimeId!==e||r.actorSessionId!==t||r.transportRequestId!==n);r.length!==c.records.length&&(l.delete(yl({runtimeId:e,actorSessionId:t,transportRequestId:n})),f({...c,records:r}))}function S(e,t,n){let r=ne(e,t,n);if(r.status!==`failed`&&r.status!==`outcome-unknown`)throw new al(`Relay transport request ${n} does not have an acknowledgeable outcome.`);x(e,t,n)}function C(){let e=n(),t=c.records.map(t=>p(t,e));t.some((e,t)=>e!==c.records[t])&&f({...c,records:t})}function w(e,t){let r=n().toISOString(),i=c.records.map(n=>n.runtimeId!==e||n.actorSessionId===t||n.status!==`pending`&&n.status!==`retrying`?n:(l.delete(yl(n)),{...n,frame:null,status:`outcome-unknown`,errorCode:`RELAY_ACTOR_SESSION_CHANGED`,updatedAt:r}));i.some((e,t)=>e!==c.records[t])&&f({...c,records:i})}return{controlSessionId:c.controlSessionId,prepare:te,records:()=>[...c.records],pending:()=>[...c.records],replayable:(e,t)=>(C(),c.records.filter(n=>n.runtimeId===e&&n.actorSessionId===t&&n.persistence===`frame`&&n.frame!==null&&(n.status===`pending`||n.status===`retrying`))),fenceActor:w,beginAttempt:b,markFailed:y,complete:x,acknowledge:S,subscribe:e=>(u.add(e),e(d()),()=>u.delete(e))}}function Cl(e=null){let t=e;return{read:()=>t,write:e=>{t=e}}}var wl=Nt(nn),Tl=Bt(sn),El=Bt(Xt),Dl=[`rpc.read`,`rpc.mutate`,`cursor.resume`,`terminal.stream`,`browser.stream`,`bulk.transfer`,`envelope.validation`,`payload.e2e`];function Ol(e,t){if(!Array.isArray(e))return null;for(let n of e)if(Array.isArray(n)&&n.length===2&&n[0]===t&&typeof n[1]==`string`)return n[1];return null}function kl(e,t){let n=JSON.parse(e),r=ra(n);if(r!==null)return{messageType:`request`,...r};let i=Al(n,t);if(i!==null)return i;let a=jl(n);if(a!==null)return a;throw Error(`Forge relay protocol v2 requires a recognized Effect RPC frame.`)}function Al(e,t){if(e._tag!==`Request`||typeof e.id!=`string`||e.id.length===0||typeof e.tag!=`string`||e.tag.length===0)return null;let n=pa({method:e.tag,payload:e.payload,grantedScopes:t});return{messageType:`request`,requestId:e.id,correlationId:Ol(e.headers,ln.requestId)??e.id,method:e.tag,...n}}function jl(e){return e._tag!==`Ack`&&e._tag!==`Interrupt`||typeof e.requestId!=`string`||e.requestId.length===0?null:{messageType:`acknowledgement`,requestId:e.requestId,correlationId:e.requestId,method:`@effect/rpc/${e._tag}`,requiredScope:null,deliveryClass:`read`,journalPersistence:`none`}}function Ml(e,t){let n=new Event(`error`);return Object.defineProperties(n,{error:{value:Error(t),enumerable:!0},message:{value:`${e}: ${t}`,enumerable:!0}}),n}var Nl=new Set([`network`,`server`,`auth`,`permission`,`client`]),Pl=new Set([`network`,`server`]);function Fl(e){return e&&typeof e==`object`?e:{}}function Il(e){return typeof e.code==`string`&&e.code.length>0?e.code:typeof e.kind==`string`&&Nl.has(e.kind)?`RELAY_ACTION_GRANT_UNAVAILABLE`:`MALFORMED_FRAME`}function Ll(e){if(e.retryable===!0||typeof e.kind==`string`&&Pl.has(e.kind))return!0;let t=typeof e.status==`number`?e.status:null;return t===429||t!==null&&t>=500}function Rl(e){let t=Fl(e);return{code:Il(t),message:e instanceof Error?e.message:`Forge relay frame encoding failed.`,retryable:Ll(t)}}function zl(e,t){let n=new Event(e.type),r=e;for(let e of t)r[e]!==void 0&&Object.defineProperty(n,e,{value:r[e],enumerable:!0});return n}function Bl(e){return!Array.isArray(e)||e.length!==2||typeof e[0]!=`string`?!1:Object.values(ln).includes(e[0])}function Vl(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Hl(e){if(!Array.isArray(e))return null;for(let t of e){let e=Vl(t);if(e?._tag!==`Fail`)continue;let n=Vl(e.error)?.code;if(typeof n==`string`&&n.length>0)return n}return null}function Ul(e){let t=Vl(e.exit);return t===null?`RELAY_RPC_RESPONSE_INVALID`:t._tag===`Success`?null:t._tag!==`Failure`||!Array.isArray(t.cause)?`RELAY_RPC_RESPONSE_INVALID`:Hl(t.cause)??`RELAY_RPC_FAILED`}function Wl(e){if(typeof e!=`string`)return null;try{let t=wl(JSON.parse(e));return t._tag===`Some`?t.value:null}catch{return null}}function Gl(e,t){if(e.role===`control`&&e.protocolVersion===t&&e.protocolVersion>=1){if(e.protocolVersion===1)return null;if(e.actor!==void 0&&e.scopes!==void 0)return{runtimeId:e.runtimeId,connectionEpoch:e.connectionEpoch,protocolVersion:e.protocolVersion,actor:e.actor,scopes:e.scopes}}}function Kl(e,t,n){if(typeof e==`string`)try{let r=Vl(JSON.parse(e));if(r?._tag!==`Exit`||typeof r.requestId!=`string`)return;let i=Ul(r);if(i===null){n.complete(t.runtimeId,t.actor.sessionId,r.requestId);return}n.markFailed(t.runtimeId,t.actor.sessionId,r.requestId,i)}catch{}}function ql(e){let t=Ol(e,ln.sequence);if(t===null)return;let n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:void 0}function Jl(e){return{issuedAt:Ol(e,ln.issuedAt)??new Date().toISOString(),expiresAt:Ol(e,ln.expiresAt)??new Date(Date.now()+12e4).toISOString()}}function Yl(e){if(e!==2&&e!==3&&e!==4)throw new Y(`protocol_version_mismatch`,`Unsupported Forge relay envelope version: ${e}`,!1);return e}async function Xl(e){let t=fa({method:e.identity.method,payload:e.payload});if(t===null)return;let n=Zl(e.context);if(e.acquire===void 0)throw new Y(`action_grant_required`,`CMMD action-grant issuance is unavailable for this remote response.`,!1);return e.acquire({...n,method:`orchestration.dispatchCommand`,...t,durableRequestId:e.identity.correlationId,payloadHash:e.payloadHash,requiredScope:`approval.respond`})}function Zl(e){if(e.protocolVersion===3)return{protocolVersion:3};if(e.protocolVersion!==4)throw new Y(`protocol_update_required`,`Update Forge on the target runtime before responding remotely.`,!1);return{protocolVersion:4,channelId:Ql(e.channelId),channelTicketDigest:Ql(e.channelTicketDigest),runtimeEndpointKeyId:Ql(e.runtimeEndpointKeyId),controlEndpointKeyId:Ql(e.controlEndpointKeyId)}}function Ql(e){if(typeof e==`string`&&e.length>0)return e;throw new Y(`channel_ticket_binding_invalid`,`The encrypted Forge relay channel is missing its CMMD ticket binding.`,!1)}function $l(e){return e===void 0?{}:{sequence:e}}function eu(e){return e===void 0?{}:{actionGrant:e}}async function tu(e){let t=kl(e.data,e.context.scopes),n=JSON.parse(e.data),r=Jl(n.headers),i=ql(n.headers),a=await e.crypto.sha256Base64Url(e.data),o=await Xl({context:e.context,identity:t,payload:n.payload,payloadHash:a,...e.acquireActionGrant===void 0?{}:{acquire:e.acquireActionGrant}}),s=Yl(e.context.protocolVersion),c={messageType:t.messageType,requestId:t.requestId,correlationId:t.correlationId,method:t.method,requiredScope:t.requiredScope,deliveryClass:t.deliveryClass,runtimeId:e.context.runtimeId,connectionEpoch:e.context.connectionEpoch,actor:e.context.actor,...r,payloadHash:a,...$l(i)};return s===2?{protocolVersion:2,...c}:s===3?{protocolVersion:3,...c,...eu(o)}:{protocolVersion:4,...c,...eu(o)}}function nu(e){return typeof e==`string`&&e.length>0}function ru(e){return[e.protocolVersion===4,nu(e.runtimeId),Number.isSafeInteger(e.connectionEpoch),Number(e.connectionEpoch)>0,e.hpkeSuite===fc,nu(e.channelId),nu(e.runtimeEndpointKeyId),nu(e.runtimeEndpointPublicKey),nu(e.controlEndpointKeyId),nu(e.controlEndpointPublicKey),nu(e.controlChannelNonce),e.controlEndpointKeyPair!==void 0].every(Boolean)}function iu(e){if(!ru(e))throw new Y(`end_to_end_encryption_required`,`Forge relay protocol v4 requires complete endpoint encryption metadata.`,!1);return e}async function au(e){if(await Kc(e.controlEndpointKeyPair.publicKey)!==e.controlEndpointPublicKey)throw new Y(`endpoint_key_invalid`,`The control endpoint private key does not match the CMMD route.`,!1);let t=await Jc(e.runtimeEndpointPublicKey),[n,r]=await Promise.all([Bc({exactCompactTicket:e.token,channelId:e.channelId,direction:`control-to-runtime`,runtimeId:e.runtimeId,connectionEpoch:e.connectionEpoch},e.payloadDigestProvider),Bc({exactCompactTicket:e.token,channelId:e.channelId,direction:`runtime-to-control`,runtimeId:e.runtimeId,connectionEpoch:e.connectionEpoch},e.payloadDigestProvider)]);return{controlToRuntimeBinding:n,runtimeToControlBinding:r,sender:await el({binding:n,senderKey:e.controlEndpointKeyPair,recipientPublicKey:t,...e.payloadRandomSource?{randomSource:e.payloadRandomSource}:{}}),runtimePublicKey:t,recipient:null,phase:`awaiting-runtime-hello`}}function ou(e,t,n){return[e.direction===`runtime-to-control`,e.frameClass===n,e.channelId===t.channelId].every(Boolean)}function su(e){return[e.confirmation.phase===e.expectedPhase,e.confirmation.channelId===e.route.channelId,e.confirmation.runtimeId===e.context.runtimeId,e.confirmation.connectionEpoch===e.context.connectionEpoch].every(Boolean)}function cu(e){let{envelope:t}=e.application;return[t.runtimeId===e.context.runtimeId,t.connectionEpoch===e.context.connectionEpoch,t.actor.userId===e.context.actor.userId,t.actor.deviceId===e.context.actor.deviceId,t.actor.sessionId===e.context.actor.sessionId,t.payloadHash===e.payloadHash].every(Boolean)}async function lu(e){if(e.channel.recipient!==null){if(e.message.encapsulatedKey!==void 0)throw new Y(`endpoint_key_invalid`,`The runtime attempted to replace its endpoint encapsulation.`,!1);return e.channel.recipient}if(e.message.sequence!==0||!e.message.encapsulatedKey)throw new Y(`channel_confirmation_failed`,`The runtime handshake omitted its endpoint encapsulation.`,!1);let t=await tl({binding:e.channel.runtimeToControlBinding,recipientKey:e.route.controlEndpointKeyPair,senderPublicKey:e.channel.runtimePublicKey,encapsulatedKey:e.message.encapsulatedKey});return e.channel.recipient=t,t}var uu=class extends EventTarget{socket;route;relayCrypto;journal;lifecycle;acquireActionGrant;CONNECTING=WebSocket.CONNECTING;OPEN=WebSocket.OPEN;CLOSING=WebSocket.CLOSING;CLOSED=WebSocket.CLOSED;binaryType=`blob`;onopen=null;onclose=null;onerror=null;onmessage=null;authenticated=!1;context=null;payloadChannel=null;sendChain=Promise.resolve();constructor(e,t,n,r,i={},a){super(),this.socket=e,this.route=t,this.relayCrypto=n,this.journal=r,this.lifecycle=i,this.acquireActionGrant=a,e.addEventListener(`open`,()=>void this.beginAuthentication()),e.addEventListener(`message`,e=>void this.handleMessageSafely(e)),e.addEventListener(`error`,e=>{let t=zl(e,[`error`,`message`]),n=typeof t.message==`string`?String(t.message):`Forge relay connection failed.`;this.lifecycle.onError?.({code:`RELAY_SOCKET_ERROR`,message:n}),this.emit(`error`,t)}),e.addEventListener(`close`,e=>{this.authenticated=!1,this.context=null,this.payloadChannel=null,this.lifecycle.onDisconnected?.({code:e.code,reason:e.reason}),this.emit(`close`,zl(e,[`code`,`reason`,`wasClean`]))})}get bufferedAmount(){return this.socket.bufferedAmount}get extensions(){return this.socket.extensions}get protocol(){return this.socket.protocol}get readyState(){return this.authenticated?this.socket.readyState:WebSocket.CONNECTING}get url(){return this.route.relayWebSocketUrl}send(e){if(!this.authenticated||typeof e!=`string`)throw new DOMException(`Forge relay RPC socket is not open for text frames.`,`InvalidStateError`);if(this.route.protocolVersion===1){this.socket.send(JSON.stringify({type:`relay.frame`,payload:e}));return}let t=this.context;if(t===null)throw new DOMException(`Forge relay v2 context is unavailable.`,`InvalidStateError`);let n=kl(e,t.scopes),r=n.messageType===`request`&&n.journalPersistence!==`none`?this.journal.prepare({runtimeId:t.runtimeId,actorSessionId:t.actor.sessionId,transportRequestId:n.requestId,...n.correlationId===n.requestId?{}:{durableRequestId:n.correlationId},method:n.method,frame:e,persistence:n.journalPersistence}):null;this.enqueueFrame(e,r)}enqueueFrame(e,t){this.sendChain=this.sendChain.then(()=>this.transmitFrame(e,t)).catch(e=>{let n=Rl(e);t!==null&&!n.retryable&&this.journal.markFailed(t.runtimeId,t.actorSessionId,t.transportRequestId,n.code),this.lifecycle.onError?.({code:n.code,message:n.message}),this.emit(`error`,Ml(n.code,n.message)),this.socket.readyState<WebSocket.CLOSING&&this.socket.close(4400,`${n.code}: ${n.message}`)})}async transmitFrame(e,t){let n=this.requireReadyContext(),r=await this.outboundFrame(e,t),i=await tu({data:r,context:n,crypto:this.relayCrypto,...this.acquireActionGrant?{acquireActionGrant:this.acquireActionGrant}:{}});if(n.protocolVersion===4){let e=await this.requirePayloadChannel().sender.seal({frameClass:`application`,plaintext:new TextEncoder().encode(JSON.stringify({payload:r,envelope:i}))});this.socket.send(JSON.stringify(e));return}this.socket.send(JSON.stringify({type:`relay.frame`,payload:r,envelope:i}))}requireReadyContext(){if(!this.authenticated||this.socket.readyState!==WebSocket.OPEN)throw new DOMException(`Forge relay RPC socket closed before send.`,`InvalidStateError`);if(this.context===null)throw new DOMException(`Forge relay v2 context is unavailable.`,`InvalidStateError`);return this.context}requirePayloadChannel(){let e=this.payloadChannel;if(e===null||e.phase!==`ready`)throw new Y(`channel_confirmation_failed`,`The Forge relay endpoint channel is not confirmed.`,!1);return e}async outboundFrame(e,t){return t===null?e:this.withDurableHeaders(t,e)}async withDurableHeaders(e,t){let n=this.journal.beginAttempt(e.runtimeId,e.actorSessionId,e.transportRequestId),r=JSON.parse(t),i=await Su({payload:xu(e.method,r.payload),sequence:n.sequence,requestId:n.durableRequestId,issuedAt:new Date(n.updatedAt),crypto:this.relayCrypto}),a=Array.isArray(r.headers)?r.headers.filter(e=>!Bl(e)):[];return JSON.stringify({...r,headers:[...a,...Object.entries(i)]})}close(e,t){this.socket.close(e,t)}asWebSocket(){return this}emit(e,t){this.dispatchEvent(t);let n=this[`on${e}`];n&&n.call(this.asWebSocket(),t)}async handleMessage(e){if(this.authenticated){if(this.context?.protocolVersion===4){await this.handleEncryptedApplicationMessage(e.data);return}this.context!==null&&Kl(e.data,this.context,this.journal),this.emit(`message`,new MessageEvent(`message`,{data:e.data}));return}await this.handleAuthenticationMessage(e.data)}async handleMessageSafely(e){try{await this.handleMessage(e)}catch(e){let t=Rl(e);this.lifecycle.onError?.({code:t.code,message:t.message}),this.emit(`error`,Ml(t.code,t.message)),this.socket.readyState<WebSocket.CLOSING&&this.socket.close(4400,`${t.code}: ${t.message}`)}}async beginAuthentication(){try{this.route.protocolVersion===4&&(this.payloadChannel=await au(iu(this.route))),this.socket.send(JSON.stringify({type:`relay.auth`,ticket:this.route.token,protocolMinVersion:this.route.protocolVersion,protocolMaxVersion:this.route.protocolVersion,capabilities:Dl,...this.payloadChannel?{controlToRuntimeEncapsulatedKey:this.payloadChannel.sender.encapsulatedKey}:{}}))}catch(e){let t=Rl(e);this.lifecycle.onError?.({code:t.code,message:t.message}),this.emit(`error`,Ml(t.code,t.message)),this.socket.close(4400,t.message)}}async handleAuthenticationMessage(e){let t=Wl(e);if(t!==null){if(t.type===`relay.encrypted-frame`&&this.context?.protocolVersion===4){await this.handleEncryptedHandshakeMessage(t);return}if(t.type===`relay.error`){this.lifecycle.onError?.({code:t.code,message:t.message}),this.emit(`error`,Ml(t.code,t.message)),this.socket.close(4403,t.message);return}t.type===`relay.authenticated`&&await this.handleAuthenticatedMessage(t)}}async handleAuthenticatedMessage(e){let t=Gl(e,this.route.protocolVersion);if(t===void 0){this.socket.close(4400,`Forge relay authenticated the wrong role.`);return}if(t!==null&&t.protocolVersion===4){let n=iu(this.route),r=this.payloadChannel;if(r===null||![e.runtimeId===n.runtimeId,e.connectionEpoch===n.connectionEpoch].every(Boolean)){this.socket.close(4400,`Forge relay authenticated stale endpoint metadata.`);return}t={...t,channelId:n.channelId,channelTicketDigest:Vc(r.controlToRuntimeBinding),runtimeEndpointKeyId:n.runtimeEndpointKeyId,controlEndpointKeyId:n.controlEndpointKeyId},this.context=t;return}await this.activateAuthenticatedRelay(t)}async handleEncryptedHandshakeMessage(e){if(e.type!==`relay.encrypted-frame`)return;let t=this.payloadChannel,n=this.context,r=iu(this.route);if(t===null||n===null||!ou(e,r,`handshake`))throw new Y(`channel_confirmation_failed`,`The runtime sent an invalid encrypted handshake frame.`,!1);let i=await(await lu({channel:t,route:r,message:e})).open(e),a=Tl(JSON.parse(new TextDecoder().decode(i))),o=t.phase===`awaiting-runtime-hello`?`runtime-hello`:`runtime-confirm`;if(!su({confirmation:a,expectedPhase:o,route:r,context:n}))throw new Y(`channel_confirmation_failed`,`The runtime endpoint confirmation does not match the CMMD route.`,!1);if(o===`runtime-hello`){let e=await t.sender.seal({frameClass:`handshake`,plaintext:new TextEncoder().encode(JSON.stringify({type:`relay.endpoint-confirmation`,protocolVersion:4,phase:`control-confirm`,channelId:r.channelId,runtimeId:n.runtimeId,connectionEpoch:n.connectionEpoch}))});t.phase=`awaiting-runtime-confirm`,this.socket.send(JSON.stringify(e));return}t.phase=`ready`,await this.activateAuthenticatedRelay(n)}async handleEncryptedApplicationMessage(e){let t=Wl(e);if(t?.type!==`relay.encrypted-frame`)throw new Y(`end_to_end_encryption_required`,`The runtime sent plaintext after the encrypted channel was confirmed.`,!1);let n=this.requirePayloadChannel();if(!ou(t,iu(this.route),`application`)||t.encapsulatedKey!==void 0||n.recipient===null)throw new Y(`channel_authentication_failed`,`The runtime sent an invalid encrypted application frame.`,!1);let r=await n.recipient.open(t),i=El(JSON.parse(new TextDecoder().decode(r))),a=this.requireReadyContext();if(!cu({application:i,context:a,payloadHash:await this.relayCrypto.sha256Base64Url(i.payload)}))throw new Y(`channel_authentication_failed`,`The decrypted runtime envelope does not match the active route.`,!1);Kl(i.payload,a,this.journal),this.emit(`message`,new MessageEvent(`message`,{data:i.payload}))}async activateAuthenticatedRelay(e){this.context=e,this.authenticated=!0,this.lifecycle.onAuthenticated?.();let t=e===null?[]:this.replayForActor(e);for(let e of t)e.frame!==null&&this.enqueueFrame(e.frame,e);t.length>0&&await this.sendChain,this.emit(`open`,new Event(`open`))}replayForActor(e){return this.journal.fenceActor(e.runtimeId,e.actor.sessionId),this.journal.replayable(e.runtimeId,e.actor.sessionId)}};function du(e,t,n=mu,r=Sl({storage:Cl(),randomUUID:n.randomUUID}),i={},a){return new uu(e,t,n,r,i,a).asWebSocket()}var fu=Vi(on);async function pu(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return btoa(String.fromCharCode(...new Uint8Array(n))).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replaceAll(`=`,``)}var mu={randomUUID:()=>crypto.randomUUID(),sha256Base64Url:pu},hu=`forge-relay-binding=`,gu=3e4;function _u(e){let t=new URL(String(e)).hash.slice(1);if(!t.startsWith(hu))throw Error(`Forge relay socket URL is missing its route binding.`);let n=decodeURIComponent(t.slice(20));if(n.length===0)throw Error(`Forge relay socket URL has an invalid route binding.`);return n}function vu(e){let t=e.crypto??mu,n=e.bindingTtlMs??gu,r=e.createSocket??((e,t)=>new globalThis.WebSocket(e,t)),i=new Map;return{acquireSocketUrl:async()=>{let r=await e.acquireRoute(),a=t.randomUUID();if(i.has(a))throw Error(`Forge relay route binding identifier was reused.`);let o=new URL(r.relayWebSocketUrl);o.hash=`${hu}${encodeURIComponent(a)}`;let s=setTimeout(()=>i.delete(a),n);return i.set(a,{route:r,expires:s}),o.toString()},constructSocket:(n,a)=>{let o=_u(n),s=i.get(o);if(s===void 0)throw Error(`Forge relay route binding is missing, expired, or already consumed.`);return i.delete(o),clearTimeout(s.expires),e.lifecycle?.onConnecting?.(),du(r(s.route.relayWebSocketUrl,a),s.route,t,e.journal,e.lifecycle,e.acquireActionGrant)}}}var yu=new Map;function bu(e){let t=yu.get(e);if(t!==void 0)return t;let n=on.requests.get(e);if(n===void 0)return null;let r=Bt(n.payloadSchema);return yu.set(e,r),r}function xu(e,t){let n=bu(e);if(n===null)return t;try{return n(t)}catch{return t}}async function Su(e){let t=e.issuedAt??new Date,n=e.crypto??mu;return{[ln.requestId]:e.requestId??n.randomUUID(),[ln.sequence]:String(e.sequence),[ln.issuedAt]:t.toISOString(),[ln.expiresAt]:new Date(t.getTime()+12e4).toISOString(),[ln.payloadHash]:await n.sha256Base64Url(ta(e.payload))}}function Cu(e,t){return Gt(Yt,({rpc:t,request:n,next:r})=>Be(function*(){return pa({method:t._tag,payload:n.payload,grantedScopes:e}),yield*r(n)}))}function wu(e,t=mu){return fu.pipe(D(Cu(e,t)))}function Tu(e){let t=e.crypto??mu,n=vu({acquireRoute:e.acquireRoute,...e.acquireActionGrant?{acquireActionGrant:e.acquireActionGrant}:{},crypto:t,journal:e.journal,...e.lifecycle?{lifecycle:e.lifecycle}:{}}),i=Ye(n.acquireSocketUrl).pipe(r),a=C(Yn,n.constructSocket),o=Qn(i).pipe(h(a)),s=e.delayForRetry??$i,c=bt(u(e.maxRetries??10),e=>Ie(pe(s(e)??0)));return Je(Gi,Ki({retryPolicy:c,retryTransientErrors:!0})).pipe(h(F(o,Ii)))}var Eu=class extends Error{name=`RelayControlRouteSecurityFailure`};async function Du(e){let t=await Gc(e),n=await Kc(t.publicKey);return{keyPair:t,publicKey:n,keyId:qc(`control`,n),channelNonce:await Hc(e)}}function Ou(e){return{hpkeSuite:fc,controlEndpointKeyId:e.keyId,controlEndpointPublicKey:e.publicKey,controlChannelNonce:e.channelNonce}}function ku(e){let t=e.route;if(t.protocolVersion!==4||t.hpkeSuite!==`DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/CHACHA20_POLY1305/AUTH`||!t.channelId||!t.runtimeEndpointKeyId||!t.runtimeEndpointPublicKey||t.controlEndpointKeyId!==e.endpoint.keyId||t.controlEndpointPublicKey!==e.endpoint.publicKey||t.controlChannelNonce!==e.endpoint.channelNonce)throw new Eu(`Forge could not establish a verified end-to-end encrypted runtime route.`);return{...t,runtimeId:e.runtimeId,protocolVersion:4,channelId:t.channelId,hpkeSuite:fc,runtimeEndpointKeyId:t.runtimeEndpointKeyId,runtimeEndpointPublicKey:t.runtimeEndpointPublicKey,controlEndpointKeyId:e.endpoint.keyId,controlEndpointPublicKey:e.endpoint.publicKey,controlChannelNonce:e.endpoint.channelNonce,controlEndpointKeyPair:e.endpoint.keyPair,...e.digestProvider?{payloadDigestProvider:e.digestProvider}:{},...e.randomSource?{payloadRandomSource:e.randomSource}:{}}}function Au(e,t=pn){return`${e}\0${t}`}function ju(e){let t=new Map,n=!1;return{register(e){if(n)throw Error(`Terminal control sequencer is disposed.`);let r=Au(e.threadId,e.terminalId);t.get(r)?.sessionEpoch!==e.sessionEpoch&&t.set(r,{sessionEpoch:e.sessionEpoch,nextControlSequence:1,tail:Promise.resolve(),pendingWriteBytes:0})},enqueue(r){if(n)return Promise.reject(Error(`Terminal control sequencer is disposed.`));let i=r.terminalId??`default`,a=t.get(Au(r.threadId,i));if(!a)return Promise.reject(Error(`Terminal must be opened before sending controls.`));let o=r.writeBytes??0;if(a.pendingWriteBytes+o>e.maxPendingWriteBytes)return Promise.reject(Error(`Terminal input queue is full while reconnecting.`));a.pendingWriteBytes+=o;let s=a.tail.then(async()=>{let t=a.nextControlSequence;await r.execute({sessionEpoch:a.sessionEpoch,controllerId:e.controllerId,controlSequence:t}),a.nextControlSequence=t+1});return a.tail=s.finally(()=>{a.pendingWriteBytes-=o}).catch(()=>void 0),s},remove(e,n){if(n){t.delete(Au(e,n));return}let r=`${e}\0`;for(let e of t.keys())e.startsWith(r)&&t.delete(e)},terminalIds(e){let n=`${e}\0`;return[...t.keys()].filter(e=>e.startsWith(n)).map(e=>e.slice(n.length))},dispose(){n=!0,t.clear()}}}Bt(Qt);var Mu=[3e3,4e3,8e3,16e3],Nu=3e4;function Pu(e={}){let t=e.retryDelaysMs??Mu;if(t.length===0)throw Error(`retryDelaysMs must not be empty`);let n=e.maxRetries??null,r=e.backoffResetAfterMs??3e4,i=e.now??(()=>Date.now()),a={desired:!1,network:`online`,phase:`available`,attempt:0,generation:0,lastFailure:null,retryAtMs:null,retriesExhausted:!1,credentialsEpoch:0},o=new Set,s=null,c=0,l=e=>{a=e;for(let e of o)e(a);return a},u=()=>l({...a,phase:`connecting`,attempt:c+1,retryAtMs:null,credentialsEpoch:a.credentialsEpoch+1}),d=()=>t[Math.min(Math.max(c-1,0),t.length-1)]??0;return{getState:()=>a,connect:()=>a.desired?a:a.phase===`available`?l({...a,desired:!0,phase:`connecting`}):l({...a,desired:!0}),disconnect:()=>!a.desired&&a.phase===`available`?a:(c=0,s=null,l({...a,desired:!1,phase:`available`,attempt:0,lastFailure:null,retryAtMs:null,retriesExhausted:!1})),retryNow:()=>!a.desired&&a.phase===`available`?a:(c=0,l({...a,retryAtMs:null,retriesExhausted:!1})),setNetwork:e=>a.network===e?a:e===`offline`?(s=null,l({...a,network:e,phase:a.desired?`offline`:`available`,retryAtMs:null})):a.desired&&a.phase===`offline`?l({...a,network:e,phase:`connecting`}):l({...a,network:e}),attemptStarted:()=>u(),attemptConnected:()=>(s=i(),l({...a,phase:`connected`,generation:a.generation+1,lastFailure:null,retryAtMs:null,retriesExhausted:!1})),attemptFailed:e=>{let t=s===null?0:i()-s;s=null,t>=r&&(c=0);let o={...a,lastFailure:e};return e.kind===`blocked`?l({...o,phase:`blocked`,retryAtMs:null}):a.network===`offline`?l({...o,phase:`offline`,retryAtMs:null}):(c+=1,l(n!==null&&c>n?{...o,phase:`backoff`,retryAtMs:null,retriesExhausted:!0}:{...o,phase:`backoff`,retryAtMs:i()+d(),retriesExhausted:!1}))},subscribe:e=>(o.add(e),()=>o.delete(e))}}function Fu(e={}){let t=e.now??(()=>Date.now()),n={status:`ok`,detectedAtMs:null,source:null,reAuthInFlight:!1},r=new Set,i=e=>{n=e;for(let e of r)e(n);return n};return{getState:()=>n,reportAuthFailure:e=>n.status===`expired`?n:i({status:`expired`,detectedAtMs:t(),source:e,reAuthInFlight:n.reAuthInFlight}),clearAuthFailure:()=>i({status:`ok`,detectedAtMs:null,source:null,reAuthInFlight:n.reAuthInFlight}),beginReAuth:()=>!n.reAuthInFlight&&(i({...n,reAuthInFlight:!0}),!0),endReAuth:()=>{n.reAuthInFlight&&i({...n,reAuthInFlight:!1})},subscribe:e=>(r.add(e),()=>r.delete(e))}}function Iu(e){return!e.isWebSurface||e.failureStatus!==`expired`?{kind:`none`}:e.isAuthExemptPath?{kind:`clear-failure`}:{kind:`navigate-login`}}var Lu=new Set([`localhost`,`127.0.0.1`,`::1`]);function Ru(e){return e.trim().toLowerCase().replace(/^\[(.*)\]$/,`$1`)}function zu(e){let t=Ru(e);return Lu.has(t)||t.endsWith(`.localhost`)}function Bu(e){try{return zu(new URL(e).hostname)}catch{return!1}}function Vu(e){let t=e.split(`.`).map(e=>Number(e));if(t.length!==4||t.some(e=>!Number.isInteger(e)||e<0||e>255))return!1;let[n,r]=t;return n===10||n===172&&r>=16&&r<=31||n===192&&r===168}var Hu=`/api/dev/local-web/bootstrap`,Uu=3e3,Wu=null,Gu=null,Ku=null;function qu(){return Ku!==null&&Date.now()-Ku<Uu}function Ju(e){try{return Bt(Mt)(e)}catch{return null}}function Yu(){return!1}function Xu(){return typeof window>`u`?null:window.desktopBridge?.getLocalEnvironmentBootstrap()??Wu}async function Zu(){if(!Yu()||window.desktopBridge)return Wu=null,Xu();let e;try{e=await fetch(new URL(Hu,window.location.origin),{credentials:`include`})}catch{return Wu=null,Ku=Date.now(),null}if(e.status===204||e.status===404||!e.ok)return Wu=null,Ku=Date.now(),null;let t=Ju(await e.json().catch(()=>null));return Wu=t,Ku=null,t}async function Qu(){let e=typeof window>`u`?null:window.desktopBridge?.getLocalEnvironmentBootstrap();return e?(Wu=null,e):Wu||(qu()?null:Gu||(Gu=Zu().finally(()=>{Gu=null}),Gu))}function $u(){return Xu()}var ed=`forge_backend_mode`,td=`forge_apex_url`;function nd(){return $u()}function rd(e){return new URL(e,window.location.origin).toString()}function id(e,t){let n=new URL(e);return`${n.pathname.endsWith(`/`)?n.pathname.slice(0,-1):n.pathname}${t.startsWith(`/`)?t:`/${t}`}`}function ad(e){let t;try{t=new URL(window.location.href)}catch{return e}let n=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&t.port!==``&&n.port!==``&&t.origin!==n.origin&&zu(t.hostname)&&zu(n.hostname),e}function od(){return null}function sd(){let e=rd(window.location.origin),t=new URL(e);if(t.protocol===`http:`)t.protocol=`ws:`;else if(t.protocol===`https:`)t.protocol=`wss:`;else throw Error(`Unsupported HTTP base URL protocol: ${t.protocol}`);return t.pathname=`/ws`,{source:`window-origin`,target:{httpBaseUrl:e,wsBaseUrl:t.toString()}}}function cd(){try{if(localStorage.getItem(ed)!==`apex`)return null;let e=localStorage.getItem(td)?.trim()??void 0??``;if(!e)return null;let t=rd(e),n=new URL(t);return n.protocol=t.startsWith(`https:`)?`wss:`:`ws:`,{source:`configured`,target:{httpBaseUrl:t,wsBaseUrl:n.toString()}}}catch{return null}}function ld(){let e=nd();return!e||e.primaryMode!==`cloud`||!e.bearerToken?null:{source:`paired-bearer`,target:{httpBaseUrl:rd(e.httpBaseUrl),wsBaseUrl:rd(e.wsBaseUrl)},bearerToken:e.bearerToken}}function ud(){let e=nd();if(!e||e.primaryMode===`cloud`||!e.httpBaseUrl&&!e.wsBaseUrl)return null;if(!e.httpBaseUrl||!e.wsBaseUrl)throw Error(`Desktop bootstrap must provide both httpBaseUrl and wsBaseUrl for the local environment.`);return{source:`desktop-managed`,target:{httpBaseUrl:rd(e.httpBaseUrl),wsBaseUrl:rd(e.wsBaseUrl)},...e.bearerToken?{bearerToken:e.bearerToken}:{}}}function dd(e,t){let n=fd();if(!n)throw Error(`Unable to resolve the primary environment HTTP base URL.`);let r=new URL(ad(n.target.httpBaseUrl));return r.pathname=id(r.toString(),e),t&&(r.search=new URLSearchParams(t).toString()),r.toString()}function fd(){return ld()??cd()??ud()??od()??sd()}function pd(e={}){let t=fd(),n=t?.bearerToken;return!t||!n||!md(t)?e:{...e,credentials:`omit`,headers:{...e.headers,Authorization:`Bearer ${n}`}}}function md(e){if(e.source!==`desktop-managed`||typeof window>`u`)return!0;try{return new URL(ad(e.target.httpBaseUrl)).origin!==window.location.origin}catch{return!0}}async function hd(e,t){return await e.text()||t}async function gd(){let e=dd(`/api/auth/logout`),t=await fetch(e,pd({credentials:`include`,method:`POST`}));if(!t.ok)throw Error(await hd(t,`Failed to logout authenticated session (${t.status}).`))}var _d=10,vd=_d+1,yd=Object.freeze({attemptCount:0,closeCode:null,closeReason:null,connectedAt:null,disconnectedAt:null,hasConnected:!1,lastError:null,lastErrorAt:null,nextRetryAt:null,online:typeof navigator>`u`||navigator.onLine!==!1,phase:`idle`,reconnectAttemptCount:0,reconnectMaxAttempts:vd,reconnectPhase:`idle`,socketUrl:null}),bd=jt(yd).pipe(kt,Dt(`ws-connection-status`)),xd=Array.from({length:_d},(e,t)=>$i(t)??0);function Sd(){return{connection:Pu({retryDelaysMs:xd,maxRetries:_d,backoffResetAfterMs:Nu}),cloudAuth:Fu()}}var Cd=Sd(),wd=Object.freeze({status:`ok`}),Td=jt(wd).pipe(kt,Dt(`cloud-auth-failure`));function Ed(e){let t=Cd.cloudAuth.reportAuthFailure(e);Ot.set(Td,Od(t))}function Dd(){Cd.cloudAuth.clearAuthFailure(),Ot.set(Td,wd)}function Od(e){return e.status!==`expired`||e.detectedAtMs===null?wd:{status:`expired`,detectedAt:new Date(e.detectedAtMs).toISOString(),source:e.source??`http`}}function kd(){return Ot.get(Td)}function Ad(){return Cd.cloudAuth.beginReAuth()}function jd(){Cd.cloudAuth.endReAuth()}function Md(){return new Date().toISOString()}function Nd(e){let t=e(Pd());return Ot.set(bd,t),t}function Pd(){return Ot.get(bd)}function Fd(e){return e.phase===`connected`||e.hasConnected&&e.disconnectedAt===null&&e.phase===`connecting`?`connected`:!e.online&&(e.disconnectedAt!==null||e.phase===`disconnected`)?`offline`:e.hasConnected?`reconnecting`:e.phase===`disconnected`?`error`:`connecting`}var Id=!1;function Ld(e){Cd.connection.getState().desired||Cd.connection.connect(),Id=!1;let t=Cd.connection.attemptStarted();return Nd(n=>({...n,attemptCount:n.attemptCount+1,nextRetryAt:null,phase:`connecting`,reconnectAttemptCount:t.attempt,reconnectPhase:`attempting`,socketUrl:e}))}function Rd(){return Id=!1,Cd.connection.attemptConnected(),Nd(e=>({...e,closeCode:null,closeReason:null,connectedAt:Md(),disconnectedAt:null,hasConnected:!0,nextRetryAt:null,phase:`connected`,reconnectAttemptCount:0,reconnectPhase:`idle`}))}function zd(e){return Id||(Id=!0,Cd.connection.attemptFailed({kind:`transient`,message:e?.trim()?e:`Unable to connect to the Forge server WebSocket.`})),Nd(t=>Kd(t,{lastError:e?.trim()?e:t.lastError,lastErrorAt:Md()}))}function Bd(e){return Pd().hasConnected&&Vd(e)?Pd():(Id||(Id=!0,Cd.connection.attemptFailed({kind:`transient`,message:e?.reason?.trim()||`WebSocket connection closed.`})),Nd(t=>Kd(t,{closeCode:e?.code??t.closeCode,closeReason:e?.reason?.trim()?e.reason:t.closeReason})))}function Vd(e){return(e?.reason?.trim()??``).length===0&&(e?.code===1e3||e?.code===1001)}function Hd(e){return Cd.connection.setNetwork(e?`online`:`offline`),Nd(t=>({...t,online:e}))}function Ud(){return Cd.connection.retryNow(),Nd(e=>({...e,nextRetryAt:null,reconnectAttemptCount:0,reconnectPhase:`idle`}))}function Wd(){return Sn(bd)}function Gd(e){return $i(e)}function Kd(e,t){let n=Cd.connection.getState(),r=e.disconnectedAt??Md();return{...e,...t,disconnectedAt:r,nextRetryAt:n.retryAtMs===null?null:new Date(n.retryAtMs).toISOString(),phase:`disconnected`,reconnectPhase:n.retriesExhausted?`exhausted`:`waiting`}}var qd=class extends Error{constructor(e=`Session has expired. Please re-login.`){super(e),this.name=`ForgeAuthExpiredError`}};function Jd(e){return e instanceof qd||e instanceof Error&&e.name===`ForgeAuthExpiredError`}var Yd=`forge_auth_expired_reason`,Xd=`session-expired`,Zd=`reason`,Qd=`cmmd-auth-expired`,$d={"session-expired":`Session has expired. Please re-login.`,"desktop-session-required":`Forge Desktop needs a CMMD sign-in before this device can host or control runtimes.`,"desktop-principal-mismatch":`Forge Desktop and the local Forge session are signed in to different CMMD accounts. Sign in again to reconcile them.`,"desktop-state-unavailable":`Forge Desktop could not verify its native CMMD session. Restart Forge or sign in again.`};function ef(e){if(!(e===null||!(e in $d)))return $d[e]}function tf(e){if(!(typeof window>`u`))try{window.sessionStorage.setItem(Yd,e)}catch{}}function nf(){if(typeof window>`u`)return null;try{return new URL(window.location.href).searchParams.getAll(Zd).includes(Qd)?Xd:null}catch{return null}}function rf(){if(!(typeof window>`u`))try{let e=new URL(window.location.href),t=e.searchParams.getAll(Zd);if(!t.includes(Qd))return;e.searchParams.delete(Zd);for(let n of t)n!==Qd&&e.searchParams.append(Zd,n);window.history.replaceState({},typeof document>`u`?``:document.title,e.toString())}catch{}}function af(){let e=nf();return e!==null&&rf(),e}function of(){if(!(typeof window>`u`)){try{window.sessionStorage.removeItem(Yd)}catch{}rf()}}function sf(){if(typeof window>`u`)return null;try{let e=window.sessionStorage.getItem(Yd);return rf(),e}catch{return rf(),null}}function cf(){if(typeof window>`u`)return null;try{let e=window.sessionStorage.getItem(Yd);return e===null?af():(window.sessionStorage.removeItem(Yd),rf(),e)}catch{return af()}}async function lf(){try{let e=dd(`/api/auth/session/renew`);return e.startsWith(`https://`)?(await fetch(e,{credentials:`include`,method:`POST`})).ok:!1}catch{return!1}}async function uf(){if(await lf()){Dd(),window.location.reload();return}await gd().catch(()=>void 0),Dd(),tf(`session-expired`);let e=new URL(dd(`/login`));window.location.assign(e.toString())}var df=e({handleCmmdAuthExpired:()=>pf}),ff=null;async function pf(e){if((e===void 0||e===401)&&!(typeof window>`u`)){if(ff)return ff;if(Ad())return ff=uf().finally(()=>{jd(),ff=null}),ff}}export{Qn as $,pd as A,Eu as B,zd as C,Ed as D,Hd as E,zu as F,wu as G,Ou as H,Bu as I,Gi as J,Sl as K,Vu as L,dd as M,$u as N,Wd as O,Qu as P,Yn as Q,Iu as R,Bd as S,Ud as T,ku as U,Du as V,Tu as W,Ki as X,Vi as Y,Ii as Z,kd as _,of as a,Gd as b,uf as c,tf as d,Cn as et,cf as f,Td as g,Dd as h,qd as i,fd as j,gd as k,lf as l,_d as m,pf as n,Jd as o,vd as p,xl as q,Yd as r,sf as s,df as t,Sn as tt,ef as u,Pd as v,Rd as w,Ld as x,Fd as y,ju as z};
|
|
3
|
+
//# sourceMappingURL=cmmdAuthRedirect-Bqx90tp9.js.map
|