@mongodb-js/compass-web 0.36.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/106.e50960c29b57a8b92ec5.mjs +2 -0
  2. package/dist/{20.f2c2353886886939e128.mjs.LICENSE.txt → 106.e50960c29b57a8b92ec5.mjs.LICENSE.txt} +6 -0
  3. package/dist/128.2ec06394c7c1718c925f.mjs +1 -0
  4. package/dist/14.ee5055b184ec8814d6f7.mjs +2 -0
  5. package/dist/{938.e127bbcdd0ce0eab8722.mjs.LICENSE.txt → 14.ee5055b184ec8814d6f7.mjs.LICENSE.txt} +5 -17
  6. package/dist/260.52fdf61d69ac2a2921dc.mjs +2 -0
  7. package/dist/260.52fdf61d69ac2a2921dc.mjs.LICENSE.txt +13 -0
  8. package/dist/302.34205d8fa79ef45d79b5.mjs +1 -0
  9. package/dist/318.ca5407b8a126de079455.mjs +2 -0
  10. package/dist/318.ca5407b8a126de079455.mjs.LICENSE.txt +34 -0
  11. package/dist/560.e85e11aa098b341006f3.mjs +23 -0
  12. package/dist/568.5af0b00ce345e98d8b78.mjs +1 -0
  13. package/dist/714.fde8d188a97cdddc2703.mjs +344 -0
  14. package/dist/717.e27dd37bf389fe1e1fe3.mjs +1 -0
  15. package/dist/810.c52538ab1ee7a0892ac8.mjs +2 -0
  16. package/dist/{832.a6fb147f7fd965a7f30c.mjs.LICENSE.txt → 810.c52538ab1ee7a0892ac8.mjs.LICENSE.txt} +0 -7
  17. package/dist/assets-manifest.json +13 -11
  18. package/dist/compass-web.d.ts +8 -291
  19. package/dist/compass-web.mjs +20 -48
  20. package/dist/index-0b9a48a6.e104f028edf21b1c2537.mjs +29 -0
  21. package/dist/index-bde52cb3.96252163ac8fa874fc4c.mjs +1 -0
  22. package/package.json +40 -40
  23. package/dist/149.abccc0e903c0f5ea7354.mjs +0 -372
  24. package/dist/20.f2c2353886886939e128.mjs +0 -2
  25. package/dist/207.d69541eff41412663f35.mjs +0 -2
  26. package/dist/207.d69541eff41412663f35.mjs.LICENSE.txt +0 -8
  27. package/dist/563.mjs +0 -1
  28. package/dist/566.513352a4be9e2a46530b.mjs +0 -23
  29. package/dist/68.f1ca0ed16b5fa27e2cf1.mjs +0 -1
  30. package/dist/69.mjs +0 -1
  31. package/dist/724.8aae14d079e334751961.mjs +0 -8
  32. package/dist/724.8aae14d079e334751961.mjs.LICENSE.txt +0 -5
  33. package/dist/737.mjs +0 -1
  34. package/dist/745.mjs +0 -1
  35. package/dist/832.a6fb147f7fd965a7f30c.mjs +0 -2
  36. package/dist/938.e127bbcdd0ce0eab8722.mjs +0 -2
  37. package/dist/965.3c1bdf715c3551cfe1ba.mjs +0 -1
  38. package/dist/995.c3bb8ac49cdffa0211da.mjs +0 -2
  39. package/dist/995.c3bb8ac49cdffa0211da.mjs.LICENSE.txt +0 -11
  40. package/dist/index-bde52cb3.a964d5743a224d2efb82.mjs +0 -1
  41. /package/dist/{566.513352a4be9e2a46530b.mjs.LICENSE.txt → 560.e85e11aa098b341006f3.mjs.LICENSE.txt} +0 -0
  42. /package/dist/{149.abccc0e903c0f5ea7354.mjs.LICENSE.txt → 714.fde8d188a97cdddc2703.mjs.LICENSE.txt} +0 -0
@@ -0,0 +1,29 @@
1
+ export const __webpack_esm_id__=923;export const __webpack_esm_ids__=[923];export const __webpack_esm_modules__={736:(e,t,n)=>{n.d(t,{dq:()=>De,Fi:()=>$e,HM:()=>Ee,gs:()=>Ne});var a=n(55712),r=n(96652),i=n.n(r),o=n(51295),s=n(26544);const{debug:l,mongoLogId:c,log:d}=(0,s.h)("COMPASS-INTERCOM");n(95039);var u=n(58886),p=n(56900),m=n(73190);n(34110).Buffer,n(65738),n(15088).process;const g=(0,s.h)("COMPASS-PREFERENCES");const h=e=>({savePreferences:async t=>e()?.savePreferences?.(t)??{},refreshPreferences:async()=>e()?.getPreferences?.()??{},getPreferences:()=>e()?.getPreferences?.()??{},getConfigurableUserPreferences:async()=>e()?.getConfigurableUserPreferences?.()??{},getPreferenceStates:async()=>e()?.getPreferenceStates()??{},onPreferenceValueChanged:(t,n)=>e()?.onPreferencesChanged?.((e=>{if(Object.keys(e).includes(t))return n(e[t])}))??(()=>{}),createSandbox:async()=>f(await(e()?.getPreferenceSandboxProperties())),getPreferencesUser(){const t=e();if(!t)throw new Error("Can not get user");return(0,I.sq)(t)}});async function f(e){const t=await u.p.CreateSandbox(e,g);return h((()=>t))}h((()=>{}));var y=n(75531);y.ipcRenderer&&(e=>{if(!e)throw new Error("IPC not available");let t,n={};async function a(){return t=e.invoke("compass:get-preferences"),n=await t,t=void 0,n}a(),e.on("compass:preferences-changed",(()=>{a().catch((()=>{}))}))})(y.ipcRenderer),n(21261),n(92879),n(31977),n(49743),n(9656),n(72673),n(35467),n(94476),n(64971),n(24330),n(83478),n(65166),n(1256),n(61038),n(73035),n(23855),n(78773),n(4308),n(13353),n(8006),n(85859);var b=n(90605),v=n(15088).process;const{log:x,mongoLogId:E}=(0,s.h)("COMPASS-PREFERENCES"),C=Object.entries(m.Mn).filter((([,e])=>e.cli));function w(e){return[...new Set(C.filter((([,t])=>t.type===e)).flatMap((([e])=>[e,(0,b.kebabCase)(e)])))]}w("string"),w("boolean"),w("number"),v.versions.electron&&v.defaultApp;var I=n(17565);p.z.object({id:p.z.string().uuid(),createdAt:p.z.union([p.z.coerce.date(),p.z.number()]).transform((e=>new Date(e))),lastUsed:p.z.union([p.z.coerce.date(),p.z.number()]).transform((e=>new Date(e)))}),n(15088).process;const{debug:S}=(0,s.h)("COMPASS-INTERCOM");var A=n(15088).process;const{debug:k}=(0,s.h)("COMPASS-INTERCOM"),D={submittedNlPrompt:"submitted-nl-prompt"},N=(0,o.AHW)({alignSelf:"center",path:{transition:"fill 0.16s ease-in"}}),M=(0,o.AHW)({path:{fill:o.MFm.green.dark1}}),T=(0,o.AHW)({path:{fill:o.MFm.green.dark2}}),P=({darkMode:e,size:t=16})=>i().createElement("svg",{width:t,height:t,viewBox:"0 0 16 16",fill:"none",className:(0,o.cx)(N,e?M:T),xmlns:"http://www.w3.org/2000/svg"},i().createElement("path",{d:"M6.27339 2.89343L5.27506 5.88842C5.17495 6.18877 4.93927 6.42445 4.63892 6.52456L1.64393 7.52289C1.18542 7.67573 1.18542 8.32427 1.64393 8.47711L4.63892 9.47544C4.93927 9.57555 5.17495 9.81123 5.27506 10.1116L6.27339 13.1066C6.42623 13.5651 7.07477 13.5651 7.22761 13.1066L8.22594 10.1116C8.32605 9.81123 8.56173 9.57555 8.86208 9.47544L11.8571 8.47711C12.3156 8.32427 12.3156 7.67573 11.8571 7.52289L8.86208 6.52456C8.56173 6.42445 8.32605 6.18877 8.22594 5.88842L7.22761 2.89343C7.07477 2.43492 6.42623 2.43492 6.27339 2.89343Z",fill:"#00684A"}),i().createElement("path",{d:"M12.5469 1.17194L12.3159 1.8651C12.2158 2.16545 11.9801 2.40113 11.6797 2.50125L10.9866 2.7323C10.7573 2.80872 10.7573 3.13299 10.9866 3.20941L11.6797 3.44046C11.9801 3.54058 12.2158 3.77626 12.3159 4.0766L12.5469 4.76977C12.6233 4.99902 12.9476 4.99902 13.024 4.76977L13.2551 4.0766C13.3552 3.77626 13.5909 3.54058 13.8912 3.44046L14.5844 3.20941C14.8136 3.13299 14.8136 2.80872 14.5844 2.7323L13.8912 2.50125C13.5909 2.40113 13.3552 2.16545 13.2551 1.8651L13.024 1.17194C12.9476 0.942687 12.6233 0.942687 12.5469 1.17194Z",fill:"#00684A"}),i().createElement("path",{d:"M12.5469 11.2302L12.3159 11.9234C12.2158 12.2237 11.9801 12.4594 11.6797 12.5595L10.9866 12.7906C10.7573 12.867 10.7573 13.1913 10.9866 13.2677L11.6797 13.4988C11.9801 13.5989 12.2158 13.8346 12.3159 14.1349L12.5469 14.8281C12.6233 15.0573 12.9476 15.0573 13.024 14.8281L13.2551 14.1349C13.3552 13.8346 13.5909 13.5989 13.8912 13.4988L14.5844 13.2677C14.8136 13.1913 14.8136 12.867 14.5844 12.7906L13.8912 12.5595C13.5909 12.4594 13.3552 12.2237 13.2551 11.9234L13.024 11.2302C12.9476 11.001 12.6233 11.001 12.5469 11.2302Z",fill:"#00684A"})),L=()=>'<svg\n width="16"\n height="16"\n viewBox="0 0 16 16"\n fill="none"\n xmlns="http://www.w3.org/2000/svg"\n>\n <path d="M6.27339 2.89343L5.27506 5.88842C5.17495 6.18877 4.93927 6.42445 4.63892 6.52456L1.64393 7.52289C1.18542 7.67573 1.18542 8.32427 1.64393 8.47711L4.63892 9.47544C4.93927 9.57555 5.17495 9.81123 5.27506 10.1116L6.27339 13.1066C6.42623 13.5651 7.07477 13.5651 7.22761 13.1066L8.22594 10.1116C8.32605 9.81123 8.56173 9.57555 8.86208 9.47544L11.8571 8.47711C12.3156 8.32427 12.3156 7.67573 11.8571 7.52289L8.86208 6.52456C8.56173 6.42445 8.32605 6.18877 8.22594 5.88842L7.22761 2.89343C7.07477 2.43492 6.42623 2.43492 6.27339 2.89343Z" fill="#00684A"/>\n <path d="M12.5469 1.17194L12.3159 1.8651C12.2158 2.16545 11.9801 2.40113 11.6797 2.50125L10.9866 2.7323C10.7573 2.80872 10.7573 3.13299 10.9866 3.20941L11.6797 3.44046C11.9801 3.54058 12.2158 3.77626 12.3159 4.0766L12.5469 4.76977C12.6233 4.99902 12.9476 4.99902 13.024 4.76977L13.2551 4.0766C13.3552 3.77626 13.5909 3.54058 13.8912 3.44046L14.5844 3.20941C14.8136 3.13299 14.8136 2.80872 14.5844 2.7323L13.8912 2.50125C13.5909 2.40113 13.3552 2.16545 13.2551 1.8651L13.024 1.17194C12.9476 0.942687 12.6233 0.942687 12.5469 1.17194Z" fill="#00684A"/>\n <path d="M12.5469 11.2302L12.3159 11.9234C12.2158 12.2237 11.9801 12.4594 11.6797 12.5595L10.9866 12.7906C10.7573 12.867 10.7573 13.1913 10.9866 13.2677L11.6797 13.4988C11.9801 13.5989 12.2158 13.8346 12.3159 14.1349L12.5469 14.8281C12.6233 15.0573 12.9476 15.0573 13.024 14.8281L13.2551 14.1349C13.3552 13.8346 13.5909 13.5989 13.8912 13.4988L14.5844 13.2677C14.8136 13.1913 14.8136 12.867 14.5844 12.7906L13.8912 12.5595C13.5909 12.4594 13.3552 12.2237 13.2551 11.9234L13.024 11.2302C12.9476 11.001 12.6233 11.001 12.5469 11.2302Z" fill="#00684A"/>\n</svg>\n',O=(0,o.AHW)({flexShrink:0,display:"flex",gap:o.YKD[200]}),R=2e3,H=(0,o.i7C)({"0%":{width:o.YKD[7]},"90%":{width:o.YKD[7]},"100%":{width:0}}),F=(0,o.AHW)({overflow:"hidden",animation:`${H} ${R}ms ease-in`,width:0,display:"flex",alignItems:"center",justifyContent:"space-around"}),W=(0,o.AHW)({color:o.MFm.green.light1}),j=(0,o.AHW)({color:o.MFm.green.dark1}),B=(0,o.AHW)({fill:o.MFm.gray.dark1}),z=(0,o.AHW)({fill:o.MFm.gray.light1}),_=(0,o.AHW)({backgroundColor:o.MFm.green.light3,borderColor:o.MFm.green.dark1,fill:o.MFm.green.dark1}),$=(0,o.AHW)({backgroundColor:o.MFm.red.light3,borderColor:o.MFm.red.dark2,fill:o.MFm.red.dark2});function Y({onSubmitFeedback:e}){const t=(0,o.D27)(),n=(0,r.useRef)(null),a=(0,r.useRef)(null),[s,l]=(0,r.useState)("none"),[c,d]=(0,r.useState)(!1),[u,p]=(0,r.useState)(!0),m=(0,r.useCallback)((t=>{"none"!==s&&(e(s,t),d(!0))}),[s,e,d]);return(0,r.useEffect)((()=>{if(c){const e=setTimeout((()=>{p(!1)}),R);return()=>{clearTimeout(e)}}}),[c]),c?u?i().createElement("div",{className:F},i().createElement(o.MWq,{className:t?W:j},"Success!")):null:i().createElement("div",{className:O},i().createElement(o.$nd,{className:(0,o.cx)(t?z:B,"positive"===s&&_),onClick:()=>l("positive"),size:"small","data-testid":"ai-feedback-thumbs-up",ref:n,"aria-label":"Submit positive feedback"},i().createElement(o.Int,{glyph:"ThumbsUp"})),i().createElement(o.$nd,{className:(0,o.cx)(t?z:B,"negative"===s&&$),onClick:()=>l("negative"),size:"small",ref:a,"aria-label":"Submit negative feedback"},i().createElement(o.Int,{glyph:"ThumbsDown"})),"none"!==s&&i().createElement(o.buA,{refEl:"positive"===s?n:a,open:!0,setOpen:()=>l("none"),onSubmitFeedback:m,label:"Provide Feedback",tooltipJustify:"end",placeholder:"positive"===s?"What do you like about the generated query?":"What could be better about the generated query?"}))}const K=({title:e="",description:t,refEl:n,showGuideCue:a,onCloseGuideCue:s})=>{const l=(0,o.BiT)();return(0,r.useEffect)((()=>{if(!a)return;const e=e=>{const t=document.querySelector(`[data-popoverid="ai-guide-cue-description-popover-${l}"]`);t&&(e.composedPath().includes(t)||e.composedPath().includes(n.current)||s())};return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}}),[l,s,n,a]),i().createElement(o.$uG,{spacing:o.YKD[400],open:a,setOpen:()=>{},refEl:n,numberOfSteps:1,currentStep:1,onPrimaryButtonClick:s,onDismiss:s,title:e,"data-popoverid":`ai-guide-cue-description-popover-${l}`,buttonText:"Got it"},i().createElement("span",{"data-testid":"ai-guide-cue-description-span"},t))},G=(0,o.AHW)({width:"100%",flexDirection:"column",gap:o.YKD[25],padding:`0px ${o.YKD[100]}px`,marginBottom:o.YKD[300]}),V=(0,o.AHW)({display:"flex",width:"100%",paddingTop:o.YKD[100],gap:o.YKD[200]}),U=o.YKD[50],q=o.YKD[25],Z=(0,o.i7C)({"0%":{backgroundPosition:"400% 400%",backgroundImage:`linear-gradient(\n 20deg,\n ${o.MFm.blue.light1} 0%,\n ${o.MFm.blue.light1} 30%,\n #00ede0 45%,\n #00ebc1 75%,\n #0498ec\n )`},"100%":{backgroundPosition:"0% 0%",backgroundImage:`linear-gradient(\n 20deg,\n ${o.MFm.blue.light1} 0%,\n ${o.MFm.blue.light1} 30%,\n #00ede0 45%,\n #00ebc1 75%,\n #0498ec\n )`}}),J=(0,o.i7C)({"0%":{opacity:1},"100%":{opacity:0}}),Q=(0,o.AHW)({"&::before, &::after":{content:'""',position:"absolute",top:`-${U+q}px`,left:`-${U+q}px`,width:`calc(100% + ${2*(U+q)}px)`,height:`calc(100% + ${2*(U+q)}px)`,borderRadius:o.YKD[200],backgroundColor:o.MFm.blue.light1,backgroundSize:"400% 400%",backgroundPosition:"800% 800%"},"&::after":{animation:`4000ms linear 0s infinite alternate ${Z}`},"&::before":{filter:"blur(4px) opacity(0.6)",animation:`4000ms linear 0s infinite alternate ${Z}, 4000ms linear 0s infinite alternate ${J}`,opacity:0}}),X=(0,o.AHW)({"> *":{boxShadow:"none !important"}}),ee=(0,o.AHW)({width:"100%",display:"flex",flexDirection:"column",position:"relative",zIndex:2}),te=(0,o.AHW)({width:"100%",position:"relative"}),ne=o.YKD[400]+o.YKD[300],ae=(0,o.AHW)({flexGrow:1,textarea:{margin:0,padding:o.YKD[50]+o.YKD[25],paddingLeft:o.YKD[800],paddingRight:2*o.YKD[1600]+o.YKD[200],height:ne,minHeight:`${ne}px`,maxHeight:2*o.YKD[1600]}}),re=(0,o.AHW)({marginTop:o.YKD[100]}),ie=(0,o.AHW)({position:"absolute",right:o.YKD[100],display:"flex",gap:o.YKD[200],alignItems:"center",height:o.YKD[600]+o.YKD[100]}),oe=(0,o.AHW)({color:o.MFm.gray.dark3,backgroundColor:o.MFm.green.base,borderRadius:"50%"}),se=(0,o.AHW)({color:o.MFm.white,backgroundColor:o.MFm.green.dark1,borderRadius:"50%"}),le=(0,o.AHW)({border:"none",height:o.YKD[600]-o.YKD[100],display:"flex",fontSize:"12px",borderRadius:o.YKD[100]}),ce=(0,o.AHW)({backgroundColor:o.MFm.gray.light2}),de=(0,o.AHW)({height:"14px",lineHeight:"14px",padding:`0px ${o.YKD[100]}px`,borderRadius:"2px"}),ue=(0,o.AHW)({backgroundColor:o.MFm.gray.dark1,color:o.MFm.gray.light1}),pe=(0,o.AHW)({backgroundColor:o.MFm.gray.light1,color:o.MFm.gray.dark1}),me=(0,o.AHW)({padding:o.YKD[100],display:"inline-flex",width:16+o.YKD[200],justifyContent:"space-around"}),ge=(0,o.AHW)({margin:0,padding:0,border:"none",background:"none",cursor:"pointer"}),he=(0,o.AHW)(ge,o.Rg,{height:o.YKD[600]+o.YKD[100],display:"flex",alignItems:"center",padding:`${o.YKD[100]}px ${o.YKD[200]}px`,position:"absolute"}),fe=(0,o.AHW)({display:"flex"});function ye(e){if(e.current){e.current.style.height="0px";let t=e.current.scrollHeight;t>ne&&(t+=o.YKD[50]),e.current.style.height=`${t}px`}}const be=(0,r.forwardRef)((function({value:e,...t},n){const s=(0,r.useRef)(null);return(0,r.useLayoutEffect)((()=>ye(s)),[]),(0,r.useEffect)((()=>ye(s)),[e]),i().createElement(o.fs1,(0,a.A)({ref:e=>{s.current=e,"function"==typeof n?n(e):n&&(n.current=e)},value:e},t))})),ve="Close AI Helper",xe=({darkMode:e})=>i().createElement("svg",{width:14,height:14,viewBox:"0 0 14 14",fill:"none",xmlns:"http://www.w3.org/2000/svg"},i().createElement("rect",{width:"14",height:"14",rx:"2",fill:e?o.MFm.gray.dark1:o.MFm.gray.light1}),i().createElement("path",{d:"M5.24984 6.41668L2.9165 8.75001M2.9165 8.75001L5.24984 11.0833M2.9165 8.75001H9.33317C9.95201 8.75001 10.5455 8.50418 10.9831 8.06659C11.4207 7.62901 11.6665 7.03552 11.6665 6.41668C11.6665 5.79784 11.4207 5.20435 10.9831 4.76676C10.5455 4.32918 9.95201 4.08334 9.33317 4.08334H8.74984",stroke:e?o.MFm.gray.light1:o.MFm.gray.dark1,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}));function Ee({aiPromptText:e,didGenerateEmptyResults:t,didSucceed:n,errorMessage:a,errorCode:s,isFetching:l,placeholder:c="Tell us what to find (e.g. movies from 2000) or paste a query in another language (SQL, Java, etc.)",show:d,onCancelRequest:u,onClose:p,onChangeAIPromptText:m,onSubmitFeedback:g,onSubmitText:h,isAggregationGeneratedFromQuery:f=!1,onResetIsAggregationGeneratedFromQuery:y}){const b=(0,r.useRef)(null),[v,x]=(0,r.useState)(!1),[E,C]=(0,r.useState)(t),w=(0,o.D27)(),I=(0,r.useRef)(null);(0,o.wTI)((()=>{t&&C(!0)}),[t]);const S=(0,r.useCallback)((e=>{!function(e){const t=window;if(void 0!==t&&t.Intercom&&"function"==typeof t.Intercom&&A.env.HADRON_METRICS_INTERCOM_APP_ID)try{t.Intercom("track",e,void 0)}catch(e){k("intercom track error",e)}}(D.submittedNlPrompt),h(e)}),[h]),N=(0,r.useCallback)((t=>{if("Enter"!==t.key||t.shiftKey)"Escape"===t.key&&(l?u():p());else{if(t.preventDefault(),!e)return;S(e)}}),[e,p,S,l,u]);(0,o.wTI)((()=>{n&&x(!0)}),[n]),(0,r.useEffect)((()=>{if(v){const e=setTimeout((()=>{x(!1)}),1500);return()=>clearTimeout(e)}}),[v]),(0,r.useEffect)((()=>{d&&b.current?.focus()}),[d]);const M=(0,o.HIF)(u);return(0,r.useEffect)((()=>()=>M.current?.()),[M]),d?i().createElement("div",{className:G},i().createElement("div",{className:V},i().createElement("div",{className:te},i().createElement("div",{className:l?Q:void 0},i().createElement("div",{className:ee},i().createElement("button",{className:he,"data-testid":"close-ai-button","aria-label":ve,title:ve,onClick:()=>p()},i().createElement(K,{showGuideCue:f,onCloseGuideCue:()=>{y?.()},refEl:I,title:"Aggregation generated",description:"Your query requires stages from MongoDB's aggregation framework. Continue to work on it in our Aggregation Pipeline Builder"}),i().createElement(K,{showGuideCue:E,onCloseGuideCue:()=>C(!1),refEl:I,title:"No content generated",description:"The query generated returns all of the documents in your collection. Consider adjusting and resubmitting your prompt to narrow down the results."}),i().createElement("span",{className:fe,ref:I},i().createElement(o.Int,{glyph:"Sparkle"}))),i().createElement(be,{className:(0,o.cx)(ae,l&&X),ref:b,"data-testid":"ai-user-text-input","aria-labelledby":"",spellCheck:!1,"aria-label":"Enter a plain text query that the AI will translate into MongoDB query language.",placeholder:c,value:e,onChange:e=>m(e.target.value),onKeyDown:N}),i().createElement("div",{className:ie},l?i().createElement("div",{className:me},i().createElement(o.Q0K,null)):v?i().createElement("div",{className:me},i().createElement(o.Int,{className:w?oe:se,glyph:"CheckmarkWithCircle"})):i().createElement(i().Fragment,null,e&&i().createElement(o.K0,{"aria-label":"Clear prompt",onClick:()=>m(""),"data-testid":"ai-text-clear-prompt"},i().createElement(o.Int,{glyph:"X"}))),i().createElement(o.$nd,{size:"small",className:(0,o.cx)(le,!w&&ce),disabled:!e,"data-testid":"ai-generate-button",onClick:()=>l?u():S(e)},l?i().createElement(i().Fragment,null,i().createElement("div",null,"Cancel"),i().createElement("span",{className:(0,o.cx)(de,w?ue:pe)},"esc")):i().createElement(i().Fragment,null,i().createElement("div",null,"Generate"),i().createElement(xe,{darkMode:w}))))))),n&&g&&i().createElement(Y,{onSubmitFeedback:g})),a&&i().createElement("div",{className:re},i().createElement(o.lZ$,{"data-testid":"ai-error-msg",variant:o.uAY.Danger},i().createElement(Ce,{errorCode:s,errorMessage:a})))):null}const Ce=({errorCode:e,errorMessage:t})=>e?"NOT_SUPPORTED"===e?i().createElement(i().Fragment,null,"Sorry, this version of Compass is no longer suitable to generate queries. Please update to the latest version to access all the features."):"USER_INPUT_TOO_LONG"===e?i().createElement(i().Fragment,null,"Looks like your input exceeds the allowed length. Please reduce it and submit your prompt again."):"PROMPT_TOO_LONG"===e?i().createElement(i().Fragment,null,"Sorry, your request is too large. Please use a smaller prompt or try using this feature on a collection with smaller documents."):"TOO_MANY_REQUESTS"===e?i().createElement(i().Fragment,null,"Sorry, we are receiving too many requests in a short period of time. Please wait a few minutes and try again."):"GATEWAY_TIMEOUT"===e?i().createElement(i().Fragment,null,"It took too long to generate your query, please check your connection and try again. If the problem persists, contact our support team."):i().createElement(i().Fragment,null,"Sorry, we were unable to generate the query, please try again. If the error persists, try changing your prompt."):i().createElement(i().Fragment,null,t);var we=n(28508);const Ie=(0,o.AHW)({[`@container ${o.XvC.toolbarContainerQueryName} (width < 900px)`]:{display:"none"}}),Se=(0,o.AHW)({border:"none",outline:"none",boxShadow:"none",padding:`${o.YKD[100]}px ${o.YKD[200]}px`,margin:`${-o.YKD[100]}px ${-o.YKD[200]}px`,background:"none",whiteSpace:"normal",position:"relative",textDecoration:"underline",fontWeight:"bold",display:"inline-flex",gap:`${o.YKD[100]}px`,transition:"color 0.16s ease-in",path:{transition:"fill 0.16s ease-in"},"&:hover":{cursor:"pointer"}},o.Rg,N),Ae=(0,o.AHW)({color:o.MFm.green.dark1,"&:hover":{path:{fill:o.MFm.green.base},color:o.MFm.green.base}},M),ke=(0,o.AHW)({color:o.MFm.green.dark2,"&:hover":{path:{fill:o.MFm.green.dark1},color:o.MFm.green.dark1}},T);function De({"data-testid":e="open-gen-ai-button",type:t,onClick:n}){const a=(0,o.D27)(),s=(0,we.Jr)(),l=(0,r.useCallback)((()=>{s("AI Generate Query Clicked",{type:t}),n()}),[s,n,t]);return i().createElement("button",{className:(0,o.cx)(Se,a?Ae:ke),onClick:l,"data-testid":e,type:"button",title:`Generate ${t}`},i().createElement("span",{className:Ie},"Generate ",t),i().createElement(P,{darkMode:a}))}function Ne({onClickAI:e,darkMode:t,placeholderText:n,track:a}){const r=document.createElement("div"),i=document.createTextNode(`${n} or `);r.appendChild(i);const s=document.createElement("button");s.setAttribute("data-testid","open-ai-query-entry-button"),s.setAttribute("type","button"),s.style.pointerEvents="auto",s.addEventListener("mousedown",(e=>{e.preventDefault(),e.stopPropagation()})),s.addEventListener("click",(t=>{t.preventDefault(),t.stopPropagation(),a("AI Generate Query Clicked",{type:"query"}),e()})),s.className=(0,o.cx)(Se,t?Ae:ke);const l=`<span>Generate query</span>\n${L()}`;return s.innerHTML=l,r.appendChild(s),()=>r}var Me=n(19125);const Te=(0,o.AHW)({display:"block",width:270,height:180}),Pe=()=>i().createElement("svg",{className:Te,fill:"none",xmlns:"http://www.w3.org/2000/svg"},i().createElement("g",{clipPath:"url(#clip0_1579_7883)"},i().createElement("path",{d:"M116.936 64.1154H92.1264C64.7369 64.1154 42.5078 86.3 42.5078 113.635C42.5078 140.969 64.7369 163.154 92.1264 163.154H216.173C229.867 163.154 240.982 152.062 240.982 138.394V88.875C240.982 75.2077 229.867 64.1154 216.173 64.1154C202.478 64.1154 191.363 53.0231 191.363 39.3558C191.363 25.6885 180.249 14.5962 166.554 14.5962C152.859 14.5962 141.745 25.6885 141.745 39.3558C141.745 53.0231 130.829 64.1154 116.936 64.1154Z",fill:"#00684A"}),i().createElement("g",{clipPath:"url(#clip1_1579_7883)"},i().createElement("path",{d:"M215.659 34.7402L217.247 38.0921C218.041 39.4233 218.462 40.9478 218.462 42.4979V63.5134C218.462 65.3881 216.94 66.9053 215.059 66.9053H193.129C191.387 66.9053 189.565 67.1278 188.128 66.1467L185.336 63.8489",fill:"black"}),i().createElement("path",{d:"M215.659 34.7402L217.247 38.0921C218.041 39.4233 218.462 40.9478 218.462 42.4979V63.5134C218.462 65.3881 216.94 66.9053 215.059 66.9053H193.129C191.387 66.9053 189.565 67.1278 188.128 66.1467L185.336 63.8489",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M200.375 64.8374V82.0488",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M200.374 86.1556C201.512 86.1556 202.434 85.2363 202.434 84.1022C202.434 82.9682 201.512 82.0488 200.374 82.0488C199.237 82.0488 198.314 82.9682 198.314 84.1022C198.314 85.2363 199.237 86.1556 200.374 86.1556Z",fill:"#B2FD34",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M191.564 64.8374V76.2095",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M191.564 80.3163C192.701 80.3163 193.624 79.3969 193.624 78.2629C193.624 77.1288 192.701 76.2095 191.564 76.2095C190.426 76.2095 189.504 77.1288 189.504 78.2629C189.504 79.3969 190.426 80.3163 191.564 80.3163Z",fill:"#B2FD34",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M209.262 64.8374V76.2095",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M209.261 80.3163C210.399 80.3163 211.321 79.3969 211.321 78.2629C211.321 77.1288 210.399 76.2095 209.261 76.2095C208.123 76.2095 207.201 77.1288 207.201 78.2629C207.201 79.3969 208.123 80.3163 209.261 80.3163Z",fill:"#B2FD34",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M200.455 36.8852V19.6738",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M200.454 19.6737C201.592 19.6737 202.514 18.7544 202.514 17.6203C202.514 16.4862 201.592 15.5669 200.454 15.5669C199.317 15.5669 198.395 16.4862 198.395 17.6203C198.395 18.7544 199.317 19.6737 200.454 19.6737Z",fill:"#B2FD34",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M209.262 36.885V25.5093",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M209.261 25.5131C210.399 25.5131 211.321 24.5937 211.321 23.4597C211.321 22.3256 210.399 21.4062 209.261 21.4062C208.123 21.4062 207.201 22.3256 207.201 23.4597C207.201 24.5937 208.123 25.5131 209.261 25.5131Z",fill:"#B2FD34",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M191.564 36.885V25.5093",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M191.564 25.5131C192.701 25.5131 193.624 24.5937 193.624 23.4597C193.624 22.3256 192.701 21.4062 191.564 21.4062C190.426 21.4062 189.504 22.3256 189.504 23.4597C189.504 24.5937 190.426 25.5131 191.564 25.5131Z",fill:"#B2FD34",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M215.211 49.0669H232.48",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M234.536 51.1205C235.674 51.1205 236.596 50.2011 236.596 49.0671C236.596 47.933 235.674 47.0137 234.536 47.0137C233.399 47.0137 232.477 47.933 232.477 49.0671C232.477 50.2011 233.399 51.1205 234.536 51.1205Z",fill:"#B2FD34",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M215.211 57.8491H226.623",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M228.683 59.9027C229.821 59.9027 230.743 58.9834 230.743 57.8493C230.743 56.7152 229.821 55.7959 228.683 55.7959C227.545 55.7959 226.623 56.7152 226.623 57.8493C226.623 58.9834 227.545 59.9027 228.683 59.9027Z",fill:"#B2FD34",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M215.211 40.2075H226.623",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M228.683 42.2611C229.821 42.2611 230.743 41.3418 230.743 40.2077C230.743 39.0736 229.821 38.1543 228.683 38.1543C227.545 38.1543 226.623 39.0736 226.623 40.2077C226.623 41.3418 227.545 42.2611 228.683 42.2611Z",fill:"#B2FD34",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M184.644 48.9863H167.379",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M165.32 51.0399C166.457 51.0399 167.38 50.1206 167.38 48.9865C167.38 47.8524 166.457 46.9331 165.32 46.9331C164.182 46.9331 163.26 47.8524 163.26 48.9865C163.26 50.1206 164.182 51.0399 165.32 51.0399Z",fill:"#B2FD34",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M184.644 40.2075H173.236",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M171.177 42.2611C172.315 42.2611 173.237 41.3418 173.237 40.2077C173.237 39.0736 172.315 38.1543 171.177 38.1543C170.039 38.1543 169.117 39.0736 169.117 40.2077C169.117 41.3418 170.039 42.2611 171.177 42.2611Z",fill:"#B2FD34",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M184.644 57.8491H173.236",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M171.177 59.9027C172.315 59.9027 173.237 58.9834 173.237 57.8493C173.237 56.7152 172.315 55.7959 171.177 55.7959C170.039 55.7959 169.117 56.7152 169.117 57.8493C169.117 58.9834 170.039 59.9027 171.177 59.9027Z",fill:"#00ED64",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M188.362 65.2207H212.47C214.692 65.2207 216.494 63.4245 216.494 61.2087V37.177C216.494 34.9613 214.692 33.165 212.47 33.165H188.362C186.139 33.165 184.338 34.9613 184.338 37.177V61.2087C184.338 63.4245 186.139 65.2207 188.362 65.2207Z",fill:"#B2FD34",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("mask",{id:"mask0_1579_7883",maskUnits:"userSpaceOnUse",x:"184",y:"33",width:"33",height:"33"},i().createElement("path",{d:"M188.362 65.2207H212.47C214.692 65.2207 216.494 63.4245 216.494 61.2087V37.177C216.494 34.9613 214.692 33.165 212.47 33.165H188.362C186.139 33.165 184.338 34.9613 184.338 37.177V61.2087C184.338 63.4245 186.139 65.2207 188.362 65.2207Z",fill:"white"})),i().createElement("g",{mask:"url(#mask0_1579_7883)"},i().createElement("path",{d:"M182.669 136.455L182.881 160.148C163.307 169.791 137.443 160.148 137.443 160.148C137.443 160.148 138.233 141.23 137.209 130.875C134.878 107.266 123.928 111.136 123.928 80.4737C123.928 57.941 140.944 43.3156 164.477 44.428C188.01 45.5404 208.283 54.8992 208.283 94.5521L215.118 109.32C216.029 111.286 214.847 113.583 212.714 113.992L208.283 114.845L204.991 135.974C204.508 139.078 201.456 141.098 198.398 140.343L162.611 131.484",fill:"black"}),i().createElement("path",{d:"M182.669 136.455L182.881 160.148C163.307 169.791 137.443 160.148 137.443 160.148C137.443 160.148 138.233 141.23 137.209 130.875C134.878 107.266 123.928 111.136 123.928 80.4737C123.928 57.941 140.944 43.3156 164.477 44.428C188.01 45.5404 208.283 54.8992 208.283 94.5521L215.118 109.32C216.029 111.286 214.847 113.583 212.714 113.992L208.283 114.845L204.991 135.974C204.508 139.078 201.456 141.098 198.398 140.343L162.611 131.484",stroke:"black",strokeMiterlimit:"10"})),i().createElement("path",{d:"M66.2384 70.9209L63.9261 74.4004C62.4224 76.6617 61.6211 79.3169 61.6211 82.0304V113.017C61.6211 116.439 64.4017 119.21 67.8336 119.21H99.0755C101.702 119.21 104.271 118.466 106.488 117.066L110.601 114.469",fill:"black"}),i().createElement("path",{d:"M66.2384 70.9209L63.9261 74.4004C62.4224 76.6617 61.6211 79.3169 61.6211 82.0304V113.017C61.6211 116.439 64.4017 119.21 67.8336 119.21H99.0755C101.702 119.21 104.271 118.466 106.488 117.066L110.601 114.469",stroke:"black",strokeMiterlimit:"10"}),i().createElement("path",{d:"M108.456 68.6924H68.8215C66.5988 68.6924 64.7969 70.4886 64.7969 72.7044V112.215C64.7969 114.431 66.5988 116.227 68.8215 116.227H108.456C110.679 116.227 112.481 114.431 112.481 112.215V72.7044C112.481 70.4886 110.679 68.6924 108.456 68.6924Z",fill:"#00ED64",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M88.6348 68.6924V43.1689",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M88.6351 43.169C90.3224 43.169 91.6902 41.8055 91.6902 40.1236C91.6902 38.4416 90.3224 37.0781 88.6351 37.0781C86.9479 37.0781 85.5801 38.4416 85.5801 40.1236C85.5801 41.8055 86.9479 43.169 88.6351 43.169Z",fill:"#00ED64",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M101.697 68.6927V51.8242",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M101.698 51.8277C103.385 51.8277 104.753 50.4642 104.753 48.7823C104.753 47.1003 103.385 45.7368 101.698 45.7368C100.01 45.7368 98.6426 47.1003 98.6426 48.7823C98.6426 50.4642 100.01 51.8277 101.698 51.8277Z",fill:"#00ED64",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M75.4531 68.6927V51.8242",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M75.4535 51.8277C77.1407 51.8277 78.5085 50.4642 78.5085 48.7823C78.5085 47.1003 77.1407 45.7368 75.4535 45.7368C73.7662 45.7368 72.3984 47.1003 72.3984 48.7823C72.3984 50.4642 73.7662 51.8277 75.4535 51.8277Z",fill:"#00ED64",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M88.5156 116.227V141.754",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M88.516 147.841C90.2032 147.841 91.571 146.478 91.571 144.796C91.571 143.114 90.2032 141.75 88.516 141.75C86.8287 141.75 85.4609 143.114 85.4609 144.796C85.4609 146.478 86.8287 147.841 88.516 147.841Z",fill:"#00ED64",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M75.4531 116.227V133.096",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M75.4535 139.187C77.1407 139.187 78.5085 137.823 78.5085 136.141C78.5085 134.459 77.1407 133.096 75.4535 133.096C73.7662 133.096 72.3984 134.459 72.3984 136.141C72.3984 137.823 73.7662 139.187 75.4535 139.187Z",fill:"#00ED64",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M101.697 116.227V133.096",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M101.698 139.187C103.385 139.187 104.753 137.823 104.753 136.141C104.753 134.459 103.385 133.096 101.698 133.096C100.01 133.096 98.6426 134.459 98.6426 136.141C98.6426 137.823 100.01 139.187 101.698 139.187Z",fill:"#00ED64",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M64.7696 92.3994H39.1621",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M36.1117 95.4449C37.7989 95.4449 39.1667 94.0814 39.1667 92.3995C39.1667 90.7175 37.7989 89.354 36.1117 89.354C34.4244 89.354 33.0566 90.7175 33.0566 92.3995C33.0566 94.0814 34.4244 95.4449 36.1117 95.4449Z",fill:"#00ED64",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M64.7693 79.3789H47.8477",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M44.7933 82.4244C46.4806 82.4244 47.8484 81.0609 47.8484 79.3789C47.8484 77.697 46.4806 76.3335 44.7933 76.3335C43.1061 76.3335 41.7383 77.697 41.7383 79.3789C41.7383 81.0609 43.1061 82.4244 44.7933 82.4244Z",fill:"#00ED64",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M64.7693 105.541H47.8477",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M44.7933 108.586C46.4806 108.586 47.8484 107.223 47.8484 105.541C47.8484 103.859 46.4806 102.495 44.7933 102.495C43.1061 102.495 41.7383 103.859 41.7383 105.541C41.7383 107.223 43.1061 108.586 44.7933 108.586Z",fill:"#00ED64",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("mask",{id:"mask1_1579_7883",maskUnits:"userSpaceOnUse",x:"64",y:"68",width:"49",height:"49"},i().createElement("path",{d:"M108.456 68.6924H68.8215C66.5988 68.6924 64.7969 70.4886 64.7969 72.7044V112.215C64.7969 114.431 66.5988 116.227 68.8215 116.227H108.456C110.679 116.227 112.481 114.431 112.481 112.215V72.7044C112.481 70.4886 110.679 68.6924 108.456 68.6924Z",fill:"white"})),i().createElement("g",{mask:"url(#mask1_1579_7883)"},i().createElement("path",{d:"M147.952 133.136L148.164 158.072C128.59 167.715 102.726 158.072 102.726 158.072C102.726 158.072 103.517 137.91 102.492 127.559C100.162 103.95 89.2109 107.82 89.2109 77.1578C89.2109 54.6251 106.228 39.9996 129.761 41.1121C153.294 42.2245 173.567 51.5833 173.567 91.2362L180.401 106.004C181.312 107.97 180.13 110.268 177.997 110.676L173.567 111.529L170.274 132.658C169.791 135.762 166.739 137.782 163.681 137.027L127.895 128.168",fill:"black"})),i().createElement("path",{d:"M161.116 135.39L161.328 159.082C141.754 168.726 115.89 159.082 115.89 159.082C115.89 159.082 116.681 140.164 115.656 129.81C113.326 106.201 102.375 110.071 102.375 79.4083C102.375 56.8756 119.392 42.2501 142.925 43.3625C166.458 44.475 186.731 53.8338 186.731 93.4867L193.565 108.254C194.476 110.22 193.294 112.518 191.161 112.926L186.731 113.78L183.438 134.908C182.955 138.012 179.903 140.033 176.845 139.278L141.059 130.419",fill:"black"}),i().createElement("path",{d:"M161.116 135.39L161.328 159.082C141.754 168.726 115.89 159.082 115.89 159.082C115.89 159.082 116.681 140.164 115.656 129.81C113.326 106.201 102.375 110.071 102.375 79.4083C102.375 56.8756 119.392 42.2501 142.925 43.3625C166.458 44.475 186.731 53.8338 186.731 93.4867L193.565 108.254C194.476 110.22 193.294 112.518 191.161 112.926L186.731 113.78L183.438 134.908C182.955 138.012 179.903 140.033 176.845 139.278L141.059 130.419",stroke:"black",strokeMiterlimit:"10"}),i().createElement("path",{d:"M156.926 133.136L157.139 158.072C137.564 167.715 111.701 158.072 111.701 158.072C111.701 158.072 112.491 137.91 111.467 127.559C109.136 103.95 98.1855 107.82 98.1855 77.1578C98.1855 54.6251 115.202 39.9996 138.735 41.1121C162.268 42.2245 182.541 51.5833 182.541 91.2362L189.376 106.004C190.287 107.97 189.105 110.268 186.972 110.676L182.541 111.529L179.248 132.658C178.765 135.762 175.714 137.782 172.655 137.027L136.869 128.168",fill:"#E3FCF7"}),i().createElement("path",{d:"M156.926 133.136L157.139 158.072C137.564 167.715 111.701 158.072 111.701 158.072C111.701 158.072 112.491 137.91 111.467 127.559C109.136 103.95 98.1855 107.82 98.1855 77.1578C98.1855 54.6251 115.202 39.9996 138.735 41.1121C162.268 42.2245 182.541 51.5833 182.541 91.2362L189.376 106.004C190.287 107.97 189.105 110.268 186.972 110.676L182.541 111.529L179.248 132.658C178.765 135.762 175.714 137.782 172.655 137.027L136.869 128.168",stroke:"black",strokeMiterlimit:"10"}),i().createElement("path",{d:"M166.231 86.7863V86.7717C166.301 85.0539 166.187 83.3324 165.884 81.6437V81.6291L167.654 79.5976L168.968 78.0913L168.986 78.0694L165.825 71.4971L161.435 71.6539L161.42 71.6393C160.37 70.2898 159.177 69.0571 157.856 67.9702L157.842 67.9556L157.929 63.2178L151.274 60.1979L150.542 60.8544L147.992 63.1449L147.959 63.1777H147.945C146.357 62.8421 144.74 62.6744 143.119 62.6707H142.958L139.907 58.9141L132.864 60.8617L132.223 65.3843L132.209 65.3989C130.774 66.1502 129.428 67.0584 128.195 68.1015L128.18 68.1161L123.3 67.186L119.169 73.1967L121.646 77.1357V77.1503C121.049 78.6128 120.607 80.1337 120.325 81.6838V81.6984L115.92 84.1384L116.63 91.3892L121.086 92.8408V92.8553C121.569 94.3507 122.206 95.795 122.985 97.1627L123 97.1773L121.185 101.886L126.402 106.988L130.712 105.256L130.727 105.271C131.623 105.84 132.56 106.347 133.526 106.788C134.005 106.992 134.51 107.207 135.018 107.397H135.033L136.658 112.095L143.946 112.631L146.075 108.63H146.09C146.5 108.575 146.909 108.509 147.312 108.433C147.766 108.345 148.212 108.254 148.669 108.137C148.819 108.101 148.969 108.061 149.116 108.021C149.716 107.864 150.305 107.681 150.886 107.474H150.901L155.072 109.979L157.073 108.546L161.014 105.726L160.088 101.397L160.103 101.383C161.255 100.135 162.265 98.7639 163.118 97.294L163.132 97.2795L167.801 96.5318H167.845L169.67 89.4816L166.224 86.79L166.231 86.7863ZM142.793 100.102C139.954 100.102 137.177 99.2636 134.814 97.6916C132.45 96.1196 130.61 93.8802 129.523 91.2651C128.436 88.6501 128.151 85.7687 128.707 82.9932C129.26 80.214 130.628 77.6646 132.637 75.6622C134.645 73.6599 137.203 72.2958 139.991 71.7451C142.775 71.1943 145.665 71.4752 148.289 72.5584C150.912 73.6416 153.155 75.4762 154.735 77.8323C156.312 80.1885 157.157 82.9567 157.157 85.787C157.157 89.5838 155.643 93.2274 152.95 95.9117C150.257 98.5961 146.602 100.106 142.793 100.106V100.102Z",fill:"black"}),i().createElement("path",{d:"M162.791 82.9421V82.9276C162.865 81.2134 162.748 79.4955 162.447 77.8068V77.7922L164.215 75.7644L165.528 74.258L165.546 74.2398L162.385 67.6638L157.995 67.8243L157.98 67.8097C156.93 66.4602 155.737 65.2275 154.417 64.1406L154.402 64.126L154.49 59.3882L147.838 56.3683L147.106 57.0248L144.556 59.3043L144.523 59.3372H144.509C142.921 59.0053 141.304 58.8375 139.679 58.8411H139.518L136.467 55.0845L129.424 57.0321L128.784 61.5547L128.769 61.5693C127.335 62.3206 125.988 63.2288 124.752 64.2719L124.737 64.2865L119.853 63.3455L115.722 69.3598L118.199 73.2988V73.3134C117.606 74.776 117.163 76.2969 116.882 77.8469V77.8615L112.477 80.3015L113.186 87.5523L117.65 88.9966V89.0112C118.133 90.5065 118.77 91.9508 119.549 93.3186L119.564 93.3332L117.752 98.0417L122.97 103.144L127.28 101.412L127.294 101.426C128.194 101.995 129.135 102.502 130.104 102.944C130.584 103.148 131.089 103.363 131.597 103.549H131.612L133.229 108.247L140.517 108.783L142.646 104.778H142.661C143.071 104.724 143.481 104.662 143.887 104.585C144.34 104.497 144.783 104.406 145.244 104.286C145.394 104.249 145.544 104.209 145.691 104.169C146.287 104.012 146.876 103.826 147.461 103.622H147.476L151.647 106.128L153.648 104.694L157.578 101.871L156.648 97.5494L156.663 97.5348C157.816 96.2838 158.825 94.9124 159.678 93.4462L159.692 93.4316L164.361 92.6876H164.405L166.231 85.6375L162.784 82.9458L162.791 82.9421ZM139.357 96.2582C136.518 96.2582 133.741 95.4194 131.378 93.8474C129.014 92.2755 127.174 90.036 126.087 87.421C125 84.8059 124.715 81.9246 125.271 79.149C125.824 76.3698 127.192 73.8204 129.201 71.818C131.209 69.8157 133.767 68.4516 136.555 67.9009C139.339 67.3502 142.229 67.631 144.853 68.7142C147.476 69.7975 149.722 71.632 151.299 73.9882C152.876 76.3443 153.721 79.1125 153.721 81.9428C153.721 85.7396 152.207 89.3832 149.514 92.0676C146.821 94.7519 143.166 96.2619 139.357 96.2619V96.2582Z",fill:"#006CFA",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M156.841 145.438L138.734 128.631L156.926 133.136",fill:"black"}),i().createElement("path",{d:"M111.998 143.669C111.998 143.669 132.622 157.492 157.136 156.635L157.146 158.079C157.146 158.079 147.557 163.331 133.189 162.19C118.821 161.048 111.705 158.079 111.705 158.079",fill:"black"}),i().createElement("path",{d:"M227.196 95.6279L231.115 102.397L235.037 109.167H227.196H219.355L223.274 102.397L227.196 95.6279Z",fill:"white",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M227.196 104.399L219.355 109.166H235.037L227.196 104.399Z",fill:"black"}),i().createElement("path",{d:"M227.195 104.4V95.6279",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M227.477 112.974C227.477 135.769 208.942 154.246 186.075 154.246H169.604",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),i().createElement("path",{d:"M52.0993 142.845L45.4295 143.739L40.9805 137.604L47.5223 136.536L52.0993 142.845Z",fill:"black",stroke:"black",strokeLinejoin:"round"}),i().createElement("path",{d:"M52.1103 142.838L55.0519 136.805L50.5992 130.667L47.5332 136.524L52.1103 142.838Z",fill:"white",stroke:"black",strokeLinejoin:"round"}),i().createElement("path",{d:"M44.0977 131.816L40.9805 137.604L47.5333 136.524L50.5993 130.667L44.0977 131.816Z",fill:"white",stroke:"black",strokeLinejoin:"round"}))));var Le=n(68526),Oe=n(20625);const Re=(0,o.AHW)({marginTop:o.YKD[400],marginLeft:o.YKD[300],marginRight:o.YKD[300],display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center"}),He=(0,o.AHW)({color:o.MFm.gray.dark1}),Fe=(0,o.AHW)({color:o.MFm.gray.light2}),We={marginTop:o.YKD[400],marginLeft:o.YKD[800],marginRight:o.YKD[800],textAlign:"center"},je={[o.BDt.Light]:(0,o.AHW)({color:o.MFm.gray.dark1,...We}),[o.BDt.Dark]:(0,o.AHW)({color:o.MFm.gray.light2,...We})},Be=(0,o.AHW)({width:"480px",padding:o.YKD[400],marginTop:o.YKD[400],textAlign:"left"}),ze=({isProjectAIEnabled:e,isSampleDocumentPassingEnabled:t,projectId:n})=>{const a=n?i().createElement(o.N_E,{href:window.location.origin+"/v2/"+n+"#/settings/groupSettings",target:"_blank",hideExternalIcon:!0},"Project Settings"):"Project Settings";return e?t?i().createElement(i().Fragment,null,"AI features are enabled for project users with data access. Project Owners can disable Data Explorer AI features in ",a,"."):i().createElement(i().Fragment,null,"AI features are enabled for project users with data access. Project Owners can disable these features or enable sending sample field values in Data Explorer AI features to improve their accuracy in"," ",a,"."):i().createElement(i().Fragment,null,"AI features are disabled for project users with data access. Project Owners can enable Data Explorer AI features in ",a,".")},_e=(0,Me.Ng)((e=>({isOptInModalVisible:e.optIn.isModalOpen,isOptInInProgress:"in-progress"===e.optIn.state})),{onOptInModalClose:Le.Cw,onOptInClick:Le.Zk})((({isOptInModalVisible:e,isOptInInProgress:t,isCloudOptIn:n,onOptInModalClose:a,onOptInClick:s,projectId:l})=>{const c=(0,Oe.Fg)("enableGenAIFeaturesAtlasProject"),d=(0,Oe.Fg)("enableGenAISampleDocumentPassing"),u=(0,we.Jr)(),p=(0,o.D27)();(0,r.useEffect)((()=>{e&&u("AI Opt In Modal Shown",{})}),[e,u]);const m=(0,r.useCallback)((()=>{u("AI Opt In Modal Dismissed",{}),a()}),[u,a]);return i().createElement(o._U_,{showBlob:!0,blobPosition:"top right",title:"Use AI Features in "+(n?"Data Explorer":"Compass"),open:e,onClose:m,"data-testid":"ai-optin-modal",buttonProps:{children:"Use AI Features",onClick:()=>{!t&&c&&s()},disabled:!c},linkText:"Not now",onLinkClick:a,graphic:i().createElement(Pe,null),disclaimer:i().createElement("div",{className:je[p?o.BDt.Dark:o.BDt.Light]},"Features in ",n?"Data Explorer":"Compass"," powered by generative AI may produce inaccurate responses. Please see our"," ",i().createElement(o.N_E,{hideExternalIcon:!1,href:"https://www.mongodb.com/docs/generative-ai-faq/",target:"_blank"},"FAQ")," ","for more information. Continue to opt into all AI-powered features within ",n?"Data Explorer":"Compass",".")},i().createElement(o.nBu,{className:(0,o.cx)(Re,p?Fe:He)},"AI-powered features in ",n?"Data Explorer":"Compass"," ","supply users with an intelligent toolset to build faster and smarter with MongoDB.",n&&i().createElement(o.lZ$,{"data-testid":"ai-optin-cloud-banner",variant:c?"info":"warning",className:Be},i().createElement(ze,{isProjectAIEnabled:c,isSampleDocumentPassingEnabled:d,projectId:l}))))})),$e=({projectId:e,isCloudOptIn:t})=>i().createElement(o.ETl,null,i().createElement(_e,{isCloudOptIn:t,projectId:e}))},858:(e,t,n)=>{n.d(t,{M:()=>l});var a=n(96652),r=n.n(a),i=n(51295);(0,i.AHW)({display:"flex",alignItems:"center",gap:i.YKD[100]});const o=Object.freeze({filename:"",passphrase:"",connectionList:[],error:"",inProgress:!1});n(95039),n(93885),n(4308),n(60783),n(96452),Object.freeze({...o,passphraseRequired:!1,fileContents:""}),(0,i.AHW)({maxHeight:"24vh",overflow:"auto"}),(0,i.AHW)({marginLeft:i.YKD[200]}),n(20625),Object.freeze({...o,removeSecrets:!0}),(0,i.AHW)({maxHeight:"24vh",overflow:"auto"});const s=r().createContext(null),l=e=>{const t=(0,a.useContext)(s);return t?{supportsConnectionImportExport:!0,openConnectionImportExportModal(n){if("import-saved-connections"===n)t.getHandlers().openConnectionImportModal(e);else{if("export-saved-connections"!==n)throw new Error(`Unidentified action ${n} passed to handler`);t.getHandlers().openConnectionExportModal(e)}}}:{supportsConnectionImportExport:!1,openConnectionImportExportModal(){}}}},4863:(e,t,n)=>{n.d(t,{w:()=>o,x:()=>i});var a=n(20625),r=n(46729);function i(e,t){return e?(0,r.J0)(t):t}function o(){const e=(0,a.Fg)("protectConnectionStrings");return t=>i(e,t)}},6927:(e,t,n)=>{n.d(t,{$g:()=>y,Ol:()=>h,R3:()=>f,ti:()=>l});var a=n(56900),r=n(17855);const i=a.z.array(a.z.string()),o=a.z.object({ns:a.z.string().nullable(),cardinality:a.z.number().nullable().transform((e=>10===e?100:e)),fields:a.z.array(a.z.string()).nullable()}),s=a.z.object({id:a.z.string().uuid(),relationship:a.z.tuple([o,o]),isInferred:a.z.boolean(),note:a.z.string().optional()}),l=!0,c=a.z.custom((e=>"object"==typeof e&&null!==e&&"bsonType"in e)),d=a.z.preprocess((e=>{const{expanded:t,jsonSchema:n,...a}=e,r={...a};return n&&(r.fieldData=n),r}),a.z.object({ns:a.z.string(),fieldData:c,indexes:a.z.array(a.z.record(a.z.unknown())),shardKey:a.z.record(a.z.unknown()).optional(),displayPosition:a.z.tuple([a.z.number(),a.z.number()]),note:a.z.string().optional()})),u=a.z.object({collections:a.z.array(d),relationships:a.z.array(s)}),p=a.z.object({id:a.z.string().uuid(),timestamp:a.z.string().datetime()}),m=a.z.discriminatedUnion("type",[a.z.object({type:a.z.literal("SetModel"),model:u}),a.z.object({type:a.z.literal("AddRelationship"),relationship:s}),a.z.object({type:a.z.literal("UpdateRelationship"),relationship:s}),a.z.object({type:a.z.literal("RemoveRelationship"),relationshipId:a.z.string().uuid()}),a.z.object({type:a.z.literal("MoveCollection"),ns:a.z.string(),newPosition:a.z.tuple([a.z.number(),a.z.number()])}),a.z.object({type:a.z.literal("MoveMultipleCollections"),newPositions:a.z.record(a.z.string(),a.z.tuple([a.z.number(),a.z.number()]))}),a.z.object({type:a.z.literal("RemoveCollection"),ns:a.z.string()}),a.z.object({type:a.z.literal("RenameCollection"),fromNS:a.z.string(),toNS:a.z.string()}),a.z.object({type:a.z.literal("UpdateCollectionNote"),ns:a.z.string(),note:a.z.string()}),a.z.object({type:a.z.literal("AddCollection"),ns:a.z.string(),position:a.z.tuple([a.z.number(),a.z.number()]),initialSchema:a.z.custom()}),a.z.object({type:a.z.literal("RenameField"),ns:a.z.string(),field:i,newName:a.z.string()}),a.z.object({type:a.z.literal("RemoveField"),ns:a.z.string(),field:i}),a.z.object({type:a.z.literal("ChangeFieldType"),ns:a.z.string(),field:i,from:c,to:c}),a.z.object({type:a.z.literal("AddField"),ns:a.z.string(),field:i,jsonSchema:c}),a.z.object({type:a.z.literal("DuplicateField"),ns:a.z.string(),field:i}),a.z.object({type:a.z.literal("MoveField"),sourceNS:a.z.string(),targetNS:a.z.string(),targetField:i,field:i,jsonSchema:c}),a.z.object({type:a.z.literal("ToggleExpandCollection"),ns:a.z.string(),expanded:a.z.boolean()}),a.z.object({type:a.z.literal("ToggleExpandField"),ns:a.z.string(),field:i})]),g=a.z.intersection(p,m),h=a.z.array(g).nonempty().refine((e=>"SetModel"===e[0]?.type),{message:"First edit must be of type 'SetModel'"}),f=e=>{try{return g.parse(e),{result:!0}}catch(e){return{result:!1,errors:e.issues.map((({path:e,message:t})=>"Required"===t?`'${e}' is required`:`Invalid field '${e}': ${t}`))}}},y=a.z.preprocess((e=>{const t=e;return!t.database&&Array.isArray(t.edits)&&t.edits.length>0&&(t.database=(0,r.Ay)(t.edits?.[0].model.collections[0].ns).database),t}),a.z.object({id:a.z.string(),name:a.z.string(),connectionId:a.z.string().nullable(),database:a.z.string(),edits:h,createdAt:a.z.string().datetime(),updatedAt:a.z.string().datetime()}))},9118:(e,t,n)=>{n.d(t,{D:()=>m});var a=n(56900),r=n(6927),i=(n(59509),n(25691),n(23177),n(3142),n(51615),n(84217),n(25953),n(42319),n(28465),n(12887),n(36106),n(84542),n(57068),n(69517),n(96652)),o=n.n(i),s=n(36214);const l=new class{items=new Map;save(e){return this.items.set(e.id,e),Promise.resolve(!0)}delete(e){return this.items.delete(e),Promise.resolve(!0)}loadAll(){return Promise.resolve(Array.from(this.items.values()))}load(e){return Promise.resolve(this.items.get(e)??null)}};var c=n(70002),d=n(62183),u=n(44142);class p{userData;constructor(e,t,n){this.userData=new a.Tu(r.$g,"DataModelDescriptions",{orgId:e,projectId:t,atlasService:n})}save(e){return this.userData.write(e.id,e)}delete(e){return this.userData.delete(e)}async loadAll(){try{return(await this.userData.readAll()).data}catch{return[]}}async load(e){return(await this.loadAll()).find((t=>t.id===e))??null}}const m=(0,d.xw)((function({children:e,orgId:t,projectId:n}){const a=(0,i.useRef)(),r=(0,c.fA)(),d=(0,u.Ul)("DATA-MODEL-STORAGE");return a.current||(t&&n?a.current=new p(t,n,r):(d.log.warn((0,u.oW)(1001000379),"DataModelStorageServiceProviderWeb","Falling back to in memory storage because orgId or projectId is missing"),a.current=l)),o().createElement(s.jo,{storage:a.current},e)}))},9312:(e,t,n)=>{n.d(t,{y:()=>Ar});var a=n(96652),r=n.n(a),i=n(62183),o=n(20625),s=n(60783),l=n(28508),c=n(44142),d=n(19125),u=n(55712),p=n(13353);function m(e,t){return e.type===t}var g=n(6927),h=(n(59509),n(25691),n(23177),n(3142),n(51615),n(84217),n(25953),n(42319),n(28465),n(12887),n(36106),n(84542),n(57068),n(69517),n(21261),n(92879),n(31977),n(49743),n(9656),n(72673),n(35467),n(94476),n(64971),n(24330),n(83478),n(65166),n(1256),n(61038),n(73035),n(23855),n(26250)),f=n(51295),y=n(17855);n(95039);const b=({jsonSchema:e,visitor:t,parentFieldPath:n=[]})=>{if(e&&e.properties)for(const[a,r]of Object.entries(e.properties)){const e=[],i=[];if(r.bsonType&&e.push(r.bsonType),r.properties&&i.push(r),r.items&&i.push(r.items.anyOf||r.items),r.anyOf)for(const t of r.anyOf)t.bsonType&&e.push(t.bsonType),t.properties&&i.push(t),t.items&&i.push(t.items);const o=[...n,a];t({fieldPath:o,fieldTypes:e.flat(),fieldSchema:r}),i.flat().forEach((e=>b({jsonSchema:e,visitor:t,parentFieldPath:o})))}};function v(e,t){if(e&&!Array.isArray(e)){if(e.items){const n=v(e.items,t);if(n)return n}if(e.properties&&e.properties[t])return e.properties[t];if(e.anyOf)for(const n of e.anyOf)if(n.properties&&n.properties[t])return n.properties[t]}}function x(e){const t=[];return e.bsonType&&(Array.isArray(e.bsonType)?t.push(...e.bsonType):t.push(e.bsonType)),e.anyOf&&t.push(...e.anyOf.flatMap((e=>e.bsonType||[]))),t}function E({jsonSchema:e,fieldPath:t,parentFieldPath:n=[]}){const a=t[0],r=t.slice(1);let i;if(e.properties&&e.properties[a]&&(i=e.properties[a]),!i&&e.items&&(i=v(e.items,a)),!i&&e.anyOf)for(const t of e.anyOf){if(t.properties&&t.properties[a]){i=t.properties[a];break}if(t.items&&(i=v(t.items,a),i))break}if(i)return 1===t.length?{fieldTypes:x(i),jsonSchema:i}:E({jsonSchema:i,fieldPath:r,parentFieldPath:[...n,a]})}function C({schema:e,newFieldName:t,newFieldSchema:n}){const a={...e};return e.properties?a.properties={...e.properties,[t]:n}:e.anyOf?a.anyOf=function({anyOf:e,newFieldName:t,newFieldSchema:n}){let a=!1;const r=e.map((e=>a||"object"!==e.bsonType?e:(a=!0,w({schema:e,newFieldName:t,newFieldSchema:n,update:"addField"}))));return a||r.push({bsonType:"object",properties:{[t]:n}}),r}({anyOf:e.anyOf,newFieldName:t,newFieldSchema:n}):e.items&&(a.items=function({items:e,newFieldName:t,newFieldSchema:n}){if(!Array.isArray(e))return C({schema:e,newFieldName:t,newFieldSchema:n});let a=!1;const r=e.map((e=>a||"object"!==e.bsonType?e:(a=!0,w({schema:e,newFieldName:t,newFieldSchema:n,update:"addField"}))));return a||r.push({bsonType:"object",properties:{[t]:n}}),r}({items:e.items,newFieldName:t,newFieldSchema:n})),a}function w({schema:e,fieldName:t,newFieldName:n,newFieldSchema:a,update:r}){switch(r){case"removeField":{if(!e.properties||!e.properties[t])throw new Error("Field to remove does not exist");const n={...e,properties:Object.fromEntries(Object.entries(e.properties).filter((([e])=>e!==t)))};return n.required&&Array.isArray(n.required)&&(n.required=n.required.filter((e=>e!==t))),n}case"renameField":{if(!e.properties||!e.properties[t])throw new Error("Field to rename does not exist");if(!n)throw new Error("New field name is required for the rename operation");const a={...e,properties:Object.fromEntries(Object.entries(e.properties).map((([e,a])=>e===t?[n,a]:[e,a])))};return a.required&&Array.isArray(a.required)&&(a.required=a.required.map((e=>e!==t?e:n))),a}case"changeFieldSchema":if(!e.properties||!e.properties[t])throw new Error("Field to change type does not exist");if(!a)throw new Error("New field schema is required for the change operation");return{...e,properties:{...e.properties,[t]:a}};case"addField":if(!a)throw new Error("New field schema is required for the add operation");if(!n)throw new Error("New field name is required for the add operation");return C({schema:e,newFieldName:n,newFieldSchema:a});default:return e}}function I({jsonSchema:e,updateParameters:t,parentPath:n=[]}){const a={...e};return a.properties&&(a.properties=Object.fromEntries(Object.entries(a.properties).map((([e,a])=>[e,I({jsonSchema:t.updateFn({fieldSchema:a,fieldPath:[...n,e]}),parentPath:[...n,e],updateParameters:t})])))),a.anyOf&&(a.anyOf=a.anyOf.map((e=>I({jsonSchema:e,parentPath:n,updateParameters:t})))),a.items&&(Array.isArray(a.items)?a.items=a.items.map((e=>I({jsonSchema:e,parentPath:n,updateParameters:t}))):a.items=I({jsonSchema:a.items,parentPath:n,updateParameters:t})),a}function S({jsonSchema:e,fieldPath:t,updateParameters:n}){const a={...e};if(0===t.length&&"addField"===n.update)return w({schema:a,...n});const r=t[0],i=t.slice(1),o=0===i.length;if(a.properties&&a.properties[r]){if(o&&"addField"!==n.update)return w({schema:a,fieldName:r,...n});a.properties={...a.properties,[r]:S({jsonSchema:a.properties[r],fieldPath:i,updateParameters:n})}}return a.anyOf&&(a.anyOf=a.anyOf.map((e=>S({jsonSchema:e,fieldPath:t,updateParameters:n})))),a.items&&(Array.isArray(a.items)?a.items=a.items.map((e=>S({jsonSchema:e,fieldPath:t,updateParameters:n}))):a.items=S({jsonSchema:a.items,fieldPath:t,updateParameters:n})),a}const A=e=>{const t=e.anyOf?.filter((e=>"array"===e.bsonType));return t&&t.length>0?t:[{bsonType:"array",items:e.items||{}}]},k=e=>{const t=e.anyOf?.filter((e=>"object"===e.bsonType));return t&&t.length>0?t:[{bsonType:"object",properties:e.properties||{},required:e.required||[]}]},D=(e,t)=>{const n=e.anyOf?.filter((e=>"string"==typeof e.bsonType&&"object"!==e.bsonType&&"array"!==e.bsonType&&t.includes(e.bsonType)))||[],a=n.map((e=>e.bsonType)).flat(),r=e.bsonType?Array.isArray(e.bsonType)?e.bsonType:[e.bsonType]:[],i=r.filter((e=>"object"!==e&&"array"!==e&&t.includes(e))).map((e=>({bsonType:e}))),o=t.filter((e=>"object"!==e&&"array"!==e&&!a.includes(e)&&!r.includes(e))).map((e=>({bsonType:e})));return[...n,...i,...o]};function*N(e){if(e.properties&&(yield*Object.entries(e.properties)),e.items)if(Array.isArray(e.items))for(const t of e.items)yield*N(t);else yield*N(e.items);if(e.anyOf)for(const t of e.anyOf)yield*N(t)}var M=n(90605);const T=e=>1===e.length&&"_id"===e[0],P=e=>JSON.stringify(e);function L(e,t){return P(e)===P(t)}function O(e,t){return e.every(((e,n)=>e===t[n]))}function R(e,t,n){const[a,r]=e;return a.ns===t&&!!a.fields&&O(n,a.fields)||r.ns===t&&!!r.fields&&O(n,r.fields)}function H(e,t=2,n=Date.now){let a=-1,r=-1;return Array.from({length:t},((t,i)=>{return o=i,()=>{const t=r;r=n(),(a===o||-1===a||r-t>100)&&(a=o,e())};var o}))}function F(e,t=[]){return t.filter((t=>{const[n,a]=t.relationship;return n.ns===e||a.ns===e}))}function W(e){const[t,n]=e.relationship;return!!(t.ns&&n.ns&&t.fields&&n.fields&&0!==t.fields.length&&0!==n.fields.length)}function j(e){return(0,M.cloneDeepWith)(e,(e=>{if(!e)return e;if("object"==typeof e&&"expanded"in e){const{expanded:t,...n}=e;return n}return Array.isArray(e)?e.map((e=>{if("object"==typeof e&&"expanded"in e){const{expanded:t,...n}=e;return n}return e})):e}))}const B={},z=({fieldData:e})=>{if(!e||!e.properties)return[];const t=[];return b({jsonSchema:e,visitor:({fieldPath:e,fieldTypes:n,fieldSchema:a})=>{t.push(((e,t,n)=>({name:e[e.length-1],path:e,id:e,depth:e.length-1,type:1===t.length?t[0]:t,expanded:n}))(e,n,a.expanded??g.ti))}}),t},_=["key"],$=[],Y=({fieldPath:e,isExpanded:t,highlightedFields:n,selectedField:a})=>{const r=t??g.ti;return!!r||!!(a&&O(e,a)&&e.length<a.length)||!(!n||!n.some((t=>O(e,t)&&e.length<t.length)))||r},K=({fieldData:e,highlightedFields:t=[],selectedField:n})=>{if(!e||!e.properties)return[];const a=z({fieldData:e}),r=new Set(a.map((e=>P(e.path)))),i=n&&r.has(P(n))?n:void 0,o=t.filter((e=>r.has(P(e))));return a.map((e=>({...e,glyphs:"objectId"===e.type?_:$,selectable:!0,selected:!!i?.length&&L(e.path,i),editable:!T(e.path),variant:o.length&&o.some((t=>L(e.path,t)))?"preview":void 0,expanded:Y({fieldPath:e.path,isExpanded:e.expanded,highlightedFields:o,selectedField:i})})))};function G({ns:e,fieldData:t,displayPosition:n}){return{id:e,position:{x:n[0],y:n[1]},fields:z({fieldData:t})}}function V(e,t=!1){const[n,a]=e.relationship;return{id:e.id,source:n.ns??"",target:a.ns??"",sourceFieldId:n.fields??[],targetFieldId:a.fields??[],markerStart:1===n.cardinality?"one":"many",markerEnd:1===a.cardinality?"one":"many",selected:t,animated:!W(e)}}function*U(e,t=[],n=!1){if(e.anyOf)for(const n of e.anyOf)yield*U(n,t);else if(Array.isArray(e.bsonType))for(const n of e.bsonType)yield*U({...e,bsonType:n},t);else if(yield{schema:e,path:t,isArrayItem:n},e.items)for(const n of Array.isArray(e.items)?e.items:[e.items])yield*U(n,t,!0);else if(e.properties)for(const[n,a]of Object.entries(e.properties))yield*U(a,[...t,n])}function q(e,t){const n=[];for(const{schema:a,path:r}of U(e))a.bsonType===t.bsonType&&(0,M.isEqual)(a,t)&&n.push(r);return n}function Z(e,t){const[n,...a]=t;if(!n)return[e];if(!(n in e))return[];const r=e[n];return Array.isArray(r)?r.flatMap((e=>Z(e,a))):Z(r,a)}async function J(e,t,n,a,r,i,o){const s=t.properties?._id;return s&&(await r.indexes(e,{full:!1}).catch((()=>[]))).some((e=>1===e.fields.length&&"_id"===e.fields[0].field))?(await Promise.all(a.flatMap((t=>t.ns===e?[]:q(t.schema,s).map((async n=>{try{const a=t.sample.flatMap((e=>Z(e,n))).filter((e=>null!=e)).slice(0,100);if(0===a.length)return null;const o="objectId"===s.bsonType?1:a.length;return await r.count(e,{_id:{$in:a}},{hint:{_id:1},maxTimeMS:1e4,limit:o},{abortSignal:i,fallbackReadPreference:"secondaryPreferred"})!==o?null:[{ns:t.ns,fields:n,cardinality:1},{ns:e,fields:["_id"],cardinality:1}]}catch(e){return o?.(e),null}})))))).filter((e=>!!e)):[]}function Q(e,t=[]){const n=t.length>0?E({jsonSchema:e,fieldPath:t})?.jsonSchema:e;if(!n)return"field-1";const a=new Set(function*(){for(const[e]of N(n))yield e}());let r=1,i=`field-${r}`;for(;a.has(i);)r++,i=`field-${r}`;return i}function X(e){const t=[];return b({jsonSchema:e,visitor:({fieldPath:e})=>{t.push(e)}}),t}const ee={ANALYZING_COLLECTIONS_START:"data-modeling/analysis-stats/ANALYZING_COLLECTIONS_START",NAMESPACE_SAMPLE_FETCHED:"data-modeling/analysis-stats/NAMESPACE_SAMPLE_FETCHED",NAMESPACE_SCHEMA_ANALYZED:"data-modeling/analysis-stats/NAMESPACE_SCHEMA_ANALYZED",NAMESPACE_RELATIONS_INFERRED:"data-modeling/analysis-stats/NAMESPACE_RELATIONS_INFERRED",ANALYSIS_FINISHED:"data-modeling/analysis-stats/ANALYSIS_FINISHED",ANALYSIS_FAILED:"data-modeling/analysis-stats/ANALYSIS_FAILED",ANALYSIS_CANCELED:"data-modeling/analysis-stats/ANALYSIS_CANCELED",REDO_ANALYSIS_FINISHED:"data-modeling/analysis-stats/REDO_ANALYSIS_FINISHED",REDO_ANALYSIS_FAILED:"data-modeling/analysis-stats/REDO_ANALYSIS_FAILED",REDO_ANALYSIS_CANCELED:"data-modeling/analysis-stats/REDO_ANALYSIS_CANCELED"},te={currentAnalysisOptions:null,step:"IDLE",samplesFetched:0,schemasAnalyzed:0,willInferRelations:!1,collectionRelationsInferred:0};async function ne({collections:e,relations:t}){const n=t.length>0,a=e.map((e=>G({ns:e.ns,fieldData:e.schema,displayPosition:[0,0]})));return await(0,f.PVz)({nodes:a,edges:t.map((e=>V(e,!1))),direction:n?"STAR":"RECTANGLE"})}function ae(e,t,n,a,r){return async(i,o,{connections:s,cancelAnalysisControllerRef:l,track:d,logger:u,preferences:p,dataModelStorage:m})=>{if(l.current)return;const g=s.getConnectionById(t)?.info,h=p.getPreferences().enableAutomaticRelationshipInference&&r.automaticallyInferRelations;d("Data Modeling Diagram Creation Started",{num_collections:a.length,automatically_infer_relations:h,sample_size:r.samplingOptions.allDocuments?"all_documents":r.samplingOptions.sampleSize},g);const f=l.current=new AbortController,y=Date.now();try{const{collections:s,relations:l,relationsInferencePhaseMs:c}=await i(oe({name:e,connectionId:t,database:n,selectedCollections:a,options:r})),u=await ne({collections:s,relations:l});i({type:ee.ANALYSIS_FINISHED,name:e,connectionId:t,database:n,relations:l,collections:s.map((e=>{const t=u.nodes.find((t=>t.id===e.ns)),n=t?t.position:{x:0,y:0};return{...e,position:n}}))}),d("Data Modeling Diagram Created",{num_collections:a.length,num_relations_inferred:h?l.length:void 0,analysis_time_ms:Date.now()-y,relationship_inference_phase_ms:c,sample_size:r.samplingOptions.allDocuments?"all_documents":r.samplingOptions.sampleSize},g),m.save(He(o()))}catch(e){const t=Date.now()-y;let n;e instanceof ie&&(n=e.relationshipInferencePhaseMs),f.signal.aborted?(i({type:ee.ANALYSIS_CANCELED}),d("Data Modeling Diagram Creation Cancelled",{num_collections:a.length,automatically_infer_relations:h,analysis_time_ms:t,relationship_inference_phase_ms:n,sample_size:r.samplingOptions.allDocuments?"all_documents":r.samplingOptions.sampleSize},g)):(u.log.error((0,c.oW)(1001000350),"DataModeling","Failed to analyze schema",{err:e}),i({type:ee.ANALYSIS_FAILED,error:e}),d("Data Modeling Diagram Creation Failed",{num_collections:a.length,analysis_time_ms:t,relationship_inference_phase_ms:n,automatically_infer_relations:h,sample_size:r.samplingOptions.allDocuments?"all_documents":r.samplingOptions.sampleSize},g))}finally{l.current=null}}}const re=e=>"IDLE"!==e.analysisProgress.step;class ie extends Error{relationshipInferencePhaseMs;constructor(e,t){super(e.message,{cause:e}),this.name="RelationshipInferenceError",this.relationshipInferencePhaseMs=t}}function oe({name:e,connectionId:t,database:n,selectedCollections:a,options:r}){return async(i,o,{connections:s,logger:l,preferences:d,cancelAnalysisControllerRef:u,track:m})=>{const g=u.current?.signal,f=a.map((e=>`${n}.${e}`)),y=d.getPreferences().enableAutomaticRelationshipInference&&r.automaticallyInferRelations;i({type:ee.ANALYZING_COLLECTIONS_START,name:e,connectionId:t,database:n,collections:a,options:r,willInferRelations:y});let b=[];const v=s.getDataServiceForConnection(t),x=await Promise.all(f.map((async e=>{const t=await async function({samplingOptions:e,dataService:t,ns:n,abortSignal:a}){return e.allDocuments?await t.find(n,{},{promoteValues:!1},{abortSignal:a,fallbackReadPreference:"secondaryPreferred"}):await t.sample(n,{size:e.sampleSize},{promoteValues:!1},{abortSignal:a,fallbackReadPreference:"secondaryPreferred"})}({samplingOptions:r.samplingOptions,dataService:v,ns:e,abortSignal:g});i({type:ee.NAMESPACE_SAMPLE_FETCHED});const n=await(0,h.Dy)(t,{signal:g}),a=await n.getMongoDBJsonSchema({signal:g});return i({type:ee.NAMESPACE_SCHEMA_ANALYZED}),{ns:e,schema:a,sample:t}})));let E;if(y){const e=await async function({track:e,logger:t,connections:n,connectionId:a,selectedCollections:r,collections:i,dataService:o,abortSignal:s,samplingOptions:l}){const d=Date.now();let u=[];try{const m=n.getConnectionById(a)?.info;return e("Data Modeling Diagram Creation Relationship Inferral Started",{num_collections:r.length,sample_size:l.allDocuments?"all_documents":l.sampleSize},m),u=(await Promise.all(i.map((async({ns:e,schema:n,sample:a})=>await J(e,n,0,i,o,s,(n=>{t.log.warn((0,c.oW)(1001000371),"DataModeling","Failed to identify relationship for collection",{ns:e,error:n.message})})))))).flatMap((e=>e.map((e=>({id:(new p.UUID).toHexString(),relationship:e,isInferred:!0}))))),{relations:u,relationsInferencePhaseMs:Date.now()-d}}catch(e){const t=d?Date.now()-d:void 0;throw new ie(e,t)}}({track:m,logger:l,connections:s,connectionId:t,selectedCollections:a,collections:x,dataService:v,abortSignal:g,samplingOptions:r.samplingOptions});b=e.relations,E=e.relationsInferencePhaseMs,i({type:ee.NAMESPACE_RELATIONS_INFERRED})}if(g?.aborted){if(void 0!==E)throw new ie(g.reason,E);throw g.reason}return{collections:x,relations:b,relationsInferencePhaseMs:E}}}var se=n(46410),le=n.n(se),ce=n(19046),de=n(12738);function ue(e,t,n){const a=document.createElement("a");a.download=t,a.href=e,a.click(),setTimeout((()=>{a.remove(),n?.()}),0)}var pe=n(56900),me=n(34110).Buffer;const ge="Compass Data Modeling Diagram";function he(e,t,n){return{type:ge,version:1,name:e,database:n,edits:me.from(JSON.stringify(t)).toString("base64")}}function fe(e){const{groups:t={}}=e.match(/^(?<name>.+?)(\s\((?<count>\d+)\))?$/)??{};return[t.name??e,t.count?Number(t.count):0]}function ye(e,t){if(!e.includes(t))return t;const[n,a]=fe(t),r=e.reduce(((e,t)=>{const[a,r]=fe(t);return a===n&&r>=e?r+1:e}),a+1);return`${n} (${r})`}function be(e,t){return e.ns===t.ns&&e.fields&&O(t.field,e.fields)?{...e,fields:[...e.fields.slice(0,t.field.length-1),t.newName,...e.fields.slice(t.field.length)]}:e}function ve(e,t){if(!e.find((e=>e.ns===t)))throw new Error(`Collection '${t}' not found`)}function xe(e,t){if("SetModel"===e.type)return e.model;if(!t)throw new Error("Editing a model that has not been initialized");switch(e.type){case"AddCollection":{const n={ns:e.ns,fieldData:e.initialSchema,displayPosition:e.position,indexes:[]};return{...t,collections:[...t.collections,n]}}case"AddRelationship":return{...t,relationships:[...t.relationships,e.relationship]};case"RemoveRelationship":return{...t,relationships:t.relationships.filter((t=>t.id!==e.relationshipId))};case"UpdateRelationship":{const n=t.relationships.find((t=>t.id===e.relationship.id));if(!n)throw new Error("Can not update non-existent relationship");return{...t,relationships:t.relationships.map((t=>t===n?e.relationship:t))}}case"MoveCollection":return ve(t.collections,e.ns),{...t,collections:t.collections.map((t=>t.ns===e.ns?{...t,displayPosition:e.newPosition}:t))};case"MoveMultipleCollections":{const n=new Set(Object.keys(e.newPositions));for(const e of n)ve(t.collections,e);return{...t,collections:t.collections.map((t=>n.has(t.ns)?{...t,displayPosition:e.newPositions[t.ns]}:t))}}case"RemoveCollection":return ve(t.collections,e.ns),{...t,relationships:t.relationships.filter((t=>!(t.relationship[0].ns===e.ns||t.relationship[1].ns===e.ns))),collections:t.collections.filter((t=>t.ns!==e.ns))};case"RenameCollection":return ve(t.collections,e.fromNS),{...t,relationships:t.relationships.map((t=>{const[n,a]=t.relationship;return{...t,relationship:[{...n,ns:n.ns===e.fromNS?e.toNS:n.ns},{...a,ns:a.ns===e.fromNS?e.toNS:a.ns}]}})),collections:t.collections.map((t=>({...t,ns:t.ns===e.fromNS?e.toNS:t.ns})))};case"UpdateCollectionNote":return ve(t.collections,e.ns),{...t,collections:t.collections.map((t=>t.ns===e.ns?{...t,note:e.note}:t))};case"AddField":return ve(t.collections,e.ns),{...t,collections:t.collections.map((t=>t.ns===e.ns?{...t,fieldData:S({jsonSchema:t.fieldData,fieldPath:e.field.slice(0,-1),updateParameters:{update:"addField",newFieldSchema:e.jsonSchema,newFieldName:e.field[e.field.length-1]}})}:t))};case"RemoveField":return ve(t.collections,e.ns),{...t,relationships:t.relationships.filter((({relationship:t})=>!R(t,e.ns,e.field))),collections:t.collections.map((t=>t.ns!==e.ns?t:{...t,fieldData:S({jsonSchema:t.fieldData,fieldPath:e.field,updateParameters:{update:"removeField"}})}))};case"RenameField":return ve(t.collections,e.ns),{...t,relationships:t.relationships.map((t=>R(t.relationship,e.ns,e.field)?{...t,relationship:[be(t.relationship[0],e),be(t.relationship[1],e)]}:t)),collections:t.collections.map((t=>t.ns!==e.ns?t:{...t,fieldData:S({jsonSchema:t.fieldData,fieldPath:e.field,updateParameters:{update:"renameField",newFieldName:e.newName}})}))};case"ChangeFieldType":return ve(t.collections,e.ns),{...t,collections:t.collections.map((t=>t.ns!==e.ns?t:{...t,fieldData:S({jsonSchema:t.fieldData,fieldPath:e.field,updateParameters:{update:"changeFieldSchema",newFieldSchema:e.to}})}))};case"ToggleExpandCollection":return ve(t.collections,e.ns),{...t,collections:t.collections.map((t=>t.ns!==e.ns?t:{...t,fieldData:I({jsonSchema:t.fieldData,updateParameters:{updateFn:({fieldSchema:t})=>({...t,expanded:e.expanded})}})}))};case"ToggleExpandField":{ve(t.collections,e.ns);const n=E({jsonSchema:t.collections.find((t=>t.ns===e.ns)).fieldData,fieldPath:e.field})?.jsonSchema,a=n?.expanded??g.ti;return{...t,collections:t.collections.map((t=>t.ns!==e.ns?t:{...t,fieldData:S({jsonSchema:t.fieldData,fieldPath:e.field,updateParameters:{update:"changeFieldSchema",newFieldSchema:{...n,expanded:!a}}})}))}}default:return t}}function Ee(e){return Array.isArray(e)&&e.length>0}const Ce={OPEN_DIAGRAM:"data-modeling/diagram/OPEN_DIAGRAM",RENAME_DIAGRAM:"data-modeling/diagram/RENAME_DIAGRAM",DELETE_DIAGRAM:"data-modeling/diagram/DELETE_DIAGRAM",APPLY_INITIAL_LAYOUT:"data-modeling/diagram/APPLY_INITIAL_LAYOUT",APPLY_EDIT:"data-modeling/diagram/APPLY_EDIT",UNDO_EDIT:"data-modeling/diagram/UNDO_EDIT",REDO_EDIT:"data-modeling/diagram/REDO_EDIT",REVERT_FAILED_EDIT:"data-modeling/diagram/REVERT_FAILED_EDIT",COLLECTION_SELECTED:"data-modeling/diagram/COLLECTION_SELECTED",RELATIONSHIP_SELECTED:"data-modeling/diagram/RELATIONSHIP_SELECTED",FIELD_SELECTED:"data-modeling/diagram/FIELD_SELECTED",DIAGRAM_BACKGROUND_SELECTED:"data-modeling/diagram/DIAGRAM_BACKGROUND_SELECTED"},we=(e,t,n)=>{if(t===n)return e;const{current:a}=e,r=a.findIndex((e=>"AddCollection"===e.type&&e.ns===t)),i={...a[r],ns:n};return{prev:e.prev,current:[...a.slice(0,r),i,...a.slice(r+1)],next:[]}},Ie=(e,t)=>{switch(t.type){case"RenameCollection":if(!e)return e;if("collection"===e?.type&&e.id===t.fromNS)return{type:"collection",id:t.toNS};break;case"AddCollection":return{type:"collection",id:t.ns};case"RenameField":return{type:"field",namespace:t.ns,fieldPath:[...t.field.slice(0,t.field.length-1),t.newName]};case"AddField":return{type:"field",namespace:t.ns,fieldPath:t.field}}return e};function Se(e){return(t,n,{track:a})=>{t({type:Ce.RELATIONSHIP_SELECTED,relationshipId:e}),a("Data Modeling Relationship Form Opened",{})}}function Ae({localNamespace:e,foreignNamespace:t=null,localFields:n=null,foreignFields:a=null}){return(r,i,{track:o})=>{const s=(new p.UUID).toString(),l=ze(i());r(De({type:"AddRelationship",relationship:{id:s,relationship:[{ns:e,cardinality:1,fields:n},{ns:t,cardinality:1,fields:a}],isInferred:!1}})),r({type:Ce.RELATIONSHIP_SELECTED,relationshipId:s}),o("Data Modeling Relationship Added",{num_relationships:l+1})}}function ke(e,t,n){e("data-modeling-error",{variant:"warning",title:t,description:n.join(" ")})}function De(e){return(t,n,{dataModelStorage:a,openToast:r})=>{const i={...e,id:(new p.UUID).toString(),timestamp:(new Date).toISOString()},{result:o,errors:s}=(0,g.R3)(i);let l=o;if(!o)return ke(r,"Could not apply changes",s),l;t({type:Ce.APPLY_EDIT,edit:i});try{je(n())}catch(e){ke(r,"Could not apply changes",["Something went wrong when applying the changes.",e.message]),t({type:Ce.REVERT_FAILED_EDIT}),l=!1}return a.save(He(n())),l}}function Ne(e){return{type:Ce.OPEN_DIAGRAM,diagram:e}}function Me(e){return(t,n,{track:a})=>{const r=ze(n());t(De({type:"RemoveRelationship",relationshipId:e})),a("Data Modeling Relationship Deleted",{num_relationships:r-1})}}function Te(e){return(t,n,{track:a})=>{a("Data Modeling Collection Removed",{source:"side_panel"}),t(De({type:"RemoveCollection",ns:e}))}}function Pe(e,t){return(n,a,{track:r})=>{r("Data Modeling Field Removed",{source:"side_panel"}),n(De({type:"RemoveField",ns:e,field:t}))}}function Le({ns:e,field:t,newName:n,source:a}){return(r,i,{track:o})=>{o("Data Modeling Field Renamed",{source:a}),r(De({type:"RenameField",ns:e,field:t,newName:n}))}}function Oe(e){if(e){if(Array.isArray(e)){if(0===e.length)return;return 1===e.length?e[0]:"mixed"}return e}}function Re({ns:e,fieldPath:t,newTypes:n,source:a}){return(r,i,{track:o})=>{const s=je(i()).collections.find((t=>t.ns===e))?.fieldData;if(!s)throw new Error("Collection not found in model");const l=E({jsonSchema:s,fieldPath:t});if(!l)throw new Error("Field not found in schema");const c=l.fieldTypes,d=function(e,t){if(x(e).join(",")===t.join(","))return e;if(!t.some((e=>"object"===e||"array"===e)))return{bsonType:t};const n=[...t.includes("array")?A(e):[],...t.includes("object")?k(e):[],...D(e,t)];return 1===n.length?n[0]:{anyOf:n}}(l.jsonSchema,n);o("Data Modeling Field Type Changed",{source:a,from:Oe(c),to:Oe(n)}),r(De({type:"ChangeFieldType",ns:e,field:t,from:l.jsonSchema,to:d}))}}function He(e){if(!e.diagram)throw new Error("No current diagram in state");const{id:t,connectionId:n,database:a,name:r,createdAt:i,updatedAt:o,edits:{current:s}}=e.diagram;return{id:t,connectionId:n,name:r,database:a,edits:s,createdAt:i,updatedAt:o}}const Fe=(0,M.memoize)(He),We=(0,M.memoize)((function(e){const t=e.slice().reverse().findIndex((e=>"SetModel"===e.type));if(-1===t)throw new Error("No diagram model found.");const n=e.length-1-t,a=e[n];if("SetModel"!==a.type)throw new Error("Something went wrong, last edit is not a SetModel");let r=a.model;for(let t=n+1;t<e.length;t++)r=xe(e[t],r);return r})),je=e=>We(Fe(e).edits),Be=(0,M.memoize)((function(e){const t=We(e);return Object.fromEntries(t.collections.map((e=>[e.ns,X(e.fieldData)])))}));function ze(e){return je(e).relationships.length}const _e="data-modeling/export-diagram/MODAL_OPENED",$e="data-modeling/export-diagram/MODAL_CLOSED",Ye="data-modeling/export-diagram/FORMAT_SELECTED",Ke="data-modeling/export-diagram/EXPORT_STARTED",Ge="data-modeling/export-diagram/EXPORT_COMPLETED",Ve={isModalOpen:!1,isExporting:!1},Ue=()=>{const e=(0,f.D27)(),t=(0,a.useMemo)((()=>e?f.MFm.white:f.MFm.black),[e]);return r().createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none"},r().createElement("path",{d:"M13.5 4.25H8.25L6.58313 3C6.3665 2.8382 6.1035 2.75054 5.83313 2.75H2.5C2.16848 2.75 1.85054 2.8817 1.61612 3.11612C1.3817 3.35054 1.25 3.66848 1.25 4V12.5C1.25 12.8315 1.3817 13.1495 1.61612 13.3839C1.85054 13.6183 2.16848 13.75 2.5 13.75H13.5556C13.8723 13.7497 14.1759 13.6237 14.3998 13.3998C14.6237 13.1759 14.7497 12.8723 14.75 12.5556V5.5C14.75 5.16848 14.6183 4.85054 14.3839 4.61612C14.1495 4.3817 13.8315 4.25 13.5 4.25ZM13.25 12.25H2.75V4.25H5.75L7.55 5.6C7.67982 5.69737 7.83772 5.75 8 5.75H13.25V12.25ZM8 6.75C8.19891 6.75 8.38968 6.82902 8.53033 6.96967C8.67098 7.11032 8.75 7.30109 8.75 7.5V8.25H9.5C9.69891 8.25 9.88968 8.32902 10.0303 8.46967C10.171 8.61032 10.25 8.80109 10.25 9C10.25 9.19891 10.171 9.38968 10.0303 9.53033C9.88968 9.67098 9.69891 9.75 9.5 9.75H8.75V10.5C8.75 10.6989 8.67098 10.8897 8.53033 11.0303C8.38968 11.171 8.19891 11.25 8 11.25C7.80109 11.25 7.61032 11.171 7.46967 11.0303C7.32902 10.8897 7.25 10.6989 7.25 10.5V9.75H6.5C6.30109 9.75 6.11032 9.67098 5.96967 9.53033C5.82902 9.38968 5.75 9.19891 5.75 9C5.75 8.80109 5.82902 8.61032 5.96967 8.46967C6.11032 8.32902 6.30109 8.25 6.5 8.25H7.25V7.5C7.25 7.30109 7.32902 7.11032 7.46967 6.96967C7.61032 6.82902 7.80109 6.75 8 6.75Z",fill:t}))};var qe=n(45363),Ze=n(29851);const Je={sampleSize:100,allDocuments:!1};function Qe(e){return!!e.allDocuments||!isNaN(e.sampleSize)&&e.sampleSize>0}const Xe="data-modeling/reselect-collections-wizard/SHOW_WIZARD",et="data-modeling/reselect-collections-wizard/HIDE_WIZARD",tt="data-modeling/reselect-collections-wizard/CONNECTION_SELECTED",nt="data-modeling/reselect-collections-wizard/CONNECT_TO_CONNECTION_CLICKED",at="data-modeling/reselect-collections-wizard/CONNECT_TO_CONNECTION_SUCCEEDED",rt="data-modeling/reselect-collections-wizard/CONNECT_TO_CONNECTION_FAILED",it="data-modeling/reselect-collections-wizard/TOGGLE_INFER_RELATION_CLICKED",ot="data-modeling/reselect-collections-wizard/CHANGE_SAMPLING_OPTIONS",st="data-modeling/reselect-collections-wizard/SELECT_COLLECTIONS_CLICKED",lt="data-modeling/reselect-collections-wizard/START_ANALYSIS",ct="data-modeling/reselect-collections-wizard/GOTO_STEP",dt={isOpen:!1,step:"SELECT_CONNECTION",diagramName:"",selectedCollections:[],newSelectedCollections:[],automaticallyInferRelations:!0,samplingOptions:Je,isConnecting:!1,databaseCollections:[]};function ut(e){return{type:it,val:e}}async function pt(e,t,n){const a=n.getMongoDBInstanceForConnection(e),r=t.getDataServiceForConnection(e);return await a.fetchDatabases({dataService:r}),a.databases.map((e=>e.name)).filter((e=>!(0,y.Ay)(e).specialish))}async function mt(e,t,n,a){await pt(e,n,a);const r=a.getMongoDBInstanceForConnection(e),i=n.getDataServiceForConnection(e),o=r.databases.get(t);if(!o)throw new Error("The selected database does not exist on this connection.");return await o.fetchCollections({dataService:i,force:!0}),o.collections.map((e=>e.name)).filter((e=>!(0,y.Ay)(e).specialish))}function gt(e){return{type:ot,samplingOptions:e}}const ht=(0,f.AHW)({padding:`${f.YKD[300]}px ${f.YKD[400]}px`}),ft=(0,f.AHW)({display:"flex",justifyContent:"space-between",alignItems:"center",padding:`${f.YKD[150]}px ${f.YKD[300]}px`,backgroundColor:f.MFm.gray.light3,borderBottom:`1px solid ${f.MFm.gray.light2}`,marginBottom:f.YKD[50],boxShadow:`0px ${f.YKD[50]}px ${f.YKD[100]}px -${f.YKD[25]}px ${(0,f.No6)(.85,f.MFm.black)}`}),yt=(0,f.AHW)({backgroundColor:f.MFm.gray.dark3,borderBottom:`1px solid ${f.MFm.gray.dark2}`,boxShadow:`0px ${f.YKD[50]}px ${f.YKD[100]}px -${f.YKD[25]}px ${(0,f.No6)(.85,f.MFm.white)}`}),bt=(0,f.AHW)({display:"flex"}),vt=(0,d.Ng)((e=>{const{diagram:t,step:n}=e;return{step:n,hasUndo:(t?.edits.prev.length??0)>0,hasRedo:(t?.edits.next.length??0)>0,diagramName:t?.name}}),{onUndoClick:function(){return(e,t,{dataModelStorage:n})=>{e({type:Ce.UNDO_EDIT}),n.save(He(t()))}},onRedoClick:function(){return(e,t,{dataModelStorage:n})=>{e({type:Ce.REDO_EDIT}),n.save(He(t()))}},onExportClick:function(){return(e,t,{track:n})=>(n("Screen",{name:"export_diagram_modal"},void 0),e({type:_e}))},onAddCollectionsFromDatabaseClick:function(){return async(e,t,{connections:n,instanceManager:a,logger:r,track:i})=>{const{diagram:o}=t();if(!o)return;const s=o.name,l=o.connectionId||void 0,c=o.database,d=je(t()).collections.map((e=>(0,y.Ay)(e.ns).collection));i("Data Modeling Add DB Collections Modal Opened",{});try{const t=n.getConnectionById(l||"");if(!l||!t||"connected"!==t.status)return void e({type:Xe,step:"SELECT_CONNECTION",diagramName:s,selectedConnectionId:l,selectedDatabase:c,selectedCollections:d,databaseCollections:[]});if(!(await pt(l,n,a)).some((e=>e===c)))throw new Error("The selected database does not exist on this connection.");const r=await mt(l,c,n,a);e({type:Xe,step:"SELECT_COLLECTIONS",diagramName:s,selectedConnectionId:l,selectedDatabase:c,selectedCollections:d,databaseCollections:r})}catch(t){r.log.error(r.mongoLogId(1001000387),"DataModeling","Failed to find the database",{err:t}),e({type:Xe,step:"SELECT_CONNECTION",diagramName:s,selectedConnectionId:l,selectedDatabase:c,selectedCollections:d,databaseCollections:[],error:t})}}}})((({step:e,diagramName:t,hasUndo:n,onUndoClick:i,hasRedo:o,diagramEditorHasFocus:s,onRedoClick:l,onExportClick:c,onRelationshipDrawingToggle:d,onAddCollectionClick:u,onAddCollectionsFromDatabaseClick:p,isInRelationshipDrawingMode:m})=>{const g=(0,f.D27)(),{openDataModelingWorkspace:h}=(0,qe.$L)(),[y,b]=(0,a.useState)(!1),v=(0,a.useMemo)((()=>[{name:"diagrams",onClick:()=>h()},{name:t||"untitled"}]),[t,h]),[x,E]=(0,a.useMemo)((()=>H(i)),[i]),[C,w]=(0,a.useMemo)((()=>H(l)),[l]);return(0,f.vCs)("mod+z",x,{enabled:"EDITING"===e},[x]),(0,f.vCs)("mod+shift+z",C,{enabled:"EDITING"===e},[C]),(0,f.vCs)("mod+y",C,{enabled:"EDITING"===e},[C]),(0,Ze.l)({roles:s?{undo:E,redo:w}:{}}),"EDITING"!==e?null:r().createElement("div",null,r().createElement(f.BIu,{className:ht,items:v}),r().createElement("div",{className:(0,f.cx)(ft,g&&yt),"data-testid":"diagram-editor-toolbar"},r().createElement("div",{className:bt},r().createElement(f.m_M,{trigger:r().createElement(f.K0,{"aria-label":"Undo",disabled:!n,onClick:i},r().createElement(f.Int,{glyph:"Undo"}))},"Undo"),r().createElement(f.m_M,{trigger:r().createElement(f.K0,{"aria-label":"Redo",disabled:!o,onClick:l},r().createElement(f.Int,{glyph:"Redo"}))},"Redo"),r().createElement(f.W1t,{align:"bottom",justify:"start",open:y,setOpen:b,"data-testid":"add-collection-menu",trigger:({onClick:e})=>r().createElement(f.m_M,{trigger:r().createElement(f.K0,{"aria-label":"Add Collection",onClick:e},r().createElement(Ue,null))},"Add or select collections from the database")},r().createElement(f.Drp,{"data-testid":"add-new-collection",onClick:()=>{b(!1),u()}},"Add a new Collection"),r().createElement(f.Drp,{"data-testid":"select-from-database",onClick:()=>{b(!1),p()}},"Select from database")),r().createElement(f.m_M,{trigger:r().createElement(f.K0,{"aria-label":m?"Exit Relationship Drawing Mode":"Add Relationship",onClick:d,active:m,"aria-pressed":m},r().createElement(f.Int,{glyph:"Relationship"}))},"Add a relationship by dragging from one collection to another")),r().createElement("div",{className:bt},r().createElement(f.m_M,{trigger:r().createElement(f.$nd,{size:"xsmall","aria-label":"Export",onClick:c},r().createElement(f.Int,{glyph:"Export"}))},"Export data model"))))})),xt=(0,f.AHW)({paddingTop:f.YKD[600]}),Et=(0,f.AHW)({display:"flex",flexDirection:"column",gap:f.YKD[300]}),Ct=(0,f.AHW)({display:"flex",gap:f.YKD[200],"> svg":{marginTop:f.YKD[50]}}),wt=(0,f.AHW)({display:"flex",justifyContent:"flex-end",gap:f.YKD[200]}),It=(0,d.Ng)((e=>{const{exportDiagram:{isExporting:t,isModalOpen:n,exportFormat:a}}=e;return{isModalOpen:n,isExporting:t,exportFormat:a}}),{onCloseClick:function(){return(e,t,{cancelExportControllerRef:n})=>{n.current?.abort(),e({type:$e})}},onSelectFormat:function(e){return{type:Ye,format:e}},onExportDiagram:function(e){return async(t,n,{track:a,cancelExportControllerRef:i})=>{const{exportDiagram:{exportFormat:o,isExporting:s},diagram:l}=n();if(l&&!s&&o)try{t({type:Ke});const s=i.current=new AbortController;if("json"===o){const e=je(n());!function(e,t){const n=function({collections:e,relationships:t}){return{collections:Object.fromEntries(e.map((e=>{const{ns:t,fieldData:n,...a}=e;return[t,{ns:t,jsonSchema:j(n)}]}))),relationships:t}}(t),a=new Blob([JSON.stringify(n,null,2)],{type:"application/json"}),r=window.URL.createObjectURL(a);ue(r,e,(()=>{window.URL.revokeObjectURL(r)}))}(l.name,e)}else if("png"===o)await async function(e,t,n){const a=await(0,de.kk)(function(e){return new Promise(((t,n)=>{const a=(0,f.JoD)(e.getNodes()),i=document.createElement("div");i.setAttribute("data-testid","export-diagram-container"),i.style.position="fixed",i.style.top="100vh",i.style.left="100vw",i.style.width=`${a.width}px`,i.style.height=`${a.height}px`,document.body.appendChild(i);const{nodes:o,edges:s}=function(e){const t=e.getEdges().map((e=>({...e,selected:!1,animated:!1})));return{nodes:e.getNodes().map((e=>({...e,selected:!1,fields:e.fields.map((e=>({...e,variant:void 0,selected:!1})))}))),edges:t}}(e);le().render(r().createElement(f.Fp_,null,r().createElement(f.yFB,{edges:s,nodes:o,onlyRenderVisibleElements:!1})),i,(()=>{(0,f.Rbc)((()=>{const e=i.querySelector(".react-flow__viewport");if(!e)return document.body.removeChild(i),n(new Error("Diagram element not found"));const r=(0,f.R4u)(a,a.width,a.height,.5,2,`${f.YKD[400]}px`);!function(e,t){const n=e.querySelector("svg defs");n&&(t.querySelectorAll("svg").forEach((e=>{if(0!==e.querySelectorAll("path[marker-end], path[marker-start]").length){const t=n.cloneNode(!0);e.insertBefore(t,e.firstChild)}})),n.remove())}(i,e),(0,f.Rbc)((()=>{(0,ce.$E)(e,{backgroundColor:"#fff",pixelRatio:2,width:a.width,height:a.height,style:{width:`${a.width}px`,height:`${a.height}px`,transform:`translate(${r.x}px, ${r.y}px) scale(${r.zoom})`},filter:e=>!e.classList?.contains("node-add-field-button")}).then(t).catch(n).finally((()=>{document.body.removeChild(i)}))}))}))}))}))}(t),n??(new AbortController).signal);ue(a,e)}(l.name,e,s.signal);else{if("diagram"!==o)throw new Error(`Unsupported export format: ${o}`);!function(e,t,n){const a=new Blob([JSON.stringify(he(e,t,n),null,2)],{type:"application/json"}),r=window.URL.createObjectURL(a);ue(r,`${e}.mdm`,(()=>{window.URL.revokeObjectURL(r)}))}(l.name,l.edits.current,l.database)}a("Data Modeling Diagram Exported",{format:o})}catch(e){(0,de.nc)(e)||(0,f.c3r)("export-diagram-error",{variant:"warning",title:"Export failed",description:`An error occurred while exporting the diagram: ${e.message}`})}finally{i.current=null,t({type:Ge})}}}})((({isModalOpen:e,isExporting:t,exportFormat:n,onExportDiagram:a,onSelectFormat:i,onCloseClick:o})=>{const s=(0,f.rNO)();return r().createElement(f.aFV,{open:e,setOpen:o,"data-testid":"export-diagram-modal"},r().createElement(f.rQ0,{title:"Export data model"}),r().createElement(f.cwr,{className:xt},r().createElement("div",{className:Et},r().createElement(f.JU7,{htmlFor:""},"Select file format:"),r().createElement(f.z6M,{className:Et,value:n},r().createElement("div",{className:Ct},r().createElement(f.Int,{glyph:"Diagram"}),r().createElement(f.sxL,{checked:"diagram"===n,value:"diagram","aria-label":"MDM File",onClick:()=>i("diagram"),size:"small",description:"Importable into Compass and Data Explorer so teammates can collaborate."},"MDM File")),r().createElement("div",{className:Ct},r().createElement(f.x4h,null),r().createElement(f.sxL,{checked:"png"===n,value:"png","aria-label":"PNG",onClick:()=>i("png"),size:"small",description:"Shareable image for documentation or presentations."},"PNG")),r().createElement("div",{className:Ct},r().createElement(f.Int,{glyph:"CurlyBraces"}),r().createElement(f.sxL,{checked:"json"===n,value:"json","aria-label":"JSON",onClick:()=>i("json"),size:"small",description:"Raw schema data for programmatic use."},"JSON"))))),r().createElement(f.jlY,{className:wt},r().createElement(f.$nd,{variant:"default",onClick:o,"data-testid":"cancel-button"},"Cancel"),r().createElement(f.$nd,{variant:"primary",onClick:()=>a(s),"data-testid":"export-button",disabled:!n,loadingIndicator:r().createElement(f.Q0K,null),isLoading:t},"Export")))})),St=(0,f.AHW)({borderBottom:`1px solid ${f.MFm.gray.light2}`,padding:f.YKD[400]}),At=(0,f.AHW)({borderBottom:`1px solid ${f.MFm.gray.dark2}`}),kt=(0,f.AHW)({width:"100%",textTransform:"uppercase","&:not(:last-child)":{marginBottom:f.YKD[400]}}),Dt=(0,f.AHW)({width:"100%",display:"flex",alignItems:"center"}),Nt=({label:e,children:t})=>{const n=(0,f.D27)();return r().createElement("div",{className:(0,f.cx)(St,n&&At)},r().createElement(f.nD3,{text:e,defaultOpen:!0,textClassName:kt,buttonTextClassName:Dt,size:"small"},t))},Mt=(0,f.AHW)({marginBottom:f.YKD[400],marginTop:f.YKD[400],"&:first-child":{marginTop:0},"&:last-child":{marginBottom:0}}),Tt=({className:e,...t})=>r().createElement(f.GEW,(0,u.A)({},t,{className:(0,f.cx)(Mt,e)}));function Pt(e,t){const[n,r]=(0,a.useState)(e);return(0,f.wTI)((()=>{r(e)}),[e]),{value:n,onChange:e=>{r(e.currentTarget.value)},onBlur:()=>{t(n)},onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||e.target.blur?.()}}}function Lt(e){const[t,n]=e;let a="",r="";return t.ns&&(a+=(0,y.Ay)(t.ns).collection,t.fields&&t.fields.length&&(a+=`.${t.fields.join(".")}`)),n.ns&&(r+=(0,y.Ay)(n.ns).collection,n.fields&&n.fields.length&&(r+=`.${n.fields.join(".")}`)),[a,r].join(" → ").trim()}const Ot=(0,f.AHW)({marginLeft:"auto",maxHeight:20,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),Rt=(0,f.AHW)({color:f.MFm.gray.dark1}),Ht=(0,f.AHW)({display:"flex",flexDirection:"column",gap:f.YKD[200]}),Ft=(0,f.AHW)({display:"flex",alignItems:"center"}),Wt=(0,f.AHW)({flexGrow:1,minWidth:0,display:"flex",alignItems:"center",gap:f.YKD[100],paddingRight:f.YKD[200]}),jt=(0,f.AHW)({overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),Bt=(0,f.AHW)({display:"flex",color:f.MFm.yellow.dark2}),zt=(0,f.AHW)({color:f.MFm.yellow.light2}),_t=(0,f.AHW)({marginTop:f.YKD[400]}),$t=({relationships:e,emptyMessage:t,onCreateNewRelationshipClick:n,onEditRelationshipClick:a,onDeleteRelationshipClick:i})=>{const o=(0,f.D27)();return r().createElement(Nt,{label:r().createElement(r().Fragment,null,"Relationships ",r().createElement(f.Exy,null,e.length),r().createElement(f.$nd,{className:Ot,size:"xsmall",onClick:n},"Add Relationship"))},r().createElement("div",{className:_t},e.length?r().createElement("ul",{className:Ht},e.map((e=>{const t=Lt(e.relationship);return r().createElement("li",{key:e.id,"data-relationship-id":e.id,className:Ft},r().createElement("div",{className:Wt},r().createElement("span",{className:jt,title:t},t),!W(e)&&r().createElement(f.m_M,{trigger:r().createElement("div",{className:(0,f.cx)(Bt,o&&zt)},r().createElement(f.Int,{glyph:"Warning"}))},"Cannot resolve the relationship - please verify the linked fields and namespace.")),r().createElement(f.K0,{"aria-label":"Edit relationship",title:"Edit relationship",onClick:()=>{a(e.id)}},r().createElement(f.Int,{glyph:"Edit"})),r().createElement(f.K0,{"aria-label":"Delete relationship",title:"Delete relationship",onClick:()=>{i(e.id)}},r().createElement(f.Int,{glyph:"Trash"})))}))):r().createElement("div",{className:Rt},t)))};function Yt({newName:e,existingNames:t,currentName:n,entity:a}){if(0===e.trim().length)return{isValid:!1,errorMessage:`${a} name cannot be empty.`};const r=t.filter((e=>e!==n)).some((t=>t.trim()===e.trim()));return{isValid:!r,errorMessage:r?`${a} name must be unique.`:void 0}}const Kt=(0,d.Ng)(((e,t)=>{const n=je(e),a=n.collections.find((e=>e.ns===t.namespace));if(!a)throw new Error("Namespace not found in model: "+t.namespace);return{note:a.note,namespace:a.ns,isDraftCollection:e.diagram?.draftCollection===t.namespace,collections:n.collections,relationships:F(t.namespace,n.relationships)}}),{onCreateNewRelationshipClick:Ae,onEditRelationshipClick:Se,onDeleteRelationshipClick:Me,onNoteChange:function(e,t){return De({type:"UpdateCollectionNote",ns:e,note:t})},onRenameCollection:function(e,t){return De({type:"RenameCollection",fromNS:e,toNS:t})}})((({namespace:e,collections:t,note:n="",relationships:i,isDraftCollection:o,onCreateNewRelationshipClick:s,onEditRelationshipClick:l,onDeleteRelationshipClick:c,onNoteChange:d,onRenameCollection:p})=>{const m=(0,a.useMemo)((()=>t.map((e=>e.ns))),[t]),{value:g,...h}=Pt((0,y.Ay)(e).collection,(t=>{const n=t.trim();b&&(o||n!==(0,y.Ay)(e).collection)&&p(e,`${(0,y.Ay)(e).database}.${n}`)})),{isValid:b,errorMessage:v}=(0,a.useMemo)((()=>Yt({newName:g,existingNames:m.map((e=>(0,y.Ay)(e).collection)),currentName:(0,y.Ay)(e).collection,entity:"Collection"})),[g,m,e]),x=Pt(n,(t=>{d(e,t)})),E=(0,a.useRef)(null);return(0,a.useEffect)((()=>{o&&E.current?.focus()}),[o]),r().createElement(r().Fragment,null,r().createElement(Nt,{label:"Collection properties"},r().createElement(Tt,null,r().createElement(f.ksK,(0,u.A)({ref:E,label:"Name","data-testid":"data-model-collection-drawer-name-input",sizeVariant:"small",value:g},h,{state:b?void 0:"error",errorMessage:v})))),r().createElement($t,{relationships:i,emptyMessage:"This collection does not have any relationships yet.",onCreateNewRelationshipClick:()=>{s({localNamespace:e})},onEditRelationshipClick:l,onDeleteRelationshipClick:c}),r().createElement(Nt,{label:"Notes"},r().createElement(Tt,null,r().createElement(f.fs1,(0,u.A)({label:"","aria-label":"Notes"},x)))))})),Gt="~~##$$##~~",Vt=(0,f.AHW)({display:"flex",justifyContent:"space-between",gap:f.YKD[100]}),Ut=(0,f.AHW)({color:f.MFm.gray.base,fontWeight:"bold"}),qt=(0,f.AHW)({marginTop:f.YKD[400],display:"flex",gap:f.YKD[200]}),Zt=(0,f.AHW)({marginTop:f.YKD[100]}),Jt=(0,f.AHW)({"button .hidden-cardinality-option-label":{display:"none"}}),Qt=[{tag:"One",label:"1",value:1},{tag:"Many",label:"N/A",value:null},{tag:"Many",label:"100",value:100},{tag:"Many",label:"1000",value:1e3},{tag:"Many",label:"10000+",value:1e4}],Xt=({label:e,value:t,onChange:n})=>r().createElement(f.l6P,{size:"small",label:e,value:String(t??"null"),allowDeselect:!1,onChange:e=>n("null"===e?null:Number(e)),className:Jt},Qt.map((({tag:e,value:t,label:n})=>r().createElement(f.c$x,{key:String(t),value:String(t)},r().createElement("div",{className:Vt},e,r().createElement("span",{className:(0,f.cx)(Ut,null===t&&"hidden-cardinality-option-label")},n)))))),en=(0,f.AHW)({width:"100%",display:"grid",gridTemplateAreas:'\n "local foreign"\n ',gridTemplateColumns:"1fr 1fr",gap:f.YKD[400]}),tn=(0,f.AHW)({gridArea:"local"}),nn=(0,f.AHW)({gridArea:"foreign"}),an=(0,d.Ng)(((e,t)=>{const n=He(e),a=(r=n.edits,i=t.relationshipId,We(r).relationships.find((e=>e.id===i)));var r,i;if(!a)throw new Error(`Can not find relationship with ${t.relationshipId}`);return{relationship:a,fields:Be(n.edits)}}),{onRelationshipUpdate:function(e){return De({type:"UpdateRelationship",relationship:e})},onDeleteRelationshipClick:Me})((({relationshipId:e,relationship:t,fields:n,onRelationshipUpdate:i})=>{const o=(0,a.useMemo)((()=>Object.keys(n)),[n]),{localCollection:s,localField:l,localCardinality:c,foreignCollection:d,foreignField:p,foreignCardinality:m,onFieldChange:g,note:h}=function(e,t){const n=(0,f.HIF)(t),[r,i]=e.relationship;return{localCollection:r.ns??"",localField:r.fields?.join(Gt)??"",localCardinality:r.cardinality,foreignCollection:i.ns??"",foreignField:i.fields?.join(Gt)??"",foreignCardinality:i.cardinality,onFieldChange:(0,a.useCallback)((({key:t,value:a})=>{const r=(0,M.cloneDeep)(e);switch(t){case"localCollection":r.relationship[0].ns=a,r.relationship[0].fields=null;break;case"localField":r.relationship[0].fields=a.split(Gt);break;case"localCardinality":r.relationship[0].cardinality=a;break;case"foreignCollection":r.relationship[1].ns=a,r.relationship[1].fields=null;break;case"foreignField":r.relationship[1].fields=a.split(Gt);break;case"foreignCardinality":r.relationship[1].cardinality=a;break;case"note":r.note=a}n.current(r)}),[n,e]),note:e.note??""}}(t,i),b=Pt(h,(e=>{g({key:"note",value:e})})),v=(0,a.useMemo)((()=>n[s]??[]),[n,s]),x=(0,a.useMemo)((()=>n[d]??[]),[n,d]);return r().createElement("div",{"data-relationship-id":e},r().createElement(Nt,{label:"Relationship properties"},r().createElement("div",{className:en},r().createElement("div",{className:tn},r().createElement(Tt,null,r().createElement(f.G3_,{size:"small",label:"Local collection",value:s,onChange:e=>{e&&g({key:"localCollection",value:e})},multiselect:!1,clearable:!1},o.map((e=>r().createElement(f.jOs,{key:e,value:e,displayName:(0,y.Ay)(e).collection}))))),r().createElement(Tt,null,r().createElement(f.G3_,{size:"small",label:"Local field",value:l,onChange:e=>{e&&g({key:"localField",value:e})},multiselect:!1,clearable:!1},v.map((e=>r().createElement(f.jOs,{key:e.join("."),value:e.join(Gt),displayName:e.join(".")}))))),r().createElement(Tt,null,r().createElement(Xt,{label:"Local cardinality",value:c,onChange:e=>g({key:"localCardinality",value:e})}))),r().createElement("div",{className:nn},r().createElement(Tt,null,r().createElement(f.G3_,{size:"small",label:"Foreign collection",value:d,onChange:e=>{e&&g({key:"foreignCollection",value:e})},multiselect:!1,clearable:!1},o.map((e=>r().createElement(f.jOs,{key:e,value:e,displayName:(0,y.Ay)(e).collection}))))),r().createElement(Tt,null,r().createElement(f.G3_,{size:"small",label:"Foreign field",value:p,onChange:e=>{e&&g({key:"foreignField",value:e})},multiselect:!1,clearable:!1},x.map((e=>r().createElement(f.jOs,{key:e.join("."),value:e.join(Gt),displayName:e.join(".")}))))),r().createElement(Tt,null,r().createElement(Xt,{label:"Foreign cardinality",value:m,onChange:e=>g({key:"foreignCardinality",value:e})})))),r().createElement("div",{className:qt},r().createElement(f.Int,{glyph:"InfoWithCircle",className:Zt}),r().createElement("span",null,"Relationship cardinality can inform whether you embed or reference."," ",r().createElement(f.N_E,{href:"https://www.mongodb.com/docs/manual/applications/data-models-relationships"},"Learn more")))),r().createElement(Nt,{label:"Notes"},r().createElement(Tt,null,r().createElement(f.fs1,(0,u.A)({label:"","aria-label":"Notes"},b)))))}));var rn=n(183);const on=Object.keys(rn.BSONType),sn=(0,d.Ng)(((e,t)=>{const n=He(e),a=We(n.edits),r=a.collections.find((e=>e.ns===t.namespace))?.fieldData;if(!r)throw new Error("Collection not found");return{types:E({jsonSchema:r,fieldPath:t.fieldPath})?.fieldTypes??[],fieldPaths:Be(n.edits)[t.namespace],relationships:a.relationships.filter((({relationship:e})=>function(e,t,n){const[a,r]=e;return a.ns===t&&!!a.fields&&L(a.fields,n)||r.ns===t&&!!r.fields&&L(r.fields,n)}(e,t.namespace,t.fieldPath)))}}),{onCreateNewRelationshipClick:Ae,onEditRelationshipClick:Se,onDeleteRelationshipClick:Me,onRenameField:Le,onChangeFieldType:Re})((({namespace:e,fieldPath:t,fieldPaths:n,types:i,relationships:o,onCreateNewRelationshipClick:s,onEditRelationshipClick:l,onDeleteRelationshipClick:c,onRenameField:d,onChangeFieldType:p})=>{const[m,g]=(0,a.useState)(),[h,y]=(0,a.useState)(i);(0,f.wTI)((()=>{y(i)}),[i]);const{value:b,...v}=Pt(t[t.length-1],(n=>{const a=n.trim();a!==t[t.length-1]&&x&&d({ns:e,field:t,newName:a,source:"side_panel"})})),{isValid:x,errorMessage:E}=(0,a.useMemo)((()=>function(e,t,n){const a=n.trim();if(!a.length)return{isValid:!1,errorMessage:"Field name cannot be empty."};const r=t.filter((t=>t.length===e.length&&L(t.slice(0,t.length-1),e.slice(0,t.length-1))&&t[t.length-1]!==e[e.length-1])).map((e=>e[e.length-1])).some((e=>e===a));return{isValid:!r,errorMessage:r?"Field already exists.":void 0}}(t,n,b)),[t,n,b]),C=(0,a.useMemo)((()=>T(t)),[t]);return r().createElement(r().Fragment,null,r().createElement(Nt,{label:"Field properties"},r().createElement(Tt,null,r().createElement(f.ksK,(0,u.A)({label:"Field name",disabled:C,"data-testid":"data-model-collection-drawer-name-input",sizeVariant:"small",value:b},v,{state:x?void 0:"error",errorMessage:E}))),r().createElement(Tt,null,r().createElement(f.G3_,{"data-testid":"lg-combobox-datatype",label:"Datatype","aria-label":"Datatype",disabled:C,value:h,size:"small",multiselect:!0,clearable:!1,onChange:n=>{y(n),0!==n.length?(g(void 0),p({ns:e,fieldPath:t,newTypes:n,source:"side_panel"})):g("Field must have a type.")},state:m?"error":void 0,errorMessage:m},on.map((e=>r().createElement(f.jOs,{key:e,value:e})))))),r().createElement($t,{relationships:o,emptyMessage:"This field does not have any relationships yet.",onCreateNewRelationshipClick:()=>{s({localNamespace:e,localFields:t})},onEditRelationshipClick:l,onDeleteRelationshipClick:c}))}));var ln=n(36214);const cn=(0,f.AHW)({marginTop:f.YKD[400]}),dn=(0,f.AHW)({color:f.MFm.gray.dark1,display:"flex",gap:f.YKD[200],marginTop:f.YKD[800],svg:{marginTop:f.YKD[100]}}),un=(0,f.AHW)({color:f.MFm.gray.light1}),pn=(0,f.AHW)({fontWeight:"bold",color:f.MFm.gray.base}),mn=({label:e,children:t})=>r().createElement("div",null,r().createElement("span",{className:pn},e)," ",t),gn=new Intl.DateTimeFormat(void 0,{weekday:"short",year:"numeric",month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit",timeZoneName:"short"}),hn=e=>gn.format(new Date(e).getTime()),fn=(0,d.Ng)((e=>{if(!e.diagram)throw new Error("No diagram selected");return{diagramId:e.diagram.id,diagramName:e.diagram.name,createdAt:e.diagram.createdAt,updatedAt:e.diagram.updatedAt,connectionId:e.diagram.connectionId??void 0,database:e.diagram.database}}),{onRenameDiagram:function(e,t){return{type:Ce.RENAME_DIAGRAM,id:e,name:t}}})((({diagramId:e,diagramName:t,createdAt:n,updatedAt:i,connectionId:o,database:l,onRenameDiagram:c})=>{const d=(0,f.D27)(),p=(0,s.Gv)(o),{items:m}=(0,ln.U5)(),g=(0,a.useMemo)((()=>m.map((e=>e.name))),[m]),{value:h,...y}=Pt(t,(n=>{const a=n.trim();b&&a!==t&&c(e,a)})),{isValid:b,errorMessage:v}=(0,a.useMemo)((()=>Yt({newName:h,existingNames:g,currentName:t,entity:"Diagram"})),[h,t,g]);return r().createElement(r().Fragment,null,r().createElement(Nt,{label:"Model"},r().createElement(Tt,null,r().createElement(f.ksK,(0,u.A)({label:"Diagram name","data-testid":"data-model-overview-drawer-name-input",sizeVariant:"small",value:h},y,{state:b?void 0:"error",errorMessage:v}))),r().createElement("div",{className:cn},r().createElement(f.JU7,{as:"div",htmlFor:""},"Generated"),r().createElement(mn,{label:"From"},p?`${p.title}.${l}`:l),r().createElement(mn,{label:"At"},hn(n))),r().createElement("div",{className:cn},r().createElement(f.JU7,{as:"div",htmlFor:""},"Last updated"),r().createElement(mn,{label:"At"},hn(i))),r().createElement("div",{className:(0,f.cx)(dn,d&&un)},r().createElement(f.Int,{glyph:"InfoWithCircle"}),r().createElement("span",null,"This diagram was generated based on a sample of documents. Changes made to the diagram will not impact your data."))))})),yn="data-modeling-drawer",bn=(0,f.AHW)({display:"flex",width:"100%"}),vn=(0,f.AHW)({flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),xn=(0,f.AHW)({marginRight:f.YKD[200]}),En=e=>(0,y.Ay)(e).collection,Cn=(0,d.Ng)((e=>{const t=!!e.diagram,n=e.diagram?.selectedItems;if(!t||!n)return{hasDiagram:t,selectedItems:null};const a=je(e);if("collection"===n.type)return a.collections.find((e=>e.ns===n.id))?{hasDiagram:t,selectedItems:{...n,title:En(n.id)}}:{hasDiagram:t,selectedItems:null};if("relationship"===n.type){const e=a.relationships.find((e=>e.id===n.id));return e?{hasDiagram:t,selectedItems:{...n,title:Lt(e.relationship)}}:{hasDiagram:t,selectedItems:null}}if("field"===n.type){const e=a.collections.find((e=>e.ns===n.namespace));return E({jsonSchema:e?.fieldData??{},fieldPath:n.fieldPath})?{hasDiagram:t,selectedItems:{...n,title:`${En(n.namespace)}.${n.fieldPath.join(".")}`}}:{hasDiagram:t,selectedItems:null}}}),{onDeleteCollection:Te,onDeleteRelationship:Me,onDeleteField:Pe})((function({selectedItems:e,hasDiagram:t,onDeleteCollection:n,onDeleteRelationship:i,onDeleteField:o}){const{content:s,label:l,actions:c,title:d,handleAction:u}=(0,a.useMemo)((()=>t?"collection"===e?.type?{title:e.title,label:"Collection Configuration",content:r().createElement(Kt,{key:e.id,namespace:e.id}),actions:[{action:"delete",label:"Delete Collection",icon:"Trash"}],handleAction:t=>{"delete"===t&&n(e.id)}}:"relationship"===e?.type?{title:e.title,label:"Relationship Configuration",content:r().createElement(an,{key:e.id,relationshipId:e.id}),actions:[{action:"delete",label:"Delete",icon:"Trash"}],handleAction:t=>{"delete"===t&&i(e.id)}}:"field"===e?.type?{title:e.title,label:"Field Configuration",content:r().createElement(sn,{key:`${e.namespace}.${JSON.stringify(e.fieldPath)}`,namespace:e.namespace,fieldPath:e.fieldPath}),actions:[...T(e.fieldPath)?[]:[{action:"delete",label:"Delete Field",icon:"Trash"}]],handleAction:t=>{"delete"===t&&o(e.namespace,e.fieldPath)}}:{title:"Data Model Overview",label:"Data Model Overview",content:r().createElement(fn,null)}:{content:null}),[t,e,n,i,o]);return s?r().createElement(f.TmU,{id:yn,title:r().createElement("div",{className:bn},r().createElement("span",{className:vn,title:d},d),c&&c.length>0&&r().createElement(f.eDW,{actions:c,"data-testid":"data-modeling-drawer-actions",onAction:u,className:xn,collapseAfter:c.length>1?0:1})),label:l,glyph:"Wrench",autoOpen:!0},s):null})),wn=(0,d.Ng)((e=>{const t=e.analysisProgress;return{step:t.step,sampledCollections:t.samplesFetched,analyzedCollections:t.schemasAnalyzed,collectionRelationsInferred:t.collectionRelationsInferred,totalCollections:t.currentAnalysisOptions?.collections.length??0}}),{onCancelClick:function(){return(e,t,{cancelAnalysisControllerRef:n})=>{n.current?.abort(),n.current=null}}})((({step:e,sampledCollections:t,analyzedCollections:n,collectionRelationsInferred:a,totalCollections:i,onCancelClick:o})=>{const s=(0,f.D27)();return r().createElement(f.vA_,(0,u.A)({darkMode:s,variant:"success",cancelText:"Cancel",onCancel:o,description:"This might take a few minutes."},function({step:e,sampledCollections:t,analyzedCollections:n,collectionRelationsInferred:a,totalCollections:r}){return"SAMPLING"===e?{isIndeterminate:!1,label:"Sampling collections…",maxValue:r,value:t,formatValue:"fraction"}:"ANALYZING_SCHEMA"===e?{isIndeterminate:!1,label:"Analyzing collection schemas…",maxValue:r,value:n,formatValue:"fraction"}:"INFERRING_RELATIONSHIPS"===e?{isIndeterminate:!1,label:"Inferring relationships between collections…",maxValue:r,value:a,formatValue:void 0}:{isIndeterminate:!0,label:"Preparing diagram…"}}({step:e,sampledCollections:t,analyzedCollections:n,collectionRelationsInferred:a,totalCollections:i})))})),In=(0,f.AHW)({margin:f.YKD[200],"& > div":{display:"flex",alignItems:"center"}}),Sn=(0,f.AHW)({marginLeft:"auto"}),An=(0,f.AHW)({"[data-nodeid] + div > div > div:first-child > div:nth-child(2)":{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}),kn=({children:e,onRetryClick:t})=>r().createElement(f.lZ$,{variant:"danger",className:In},r().createElement("div",null,e),r().createElement(f.$nd,{className:Sn,size:"xsmall",onClick:t},"Retry")),Dn=(0,f.AHW)({display:"grid",gridTemplateColumns:"100%",gridTemplateRows:"1fr auto",gap:2,height:"100%"}),Nn=(0,f.AHW)({minHeight:0,".connectablestart":{userSelect:"none"}}),Mn=(0,f.AHW)({display:"contents"}),Tn={maxZoom:1,minZoom:.25},Pn={zoomable:!0,pannable:!0},Ln=(0,d.Ng)((e=>{const{diagram:t}=e,n=t?je(e):null;return{model:n,diagramLabel:t?.name||"Schema Preview",selectedItems:e.diagram?.selectedItems??null,newCollection:t?.draftCollection,database:n?.collections[0]?.ns?(0,y.Ay)(n.collections[0].ns).database:null}}),{onAddNewFieldToCollection:function(e,t){return(n,a,{track:r})=>{const i=je(a()).collections.find((t=>t.ns===e));if(!i)throw new Error("Collection to add field to not found");const o={type:"AddField",ns:e,field:[Q(i.fieldData)],jsonSchema:{bsonType:"string"}};return r("Data Modeling Field Added",{source:t}),n(De(o))}},onAddFieldToObjectField:function(e,t,n){return(a,r,{track:i})=>{const o=je(r()).collections.find((t=>t.ns===e));if(!o)throw new Error("Collection to add field to not found");const s={type:"AddField",ns:e,field:[...t,Q(o.fieldData,t)],jsonSchema:{bsonType:"string"}};return i("Data Modeling Field Added",{source:n}),a(De(s))}},onMoveCollection:function(e,t){return De({type:"MoveCollection",ns:e,newPosition:t})},onMoveMultipleCollections:function(e){return De({type:"MoveMultipleCollections",newPositions:e})},onCollectionSelect:function(e){return{type:Ce.COLLECTION_SELECTED,namespace:e}},onRelationshipSelect:Se,onFieldSelect:function(e,t){return{type:Ce.FIELD_SELECTED,namespace:e,fieldPath:t}},onRenameField:Le,onChangeFieldType:Re,onDiagramBackgroundClicked:function(){return{type:Ce.DIAGRAM_BACKGROUND_SELECTED}},onCreateNewRelationship:Ae,onDeleteCollection:Te,onDeleteRelationship:Me,onDeleteField:Pe,onToggleCollectionExpanded:function(e,t){return De({type:"ToggleExpandCollection",ns:e,expanded:t})},onToggleFieldExpanded:function(e,t){return De({type:"ToggleExpandField",ns:e,field:t})}})((({diagramLabel:e,model:t,isInRelationshipDrawingMode:n,newCollection:i,onAddFieldToObjectField:s,onAddNewFieldToCollection:l,onMoveCollection:c,onMoveMultipleCollections:d,onCollectionSelect:p,onRelationshipSelect:m,onFieldSelect:g,onRenameField:h,onChangeFieldType:b,onDiagramBackgroundClicked:v,onCreateNewRelationship:x,onRelationshipDrawn:E,onDeleteCollection:C,onDeleteRelationship:w,onDeleteField:I,selectedItems:S,DiagramComponent:A=f.yFB,onToggleCollectionExpanded:k,onToggleFieldExpanded:D})=>{const N=(0,f.D27)(),M=(0,o.Fg)("enableDataModelingCollapse"),T=(0,a.useRef)((0,f.rNO)()),{openDrawer:P}=(0,f.u6F)(),{isDrawerOpen:L}=(0,f.YUc)(),O=(0,a.useCallback)((e=>{e&&(e._diagram=T.current)}),[]),R=(0,a.useMemo)((()=>{const e=((e,t)=>{if(!e||"relationship"!==e.type)return B;const{id:n}=e,{relationship:a}=t?.find((e=>e.id===n))??{},r=Object.create(null);return a?.[0].ns&&a?.[0].fields&&(r[a[0].ns]=[a[0].fields]),a?.[1].ns&&a?.[1].fields&&(r[a[1].ns]||(r[a[1].ns]=[]),r[a[1].ns].push(a[1].fields)),r})(S,t?.relationships);return(t?.collections??[]).map((a=>{const r=!!S&&"collection"===S.type&&S.id===a.ns,i=F(a.ns,t?.relationships);return function({ns:e,fieldData:t,displayPosition:n,selectedField:a,highlightedFields:r,selected:i,isInRelationshipDrawingMode:o,relationships:s}){let l;return s.some((e=>!W(e)))&&(l={type:"warn",warnMessage:"One or more relationships cannot be resolved."}),{id:e,type:"collection",position:{x:n[0],y:n[1]},title:(0,y.Ay)(e).collection,fields:K({fieldData:t,highlightedFields:r[e]??void 0,selectedField:a}),selected:i,connectable:o,draggable:!o,variant:l}}({...a,highlightedFields:e,selectedField:"field"===S?.type&&S.namespace===a.ns?S.fieldPath:void 0,selected:r,isInRelationshipDrawingMode:n,relationships:i})}))}),[t?.collections,t?.relationships,S,n]),H=(0,a.useMemo)((()=>(t?.relationships??[]).map((e=>V(e,!!S&&"relationship"===S.type&&S.id===e.id)))),[t?.relationships,S]);(0,a.useEffect)((()=>(0,f.Rbc)((()=>{T.current.fitView()}))),[]);const j=(0,a.useRef)(!1);(0,a.useEffect)((()=>{const e=j.current;if(j.current=!!L,!i)return;const t=R.find((e=>e.id===i));if(!t)return;const n=e?0:240,a=T.current.getViewport().zoom,r=n/a;return(0,f.Rbc)((()=>{T.current.setCenter(t.position.x+122+r,t.position.y+32,{duration:500,zoom:a})}))}),[i,R,L]);const z=(0,a.useCallback)(((e,t)=>{x({localNamespace:e,foreignNamespace:t}),E(),P(yn)}),[E,x,P]),_=(0,a.useCallback)(((e,t)=>{"collection"===t.type&&(p(t.id),P(yn))}),[p,P]),$=(0,a.useCallback)(((e,t)=>{m(t.id),P(yn)}),[m,P]),Y=(0,a.useCallback)(((e,{id:t,nodeId:n})=>{const a=Array.isArray(t)?t:"string"==typeof t?[t]:void 0;a&&(e.stopPropagation(),g(n,a),P(yn))}),[g,P]),G=(0,a.useCallback)(((e,t,n)=>{if(1===n.length)c(t.id,[t.position.x,t.position.y]);else{const e=Object.fromEntries(n.map((e=>[e.id,[e.position.x,e.position.y]])));d(e)}}),[c,d]),U=(0,a.useCallback)((()=>{v()}),[v]),q=(0,a.useCallback)((({source:e,target:t})=>{z(e,t)}),[z]),Z=(0,a.useCallback)(((e,t)=>{e.stopPropagation(),l(t,"diagram")}),[l]),J=(0,a.useCallback)(((e,t,n)=>{s(t,n,"diagram")}),[s]),Q=(0,a.useCallback)(((e,t,n)=>{b({ns:e,fieldPath:t,newTypes:n,source:"diagram"})}),[b]),X=(0,a.useCallback)((()=>{switch(S?.type){case"collection":C(S.id);break;case"relationship":w(S.id);break;case"field":I(S.namespace,S.fieldPath)}}),[S,C,w,I]);(0,f.vCs)("Backspace",X,[X]),(0,f.vCs)("Delete",X,[X]),(0,f.vCs)("Escape",(()=>{v()}),[v]);const ee=(0,a.useCallback)(((e,t,n)=>{e.preventDefault(),e.stopPropagation(),k(t,n)}),[k]),te=(0,a.useCallback)(((e,t,n)=>{e.preventDefault(),e.stopPropagation(),D(t,n)}),[D]),ne=(0,a.useMemo)((()=>({isDarkMode:N,title:e,edges:H,nodes:R,zoomOnScroll:!1,zoomOnPinch:!0,panOnScroll:!0,onAddFieldToNodeClick:Z,onAddFieldToObjectFieldClick:J,onNodeClick:_,onPaneClick:U,onEdgeClick:$,onFieldClick:Y,onFieldNameChange:(e,t,n)=>h({ns:e,field:t,newName:n,source:"diagram"}),onFieldTypeChange:Q,onNodeDragStop:G,onConnect:q,onNodeExpandToggle:M?ee:void 0,onFieldExpandToggle:M?te:void 0,fieldTypes:on})),[N,e,H,R,Z,J,_,U,$,Y,h,Q,G,q,ee,te,M]),ae=(0,f.EqB)(ne);return r().createElement("div",{ref:O,className:Dn,"data-testid":"diagram-editor-container"},r().createElement("div",{className:Nn,"data-testid":"model-preview"},r().createElement(A,(0,u.A)({},ae,{nodeDragThreshold:5,minimapProps:Pn,fitViewOptions:Tn,className:An}))))})),On=(0,d.Ng)((e=>{const{diagram:t,step:n}=e;return{step:n,diagramId:t?.id}}),{onRetryClick:function(){return(e,t)=>{const{currentAnalysisOptions:n}=t().analysisProgress;if(!n)return null;const{name:a,connectionId:r,database:i,collections:o,automaticallyInferRelations:s,samplingOptions:l}=n;e(ae(a,r,i,o,{automaticallyInferRelations:s,samplingOptions:l}))}},onAddCollectionClick:function(e,t){return(n,a,{track:r})=>{const i=a(),o=He(i).database,s=je(i).collections;e||(e=function(e,t){const n=`${e}.new-collection`;let a=1,r=n;for(;t.some((e=>e.ns===r));)r=`${n}-${a}`,a++;return r}(o,s)),t||(t=function(e,t){const n=e.map((e=>G(e))),a=G({ns:t.ns,fieldData:t.fieldData,displayPosition:[0,0]}),r=(0,f.LP5)(n,a);return[r.x,r.y]}(s,{ns:e,fieldData:{},indexes:[]})),r("Data Modeling Collection Added",{source:"toolbar"}),n(De({type:"AddCollection",ns:e,initialSchema:{bsonType:"object",properties:{_id:{bsonType:"objectId"}},required:["_id"]},position:t}))}}})((({step:e,diagramId:t,onRetryClick:n,onAddCollectionClick:i,DiagramComponent:o=f.yFB})=>{const{openDrawer:s}=(0,f.u6F)();let l;const[c,d]=(0,a.useState)(!1),p=(0,a.useCallback)((()=>{d((e=>!e))}),[]),m=(0,a.useCallback)((()=>{d(!1)}),[]),g=(0,a.useCallback)((()=>{i(),s(yn)}),[s,i]),[h,y]=(0,f.Ely)();return"NO_DIAGRAM_SELECTED"===e?null:("ANALYZING"===e&&(l=r().createElement(wn,null)),"ANALYSIS_FAILED"===e&&(l=r().createElement(kn,{onRetryClick:n},"Analysis canceled")),"ANALYSIS_CANCELED"===e&&(l=r().createElement(kn,{onRetryClick:n},"Analysis canceled")),"EDITING"===e&&t&&(l=r().createElement(Ln,{key:t,isInRelationshipDrawingMode:c,onRelationshipDrawn:m,DiagramComponent:o})),r().createElement("div",(0,u.A)({className:Mn},h),r().createElement(f.XvC,{toolbar:r().createElement(vt,{diagramEditorHasFocus:y!==f.X1w.NoFocus,onRelationshipDrawingToggle:p,isInRelationshipDrawingMode:c,onAddCollectionClick:g})},l,r().createElement(It,null))))})),Rn="data-modeling/generate-diagram-wizard/GOTO_STEP",Hn="data-modeling/generate-diagram-wizard/CREATE_NEW_DIAGRAM",Fn="data-modeling/generate-diagram-wizard/CANCEL_CREATE_NEW_DIAGRAM",Wn="data-modeling/generate-diagram-wizard/CHANGE_NAME",jn="data-modeling/generate-diagram-wizard/INVALID_NAME",Bn="data-modeling/generate-diagram-wizard/SELECT_CONNECTION",zn="data-modeling/generate-diagram-wizard/CONNECTION_CONNECTED",_n="data-modeling/generate-diagram-wizard/DATABASES_FETCHED",$n="data-modeling/generate-diagram-wizard/CONNECTION_FAILED",Yn="data-modeling/generate-diagram-wizard/SELECT_DATABASE",Kn="data-modeling/generate-diagram-wizard/DATABASES_FETCH_FAILED",Gn="data-modeling/generate-diagram-wizard/COLLECTIONS_FETCHED",Vn="data-modeling/generate-diagram-wizard/COLLECTIONS_FETCH_FAILED",Un="data-modeling/generate-diagram-wizard/SELECT_COLLECTIONS",qn="data-modeling/generate-diagram-wizard/TOGGLE_INFER_RELATIONS",Zn="data-modeling/generate-diagram-wizard/CHANGE_SAMPLING_OPTIONS",Jn="data-modeling/generate-diagram-wizard/CONFIRM_SELECTED_COLLECTIONS",Qn={inProgress:!1,step:"SETUP_DIAGRAM",formFields:{diagramName:{},selectedConnection:{},selectedDatabase:{},selectedCollections:{},samplingOptions:{value:Je}},connectionDatabases:null,databaseCollections:null,automaticallyInferRelations:!0},Xn=4*f.YKD[1600],ea=(0,f.AHW)({display:"flex",flexDirection:"column",overflow:"hidden"}),ta=(0,f.AHW)({display:"flex",flexDirection:"column",height:"100%",justifyContent:"flex-end",gap:f.YKD[300]}),na=(0,f.AHW)({whiteSpace:"nowrap",textOverflow:"ellipsis",overflow:"hidden"}),aa=(0,f.AHW)({flexShrink:0}),ra=(0,f.AHW)({fontStyle:"italic"}),ia=(0,f.AHW)({display:"flex",alignItems:"center",gap:f.YKD[200]}),oa=(0,f.AHW)({display:"flex",gap:f.YKD[200],alignItems:"flex-start"}),sa=(0,f.AHW)({fontWeight:"bold",height:2*f.YKD[600],marginBottom:f.YKD[400],whiteSpace:"nowrap",textOverflow:"ellipsis",overflow:"hidden"}),la=(0,f.AHW)({color:f.MFm.green.light2}),ca=(0,f.AHW)({color:f.MFm.green.dark2});function da({diagram:e,onOpen:t,onRename:n,onDelete:a}){const i=(0,f.D27)(),o=(0,f.Unm)(new Date(e.updatedAt).getTime());return r().createElement(f.ZpM,{className:ea,contentStyle:"clickable",onClick:()=>t(e),"data-testid":"saved-diagram-card","data-diagram-name":e.name,title:e.name},r().createElement("div",{className:oa},r().createElement(f.Pds,{as:"div",className:(0,f.cx)(sa,i?la:ca),title:e.name},e.name),r().createElement(f.pNw,{isVisible:!0,actions:[{action:"rename",label:"Rename"},{action:"delete",label:"Delete"}],onAction:t=>{switch(t){case"rename":n(e.id);break;case"delete":a(e.id)}}})),r().createElement("div",{className:ta},r().createElement("div",{className:ia},r().createElement(f.Int,{title:null,glyph:"Database",color:f.MFm.gray.dark1,className:aa}),r().createElement("span",{className:na},e.database)),r().createElement("div",{className:ra},"Last modified: ",o)))}const ua=({onImportDiagram:e,...t})=>r().createElement(f.m_M,{trigger:r().createElement("span",null,r().createElement(f.SxS,{id:"import-diagram-file-input","data-testid":"import-diagram-file-input",multiple:!1,accept:".mdm",onSelect:t=>{0!==t.length&&e(t[0])},trigger:({onClick:e})=>r().createElement(f.$nd,(0,u.A)({},t,{onClick:e}),"Import diagram")}))},"Only MDM files exported from Compass or Atlas Data Explorer can be imported."),pa=(0,f.AHW)({padding:f.YKD[400],display:"grid",gridTemplateAreas:"\n 'title createDiagram'\n 'searchInput sortControls'\n ",columnGap:f.YKD[800],rowGap:f.YKD[200],gridTemplateColumns:"5fr"}),ma=(0,f.AHW)({gridArea:"title"}),ga=(0,f.AHW)({gridArea:"createDiagram",display:"flex",justifyContent:"flex-end",gap:f.YKD[200]}),ha=(0,f.AHW)({gridArea:"searchInput"}),fa=(0,f.AHW)({gridArea:"sortControls",display:"flex",justifyContent:"flex-end"}),ya=(0,f.AHW)({color:f.MFm.gray.dark1}),ba=(0,f.AHW)({color:f.MFm.gray.light1}),va=()=>{const{onSearchDiagrams:e,onCreateDiagram:t,sortControls:n,searchTerm:i,onImportDiagram:o}=(0,a.useContext)(wa),s=(0,f.D27)();return r().createElement("div",{className:pa},r().createElement(f.Pds,{className:(0,f.cx)(ma,s?ba:ya)},"Open an existing diagram:"),r().createElement("div",{className:ga},r().createElement(ua,{leftGlyph:r().createElement(f.Int,{glyph:"Import"}),size:"small",onImportDiagram:o}),r().createElement(f.$nd,{onClick:t,variant:"primary",size:"small","data-testid":"create-diagram-button",leftGlyph:r().createElement(f.Int,{glyph:"Plus"})},"Generate new diagram")),r().createElement(f.DOo,{"aria-label":"Search diagrams",value:i,className:ha,onChange:t=>e(t.target.value)}),r().createElement("div",{className:fa},n))},xa=[{name:"name",label:"Name"},{name:"updatedAt",label:"Last Modified"}],Ea=(0,f.AHW)({height:"100%"}),Ca=(0,f.AHW)({gap:f.YKD[200],paddingLeft:f.YKD[400],paddingRight:f.YKD[400],paddingBottom:f.YKD[200]}),wa=r().createContext({onSearchDiagrams:()=>{},onImportDiagram:()=>{},onCreateDiagram:()=>{},sortControls:null,searchTerm:""}),Ia=(0,f.AHW)({maxWidth:"750px"}),Sa=(0,f.AHW)({display:"flex",gap:f.YKD[200]}),Aa=(0,f.AHW)({display:"flex",flexDirection:"row",justifyContent:"center",alignItems:"flex-start",gap:f.YKD[600],marginTop:f.YKD[400],marginBottom:f.YKD[400]}),ka=(0,f.AHW)({fontWeight:"bold"}),Da=(0,f.AHW)({display:"grid",gridTemplateRows:`${f.YKD[1800]}px 1fr 1fr`,justifyItems:"center",gap:f.YKD[400],width:3*f.YKD[1400]}),Na={visualization:{icon:()=>{const e=(0,f.D27)(),t=(0,a.useMemo)((()=>e?f.MFm.white:f.MFm.black),[e]),n=f.MFm.green.base;return r().createElement("svg",{width:"72",height:"72",viewBox:"0 0 72 72",fill:"none",xmlns:"http://www.w3.org/2000/svg"},r().createElement("g",{id:"Technical_MDB_SchemaVisualization"},r().createElement("g",{id:"mdb_schema_visualization"},r().createElement("path",{id:"Vector",d:"M18.0203 46V35C18.0203 32.8 19.8229 31 22.0261 31H50.0666C52.2698 31 54.0724 32.8 54.0724 35V46M36.0463 36V46",stroke:t,strokeMiterlimit:"10",strokeLinejoin:"round"}),r().createElement("path",{id:"Vector_2",d:"M66.0896 62H6.00289C4.9013 62 4 61.1 4 60V12C4 10.9 4.9013 10 6.00289 10H65.9895C67.0911 10 67.9924 10.9 67.9924 12V59.9C68.0925 61.1 67.1912 62 66.0896 62Z",stroke:t,strokeMiterlimit:"10",strokeLinejoin:"round"}),r().createElement("path",{id:"Vector_3",d:"M68 20H4V12.1C4 10.9 4.9 10 6.1 10H65.9C67.1 10 68 10.9 68 12.1V20Z",fill:n,stroke:t,strokeMiterlimit:"10",strokeLinecap:"round",strokeLinejoin:"round"}),r().createElement("path",{id:"Vector_4",d:"M40 56H32C31.4 56 31 55.6 31 55V47C31 46.4 31.4 46 32 46H40C40.6 46 41 46.4 41 47V55C41 55.6 40.6 56 40 56Z",fill:n,stroke:t,strokeMiterlimit:"10",strokeLinecap:"round",strokeLinejoin:"round"}),r().createElement("path",{id:"Vector_5",d:"M58 56H50C49.4 56 49 55.6 49 55V47C49 46.4 49.4 46 50 46H58C58.6 46 59 46.4 59 47V55C59 55.6 58.5 56 58 56Z",fill:n,stroke:t,strokeMiterlimit:"10",strokeLinecap:"round",strokeLinejoin:"round"}),r().createElement("path",{id:"Vector_6",d:"M22 56H14C13.4 56 13 55.6 13 55V47C13 46.4 13.4 46 14 46H22C22.6 46 23 46.4 23 47V55C23 55.6 22.6 56 22 56Z",fill:n,stroke:t,strokeMiterlimit:"10",strokeLinecap:"round",strokeLinejoin:"round"}),r().createElement("path",{id:"Vector_7",d:"M40 36H32C31.4 36 31 35.6 31 35V27C31 26.4 31.4 26 32 26H40C40.6 26 41 26.4 41 27V35C41 35.6 40.6 36 40 36Z",fill:n,stroke:t,strokeMiterlimit:"10",strokeLinecap:"round",strokeLinejoin:"round"}))))},title:"Quick Visualization",subtitle:"Instantly visualize your data models"},collaboration:{icon:()=>{const e=(0,f.D27)(),t=(0,a.useMemo)((()=>e?f.MFm.white:f.MFm.black),[e]);return r().createElement("svg",{width:"72",height:"72",viewBox:"0 0 72 72",fill:"none",xmlns:"http://www.w3.org/2000/svg"},r().createElement("g",{id:"General_CONTENT_Collaborate"},r().createElement("g",{id:"general_content_collaborate"},r().createElement("path",{id:"Vector",d:"M36 45.4857C40.8285 45.4857 44.7429 41.5714 44.7429 36.7429C44.7429 31.9143 40.8285 28 36 28C31.1715 28 27.2571 31.9143 27.2571 36.7429C27.2571 41.5714 31.1715 45.4857 36 45.4857ZM36 45.4857C26.1 45.4857 18 53.8171 18 64H54C54 53.6849 45.9 45.4857 36 45.4857Z",stroke:t,strokeMiterlimit:"10"}),r().createElement("path",{id:"Vector_2",d:"M4 64H3.5C3.5 64.2761 3.72386 64.5 4 64.5V64ZM21.5 46C21.5 49.0376 19.0376 51.5 16 51.5V52.5C19.5899 52.5 22.5 49.5899 22.5 46H21.5ZM16 51.5C12.9624 51.5 10.5 49.0376 10.5 46H9.5C9.5 49.5899 12.4101 52.5 16 52.5V51.5ZM10.5 46C10.5 42.9624 12.9624 40.5 16 40.5V39.5C12.4101 39.5 9.5 42.4101 9.5 46H10.5ZM16 40.5C19.0376 40.5 21.5 42.9624 21.5 46H22.5C22.5 42.4101 19.5899 39.5 16 39.5V40.5ZM18 63.5H4V64.5H18V63.5ZM4.5 64C4.5 57.6095 9.60948 52.5 16 52.5V51.5C9.05719 51.5 3.5 57.0572 3.5 64H4.5ZM16 52.5C17.9067 52.5 19.6974 52.9545 21.2722 53.7606L21.7278 52.8705C20.0141 51.9932 18.0675 51.5 16 51.5V52.5Z",fill:t}),r().createElement("path",{id:"Vector_3",d:"M68 64H68.5C68.5 64.2761 68.2761 64.5 68 64.5V64ZM50.5 46C50.5 49.0376 52.9624 51.5 56 51.5V52.5C52.4101 52.5 49.5 49.5899 49.5 46H50.5ZM56 51.5C59.0376 51.5 61.5 49.0376 61.5 46H62.5C62.5 49.5899 59.5899 52.5 56 52.5V51.5ZM61.5 46C61.5 42.9624 59.0376 40.5 56 40.5V39.5C59.5899 39.5 62.5 42.4101 62.5 46H61.5ZM56 40.5C52.9624 40.5 50.5 42.9624 50.5 46H49.5C49.5 42.4101 52.4101 39.5 56 39.5V40.5ZM54 63.5H68V64.5H54V63.5ZM67.5 64C67.5 57.6095 62.3905 52.5 56 52.5V51.5C62.9428 51.5 68.5 57.0572 68.5 64H67.5ZM56 52.5C54.0933 52.5 52.3026 52.9545 50.7278 53.7606L50.2722 52.8705C51.9859 51.9932 53.9325 51.5 56 51.5V52.5Z",fill:t}),r().createElement("path",{id:"Vector_4",d:"M66 8H6C4.89543 8 4 8.89543 4 10V18C4 19.1046 4.89543 20 6 20L31 20L34.4636 24.1563C35.2631 25.1158 36.7369 25.1158 37.5364 24.1563L41 20L44.5 20H66C67.1046 20 68 19.1046 68 18V10C68 8.89543 67.1046 8 66 8Z",fill:f.MFm.green.base,stroke:t}))))},title:"Collaboration & Sharing with your team",subtitle:"Collaborate and share schemas across teams"},interactive:{icon:()=>{const e=(0,f.D27)(),t=(0,a.useMemo)((()=>e?f.MFm.white:f.MFm.black),[e]),n=f.MFm.green.base;return r().createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"72",height:"72",viewBox:"0 0 72 72",fill:"none"},r().createElement("path",{d:"M4 60H48.5C51.8 60 54.8 58.7027 57 56.5073C59.2 54.3119 60.5 51.3181 60.5 48.0249C60.5 41.4387 55.1 36.0499 48.5 36.0499L24 35.9501C17.4 35.9501 12 30.5613 12 23.9751C12 20.6819 13.3 17.6881 15.5 15.4927C17.7 13.2973 20.7 12 24 12H68M60 20L67.68 12.8C68.1067 12.4 68.1067 11.6 67.68 11.2L60 4M12 52L4.32 59.2C3.89333 59.6 3.89333 60.4 4.32 60.8L12 68",stroke:t,strokeMiterlimit:"10"}),r().createElement("path",{d:"M31.7835 22.6262L44.3054 35.2971C44.6903 35.6866 44.6903 36.3134 44.3054 36.7029L31.7835 49.3738C30.8991 50.2688 29.4539 50.2688 28.5694 49.3738C27.6997 48.4937 27.6997 47.0777 28.5694 46.1976L37.9524 36.7029C38.3374 36.3134 38.3374 35.6866 37.9524 35.2971L28.5694 25.8024C27.6997 24.9223 27.6997 23.5063 28.5694 22.6262C29.4539 21.7312 30.8991 21.7312 31.7835 22.6262Z",fill:n,stroke:t}))},title:"Interactive Diagram Analysis",subtitle:"Explore and annotate interactive diagrams"}},Ma=({features:e})=>r().createElement("div",{className:Aa},e.map(((e,t)=>{const{icon:n,title:a,subtitle:i}=Na[e];return r().createElement("div",{key:t,className:Da},r().createElement(n,null),r().createElement(f.nBu,{className:ka},a),r().createElement(f.nBu,null,i))}))),Ta=({onCreateDiagramClick:e,onImportDiagramClick:t})=>r().createElement(f.XvC,null,r().createElement(f.HYq,{title:"Visualize your Data Model",subTitle:r().createElement(r().Fragment,null,"Your data model is the foundation of application performance. As applications evolve, so must your schema—intelligently and strategically. Minimize complexity, prevent performance bottlenecks, and keep your development agile.",r().createElement(Ma,{features:["visualization","collaboration","interactive"]}),r().createElement(f.N_E,{href:"https://www.mongodb.com/docs/compass/current/data-modeling/"},"Data modeling documentation")),subTitleClassName:Ia,callToAction:r().createElement("div",{className:Sa},r().createElement(ua,{onImportDiagram:t}),r().createElement(f.$nd,{onClick:e,variant:"primary","data-testid":"create-diagram-button"},"Generate diagram"))})),Pa=(0,d.Ng)(null,{onCreateDiagramClick:function(){return(e,t,{track:n})=>{n("Data Modeling Create Diagram Modal Opened",{}),e({type:Hn})}},onOpenDiagramClick:Ne,onDiagramDeleteClick:function(e){return async(t,n,{dataModelStorage:a})=>{await(0,f.$TK)({title:"Are you sure you want to delete this diagram?",description:"This action can not be undone.",variant:"danger"})&&(a.delete(e),t({type:Ce.DELETE_DIAGRAM,id:e}))}},onDiagramRenameClick:function(e){return async(t,n,{dataModelStorage:a})=>{try{const n=await a.load(e);if(!n)return;const r=await(0,f.q9R)({title:"Rename diagram",label:"Name",defaultValue:n.name});if(!r)return;t({type:Ce.RENAME_DIAGRAM,id:e,name:r}),a.save({...n,name:r})}catch{}}},onImportDiagramClick:function(e){return async(t,n,{dataModelStorage:a,track:r,openToast:i})=>{try{const{name:n,edits:i,database:o}=await async function(e){const t=new FileReader;return new Promise(((n,a)=>{t.onload=e=>{try{const t=e.target?.result;if("string"!=typeof t)throw new Error("Invalid file contents");const a=JSON.parse(t);if(1!==a.version||a.type!==ge)throw new Error("Unsupported diagram file format");const{name:r,edits:i,database:o}=a;if(!r||!i||"string"!=typeof i||!o)throw new Error("Diagram file is missing required fields");const s=JSON.parse(me.from(i,"base64").toString("utf-8")),l=g.Ol.parse(s);return n({name:a.name,edits:[l[0],...l.slice(1)],database:a.database})}catch(e){const t=e instanceof pe.z.ZodError?"Failed to parse diagram file: Invalid diagram data.":`Failed to parse diagram file: ${e.message}`;a(new Error(t))}},t.onerror=e=>{a(e.target?.error||new Error("File read error"))},t.readAsText(e)}))}(e),s=(await a.loadAll()).map((e=>e.name)),l={id:(new p.UUID).toString(),name:ye(s,n),connectionId:null,database:o,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString(),edits:i};t(Ne(l)),r("Data Modeling Diagram Imported",{}),a.save(l)}catch(e){ke(i,"Error opening diagram",[e.message])}}}})((({onCreateDiagramClick:e,onOpenDiagramClick:t,onDiagramRenameClick:n,onDiagramDeleteClick:i,onImportDiagramClick:o})=>{const{items:s,status:l}=(0,ln.U5)(),[c,d]=(0,a.useState)(""),u=(0,a.useMemo)((()=>{try{const e=new RegExp(c,"i");return s.filter((t=>e.test(t.name)||e.test(t.database)))}catch{return s}}),[s,c]),[p,m]=(0,f.yRS)("saved-diagrams-list-controls",{name:xa[0].name,order:1}),[g,h]=(0,f.yv$)(xa,{initialState:p,onChange:m}),y=(0,f.Vdw)(u,h);return"INITIAL"===l||"LOADING"===l?null:0===s.length?r().createElement(Ta,{onCreateDiagramClick:e,onImportDiagramClick:o}):r().createElement(wa.Provider,{value:{sortControls:g,searchTerm:c,onCreateDiagram:e,onSearchDiagrams:d,onImportDiagram:o}},r().createElement(f.XvC,null,r().createElement(f.Q$5,{"data-testid":"saved-diagram-list",itemMinWidth:Xn,itemHeight:180+f.YKD[200],itemsCount:y.length,className:Ea,renderItem:({index:e})=>r().createElement(da,{diagram:y[e],onOpen:t,onRename:n,onDelete:i}),itemKey:e=>y[e].id,renderHeader:va,headerHeight:3*f.YKD[800]+f.YKD[200],classNames:{row:Ca},resetActiveItemOnBlur:!1,renderEmptyList:()=>r().createElement(f.HYq,{title:"No results found.",subTitle:"We can't find any diagram matching your search."})})))}));function La(){const e=(0,s.n5)();return(0,a.useMemo)((()=>{const t=[],n=[];for(const a of e)"connected"===a.status?t.push({id:a.info.id,name:a.title,description:"Active"}):n.push({id:a.info.id,name:a.title});return[...t,...n]}),[e])}const Oa=(0,f.AHW)({display:"flex",flexDirection:"column",gap:f.YKD[600],marginTop:f.YKD[600],marginBottom:f.YKD[600]}),Ra=(0,f.AHW)({display:"flex",flexDirection:"row",gap:f.YKD[400],"& > div":{flex:1}}),Ha=(0,d.Ng)((({generateDiagramWizard:e})=>{const{formFields:{diagramName:t,selectedConnection:n,selectedDatabase:a}}=e;return{diagramName:t,selectedConnection:n,selectedDatabase:a,databases:e.connectionDatabases??[]}}),{onConnectionSelect:function(e){return async(t,n,a)=>{try{t({type:Bn,id:e});const n=a.connections.getConnectionById(e)?.info;if(!n)return;await a.connections.connect(n);const r=a.connections.getConnectionById(e)?.error;if(r)throw r}catch(e){return a.logger.log.error(a.logger.mongoLogId(1001000348),"DataModeling","Failed to select connection",{err:e}),void t({type:$n,error:new Error("Connection failed.")})}try{t({type:zn});const n=a.instanceManager.getMongoDBInstanceForConnection(e),r=a.connections.getDataServiceForConnection(e);await n.fetchDatabases({dataService:r}),t({type:_n,connectionId:e,databases:n.databases.map((e=>e.name)).filter((e=>!(0,y.Ay)(e).specialish))})}catch(e){a.logger.log.error(a.logger.mongoLogId(1001000351),"DataModeling","Failed to list databases",{err:e}),t({type:Kn,error:e})}}},onDatabaseSelect:function(e){return async(t,n,a)=>{if(t({type:Yn,database:e}),!n().generateDiagramWizard.formFields.diagramName.value){const n=await a.dataModelStorage.loadAll(),r=new Date,i=r.getDate().toString().padStart(2,"0"),o=(r.getMonth()+1).toString().padStart(2,"0"),s=r.getFullYear(),l=[e,i,o,s].join("_");t({type:Wn,name:ye(n.map((e=>e.name)),l)})}try{const{selectedConnection:e,selectedDatabase:r}=n().generateDiagramWizard.formFields;if(!e.value||!r.value)return;const i=a.instanceManager.getMongoDBInstanceForConnection(e.value),o=a.connections.getDataServiceForConnection(e.value),s=i.databases.get(r.value);if(!s)return;await s.fetchCollections({dataService:o}),t({type:Gn,connectionId:e.value,database:r.value,collections:s.collections.map((e=>e.name)).filter((e=>!(0,y.Ay)(e).specialish))})}catch(e){a.logger.log.error(a.logger.mongoLogId(1001000349),"DataModeling","Failed to select database",{err:e}),t({type:Vn,error:e})}}},onNameChange:function(e){return{type:Wn,name:e}},onValidateName:function(){return async(e,t,{dataModelStorage:n})=>{const a=t().generateDiagramWizard.formFields.diagramName.value;a&&(await n.loadAll()).some((e=>e.name===a))&&e({type:jn,error:new Error("Diagram with this name already exists.")})}}})((({diagramName:e,selectedConnection:t,selectedDatabase:n,databases:i,onNameChange:o,onValidateName:s,onConnectionSelect:l,onDatabaseSelect:c})=>{const d=La(),u=(0,a.useMemo)((()=>t.error?t.error.message:0===d.length?"You do not have any connections, create a new connection first.":void 0),[t.error,d.length]),p=(0,a.useMemo)((()=>{if(!u)return n.error?n.error.message:0===i.length?"No databases found for the selected connection.":void 0}),[u,n.error,i.length]);return r().createElement("div",{className:Oa},r().createElement("div",{className:Ra},r().createElement(f.G3_,{label:"Connection",placeholder:"Select connection","aria-label":"Select connection",value:t.value??"","data-testid":"new-diagram-connection-selector",onChange:e=>{e&&l(e)},clearable:!1,multiselect:!1,disabled:t.isConnecting,state:u?"error":void 0,errorMessage:u},d.map((e=>r().createElement(f.jOs,{key:e.id,value:e.id,displayName:e.name,description:e.description})))),r().createElement(f.G3_,{label:"Database",placeholder:"Select database","aria-label":"Select database",value:n.value??"","data-testid":"new-diagram-database-selector",onChange:e=>{e&&c(e)},clearable:!1,multiselect:!1,disabled:!t.value||t.isConnecting,state:p?"error":void 0,errorMessage:p},i.map((e=>r().createElement(f.jOs,{key:e,value:e}))))),r().createElement(f.ksK,{label:"Diagram name",value:e.value,"data-testid":"new-diagram-name-input",onChange:e=>{o(e.currentTarget.value)},onBlur:s,state:e.error?"error":void 0,errorMessage:e.error?.message}),r().createElement(f.lZ$,{variant:"info"},"Diagram will be generated from a sample of documents in the selected database. Changes made to the diagram will not impact your data."))})),Fa=(0,f.AHW)({textAlign:"center",marginTop:f.YKD[1800],marginBottom:f.YKD[1800]}),Wa=(0,f.AHW)({marginTop:f.YKD[600],marginBottom:f.YKD[600]}),ja=(0,f.AHW)({height:200,overflow:"auto"}),Ba=({collections:e,selectedCollections:t,disabledCollections:n=[],isFetchingCollections:i,error:o,onCollectionsSelect:s})=>{const[l,c]=(0,a.useState)(""),d=(0,a.useMemo)((()=>{try{return e.filter((e=>e.toLowerCase().includes(l.toLowerCase())))}catch{return e}}),[e,l]),u=(0,a.useCallback)((e=>{const a=t.filter((t=>{if(n.includes(t))return!1;const a=e.find((e=>e.id===t));return!a||a.selected})),r=e.filter((e=>e.selected&&!n.includes(e.id))).map((e=>e.id));s(Array.from(new Set([...r,...a])))}),[t,n,s]);return i?r().createElement("div",{className:Fa},r().createElement(f.iyS,{progressText:""},"Fetching collections …")):o?r().createElement("div",{className:Wa},r().createElement(f.rpn,{warnings:[o.message]})):r().createElement(r().Fragment,null,r().createElement(f.GEW,null,r().createElement(f.DOo,{"aria-label":"Search collections",value:l,onChange:e=>{c(e.target.value)}})),0===e.length?r().createElement(f.nBu,null,"This database has no collections."):0===d.length?r().createElement(f.nBu,null,"No collections match your search."):r().createElement(f.Bq0,{className:ja,items:d.map((e=>({id:e,selected:t.includes(e),disabled:n.includes(e)}))),label:{displayLabelKey:"id",name:"Collection Name"},onChange:u}))},za=(0,d.Ng)((e=>{const{formFields:{selectedCollections:t},databaseCollections:n}=e.generateDiagramWizard;return{collections:n??[],selectedCollections:t.value??[],isFetchingCollections:Boolean(t.isFetchingCollections),error:t.error}}),{onCollectionsSelect:function(e){return{type:Un,collections:e}}})(Ba),_a=(0,f.AHW)({flexDirection:"row",alignItems:"center"}),$a=(0,f.AHW)({marginRight:"auto"}),Ya=(0,f.AHW)({display:"flex",gap:f.YKD[200]}),Ka=({title:e,description:t,onPreviousClick:n,onNextClick:a,isNextDisabled:i,nextLabel:o,previousLabel:s,children:l,step:c,footerText:d,isLoading:u})=>r().createElement(r().Fragment,null,r().createElement(f.rQ0,{title:e,subtitle:t}),r().createElement(f.cwr,null,r().createElement("form",{onSubmit:e=>{e.preventDefault(),a()}},l)),r().createElement(f.jlY,{className:_a},r().createElement(f.nBu,{className:$a},d),r().createElement("div",{className:Ya},r().createElement(f.$nd,{onClick:n,key:`${c}-previous`},s),r().createElement(f.$nd,{onClick:a,disabled:i,"data-testid":"confirm-button",variant:"primary",loadingIndicator:r().createElement(f.Q0K,null),key:`${c}-next`,isLoading:u},o)))),Ga=(0,f.AHW)({marginTop:f.YKD[600],marginBottom:f.YKD[600]}),Va=(0,f.AHW)({display:"flex",flexDirection:"column",gap:f.YKD[100]}),Ua=(0,f.AHW)({display:"flex",alignItems:"center",gap:f.YKD[100]}),qa=(0,f.AHW)({display:"flex",alignItems:"center",gap:f.YKD[200]}),Za=(0,f.AHW)({flexDirection:"row",gap:f.YKD[400],alignItems:"center",marginTop:f.YKD[200]}),Ja=(0,f.AHW)({width:100}),Qa=(0,f.AHW)({display:"flex",alignItems:"center",gap:f.YKD[100],color:f.MFm.yellow.dark2}),Xa=(0,f.AHW)({display:"flex",alignItems:"center",gap:f.YKD[100],color:f.MFm.red.base}),er=(0,f.AHW)({marginTop:f.YKD[200]}),tr=(0,f.AHW)({alignSelf:"flex-start"}),nr=(0,f.AHW)({color:f.MFm.gray.dark1}),ar=(0,f.AHW)({color:f.MFm.gray.light1}),rr=(0,f.AHW)({display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:f.YKD[200],marginTop:f.YKD[600]}),ir="infer-relationships-label",or="infer-relationships-toggle",sr="infer-relationships-description",lr="sampling-options-description",cr=({automaticallyInferRelationships:e,samplingOptions:t,error:n,onAutomaticallyInferRelationshipsToggle:i,onSamplingOptionsChange:s})=>{const l=(0,o.Fg)("enableAutomaticRelationshipInference"),c=(0,a.useCallback)((e=>{s({...t,...e})}),[s,t]),d=(0,a.useCallback)((e=>{c({allDocuments:"allDocuments"===e.target.value})}),[c]),u=(0,a.useCallback)((e=>{c({sampleSize:parseInt(e.target.value,10)})}),[c]),p=(0,a.useMemo)((()=>!Qe(t)),[t]),m=(0,a.useMemo)((()=>!p&&(t.allDocuments||t.sampleSize>100)),[t,p]),g=(0,f.D27)();return n?r().createElement("div",{className:Ga},r().createElement(f.rpn,{warnings:[n.message]})):r().createElement(r().Fragment,null,l&&r().createElement(r().Fragment,null,r().createElement("div",{className:rr},r().createElement(f.JU7,{id:ir,htmlFor:or},"Automatically infer relationships"),r().createElement(f.lMk,{id:or,"aria-labelledby":ir,"aria-describedby":sr,checked:e,onChange:e=>{i(e)},size:"small"})),r().createElement("div",{id:sr,className:(0,f.cx)(nr,g&&ar)},"Analysis process will try to automatically discover relationships in selected collections. This operation will run multiple find requests against indexed fields of the collections and"," ",r().createElement("strong",null,"will take additional time per collection being analyzed."))),r().createElement(f.GEW,{className:Va},r().createElement(f.nBu,{weight:"bold"},"Document sampling"),r().createElement("div",{id:lr,className:(0,f.cx)(nr,g&&ar)},"By default, diagrams are generated from a small sample per collection. Larger samples improve accuracy but increase analysis time and memory usage, while smaller samples are faster but may miss infrequent fields or relationships."),r().createElement(f.z6M,{className:Za,onChange:d,value:t.allDocuments?"allDocuments":"sampleSize","aria-describedby":lr},r().createElement(f.sxL,{value:"sampleSize",className:Ua,default:!0},r().createElement("div",{className:qa},r().createElement(f.ksK,{id:"sample-size-input","data-testid":"sample-size-input","aria-label":"Sample size",className:Ja,type:"number",min:1,value:t.sampleSize.toString(),onChange:u}),r().createElement(f.nBu,null,"documents per collection."))),r().createElement(f.sxL,{value:"allDocuments"},r().createElement(f.nBu,null,"All documents"))),r().createElement("div",{className:er},p&&r().createElement("div",{className:Xa,"data-testid":"sample-size-warning"},r().createElement(f.Int,{glyph:"Warning",size:"large"}),r().createElement("span",null,"Invalid input")),m&&r().createElement("div",{className:Qa,"data-testid":"sample-size-warning"},r().createElement(f.Int,{glyph:"Warning",size:"large",className:tr}),r().createElement("span",null,r().createElement("strong",null,"Warning:")," Consider your dataset size and the available resources on your device or browser.")))))},dr=(0,d.Ng)((e=>{const{formFields:{selectedCollections:t,samplingOptions:n},automaticallyInferRelations:a}=e.generateDiagramWizard;return{automaticallyInferRelationships:a,samplingOptions:n.value,error:t.error}}),{onAutomaticallyInferRelationshipsToggle:function(e){return{type:qn,newVal:e}},onSamplingOptionsChange:function(e){return{type:Zn,samplingOptions:e}}})(cr),ur=(0,d.Ng)((e=>{const{inProgress:t,step:n,formFields:a,databaseCollections:r}=e.generateDiagramWizard;return{isOpen:t,currentStep:n,isGotoCollectionsStepDisabled:!a.diagramName.value||Boolean(a.diagramName.error)||!a.selectedConnection.value||!a.selectedDatabase.value,isGenerateDiagramDisabled:!a.selectedCollections.value||0===a.selectedCollections.value.length||!Qe(a.samplingOptions.value)||re(e),numSelectedCollections:a.selectedCollections.value?.length||0,numTotalCollections:r?.length||0,selectedDatabaseName:a.selectedDatabase.value||""}}),{onCancel:function(){return{type:Fn}},onStep:function(e){return(t,n)=>{n().generateDiagramWizard.step!==e&&t({type:Rn,step:e})}},onGenerate:function(){return(e,t)=>{const{formFields:{diagramName:n,selectedConnection:a,selectedDatabase:r,selectedCollections:i,samplingOptions:o},automaticallyInferRelations:s}=t().generateDiagramWizard;n.value&&a.value&&r.value&&i.value&&(e({type:Jn}),e(ae(n.value,a.value,r.value,i.value,{automaticallyInferRelations:s,samplingOptions:o.value??Je})))}}})((({isOpen:e,currentStep:t,isGenerateDiagramDisabled:n,isGotoCollectionsStepDisabled:i,numSelectedCollections:o,numTotalCollections:s,selectedDatabaseName:l,onCancel:c,onStep:d,onGenerate:u})=>{const p=(0,a.useMemo)((()=>{switch(t){case"SETUP_DIAGRAM":return{title:"New diagram setup",onNextClick:()=>d("SELECT_COLLECTIONS"),onPreviousClick:c,nextLabel:"Next",previousLabel:"Cancel",isNextDisabled:i,step:t};case"SELECT_COLLECTIONS":return{title:`Select collections for ${l}`,description:"These collections will be included in your generated diagram.",onNextClick:()=>d("DIAGRAM_SETTINGS"),onPreviousClick:()=>d("SETUP_DIAGRAM"),nextLabel:"Next",previousLabel:"Back",isNextDisabled:n,step:t,footerText:s>0&&r().createElement(r().Fragment,null,r().createElement("strong",null,o),"/",r().createElement("strong",null,s)," total"," ",1===s?"collection":"collections"," ","selected.")};case"DIAGRAM_SETTINGS":return{title:"Diagram settings",onNextClick:u,onPreviousClick:()=>d("SELECT_COLLECTIONS"),nextLabel:"Generate",previousLabel:"Back",isNextDisabled:n,step:t,footerText:s>0&&r().createElement(r().Fragment,null,r().createElement("strong",null,o),"/",r().createElement("strong",null,s)," total"," ",1===s?"collection":"collections"," ","selected.")};default:throw new Error("Unknown diagram generation step")}}),[t,i,n,o,s,l,c,u,d]);return r().createElement(f.aFV,{open:e,"data-testid":"new-diagram-modal",setOpen:e=>{e||c()}},r().createElement(Ka,p,"SETUP_DIAGRAM"===t?r().createElement(Ha,null):"SELECT_COLLECTIONS"===t?r().createElement(za,null):"DIAGRAM_SETTINGS"===t?r().createElement(dr,null):null))})),pr=(0,d.Ng)((e=>{const{databaseCollections:t,selectedCollections:n,error:a,automaticallyInferRelations:r,samplingOptions:i,newSelectedCollections:o}=e.reselectCollections;return{collections:t,selectedCollections:[...o,...n],disabledCollections:n,automaticallyInferRelationships:r,samplingOptions:i,isFetchingCollections:!1,error:a}}),{onCollectionsSelect:function(e){return{type:st,collections:e}},onAutomaticallyInferRelationshipsToggle:ut,onSamplingOptionsChange:gt})(Ba),mr=(0,d.Ng)((e=>{const{automaticallyInferRelations:t,samplingOptions:n}=e.reselectCollections;return{automaticallyInferRelationships:t,samplingOptions:n}}),{onAutomaticallyInferRelationshipsToggle:ut,onSamplingOptionsChange:gt})(cr),gr=(0,d.Ng)((e=>{const{reselectCollections:{isConnecting:t,selectedConnectionId:n,error:a}}=e;return{isConnecting:t,error:a,selectedConnectionId:n}}),{onConnectionSelect:function(e){return{type:tt,connectionId:e}}})((function({selectedConnectionId:e,onConnectionSelect:t,isConnecting:n,error:a}){const i=La();return r().createElement(f.G3_,{label:"Connection",placeholder:"Select connection","aria-label":"Select connection",value:e??"","data-testid":"reselect-collections-connection-selector",onChange:e=>{e&&t(e)},clearable:!1,multiselect:!1,disabled:n,state:a?"error":void 0,errorMessage:a?.message},i.map((e=>r().createElement(f.jOs,{key:e.id,value:e.id,displayName:e.name,description:e.description}))))})),hr=(0,d.Ng)((e=>{const{isOpen:t,step:n,error:a,isConnecting:r,databaseCollections:i,selectedConnectionId:o,selectedDatabase:s,selectedCollections:l,newSelectedCollections:c,samplingOptions:d}=e.reselectCollections,u=c.length+l.filter((e=>i.includes(e))).length;return{isOpen:t,currentStep:n,isConnectButtonDisabled:r||Boolean(a)||!o||!s,isGenerateDiagramDisabled:0===i.length||0===c.length||!Qe(d)||re(e),numSelectedCollections:u,numTotalCollections:i.length,selectedDatabaseName:s||"",isConnecting:r,samplingOptions:d}}),{onCancel:function(){return{type:et}},onConnect:function(){return async(e,t,{connections:n,instanceManager:a,logger:r})=>{const{reselectCollections:{selectedConnectionId:i,selectedDatabase:o}}=t();if(i&&o)try{const t=n.getConnectionById(i??"")?.info;if(!t)throw new Error("Can not find selected connection.");e({type:nt}),await n.connect(t);const r=n.getConnectionById(i??"")?.error;if(r)throw r;const s=await mt(i,o,n,a);e({type:at,collections:s})}catch(t){return r.log.error(r.mongoLogId(1001000392),"DataModeling","Failed to connect",{err:t}),void e({type:rt,error:t})}}},onStep:function(e){return(t,n)=>{n().reselectCollections.step!==e&&t({type:ct,step:e})}},onGenerate:function(){return(e,t)=>{const{reselectCollections:{diagramName:n,selectedConnectionId:a,selectedDatabase:r,newSelectedCollections:i,selectedCollections:o,automaticallyInferRelations:s,samplingOptions:l},diagram:d}=t();if(!d)throw new Error("Can not start analysis when there is no diagram");if(!a||!r)throw new Error("Can not start analysis when connection or database is not selected");e({type:lt}),e(function(e,t,n,a,r){return async(i,o,{cancelAnalysisControllerRef:s,logger:l,track:d,connections:u})=>{if(s.current)return;const p=He(o()),m=s.current=new AbortController,g=u.getConnectionById(t)?.info,h=r.automaticallyInferRelations;d("Data Modeling Add DB Collections Started",{num_collections:a.length,automatically_infer_relations:h,sample_size:r.samplingOptions.allDocuments?"all_documents":r.samplingOptions.sampleSize},g);const f=Date.now();try{const o=We(p.edits),s=new Set(o.collections.map((e=>e.ns))),l=h?a:a.filter((e=>!s.has(e))),{collections:c,relations:u,relationsInferencePhaseMs:m}=await i(oe({name:e,connectionId:t,database:n,selectedCollections:l,options:r})),y=await async function(e,t,n){const a=new Set(e.collections.map((e=>e.ns))),r=t.filter((e=>!a.has(e.ns))).map((e=>({ns:e.ns,fieldData:e.schema,indexes:[],shardKey:void 0}))),i=e.collections.map((({displayPosition:e,...t})=>t)),o=[...i,...r],s=await ne({collections:o.map((e=>({ns:e.ns,schema:e.fieldData}))),relations:n}),l=new Map(Array.from(i.map((e=>[e.ns,X(e.fieldData)])))),c=n.filter((e=>{const[t,n]=e.relationship,a=!l.has(t.ns),r=!l.has(n.ns),i=a||r,o=a||(l.get(t.ns)?.some((e=>(0,M.isEqual)(e,t.fields)))??!1),s=r||(l.get(n.ns)?.some((e=>(0,M.isEqual)(e,n.fields)))??!1);return i&&o&&s})),d=e.relationships;return{collections:o.map((e=>{const t=s.nodes.find((t=>t.id===e.ns)),n=t?t.position:{x:0,y:0};return{...e,displayPosition:[n.x,n.y]}})),relationships:[...d,...c]}}(o,c,u);i(function(e){return De({type:"SetModel",model:e})}(y)),i({type:ee.REDO_ANALYSIS_FINISHED}),d("Data Modeling Add DB Collections Succeeded",{num_collections:a.length,num_relations_inferred:h?u.length:void 0,analysis_time_ms:Date.now()-f,relationship_inference_phase_ms:m,sample_size:r.samplingOptions.allDocuments?"all_documents":r.samplingOptions.sampleSize},g)}catch(e){let t;e instanceof ie&&(t=e.relationshipInferencePhaseMs),m.signal.aborted?(i({type:ee.REDO_ANALYSIS_CANCELED}),d("Data Modeling Add DB Collections Cancelled",{num_collections:a.length,automatically_infer_relations:h,analysis_time_ms:Date.now()-f,relationship_inference_phase_ms:t,sample_size:r.samplingOptions.allDocuments?"all_documents":r.samplingOptions.sampleSize},g)):(l.log.error((0,c.oW)(1001000388),"DataModeling","Failed to re-analyze schema",{err:e}),i({type:ee.REDO_ANALYSIS_FAILED,error:e}),d("Data Modeling Add DB Collections Failed",{num_collections:a.length,automatically_infer_relations:h,analysis_time_ms:Date.now()-f,relationship_inference_phase_ms:t,sample_size:r.samplingOptions.allDocuments?"all_documents":r.samplingOptions.sampleSize},g))}finally{s.current=null}}}(n,a,r,[...i,...o],{automaticallyInferRelations:s,samplingOptions:l??Je}))}}})((({isOpen:e,currentStep:t,isGenerateDiagramDisabled:n,isConnecting:i,isConnectButtonDisabled:o,numSelectedCollections:s,numTotalCollections:l,selectedDatabaseName:c,onCancel:d,onConnect:u,onStep:p,onGenerate:m})=>{const g=(0,a.useMemo)((()=>{switch(t){case"SELECT_CONNECTION":return{title:"Select connection",description:"To fetch the collections for this database, select and connect to the database associated with this data model first.",onNextClick:u,onPreviousClick:d,nextLabel:"Connect",previousLabel:"Cancel",isNextDisabled:o,step:t,isLoading:i};case"SELECT_COLLECTIONS":return{title:`Select collections for ${c}`,description:"These collections will be included in your generated diagram.",onNextClick:()=>p("DIAGRAM_SETTINGS"),onPreviousClick:d,nextLabel:"Next",previousLabel:"Cancel",isNextDisabled:n,step:t,footerText:l>0&&r().createElement(r().Fragment,null,r().createElement("strong",null,s),"/",r().createElement("strong",null,l)," total"," ",1===l?"collection":"collections"," ","selected.")};case"DIAGRAM_SETTINGS":return{title:"Diagram settings",onNextClick:m,onPreviousClick:()=>p("SELECT_COLLECTIONS"),nextLabel:"Generate",previousLabel:"Back",isNextDisabled:n,step:t,footerText:l>0&&r().createElement(r().Fragment,null,r().createElement("strong",null,s),"/",r().createElement("strong",null,l)," total"," ",1===l?"collection":"collections"," ","selected.")};default:throw new Error(`Unknown diagram generation step: "${t}"`)}}),[t,o,n,s,l,c,d,u,p,m,i]);return r().createElement(f.aFV,{open:e,"data-testid":"reselect-collections-modal",setOpen:e=>{e||d()}},r().createElement(Ka,g,"SELECT_CONNECTION"===t?r().createElement(gr,null):"SELECT_COLLECTIONS"===t?r().createElement(pr,null):"DIAGRAM_SETTINGS"===t?r().createElement(mr,null):null))})),fr=(0,f.AHW)({height:"100%",width:"100%",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:"16px"}),yr=()=>{const{openDataModelingWorkspace:e}=(0,qe.$L)();return r().createElement("div",{className:fr},r().createElement("div",null,"This data model has been deleted."),r().createElement(f.$nd,{onClick:()=>e({newTab:!1}),variant:"primary"},"Back to Data Modeling"))},br=(0,d.Ng)((e=>({showList:"NO_DIAGRAM_SELECTED"===e.step,currentDiagramId:e.diagram?.id})))((({showList:e,currentDiagramId:t})=>{const n=(0,ln.U5)(),i=(0,a.useMemo)((()=>t&&!n.items.some((e=>e.id===t))),[n.items,t]);return r().createElement(r().Fragment,null,e?r().createElement(Pa,null):i?r().createElement(yr,null):r().createElement(f.Fp_,{fitView:!0},r().createElement(On,null),r().createElement(Cn,null)),r().createElement(ur,null),r().createElement(hr,null))}));var vr=n(44457),xr=n(82162);const Er=(0,xr.HY)({step:(e="NO_DIAGRAM_SELECTED",t)=>m(t,ee.ANALYZING_COLLECTIONS_START)?"ANALYZING":m(t,ee.ANALYSIS_FAILED)?"ANALYSIS_FAILED":m(t,ee.ANALYSIS_CANCELED)?"ANALYSIS_CANCELED":m(t,ee.ANALYSIS_FINISHED)||m(t,Ce.OPEN_DIAGRAM)||m(t,ee.REDO_ANALYSIS_FINISHED)||m(t,ee.REDO_ANALYSIS_FAILED)||m(t,ee.REDO_ANALYSIS_CANCELED)?"EDITING":m(t,Fn)||m(t,$n)||m(t,Vn)?"NO_DIAGRAM_SELECTED":e,generateDiagramWizard:(e=Qn,t)=>m(t,Hn)?{...Qn,inProgress:!0}:m(t,Wn)?{...e,formFields:{...e.formFields,diagramName:{value:t.name}}}:m(t,jn)?{...e,formFields:{...e.formFields,diagramName:{...e.formFields.diagramName,error:t.error}}}:m(t,Bn)?{...e,formFields:{...e.formFields,selectedConnection:{isConnecting:!0,value:t.id},selectedDatabase:{}},connectionDatabases:[]}:m(t,zn)?{...e,formFields:{...e.formFields,selectedConnection:{...e.formFields.selectedConnection,isConnecting:!1,error:void 0},selectedDatabase:{isFetchingDatabases:!0}}}:m(t,$n)?{...e,formFields:{...e.formFields,selectedConnection:{...e.formFields.selectedConnection,isConnecting:!1,error:t.error}}}:m(t,_n)?t.connectionId!==e.formFields.selectedConnection.value?e:{...e,connectionDatabases:t.databases,formFields:{...e.formFields,selectedDatabase:{isFetchingDatabases:!1}}}:m(t,Kn)?{...e,formFields:{...e.formFields,selectedDatabase:{isFetchingDatabases:!1,error:t.error}}}:m(t,Yn)?{...e,formFields:{...e.formFields,selectedDatabase:{value:t.database},selectedCollections:{isFetchingCollections:!0}}}:m(t,Gn)?t.connectionId!==e.formFields.selectedConnection.value||t.database!==e.formFields.selectedDatabase.value?e:{...e,databaseCollections:t.collections,formFields:{...e.formFields,selectedCollections:{value:t.collections}},automaticallyInferRelations:!0}:m(t,Un)?{...e,formFields:{...e.formFields,selectedCollections:{value:t.collections}}}:m(t,Jn)||m(t,Fn)?{...e,inProgress:!1}:m(t,Vn)?{...e,formFields:{...e.formFields,selectedCollections:{isFetchingCollections:!1,error:t.error}}}:m(t,qn)?{...e,automaticallyInferRelations:t.newVal}:m(t,Zn)?{...e,formFields:{...e.formFields,samplingOptions:{...e.formFields.samplingOptions,value:t.samplingOptions}}}:m(t,Rn)?{...e,step:t.step}:e,analysisProgress:(e=te,t)=>{const n=e.currentAnalysisOptions?.collections.length??0;if(m(t,ee.ANALYZING_COLLECTIONS_START))return{...te,currentAnalysisOptions:{name:t.name,connectionId:t.connectionId,database:t.database,collections:t.collections,automaticallyInferRelations:t.options.automaticallyInferRelations,samplingOptions:t.options.samplingOptions},step:"SAMPLING",willInferRelations:t.willInferRelations};if(m(t,ee.NAMESPACE_SAMPLE_FETCHED)){const t=e.samplesFetched+1,a="ANALYZING_SCHEMA";return{...e,samplesFetched:t,step:t===n?a:e.step}}if(m(t,ee.NAMESPACE_SCHEMA_ANALYZED)){const t=e.schemasAnalyzed+1,a=e.willInferRelations?"INFERRING_RELATIONSHIPS":"IDLE";return{...e,schemasAnalyzed:t,step:t===n?a:e.step}}if(m(t,ee.NAMESPACE_RELATIONS_INFERRED)){const t=e.collectionRelationsInferred+1,a="IDLE";return{...e,collectionRelationsInferred:t,step:t===n?a:e.step}}return m(t,ee.ANALYSIS_CANCELED)||m(t,ee.ANALYSIS_FAILED)||m(t,ee.ANALYSIS_FINISHED)||m(t,ee.REDO_ANALYSIS_CANCELED)||m(t,ee.REDO_ANALYSIS_FAILED)||m(t,ee.REDO_ANALYSIS_FINISHED)?{...e,step:"IDLE"}:e},diagram:(e=null,t)=>{if(m(t,Ce.OPEN_DIAGRAM)){const e=t.diagram.edits,n=e.map(((e,t,n)=>n.slice(0,t)));return n.shift(),{...t.diagram,edits:{prev:n,current:e,next:[]},selectedItems:null}}if(m(t,ee.ANALYSIS_FINISHED))return{id:(new p.UUID).toString(),name:t.name,connectionId:t.connectionId,database:t.database,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString(),edits:{prev:[],current:[{type:"SetModel",id:(new p.UUID).toString(),timestamp:(new Date).toISOString(),model:{collections:t.collections.map((e=>({ns:e.ns,fieldData:e.schema,displayPosition:[e.position.x,e.position.y],indexes:[],shardKey:void 0}))),relationships:t.relations}}],next:[]},selectedItems:null};if(!e)return e;if(m(t,Ce.RENAME_DIAGRAM))return{...e,name:t.name,updatedAt:(new Date).toISOString()};if(m(t,Ce.APPLY_EDIT)&&e.draftCollection&&"RenameCollection"===t.edit.type)return{...e,edits:we(e.edits,e.draftCollection,t.edit.toNS),updatedAt:(new Date).toISOString(),selectedItems:{type:"collection",id:t.edit.toNS},draftCollection:void 0};if(m(t,Ce.APPLY_EDIT))return{...e,edits:{prev:[...e.edits.prev,e.edits.current],current:[...e.edits.current,t.edit],next:[]},updatedAt:(new Date).toISOString(),selectedItems:Ie(e.selectedItems,t.edit),draftCollection:"AddCollection"===t.edit.type?t.edit.ns:void 0};if(m(t,Ce.UNDO_EDIT)||m(t,Ce.REVERT_FAILED_EDIT)){const n=e.edits.prev.pop()||[];if(!Ee(n))return e;const a=m(t,Ce.REVERT_FAILED_EDIT)?e.edits.next:[...e.edits.next,e.edits.current];return{...e,edits:{prev:[...e.edits.prev],current:n,next:a},updatedAt:(new Date).toISOString()}}if(m(t,Ce.REDO_EDIT)){const t=e.edits.next.pop()||[];return Ee(t)?{...e,edits:{prev:[...e.edits.prev,e.edits.current],current:t,next:[...e.edits.next]},updatedAt:(new Date).toISOString()}:e}return m(t,Ce.COLLECTION_SELECTED)?{...e,selectedItems:{type:"collection",id:t.namespace}}:m(t,Ce.RELATIONSHIP_SELECTED)?{...e,selectedItems:{type:"relationship",id:t.relationshipId}}:m(t,Ce.FIELD_SELECTED)?{...e,selectedItems:{type:"field",namespace:t.namespace,fieldPath:t.fieldPath}}:m(t,Ce.DIAGRAM_BACKGROUND_SELECTED)?{...e,selectedItems:null}:e},exportDiagram:(e=Ve,t)=>m(t,_e)?{...e,isModalOpen:!0}:m(t,$e)?{...e,isModalOpen:!1}:m(t,Ye)?{...e,exportFormat:t.format}:m(t,Ke)?{...e,isExporting:!0}:m(t,Ge)?{...e,isExporting:!1,isModalOpen:!1}:e,reselectCollections:(e=dt,t)=>{if(m(t,Xe)){const{type:n,...a}=t;return{...e,...a,isOpen:!0}}return m(t,et)?{...dt,isOpen:!1}:m(t,tt)?{...e,selectedConnectionId:t.connectionId,error:void 0,isConnecting:!1}:m(t,nt)?{...e,isConnecting:!0}:m(t,rt)?{...e,isConnecting:!1,error:t.error}:m(t,at)?{...e,isConnecting:!1,error:void 0,databaseCollections:t.collections,step:"SELECT_COLLECTIONS"}:m(t,it)?{...e,automaticallyInferRelations:t.val}:m(t,st)?{...e,newSelectedCollections:t.collections}:m(t,lt)?dt:m(t,ot)?{...e,samplingOptions:t.samplingOptions}:m(t,ct)?{...e,step:t.step}:e}});var Cr=n(67219);const wr="Data Modeling",Ir=(0,d.Ng)((e=>({tabTitle:"NO_DIAGRAM_SELECTED"===e.step?wr:e.diagram?.name??wr})))((function({tabTitle:e,...t}){return r().createElement(f.N81,(0,u.A)({},t,{type:wr,title:e,iconGlyph:"Diagram"}))})),Sr=(0,i.nk)({name:"DataModeling",component:function({children:e}){return r().createElement(r().Fragment,null,e)},activate:function({openToast:e=f.c3r},t,{cleanup:n,addCleanup:a}){const r={current:null},i={current:null},o=(0,xr.y$)(Er,(0,xr.Tw)(Cr.A.withExtraArgument({...t,cancelAnalysisControllerRef:r,cancelExportControllerRef:i,openToast:e})));return a((()=>{r.current?.abort(),i.current?.abort()})),{store:o,deactivate:n}}},{preferences:o.fx,connections:s.u4,instanceManager:vr.Q3,dataModelStorage:ln.c5,track:l.yL,logger:(0,c.fF)("COMPASS-DATA-MODELING")}),Ar={name:wr,provider:Sr,content:br,header:Ir}},17156:(e,t,n)=>{n.d(t,{UZ:()=>br,yo:()=>E,lh:()=>fr,Bo:()=>ur});var a=n(96652),r=n.n(a),i=n(55712),o=n(39059),s=n(51295),l=n(20625);async function c(e,t,{signal:n,maxTimeMS:a},r=()=>{}){try{return await e.fetchShardKey(t,{maxTimeMS:a},{abortSignal:n})??{}}catch(t){if(e.isCancelError(t))throw t;r(t)}return{}}function d(e,t=250){if(e.isRoot()||"Object"===e.currentType){for(const n of e.elements??[])if(d(n,t))return!0;return!1}return"Array"===e.currentType&&e.elements&&e.elements.size>=t&&e.elements.some((e=>["Object","Document","ObjectId","String"].includes(e.currentType)))}function u(e){if(!e)return;const t=[];return(e.size??0)>1e7&&t.push(s.qpO.get("bloated-document")),d(e)&&t.push(s.qpO.get("unbound-array")),t.length>0?t:void 0}function p(e){return null!==e&&"object"==typeof e&&("[object RegExp]"===Object.prototype.toString.call(e)||Object.values(e).some(p))}n(95039);const m=(0,s.AHW)({position:"relative",textOverflow:"ellipsis",maxWidth:"100%",borderRadius:"inherit","&::-webkit-scrollbar":{display:"none"}}),g=(0,s.AHW)({paddingTop:s.YKD[400],paddingBottom:s.YKD[400]});class h extends r().Component{constructor(e){super(e),this.state={expanded:e.doc.expanded}}componentDidMount(){this.subscribeToDocumentEvents(this.props.doc)}componentDidUpdate(e){e.doc!==this.props.doc&&(this.unsubscribeFromDocumentEvents(e.doc),this.subscribeToDocumentEvents(this.props.doc))}componentWillUnmount(){this.unsubscribeFromDocumentEvents(this.props.doc)}subscribeToDocumentEvents(e){e.on(o.Tx.Expanded,this.handleExpanded),e.on(o.Tx.Collapsed,this.handleCollapsed)}unsubscribeFromDocumentEvents(e){e.on(o.Tx.Expanded,this.handleExpanded),e.on(o.Tx.Collapsed,this.handleCollapsed)}handleExpanded=()=>{this.setState({expanded:!0})};handleCollapsed=()=>{this.setState({expanded:!1})};handleClone=()=>{const e=this.props.doc.generateObject({excludeInternalFields:!0});this.props.openInsertDocumentDialog?.(e,!0)};handleCopy=()=>{this.props.copyToClipboard?.(this.props.doc)};handleExpandAll=()=>{const{doc:e}=this.props;e.expanded?e.collapse():e.expand()};renderElements(){return r().createElement(r().Fragment,null,r().createElement(s.gD8.yo,{value:this.props.doc,extraGutterWidth:s.YKD[900],onUpdateQuery:this.props.onUpdateQuery,query:this.props.query}))}renderActions(){return r().createElement(s.gD8.YO,{onCopy:this.props.copyToClipboard?this.handleCopy:void 0,onClone:this.props.openInsertDocumentDialog?this.handleClone:void 0,onExpand:this.handleExpandAll,expanded:this.state.expanded,insights:this.props.showInsights?u(this.props.doc):void 0})}render(){return r().createElement("div",{className:m,"data-testid":"readonly-document"},r().createElement("div",{className:g},this.renderElements(),this.renderActions()))}static displayName="ReadonlyDocument"}const f=(0,l.tC)(h,["showInsights"]),y=(0,s.AHW)({position:"relative"});class b extends r().Component{constructor(e){super(e),this.state={editing:e.doc.editing,deleting:e.doc.markedForDeletion,expanded:e.doc.expanded}}componentDidMount(){this.subscribeToDocumentEvents(this.props.doc)}componentDidUpdate(e){e.doc!==this.props.doc&&(this.unsubscribeFromDocumentEvents(e.doc),this.subscribeToDocumentEvents(this.props.doc),(this.state.editing||this.state.deleting)&&setTimeout((()=>{this.setState({editing:!1,deleting:!1})})))}componentWillUnmount(){this.unsubscribeFromDocumentEvents(this.props.doc)}subscribeToDocumentEvents(e){e.on(o.Ay.Events.Cancel,this.handleCancel),e.on(o.Ay.Events.Expanded,this.handleExpanded),e.on(o.Ay.Events.Collapsed,this.handleCollapsed),e.on(o.Ay.Events.EditingStarted,this.handleEditingStarted),e.on(o.Ay.Events.EditingFinished,this.handleEditingFinished),e.on(o.Ay.Events.MarkedForDeletion,this.handleDeletionStarted),e.on(o.Ay.Events.DeletionFinished,this.handleDeletionFinished)}unsubscribeFromDocumentEvents(e){e.removeListener(o.Ay.Events.Cancel,this.handleCancel),e.removeListener(o.Ay.Events.Expanded,this.handleExpanded),e.removeListener(o.Ay.Events.Collapsed,this.handleCollapsed),e.removeListener(o.Ay.Events.EditingStarted,this.handleEditingStarted),e.removeListener(o.Ay.Events.EditingFinished,this.handleEditingFinished),e.removeListener(o.Ay.Events.MarkedForDeletion,this.handleDeletionStarted),e.removeListener(o.Ay.Events.DeletionFinished,this.handleDeletionFinished)}handleCopy(){this.props.copyToClipboard?.(this.props.doc)}handleClone(){const e=this.props.doc.generateObject({excludeInternalFields:!0});this.props.openInsertDocumentDialog?.(e,!0)}handleCancel=()=>{this.state.editing?this.props.doc.finishEditing():this.state.deleting&&this.props.doc.finishDeletion()};handleDelete(){this.props.doc.markForDeletion()}handleDeletionStarted=()=>{this.setState({editing:!1,deleting:!0})};handleDeletionFinished=()=>{this.setState({deleting:!1})};handleExpandAll(){const{doc:e}=this.props;this.state.expanded?e.collapse():e.expand()}handleExpanded=()=>{this.setState({expanded:!0})};handleCollapsed=()=>{this.setState({expanded:!1})};handleStartEditing(){this.props.doc.startEditing()}handleEditingStarted=()=>{this.setState({editing:!0})};handleEditingFinished=()=>{this.setState({editing:!1})};renderActions(){if(!this.state.editing&&!this.state.deleting)return r().createElement(s.gD8.YO,{onEdit:this.handleStartEditing.bind(this),onCopy:this.handleCopy.bind(this),onRemove:this.handleDelete.bind(this),onClone:this.handleClone.bind(this),onExpand:this.handleExpandAll.bind(this),expanded:this.state.expanded,insights:this.props.showInsights?u(this.props.doc):void 0})}renderElements(){return r().createElement(s.gD8.yo,{value:this.props.doc,editable:!0,editing:this.state.editing,onEditStart:this.handleStartEditing.bind(this),onUpdateQuery:this.props.onUpdateQuery,query:this.props.query})}renderFooter(){return r().createElement(s.gD8.eQ,{doc:this.props.doc,editing:this.state.editing,deleting:this.state.deleting,onUpdate:e=>{e?this.props.replaceDocument?.(this.props.doc):this.props.updateDocument?.(this.props.doc)},onDelete:()=>{this.props.removeDocument?.(this.props.doc)},onCancel:()=>{this.handleCancel()}})}render(){return r().createElement("div",{className:m,"data-testid":"editable-document"},r().createElement("div",{className:g},r().createElement("div",{className:y,"data-testid":"editable-document-elements"},this.renderElements()),this.renderActions()),this.renderFooter())}static displayName="EditableDocument"}const v=(0,l.tC)(b,["showInsights"]),x=e=>{const{editable:t,isTimeSeries:n,copyToClipboard:s,openInsertDocumentDialog:l,doc:c,onUpdateQuery:d,query:u}=e,p=(0,a.useMemo)((()=>"function"==typeof c?.isRoot&&c?.isRoot()?c:new o.Ay(c)),[c]);return t&&n?r().createElement(f,{doc:p,copyToClipboard:s,openInsertDocumentDialog:(e,t)=>{l?.(e,t)},onUpdateQuery:d,query:u}):t?r().createElement(v,(0,i.A)({},e,{doc:p,onUpdateQuery:d,query:u})):r().createElement(f,{doc:p,copyToClipboard:s,onUpdateQuery:d,query:u})},E=r().memo(x);var C=n(13353),w=n(90605);const I=(0,s.AHW)({listStyle:"inherit"});function S({csfleState:e}){let t;switch(e.encryptedFields&&e.encryptedFields.length>0&&(t=r().createElement("div",null,"The following fields will be encrypted according to the collection schema: ",r().createElement("ul",{className:I},e.encryptedFields.map((e=>r().createElement("li",{key:e},e)))))),e.state){case"none":return r().createElement(r().Fragment,null);case"no-known-schema":return r().createElement(s.lZ$,{variant:s.uAY.Warning},"This insert operation will not encrypt any document fields because no schema or In-Use Encryption configuration is associated with the collection.");case"incomplete-schema-for-cloned-doc":return r().createElement(s.lZ$,{"data-testid":"incomplete-schema-for-cloned-doc",variant:s.uAY.Danger},"This insert operation will not encrypt all fields that were encrypted in the original document due to a missing or incomplete schema for this collection.",t);case"has-known-schema":return r().createElement(s.lZ$,{"data-testid":"insert-csfle-has-known-schema",variant:s.uAY.Info},"This insert operation will encrypt all fields that are specified in the schema or In-Use Encryption configuration associated with the collection.",t);case"csfle-disabled":return r().createElement(s.lZ$,{variant:s.uAY.Warning},"This insert operation will not encrypt any document fields because In-Use Encryption support was explicitly disabled.");default:throw new Error(`Unknown CSFLE state ${e.state} (Compass bug)`)}}S.displayName="InsertCSFLEWarningBanner";const A=S;var k=n(70724);const D=(0,s.AHW)({borderLeft:`3px solid ${s.MFm.gray.light2}`}),N=(0,s.AHW)({borderLeft:`3px solid ${s.MFm.gray.dark2}`}),M=(0,s.U6i)((({darkMode:e,jsonDoc:t,isCommentNeeded:n,updateJsonDoc:i})=>{const[o,l]=(0,a.useState)((()=>n?`/** \n* Paste one or more documents here\n*/\n${t}`:t));return r().createElement("div",{className:(0,s.cx)(e?N:D)},r().createElement(k.Jn,{"data-testid":"insert-document-json-editor",language:"json",text:o,onChangeText:e=>{l(e),i(e.split("*/\n").pop()??"")},initialJSONFoldAll:!1,minLines:18}))})),T=(0,s.AHW)({paddingBottom:s.YKD[7]}),P=function({doc:e}){return r().createElement("div",{className:T,"data-testid":"insert-document-modal"},r().createElement(s.gD8.yo,{value:e,editable:!0,editing:!0}))};var L=n(44142);const O="insert-document-view",R=(0,s.AHW)({marginTop:s.YKD[200],display:"flex",justifyContent:"flex-end"}),H=(0,s.AHW)({marginTop:s.YKD[400]}),F=(0,s.AHW)({marginTop:s.YKD[400]}),W=(0,s.AHW)({float:"right"}),j=({jsonView:e,doc:t,hasManyDocuments:n,updateJsonDoc:a,jsonDoc:i,isCommentNeeded:o,updateComment:l})=>e?r().createElement(M,{updateJsonDoc:a,jsonDoc:i,isCommentNeeded:o,updateComment:l}):n()?r().createElement(s.lZ$,{variant:"warning"},"This view is not supported for multiple documents. To specify data types and use other functionality of this view, please insert documents one at a time."):t?r().createElement(P,{doc:t}):null,B=(0,L.V_)((({isOpen:e,jsonView:t,jsonDoc:n,doc:i,isCommentNeeded:l,error:c,ns:d,csfleState:u,track:p,insertMany:m,insertDocument:g,toggleInsertDocument:h,toggleInsertDocumentView:f,updateJsonDoc:y,updateComment:b,closeInsertDocumentDialog:v})=>{const[x,E]=(0,a.useState)([]),[C,I]=(0,a.useState)(!1),S=(0,a.useCallback)((()=>{let e;try{e=JSON.parse(n)}catch{return!1}return Array.isArray(e)}),[n]),k=(0,a.useMemo)((()=>{if(t)try{return o.Ay.FromEJSON(n),!1}catch(e){return e.message}return x.length>0&&"Insert not permitted while document contains errors."}),[n,t,x]),D=(0,a.useCallback)((e=>{x.includes(e.uuid)||E((t=>[...t,e.uuid]))}),[x]),N=(0,a.useCallback)((e=>{E(k?t=>(0,w.without)(t,e.uuid):[])}),[k,E]);(0,a.useEffect)((()=>{e&&p&&p("Screen",{name:"insert_document_modal"},void 0)}),[e,p]),(0,s.wTI)((()=>{t||E([])}),[t]),(0,a.useEffect)((()=>{if(i)return i.addListener(o.Hg.Events.Invalid,D),i.addListener(o.Hg.Events.Valid,N),i.addListener(o.Hg.Events.Removed,N),()=>{i.removeListener(o.Hg.Events.Invalid,D),i.removeListener(o.Hg.Events.Valid,N),i.removeListener(o.Hg.Events.Removed,N)}}),[i,D,N]);const M=(0,a.useCallback)((()=>{I(!0),setTimeout((()=>{I(!1)}),0),S()?m():g()}),[I,m,g,S]),T=(0,a.useCallback)((e=>{S()?f(e):h(e)}),[S,h,f]),P=t?"JSON":"List",L=(0,a.useMemo)((()=>k?{message:k,variant:"danger"}:C?{message:"Inserting Document",variant:"info"}:c?{message:c.message,variant:"danger",info:c.info}:null),[c,k,C]);return r().createElement(s.k5W,{title:"Insert Document",subtitle:`To collection ${d}`,open:e,onSubmit:M.bind(void 0),onCancel:v,submitButtonText:"Insert",submitDisabled:Boolean(k),"data-testid":"insert-document-modal",minBodyHeight:2*s.YKD[1600]},r().createElement("div",{className:R},r().createElement(s.IzF,{label:"View",size:"xsmall",value:P,"aria-controls":O,onChange:T.bind(void 0)},r().createElement(s.Zib,{disabled:Boolean(k),"data-testid":"insert-document-dialog-view-json","aria-label":"E-JSON View",value:"JSON",glyph:r().createElement(s.Int,{glyph:"CurlyBraces"}),onClick:e=>{e.preventDefault()}}),r().createElement(s.Zib,{disabled:Boolean(k),"data-testid":"insert-document-dialog-view-list","aria-label":"Document list",value:"List",onClick:e=>{e.preventDefault()},glyph:r().createElement(s.Int,{glyph:"Menu"})}))),r().createElement("div",{className:H,id:O},r().createElement(j,{jsonView:t,doc:i,hasManyDocuments:S,updateJsonDoc:y,jsonDoc:n,isCommentNeeded:l,updateComment:b})),L&&r().createElement(s.lZ$,{"data-testid":"insert-document-banner","data-variant":L.variant,variant:L.variant,className:F},L.message,L.info&&r().createElement(s.$nd,{size:"xsmall",className:W,onClick:()=>(0,s.a0R)({details:L.info,closeAction:"back"}),"data-testid":"insert-document-error-details-button"},"VIEW ERROR DETAILS")),r().createElement(A,{csfleState:u}))}),"COMPASS-CRUD-UI");var z=n(9174),_=n(67092),$=n(6415),Y=n.n($);function K(e){return"[object Object]"===Object.prototype.toString.call(e)&&!(0,_.TB)(e)}function G(e){return Array.isArray(e)?"array":K(e)?"object":"leaf"}function V(e){if(e?.inspect)return e.inspect();if(e?.toISOString)try{return e.toISOString()}catch{return String(e)}return C.EJSON.stringify(e)}function U(e){const t=G(e);if("array"===t)return e.map(U);if("object"===t){const t=Object.create(null);for(const[n,a]of Object.entries(e))t[n]=U(a);return t}if((0,_.TB)(e))return V(e);if("[object RegExp]"===Object.prototype.toString.call(e))return e.toString();if("[object Date]"!==Object.prototype.toString.call(e))return e;try{return e.toISOString()}catch{return String(e)}}const q=n(17001).vt({arrays:{detectMove:!1},textDiff:{minLength:1/0},objectHash:function(e){return V(e)}});function Z({left:e,right:t,delta:n,implicitChangeType:a}){const r="added"===a?t.value:e.value,i=Object.entries(r).map((([n,r])=>{const i={implicitChangeType:a,objectKey:n,delta:null},o=e?{path:[...e.path,n],value:r}:void 0,s=t?{path:[...t.path,n],value:t.value[n]}:void 0;if(o&&s)return{...i,changeType:"unchanged",left:o,right:s};if(o)return{...i,changeType:"removed",left:o};if(s)return{...i,changeType:"added",right:s};throw new Error("left or right required or both")}));if(n){Y()(K(n),"delta should be a simple object");for(const[e,r]of Object.entries(n))if(Array.isArray(r))if(1===r.length)i.push({implicitChangeType:a,changeType:"added",objectKey:e,right:{path:[...t.path,e],value:r[0]},delta:null});else if(2===r.length){const t=i.find((t=>t.objectKey===e));t?(t.right.value=r[1],t.changeType="changed"):Y()(!1,`property with key "${e} does not exist"`)}else if(3===r.length){const t=i.find((t=>t.objectKey===e));t?(t.changeType="removed",delete t.right):Y()(!1,`property with key "${e} does not exist"`)}else Y()(!1,"unexpected change length");else{Y()(K(r),"change should be a simple object");const t=i.find((t=>t.objectKey===e));t?t.delta=r:Y()(!1,`property with key "${e} does not exist"`)}}let o=!0;for(;o;){o=!1;const e=i.findIndex((e=>"changed"===e.changeType&&G(e.left.value)!==G(e.right.value)));if(-1!==e){const t=i[e];o=!0;const n={implicitChangeType:a,changeType:"removed",objectKey:t.objectKey,left:t.left,delta:null},r={implicitChangeType:a,changeType:"added",objectKey:t.objectKey,right:{path:t.left.path,value:t.right.value},delta:null};i.splice(e,1,n,r)}}for(const e of i){const t=G("added"===e.changeType?e.right.value:e.left.value);"array"===t?e.items=J({left:e.left??void 0,right:e.right??void 0,delta:e.delta,implicitChangeType:Q(e)}):"object"===t&&(e.properties=Z({left:e.left??void 0,right:e.right??void 0,delta:e.delta,implicitChangeType:Q(e)}))}return i}function J({left:e,right:t,delta:n,implicitChangeType:a}){const r=("added"===a?t.value:e.value).map(((n,r)=>{const i={implicitChangeType:a,index:r,delta:null},o=e?{path:[...e.path,r],value:n}:void 0,s=t?{path:[...t.path,r],value:n}:void 0;if(o&&s)return{...i,changeType:"unchanged",left:o,right:s};if(o)return{...i,changeType:"removed",left:o};if(s)return{...i,changeType:"added",right:s};throw new Error("left or right required or both")}));if(n){Y()("_t"in n&&"a"===n._t,"delta._t is not a");const i=Object.keys(n).filter((e=>e.startsWith("_")&&"_t"!==e)).map((e=>parseInt(e.slice(1),10)));for(const e of i){const t=r[e];t?(t.changeType="removed",delete t.right):Y()(!1,`item with index "${e}" does not exist`)}for(const[i,o]of Object.entries(n))if(!i.startsWith("_")){const n=parseInt(i,10);Y()(Array.isArray(o),"unexpected non-array"),Y()(3!==o.length,"array moves are not supported"),Y()(2!==o.length,"array changes are not supported");for(const e of r)e.index>=n&&"removed"!==e.changeType&&(e.index=e.index+1);r.splice(n,0,{implicitChangeType:a,changeType:"added",index:n,right:{path:[...(t??e).path,n],value:o[0]},delta:null})}}for(const e of r){const t=G("added"===e.changeType?e.right.value:e.left.value);"array"===t?e.items=J({left:e.left??void 0,right:e.right??void 0,delta:e.delta,implicitChangeType:Q(e)}):"object"===t&&(e.properties=Z({left:e.left??void 0,right:e.right??void 0,delta:e.delta,implicitChangeType:Q(e)}))}return r}function Q(e){return["added","removed"].includes(e.implicitChangeType)?e.implicitChangeType:e.changeType}const X=(0,s.AHW)({margin:0,padding:0,border:"none",background:"none","&:hover":{cursor:"pointer"},display:"flex",alignSelf:"center",color:"inherit",paddingRight:s.YKD[100]}),ee=(0,s.AHW)({backgroundColor:s.MFm.green.dark2}),te=(0,s.AHW)({backgroundColor:s.MFm.green.light1}),ne=(0,s.AHW)({backgroundColor:s.MFm.red.dark3}),ae=(0,s.AHW)({backgroundColor:s.MFm.red.light2});function re(e){const t=(e.right??e.left).path,n=[];for(const e of t)"string"==typeof e?n.push(`["${e.replace(/"/g,"\\")}"]`):n.push(`[${e}]`);return n.join("")+"_"+e.changeType}const ie=(0,s.AHW)({display:"flex",flexDirection:"column",marginTop:"1px"}),oe=(0,s.AHW)({fontWeight:"bold",alignSelf:"flex-start",paddingRight:s.YKD[100]}),se=(0,s.AHW)({display:"inline-flex",alignItems:"flex-start"});function le(e,t){const n=Te(e);if("unchanged"!==n&&"changed"!==n)return"added"===n?t?ee:te:t?ne:ae}function ce({isOpen:e,toggleIsOpen:t}){return r().createElement("button",{type:"button","aria-pressed":e,"aria-label":e?"Collapse field items":"Expand field items",className:X,onClick:t},r().createElement(s.Int,{size:"xsmall",glyph:e?"CaretDown":"CaretRight"}))}function de({item:e}){const[t,n]=(0,a.useState)(!!e.delta||"unchanged"!==e.changeType),i=le(e,(0,s.D27)());return r().createElement("div",{className:ie},r().createElement("div",{className:se},r().createElement(ce,{isOpen:t,toggleIsOpen:function(){n(!t)}}),r().createElement("div",{className:(0,s.cx)(oe,i)},e.index,":"),r().createElement("div",{className:i},"Array")),r().createElement(xe,{obj:e,isOpen:t}))}function ue({item:e}){const[t,n]=(0,a.useState)(!!e.delta||"unchanged"!==e.changeType),i=le(e,(0,s.D27)());return r().createElement("div",{className:ie},r().createElement("div",{className:se},r().createElement(ce,{isOpen:t,toggleIsOpen:function(){n(!t)}}),r().createElement("div",{className:(0,s.cx)(oe,i)},e.index,":"),r().createElement("div",{className:i},"Object")),r().createElement(De,{obj:e,isOpen:t}))}const pe=(0,s.AHW)({paddingLeft:s.YKD[400]});function me({item:e}){const t=le(e,(0,s.D27)());return r().createElement("div",{className:(0,s.cx)(ie,pe)},r().createElement("div",{className:se},r().createElement("div",{className:(0,s.cx)(oe,t)},e.index,":"),r().createElement("div",{className:t},r().createElement(Oe,{obj:e}))))}function ge({item:e}){const t=G("added"===e.changeType?e.right.value:e.left.value);return"array"===t?r().createElement(de,{item:e}):"object"===t?r().createElement(ue,{item:e}):r().createElement(me,{item:e})}const he=(0,s.AHW)({marginRight:s.YKD[100]});function fe(){return r().createElement("span",{className:he},", ")}const ye=(0,s.AHW)({display:"flex",flexDirection:"column",paddingLeft:s.YKD[400]}),be=(0,s.AHW)({marginTop:"1px"}),ve=(0,s.AHW)({marginLeft:s.YKD[600]+s.YKD[100],display:"inline-flex",flexWrap:"wrap"});function xe({obj:e,isOpen:t}){if(t){const t=Q(e);if(e.items.every((e=>{const t="added"===e.changeType?e.right.value:e.left.value;return"leaf"===G(t)&&!(0,_.TB)(t)}))){const n=[ve];return"added"===t&&n.push("change-array-inline-added"),"removed"===t&&n.push("change-array-inline-removed"),r().createElement("div",{className:be},r().createElement("div",{className:(0,s.cx)(...n)},"[",e.items.map(((t,n)=>{const a=re(t);return r().createElement("div",{className:"change-array-inline-element",key:a},r().createElement(Oe,{obj:t}),n!==e.items.length-1&&r().createElement(fe,null))})),"]"))}return r().createElement("div",{className:ye},e.items.map((e=>{const t=re(e);return r().createElement(ge,{key:t,item:e})})))}return null}function Ee({property:e}){const[t,n]=(0,a.useState)(!!e.delta||"unchanged"!==e.changeType),i=le(e,(0,s.D27)());return r().createElement("div",{className:Ce},r().createElement("div",{className:se},r().createElement(ce,{isOpen:t,toggleIsOpen:function(){n(!t)}}),r().createElement("div",{className:(0,s.cx)(oe,i)},e.objectKey,":"),r().createElement("div",{className:i},"Object")),r().createElement(De,{obj:e,isOpen:t}))}const Ce=(0,s.AHW)({display:"flex",flexDirection:"column",marginTop:"1px"});function we({property:e}){const[t,n]=(0,a.useState)(!!e.delta||"unchanged"!==e.changeType),i=le(e,(0,s.D27)());return r().createElement("div",{className:Ce},r().createElement("div",{className:se},r().createElement(ce,{isOpen:t,toggleIsOpen:function(){n(!t)}}),r().createElement("div",{className:(0,s.cx)(oe,i)},e.objectKey,":"),r().createElement("div",{className:i},"Array")),r().createElement(xe,{obj:e,isOpen:t}))}function Ie({property:e}){const t=le(e,(0,s.D27)());return r().createElement("div",{className:(0,s.cx)(Ce,pe)},r().createElement("div",{className:se},r().createElement("div",{className:(0,s.cx)(oe,t)},e.objectKey,":"),r().createElement("div",{className:t},r().createElement(Oe,{obj:e}))))}function Se({property:e}){const t=G("added"===e.changeType?e.right.value:e.left.value);return"array"===t?r().createElement(we,{property:e}):"object"===t?r().createElement(Ee,{property:e}):r().createElement(Ie,{property:e})}const Ae=(0,s.AHW)({display:"flex",flexDirection:"column",paddingLeft:s.YKD[400]}),ke=(0,s.AHW)({paddingLeft:0});function De({obj:e,isOpen:t,isRoot:n}){return t?r().createElement("div",{className:(0,s.cx)(Ae,n&&ke)},e.properties.map((e=>{const t=re(e);return r().createElement(Se,{key:t,property:e})}))):null}function Ne(e,t){const n=t?ee:te,a=t?ne:ae;return"removed"===e.implicitChangeType?a:"added"===e.implicitChangeType?n:"unchanged"!==e.changeType?"removed"===e.changeType||"changed"===e.changeType?a:n:void 0}function Me(e,t){return t?ee:te}function Te(e){return["added","removed"].includes(e.implicitChangeType)?e.implicitChangeType:e.changeType}function Pe(e,t){const[n,...a]=e;return a.length?Pe(a,t[n]):t[n]}const Le=(0,s.AHW)({display:"inline-flex",flexWrap:"wrap",columnGap:s.YKD[100],rowGap:"1px"});function Oe({obj:e}){const{left:t,right:n}=(0,a.useContext)(Re),i=Te(e),o=["unchanged","changed","removed"].includes(i),l=["changed","added"].includes(i),c=(0,s.D27)(),d=o?Pe(e.left.path,t):void 0,u=l?Pe(e.right.path,n):void 0;return r().createElement("div",{className:Le},o&&r().createElement("div",{className:Ne(e,c)},r().createElement(s.sPs,{type:_.Ay.type(d),value:d})),l&&r().createElement("div",{className:Me(0,c)},r().createElement(s.sPs,{type:_.Ay.type(u),value:u})))}const Re=(0,a.createContext)(null),He=(0,s.AHW)({overflow:"auto",fontFamily:s.aIi.code,fontSize:"12px",lineHeight:"16px"}),Fe=(0,s.AHW)({color:s.MFm.gray.light2}),We=(0,s.AHW)({color:s.MFm.gray.dark2});function je({name:e,before:t,after:n}){const i=(0,a.useMemo)((()=>function(e,t){const n=U(e),a=U(t),r={left:{path:[],value:n},right:{path:[],value:a},delta:q.diff(n,a)??null,implicitChangeType:"unchanged",changeType:"unchanged"};return{...r,properties:Z({left:r.left??void 0,right:r.right??void 0,delta:r.delta,implicitChangeType:"unchanged"})}}(t,n)),[t,n]),o=(0,s.D27)();return r().createElement(Re.Provider,{value:{left:t,right:n}},r().createElement("div",{className:(0,s.cx)(He,o?Fe:We),"data-testid":`change-view-${e}`},r().createElement(De,{obj:i,isOpen:!0,isRoot:!0})))}const Be=(0,s.AHW)({display:"flex",gap:s.YKD[200],alignItems:"center"}),ze=(0,s.AHW)({padding:s.YKD[200],overflow:"scroll",width:"100%",whiteSpace:"nowrap",display:"inline-block",verticalAlign:"middle",lineHeight:`${s.YKD[400]+2}px`,"::-webkit-scrollbar":{display:"none"}}),_e=(0,s.AHW)({fontSize:14,fontFamily:s.aIi.code});function $e({queryLabel:e="Filter",filterQuery:t}){const n=(0,s.BiT)();return r().createElement(r().Fragment,null,r().createElement("div",{className:Be},r().createElement(s.JU7,{htmlFor:n},e),r().createElement(s.Ls4,{align:"right"},"Return to the Documents tab to edit this query.")),r().createElement(s.yY_,{id:n,"data-testid":"readonly-filter",className:ze},r().createElement("code",{className:_e},"{}"===t?"None":t)))}var Ye=n(2155);const Ke=(0,s.AHW)({width:"100%",maxWidth:`calc(min(100vw, 1280px) - 2 * ${s.YKD[800]}px)`}),Ge=(0,s.AHW)({marginTop:s.YKD[600],display:"grid",width:"100%",gap:s.YKD[600],gridTemplateColumns:"475px 1fr"}),Ve=(0,s.AHW)({display:"flex",gap:s.YKD[600],flexDirection:"column"}),Ue=(0,s.AHW)({}),qe=(0,s.AHW)({flex:1}),Ze=(0,s.AHW)({marginBottom:s.YKD[200]}),Je=(0,s.AHW)({display:"inline"}),Qe=(0,s.AHW)({paddingTop:s.YKD[200],paddingBottom:s.YKD[200]}),Xe=(0,s.AHW)({}),et=(0,s.AHW)({backgroundColor:s.MFm.gray.light3}),tt=(0,s.AHW)({height:`calc(100% - ${s.YKD[1600]})`}),nt=(0,s.AHW)({minHeight:2*s.YKD[600]+2,overflow:"hidden"}),at=(0,s.AHW)({flex:"none",marginTop:s.YKD[200],marginLeft:s.YKD[200],marginRight:s.YKD[200],textAlign:"left"}),rt=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[400]}),it=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[400],contain:"size",height:"calc(100% - 20px)",overflowY:"scroll"}),ot=(0,s.AHW)({display:"flex",flexDirection:"row",justifyContent:"space-between"}),st=(0,s.AHW)({display:"flex",flexDirection:"row",gap:s.YKD[200]}),lt=(0,s.AHW)({}),ct=(0,s.AHW)({display:"flex",flexDirection:"row",padding:s.YKD[400],gap:s.YKD[400]}),dt=(0,s.AHW)({width:"315px"}),ut=["#inline-save-query-modal *"],pt=({disabled:e,onSave:t})=>{const[n,i]=(0,a.useState)(!1),[o,l]=(0,a.useState)(""),[c,d]=(0,a.useState)(!1),u=(0,a.useCallback)((()=>{i(!1),l("")}),[i,l]),p=(0,a.useCallback)((()=>{t(o),u()}),[t,o,u]),m=(0,a.useCallback)((e=>{const t=e.target.value||"";l(t),d(""!==t)}),[l,d]),g=(0,a.useCallback)((e=>{"Enter"===e.key?(t(o),u()):"Escape"===e.key&&u()}),[o,t,u]);return r().createElement(s.WA6,{containedElements:ut,trigger:({onClick:t,children:a})=>r().createElement(s.$nd,{variant:"default",onClick:t,"data-testid":"inline-save-query-modal-opener","aria-haspopup":"true","aria-expanded":!!n||void 0,disabled:e},r().createElement(s.Int,{glyph:"Favorite"}),"Save",a),align:"top",hideCloseButton:!0,customFocusTrapFallback:"#inline-save-query-modal-cancel-button",open:n,setOpen:i},r().createElement("div",{id:"inline-save-query-modal",className:ct},r().createElement(s.ksK,{id:"inline-save-query-modal-input","data-testid":"inline-save-query-modal-input",className:dt,"aria-label":"Saved query name",value:o,onChange:m,onKeyUp:g}),r().createElement(s.$nd,{"data-testid":"inline-save-query-modal-submit",variant:"primary",disabled:!c,onClick:p},"Save"),r().createElement(s.$nd,{id:"inline-save-query-modal-cancel-button",variant:"default",onClick:u},"Cancel")))},mt=(0,s.AHW)({margin:"auto",display:"flex",flexDirection:"column",gap:s.YKD[200],alignItems:"center"}),gt=(0,s.AHW)({color:s.MFm.green.dark2}),ht=(0,s.AHW)({textAlign:"center",margin:0}),ft=({count:e,preview:t})=>0===e?r().createElement("div",{"data-testid":"bulk-update-preview-empty-state",className:rt},r().createElement(s.JU7,{htmlFor:"bulk-update-preview"},"Preview"," ",r().createElement(s.VYo,{className:Je},"(sample of ",t.changes.length," document",1===t.changes.length?"":"s",")")),r().createElement("div",{className:mt},r().createElement(s.pyG,null),r().createElement("b",{className:gt},"No results"),r().createElement("p",{className:ht},"Try modifying your query to get results."))):r().createElement("div",null,r().createElement(s.JU7,{htmlFor:"bulk-update-preview"},"Preview"," ",r().createElement(s.VYo,{className:Je},"(sample of ",t.changes.length," document",1===t.changes.length?"":"s",")")),r().createElement("div",{className:it},t.changes.map((({before:e,after:t},n)=>r().createElement(vt,{key:`change=${n}`,"data-testid":"bulk-update-preview-document",before:e,after:t})))));function yt({isOpen:e,ns:t,filter:n,count:i,updateText:o,preview:l,syntaxError:c,serverError:d,enablePreview:u=!1,closeBulkUpdateModal:p,updateBulkUpdatePreview:m,runBulkUpdate:g,saveUpdateQuery:h}){const f=(0,s.D27)(),[y,b]=(0,a.useState)(o),v=(0,a.useMemo)((()=>c?.loc?.index?[{message:c.message,severity:"error",from:c.loc.index,to:c.loc.index}]:[]),[c]);(0,s.wTI)((()=>{e&&b(o)}),[e]);const x=(0,a.useMemo)((()=>"number"!=typeof i?"Update documents":1===i?"Update 1 document":`Update ${i} documents`),[i]),E=(0,s.BiT)(),C=!(!c&&!d),w=!!(0,Ye.n_)();return r().createElement(s.aFV,{open:e,setOpen:p,"data-testid":"bulk-update-modal",className:u?Ke:void 0,initialFocus:`#${E} .cm-content`},r().createElement(s.rQ0,{title:x,subtitle:t}),r().createElement(s.cwr,null,r().createElement("div",{className:u?Ge:void 0},r().createElement("div",{className:Ve},r().createElement("div",{className:Ue},r().createElement($e,{filterQuery:(0,z.AO)(n)??""})),r().createElement("div",{className:(0,s.cx)(Ue,qe)},r().createElement(s.JU7,{htmlFor:E},"Update"),r().createElement(s.VYo,{className:Ze},r().createElement(s.N_E,{tabIndex:0,href:"https://www.mongodb.com/docs/manual/reference/method/db.collection.updateMany/#std-label-update-many-update"},"Learn more about Update syntax")),r().createElement(s.yY_,{className:(0,s.cx)(Qe,tt,f?Xe:et)},r().createElement(k.Jn,{text:y,onChangeText:e=>{b(e),m(e)},id:E,"data-testid":"bulk-update-update",onBlur:()=>({}),annotations:v,minLines:12}),r().createElement("div",{className:nt},c&&r().createElement(s.lZ$,{variant:s.uAY.Warning,className:at},c.message),d&&!c&&r().createElement(s.lZ$,{variant:s.uAY.Danger,className:at},d.message))))),u&&r().createElement(ft,{count:i,preview:l}))),r().createElement(s.jlY,{className:ot},r().createElement("div",{className:lt},w&&r().createElement(pt,{disabled:C,onSave:h})),r().createElement("div",{className:st},r().createElement(s.$nd,{variant:"default",onClick:p,"data-testid":"cancel-button"},"Cancel"),r().createElement(s.$nd,{disabled:C,variant:"primary",onClick:g,"data-testid":"update-button"},x))))}const bt=(0,s.AHW)({padding:s.YKD[400]});function vt({before:e,after:t,...n}){return r().createElement(s.yY_,{"data-testid":n["data-testid"],className:bt},r().createElement(je,{before:e,after:t,name:n["data-testid"]}))}function xt({doc:e,isEditable:t,copyToClipboard:n,openInsertDocumentDialog:a}){const{expanded:r,editing:i}=e;return(0,s.MdH)((()=>[t?{telemetryLabel:"Document Item Edit",items:[{label:i?"Cancel editing":"Edit document",onAction:()=>{i?e.finishEditing():e.startEditing()}}]}:void 0,{telemetryLabel:"Document Item",items:[{label:r?"Collapse all fields":"Expand all fields",onAction:()=>{r?e.collapse():e.expand()}},{label:"Copy document",onAction:()=>{n?.(e)}},t?{label:"Clone document...",onAction:()=>{const t=e.generateObject({excludeInternalFields:!0});a?.(t,!0)}}:void 0]},t&&!i?{telemetryLabel:"Document Item Delete",items:[{label:"Delete document",onAction:()=>{e.markForDeletion()}}]}:void 0]),[e,r,i,t,n,a])}var Et=n(25540);const Ct=({doc:e,docRef:t,docIndex:n,isEditable:i,isTimeSeries:o,scrollTriggerRef:l,copyToClipboard:c,removeDocument:d,replaceDocument:u,updateDocument:p,openInsertDocumentDialog:m})=>{const g=xt({doc:e,isEditable:i,copyToClipboard:c,openInsertDocumentDialog:m}),h=(0,Et.fE)(),f=(0,Et.vE)(),y=(0,a.useCallback)(((e,t)=>{h("toggleDistinctValue",{field:e,value:t})}),[h]),b=(0,s.SVd)([t,g]);return r().createElement(s.yY_,{ref:b},l&&0===n&&r().createElement("div",{ref:l}),r().createElement(E,{doc:e,key:e.uuid,query:f.filter,onUpdateQuery:y,editable:i,isTimeSeries:o,copyToClipboard:c,removeDocument:d,replaceDocument:u,updateDocument:p,openInsertDocumentDialog:m}))},wt=(0,s.AHW)({padding:s.YKD[400],paddingTop:0,paddingRight:s.YKD[150]}),It=e=>s.YKD[25]+s.YKD[25]+(s.YKD[400]+s.YKD[400])+(25<e.elements.size?s.YKD[400]+s.YKD[200]:0)+Math.min(25,e.elements.size)*(s.YKD[400]+s.YKD[25]),St=({docs:e,isEditable:t,isTimeSeries:n,initialScrollTop:i,scrollTriggerRef:l,scrollableContainerRef:c,copyToClipboard:d,removeDocument:u,replaceDocument:p,updateDocument:m,openInsertDocumentDialog:g,listRef:h,__TEST_OVERSCAN_COUNT:f,__TEST_LIST_HEIGHT:y})=>{const b=(0,a.useMemo)((()=>e.map((e=>"function"==typeof e?.isRoot&&e?.isRoot()?e:new o.Ay(e)))),[e]),v=(0,a.useCallback)(((e,a,i)=>r().createElement(Ct,{doc:e,docRef:a,docIndex:i,isEditable:t,isTimeSeries:n,scrollTriggerRef:l,copyToClipboard:d,removeDocument:u,replaceDocument:p,updateDocument:m,openInsertDocumentDialog:g})),[t,n,l,d,g,u,p,m]);return r().createElement(s.wjn,{items:b,renderItem:v,estimateItemInitialHeight:It,rowGap:s.YKD[200],dataTestId:"document-list",itemDataTestId:"document-list-item",listOuterContainerClassName:wt,initialScrollTop:i,scrollableContainerRef:c,listRef:h,overScanCount:f,__TEST_LIST_HEIGHT:y})};var At=n(25607);const kt=(0,s.AHW)({minHeight:s.YKD[800]+s.YKD[400],"& .cm-editor":{backgroundColor:`${s.MFm.white} !important`},"& .cm-gutters":{backgroundColor:`${s.MFm.white} !important`}}),Dt=(0,s.AHW)({"& .cm-editor":{backgroundColor:`${s.MFm.black} !important`},"& .cm-gutters":{backgroundColor:`${s.MFm.black} !important`}}),Nt=(0,s.AHW)({padding:s.YKD[200]}),Mt=({namespace:e,doc:t,editable:n,isTimeSeries:i=!1,removeDocument:l,replaceDocument:c,copyToClipboard:d,openInsertDocumentDialog:u})=>{const p=(0,s.D27)(),m=(0,a.useRef)(null),[g,h]=(0,a.useState)(t.expanded),[f,y]=(0,a.useState)(t.editing),[b,v]=(0,a.useState)(t.markedForDeletion),[x,E]=(0,a.useState)((()=>t.modifiedEJSONString??t.toEJSON())),[C]=(0,a.useState)((()=>t.toEJSON())),[w,I]=(0,a.useState)(null),S=(0,s.HIF)(t.setModifiedEJSONString.bind(t));(0,a.useEffect)((()=>{const e=S.current;return()=>{e(f?x:null)}}),[x,f,S]);const A=(0,a.useCallback)((()=>{d?.(t)}),[d,t]),D=(0,a.useCallback)((()=>{const e=t.generateObject({excludeInternalFields:!0});u?.(e,!0)}),[t,u]),N=(0,a.useCallback)((e=>{try{o.Ay.FromEJSON(e),I(null)}catch(e){I(e)}finally{E(e)}}),[]),M=(0,a.useCallback)((()=>{f?t.finishEditing():b&&t.finishDeletion(),E(t.toEJSON())}),[t,f,b]),T=(0,a.useCallback)((()=>{t.startEditing()}),[t]),P=(0,a.useCallback)((()=>{y(!0)}),[]),L=(0,a.useCallback)((()=>{const e=o.Ay.FromEJSON(x||"");e.preserveTypes(t),t.apply(e),c?.(t)}),[t,c,x]),O=(0,a.useCallback)((()=>{y(!1)}),[]),R=(0,a.useCallback)((()=>{t.markForDeletion()}),[t]),H=(0,a.useCallback)((()=>{v(!0)}),[]),F=(0,a.useCallback)((()=>{l?.(t)}),[t,l]),W=(0,a.useCallback)((()=>{v(!1)}),[]),j=(0,a.useCallback)((()=>{h(!0)}),[]),B=(0,a.useCallback)((()=>{h(!1)}),[]),z=(0,At.jv)(e),_=(0,a.useMemo)((()=>(0,k.MM)(z.map((e=>e.name)))),[z]),$=n&&!b&&!i,Y=(0,a.useMemo)((()=>f?[]:[$&&{icon:"Edit",label:"Edit",action(){T()}},{icon:"Copy",label:"Copy",action:()=>(A(),!0)},$&&{icon:"Clone",label:"Clone",action:D},$&&{icon:"Trash",label:"Delete",action(){R()}}].filter(Boolean)),[f,T,R,D,A,$]);(0,a.useEffect)((()=>(t.on(o.Ay.Events.Cancel,M),t.on(o.Ay.Events.Expanded,j),t.on(o.Ay.Events.Collapsed,B),t.on(o.Ay.Events.EditingStarted,P),t.on(o.Ay.Events.EditingFinished,O),t.on(o.Ay.Events.MarkedForDeletion,H),t.on(o.Ay.Events.DeletionFinished,W),()=>{t.removeListener(o.Ay.Events.Cancel,M),t.removeListener(o.Ay.Events.Expanded,j),t.removeListener(o.Ay.Events.Collapsed,B),t.removeListener(o.Ay.Events.EditingStarted,P),t.removeListener(o.Ay.Events.EditingFinished,O),t.removeListener(o.Ay.Events.MarkedForDeletion,H),t.removeListener(o.Ay.Events.DeletionFinished,W)})),[t,M,j,B,P,O,H,W]);const K=(0,a.useCallback)((()=>{t.expanded?t.collapse():t.expand()}),[t]),G=(0,a.useRef)();return(0,a.useEffect)((()=>{G.current&&clearTimeout(G.current),G.current=setTimeout((()=>{m.current&&(g?m.current.unfoldAll():m.current.foldAll())}),0)}),[g]),r().createElement("div",{"data-testid":"editable-json"},r().createElement(k.Jn,{ref:m,"data-testid":"json-editor",language:"json",text:x,onChangeText:N,copyable:!1,formattable:!1,customActions:Y,minLines:3,readOnly:!f,showLineNumbers:f,className:(0,s.cx)(kt,p&&Dt),actionsClassName:Nt,completer:_,onExpand:f?void 0:K,expanded:g}),r().createElement(s.gD8.eQ,{doc:t,alwaysForceUpdate:!0,editing:!!f,deleting:!!b,modified:x!==C,validationError:w,onUpdate:L,onDelete:F,onCancel:M}))},Tt=(0,s.AHW)({overflow:"hidden",position:"relative"}),Pt=({doc:e,docRef:t,docIndex:n,namespace:a,isEditable:i,isTimeSeries:o,scrollTriggerRef:l,copyToClipboard:c,removeDocument:d,replaceDocument:u,updateDocument:p,openInsertDocumentDialog:m})=>{const g=xt({doc:e,isEditable:i,copyToClipboard:c,openInsertDocumentDialog:m}),h=(0,s.SVd)([t,g]);return r().createElement(s.yY_,{className:Tt,ref:h},l&&0===n&&r().createElement("div",{ref:l}),r().createElement(Mt,{doc:e,key:e.uuid,namespace:a,editable:i,isTimeSeries:o,copyToClipboard:c,removeDocument:d,replaceDocument:u,updateDocument:p,openInsertDocumentDialog:m}))},Lt=(0,s.AHW)({padding:s.YKD[400],paddingTop:0,paddingRight:s.YKD[150]}),Ot=e=>s.YKD[25]+s.YKD[25]+(s.YKD[100]+s.YKD[100])+(s.YKD[400]+s.YKD[400])+e.elements.size*s.YKD[400],Rt=({docs:e,namespace:t,isEditable:n,isTimeSeries:i,initialScrollTop:o,scrollTriggerRef:l,scrollableContainerRef:c,copyToClipboard:d,removeDocument:u,replaceDocument:p,updateDocument:m,openInsertDocumentDialog:g,__TEST_OVERSCAN_COUNT:h,__TEST_LIST_HEIGHT:f,listRef:y})=>{const b=(0,a.useCallback)(((e,a,o)=>r().createElement(Pt,{doc:e,docRef:a,docIndex:o,namespace:t,isEditable:n,isTimeSeries:i,scrollTriggerRef:l,copyToClipboard:d,removeDocument:u,replaceDocument:p,updateDocument:m,openInsertDocumentDialog:g})),[n,i,t,l,d,g,u,p,m]);return r().createElement(s.wjn,{items:e,renderItem:b,estimateItemInitialHeight:Ot,rowGap:s.YKD[200],dataTestId:"document-list",itemDataTestId:"document-json-item",overScanCount:h??1,listOuterContainerClassName:Lt,initialScrollTop:o,scrollableContainerRef:c,listRef:y,__TEST_LIST_HEIGHT:f})};var Ht=n(42447),Ft=n(17855);const Wt="ag-header-breadcrumb",jt={Array:"[ ]",Object:"{ }"};class Bt extends r().PureComponent{constructor(e){super(e),this.onTabClicked=this.onTabClicked.bind(this)}onTabClicked(e){this.props.pathChanged(this.props.path.slice(0,e+1),this.props.types.slice(0,e+1))}onHomeClicked(){this.props.pathChanged([],[])}getPathClassName(e){return e===this.props.path.length-1?`${Wt}-tab ${Wt}-tab-active`:`${Wt}-tab`}render(){return r().createElement("div",{className:`${Wt}-container`},r().createElement("button",{type:"button",onClick:this.onHomeClicked.bind(this),className:`${Wt}-tab`},r().createElement(s.Int,{glyph:"Home",size:"xsmall",className:`${Wt}-home-icon`}),this.props.collection),this.props.path.map(((e,t)=>{let n="";return"number"==typeof e&&t>0&&(n=String(this.props.path[t-1])+"."),n=n.concat(String(e)),r().createElement("button",{type:"button",key:t,onClick:()=>this.onTabClicked(t),className:this.getPathClassName(t)},n," ",jt[this.props.types[t]])})))}static defaultPropTypes={collection:""};static displayName="BreadcrumbComponent"}const zt=Bt,_t="editable-element",$t="editable-element-value",Yt=`${$t}-is-invalid-type`,Kt="is-added",Gt="is-edited",Vt="table-view-cell-circle-button",Ut=(0,s.AHW)({display:"flex",alignItems:"center",flexDirection:"row",gap:s.YKD[100]}),qt=(0,s.AHW)({display:"flex"});class Zt extends r().Component{element;isEmpty;isDeleted;editable;constructor(e){if(super(e),this.isEmpty=void 0===e.value||null===e.value,this.isDeleted=!1,this.element=e.value,this.editable=!0,e.context.path.length>0&&"$_id"!==e.column.getColId()){const t=e.node.data.hadronDocument.getChild(e.context.path);if(!t||e.parentType&&t.currentType!==e.parentType)this.editable=!1;else if("Array"===t.currentType){let n=0;t.elements.lastElement&&(n=+t.elements.lastElement.currentKey+1),+e.column.getColId()>n&&(this.editable=!1)}}}componentDidMount(){this.isEmpty||this.subscribeElementEvents()}componentWillUnmount(){this.isEmpty||this.unsubscribeElementEvents()}subscribeElementEvents(){this.element.on(o.Hg.Events.Added,this.handleElementEvent),this.element.on(o.Hg.Events.Converted,this.handleElementEvent),this.element.on(o.Hg.Events.Edited,this.handleElementEvent),this.element.on(o.Hg.Events.Reverted,this.handleElementEvent)}unsubscribeElementEvents(){this.element.removeListener(o.Hg.Events.Added,this.handleElementEvent),this.element.removeListener(o.Hg.Events.Converted,this.handleElementEvent),this.element.removeListener(o.Hg.Events.Edited,this.handleElementEvent),this.element.removeListener(o.Hg.Events.Reverted,this.handleElementEvent)}handleElementEvent=()=>{this.forceUpdate()};handleUndo=e=>{e.stopPropagation();const t=this.props.node.data.hadronDocument.getStringId();if(this.element.isAdded()){this.isDeleted=!0;const e=!this.element.parent?.isRoot()&&"Array"===this.element.parent?.currentType;this.props.elementRemoved(String(this.element.currentKey),t,e)}else this.element.isRemoved()?this.props.elementAdded(String(this.element.currentKey),this.element.currentType,t):this.props.elementTypeChanged(String(this.element.currentKey),this.element.type,t);this.element.revert()};handleDrillDown(e){e.stopPropagation(),this.props.drillDown(this.props.node.data.hadronDocument,this.element)}handleClicked(){"editing"===this.props.node.data.state&&this.props.api.startEditingCell({rowIndex:this.props.node.rowIndex,colKey:this.props.column.getColId()})}refresh(){return!0}renderInvalidCell(){let e=`${$t}-is-${this.element.currentType.toLowerCase()}`;return e=`${e} ${Yt}`,r().createElement("div",{className:e},this.element.currentValue)}getLength(){return"Object"===this.element.currentType?Object.keys(this.element.generateObject()).length:"Array"===this.element.currentType?this.element.elements.size:void 0}renderValidCell(){let e=_t,t="";return this.element.isAdded()?e=`${e} ${_t}-${Kt}`:this.element.isEdited()&&(e=`${e} ${_t}-${Gt}`),t="Object"===this.element.currentType?`{} ${this.getLength()} fields`:"Array"===this.element.currentType?`[] ${this.getLength()} elements`:r().createElement(s.sPs,{type:this.props.value.currentType,value:this.props.value.currentValue}),r().createElement("div",{className:e},r().createElement("div",{className:Ut},this.props.value.decrypted&&r().createElement("span",{"data-testid":"hadron-document-element-decrypted-icon",title:"Encrypted Field",className:qt},r().createElement(s.Int,{glyph:"Key",size:"small"})),t))}renderUndo(e,t){let n=`${Vt} ${Vt}-undo`;return e&&t&&(n=`${n} ${Vt}-left`),e?r().createElement(s.K0,{className:n,size:"small","aria-label":"Undo change",onClick:this.handleUndo.bind(this)},r().createElement(s.Int,{glyph:"Undo"})):null}renderExpand(e){return e?r().createElement("span",null,r().createElement(s.K0,{className:Vt,size:"small","aria-label":"Expand field",onClick:this.handleDrillDown.bind(this)},r().createElement(s.Int,{glyph:"OpenNewTab",size:"xsmall"}))):null}render(){let e,t="table-view-cell",n=!1,a=!1;return this.editable?this.isEmpty||this.isDeleted?(e="No field",t=`${t}-is-empty`):this.element.isCurrentTypeValid()?this.element.isRemoved()?(e="Deleted field",t=`${t}-is-deleted`,n=!0):(e=this.renderValidCell(),this.element.isAdded()?(t=`${t}-${Kt}`,n=!0):this.element.isModified()&&(t=`${t}-${Gt}`,n=!0),a="Object"===this.element.currentType||"Array"===this.element.currentType):(e=this.renderInvalidCell(),t=`${t}-is-invalid`,n=!0):(e="",t=`${t}-is-uneditable`),r().createElement(s.Yeg,{darkMode:this.props.darkMode},r().createElement(s.gD8.ec.Provider,{value:this.props.legacyUUIDDisplayEncoding??""},r().createElement("div",{className:t,onClick:this.handleClicked.bind(this),role:"button"},this.renderUndo(n,a),this.renderExpand(a),e)))}static displayName="CellRenderer"}const Jt=(0,s.U6i)(Zt);function Qt({value:e}){return r().createElement("div",{className:"table-view-cell-row-number"},e)}Qt.displayName="RowNumberRenderer";const Xt=Qt;class en extends r().Component{doc;constructor(e){super(e),this.doc=e.data.hadronDocument,this.state={mode:e.data.state}}componentDidMount(){this.doc.on(o.Tx.RemoveSuccess,this.handleRemoveSuccess),this.doc.on(o.Tx.UpdateSuccess,this.handleUpdateSuccess)}componentWillUnmount(){this.doc.removeListener(o.Tx.RemoveSuccess,this.handleRemoveSuccess),this.doc.removeListener(o.Tx.UpdateSuccess,this.handleUpdateSuccess)}handleUpdateSuccess=e=>{let t=e;if(this.props.context.path.length)for(let e=0;e<this.props.context.path.length;e++)t=t[this.props.context.path[e]];this.props.replaceDoc(this.doc.getStringId(),String(e._id),t),this.props.context.handleUpdate(e)};handleRemoveSuccess=()=>{this.props.context.handleRemove(this.props.node)};handleCancelRemove(){this.props.api.stopEditing(),this.props.context.removeFooter(this.props.node)}handleCancelUpdate(){this.props.api.stopEditing();const e=this.doc.getStringId();let t=this.doc;if(this.props.context.path.length&&(t=this.doc.getChild(this.props.context.path)),this.doc.cancel(),this.props.context.removeFooter(this.props.node),t){let n=t.generateObject();this.props.context.path.length&&null===t.elements&&(n={}),this.props.replaceDoc(e,e,n),this.props.cleanCols()}}refresh(){return!0}render(){return r().createElement(s.Yeg,{darkMode:this.props.darkMode},r().createElement(s.gD8.eQ,{doc:this.doc,editing:"editing"===this.state.mode,deleting:"deleting"===this.state.mode,onUpdate:e=>{this.props.api.stopEditing(),e?this.props.replaceDocument(this.doc):this.props.updateDocument(this.doc)},onDelete:()=>{this.props.api.stopEditing(),this.props.removeDocument(this.doc)},onCancel:()=>{"editing"===this.state.mode?this.handleCancelUpdate():this.handleCancelRemove()}}))}static displayName="FullWidthCellRenderer"}const tn=en,nn=({context:e,copyToClipboard:t,node:n,data:i,nested:o,value:l,isEditable:c})=>{const d=(0,a.useMemo)((()=>{const e={action:"edit",label:"Edit Document",icon:"Edit"};return o?[e]:[e,{action:"copy",label:"Copy Document",icon:"Copy"},{action:"clone",label:"Clone Document",icon:"Clone"},{action:"remove",label:"Delete Document",icon:"Trash"}]}),[o]),u=(0,a.useCallback)((a=>{switch(a){case"edit":e.addFooter(n,i,"editing");break;case"remove":e.addFooter(n,i,"deleting");break;case"clone":e.handleClone(i);break;case"copy":t(i.hadronDocument)}}),[t,e,i,n]);return"editing"!==l?.state&&"deleting"!==l?.state&&c?r().createElement("div",{className:"table-view-row-actions"},r().createElement("div",{className:"table-view-row-actions-panel"},r().createElement(s.ful,{"data-testid":"table-view-row-actions",actions:d,onAction:u,iconSize:"xsmall"}))):null};class an extends r().Component{constructor(e){super(e)}refresh(){return!0}render(){if(this.props.hide)return null;let e=this.props.displayName;return"$new"===this.props.displayName&&(e="New Field"),r().createElement("div",{className:(0,s.cx)("table-view-cell-header",{"table-view-cell-header-subtable-objectid":!0===this.props.subtable})},r().createElement("b",null,e)," ",this.props.bsonType)}static displayName="HeaderCellRenderer"}const rn=an,on=_.Ay.castableTypes(!0),sn=(0,s.AHW)({minWidth:10*s.YKD[400]}),ln=({element:e})=>{const t=(0,a.useCallback)((t=>{e.changeType(t)}),[e]);return r().createElement(s.l6P,{size:"xsmall",placeholder:"placeholder",onChange:t,allowDeselect:!1,value:e.currentType,"aria-labelledby":"","aria-label":"Field type",className:(0,s.cx)(sn,"table-view-cell-editor-types"),"data-testid":"table-view-types-dropdown-select"},on.map((e=>r().createElement(s.c$x,{key:e,value:`${e}`,"data-testid":`editable-element-type-${e}`},e))))};ln.displayName="TypesDropdown";const cn=ln,dn="Relationship";class un extends r().Component{empty;constructor(e){super(e),this.state={menu:!1},void 0===e.value&&(this.empty=!0)}handleAddFieldClick(){const e=this.props.node.data.hadronDocument;let t=this.props.node.data.hadronDocument,n=!1;this.props.context.path.length&&(t=e.getChild(this.props.context.path));const a=!t.isRoot()&&"Array"===t.currentType;let r;if(r=this.empty?t.insertEnd("$new",""):t.insertAfter(this.props.value,"$new",""),a){const e=t.elements?.lastElement?.currentKey;null!==this.props.columnApi.getColumn(e)&&(n=!0)}this.props.addColumn(String(r.currentKey),String(this.props.column.getColDef().colId),this.props.node.childIndex,this.props.context.path,a,n,this.props.node.data.hadronDocument.getStringId())}handleAddChildClick(){const e={colId:this.props.value.insertEnd("$new","").currentKey,rowIndex:this.props.node.childIndex};this.props.drillDown(this.props.node.data.hadronDocument,this.props.value,e)}isElementObject(){return!this.empty&&"Object"===this.props.value.currentType}isElementArray(){return!this.empty&&"Array"===this.props.value.currentType}isParentArray(){if(this.props.context.path.length){const e=this.props.node.data.hadronDocument.getChild(this.props.context.path);return"Array"===e?.currentType}return!1}renderArrayItem(){if(this.isElementArray()&&this.props.value.isValueEditable())return this.renderMenuItem(dn,"Add array element to ",this.handleAddChildClick.bind(this),"add-element-to-array")}renderDefaultItem(){const e=this.isParentArray()?"Add array element after ":"Add field after ";return this.renderMenuItem("PlusWithCircle",e,this.handleAddFieldClick.bind(this),"add-field-after")}renderValue(){return this.empty?null:r().createElement(s.sPs,{type:this.props.value.currentType,value:this.props.value.currentValue})}renderIdentifier(){return this.empty?this.props.column.getColDef().headerName:this.isParentArray()&&(this.isElementObject()||this.isElementArray())?this.props.value.currentType:this.props.value.currentKey||this.renderValue()}renderMenuItem(e,t,n,a){return r().createElement(s.Drp,{"data-testid":a,onClick:n,glyph:e?r().createElement(s.Int,{glyph:e}):void 0},t," ",r().createElement("b",null,this.renderIdentifier()))}renderObjectItem(){if(this.isElementObject()&&this.props.value.isValueEditable())return this.renderMenuItem(dn,"Add field to ",this.handleAddChildClick.bind(this),"add-child-to-object")}renderMenu(){return r().createElement(r().Fragment,null,this.renderObjectItem(),this.renderArrayItem(),this.renderDefaultItem())}render(){return this.empty&&this.isParentArray()?null:r().createElement(s.W1t,{align:"bottom",justify:"start",trigger:({children:e,onClick:t,...n})=>r().createElement(s.$nd,(0,i.A)({size:"xsmall","data-testid":"table-view-cell-editor-add-field-button","aria-label":"Add field",onClick:t},n),r().createElement(s.Int,{glyph:"Plus",size:"xsmall"}),e)},this.renderMenu())}static displayName="AddFieldButton"}const pn=un,mn="table-view-cell-editor",gn="editable-element-value",hn=(0,s.AHW)({width:2*s.YKD[1600],marginRight:s.YKD[100]}),fn=(0,s.AHW)({marginLeft:s.YKD[100],display:"flex",gap:s.YKD[100]/2});class yn extends r().Component{element;changed=!1;wasEmpty=!1;newField=!1;oldType;_editors;_pasting;constructor(e){super(e),this.state={fieldName:""};const{node:t,context:n,column:a,value:r}=e;this.element=r,this.wasEmpty=!1,this.newField=!1;let i=t.data.hadronDocument;if(n.path.length&&(i=i.getChild(n.path)),void 0===this.element&&"$new"===a.getColDef().headerName)this.wasEmpty=!0,this.element=i.insertEnd("$new",""),this.newField=!0;else if(void 0===this.element){this.wasEmpty=!0;const e=a.getColDef().headerName;let t=a.getColDef().headerComponentParams.bsonType;"Mixed"===t&&(t="String");const n=(0,o.q_)(t);this.element=i.insertEnd(String(e),n),this.element.edit(n)}else"$new"!==this.element.currentKey&&this.setState({fieldName:String(this.element.currentKey)}),this.newField="$new"===r.currentKey;const s=(0,o.Ho)(this.element,e.legacyUUIDDisplayEncoding);this.oldType=this.element.currentType,this._editors=(0,o.C7)(this.element,s),this.editor().start()}componentDidMount(){this.props.eGridCell&&this.props.eGridCell.addEventListener("keydown",this.onKeyDown)}componentWillUnmount(){this.props.eGridCell&&this.props.eGridCell.removeEventListener("keydown",this.onKeyDown),this.props.api.stopEditing()}onKeyDown=e=>{e.stopPropagation(),27!==e.keyCode&&13!==e.keyCode||this.props.api.stopEditing()};getValue(){return this.element}isCancelAfterEnd(){this.editor().complete();const e=this.props.node.data.hadronDocument.getStringId(),t=this.element;if(this.newField){const e=this.state.fieldName,n=[...this.props.context.path,e];if(""===e||this.isDuplicateKey(e))return t.revert(),this.props.removeColumn("$new"),!1;this.props.renameColumn(String(t.currentKey),e),t.rename(e);const a=this.props.column.getColDef();a.valueGetter=function(e){return e.data.hadronDocument.getChild(n)},a.headerName=e,a.colId=e,a.editable=function(e){return"deleting"!==e.node.data.state},this.props.api.refreshHeader()}else if(this.wasEmpty){if(!this.changed)return t.revert(),!1}else t.isAdded()||t.isRemoved()||t.currentType===this.oldType||this.props.elementTypeChanged(String(t.currentKey),t.currentType,e);return!t.isRemoved()&&t.isAdded()&&this.props.elementAdded(String(t.currentKey),t.currentType,e),this.props.api.refreshCells({rowNodes:[this.props.node],force:!0}),!1}handleTypeChange(){const e=this.element?.currentType;if(e!==this.oldType&&(this.changed=!0,"Array"===e||"Object"===e))for(const e of this.element?.elements??[])e.isAdded()&&""===e.currentKey&&""===e.currentValue&&e.remove();this.forceUpdate()}handleRemoveField(){if(this.element?.isRemovable()){const e=this.props.node.data.hadronDocument.getStringId();if(this.wasEmpty)return this.element=void 0,this.props.api.stopEditing();if(this.newField||this.element.isAdded()){const t=!this.element?.parent?.isRoot()&&"Array"===this.element?.parent?.currentType;this.props.elementRemoved(String(this.element.currentKey),e,t)}else this.props.elementMarkRemoved(String(this.element.currentKey),e);this.element.remove()}this.props.api.stopEditing()}handleDrillDown(){this.changed=!0,this.props.api.stopEditing(),this.props.drillDown(this.props.node.data.hadronDocument,this.element)}handleInputChange(e){this.changed=!0,this._pasting?this._pasteEdit(e.target.value):this.editor().edit(e.target.value),this.forceUpdate()}handleFieldNameChange(e){this.setState({fieldName:e.target.value})}handlePaste(){this._pasting=!0}_pasteEdit(e){try{this.editor().paste(e)}catch{this.editor().edit(e)}finally{this._pasting=!1}}isDuplicateKey(e){const t=this.props.columnApi.getAllColumns();for(let n=0;n<t.length;n++)if(t[n].getColDef().colId===e)return!0;return!1}editor(){const e=(0,o.Ho)(this.element,this.props.legacyUUIDDisplayEncoding);return this._editors[(0,o.qm)(e)]}wrapperStyle(){return`${gn}-wrapper ${gn}-wrapper-is-${String(this.element?.currentType.toLowerCase())}`}renderFieldName(){return this.newField&&"$new"===this.element?.currentKey?r().createElement(s.ksK,{className:hn,sizeVariant:"xsmall","data-testid":"table-view-cell-editor-fieldname-input",value:this.state.fieldName,placeholder:"Field Name",onChange:this.handleFieldNameChange.bind(this),"aria-labelledby":""}):null}renderTypes(e){return e?r().createElement("div",{className:`${mn}-input-types`,onBlur:this.handleTypeChange.bind(this)},r().createElement(cn,{element:this.element})):null}renderInput(e){return e?r().createElement("div",null,r().createElement("span",{className:this.wrapperStyle()},r().createElement(s.ksK,{className:hn,"data-testid":"table-view-cell-editor-value-input",sizeVariant:"xsmall",onChange:this.handleInputChange.bind(this),onPaste:this.handlePaste.bind(this),value:this.editor().value(),placeholder:"Value","aria-labelledby":""}))):null}renderExpand(e){return e?r().createElement(s.$nd,{"data-testid":"table-view-cell-editor-expand-button","aria-label":"Expand field",size:"xsmall",onClick:this.handleDrillDown.bind(this)},r().createElement(s.Int,{glyph:"OpenNewTab",size:"xsmall"})):null}renderRemoveField(){return this.wasEmpty||"_id"===this.element?.currentKey&&!this.props.context.path.length?null:r().createElement(s.$nd,{"data-testid":"table-view-cell-editor-remove-field-button","aria-label":"Remove field",size:"xsmall",onClick:this.handleRemoveField.bind(this)},r().createElement(s.Int,{glyph:"Trash",size:"xsmall"}))}onAddField(...e){setTimeout((()=>{this.props.api.stopEditing(),this.props.addColumn(...e)}))}renderActions(e,t,n){if("$new"===this.element?.currentKey)return null;const a=87*+e+130*+t+23*+n;return r().createElement("span",{className:(0,s.cx)(`${mn}-actions`,fn)},this.renderExpand(n),r().createElement("span",null,r().createElement(pn,(0,i.A)({},this.props,{addColumn:this.onAddField.bind(this),displace:a}))),this.renderRemoveField())}render(){const e="_id"!==this.element?.currentKey||this.props.context.path.length,t="Object"!==this.element?.currentType&&"Array"!==this.element?.currentType&&this.element?.isValueEditable(),n="Object"===this.element?.currentType||"Array"===this.element?.currentType;return r().createElement(s.Yeg,{darkMode:this.props.darkMode},r().createElement("div",{className:mn},this.renderFieldName(),this.renderInput(!!t),this.renderTypes(!!e),this.renderActions(!!e,!!t,!!n)))}static displayName="CellEditor"}const bn=yn;var vn=n(95593),xn=n.n(vn),En=n(92926),Cn=n.n(En),wn=n(28742),In=n.n(wn),Sn=n(37385),An=n.n(Sn),kn=n(56565),Dn=n.n(kn),Nn=n(20930),Mn=n.n(Nn),Tn=n(67305),Pn={};Pn.styleTagTransform=Mn(),Pn.setAttributes=An(),Pn.insert=In().bind(null,"head"),Pn.domAPI=Cn(),Pn.insertStyleElement=Dn(),xn()(Tn.A,Pn),Tn.A&&Tn.A.locals&&Tn.A.locals;var Ln=n(42463),On={};On.styleTagTransform=Mn(),On.setAttributes=An(),On.insert=In().bind(null,"head"),On.domAPI=Cn(),On.insertStyleElement=Dn(),xn()(Ln.A,On),Ln.A&&Ln.A.locals&&Ln.A.locals;class Rn extends r().Component{AGGrid;collection;topLevel;unsubscribeGridStore;gridApi;columnApi;constructor(e){super(e);const t={gridOptions:{context:{addFooter:this.addFooter,removeFooter:this.removeFooter,handleUpdate:this.handleUpdate,handleRemove:this.handleRemove,handleClone:this.handleClone,path:[]},suppressDragLeaveHidesColumns:!0,onCellDoubleClicked:this.onCellDoubleClicked.bind(this),getRowHeight:({data:{isFooter:e}})=>e?38:28,getRowStyle:this.updateWidth,suppressPreventDefaultOnMouseWheel:!0,suppressRowTransform:!0,tabToNextCell:e=>e.previousCellDef&&e.nextCellDef&&e.previousCellDef.rowIndex===e.nextCellDef.rowIndex?e.nextCellDef:null},onGridReady:this.onGridReady.bind(this),isFullWidthCell:function(e){return e.data.isFooter},fullWidthCellRendererFramework:tn,fullWidthCellRendererParams:{replaceDoc:this.props.replaceDoc,cleanCols:this.props.cleanCols,removeDocument:this.props.removeDocument,replaceDocument:this.props.replaceDocument,updateDocument:this.props.updateDocument,darkMode:this.props.darkMode},getRowNodeId:function(e){const t=e.isFooter?"1":"0";return String(e.hadronDocument.getStringId())+t},onColumnResized:this.onColumnResized.bind(this)};this.collection=(0,Ft.Ay)(e.ns).collection,this.topLevel=!0,this.AGGrid=r().createElement(Ht.AgGridReact,t)}componentDidMount(){this.unsubscribeGridStore=this.props.store.gridStore.listen(this.modifyColumns,this)}componentWillUnmount(){this.unsubscribeGridStore?.(),this.gridApi?.destroy?.()}componentDidUpdate(e){this.handleBreadcrumbChange(),this.props.docs.length>e.docs.length&&this.handleInsert()}handleClone=({hadronDocument:e})=>{const t=e.generateObject({excludeInternalFields:!0});this.props.openInsertDocumentDialog?.(t,!0)};onGridReady(e){this.gridApi=e.api,this.columnApi=e.columnApi,this.handleBreadcrumbChange()}onCellDoubleClicked(e){this.addFooter(e.node,e.data,"editing")}onColumnResized(e){if(e.finished){const e=this.columnApi?.getColumnState()||[],t=Object.create(null);for(const n of e)n.width&&(t[n.colId]=n.width);this.props.onColumnWidthChange(t)}}addFooter=(e,t,n)=>{if(!this.props.isEditable||t.isFooter||t.hasFooter)return;e.data.hasFooter=!0,e.data.state=n,this.gridApi?.refreshCells({rowNodes:[e],columns:["$rowActions"],force:!0});const a={hadronDocument:t.hadronDocument,hasFooter:!1,isFooter:!0,state:n};this.gridApi?.updateRowData({add:[a],addIndex:+e.rowIndex+1})};removeFooter=e=>{if(!this.gridApi)return;const t=e.data.hadronDocument.getStringId()+"0",n=this.gridApi.getRowNode(t);n.data.hasFooter=!1,n.data.state=null,this.gridApi.refreshCells({rowNodes:[n],columns:["$rowActions"],force:!0}),this.gridApi.clearFocusedCell(),this.gridApi.updateRowData({remove:[e.data]})};handleRemove=e=>{const t=e.data.hadronDocument.getStringId(),n=t+"0",a=this.gridApi?.getRowNode(n);this.updateRowNumbers(a.data.rowNumber,!1),this.removeFooter(e);for(const n of e.data.hadronDocument.elements)this.props.elementRemoved(String(n.currentKey),t,!1);this.gridApi?.updateRowData({remove:[a.data]})};handleUpdate=e=>{if(!this.gridApi)return;const t=String(e._id)+"0",n=this.gridApi.getRowNode(t),a=n.data.rowNumber,r={hadronDocument:new o.Ay(e),isFooter:!1,hasFooter:!1,state:null,rowNumber:a};for(let e=0;e<this.props.docs.length;e++)if(this.props.docs[e].getStringId()===r.hadronDocument.getStringId()){this.props.docs[e]=r.hadronDocument;break}n.setData(r),this.gridApi.redrawRows({rowNodes:[n]});const i=String(e._id)+"1",s=this.gridApi.getRowNode(i);this.removeFooter(s),this.props.cleanCols()};addGridColumn(e,t,n,a,r){if(!this.columnApi)return;const i=(0,w.map)(this.columnApi.getAllGridColumns(),(e=>e.getColDef()));let o=0;for(;o<i.length;){if(!r&&String(i[o].colId)===String(t))return;o++}for(o=0;o<i.length;){if(String(i[o].colId)===String(e)){if(r){let e=o+1;for(;e<i.length;){if(!String(i[e].colId).includes("$")){const t=String(i[e].colId)+"1";i[e].colId=t,i[e].headerName=t,i[e].valueGetter=function(e){return e.data.hadronDocument.getChild([...a,t])}}e++}}break}o++}const s=r?"Array":"Object",l=this.createColumnHeader(n,!0,[...a,t],s);i.splice(o+1,0,l),this.gridApi?.setColumnDefs(i),r&&this.gridApi?.refreshCells({force:!0})}removeColumns(e){if(!this.columnApi)return;const t=(0,w.map)(this.columnApi.getAllGridColumns(),(e=>e.getColDef())),n=[];for(let a=0;a<t.length;a++)e.includes(String(t[a].colId))||n.push(t[a]);this.gridApi?.setColumnDefs(n)}updateHeaders=(e,t)=>{const n=Object.keys(e);for(let a=0;a<t.length;a++)n.includes(String(t[a].colId))&&(t[a].headerComponentParams.bsonType=e[String(t[a].colId)])};modifyColumns=e=>{if(this.columnApi&&this.gridApi){if(e.add&&this.addGridColumn(e.add.colIdBefore,e.add.newColId,e.add.colType,e.add.path,e.add.isArray),e.remove&&this.removeColumns(e.remove.colIds),e.updateHeaders){const t=(0,w.map)(this.columnApi.getAllGridColumns(),(e=>e.getColDef()));this.updateHeaders(e.updateHeaders.showing,t),this.gridApi.refreshHeader()}if(e.refresh){const t=this.gridApi.getRowNode(String(e.refresh.oid)+"0");this.gridApi.refreshCells({rowNodes:[t],force:!0})}e.edit&&(this.gridApi.setFocusedCell(e.edit.rowIndex,e.edit.colId),this.gridApi.startEditingCell({rowIndex:e.edit.rowIndex,colKey:e.edit.colId}))}};updateRowNumbers(e,t){const n=t?1:-1;this.gridApi?.forEachNodeAfterFilterAndSort((function(t){!t.data.isFooter&&t.data.rowNumber>=e&&(t.data.rowNumber+=n)})),this.gridApi?.refreshCells({columns:["$rowNumber"]})}insertRow(e,t,n){const a={hadronDocument:e,isFooter:!1,hasFooter:!1,state:null,rowNumber:n};if(this.topLevel){this.updateRowNumbers(n,!0),this.gridApi?.updateRowData({add:[a],addIndex:t});for(const t of a.hadronDocument.elements)this.props.elementAdded(String(t.currentKey),t.currentType,e.getStringId())}}handleInsert(){if(!this.props.error){const e=this.props.docs[this.props.docs.length-1];for(const t of e.elements)this.addGridColumn(null,String(t.currentKey),t.currentType,[])}}handleBreadcrumbChange(){if(!this.gridApi)return;const e=this.props.table;if(0===e.path.length){this.topLevel=!0;const e=this.createColumnHeaders([],[]);this.gridApi.gridOptionsWrapper.gridOptions.context.path=[],this.gridApi.setColumnDefs(e),this.gridApi.setRowData(this.createRowData(this.props.docs,this.props.start))}else if("Object"===e.types[e.types.length-1]||"Array"===e.types[e.types.length-1]){this.topLevel=!1;const t=this.createColumnHeaders(e.path,e.types);t.push(this.createObjectIdHeader()),t.length<=3&&t.push(this.createPlaceholderHeader("Array"===e.types[e.types.length-1],e.path)),this.gridApi.gridOptionsWrapper.gridOptions.context.path=e.path,this.gridApi.setRowData(this.createRowData(this.props.docs,this.props.start)),this.gridApi.setColumnDefs(t)}if(this.gridApi.refreshCells({force:!0}),this.gridApi&&this.addFooters(),e.editParams){const t=String(e.editParams.colId);this.gridApi.ensureColumnVisible(t),this.gridApi.setFocusedCell(e.editParams.rowIndex,t),this.gridApi.startEditingCell({rowIndex:e.editParams.rowIndex,colKey:t})}else e.path.length&&"Array"===e.types[e.types.length-1]&&this.gridApi.ensureColumnVisible("0")}updateWidth=e=>{if(!this.columnApi)return;const t=this.columnApi.getAllColumns(),n=document.querySelector(".ag-root-wrapper"),a=n?n.offsetWidth:0;if("editing"===e.node.data.state||"deleting"===e.node.data.state){let e=30;const n=this.columnApi.getColumn("$new");for(let n=0;n<t.length-2;n++)e+=200;return e>a||n?{width:"100%"}:{width:`${e}px`}}};addFooters(){this.gridApi?.forEachNodeAfterFilterAndSort((e=>{e.data.hadronDocument.isModified()&&this.addFooter(e,e.data,"editing")}))}createPlaceholderHeader(e,t){const n=e?0:"$new",a=e?"Array":"Object";return this.createColumnHeader("String",!0,[...t,n],a)}createObjectIdHeader(){return{headerName:"_id",colId:"$_id",cellClass:"ag-cell-subtable-objectid",valueGetter:function(e){return e.data.hadronDocument.get("_id")},headerComponentFramework:rn,headerComponentParams:{hide:!1,bsonType:"ObjectId",subtable:!0},cellRendererFramework:Jt,cellRendererParams:{elementAdded:this.props.elementAdded,elementRemoved:this.props.elementRemoved,elementTypeChanged:this.props.elementTypeChanged,drillDown:this.props.drillDown,parentType:"",tz:this.props.tz,darkMode:this.props.darkMode,legacyUUIDDisplayEncoding:this.props.legacyUUIDDisplayEncoding},editable:!1,cellEditorFramework:bn,pinned:"left"}}createColumnHeader=(e,t,n,a)=>({headerName:String(n[n.length-1]),colId:String(n[n.length-1]),valueGetter:function(e){const t=e.data.hadronDocument.getChild(n);if(n.length<=1)return t;const r=e.node.data.hadronDocument.getChild(n.slice(0,n.length-1));return void 0===r||a===r.currentType?t:void 0},valueSetter:function(e){return(void 0!==e.oldValue||void 0!==e.newValue)&&(e.newValue.isEdited()||e.newValue.isAdded()||e.newValue.isRemoved())},headerComponentFramework:rn,headerComponentParams:{hide:!1,bsonType:e},cellRendererFramework:Jt,cellRendererParams:{elementAdded:this.props.elementAdded,elementRemoved:this.props.elementRemoved,elementTypeChanged:this.props.elementTypeChanged,drillDown:this.props.drillDown,parentType:a,tz:this.props.tz,darkMode:this.props.darkMode,legacyUUIDDisplayEncoding:this.props.legacyUUIDDisplayEncoding},editable:function(e){if(!t||"deleting"===e.node.data.state)return!1;if(n.length<=1)return!0;const r=e.node.data.hadronDocument.getChild(n.slice(0,n.length-1));if(!r||r.currentType!==a)return!1;if("Array"===r.currentType&&"$_id"!==e.column.getColId()){let t=0;if(r.elements.lastElement&&(t=+r.elements.lastElement.currentKey+1),+e.column.getColId()>t)return!1}return!0},cellEditorFramework:bn,cellEditorParams:{addColumn:this.props.addColumn,removeColumn:this.props.removeColumn,renameColumn:this.props.renameColumn,elementAdded:this.props.elementAdded,elementRemoved:this.props.elementRemoved,version:this.props.version,elementTypeChanged:this.props.elementTypeChanged,elementMarkRemoved:this.props.elementMarkRemoved,drillDown:this.props.drillDown,tz:this.props.tz,darkMode:this.props.darkMode,legacyUUIDDisplayEncoding:this.props.legacyUUIDDisplayEncoding},resizable:!0,width:this.props.columnWidths[String(n[n.length-1])]});createColumnHeaders=(e,t)=>{const n=Object.create(null),a=Object.create(null),r=this.props.isEditable,i=t.length?t[t.length-1]:"Object",o=this.createColumnHeader;n.hadronRowNumber={headerName:"Row",field:"rowNumber",colId:"$rowNumber",width:30,pinned:"left",headerComponentFramework:rn,headerComponentParams:{hide:!0},cellRendererFramework:Xt};for(let t=0;t<this.props.docs.length;t++){let s=this.props.docs[t];if((!(e.length>0)||(s=s.getChild(e),s&&s.currentType===i))&&void 0!==s)for(const l of s.elements??[]){const s=l.currentKey,c=l.currentType;n[s]=o(c,r,[...e,s],i),s in a||(a[s]={}),a[s][String(this.props.docs[t].getStringId())]=c}}this.props.resetColumns(a);const l=Object.values(n),c=Object.create(null);return(0,w.map)(a,(function(e,t){const n=Object.values(e);let a=n[0];for(let e=0;e<n.length;e++)if(a!==n[e]){a="Mixed";break}c[t]=a})),this.updateHeaders(c,l),l.push({colId:"$rowActions",valueGetter:function(e){return e.data},headerComponentFramework:rn,headerComponentParams:{hide:!0},cellRendererFramework:nn,cellRendererParams:{nested:0!==e.length,isEditable:this.props.isEditable,copyToClipboard:this.props.copyToClipboard,tz:this.props.tz},editable:!1,pinned:"right",width:s.YKD[7]+s.YKD[400]}),l};createRowData=(e,t)=>e.map(((e,n)=>({hadronDocument:e,isFooter:!1,hasFooter:!1,state:null,rowNumber:n+t})));render(){return r().createElement("div",{className:(0,s.cx)("document-table-view-container",this.props.darkMode&&"document-table-view-container-darkmode"),"data-testid":"document-list"},r().createElement("div",{className:(0,s.cx)("ag-parent",this.props.className)},r().createElement(zt,{collection:this.collection,pathChanged:this.props.pathChanged,path:this.props.table.path,types:this.props.table.types}),this.AGGrid))}static displayName="DocumentTableView"}const Hn=(0,s.U6i)(Rn);var Fn=n(28508);const Wn=({activeView:e,onChange:t})=>{const n=(0,s.BiT)();return r().createElement(s.IzF,{id:n,"aria-label":"View",size:"xsmall",value:e,onChange:e=>t(e)},r().createElement(s.Zib,{"data-testid":"toolbar-view-list","aria-label":"Document list",value:"List",glyph:r().createElement(s.Int,{glyph:"Menu"})}),r().createElement(s.Zib,{"data-testid":"toolbar-view-json","aria-label":"E-JSON View",value:"JSON",glyph:r().createElement(s.Int,{glyph:"CurlyBraces"})}),r().createElement(s.Zib,{"data-testid":"toolbar-view-table","aria-label":"Table View",value:"Table",glyph:r().createElement(s.Int,{glyph:"Table"})}))};var jn=n(62183);const Bn="960px",zn=(0,s.AHW)({display:"flex",alignItems:"center"}),_n=(0,s.AHW)({whiteSpace:"nowrap"}),$n=(0,s.AHW)({display:"contents"});function Yn({insertDataHandler:e,isDisabled:t=!1,isMockDataGeneratorEligibleAndSchemaReady:n=!1}){const i=(0,l.Fg)("enableImportExport"),o=(0,jn.TH)(),c=(0,Fn.RI)(Fn.Cv.mockDataGenerator,!1),d=c?.assignment?.assignmentData,u=!0===d?.isInSample,p=d?.variant===Fn.qP.mockDataGeneratorVariant,[m,g]=(0,a.useState)(!1);(0,Fn.qv)(Fn.Cv.mockDataGenerator,m&&n&&u);const h=(0,a.useMemo)((()=>{const e=[{action:"insert-document",label:"Insert document"}];return i&&e.unshift({action:"import-file",label:"Import JSON or CSV file"}),n&&p&&e.push({action:"generate-mock-data",label:"Generate mock data script"}),e}),[i,n,p]),f=(0,a.useCallback)((t=>{"generate-mock-data"===t?o.emit("open-mock-data-generator-modal"):e(t)}),[o,e]),y=(0,a.useCallback)((()=>{g(!0)}),[]);return r().createElement("span",{onClickCapture:y,className:$n},r().createElement(s.F1Z,{"data-testid":"crud-add-data",actions:h,onAction:f,buttonText:"Add data",buttonProps:{size:"xsmall",variant:"primary",leftGlyph:r().createElement(s.Int,{glyph:"PlusWithCircle"}),disabled:t,className:_n},narrowBreakpoint:Bn}))}const Kn=({instanceDescription:e,insertDataHandler:t,isWritable:n,isMockDataGeneratorEligibleAndSchemaReady:a})=>n?r().createElement(Yn,{insertDataHandler:t,isMockDataGeneratorEligibleAndSchemaReady:a}):r().createElement(s.m_M,{trigger:({children:e,...n})=>r().createElement("div",(0,i.A)({className:zn},n),r().createElement(Yn,{insertDataHandler:t,isDisabled:!0,isMockDataGeneratorEligibleAndSchemaReady:a}),e),enabled:!n,justify:"middle"},e),Gn=(0,s.AHW)({display:"flex",alignItems:"center"}),Vn=(0,s.AHW)({whiteSpace:"nowrap"}),Un=[{action:"bulk-update",label:"Bulk update documents"},{action:"bulk-delete",label:"Bulk delete documents"}];function qn(){const e=(0,s.D27)()?s.MFm.gray.light2:s.MFm.gray.base;return r().createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none"},r().createElement("path",{d:"M12.4121 5.05859C12.8018 5.05876 13.1181 5.37493 13.1182 5.76465V11.4121C13.118 12.8414 11.9586 14 10.5293 14H5.82324C5.43354 13.9998 5.11816 13.6837 5.11816 13.2939C5.11826 12.9043 5.4336 12.5881 5.82324 12.5879H10.5293C11.1789 12.5879 11.7059 12.0617 11.7061 11.4121V5.76465C11.7061 5.37483 12.0223 5.05859 12.4121 5.05859ZM8.92871 2C9.74731 2 10.4111 2.66382 10.4111 3.48242V9.88672C10.4111 10.7053 9.74731 11.3691 8.92871 11.3691H4.48242C3.66382 11.3691 3 10.7053 3 9.88672V6.44629H6.33496C6.94891 6.44629 7.44629 5.94891 7.44629 5.33496V2H8.92871ZM6.58203 4.84082C6.58203 5.25012 6.25012 5.58203 5.84082 5.58203H3V4.90039C3.00012 4.7041 3.07805 4.51581 3.2168 4.37695L5.37695 2.2168C5.51581 2.07805 5.7041 2.00012 5.90039 2H6.58203V4.84082Z",fill:e}))}function Zn({disabled:e=!1,onUpdate:t,onDelete:n}){const i=(0,a.useCallback)((e=>{"bulk-update"===e?t():n()}),[t,n]);return r().createElement(s.F1Z,{"data-testid":"crud-bulk-actions",actions:Un,onAction:i,buttonText:"Bulk",buttonProps:{size:"xsmall",leftGlyph:r().createElement(qn,null),disabled:e,className:Vn},narrowBreakpoint:Bn})}const Jn=({isWritable:e,disabledTooltip:t,onUpdate:n,onDelete:a})=>e?r().createElement(Zn,{onUpdate:n,onDelete:a}):r().createElement(s.m_M,{trigger:({children:e,...t})=>r().createElement("div",(0,i.A)({className:Gn},t),r().createElement(Zn,{disabled:!0,onUpdate:n,onDelete:a}),e),enabled:!e,justify:"middle"},t);var Qn=n(60783);const Xn=(0,s.AHW)({width:"100%",position:"relative"}),ea=(0,s.AHW)({display:"flex",flexDirection:"column",alignItems:"center",gap:s.YKD[300],padding:s.YKD[400]}),ta=(0,s.AHW)({width:"100%",display:"flex",gap:s.YKD[200],justifyContent:"space-between"}),na=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[200]}),aa=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[200]}),ra=(0,s.AHW)({display:"flex",alignItems:"center"}),ia=(0,s.AHW)({whiteSpace:"nowrap"}),oa=(0,s.AHW)({[`@container ${s.XvC.toolbarContainerQueryName} (width < ${Bn})`]:{display:"none"}}),sa=(0,s.AHW)({whiteSpace:"nowrap"}),la=(0,s.AHW)({width:s.YKD[1600]+s.YKD[300]}),ca=(0,s.AHW)({paddingLeft:s.YKD[200],paddingRight:s.YKD[200]}),da=(0,s.AHW)({textDecoration:"underline",textDecorationStyle:"dotted",textUnderlineOffset:"3px"}),ua=[{action:"export-query",label:"Export query results"},{action:"export-full-collection",label:"Export the full collection"}],pa=[{action:"expand-all",label:"Expand all documents"},{action:"collapse-all",label:"Collapse all documents"}],ma=({activeDocumentView:e,count:t,end:n,error:i,getPage:o,insertDataHandler:c,instanceDescription:d,isWritable:u,isFetching:p,isMockDataGeneratorEligibleAndSchemaReady:m,lastCountRunMaxTimeMS:g,loadingCount:h,onApplyClicked:f,onResetClicked:y,onUpdateButtonClicked:b,onDeleteButtonClicked:v,onExpandAllClicked:x,onCollapseAllClicked:E,openExportFileDialog:C,onOpenExportToLanguage:w,outdated:I,page:S,readonly:A,refreshDocuments:k,resultId:D,start:N,viewSwitchHandler:M,insights:T,queryLimit:P,querySkip:L,docsPerPage:O,updateMaxDocumentsPerPage:R})=>{const H=(0,Fn.Jr)(),F=(0,Qn.jj)(),W=(0,l.Fg)("enableImportExport"),j=(0,a.useCallback)((()=>{H("Query Results Refreshed",{},F.current),k()}),[k,H,F]),B=(0,a.useMemo)((()=>0===S),[S]),z=(0,a.useMemo)((()=>null!=t&&O*(S+1)>=t),[t,S,O]),_=(0,l.Fg)("enableExplainPlan"),$=(0,a.useMemo)((()=>L||P),[L,P]),Y=(0,s.MdH)((()=>[{telemetryLabel:"Expand all documents",items:[{label:"Expand all documents",onAction:()=>{x()}},{label:"Collapse all documents",onAction:()=>{E()}},W?{label:"Import JSON or CSV file",onAction:()=>{c("import-file")}}:void 0,A?void 0:{label:"Insert document...",onAction:()=>{c("insert-document")}},...W?[{label:"Export query results...",onAction:()=>{C(!1)}},{label:"Export full collection...",onAction:()=>{C(!0)}}]:[],...A||!u||$?[]:[{label:"Bulk update",onAction:()=>{b()}},{label:"Bulk delete",onAction:()=>{v()}}],{label:"Refresh",onAction:()=>{j()}}]}]),[W,A,u,$,E,x,c,C,b,v,j]);return r().createElement("div",{className:ea,ref:Y},r().createElement("div",{className:Xn},r().createElement(Et.sJ,{source:"crud",resultId:D,buttonLabel:"Find",onApply:f,onReset:y,showExplainButton:_})),r().createElement("div",{className:ta},r().createElement("div",{className:na},!A&&r().createElement(Kn,{insertDataHandler:c,isWritable:u,instanceDescription:d,isMockDataGeneratorEligibleAndSchemaReady:m}),!A&&r().createElement(Jn,{isWritable:u&&!$,disabledTooltip:u?"Remove limit and skip in your query to perform a bulk operation":d,onUpdate:b,onDelete:v}),W&&r().createElement(s.F1Z,{"data-testid":"crud-export-collection",actions:ua,onAction:e=>C("export-full-collection"===e),buttonText:"Export Data",buttonProps:{className:ia,size:"xsmall",leftGlyph:r().createElement(s.Int,{glyph:"Export"})},narrowBreakpoint:Bn}),r().createElement(s.$nd,{onClick:w,title:"Export query to language","aria-label":"Export query to language","data-testid":"crud-export-to-language-button",className:ia,size:"xsmall",leftGlyph:r().createElement(s.Int,{glyph:"Code"})},r().createElement("span",{className:oa},"Export Code")),T&&r().createElement(s.gIH,{signals:T})),r().createElement("div",{className:aa},r().createElement(s.l6P,{"data-testid":"crud-document-per-page-selector",size:"xsmall",disabled:p,allowDeselect:!1,dropdownWidthBasis:"option","aria-label":"Update number of documents per page",value:`${O}`,onChange:e=>R(parseInt(e))},["25","50","75","100"].map((e=>r().createElement(s.c$x,{className:la,key:e,value:e},e)))),r().createElement(s.nBu,{"data-testid":"crud-document-count-display"},N," – ",n," ",!h&&r().createElement("span",null,"of ",t??r().createElement(s.m_M,{trigger:r().createElement("span",{"data-testid":"crud-document-count-unavailable",className:da},"N/A")},r().createElement(s.nBu,null,`The count is not available for this query. This can happen when the count operation fails or exceeds the maxTimeMS of ${g}.`)))),h&&r().createElement("div",{className:ca},r().createElement(s.Q0K,{size:"12px",title:"Fetching document count…"})),!h&&!p&&r().createElement(s.K0,{"aria-label":"Refresh documents",title:"Refresh documents","data-testid":"refresh-documents-button",onClick:j},r().createElement(s.Int,{glyph:"Refresh"})),r().createElement("div",{className:ra},r().createElement(s.K0,{"data-testid":"docs-toolbar-prev-page-btn","aria-label":"Previous Page",title:"Previous Page",onClick:()=>o(S-1),disabled:B},r().createElement(s.Int,{glyph:"ChevronLeft"})),r().createElement(s.K0,{"data-testid":"docs-toolbar-next-page-btn","aria-label":"Next Page",title:"Next Page",onClick:()=>o(S+1),disabled:z},r().createElement(s.Int,{glyph:"ChevronRight"}))),r().createElement(s.F1Z,{"data-testid":"crud-export-collection",actions:pa,onAction:e=>"expand-all"===e?x():E(),buttonText:"",buttonProps:{className:sa,size:"xsmall",title:"Output Options","aria-label":"Output Options",disabled:"Table"===e}}),r().createElement(Wn,{activeView:e,onChange:M}))),i&&r().createElement(s.dFH,{"data-testid":"document-list-error-summary",errors:(K=i,"MongoServerError"===K.name&&50===K.code?.value?"Operation exceeded time limit. Please try increasing the maxTimeMS for the query in the expanded filter options.":i.message)}),I&&!i&&r().createElement(s.rpn,{"data-testid":"crud-outdated-message-id",warnings:['The content is outdated and no longer in sync\nwith the current query. Press "Find" again to see the results for\nthe current query.']}));var K},ga="fetching",ha="error",fa="fetchedInitial",ya=({query:e,isCollectionScan:t,isSearchIndexesSupported:n,canCreateIndexes:a,onCreateIndex:r,onCreateSearchIndex:i,onAssistantButtonClick:o})=>{if(t)return/\$(text|regex)\b/.test(e)&&n?{...s.qpO.get("atlas-text-regex-usage-in-query"),...a?{onPrimaryActionButtonClick:i}:{primaryActionButtonLabel:void 0}}:{...s.qpO.get("query-executed-without-index"),...a?{onPrimaryActionButtonClick:r}:{primaryActionButtonLabel:void 0},onAssistantButtonClick:o}},ba=(0,s.AHW)({display:"flex",justifyContent:"flex-end",gap:s.YKD[2]}),va=(0,s.AHW)({display:"flex",flexDirection:"column",flex:"none",flexShrink:0,overflow:"auto",marginBottom:s.YKD[200],gap:s.YKD[200],maxHeight:"340px"}),xa=(0,s.AHW)({display:"flex",flexShrink:0,marginBottom:s.YKD[200]}),Ea=(0,s.AHW)({marginTop:s.YKD[400]-s.YKD[100],paddingLeft:s.YKD[800],display:"flex",flexDirection:"column",gap:s.YKD[400]}),Ca=(0,s.AHW)({display:"flex",flexDirection:"row",alignItems:"center",gap:s.YKD[400],marginTop:s.YKD[100]}),wa=(0,s.AHW)({alignSelf:"end"}),Ia=({open:e,documentCount:t,filter:n,namespace:a,sampleDocuments:i,onCancel:o,onConfirmDeletion:l,onExportToLanguage:c})=>{const d=r().createElement("div",{className:va},i.map(((e,t)=>r().createElement(s.yY_,{key:t,className:(0,s.cx)(xa)},r().createElement(f,{doc:e}))))),u=(0,s.BiT)();return r().createElement(s.aFV,{setOpen:o,open:e,"data-testid":"bulk-delete-modal",initialFocus:`#${u}`},r().createElement(s.rQ0,{title:`Delete ${t??""} document${1===t?"":"s"}`,subtitle:a,variant:"danger"}),r().createElement(s.cwr,{variant:"danger",className:Ea},r().createElement("div",{className:Ca},r().createElement($e,{filterQuery:(0,z.AO)(n)??""}),r().createElement(s.$nd,{className:wa,variant:"primaryOutline",size:"default",leftGlyph:r().createElement(s.Int,{glyph:"Code"}),onClick:c,"data-testid":"export-button",id:u,autoFocus:!0},"Export")),r().createElement("div",null,r().createElement("b",{"data-testid":"preview-title"},"Preview (sample of ",i.length," document",1===i.length?"":"s",")"),d)),r().createElement(s.jlY,{className:ba},r().createElement(s.$nd,{variant:"default",onClick:o,"data-testid":"cancel-button"},"Cancel"),r().createElement(s.$nd,{variant:"danger",onClick:l,"data-testid":"delete-button"},"Delete ",t??""," document",1===t?"":"s")))};var Sa=n(45363),Aa=n(21119);const ka=(0,s.AHW)({paddingTop:0,paddingRight:s.YKD[400],paddingBottom:s.YKD[800],paddingLeft:s.YKD[400]}),Da=(0,s.AHW)({display:"flex",flexDirection:"column",alignItems:"stretch",width:"100%",height:"100%",flexGrow:1,position:"relative"}),Na=(0,s.AHW)({height:"100%",display:"flex",justifyContent:"center"}),Ma=({initialScrollTop:e,scrollTriggerRef:t,scrollableContainerRef:n,columnWidths:a,onColumnWidthChange:o,...s})=>0===s.docs?.length?null:"List"===s.view?r().createElement(St,(0,i.A)({},s,{initialScrollTop:e,scrollTriggerRef:t,scrollableContainerRef:n})):"Table"===s.view?r().createElement(r().Fragment,null,r().createElement("div",{ref:t}),r().createElement(Hn,(0,i.A)({key:s.darkMode?"dark":"light"},s,{className:ka,columnWidths:a,onColumnWidthChange:o}))):r().createElement(Rt,(0,i.A)({},s,{initialScrollTop:e,scrollTriggerRef:t,scrollableContainerRef:n})),Ta=(0,s.U6i)((e=>{const{view:t,error:n,count:o,lastCountRunMaxTimeMS:c,loadingCount:d,start:u,end:p,page:m,getPage:g,store:h,openExportFileDialog:f,viewChanged:y,isWritable:b,isMockDataGeneratorEligibleAndSchemaReady:v,instanceDescription:x,refreshDocuments:E,resultId:w,isCollectionScan:I,isSearchIndexesSupported:S,openInsertDocumentDialog:A,openImportFileDialog:k,openBulkUpdateModal:D,docs:N,status:M,debouncingLoad:T,closeInsertDocumentDialog:P,insertDocument:L,insertMany:O,updateJsonDoc:R,toggleInsertDocument:H,toggleInsertDocumentView:F,version:W,ns:j,updateComment:z,insert:_,bulkUpdate:$,isUpdatePreviewSupported:Y,closeBulkUpdateModal:K,updateBulkUpdatePreview:G,runBulkUpdate:V,docsPerPage:U,updateMaxDocumentsPerPage:q}=e,Z=(0,a.useCallback)((e=>{"insert-document"===e?A?.({_id:new C.ObjectId},!1):"import-file"===e&&k?.("crud-toolbar")}),[k,A]),J=(0,a.useCallback)((()=>{h.refreshDocuments(!0)}),[h]),Q=(0,a.useCallback)((()=>{h.refreshDocuments()}),[h]),X=(0,a.useCallback)((()=>{h.cancelOperation()}),[h]),ee=(0,a.useCallback)((()=>{D()}),[D]),te=(0,a.useCallback)((()=>{h.openBulkDeleteDialog()}),[h]),ne=(0,a.useCallback)((e=>{h.saveUpdateQuery(e)}),[h]),ae=(0,a.useCallback)((()=>{h.closeBulkDeleteDialog()}),[h]),re=(0,a.useCallback)((()=>{h.runBulkDelete()}),[h]),ie=(0,a.useCallback)((()=>{h.openDeleteQueryExportToLanguageDialog()}),[h]),oe=(0,Et.L0)("crud"),se=(0,Et.PW)("crud"),{readOnly:le,readWrite:ce,enableImportExport:de,legacyUUIDDisplayEncoding:ue}=(0,l.gc)(["readOnly","readWrite","enableImportExport","legacyUUIDDisplayEncoding"]),pe=!le&&!h.state.isDataLake&&!h.state.isReadonly&&0===Object.keys(oe.project??{}).length,me=0===N.length,ge=M===fa,he=M===ga&&!T,fe=M===ha,{scrollRef:ye,currentViewInitialScrollTop:be,setCurrentViewInitialScrollTop:ve}=((e,t)=>{const n=(0,a.useRef)(null),[r,i]=(0,Sa.i2)("list-view-initial-scroll-top",0),[o,l]=(0,Sa.i2)("json-view-initial-scroll-top",0),c=(0,a.useMemo)((()=>"List"===e?r:"JSON"===e?o:void 0),[e,r,o]),d=(0,s.HIF)(c),u=(0,a.useCallback)((t=>{"List"===e?i(t):"JSON"===e&&l(t)}),[e,i,l]),p=(0,s.HIF)(u);return(0,a.useLayoutEffect)((()=>(n.current&&void 0!==d.current&&(n.current.scrollTop=d.current),()=>{p.current(n.current?.scrollTop??0)})),[d,p]),(0,a.useLayoutEffect)((()=>{n.current&&void 0!==d.current&&!t&&(n.current.scrollTop=d.current)}),[d,t]),{scrollRef:n,currentViewInitialScrollTop:c,setCurrentViewInitialScrollTop:u}})(t,he),xe=(0,a.useCallback)((e=>{const t=ye.current?.scrollTop??0;q(e),ve(e>U?t:0)}),[ye,U,ve,q]),[Ee,Ce]=(0,Sa.i2)("columnWidths",{}),we=(0,a.useCallback)((e=>{Ce((t=>({...t,...e})))}),[Ce]),Ie=(0,a.useCallback)((t=>{let n=null;return he?n=r().createElement("div",{className:Na},r().createElement(s.yao,{"data-testid":"fetching-documents",progressText:"Fetching Documents",cancelText:"Stop",onCancel:X})):fe||(n=me?ge?r().createElement("div",{"data-testid":"document-list-zero-state"},r().createElement(s.HYq,{icon:s.pyG,title:"This collection has no data",subTitle:"It only takes a few seconds to import data from a JSON or CSV file.",callToAction:de&&r().createElement(s.$nd,{disabled:!pe,onClick:()=>{k?.("empty-state")},"data-testid":"import-data-button",variant:"primary",size:"small"},"Import data")})):r().createElement("div",{"data-testid":"document-list-zero-state"},r().createElement(s.HYq,{icon:s.pyG,title:"No results",subTitle:"Try modifying your query to get results."})):r().createElement(Ma,(0,i.A)({},e,{isEditable:pe,outdated:se,query:oe,initialScrollTop:be,scrollableContainerRef:ye,scrollTriggerRef:t,columnWidths:Ee,onColumnWidthChange:we,legacyUUIDDisplayEncoding:ue}))),n}),[he,fe,X,me,ge,de,pe,k,e,se,oe,ye,be,Ee,we,ue]),Se=(0,a.useCallback)((e=>{"List"!==t&&"JSON"!==t||ve(ye.current?.scrollTop??0),y(e)}),[t,ve,ye,y]),Ae=(0,a.useCallback)((()=>{N.forEach((e=>!e.expanded&&e.expand()))}),[N]),ke=(0,a.useCallback)((()=>{N.forEach((e=>e.expanded&&e.collapse()))}),[N]),{tellMoreAboutInsight:De}=(0,Aa.hb)();return r().createElement("div",{className:Da,"data-testid":"compass-crud"},r().createElement(s.XvC,{scrollableContainerRef:ye,initialTopInView:0===be,toolbar:r().createElement(ma,{activeDocumentView:t,error:n,count:o,isFetching:he,isMockDataGeneratorEligibleAndSchemaReady:v,lastCountRunMaxTimeMS:c,loadingCount:d,start:u,end:p,page:m,getPage:g,insertDataHandler:Z,onApplyClicked:J,onResetClicked:Q,onUpdateButtonClicked:ee,onDeleteButtonClicked:te,onExpandAllClicked:Ae,onCollapseAllClicked:ke,openExportFileDialog:f,onOpenExportToLanguage:h.openQueryExportToLanguageDialog.bind(h),outdated:se,readonly:!pe,viewSwitchHandler:Se,isWritable:b,instanceDescription:x,refreshDocuments:E,resultId:w,querySkip:oe.skip,queryLimit:oe.limit,insights:ya({query:JSON.stringify(oe.filter??{}),isCollectionScan:Boolean(I),isSearchIndexesSupported:S,canCreateIndexes:!ce,onCreateIndex:h.openCreateIndexModal.bind(h),onCreateSearchIndex:h.openCreateSearchIndexModal.bind(h),onAssistantButtonClick:De?()=>De({id:"query-executed-without-index",query:JSON.stringify(oe)}):void 0}),docsPerPage:U,updateMaxDocumentsPerPage:xe})},Ie),pe&&r().createElement(r().Fragment,null,r().createElement(B,(0,i.A)({closeInsertDocumentDialog:P,insertDocument:L,insertMany:O,updateJsonDoc:R,toggleInsertDocument:H,toggleInsertDocumentView:F,jsonView:!0,version:W,ns:j,updateComment:z},_)),r().createElement(yt,(0,i.A)({ns:j,filter:oe.filter??{},count:o,enablePreview:Y},$,{closeBulkUpdateModal:K,updateBulkUpdatePreview:G,runBulkUpdate:V,saveUpdateQuery:ne})),r().createElement(Ia,{open:"open"===h.state.bulkDelete.status,namespace:h.state.ns,documentCount:h.state.bulkDelete.affected,filter:oe.filter??{},onCancel:ae,onConfirmDeletion:re,sampleDocuments:h.state.bulkDelete.previews,onExportToLanguage:ie})))}));var Pa=n(94664),La=n.n(Pa),Oa=n(48783),Ra=n.n(Oa),Ha=n(89951),Fa=n(19461),Wa=n(32318);class ja{options;constructor(e){this.options=e;for(const e of Object.getOwnPropertyNames(Object.getPrototypeOf(this)))this[e]=this[e]}}const Ba="Mixed";class za extends ja{constructor(e){super(e)}init(){const e=this.options.actions;this.columns={},this.showing={},this.stageRemove={},this.listenTo(e.addColumn,this.addColumn.bind(this)),this.listenTo(e.removeColumn,this.removeColumn.bind(this)),this.listenTo(e.resetColumns,this.resetColumns.bind(this)),this.listenTo(e.cleanCols,this.cleanCols.bind(this)),this.listenTo(e.elementAdded,this.elementAdded.bind(this)),this.listenTo(e.elementRemoved,this.elementRemoved.bind(this)),this.listenTo(e.elementMarkRemoved,this.elementMarkRemoved.bind(this)),this.listenTo(e.elementTypeChanged,this.elementTypeChanged.bind(this)),this.listenTo(e.renameColumn,this.renameColumn.bind(this)),this.listenTo(e.replaceDoc,this.replaceDoc.bind(this)),this.setShowing=this.setShowing.bind(this)}setShowing(e){if(!(e in this.columns))return;const t=Object.values(this.columns[e]);let n=t[0];for(let e=0;e<t.length;e++)if(n!==t[e]){n=Ba;break}this.showing[e]=n}stageField(e,t,n){n?(e in this.stageRemove||(this.stageRemove[e]={}),this.stageRemove[e][t]=!0):e in this.stageRemove&&(delete this.stageRemove[e][t],(0,w.isEmpty)(this.stageRemove[e])&&delete this.stageRemove[e])}resetColumns(e){this.showing={},this.stageRemove={},this.columns=(0,w.cloneDeep)(e);const t=Object.keys(e);for(let e=0;e<t.length;e++)this.setShowing(t[e])}replaceDoc(e,t,n){const a={refresh:{oid:t}};(0,w.forEach)(this.columns,((a,r)=>{e in this.columns[r]&&(delete this.columns[r][e],(0,w.isEmpty)(this.columns[r])&&delete this.columns[r]),r in n&&(r in this.columns||(this.columns[r]={}),this.columns[r][t]=_.Ay.type(n[r])),this.setShowing(r)})),(0,w.forEach)(this.stageRemove,((t,n)=>{n in this.stageRemove&&e in this.stageRemove[n]&&(delete this.stageRemove[n][e],(0,w.isEmpty)(this.stageRemove[n])&&delete this.stageRemove[n])})),(0,w.forEach)(n,((e,a)=>{if("_id"!==a&&!(a in this.columns)){const e=_.Ay.type(n[a]);this.columns[a]={},this.columns[a][t]=e,this.setShowing(a)}})),a.updateHeaders={showing:this.showing},this.trigger(a)}renameColumn(e,t){this.columns[e]&&(this.columns[t]=this.columns[e],this.setShowing(t),this.stageRemove[e]&&(this.stageRemove[t]=this.stageRemove[e]),delete this.columns[e],delete this.stageRemove[e],delete this.showing[e])}cleanCols(){const e=[],t=Object.keys(this.showing);for(let n=0;n<t.length;n++){const a=t[n];a in this.columns||a in this.stageRemove||(e.push(a),delete this.showing[a])}e.length&&this.trigger({remove:{colIds:e}})}elementAdded(e,t,n){let a;if(e in this.columns?(this.columns[e][n]=t,a=this.showing[e],Object.keys(this.columns[e]).length<2?this.showing[e]=t:t!==a&&(this.showing[e]=Ba)):(this.columns[e]={},this.columns[e][n]=t,this.showing[e]=t),this.stageField(e,n,!1),a!==this.showing[e]){const t={updateHeaders:{showing:{[e]:this.showing[e]}}};this.trigger(t)}}elementMarkRemoved(e,t){if(delete this.columns[e][t],this.stageField(e,t,!0),(0,w.isEmpty)(this.columns[e]))delete this.columns[e];else{const t=this.showing[e];if(t===Ba&&this.setShowing(e),t!==this.showing[e]){const t={updateHeaders:{showing:{[e]:this.showing[e]}}};this.trigger(t)}}}elementRemoved(e,t,n){const a=Object.create(null),r={};if(n){for(let n=+e;n<Object.keys(this.showing).length;n++)n+1 in this.columns&&t in this.columns[n+1]?(n in this.columns||(this.columns[n]={}),this.columns[n][t]=this.columns[n+1][t],this.stageField(String(n),t,!1),this.showing[n]!==this.columns[n][t]&&(this.setShowing(String(n)),r[n]=this.showing[n])):n+1 in this.stageRemove&&t in this.stageRemove[n+1]?(this.stageField(String(n),t,!0),n in this.columns&&(delete this.columns[n][t],(0,w.isEmpty)(this.columns[n])&&delete this.columns[n],this.setShowing(String(n)),r[n]=this.showing[n])):(this.stageField(String(n),t,!1),n in this.columns&&(delete this.columns[n][t],(0,w.isEmpty)(this.columns[n])?delete this.columns[n]:(this.setShowing(String(n)),r[n]=this.showing[n])),n in this.columns||n in this.stageRemove||(a.remove={colIds:[n]},delete this.showing[n]));a.refresh={oid:t}}else if(this.columns[e]&&this.columns[e][t]&&delete this.columns[e][t],this.stageField(e,t,!1),(0,w.isEmpty)(this.columns[e]))delete this.columns[e],e in this.stageRemove||(a.remove={colIds:[e]},delete this.showing[e]);else{const t=this.showing[e];t===Ba&&this.setShowing(e),t!==this.showing[e]&&(r[e]=this.showing[e])}(0,w.isEmpty)(r)||(a.updateHeaders={showing:r}),(0,w.isEmpty)(a)||this.trigger(a)}elementTypeChanged(e,t,n){const a=this.showing[e];if(this.columns[e][n]=t,t!==a&&(a===Ba?this.setShowing(e):this.showing[e]=1===Object.keys(this.columns[e]).length?t:Ba,a!==this.showing[e])){const t={updateHeaders:{showing:{[e]:this.showing[e]}}};this.trigger(t)}}addColumn(e,t,n,a,r,i,o){const s={edit:{colId:e,rowIndex:n}};if(i||(s.add={newColId:e,colIdBefore:t,path:a,isArray:r,colType:""}),r){let t=Object.keys(this.showing).length-1;i||(t++,this.columns[t]={});const n={};for(let a=t;a>+e;a--)a-1 in this.columns&&o in this.columns[a-1]?(a in this.columns||(this.columns[a]={}),this.columns[a][o]=this.columns[a-1][o],this.setShowing(String(a)),n[a]=this.showing[a]):a-1 in this.stageRemove&&o in this.stageRemove[a-1]&&(a in this.columns&&(delete this.columns[a][o],(0,w.isEmpty)(this.columns[a])&&delete this.columns[a]),a in this.showing||(this.showing[a]=this.showing[a-1])),this.stageField(String(a),o,!1),String(a-1)in this.stageRemove&&o in this.stageRemove[a-1]&&this.stageField(String(a),o,!0);e in this.columns&&(delete this.columns[e][o],(0,w.isEmpty)(this.columns[e])?delete this.columns[e]:(this.setShowing(e),n[e]=this.showing[e])),this.stageField(""+e,o,!1),(0,w.isEmpty)(n)||(s.updateHeaders={showing:n})}this.trigger(s)}removeColumn(e){this.trigger({remove:{colIds:[e]}})}}var _a=n(183);function $a({affectedDocuments:e,error:t,type:n}){let a;a=(e=>e instanceof _a.MongoNetworkError)(t)?("delete"===n?"Delete":"Update")+" operation - network error occurred.":void 0===e?`The ${n} operation failed.`:1===e?`${e} document could not be ${"delete"===n?"deleted":"updated"}.`:`${e} documents could not be ${"delete"===n?"deleted":"updated"}.`,(0,s.c3r)(`bulk-${n}-toast`,{title:a,variant:"warning",dismissible:!0,description:r().createElement(s.AF4,{statusMessage:t.message})})}const Ya="{\n $set: {\n\n },\n}",Ka=async(e,t,n,a,r,i,s,l)=>{const c=Ra().gte(n,"4.4.0")&&!a&&["disabled","unavailable",void 0].includes(e?.getCSFLEMode?.())&&(0,w.isEmpty)(s?.projection),d={...s,projection:c?{_id:0,__doc:"$$ROOT",__size:{$bsonSize:"$$ROOT"}}:s?.projection};try{let n=0,a=0;const s=(await e.find(r,i,d,l)).map((e=>{const{__doc:t,__size:r,...i}=e;let s;t&&r&&0===Object.keys(i).length?(s=new o.Ay(t),s.size=Number(r)):s=new o.Ay(e);const{subtype3Count:l,subtype4Count:c}=s.findUUIDs();return n+=l,a+=c,s}));return n>0&&t("UUID Encountered",{subtype:3,count:n}),a>0&&t("UUID Encountered",{subtype:4,count:a}),s}catch(t){if(c&&"MongoServerError"===t.name)return(await e.find(r,i,s,l)).map((e=>new o.Ay(e)));throw t}},Ga=e=>{const t=e.toJSON();return{document_count:t.document_count,storage_size:t.storage_size,free_storage_size:t.free_storage_size,avg_document_size:t.avg_document_size}},Va="error",Ua="modifying",qa=new Error("Cannot delete documents that do not have an _id field."),Za=new Error("Unable to update, no changes have been made."),Ja=5e3,Qa="compass_crud-max_docs_per_page";class Xa extends ja{mixins=[Ha.A.store()];listenables;dataService;preferences;localAppRegistry;favoriteQueriesStorage;recentQueriesStorage;fieldStoreService;logger;track;connectionInfoRef;instance;connectionScopedAppRegistry;queryBar;collection;constructor(e,t){super(e),this.listenables=e.actions,this.favoriteQueriesStorage=t.favoriteQueryStorage,this.recentQueriesStorage=t.recentQueryStorage,this.dataService=t.dataService,this.localAppRegistry=t.localAppRegistry,this.preferences=t.preferences,this.logger=t.logger,this.track=t.track,this.connectionInfoRef=t.connectionInfoRef,this.instance=t.instance,this.fieldStoreService=t.fieldStoreService,this.connectionScopedAppRegistry=t.connectionScopedAppRegistry,this.queryBar=t.queryBar,this.collection=t.collection}getInitialState(){const e=!!this.instance.dataLake.isDataLake,t=!!this.options.isReadonly;return{ns:this.options.namespace,collection:(0,Ft.Ay)(this.options.namespace).collection,abortController:null,error:null,docs:[],start:0,version:this.instance.build.version,end:0,page:0,view:"List",count:null,insert:this.getInitialInsertState(),bulkUpdate:this.getInitialBulkUpdateState(),bulkDelete:this.getInitialBulkDeleteState(),table:this.getInitialTableState(),isDataLake:e,isReadonly:t,isTimeSeries:!!this.options.isTimeSeries,status:"initial",debouncingLoad:!1,loadingCount:!1,lastCountRunMaxTimeMS:Ja,shardKeys:null,resultId:er(),isWritable:this.instance.isWritable,instanceDescription:this.instance.description,isCollectionScan:!1,isSearchIndexesSupported:this.options.isSearchIndexesSupported,isUpdatePreviewSupported:"Single"!==this.instance.topologyDescription.type,docsPerPage:this.getInitialDocsPerPage(),collectionStats:Ga(this.collection)}}getInitialDocsPerPage(){const e=localStorage.getItem(Qa);return(e?parseInt(e):null)??25}getInitialInsertState(){return{doc:null,jsonDoc:null,csfleState:{state:"none"},mode:Ua,jsonView:!1,isOpen:!1,isCommentNeeded:!0}}getInitialBulkUpdateState(){return{isOpen:!1,updateText:Ya,preview:{changes:[]},syntaxError:void 0,serverError:void 0}}getInitialBulkDeleteState(){return{previews:[],status:"closed",affected:0}}getInitialTableState(){return{doc:null,path:[],types:[],editParams:null}}modeForTelemetry(){return this.state.view.toLowerCase()}copyToClipboard(e){this.track("Document Copied",{mode:this.modeForTelemetry()},this.connectionInfoRef.current);const t=e.toEJSON();navigator.clipboard.writeText(t)}getWriteError(e){return{message:e.message,info:e.errInfo}}updateMaxDocumentsPerPage(e){const t=this.state.docsPerPage;localStorage.setItem(Qa,String(e)),this.setState({docsPerPage:e}),t!==e&&this.refreshDocuments()}async removeDocument(e){this.track("Document Deleted",{mode:this.modeForTelemetry()},this.connectionInfoRef.current);const t=e.getId();if(void 0!==t){e.onRemoveStart();try{await this.dataService.deleteOne(this.state.ns,{_id:t}),e.onRemoveSuccess();const n={view:this.state.view,ns:this.state.ns};this.localAppRegistry.emit("document-deleted",n),this.connectionScopedAppRegistry.emit("document-deleted",n);const a=this.findDocumentIndex(e),r=this.state.docs?[...this.state.docs]:this.state.docs;r?.splice(a,1),this.setState({docs:r,count:null===this.state.count?null:this.state.count-1,end:Math.max(this.state.end-1,0)})}catch(t){e.onRemoveError(t),this.trigger(this.state)}}else e.onRemoveError(qa),this.trigger(this.state)}async _verifyUpdateAllowed(e,t){return!("enabled"===this.dataService.getCSFLEMode?.()&&!await(this.dataService.isUpdateAllowed?.(e,t.generateOriginalObject())))||(t.onUpdateError(new Error("Update blocked as it could unintentionally write unencrypted data due to a missing or incomplete schema.")),!1)}async updateDocument(e){this.track("Document Updated",{mode:this.modeForTelemetry()},this.connectionInfoRef.current);try{e.onUpdateStart();const{query:t,updateDoc:n}=e.generateUpdateUnlessChangedInBackgroundQuery({alwaysIncludeKeys:Object.keys(this.state.shardKeys||{}).map((e=>e.split(".")))});if(this.logger.debug("Performing findOneAndUpdate",{query:t,updateDoc:n}),0===Object.keys(n).length)return void e.onUpdateError(Za);if(!await this._verifyUpdateAllowed(this.state.ns,e))return;const[a,r]=await tr(this.dataService,this.state.ns,t,n,"update");if(a){if("InvalidPipelineOperator"===a.codeName&&a.message.match(/\$[gs]etField/)){const e=" ";a.message+=` (Updating fields whose names contain dots or start with $ require MongoDB${e}5.0 or above.)`}e.onUpdateError(a)}else if(r){e.onUpdateSuccess(r);const t=this.findDocumentIndex(e),n=this.state.docs?[...this.state.docs]:this.state.docs;n?.splice(t,1,new o.Ay(r)),this.setState({docs:n})}else e.onUpdateBlocked()}catch(t){e.onUpdateError(new Error(`An error occured when attempting to update the document: ${String(t.message)}`))}}async replaceDocument(e){this.track("Document Updated",{mode:this.modeForTelemetry()},this.connectionInfoRef.current);try{if(e.onUpdateStart(),!await this._verifyUpdateAllowed(this.state.ns,e))return;const t=e.generateObject(),n={alwaysIncludeKeys:[["_id"],...Object.keys(this.state.shardKeys||{}).map((e=>e.split(".")))]};if("enabled"===this.dataService.getCSFLEMode?.()){const a=await this.dataService.knownSchemaForCollection(this.state.ns);n.includableEncryptedKeys=a.encryptedFields.equalityQueryableEncryptedFields,t.__safeContent__&&(0,w.isEqual)(t.__safeContent__,e.generateOriginalObject().__safeContent__)&&a.hasSchema&&delete t.__safeContent__}const a=e.getQueryForOriginalKeysAndValuesForSpecifiedKeys(n);this.logger.debug("Performing findOneAndReplace",{query:a,object:t});const[r,i]=await tr(this.dataService,this.state.ns,a,t,"replace");if(r)e.onUpdateError(r);else{e.onUpdateSuccess(i);const t=this.findDocumentIndex(e),n=this.state.docs?[...this.state.docs]:this.state.docs;n?.splice(t,1,new o.Ay(i)),this.setState({docs:n})}}catch(t){e.onUpdateError(new Error(`An error occured when attempting to update the document: ${String(t.message)}`))}}updateComment(e){const t={...this.state.insert,isCommentNeeded:e};this.setState({insert:t})}findDocumentIndex(e){return(0,w.findIndex)(this.state.docs,(t=>e.getStringId()===t.getStringId()))}async getPage(e){const{ns:t,status:n,docsPerPage:a}=this.state;if(e<0)return;if(n===ga)return;const{filter:r,limit:i,sort:o,hint:s,project:c,collation:d,maxTimeMS:u,skip:p=0}=this.queryBar.getLastAppliedQuery("crud"),m=p+e*a;let g=a;if(i){const e=i-m;if(e<1)return;e<g&&(g=e)}const h=new AbortController,f=h.signal,y={skip:m,limit:g,hint:s??void 0,sort:o??void 0,projection:c??void 0,collation:d,maxTimeMS:(0,l.Tv)(this.preferences,u),promoteValues:!1,bsonRegExp:!0};this.setState({status:ga,abortController:h,error:null});const b=this.debounceLoading();let v,x;try{x=await Ka(this.dataService,this.track,this.state.version,this.state.isDataLake,t,r??{},y,{abortSignal:f})}catch(e){x=[],v=e}const E=v?0:x.length;this.setState({error:v,status:v?ha:"fetchedPagination",docs:x,start:0===E?0:m+1,end:m+E,page:e,table:this.getInitialTableState(),resultId:er(),abortController:null}),this.fieldStoreService.updateFieldsFromDocuments(this.state.ns,[x[0]?.generateObject()]),b()}closeInsertDocumentDialog(){this.setState({insert:this.getInitialInsertState()})}closeBulkUpdateModal(){this.setState({bulkUpdate:{...this.state.bulkUpdate,isOpen:!1}})}async openInsertDocumentDialog(e,t=!1){const n=new o.Ay(e);if(t){this.track("Document Cloned",{mode:this.modeForTelemetry()},this.connectionInfoRef.current);for(const e of n.elements)if("_id"===e.currentKey){n.elements.remove(e);break}}const a={state:"none"},r=this.dataService.getCSFLEMode?.();if("enabled"===r){const{hasSchema:t,encryptedFields:{encryptedFields:n}}=await this.dataService.knownSchemaForCollection(this.state.ns);n.length>0&&(a.encryptedFields=n.map((e=>e.join(".")))),t?await(this.dataService.isUpdateAllowed?.(this.state.ns,e))?a.state="has-known-schema":a.state="incomplete-schema-for-cloned-doc":a.state="no-known-schema"}else"disabled"===r&&(a.state="csfle-disabled");const i=n.toEJSON();this.setState({insert:{doc:n,jsonDoc:i,jsonView:!0,error:void 0,csfleState:a,mode:Ua,isOpen:!0,isCommentNeeded:!0}})}async openBulkUpdateModal(e){this.track("Bulk Update Opened",{isUpdatePreviewSupported:this.state.isUpdatePreviewSupported},this.connectionInfoRef.current),await this.updateBulkUpdatePreview(e??Ya),this.setState({bulkUpdate:{...this.state.bulkUpdate,isOpen:!0}})}async updateBulkUpdatePreview(e){if(this.state.bulkUpdate.previewAbortController&&this.state.bulkUpdate.previewAbortController.abort(),!this.state.isUpdatePreviewSupported){try{nr(e)}catch(t){return void this.setState({bulkUpdate:{...this.state.bulkUpdate,updateText:e,preview:{changes:[]},serverError:void 0,syntaxError:t,previewAbortController:void 0}})}return void this.setState({bulkUpdate:{...this.state.bulkUpdate,updateText:e,preview:{changes:[]},serverError:void 0,syntaxError:void 0,previewAbortController:void 0}})}const t=new AbortController;let n;this.setState({bulkUpdate:{...this.state.bulkUpdate,previewAbortController:t}});try{n=nr(e)}catch(n){if(t.signal.aborted)return;return void this.setState({bulkUpdate:{...this.state.bulkUpdate,updateText:e,preview:{changes:[]},serverError:void 0,syntaxError:n,previewAbortController:void 0}})}if(t.signal.aborted)return;const{ns:a}=this.state,{filter:r={}}=this.queryBar.getLastAppliedQuery("crud");let i;try{i=await this.dataService.previewUpdate(a,r,n,{sample:3,abortSignal:t.signal})}catch(n){if(t.signal.aborted)return;return void this.setState({bulkUpdate:{...this.state.bulkUpdate,updateText:e,preview:{changes:[]},serverError:n,syntaxError:void 0,previewAbortController:void 0}})}t.signal.aborted||this.setState({bulkUpdate:{...this.state.bulkUpdate,updateText:e,preview:i,serverError:void 0,syntaxError:void 0,previewAbortController:void 0}})}async runBulkUpdate(){const e=this.queryBar.getLastAppliedQuery("crud");this.track("Bulk Update Executed",{isUpdatePreviewSupported:this.state.isUpdatePreviewSupported,has_filter:Object.keys(e.filter??{}).length>0},this.connectionInfoRef.current),this.closeBulkUpdateModal(),this.setState({bulkUpdate:{...this.state.bulkUpdate,affected:this.state.count??void 0}});const{ns:t}=this.state,{filter:n={}}=e;let a;try{a=nr(this.state.bulkUpdate.updateText)}catch{return}await(this.recentQueriesStorage?.saveQuery({_ns:this.state.ns,filter:n,update:a})),function({affectedDocuments:e}){let t;switch(e){case void 0:t="The update operation is in progress.";break;case 1:t=`${e} document is being updated.`;break;default:t=`${e} documents are being updated.`}(0,s.c3r)("bulk-update-toast",{title:"",variant:"progress",dismissible:!0,description:r().createElement(s.AF4,{statusMessage:t})})}({affectedDocuments:this.state.bulkUpdate.affected});try{await this.dataService.updateMany(t,n,a),function({affectedDocuments:e,onRefresh:t}){let n;switch(e){case void 0:n="The update operation finished successfully.";break;case 1:n=`${e} document has been updated.`;break;default:n=`${e} documents have been updated.`}(0,s.c3r)("bulk-update-toast",{title:"",variant:"success",dismissible:!0,description:r().createElement(s.AF4,{statusMessage:n,actionHandler:()=>{(0,s.cQH)("bulk-update-toast"),t()},actionText:"refresh"})})}({affectedDocuments:this.state.bulkUpdate.affected,onRefresh:()=>{this.refreshDocuments()}})}catch(e){i={affectedDocuments:this.state.bulkUpdate.affected,error:e},$a({...i,type:"update"}),this.logger.log.error((0,L.oW)(1001000269),"Bulk Update Documents",`Update operation failed: ${e.message}`,e)}var i}openImportFileDialog(){this.connectionScopedAppRegistry.emit("open-import",{namespace:this.state.ns,origin:"empty-state"})}openExportFileDialog(e){const{filter:t,project:n,collation:a,limit:r,skip:i,sort:o}=this.queryBar.getLastAppliedQuery("crud");this.connectionScopedAppRegistry.emit("open-export",{namespace:this.state.ns,query:{filter:t,project:n,collation:a,limit:r,skip:i,sort:o},exportFullCollection:e,origin:"crud-toolbar"})}toggleInsertDocument(e){if("JSON"===e){const e=this.state.insert.doc?.toEJSON();this.setState({insert:{doc:this.state.insert.doc,jsonView:!0,jsonDoc:e??null,error:void 0,csfleState:this.state.insert.csfleState,mode:Ua,isOpen:!0,isCommentNeeded:this.state.insert.isCommentNeeded}})}else{let e;e=""===this.state.insert.jsonDoc?this.state.insert.doc:o.Ay.FromEJSON(this.state.insert.jsonDoc??""),this.setState({insert:{doc:e,jsonView:!1,jsonDoc:this.state.insert.jsonDoc,error:void 0,csfleState:this.state.insert.csfleState,mode:Ua,isOpen:!0,isCommentNeeded:this.state.insert.isCommentNeeded}})}}toggleInsertDocumentView(e){const t="JSON"===e;this.setState({insert:{doc:new o.yo({}),jsonDoc:this.state.insert.jsonDoc,jsonView:t,error:void 0,csfleState:this.state.insert.csfleState,mode:Ua,isOpen:!0,isCommentNeeded:this.state.insert.isCommentNeeded}})}updateJsonDoc(e){this.setState({insert:{doc:new o.yo({}),jsonDoc:e,jsonView:!0,error:void 0,csfleState:this.state.insert.csfleState,mode:Ua,isOpen:!0,isCommentNeeded:this.state.insert.isCommentNeeded}})}async insertMany(){try{const e=this.fieldStoreService.getSchemaFieldsForNamespace(this.state.ns),t=o.Ay.FromEJSONArray(this.state.insert.jsonDoc??"").map((t=>(e&&t.preserveTypesFromSchema(e),t.generateObject())));this.track("Document Inserted",{mode:this.state.insert.jsonView?"json":"field-by-field",multiple:t.length>1},this.connectionInfoRef.current),await this.dataService.insertMany(this.state.ns,t);const n={ns:this.state.ns,view:this.state.view,mode:this.state.insert.jsonView?"json":"default",multiple:!0,docs:t};this.fieldStoreService.updateFieldsFromDocuments(this.state.ns,t),this.connectionScopedAppRegistry.emit("document-inserted",n),this.state.insert=this.getInitialInsertState()}catch(e){this.setState({insert:{doc:new o.yo({}),jsonDoc:this.state.insert.jsonDoc,jsonView:!0,error:this.getWriteError(e),csfleState:this.state.insert.csfleState,mode:Va,isOpen:!0,isCommentNeeded:this.state.insert.isCommentNeeded}})}this.refreshDocuments()}async insertDocument(){let e;this.track("Document Inserted",{mode:this.state.insert.jsonView?"json":"field-by-field",multiple:!1},this.connectionInfoRef.current);try{const t=this.fieldStoreService.getSchemaFieldsForNamespace(this.state.ns);if(this.state.insert.jsonView){const n=o.Ay.FromEJSON(this.state.insert.jsonDoc??"");t&&n.preserveTypesFromSchema(t),e=n.generateObject()}else{const n=new o.Ay(this.state.insert.doc.generateObject());t&&n.preserveTypesFromSchema(t),e=n.generateObject()}await this.dataService.insertOne(this.state.ns,e);const n={ns:this.state.ns,view:this.state.view,mode:this.state.insert.jsonView?"json":"default",multiple:!1,docs:[e]};this.fieldStoreService.updateFieldsFromDocuments(this.state.ns,[e]),this.connectionScopedAppRegistry.emit("document-inserted",n),this.state.insert=this.getInitialInsertState()}catch(e){return void this.setState({insert:{doc:this.state.insert.doc,jsonDoc:this.state.insert.jsonDoc,jsonView:this.state.insert.jsonView,error:this.getWriteError(e),csfleState:this.state.insert.csfleState,mode:Va,isOpen:!0,isCommentNeeded:this.state.insert.isCommentNeeded}})}this.refreshDocuments()}drillDown(e,t,n=null){this.setState({table:{path:this.state.table.path.concat([t.currentKey]),types:this.state.table.types.concat([t.currentType]),doc:e,editParams:n}})}pathChanged(e,t){this.setState({table:{doc:this.state.table.doc,editParams:this.state.table.editParams,path:e,types:t}})}viewChanged(e){this.setState({view:e})}isCountHintSafe(e){const{isTimeSeries:t}=this.state;return!(t||e.filter&&Object.keys(e.filter).length)}isInitialQuery(e={}){return(0,w.isEmpty)(e.filter)&&(0,w.isEmpty)(e.project)&&(0,w.isEmpty)(e.collation)}collectionStatsFetched(e){this.setState({collectionStats:Ga(e)})}async refreshDocuments(e=!1){if(this.dataService&&!this.dataService.isConnected())return void this.logger.log.warn((0,L.oW)(1001000072),"Documents","Trying to refresh documents but dataService is disconnected");const{ns:t,status:n,docsPerPage:a}=this.state,r=this.queryBar.getLastAppliedQuery("crud");if(n===ga)return;if(e){const{isTimeSeries:e,isReadonly:t}=this.state,{defaultSortOrder:n}=this.preferences.getPreferences();this.track("Query Executed",{has_filter:!!r.filter&&Object.keys(r.filter).length>0,has_projection:!!r.project&&Object.keys(r.project).length>0,has_skip:(r.skip??0)>0,has_sort:!!r.sort&&Object.keys(r.sort).length>0,default_sort:n?/_id/.test(n)?"_id":"natural":"none",has_limit:(r.limit??0)>0,has_collation:!!r.collation,changed_maxtimems:6e4!==r.maxTimeMS,collection_type:e?"time-series":t?"readonly":"collection",used_regex:p(r.filter??{}),mode:this.modeForTelemetry()},this.connectionInfoRef.current)}const i=new AbortController,o=i.signal,s={maxTimeMS:(0,l.Tv)(this.preferences,r.maxTimeMS),signal:o},d={skip:r.skip,maxTimeMS:(0,l.Tv)(this.preferences,(r.maxTimeMS??0)>Ja?Ja:r.maxTimeMS),signal:o,...r.hint?{hint:r.hint}:{}};!d.hint&&this.isCountHintSafe(r)&&(d.hint="_id_");const u=!(this.options.isReadonly&&this.options.sourceName||this.options.isTimeSeries),{defaultSortOrder:m}=this.preferences.getPreferences();let g=r.sort;!g&&u&&m&&(g=(0,z.tf)("sort",m));const h={sort:g??void 0,projection:r.project??void 0,skip:r.skip,limit:a,collation:r.collation,hint:r.hint??void 0,maxTimeMS:(0,l.Tv)(this.preferences,r.maxTimeMS),promoteValues:!1,bsonRegExp:!0};r.limit&&r.limit>0&&(d.limit=r.limit,h.limit=Math.min(a,r.limit)),this.logger.log.info((0,L.oW)(1001000073),"Documents","Refreshing documents",{ns:t,withFilter:!(0,w.isEmpty)(r.filter),findOptions:h,countOptions:d}),(0,w.isEmpty)(r.filter)&&(0,w.isEmpty)(r.sort)?this.setState({isCollectionScan:!1}):this.dataService.explainFind(t,r.filter??{},h,{explainVerbosity:"queryPlanner",abortSignal:o}).then((e=>{const t=new Wa.d(e);this.setState({isCollectionScan:t.isCollectionScan})})).catch((()=>{})),async function(e,t,n,a,{signal:r,skip:i,limit:o,maxTimeMS:s,hint:c},d=()=>{}){const u={maxTimeMS:(0,l.Tv)(t,s),hint:c};let p;p=a&&Object.keys(a).length>0?a:{};const m=[{$match:p}];let g;i&&m.push({$skip:i}),o&&m.push({$limit:o}),m.push({$count:"count"});try{const t=await e.aggregate(n,m,u,{abortSignal:r});g=t.length?t[0].count:0}catch(t){if(e.isCancelError(t))throw t;d(t),g=null}return g}(this.dataService,this.preferences,t,r.filter??{},d,(e=>{this.logger.log.warn((0,L.oW)(1001000288),"Documents","Failed to count documents",e)})).then((e=>this.setState({count:e,loadingCount:!1}))).catch((e=>{if(!this.dataService.isCancelError(e))throw e;this.setState({loadingCount:!1})}));const f=[c(this.dataService,t,s,(e=>{this.logger.log.warn((0,L.oW)(1001000075),"Documents","Failed to fetch sharding keys",e)})),Ka(this.dataService,this.track,this.state.version,this.state.isDataLake,t,r.filter??{},h,{abortSignal:o})];this.setState({lastCountRunMaxTimeMS:d.maxTimeMS,status:ga,abortController:i,error:null,count:null,loadingCount:!0});const y=this.debounceLoading(),b={};try{const[e,n]=await Promise.all(f);Object.assign(b,{status:this.isInitialQuery(r)?fa:"fetchedCustom",error:null,docs:n,page:0,start:n.length>0?1:0,end:n.length,table:this.getInitialTableState(),shardKeys:e}),this.fieldStoreService.updateFieldsFromDocuments(this.state.ns,[n[0]?.generateObject()]),this.connectionScopedAppRegistry.emit("documents-refreshed",{ns:t})}catch(e){this.logger.log.error((0,L.oW)(1001000074),"Documents","Failed to refresh documents",e),Object.assign(b,{error:e,status:ha})}y(),Object.assign(b,{abortController:null,resultId:er()}),this.setState(b)}cancelOperation(){this.state.abortController?.abort(new Error("This operation was aborted")),this.setState({abortController:null})}debounceLoading(){this.setState({debouncingLoad:!0});const e=new Promise((e=>{setTimeout(e,200)}));let t;const n=new Promise((e=>{t=e}));return Promise.race([e,n]).then((()=>{this.setState({debouncingLoad:!1})})),t}hasProjection(e){return!!(e.project&&Object.keys(e.project).length>0)}openCreateIndexModal(){this.localAppRegistry.emit("open-create-index-modal",{query:C.EJSON.serialize(this.queryBar.getLastAppliedQuery("crud")?.filter)})}openCreateSearchIndexModal(){this.localAppRegistry.emit("open-create-search-index-modal")}openBulkDeleteDialog(){this.track("Bulk Delete Opened",{},this.connectionInfoRef.current);const e=(this.state.docs?.slice(0,5)||[]).map((e=>o.yo.FromEJSON(e.toEJSON())));this.setState({bulkDelete:{previews:e,status:"open",affected:this.state.count??void 0}})}bulkDeleteInProgress(){this.setState({bulkDelete:{...this.state.bulkDelete,status:"in-progress"}}),function({affectedDocuments:e}){let t;switch(e){case void 0:t="The delete operation is in progress.";break;case 1:t=`${e} document is being deleted.`;break;default:t=`${e} documents are being deleted.`}(0,s.c3r)("bulk-delete-toast",{title:"",variant:"progress",dismissible:!0,description:r().createElement(s.AF4,{statusMessage:t})})}({affectedDocuments:this.state.bulkDelete.affected})}bulkDeleteFailed(e){var t;t={affectedDocuments:this.state.bulkDelete.affected,error:e},$a({...t,type:"delete"}),this.logger.log.error((0,L.oW)(1001000268),"Bulk Delete Documents",`Delete operation failed: ${e.message}`,e)}bulkDeleteSuccess(){!function({affectedDocuments:e,onRefresh:t}){let n;switch(e){case void 0:n="The delete operation finished successfully.";break;case 1:n=`${e} document has been deleted.`;break;default:n=`${e} documents have been deleted.`}(0,s.c3r)("bulk-delete-toast",{title:"",variant:"success",dismissible:!0,description:r().createElement(s.AF4,{statusMessage:n,actionHandler:()=>{(0,s.cQH)("bulk-delete-toast"),t()},actionText:"refresh"})})}({affectedDocuments:this.state.bulkDelete.affected,onRefresh:()=>{this.refreshDocuments()}})}closeBulkDeleteDialog(){this.setState({bulkDelete:{...this.state.bulkDelete,status:"closed"}})}async runBulkDelete(){const e=this.queryBar.getLastAppliedQuery("crud"),{affected:t}=this.state.bulkDelete;if(this.closeBulkDeleteDialog(),await(0,s.$TK)({title:"Are you absolutely sure?",buttonText:`Delete ${t?`${t} `:""} document${1!==t?"s":""}`,description:`This action can not be undone. This will permanently delete ${t??"an unknown number of"} document${1!==t?"s":""}.`,warning:"The document list and count may not always reflect the latest updates in real time. This action will apply to all relevant documents, including those not currently visible, so please ensure they are handled safely.",variant:"danger"})){this.bulkDeleteInProgress();const{filter:t={}}=e;try{await this.dataService.deleteMany(this.state.ns,t),this.track("Bulk Delete Executed",{has_filter:Object.keys(e.filter??{}).length>0},this.connectionInfoRef.current),this.bulkDeleteSuccess();const n={view:this.state.view,ns:this.state.ns};this.localAppRegistry.emit("documents-deleted",n),this.connectionScopedAppRegistry.emit("documents-deleted",n)}catch(e){this.bulkDeleteFailed(e)}}}openQueryExportToLanguageDialog(){const e=this.queryBar.getLastAppliedQuery("crud");this.localAppRegistry.emit("open-query-export-to-language",{filter:(0,z.AO)(e.filter)||"{}",project:e.project?(0,z.AO)(e.project):void 0,sort:e.sort?(0,z.AO)(e.sort):void 0,collation:e.collation?(0,z.AO)(e.collation):void 0,skip:e.skip?String(e.skip):void 0,limit:e.limit?String(e.limit):void 0},"Query")}openDeleteQueryExportToLanguageDialog(){const{filter:e={}}=this.queryBar.getLastAppliedQuery("crud");this.localAppRegistry.emit("open-query-export-to-language",{filter:(0,z.AO)(e)||"{}"},"Delete Query")}async saveUpdateQuery(e){this.track("Bulk Update Favorited",{isUpdatePreviewSupported:this.state.isUpdatePreviewSupported},this.connectionInfoRef.current);const{filter:t}=this.queryBar.getLastAppliedQuery("crud");let n;try{n=nr(this.state.bulkUpdate.updateText)}catch{return}await(this.favoriteQueriesStorage?.saveQuery({_name:e,_ns:this.state.ns,filter:t,update:n})),(0,s.c3r)("saved-favorite-update-query",{title:"",variant:"success",dismissible:!0,timeout:6e3,description:`${e} added to "My Queries".`})}}function er(){return Math.floor(Math.random()*2**53)}async function tr(e,t,n,a,r){const i="update"===r?"findOneAndUpdate":"findOneAndReplace";let o;try{return[void 0,await e[i](t,n,a,{returnDocument:"after",promoteValues:!1})]}catch(e){o=e}if("ShardKeyNotFound"===o.codeName||6371402==+(o?.code??0)){const i="update"===r?"updateOne":"replaceOne";try{await e[i](t,n,a)}catch(e){return[e,void 0]}try{return[void 0,(await e.find(t,{_id:n._id},{promoteValues:!1}))[0]]}catch{}}return[o,void 0]}function nr(e){const t=(0,Fa.Ay)(e,{mode:Fa.X6.Strict,allowComments:!0,allowMethods:!0});if(!t||"object"!=typeof t)throw new Error("The provided definition is invalid.");return t}var ar=n(44457);const rr=(0,s.AHW)({listStyleType:"none",padding:0,margin:0,textAlign:"left"}),ir=(0,s.AHW)({display:"flex",gap:s.YKD[200]}),or=(e,t="number")=>{if("number"!=typeof(n=e)||isNaN(n))return"N/A";var n;const a=e<=1e3?0:1;return"bytes"===t?(0,s.V0R)(e,!0,a):(0,s.$Mb)(e)},sr=({text:e,details:t})=>r().createElement("div",{"data-testid":"collection-stats"},r().createElement(s.m_M,{"data-testid":"collection-stats-tooltip",align:"bottom",justify:"middle",trigger:r().createElement("span",{onClick:()=>{}},r().createElement(s.Exy,null,e))},r().createElement("ol",{className:rr},t.map(((e,t)=>r().createElement("li",{"data-testid":`tooltip-detail-${t}`,key:`tooltip-detail-${t}`},e)))))),lr=(0,s.AHW)({listStyle:"none",position:"relative",width:"100%"}),cr=(0,s.AHW)({position:"relative",marginBottom:s.YKD[100],"&:last-child":{marginBottom:0,borderBottom:"0 solid transparent"}});class dr extends r().Component{renderDocuments(){return this.props.docs.map(((e,t)=>r().createElement("li",{className:cr,"data-testid":"document-list-item",key:t},r().createElement(s.yY_,null,r().createElement(E,{doc:e,editable:this.props.isEditable,isTimeSeries:this.props.isTimeSeries,copyToClipboard:this.props.copyToClipboard,removeDocument:this.props.removeDocument,replaceDocument:this.props.replaceDocument,updateDocument:this.props.updateDocument,openInsertDocumentDialog:this.props.openInsertDocumentDialog})))))}render(){return r().createElement("ol",{className:(0,s.cx)(lr,this.props.className),"data-testid":"document-list"},this.renderDocuments())}static displayName="DocumentListView"}const ur=dr,pr=(0,s.AHW)({listStyle:"none",position:"relative",width:"100%"}),mr=(0,s.AHW)({position:"relative",marginBottom:s.YKD[200],"&:last-child":{marginBottom:0,borderBottom:"0px solid transparent"}}),gr=(0,s.AHW)({overflow:"hidden"});class hr extends r().Component{renderDocuments(){return this.props.docs.map(((e,t)=>r().createElement("li",{className:mr,"data-testid":"document-json-item",key:t},r().createElement(s.yY_,{className:gr},r().createElement(Mt,{namespace:this.props.namespace,key:e.uuid,doc:e,editable:this.props.isEditable,isTimeSeries:this.props.isTimeSeries,copyToClipboard:this.props.copyToClipboard,removeDocument:this.props.removeDocument,replaceDocument:this.props.replaceDocument,updateDocument:this.props.updateDocument,openInsertDocumentDialog:this.props.openInsertDocumentDialog})))))}render(){return r().createElement("ol",{className:(0,s.cx)(pr,this.props.className)},this.renderDocuments())}}const fr=hr,yr=(0,jn.nk)({name:"CompassDocuments",component:function({children:e,...t}){return r().createElement(r().Fragment,null,r().isValidElement(e)?r().cloneElement(e,t):null)},activate:function(e,{dataService:t,instance:n,localAppRegistry:a,globalAppRegistry:r,preferences:i,logger:o,track:s,favoriteQueryStorageAccess:l,recentQueryStorageAccess:c,fieldStoreService:d,connectionInfoRef:u,connectionScopedAppRegistry:p,queryBar:m,collection:g},{on:h,cleanup:f}){const y=La().createActions(["addColumn","cleanCols","closeInsertDocumentDialog","closeBulkUpdateModal","copyToClipboard","documentRemoved","drillDown","elementAdded","elementMarkRemoved","elementRemoved","elementTypeChanged","getPage","insertDocument","insertMany","toggleInsertDocumentView","toggleInsertDocument","openInsertDocumentDialog","openBulkUpdateModal","updateBulkUpdatePreview","runBulkUpdate","openExportFileDialog","openImportFileDialog","pathChanged","refreshDocuments","cancelOperation","removeDocument","removeColumn","renameColumn","replaceDoc","replaceDocument","resetColumns","updateDocument","updateJsonDoc","viewChanged","updateComment","updateMaxDocumentsPerPage"]),b=La().createStore(new Xa({...e,actions:y},{instance:n,dataService:t,localAppRegistry:a,preferences:i,logger:o,track:s,connectionInfoRef:u,favoriteQueryStorage:l?.getStorage(),recentQueryStorage:c?.getStorage(),fieldStoreService:d,connectionScopedAppRegistry:p,queryBar:m,collection:g}));if(h(a,"favorites-open-bulk-update-favorite",(e=>{b.refreshDocuments(),b.openBulkUpdateModal(),b.updateBulkUpdatePreview((0,z.AO)(e.update)||Ya)})),h(n,"change:isWritable",(()=>{b.setState({isWritable:n.isWritable})})),h(n,"change:description",(()=>{b.setState({instanceDescription:n.description})})),h(r,"refresh-data",(()=>{b.refreshDocuments()})),h(r,"import-finished",(({ns:e},{connectionId:t}={})=>{const{id:n}=u.current;n===t&&e===b.state.ns&&b.refreshDocuments()})),h(g,"change:status",((e,t)=>{"ready"===t&&b.collectionStatsFetched(e)})),e.noRefreshOnConfigure||queueMicrotask((()=>{b.refreshDocuments()})),e.query?.update){const t=e.query?.update,n=t?(0,z.AO)(t):void 0;queueMicrotask((()=>{b.openBulkUpdateModal(n)}))}const v=(e=>La().createStore(new za(e)))({actions:y});return b.gridStore=v,{store:b,actions:y,deactivate(){b.cancelOperation(),f()}}}},{dataService:Qn.S1,instance:ar.A$,preferences:l.fx,logger:(0,L.fF)("COMPASS-CRUD-UI"),track:Fn.yL,favoriteQueryStorageAccess:Ye.yS,recentQueryStorageAccess:Ye.HP,fieldStoreService:At.bM,connectionInfoRef:Qn.wj,connectionScopedAppRegistry:Qn.Do,queryBar:Et.hx,collection:ar.KK}),br={name:"Documents",provider:yr,content:Ta,header:({store:{state:{collectionStats:e}}})=>{const{documentCount:t,storageSize:n,avgDocumentSize:i}=(0,a.useMemo)((()=>{const{document_count:t=NaN,storage_size:n=NaN,free_storage_size:a=NaN,avg_document_size:r=NaN}=e??{};return{documentCount:or(t,"number"),storageSize:or(n-a,"bytes"),avgDocumentSize:or(r,"bytes")}}),[e]),o=(0,l.Fg)("enableDbAndCollStats"),s=[`Documents: ${t}`,`Storage Size: ${n}`,`Avg. Size: ${i}`];return r().createElement("div",{"data-testid":"documents-tab-title",className:ir},"Documents",o&&r().createElement(sr,{text:t,details:s}))}}},17565:(e,t,n)=>{n.d(t,{Rs:()=>s,aC:()=>o,nV:()=>l,r2:()=>c,sq:()=>i});var a=n(47799),r=n(21655).URL;function i(e){const t=function(e){const{currentUserId:t,telemetryAnonymousId:n}=e.getPreferences();return t||n}(e),{userCreatedAt:n}=e.getPreferences();if(!t)throw new Error("User not setup.");return{id:t,createdAt:new Date(n)}}function o(e){const{enableGenAIFeatures:t,enableGenAIFeaturesAtlasOrg:n,cloudFeatureRolloutAccess:a}=e;return t&&n&&!!a?.GEN_AI_COMPASS}function s(){return o({enableGenAIFeatures:(0,a.Fg)("enableGenAIFeatures"),enableGenAIFeaturesAtlasOrg:(0,a.Fg)("enableGenAIFeaturesAtlasOrg"),cloudFeatureRolloutAccess:(0,a.Fg)("cloudFeatureRolloutAccess")})}function l(e){if(!e)return{useEnvironmentVariableProxies:!0};try{return JSON.parse(e)}catch{return{proxy:new r(e).href,useEnvironmentVariableProxies:!0}}}function c(e){return JSON.stringify(e)}},20625:(e,t,n)=>{n.d(t,{Fc:()=>l,wb:()=>a.wb,Tv:()=>c,of:()=>d.N,aC:()=>s.aC,fx:()=>a.fx,nV:()=>s.nV,Rs:()=>s.Rs,Fg:()=>a.Fg,gc:()=>a.gc,JG:()=>a.JG,tC:()=>a.tC});var a=n(47799),r=(n(55469),n(95039),n(44142)),i=n(58886),o=n(65738),s=n(17565);class l{_preferences;constructor(e,t){this._preferences=new i.p({logger:(0,r.ZQ)(),preferencesStorage:new o._(e),globalPreferences:t})}savePreferences(e){return this._preferences.savePreferences(e)}refreshPreferences(){return Promise.resolve(this._preferences.getPreferences())}getPreferences(){return this._preferences.getPreferences()}getConfigurableUserPreferences(){return Promise.resolve(this._preferences.getConfigurableUserPreferences())}getPreferenceStates(){return Promise.resolve(this._preferences.getPreferenceStates())}onPreferenceValueChanged(e,t){return this._preferences.onPreferencesChanged((n=>{if(Object.keys(n).includes(e))return t(n[e])}))}createSandbox(){return Promise.resolve(new l(this.getPreferences()))}getPreferencesUser(){return(0,s.sq)(this)}}function c(e,t){const n=e.getPreferences().maxTimeMS;return"number"==typeof t&&"number"==typeof n?0===t?n:0===n?t:Math.min(t,n):"number"==typeof n?n:t}var d=n(56128);n(73190)},20724:(e,t,n)=>{n.d(t,{K:()=>Ft,N:()=>tn});var a=n(96652),r=n.n(a),i=n(55712),o=n(19125),s=n(26250),l=n(13353),c=n(12738),d=n(44142),u=n(39059),p=n(17855);const m="initial",g="analyzing",h="complete";n(95039);var f=n(67092);const y=5,b=300,v=".",x=3,E=1,C=50;class w extends Error{constructor(e){super(e),this.name="ProcessSchemaUnsupportedStateError"}}class I extends Error{constructor(e){super(e),this.name="ProcessSchemaValidationError"}}function S(e){if(null==e)return e;if("[object Date]"===Object.prototype.toString.call(e))return e;switch((0,f.TB)(e)){case"ObjectId":case"BSONSymbol":return e.toString();case"Binary":throw new w("Binary data encountered in sample value conversion. Binary fields should be excluded from sample value processing.");case"BSONRegExp":return e.pattern;case"Code":return e.code;case"Timestamp":case"Long":return e.toNumber();case"MaxKey":return"MaxKey";case"MinKey":return"MinKey";case"Decimal128":return parseFloat(e.toString())}return e&&"object"==typeof e&&"valueOf"in e?e.valueOf():"string"==typeof e&&e.length>b?e.substring(0,b)+"...":e}function A(e){return"Null"===e.name||"Undefined"===e.name}function k(e){return"Array"===e.name}function D(e){return"Document"===e.name}function N(e,t,n,a){if(!e.types||0===e.types.length)return;const r=T(e.types);if(r){if(e.name.includes(v))throw new w(`Feature is unsupported for field names that contain a '${v}'; field name: '${e.name}'`);if(e.name.endsWith("[]"))throw new w(`Feature is unsupported for field names that end with '[]'; field name: '${e.name}'`);M(r,t?`${t}.${e.name}`:e.name,n,Math.round(100*e.probability)/100,a)}}function M(e,t,n,a,r){if(!A(e))if(k(e)){const i=T(e.types||[]);if(!i)return;const o=`${t}[]`,s=function(e){const t=e.averageLength??x;return Math.max(E,Math.min(C,Math.round(t)))}(e);r[o]=s,M(i,o,n,a,r)}else if(D(e)){if(e.fields)for(const a of e.fields)N(a,t,n,r)}else if(function(e){return!A(e)&&!k(e)&&!D(e)}(e)){const r={type:e.name,probability:a};"Binary"!==e.name&&(r.sampleValues=e.values.slice(0,y).map(S)),n[t]=r}}function T(e){return e&&0!==e.length&&e.filter((e=>!A(e))).sort(((e,t)=>(t.probability||0)-(e.probability||0)))[0]||null}function P(e){const t=e.split(v);for(const n of t){if(""===n)throw new I(`invalid fieldPath '${e}': field parts cannot be empty`);if(""===n.replaceAll("[]",""))throw new I(`invalid fieldPath '${e}': field parts must have characters other than '[]'`)}}const L="SCHEMA_CONFIRMATION",O="PREVIEW_AND_DOC_COUNT",R="SCRIPT_RESULT",H={[L]:"Confirm",[O]:"Generate Script",[R]:"Done"},F={[L]:O,[O]:R,[R]:"finish"},W="https://v10.fakerjs.dev/api/",j=1e3,B=1e5;var z=n(75225);const _=2,$=10,Y=1e3,K=3,G=1e4;function V(e,t=0){if(t>K)return!1;if(0===e.length)return!0;if(0===t&&e.length>_)return!1;if(t>0&&e.length>$)return!1;for(const n of e){if(null==n)return!1;if("boolean"!=typeof n)if("number"==typeof n){if(!Number.isFinite(n)||Math.abs(n)>G)return!1}else if("string"==typeof n){if(n.length>Y)return!1}else if(Array.isArray(n)){if(!V(n,t+1))return!1}else{if("object"!=typeof n||null===n||!("json"in n)||"string"!=typeof n.json)return!1;try{const e=JSON.parse(n.json);if(!V(Object.values(e),t+1))return!1}catch{return!1}}}return!0}function U(e,t,n){const a=function(e){const t=e.split(".");if(2!==t.length)return null;const[n,a]=t;return{moduleName:n,methodName:a,fakerModule:z.a[n]}}(e);if(!a)return{isValid:!1,fakerArgs:[]};const{moduleName:r,methodName:i,fakerModule:o}=a;return function(e,t){return"helpers"!==e||"arrayElement"===t||"arrayElements"===t}(r,i)&&function(e,t){return null!=e&&"object"==typeof e&&"function"==typeof e[t]}(o,i)?function(e,t,n,a){if(n.length>0&&V(n))try{const t=function(e){return e.map((e=>"object"==typeof e&&null!==e&&"json"in e?JSON.parse(e.json):e))}(n);return e(...t),{isValid:!0,fakerArgs:n}}catch{}try{return e(),{isValid:!0,fakerArgs:[]}}catch(e){return a.log.warn((0,d.oW)(1001000377),"Collection","Invalid faker method",{error:e,fakerMethod:t,fakerArgs:n}),{isValid:!1,fakerArgs:[]}}}(o[i],e,t,n):{isValid:!1,fakerArgs:[]}}function q(e){if(!e)return{isValid:!1,errorMessage:"Document count is required"};const t=e.trim(),n=Number(e);return t?isNaN(n)?{isValid:!1,errorMessage:"Please enter a valid number"}:e.includes(".")?{isValid:!1,errorMessage:"Please enter a whole number"}:n<1||n>B?{isValid:!1,errorMessage:"Document count must be between 1 and 100000"}:{isValid:!0,parsedValue:n}:{isValid:!1,errorMessage:"Document count is required"}}var Z=n(70724);const J=3;function Q(e){const t=[];let n="";for(let a=0;a<e.length;a++){const r=e[a];if("."===r){if(n)t.push(n),n="";else if(!(t.length>0&&"[]"===t[t.length-1]))throw new Error(`Invalid field path "${e}": empty field name before dot`)}else if("["===r&&"]"===e[a+1]){const i=a+2>=e.length,o=a+2<e.length&&"."===e[a+2],s=a+2<e.length&&"["===e[a+2];i||o||s?(n&&(t.push(n),n=""),t.push("[]"),a++):n+=r}else n+=r}if(n&&t.push(n),0===t.length)throw new Error(`Invalid field path "${e}": no valid field names found`);return t}function X(e){const t={};for(const[n,a]of Object.entries(e))ee(t,Q(n),a);return t}function ee(e,t,n){if(0===t.length)throw new Error("Cannot insert field mapping: empty path parts array");if(1===t.length){const a=t[0];if("[]"===a)throw new Error('Invalid field path: array notation "[]" cannot be used without a field name');return void(e[a]=n)}const[a,r,...i]=t;if("[]"===r){e[a]&&"object"==typeof e[a]&&"type"in e[a]&&"array"===e[a].type||(e[a]={type:"array",elementType:{}});const t=e[a];if(0===i.length)t.elementType=n;else if("[]"===i[0]){let e=t,a=0;for(;a<i.length&&"[]"===i[a];)e.elementType={type:"array",elementType:{}},e=e.elementType,a++;a<i.length?(("object"!=typeof e.elementType||"mongoType"in e.elementType||"type"in e.elementType)&&(e.elementType={}),ee(e.elementType,i.slice(a),n)):e.elementType=n}else("object"!=typeof t.elementType||"mongoType"in t.elementType||"type"in t.elementType)&&(t.elementType={}),ee(t.elementType,i,n)}else(!e[a]||"object"!=typeof e[a]||"type"in e[a]||"mongoType"in e[a])&&(e[a]={}),ee(e[a],[r,...i],n)}function te(e,t={},n=""){const a=[];for(const[r,i]of Object.entries(e))if("mongoType"in i){const e=i,t=re(e);let n=1;void 0!==e.probability&&"number"==typeof e.probability&&e.probability>=0&&e.probability<=1&&(n=e.probability),n<1?a.push(`...(Math.random() < ${n} ? { ${ne(r)}: ${t} } : {})`):a.push(`${ne(r)}: ${t}`)}else if("type"in i&&"array"===i.type){const e=ae(i,r,t,n?`${n}.${r}[]`:`${r}[]`);a.push(`${ne(r)}: ${e}`)}else{const e=te(i,t,n?`${n}.${r}`:r);a.push(`${ne(r)}: ${e}`)}return 0===a.length?"{}":`{${a.join(",")}}`}function ne(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function ae(e,t="",n={},a=""){const r=e.elementType;let i=J;return a&&void 0!==n[a]&&(i=n[a]),"mongoType"in r?`Array.from({length: ${i}}, () => ${re(r)})`:"type"in r&&"array"===r.type?`Array.from({length: ${i}}, () => ${ae(r,t,n,a+"[]")})`:`Array.from({length: ${i}}, () => (${te(r,n,a)}))`}function re(e){const t=e.fakerMethod===me?ie(e.mongoType):e.fakerMethod;return"database.mongodbObjectId"===t?"new ObjectId()":`faker.${t}(${function(e){const t=[];for(let n=0;n<e.length;n++){const a=e[n];if("string"==typeof a)t.push(JSON.stringify(a));else if("number"==typeof a){if(!Number.isFinite(a))throw new Error(`Invalid number argument at index ${n}: must be a finite number`);t.push(`${a}`)}else if("boolean"==typeof a)t.push(`${a}`);else{if("object"!=typeof a||null===a||!("json"in a))throw new Error(`Invalid argument type at index ${n}: expected string, number, boolean, or {json: string}`);{const e=a;t.push(e.json)}}}return t.join(", ")}(e.fakerArgs)})`}function ie(e){switch(e){case"String":case"RegExp":case"Symbol":default:return"lorem.word";case"Number":case"Int32":case"Long":case"MinKey":case"MaxKey":return"number.int";case"Decimal128":return"number.float";case"Date":case"Timestamp":return"date.recent";case"ObjectId":case"DBRef":return"database.mongodbObjectId";case"Boolean":return"datatype.boolean";case"Binary":return"string.hexadecimal";case"Code":return"lorem.sentence"}}function oe(e,t={}){return le(X(e),t)}function se(e,t,n){try{if(!("mongoType"in e))return"type"in e&&"array"===e.type?function(e,t,n){const a=e.elementType;let r=J;void 0!==t[n]&&(r=t[n]);const i=[];for(let e=0;e<r;e++)i.push(se(a,t,n));return i}(e,t,`${n}[]`):le(e,t,n);{const t=e;let n=1;if("number"==typeof t.probability&&t.probability>=0&&t.probability<=1&&(n=t.probability),n>=1||Math.random()<n)return function(e){const t=e.fakerMethod===me?ie(e.mongoType):e.fakerMethod;try{const n=t.split(".");let a=z.a;for(const e of n)if(a=a[e],!a)throw new Error(`Faker method not found: ${t}`);const r=function(e){const t=[];for(const n of e)if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)t.push(n);else if("object"==typeof n&&null!==n&&"json"in n)try{const e=n;t.push(JSON.parse(e.json))}catch{continue}return t}(e.fakerArgs);return a.apply(z.a,r)}catch{return}}(t)}}catch{}}function le(e,t={},n=""){const a={};for(const[r,i]of Object.entries(e)){const e=se(i,t,n?`${n}.${r}`:r);void 0!==e&&(a[r]=e)}return a}var ce=n(15088).process;const de="No documents found in the collection to analyze.";class ue extends Error{constructor(){super(de),this.name="EmptyCollectionError"}}function pe(e,t){return e.type===t}const me="Unrecognized";function ge(e){if(e instanceof w)return{errorType:"unsupportedState",errorMessage:e.message};if(e instanceof ue)return{errorType:"empty",errorMessage:e.message};let t="general";return 50===e.code&&(t="timeout"),{errorType:t,errorMessage:e.message||"Unknown error"}}const he="compass-collection/CollectionMetadataFetched",fe="compass-collection/SchemaAnalysisStarted",ye="compass-collection/SchemaAnalysisFinished",be="compass-collection/SchemaAnalysisFailed",ve="compass-collection/SchemaAnalysisCanceled",xe="compass-collection/MockDataGeneratorModalOpened",Ee="compass-collection/MockDataGeneratorModalClosed",Ce="compass-collection/MockDataGeneratorNextButtonClicked",we="compass-collection/MockDataGeneratorPreviousButtonClicked",Ie="compass-collection/MockDataGeneratorDocumentCountChanged",Se="compass-collection/FakerMappingGenerationStarted",Ae="compass-collection/FakerMappingGenerationCompleted",ke="compass-collection/FakerMappingGenerationFailed",De=e=>(t,n,{workspaces:a})=>{a.openCollectionWorkspaceSubtab(n().workspaceTabId,e)},Ne=()=>async(e,t,{dataService:n,preferences:a,logger:r,schemaAnalysisAbortControllerRef:i,collection:o})=>{const{schemaAnalysis:l,namespace:m}=t();if(l.status===g)return void r.debug("Schema analysis is already in progress, skipping new analysis.");const h=new AbortController;i.current=h;try{r.debug("Schema analysis started."),e({type:fe});const t={size:100},i={maxTimeMS:a.getPreferences().maxTimeMS},l=await n.sample(m,t,i,{fallbackReadPreference:"secondaryPreferred",abortSignal:h.signal});if(h.signal.aborted)return void r.debug("Schema analysis was aborted during sampling");if(0===l.length)return r.debug(de),void e({type:be,error:new ue});const c=await(0,s.Dy)(l);if(h.signal.aborted)return void r.debug("Schema analysis was aborted during document analysis");const d=await c.getInternalSchema();d.fields=d.fields.filter((({path:e})=>!(0,u.v6)(e[0])));const g=function(e){const t=Object.create(null),n={};if(!e.fields)return{fieldInfo:t,arrayLengthMap:n};for(const a of e.fields)N(a,"",t,n);for(const e of Object.keys(t))P(e);return{fieldInfo:t,arrayLengthMap:n}}(d),f=await async function(e){let t=0,n=0;return await async function e(a,r){if(t++,1e3===t&&(t=0,await(async()=>new Promise((e=>setTimeout(e))))()),a&&0!==a.length){n=Math.max(r,n);for(const t of a)if("Document"===t.bsonType)await e(t.fields,r+1);else if("Array"===t.bsonType||t.types){const n="Array"===t.bsonType?1:0;await e(t.types,r+n)}}}(e.fields,1),n}(d),{database:y,collection:b}=(0,p.Ay)(m),v=await n.collectionInfo(y,b),x={maxNestingDepth:f,validationRules:v?.validation?.validator??null,avgDocumentSize:o.avg_document_size};if(h.signal.aborted)return void r.debug("Schema analysis was aborted before completion");e({type:ye,processedSchema:g.fieldInfo,arrayLengthMap:g.arrayLengthMap,sampleDocument:l[0],schemaMetadata:x})}catch(t){if((0,c.nc)(t)||h.signal.aborted)return r.debug("Schema analysis was aborted"),void e({type:ve});r.log.error((0,d.oW)(1001000363),"Collection","Schema analysis failed",{namespace:m,error:t.message}),e({type:be,error:t})}finally{i.current=void 0}},Me=(e={workspaceTabId:"",namespace:"",metadata:null,schemaAnalysis:{status:m},mockDataGenerator:{isModalOpen:!1,currentStep:L,documentCount:j.toString()},fakerSchemaGeneration:{status:"idle"}},t)=>{if(pe(t,he))return{...e,metadata:t.metadata};if(pe(t,"compass-collection/SchemaAnalysisReset"))return{...e,schemaAnalysis:{status:m}};if(pe(t,fe))return{...e,schemaAnalysis:{status:g}};if(pe(t,ye))return{...e,schemaAnalysis:{status:h,processedSchema:t.processedSchema,arrayLengthMap:t.arrayLengthMap,sampleDocument:t.sampleDocument,schemaMetadata:t.schemaMetadata}};if(pe(t,be))return{...e,schemaAnalysis:{status:"error",error:ge(t.error)}};if(pe(t,ve))return{...e,schemaAnalysis:{status:m}};if(pe(t,xe))return{...e,mockDataGenerator:{...e.mockDataGenerator,isModalOpen:!0,currentStep:L,documentCount:j.toString()}};if(pe(t,Ee))return{...e,mockDataGenerator:{...e.mockDataGenerator,isModalOpen:!1},fakerSchemaGeneration:{status:"idle"}};if(pe(t,Ce)){const t=e.mockDataGenerator.currentStep;let n;return n=t===O?R:t,{...e,mockDataGenerator:{...e.mockDataGenerator,currentStep:n}}}if(pe(t,we)){const t=e.mockDataGenerator.currentStep;let n;switch(t){case L:n=L;break;case O:return{...e,fakerSchemaGeneration:{status:"idle"},mockDataGenerator:{...e.mockDataGenerator,currentStep:L}};case R:n=O;break;default:n=t}return{...e,mockDataGenerator:{...e.mockDataGenerator,currentStep:n}}}return pe(t,Ie)?{...e,mockDataGenerator:{...e.mockDataGenerator,documentCount:t.documentCount}}:pe(t,Se)?e.mockDataGenerator.currentStep!==L||"in-progress"===e.fakerSchemaGeneration.status||"completed"===e.fakerSchemaGeneration.status?e:{...e,fakerSchemaGeneration:{status:"in-progress",requestId:t.requestId}}:pe(t,Ae)?"in-progress"!==e.fakerSchemaGeneration.status?e:{...e,mockDataGenerator:{...e.mockDataGenerator,currentStep:O},fakerSchemaGeneration:{status:"completed",fakerSchema:t.fakerSchema,requestId:t.requestId}}:pe(t,ke)?"in-progress"!==e.fakerSchemaGeneration.status?e:{...e,fakerSchemaGeneration:{status:"error",error:t.error,requestId:t.requestId},mockDataGenerator:{...e.mockDataGenerator,currentStep:L}}:e};var Te=n(51295),Pe=(n(21261),n(92879),n(31977),n(49743),n(9656),n(72673),n(35467),n(94476),n(64971),n(24330),n(83478),n(65166),n(1256),n(61038),n(73035),n(23855),n(20625)),Le=n(60783),Oe=n(45363),Re=n(69692),He=n(28508),Fe=n(70002);const We=(0,Te.AHW)({display:"flex",alignItems:"center",overflow:"hidden",gap:Te.YKD[200]}),je=({namespace:e,isReadonly:t,editViewName:n,sourceName:a,sourcePipeline:i})=>{const o=(0,Le.qm)(),{id:s,atlasMetadata:l}=o,{openCollectionWorkspace:c,openEditViewWorkspace:d,openShellWorkspace:u}=(0,Oe.$L)(),{readWrite:m,enableShell:g}=(0,Pe.gc)(["readWrite","enableShell"]),h=(0,He.Jr)(),{database:f,collection:y}=(0,p.Ay)(e),b=t&&a&&!n&&!m;return r().createElement("div",{className:We,"data-testid":"collection-header-actions"},g&&r().createElement(Te.$nd,{size:"small","data-testid":"collection-header-open-shell-button",onClick:()=>{u(s,{initialEvaluate:`use ${f}`,initialInput:`db[${(0,Re.Zt)(y,!0)}].find()`}),h("Open Shell",{entrypoint:"collection"},o)},leftGlyph:r().createElement(Te.Int,{glyph:"Shell"})},"Open MongoDB shell"),l&&r().createElement(Te.$nd,{"data-testid":"collection-header-view-monitoring",size:Te.MpK.Small,href:(0,Fe.k4)(l),target:"_blank",rel:"noopener noreferrer",leftGlyph:r().createElement(Te.Int,{glyph:"TimeSeries"})},"View monitoring"),l&&r().createElement(Te.$nd,{"data-testid":"collection-header-visualize-your-data",size:Te.MpK.Small,href:(0,Fe.r0)(l,e),target:"_self",rel:"noopener noreferrer",leftGlyph:r().createElement(Te.Int,{glyph:"Charts"})},"Visualize Your Data"),b&&r().createElement(Te.$nd,{"data-testid":"collection-header-actions-edit-button",size:Te.MpK.Small,onClick:()=>{a&&i&&d(s,e,{sourceName:a,sourcePipeline:i})}},r().createElement(Te.Int,{glyph:"Edit"}),"Edit Pipeline"),n&&r().createElement(Te.$nd,{"data-testid":"collection-header-actions-return-to-view-button",size:Te.MpK.Small,onClick:()=>{n&&c(s,n)}},r().createElement(Te.Int,{glyph:"ArrowLeft"}),"Return to View"))},Be=(0,Te.AHW)({whiteSpace:"nowrap"}),ze={readonly:{label:"READ-ONLY",variant:Te.xUU.LightGray},timeseries:{label:r().createElement(r().Fragment,null,r().createElement(Te.Int,{glyph:"TimeSeries",title:"Time-Series Collection"})," TIME-SERIES")},view:{label:r().createElement(r().Fragment,null,r().createElement(Te.Int,{glyph:"Visibility",title:"View"})," VIEW")},fle:{label:r().createElement(r().Fragment,null,r().createElement(Te.Int,{glyph:"Key",title:"Queryable Encryption",size:"small"})," Queryable Encryption")},clustered:{label:"CLUSTERED"}},_e=({type:e})=>{const{label:t,variant:n}=ze[e];return r().createElement(Te.Exy,{"data-testid":`collection-badge-${e}`,className:Be,variant:n??Te.xUU.DarkGray},t)};var $e=n(96452);function Ye(e){const t=Object.keys(e).sort(((e,t)=>Ke(e)-Ke(t))),n={};for(const a of t){const t=a.split(v);let r=n;for(let n=0;n<t.length;n++){const i=t[n];if(n===t.length-1){r[i]=e[a].type;break}"object"==typeof r[i]&&null!==r[i]||(r[i]={}),r=r[i]}}return n}function Ke(e){return e.split(v).length-1}const Ge=(0,Te.AHW)({backgroundColor:Te.MFm.gray.light3,border:`1px solid ${Te.MFm.gray.light2}`,borderRadius:Te.YKD[400],minHeight:"100px",maxHeight:"300px",overflow:"auto"}),Ve=(0,Te.AHW)({backgroundColor:Te.MFm.gray.dark3,border:`1px solid ${Te.MFm.gray.dark2}`,borderRadius:Te.YKD[400]}),Ue=(0,Te.AHW)({padding:`${Te.YKD[400]}px ${Te.YKD[900]}px`}),qe=(0,Te.AHW)({marginBottom:Te.YKD[400]}),Ze=(0,Te.AHW)({marginTop:Te.YKD[400]}),Je=(0,Te.AHW)({display:"flex",justifyContent:"space-between",alignItems:"flex-end",gap:Te.YKD[300]}),Qe=(0,Te.AHW)({flex:1}),Xe=(0,Te.AHW)({display:"flex",justifyContent:"center",alignItems:"center"}),et=(0,o.Ng)((e=>({schemaAnalysis:e.schemaAnalysis,fakerSchemaGenerationStatus:e.fakerSchemaGeneration.status})),{})((({schemaAnalysis:e,fakerSchemaGenerationStatus:t})=>{const n=(0,Pe.Fg)("enableGenAISampleDocumentPassing"),i=(0,Te.D27)(),o=(0,Le.qm)(),[s,l]=(0,a.useState)(!1),c=o.atlasMetadata?.projectId,d=c?`${window.location.origin}/v2/${c}#/settings/groupSettings`:null,p=!n&&c&&!s;return"in-progress"===t?r().createElement("div",{"data-testid":"raw-schema-confirmation",className:Xe},r().createElement(Te.iyS,{"data-testid":"raw-schema-confirmation-loader",progressText:"Generating mock data mappings..."})):r().createElement("div",{"data-testid":"raw-schema-confirmation"},"complete"===e.status?r().createElement(r().Fragment,null,r().createElement(Te.nBu,{className:qe},"We'll use the identified schema to generate a mock data script for your collection. You can customize the script and its"," ",r().createElement(Te.N_E,{href:W,target:"_blank",hideExternalIcon:!0},"Faker functions")," ","before running it and/or reuse it for your other clusters and collections."),r().createElement("div",{className:(0,Te.cx)(Ge,i&&Ve)},r().createElement(Te.gD8.yo,{className:Ue,editable:!1,value:new u.Ay(n?e.sampleDocument:Ye(e.processedSchema))})),p&&r().createElement(Te.lZ$,{variant:Te.uAY.Info,className:Ze,dismissible:!0,onClose:()=>l(!0),"data-testid":"sample-values-banner"},r().createElement("div",{className:Je},r().createElement("div",{className:Qe},r().createElement(Te.nBu,{weight:"medium"},"Enable Sending Sample Field Values"),r().createElement(Te.nBu,null,"To improve mock data quality, Project Owners can enable sending sample field values to the AI model. Refresh Data Explorer for changes to take effect.")),r().createElement(Te.$nd,{size:"xsmall",onClick:()=>{d&&window.open(d,"_blank","noopener noreferrer")},"data-testid":"sample-values-banner-settings-button"},"Project Settings"))),"error"===t&&r().createElement(Te.lZ$,{variant:Te.uAY.Warning,className:Ze,"data-testid":"error-banner"},"LLM Request failed. Please confirm again.")):r().createElement(Te.nBu,null,"We are analyzing your collection."))})),tt=(0,Te.AHW)({display:"flex",flexDirection:"column",gap:Te.YKD[600]}),nt=(0,Te.AHW)({fontWeight:600,fontSize:"16px",lineHeight:"28px"}),at=(0,Te.AHW)({display:"flex",flexDirection:"column",gap:Te.YKD[200]}),rt=(0,Te.AHW)({fontStyle:"italic"}),it=(0,Te.AHW)({display:"flex",flexDirection:"row",gap:Te.YKD[600],marginTop:Te.YKD[200]}),ot=(0,Te.AHW)({width:"325px"}),st=(0,Te.AHW)({fontSize:"13px",marginTop:Te.YKD[100]}),lt=(0,Te.AHW)({display:"flex",flexDirection:"column",gap:Te.YKD[200]}),ct=(0,Te.AHW)({display:"flex",flexDirection:"column",gap:Te.YKD[300]}),dt=(0,Te.AHW)({border:"1px solid #E8EDEB",borderRadius:"6px",padding:Te.YKD[200]}),ut={onDocumentCountChanged:e=>({type:Ie,documentCount:e})},pt=(0,o.Ng)((e=>{const{fakerSchemaGeneration:t,schemaAnalysis:n,mockDataGenerator:a}=e;return{documentCount:a.documentCount,fakerSchema:"completed"===t.status?t.fakerSchema:null,avgDocumentSize:n?.status===h?n.schemaMetadata.avgDocumentSize:void 0,arrayLengthMap:n?.status===h?n.arrayLengthMap:{}}}),ut)((({documentCount:e,fakerSchema:t,avgDocumentSize:n,arrayLengthMap:i,onDocumentCountChanged:o})=>{const s=(0,He.Jr)(),l=(0,a.useRef)(e),c=q(e),d=(0,a.useMemo)((()=>c.isValid&&n&&c.parsedValue?(e=>{const t=e<=1e3?0:1;return(0,Te.V0R)(e,!0,t)})(n*c.parsedValue):"Not available"),[c,n]),p=(0,a.useMemo)((()=>c.isValid?{state:"none"}:{state:"error",message:c.errorMessage}),[c.isValid,c.errorMessage]),m=(0,a.useMemo)((()=>{if(!t)return[];const e=[];for(let n=0;n<3;n++){const n=oe(t,i),a=new u.Ay(n);a.expand(),e.push(a)}return e}),[t,i]);return r().createElement("div",{className:tt,"data-testid":"preview-and-doc-count-screen"},r().createElement("section",{className:at},r().createElement(Te.nBu,{className:nt},"Specify Number of Documents to Generate"),r().createElement(Te.VYo,{className:rt},"Indicate the amount of documents you want to generate below."),r().createElement("div",{className:it},r().createElement(Te.ksK,{id:"document-count-input",className:ot,label:"Documents to generate in current collection",type:"number",value:e,onChange:e=>{o(e.target.value)},onFocus:()=>{l.current=e},onBlur:()=>{c.isValid&&void 0!==c.parsedValue&&e!==l.current&&s("Mock Data Document Count Changed",{document_count:c.parsedValue})},min:1,max:B,state:p.state,errorMessage:"error"===p.state?p.message:void 0,"data-testid":"document-count-input"}),r().createElement("div",null,r().createElement(Te.nBu,{weight:"medium"},"Estimated Disk Size"),r().createElement(Te.nBu,{className:st,"data-testid":"estimated-disk-size"},d)))),r().createElement("section",{className:lt},r().createElement(Te.nBu,{className:nt},"Preview Mock Data"),r().createElement(Te.nBu,null,"Below are examples of documents that will be generated when you run your script. If you'd like to make any changes to the script (for ex. what"," ",r().createElement(Te.N_E,{href:W,target:"_blank"},"faker functions")," ","are being used to generate the documents) you can do so in the next step."),m.length>0?r().createElement("div",{className:ct,"data-testid":"preview-documents"},m.map(((e,t)=>r().createElement("div",{key:t,className:dt},r().createElement(Te.gD8.yo,{value:e}))))):r().createElement(Te.lZ$,{variant:Te.uAY.Warning},"No faker schema available. Please go back and confirm your schema.")))}));var mt=n(46729);const gt=(0,Te.AHW)({display:"flex",flexDirection:"column",gap:Te.YKD[400]}),ht=(0,Te.AHW)({listStylePosition:"inside",listStyleType:"disc",marginLeft:Te.YKD[200]}),ft=(0,Te.AHW)({marginLeft:Te.YKD[400]}),yt=(0,Te.AHW)({margin:`${Te.YKD[200]}px 0`}),bt=(0,Te.AHW)({padding:`${Te.YKD[400]}px ${Te.YKD[800]}px`,borderRadius:Te.YKD[400]}),vt=(0,Te.AHW)({marginTop:Te.YKD[200]}),xt=(0,Te.AHW)({backgroundColor:Te.MFm.gray.light3}),Et=(0,Te.AHW)({backgroundColor:Te.MFm.gray.dark3}),Ct=(0,Te.AHW)({marginBottom:Te.YKD[300]}),wt=(0,Te.AHW)({maxHeight:"230px",overflowY:"auto"}),It=(0,o.Ng)((e=>{const{fakerSchemaGeneration:t,namespace:n,schemaAnalysis:a,mockDataGenerator:r}=e;return{fakerSchema:"completed"===t.status?t.fakerSchema:null,namespace:n,arrayLengthMap:a?.status===h?a.arrayLengthMap:{},documentCount:r.documentCount}}))((({fakerSchema:e,namespace:t,arrayLengthMap:n,documentCount:i})=>{const o=(0,Te.D27)(),s=(0,Le.qm)(),l=(0,He.Jr)(),c=s?.atlasMetadata?.userConnectionString??"<connection-string>",{database:d,collection:u}=(0,p.Ay)(t),m=(0,a.useMemo)((()=>e?function(e,t){try{const n=te(X(e),t.arrayLengthMap||{}),a=`// Mock Data Generator Script\n// Document count: ${t.documentCount}\n\nconst { faker } = require('@faker-js/faker');\n\n// Database and collection configuration - edit these to target a different location\nconst DB_NAME = ${JSON.stringify(t.databaseName)};\nconst COLL_NAME = ${JSON.stringify(t.collectionName)};\n\n// Connect to database\nuse(DB_NAME);\n\n// Document generation function\nfunction generateDocument() {\n return ${n};\n}\n\nconst BATCH_SIZE = 1000; // Number of documents to insert per batch\nconst TOTAL_DOCUMENTS = ${t.documentCount};\nconst numBatches = Math.ceil(TOTAL_DOCUMENTS / BATCH_SIZE);\n\nconsole.log(\`Starting mock data generation for \${DB_NAME}.\${COLL_NAME}\`);\nconsole.log(\`Total documents to generate: \${TOTAL_DOCUMENTS} documents\`);\nconsole.log(\`Batch size: \${BATCH_SIZE} documents per batch\`);\n\nconst startTime = new Date();\n\nfor (let batchStart = 0; batchStart < TOTAL_DOCUMENTS; batchStart += BATCH_SIZE) {\n const batchEnd = Math.min(batchStart + BATCH_SIZE, TOTAL_DOCUMENTS);\n const batchSize = batchEnd - batchStart;\n\n console.log(\`Generating batch \${Math.floor(batchStart / BATCH_SIZE) + 1} of \${numBatches} (\${batchSize} documents)...\`);\n\n // Generate documents for this batch\n const batchDocuments = [];\n for (let i = 0; i < batchSize; i++) {\n batchDocuments.push(generateDocument());\n }\n\n // Insert the batch\n db.getCollection(COLL_NAME).insertMany(batchDocuments);\n\n console.log(\`Batch inserted successfully.\`);\n}\n\nconst endTime = new Date();\nconst duration = ((endTime - startTime) / 1000).toFixed(2);\n\nconsole.log(\`\\n=== Mock Data Generation Complete ===\`);\nconsole.log(\`Total time: \${duration} seconds\`);\nconsole.log(\`Collection: \${DB_NAME}.\${COLL_NAME}\`);`;return{script:(0,Z.G8)(a,"javascript"),success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}(e,{documentCount:Number(i)||j,databaseName:d,collectionName:u,arrayLengthMap:n}):{success:!1,error:"Faker schema not available"}),[e,i,d,u,n]),g=(0,a.useCallback)((({step:e})=>{l("Mock Data Script Copied",{step:e})}),[l]);return(0,He.ou)((t=>{m.success&&e&&t("Mock Data Script Generated",{field_count:Object.keys(e).length,output_docs_count:Number(i)||j})}),[m.success,e,i]),r().createElement("section",{className:gt},r().createElement(Te.nBu,null,"We've created the following script for your use. The script can be edited to generate mock data for any collection you specify."),!m.success&&r().createElement(Te.lZ$,{variant:"danger"},r().createElement("strong",null,"Script Generation Failed:")," ",m.error,r().createElement("br",null),"Please go back to the start screen to re-submit the collection schema."),r().createElement("section",null,r().createElement(Te.nBu,{as:"h2",baseFontSize:16,weight:"medium"},"Prerequisites"),r().createElement(Te.nBu,{className:vt},"To run the generated script, you must:"),r().createElement("ul",{className:ht},r().createElement("li",null,"Install"," ",r().createElement(Te.N_E,{href:"https://www.mongodb.com/docs/mongodb-shell/install/"},"mongosh")," ","(2.5 or later)"),r().createElement("li",null,"Install"," ",r().createElement(Te.N_E,{href:"https://fakerjs.dev/guide/#installation"},"faker.js"),r().createElement(Te.awP,{className:ft,onCopy:()=>g({step:"install fakerjs"})},"npm install @faker-js/faker@10")))),r().createElement("section",null,r().createElement(Te.nBu,{as:"h2",baseFontSize:16,weight:"medium"},"1. Create a .js file with the following script"),r().createElement(Te.nBu,{className:yt},"In the directory that you created, create a file named"," ",r().createElement("strong",null,"mockdatascript.js")," (or any name you'd like). Change the DB_NAME and COLL_NAME in the below script to any database or collection you'd like to add mock data to."),r().createElement(Te.CyN,{copyButtonAppearance:m.success?"hover":"persist",language:Te.TMK.JavaScript,className:wt,onCopy:()=>g({step:"create js file"})},m.success?m.script:"// Script generation failed.")),r().createElement("section",null,r().createElement(Te.nBu,{as:"h2",baseFontSize:16,weight:"medium"},"2. Run the script with ",r().createElement(Te.R0E,null,"mongosh")),r().createElement(Te.nBu,{className:yt},"In the same working directory run the command below. Please"," ",r().createElement("strong",null,"paste in your username and password")," where there are placeholders."," ",r().createElement("em",null,"Note that this will add data to your cluster and will not be reversible.")),r().createElement(Te.CyN,{language:Te.TMK.Bash,onCopy:()=>g({step:"mongosh script"})},(e=>`\nmongosh "${(0,mt.J0)(e)}" \\\n --username <your-username> \\\n --password "<your-password>" \\\n mockdatascript.js\n`)(c))),r().createElement("section",{className:(0,Te.cx)(bt,o?Et:xt)},r().createElement(Te.bz9,{className:Ct},"Resources"),r().createElement("ul",null,r().createElement("li",null,r().createElement(Te.N_E,{href:"https://www.mongodb.com/docs/atlas/synthetic-data/"},"Generating Synthetic Data with MongoDB")),r().createElement("li",null,r().createElement(Te.N_E,{href:"https://www.mongodb.com/docs/mongodb-shell/"},"Learn About the MongoDB Shell")),s.atlasMetadata&&s.atlasMetadata.projectId&&r().createElement("li",null,r().createElement(Te.N_E,{href:`${window.location.origin}/v2/${s.atlasMetadata.projectId}#/security/database/users`,target:"_blank",rel:"noopener noreferrer"},"Access your Database Users")))))})),St=Te.AHW`
2
+ flex-direction: row;
3
+ justify-content: space-between;
4
+ `,At=Te.AHW`
5
+ display: flex;
6
+ gap: ${Te.YKD[200]}px;
7
+ flex-direction: row;
8
+ `,kt=(0,Te.AHW)({marginTop:Te.YKD[200],marginBottom:Te.YKD[400]}),Dt=(0,o.Ng)((e=>({isOpen:e.mockDataGenerator.isModalOpen,currentStep:e.mockDataGenerator.currentStep,namespace:e.namespace,fakerSchemaGenerationStatus:e.fakerSchemaGeneration?.status??"idle",documentCount:e.mockDataGenerator.documentCount})),{onClose:()=>(e,t,{fakerSchemaGenerationAbortControllerRef:n})=>{n.current?.abort(),e({type:Ee})},onNextStep:()=>({type:Ce}),onConfirmSchema:()=>async(e,t,{logger:n,atlasAiService:a,preferences:r,connectionInfoRef:i,fakerSchemaGenerationAbortControllerRef:o})=>{const{schemaAnalysis:s,fakerSchemaGeneration:u,namespace:m}=t();if(s.status!==h)return void n.log.warn((0,d.oW)(1001000305),"Collection","Cannot call `generateFakeMappings` unless schema analysis is complete");if("in-progress"===u.status)return void n.debug("Faker mapping generation is already in progress, skipping new generation.");const g=(new l.UUID).toString(),f=r.getPreferences().enableGenAISampleDocumentPassing;try{n.debug("Generating faker mappings");const{database:t,collection:r}=(0,p.Ay)(m);e({type:Se,requestId:g}),o.current?.abort(),o.current=new AbortController;const l=o.current.signal,c={databaseName:t,collectionName:r,schema:s.processedSchema,validationRules:s.schemaMetadata.validationRules,includeSampleValues:f,requestId:g,signal:l},u=function(e,t){const n={};for(const a of e){const{fieldPath:e,...r}=a;n[e]={...r,mongoType:t[e]?.type}}return n}((await a.getMockDataSchema(c,i.current)).fields,s.processedSchema),h=((e,t,n)=>{const a={};for(const r of Object.keys(e))if(t[r]){const i={...t[r],probability:e[r].probability},{isValid:o,fakerArgs:s}=U(i.fakerMethod,i.fakerArgs,n);o?a[r]={...i,fakerArgs:s}:(n.log.warn((0,d.oW)(1001000372),"Collection","Invalid faker method",{fakerMethod:i.fakerMethod}),a[r]={mongoType:i.mongoType,fakerMethod:ie(i.mongoType),fakerArgs:[],probability:i.probability})}else a[r]={mongoType:e[r].type,fakerMethod:ie(e[r].type),fakerArgs:[],probability:e[r].probability};return a._id&&(a._id={mongoType:"ObjectId",fakerMethod:"database.mongodbObjectId",fakerArgs:[],probability:a._id.probability??1}),a})(s.processedSchema,u,n);o.current=void 0,e({type:Ae,fakerSchema:h,requestId:g})}catch(t){if((0,c.nc)(t))return;const a=t instanceof Error?t.stack:String(t);n.log.error((0,d.oW)(1001000312),"Collection","Failed to generate faker.js mappings",{message:a,namespace:m}),e({type:ke,error:"faker mapping request failed",requestId:g})}},onPreviousStep:()=>(e,t,{fakerSchemaGenerationAbortControllerRef:n})=>{n.current?.abort(),e({type:we})}})((({isOpen:e,onClose:t,currentStep:n,onNextStep:i,onConfirmSchema:o,onPreviousStep:s,namespace:l,fakerSchemaGenerationStatus:c,documentCount:d})=>{const u=(0,He.Jr)(),p=(0,Pe.Rs)(),m=(0,Pe.Fg)("enableGenAISampleDocumentPassing"),g=(0,a.useMemo)((()=>{switch(n){case L:return r().createElement(et,null);case O:return r().createElement(pt,null);case R:return r().createElement(It,null)}}),[n]);(0,He.ou)((t=>{e&&t("Mock Data Generator Screen Viewed",{screen:n})}),[n,e]);const h=n===L&&"in-progress"===c||n===O&&!q(d).isValid,f=(0,a.useCallback)((()=>{u("Mock Data Generator Screen Proceeded",{from_screen:n,to_screen:F[n]}),n===R?t():n===L?o():i()}),[n,o,i,t,u]),y=n!==R,b=(0,a.useCallback)((()=>{u("Mock Data Generator Dismissed",{screen:n,gen_ai_features_enabled:p,send_sample_values_enabled:m}),t()}),[n,u,t,p,m]);return r().createElement(Te.aFV,{size:"large",open:e,setOpen:e=>{e||b()},"data-testid":"generate-mock-data-modal"},r().createElement(Te.rQ0,{title:"Generate Mock Data Script"}),r().createElement(Te.cwr,null,y&&r().createElement(Te.nBu,{className:kt},l),r().createElement("div",{"data-testid":`generate-mock-data-step-${n}`},g)),r().createElement(Te.jlY,{className:St},r().createElement(Te.$nd,{onClick:s,disabled:n===L},"Back"),r().createElement("div",{className:At},r().createElement(Te.$nd,{onClick:b},"Cancel"),r().createElement(Te.$nd,{variant:Te.AkO.Primary,onClick:f,"data-testid":"next-step-button",disabled:h},H[n]))))})),Nt=(0,Te.AHW)({padding:Te.YKD[400],paddingTop:Te.YKD[200],paddingBottom:0,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",gap:Te.YKD[200]}),Mt=(0,Te.AHW)({paddingTop:Te.YKD[200],paddingBottom:Te.YKD[200]}),Tt=(0,Te.AHW)({background:Te.MFm.white}),Pt=(0,Te.AHW)({backgroundColor:Te.MFm.black}),Lt=(0,Te.AHW)({flexShrink:0,marginLeft:"auto"}),Ot=({namespace:e,isReadonly:t,isTimeSeries:n,isClustered:i,isFLE:o,isAtlas:s,sourceName:l,editViewName:c,sourcePipeline:d})=>{const u=(0,Te.D27)(),m=(0,Pe.Fg)("showInsights"),{openCollectionWorkspace:g,openCollectionsWorkspace:h,openDatabasesWorkspace:f}=(0,Oe.$L)(),y=(0,Le.qm)(),b=y.id,v=(0,$e.T8)(y),x=(0,a.useMemo)((()=>[{name:v,onClick:()=>f(b)},{name:(0,p.Ay)(e).database,onClick:()=>h(b,(0,p.Ay)(e).database)},l&&{name:(0,p.Ay)(l).collection,onClick:()=>g(b,l)},{name:(0,p.Ay)(e).collection,onClick:()=>g(b,e)},c&&{name:(0,p.Ay)(c).collection,onClick:()=>g(b,c)}].filter(Boolean)),[b,v,e,l,c,h,g,f]),E=m&&d?.length?((e,t)=>{const n=new Set;for(const a of e){if("$match"in a){const e=JSON.stringify(a);/\$(text|regex)\b/.test(e)&&n.add(t?Te.qpO.get("atlas-text-regex-usage-in-view"):Te.qpO.get("non-atlas-text-regex-usage-in-view"))}"$lookup"in a&&n.add(Te.qpO.get("lookup-in-view"))}return Array.from(n)})(d,s):[];return r().createElement("div",{className:(0,Te.cx)(Nt,u?Pt:Tt),"data-testid":"collection-header"},r().createElement(Te.BIu,{className:Mt,items:x}),t&&r().createElement(_e,{type:"readonly"}),n&&r().createElement(_e,{type:"timeseries"}),i&&r().createElement(_e,{type:"clustered"}),o&&r().createElement(_e,{type:"fle"}),t&&l&&r().createElement(_e,{type:"view"}),!!E.length&&r().createElement(Te.gIH,{signals:E}),r().createElement("div",{className:Lt},r().createElement(je,{editViewName:c,isReadonly:t,namespace:e,sourceName:l,sourcePipeline:d})),r().createElement(Dt,null))},Rt={tabs:[],modals:[],queryBar:()=>null},Ht=r().createContext(Rt),Ft=({children:e,...t})=>{const n=(0,Te.nfZ)({...Rt,...t});return r().createElement(Ht.Provider,{value:n},e)};var Wt=n(82162),jt=n(67219);function Bt(e){return!!(e.schemaAnalysis&&e.schemaAnalysis.status===h&&Object.keys(e.schemaAnalysis.processedSchema).length>0)}async function zt(e,t,n){try{const t=await e.getAssignment(He.Cv.mockDataGenerator,!1);return!!t?.assignmentData?.variant}catch(e){return t.debug("Failed to get Mock Data Generator experiment assignment",{experiment:He.Cv.mockDataGenerator,namespace:n,error:e instanceof Error?e.message:String(e)}),!1}}var _t=n(29851),$t=n(62183),Yt=n(21119);const Kt=(0,Te.AHW)({display:"flex",alignItems:"stretch",height:"100%",width:"100%"}),Gt=(0,Te.AHW)({display:"flex",flexDirection:"column",alignItems:"stretch",height:"100%",width:"100%"}),Vt=(0,Te.AHW)({zIndex:100});function Ut({children:e,name:t,type:n}){const{log:a,mongoLogId:i}=(0,d.Ul)("COMPASS-COLLECTION-TAB-UI");return r().createElement(Te.tHk,{key:t,onError:(e,r)=>{a.error(i(1001000107),"Collection Workspace","Rendering collection tab failed",{name:t,type:n,error:e.stack,errorInfo:r})}},e)}const qt=({namespace:e,initialAggregation:t,initialPipeline:n,initialPipelineText:o,initialQuery:s,editViewName:l,collectionMetadata:c,subTab:d,onTabClick:u,hasSchemaAnalysisData:m,analyzedSchemaDepth:g})=>{const h=(0,He.Jr)(),f=(0,Le.jj)(),y=(0,Le.qm)();(0,a.useEffect)((()=>{const e=d?d.toLowerCase().replace(/ /g,"_"):null;e&&h("Screen",{name:e},f.current)}),[d,h,f]);const b=(0,a.useContext)(Ht).modals,{isReadonly:v,isTimeSeries:x,sourceName:E}=c,C=y.atlasMetadata,w=Boolean(C&&!v&&!x&&!E),I=g>7,S=(0,a.useMemo)((()=>w&&m&&!I),[w,m,I]),A={...c,namespace:e,aggregation:t,pipeline:n,pipelineText:o,query:s,editViewName:l,subTab:d,isMockDataGeneratorEligibleAndSchemaReady:S},k=function(e){const t=(0,a.useContext)(Ht).tabs,n=(0,Le.qm)(),i=(0,Pe.Fg)("enableGlobalWrites"),o=(0,Le.SA)(n.id,"globalWrites")&&!e.isReadonly&&!(0,p.Ay)(e.namespace).specialish;return t.filter((e=>!!("GlobalWrites"!==e.name||i&&o))).map((({name:t,content:n,provider:a,header:i,drawer:o})=>(a.useActivate(e),{name:t,content:r().createElement(Ut,{name:t,type:"content"},r().createElement(a,e,r().createElement(n,e))),title:r().createElement(a,e,r().createElement(i,null)),drawer:o?r().createElement(Ut,{name:t,type:"drawer"},r().createElement(a,e,r().createElement(o,e))):null})))}(A),D=k.findIndex((e=>e.name===d));return(0,Yt.ZX)("activeCollectionMetadata",c),(0,Yt.ZX)("activeCollectionSubTab",d),r().createElement("div",{className:Kt,"data-testid":"collection"},r().createElement("div",{className:Gt},r().createElement(Ot,(0,i.A)({editViewName:l},c)),r().createElement(Te.keb,{"data-testid":"collection-tabs","aria-label":"Collection Tabs",activeTabIndex:D,onTabClicked:e=>{u(k[e].name)},tabs:k})),r().createElement("div",{className:Vt},b.map(((e,t)=>r().createElement(e,(0,i.A)({key:t},A))))),k.map((({drawer:e})=>r().createElement(r().Fragment,null,e))))},Zt=(0,o.Ng)((e=>{const t=e.schemaAnalysis?.status===h?e.schemaAnalysis.schemaMetadata.maxNestingDepth:0;return{namespace:e.namespace,collectionMetadata:e.metadata,hasSchemaAnalysisData:Bt(e),analyzedSchemaDepth:t}}),{onTabClick:De})((({collectionMetadata:e,...t})=>{const n=(0,a.useContext)(Ht).queryBar;if(function(e){const t=(0,$t.TH)(),n=(0,$t.xW)(),r=(0,Le.jj)(),i=(0,Pe.Fg)("readOnly"),o=(0,a.useCallback)((()=>{t.emit("menu-share-schema-json")}),[t]),s=(0,a.useCallback)((()=>{e&&n.emit("open-import",{namespace:e.namespace,origin:"menu"},{connectionId:r.current.id},{})}),[e,n,r]),l=(0,a.useCallback)((()=>{e&&n.emit("open-export",{exportFullCollection:!0,namespace:e.namespace,origin:"menu"},{connectionId:r.current.id})}),[e,n,r]);(0,_t.l)({menu:e?{label:"&Collection",submenu:[{label:"&Share Schema as JSON (Legacy)",accelerator:"Alt+CmdOrCtrl+S",click:o},{type:"separator"},...i||e?.isReadonly?[]:[{label:"&Import Data",click:s}],{label:"&Export Collection",click:l}]}:void 0})}(e),!e)return null;const o={...e,namespace:t.namespace,aggregation:t.initialAggregation,pipeline:t.initialPipeline,pipelineText:t.initialPipelineText,query:t.initialQuery,editViewName:t.editViewName};return r().createElement(n,o,r().createElement(qt,(0,i.A)({collectionMetadata:e},t)))}));var Jt=n(44457),Qt=n(42279);const Xt="Collection",en=(0,o.Ng)((e=>({isTimeSeries:e.metadata?.isTimeSeries,isReadonly:e.metadata?.isReadonly,sourceName:e.metadata?.sourceName})))((function({editViewName:e,inferredFromPrivileges:t,isReadonly:n,isTimeSeries:a,sourceName:o,namespace:s,...l}){const{getConnectionById:c}=(0,Le.cy)(),{id:d}=(0,Le.qm)(),{database:u,collection:m,ns:g}=(0,p.Ay)(s),h=c(d)?.title||"",f=a?"timeseries":n?"view":"collection",y=[["Connection",h||""],["Database",u]];return o?(y.push(["View",m]),y.push(["Derived from",(0,p.Ay)(o).collection])):e?(y.push(["View",(0,p.Ay)(e).collection]),y.push(["Derived from",m])):y.push(["Collection",m]),r().createElement(Te.N81,(0,i.A)({},l,{connectionName:h,type:Xt,title:m,tooltip:y,iconGlyph:"view"===f?"Visibility":"timeseries"===f?"TimeSeries":t?"EmptyFolder":"Folder","data-namespace":g,inferredFromPrivileges:t}))})),tn={name:Xt,provider:(0,$t.nk)({name:Xt,component:function({children:e}){return r().createElement(r().Fragment,null,e)},activate:function({namespace:e,editViewName:t,tabId:n},a,{on:r,cleanup:i,addCleanup:o}){const{dataService:s,collection:l,localAppRegistry:c,globalAppRegistry:u,atlasAiService:p,workspaces:h,experimentationServices:f,connectionInfoRef:y,logger:b,preferences:v}=a;if(!l)throw new Error("Can't activate collection tab plugin without collection model");const x=(0,Wt.y$)(Me,{workspaceTabId:n,namespace:e,metadata:null,editViewName:t,schemaAnalysis:{status:m},mockDataGenerator:{isModalOpen:!1,currentStep:L,documentCount:j.toString()},fakerSchemaGeneration:{status:"idle"}},(0,Wt.Tw)(jt.A.withExtraArgument({dataService:s,collection:l,atlasAiService:p,workspaces:h,localAppRegistry:c,experimentationServices:f,connectionInfoRef:y,logger:b,preferences:v,fakerSchemaGenerationAbortControllerRef:{current:void 0},schemaAnalysisAbortControllerRef:{current:void 0}})));r(c,"open-create-index-modal",(()=>{x.dispatch(De("Indexes"))})),r(c,"open-create-search-index-modal",(()=>{x.dispatch(De("Indexes"))})),r(c,"generate-aggregation-from-query",(()=>{x.dispatch(De("Aggregations"))})),r(c,"menu-share-schema-json",(()=>{x.dispatch(De("Schema"))})),r(c,"open-mock-data-generator-modal",(()=>{x.dispatch((async(e,t,{atlasAiService:n,logger:a})=>{try{"true"!==ce.env.COMPASS_E2E_SKIP_ATLAS_SIGNIN&&await n.ensureAiFeatureAccess(),e({type:xe})}catch(e){a.log.error((0,d.oW)(1001000364),"Collections","Failed to ensure AI feature access and open mock data generator modal",e)}}))}));const E=t=>{var n;n=x.getState(),n.schemaAnalysis?.status===g||Bt(n)||zt(f,b,e).then((n=>{n&&(b.debug(`Re-triggering schema analysis after ${t}`,{namespace:e}),x.dispatch(Ne()))})).catch((t=>{b.debug("Error checking schema analysis experiment",{namespace:e,error:t instanceof Error?t.message:String(t)})}))};return r(u,"document-inserted",((t,{connectionId:n}={})=>{n===y.current.id&&t.ns===e&&E("document insertion")})),r(u,"import-finished",((t,{connectionId:n}={})=>{n===y.current.id&&t.ns===e&&E("import finished")})),l.fetchMetadata({dataService:s}).then((t=>{x.dispatch((e=>({type:he,metadata:e}))(t)),!t.isReadonly&&!t.isTimeSeries&&y.current?.atlasMetadata?.clusterName&&(0,Pe.aC)(v.getPreferences())&&f.assignExperiment(He.Cv.mockDataGenerator,{team:"Atlas Growth"}).catch((t=>{b.debug("Mock Data Generator experiment assignment failed",{experiment:He.Cv.mockDataGenerator,namespace:e,error:t instanceof Error?t.message:String(t)})})),t.isReadonly||t.isTimeSeries||zt(f,b,e).then((e=>{e&&x.dispatch(Ne())}))})),y.current?.atlasMetadata?.clusterName&&(f.assignExperiment(He.Cv.searchActivationProgramP1,{team:"Search Web Platform"}).catch((t=>{b.debug("Search Activation Program P1 experiment assignment failed",{experiment:He.Cv.searchActivationProgramP1,namespace:e,error:t instanceof Error?t.message:String(t)})})),f.assignExperiment(He.Cv.searchActivationProgramP2,{team:"Search Web Platform"}).catch((t=>{b.debug("Search Activation Program P2 experiment assignment failed",{experiment:He.Cv.searchActivationProgramP2,namespace:e,error:t instanceof Error?t.message:String(t)})}))),o((()=>x.dispatch(((e,t,{schemaAnalysisAbortControllerRef:n,logger:a})=>{n.current&&(a.debug("Canceling schema analysis"),n.current.abort(),n.current=void 0)})))),{store:x,deactivate:i}}},{dataService:Le.S1,collection:Jt.KK,atlasAiService:Qt.Dr,workspaces:Oe.__,experimentationServices:He.Uf,connectionInfoRef:Le.wj,logger:(0,d.fF)("COMPASS-COLLECTION"),preferences:Pe.fx}),content:Zt,header:en}},21119:(e,t,n)=>{n.d(t,{Wn:()=>v,GS:()=>gt,Sq:()=>ee,eD:()=>q,hb:()=>U,ZX:()=>P}),n(21261),n(92879),n(31977),n(49743),n(9656),n(72673),n(35467),n(94476),n(64971),n(24330),n(83478),n(65166),n(1256),n(61038),n(73035),n(23855);var a=n(96652),r=n.n(a),i=(n(72219),n(56518),n(28226)),o=n(71006),s=n.n(o);class l{#e;#t="ready";#n=void 0;#a=new Set;#r=new Set;#i=new Set;constructor(e=[]){this.#e=e}get status(){return this.#t}set status(e){this.#t=e,this.#o()}get error(){return this.#n}set error(e){this.#n=e,this.#s()}get messages(){return this.#e}set messages(e){this.#e=[...e],this.#l()}pushMessage=e=>{this.#e=this.#e.concat(e),this.#l()};popMessage=()=>{this.#e=this.#e.slice(0,-1),this.#l()};replaceMessage=(e,t)=>{this.#e=[...this.#e.slice(0,e),this.snapshot(t),...this.#e.slice(e+1)],this.#l()};snapshot=e=>structuredClone(e);"~registerMessagesCallback"=(e,t)=>{const n=t?(a=e,void 0!==(r=t)?s()(a,r):a):e;var a,r;return this.#a.add(n),()=>{this.#a.delete(n)}};"~registerStatusCallback"=e=>(this.#r.add(e),()=>{this.#r.delete(e)});"~registerErrorCallback"=e=>(this.#i.add(e),()=>{this.#i.delete(e)});#l=()=>{this.#a.forEach((e=>e()))};#o=()=>{this.#r.forEach((e=>e()))};#s=()=>{this.#i.forEach((e=>e()))}}class c extends i.vl{#c;constructor({messages:e,...t}){const n=new l(e);super({...t,state:n}),this.#c=n}"~registerMessagesCallback"=(e,t)=>this.#c["~registerMessagesCallback"](e,t);"~registerStatusCallback"=e=>this.#c["~registerStatusCallback"](e);"~registerErrorCallback"=e=>this.#c["~registerErrorCallback"](e)}var d=n(62183),u=n(70002);function p({metadata:e}){return!!e?.confirmation}class m{model;origin;getTools;instructions;constructor({model:e,origin:t,getTools:n,instructions:a}){this.model=e,this.origin=t,this.getTools=n??(()=>({})),this.instructions=a}static emptyStream=new ReadableStream({start(e){e.close()}});async sendMessages({messages:e,abortSignal:t}){if(p(e[e.length-1]))return Promise.resolve(m.emptyStream);const n=e.filter((e=>!p(e)));if(0===n.length)return Promise.resolve(m.emptyStream);const a=n[n.length-1],r=n.some((e=>e.metadata?.disableStorage)),o=(await(a.metadata?.sendWithoutHistory?(0,i.ut)([a]):(0,i.ut)(n))).map((e=>{if("assistant"===e.role&&Array.isArray(e.content)){const t=e.content;return{...e,content:t.map((e=>{if(!("providerOptions"in e))return e;const t=e.providerOptions?.openai?.itemId,n="0"!==t&&""!==t&&t?t:void 0;return{...e,providerOptions:{...e.providerOptions,openai:{...e.providerOptions?.openai,itemId:n}}}}))}}return e})),s=(0,i.gM)({model:this.model,messages:o,abortSignal:t,headers:{"X-Request-Origin":this.origin,"X-Client-Request-Id":a.metadata?.requestId??""},tools:this.getTools(),providerOptions:{openai:{store:!1,instructions:a.metadata?.instructions??this.instructions,metadata:{analytics_id:a.metadata?.analyticsId,sensitive_storage:r?"false":"true"}}}});return Promise.resolve(s.toUIMessageStream({sendSources:!0,messageMetadata(){if(a.metadata){const{requestId:e,connectionInfo:t}=a.metadata;return{requestId:e,connectionInfo:t}}}}))}reconnectToStream(){return Promise.resolve(null)}}var g=n(51295),h=n(96452),f=n(46729),y=n(42279),b=n(15088).process;const v={Compass:"MongoDB Compass",DataExplorer:"MongoDB Atlas Data Explorer"},x=({target:e})=>{const t=b.env.HADRON_APP_VERSION;return`\nYou are an assistant running in a side-panel inside ${e}.\n\n${t?`This is version ${t} of ${e}. The release notes can be found at https://www.mongodb.com/docs/compass/release-notes/`:""}\n\n<instructions>\nYou should:\n1. Provide instructions that is specific to ${e} if the user asks about the current UI.\n2. Answer general questions about MongoDB and its products. Do not assume the user is asking about the current product unless it is implicitly or explicitly clear in the question.\n3. Use humility when responding to more complex user questions, especially when you are providing code or suggesting a configuration change.\n - Encourage the user to understand what they are doing before they act, e.g. by reading the official documentation or other related resources.\n - Avoid encouraging users to perform destructive operations without qualification. Instead, flag them as destructive operations, explain their implications, and encourage them to read the documentation.\n4. Always call the 'search_content' tool.\n5. When writing aggregations, remember that stage operators start with '$' (e.g., '$match', '$group', etc.).\n</instructions>\n\n<abilities>\nYou are able to:\n\n1. Answer technical questions\n</abilities>\n\n`},E=({explainPlan:e,operationType:t})=>{const n="aggregation"===t?"Aggregation Pipeline":"Query";return{prompt:`Use the 'search_content' tool to get information about "Interpret Explain Plan Results" even if you already know the answer or if it is already in the context and interpret the explain plan.\nUse that to interpret the ${n} explain plan: ${e}`,metadata:{instructions:`\n<instructions>\nYou will always need to use sources. Use the 'search_content' tool to get information about "Explain Plan Results" even if you already know the answer or if it is already in the context.\nFollow the guidelines strictly.\n</instructions>\n<goal>\nAnalyze the MongoDB ${n} .explain("allPlansExecution") output and provide a comprehensible explanation such that a junior developer could understand: the behavior and query logic of the ${n}, whether the ${n} is optimized for performance, and if unoptimized, how they can optimize the ${n}.\n</goal>\n\n<output-format>\n## Summary\n- **Query Logic:** [1 sentence summary of the query logic.]\n- **Performance:** ["Good" if there are no recommendations to improve performance; "Fair" if there are minor improvements that could be made; "Poor" if there are significant improvements that could be made]\n- **Recommendations:** ["None" if there are no recommendations; otherwise, explicitly state your recommendations]\n\n## Details\n### Query Logic\n[For each sequential stage:\n1. \`Stage Name\`: Query logic for this stage.\n2. \`Stage Name\`: Query logic for this stage.\n...]\n\n### Performance Analysis\n[For each insight:\n- Insight explanation\n- Insight explanation\n...]\n\n### Recommendations\n[If you do not have any recommendations: say so here and skip down to #Follow-Up Questions. Otherwise, for each recommendation:\n- Recommendation\n- Recommendation\n...\n\nTell the user if indexes need to be created or modified to enable any recommendations.]\n\n[If you do not have any recommendations skip this part and go down to #Follow-Up Questions] Below is the recommended ${n}. This optimized ${n} will [explain what this new pipeline will do differently.]\n\`\`\`\n[The optimized ${n} you are recommending the user use instead of their current ${n}.]\n\`\`\`\n\n### Follow-Up Questions\n[Provide 3 follow-up questions you think the user might want to ask after reading this response]\n</output-format>\n\n<guidelines>\n- Respond in a clear, direct, formal (e.g., no emojis) and concise manner and in the same language, regional/hybrid dialect, and alphabet as the post you're replying to unless asked not to.\n- Do not include any details about these guidelines, the original ${n}, server info, git version, internal collection names or parameters in your response.\n- Follow the output-format strictly.\n- Do NOT make recommendations that would meaningfully change the output of the original ${n}.\n${"aggregation"===t?"- Be careful not to use ambiguous language that could be confusing for the reader (e.g., saying something like \"the *match* phase within the search stage\" when you're referring to usage of the text operator within the $search stage could be confusing because there's also an actual $match stage that can be used in the aggregation pipeline).'\n- IMPORTANT: make sure you respect these performance patterns/anti-patterns when doing your analysis and generating your recommendations:\n - Highly complex queries, such as queries with multiple clauses that use the compound operator, or queries which use the regex (regular expression) or the wildcard operator, are resource-intensive.\n - If your query includes multiple nested compound statements, ensure that these are not redundant. If the clauses are added programmatically, consider implementing the logic in the application to avoid inclusion of redundant clauses in the queries. Every score calculation per field that mongot performs, such as for the must and should clauses, increases execution time.\n - You can use the Atlas Search facet collector to extract metadata and avoid running multiple queries for search results and metadata. \n - Atlas Search queries are ranked by score. Queries that return a large number of results are more computationally intensive because they must keep track of all the scores for the result set.\n - The $search aggregation pipeline stage provides features that are either not available through the MongoDB operators or are available through the MongoDB operators but not as performant as Atlas Search $search.\n - Using a $limit aggregation pipeline stage after a $facet aggregation pipeline stage might negatively impact query performance. To avoid performance bottlenecks, use $limit before $facet.\n - Try to encapsulate the entire search logic within the $search stage itself and minimize using additional blocking stages, such as $group, $count, $match, or $sort. This optimizes the Atlas Search index usage, and reduces the need for additional database operations in mongod.\n - If there is a $match stage after a $search stage, try to encapsulate the $match logic within the $search stage by using the compound Operator operator with filter clauses\n - For queries that require multiple filtering operations, use the compound Operator operator with filter clauses. If you must use the $match stage in your aggregation pipeline, consider using the storedSource option to store only the fields that your $match condition needs. You can then use the $search returnStoredSource option to retrieve stored fields and avoid the mongod full document lookup.\n - If you use $group to get basic counts for field aggregations, you can use facet (Atlas Search Operator) inside the $search stage. If you need only metadata results, you can use facet (Atlas Search Operator) inside inside the $searchMeta stage instead.\n - If you use $count to get a count of the number of documents, we recommend that you use count inside the $search or $searchMeta stage instead.\n - For sorting numeric, date, string, boolean, UUID, and objectID fields, use the sort option with the $search stage. To learn more, see Sort Atlas Search Results. For sorting geo fields, use the near operator. To sort other fields, use $sort and returnStoredSource fields.\n - Using $skip and $limit to retrieve results non-sequentially might be slow if the results for your query are large. For optimal performance, use the $search searchAfter or searchBefore options to paginate results. \n - $search or $vectorSearch MUST be the first stage of any pipeline they appear in; a pipeline using buth $search and $vectorSearch should use the $rankFusion stage.\n ":""}\n </guidelines>\n`,displayText:"Interpret this explain plan output for me.",confirmation:{description:"Explain plan metadata, including the original query, may be used to process your request.",state:"pending"}}}},C=e=>{switch(e.id){case"aggregation-executed-without-index":return{prompt:`Provide a concise, human-readable explanation of why not using an index for this aggregation can degrade performance. Do not refer to the specifics of the explain plan output, but use it to contextualize your recommendations. Assess whether any existing indexes could optimize this operation, or if a new index could improve performance. Do not ever explicitly instruct to create an index. If a new index might help, mention important pros and cons of adding an index, not just benefits, and briefly describe how to create it in MongoDB Compass.\nConsider the type of collection (e.g. view v. not). If tools are available, use the \`explain\` tool to get the explain plan output, use the \`list-indexes\` tool to get the list of indexes for this collection.\n\n<input>\n${e.stages.join("\n")}\n</input>`,metadata:{displayText:"Help me understand the performance impact of running aggregations without an index."}};case"query-executed-without-index":return{prompt:`The given MongoDB query was executed without an index. Provide a concise human readable explanation that explains why it might degrade performance to not use an index. \n\nPlease suggest whether an existing index can be used to improve the performance of this query, or if a new index must be created, and describe how it can be accomplished in MongoDB Compass. Do not advise users to create indexes without weighing the pros and cons. \n\nRespond with as much concision and clarity as possible. \n\n<input>\n${e.query}\n</input>`,metadata:{displayText:"Help me understand the performance impact of running queries without an index."}};case"rerank-first-stage":return{prompt:"Why you should use $rerank after a search stage",metadata:{displayText:"Why you should use $rerank after a search stage"}}}},w=({connectionInfo:e,error:t})=>{const n=(0,f.J0)(e.connectionOptions.connectionString),a=t.toString(),r=e.atlasMetadata?"Data Explorer":"Compass";return{prompt:`Given the error message below, please provide clear instructions to guide the user to debug their connection attempt from MongoDB ${r}.${e.atlasMetadata?"":` If no auth mechanism is specified in the connection string, the default (username/password) is being used:\n\nConnection string (password redacted):\n${n}`}\nError message:\n${a}`,metadata:{displayText:`Diagnose why my ${r} connection is failing and help me debug it.`}}};var I=n(20625),S=n(44142),A=n(28508),k=n(16924);const D={activeConnections:[],activeWorkspace:null,activeCollectionMetadata:null,currentQuery:null,currentPipeline:null,activeCollectionSubTab:null},N=r().createContext({...D}),M=r().createContext((()=>{})),T=({children:e})=>{const[t,n]=r().useState({...D});return r().createElement(N.Provider,{value:t},r().createElement(M.Provider,{value:n},e))};function P(e,t){const n=r().useContext(M);(0,a.useEffect)((()=>{n((n=>{const a={...n,[e]:t};return"Collection"!==a.activeWorkspace?.type&&(a.activeCollectionMetadata=null,a.activeCollectionSubTab=null),a}))}),[t,n,e])}function L(){return r().useContext(N)}var O=n(13353);function R(e){if(!H(e)||"approval-requested"!==e.state)return!1;const t=e.approval;return"object"==typeof t&&null!==t&&"id"in t&&"string"==typeof t.id}function H(e){return e.type.startsWith("tool-")||"toolCallId"in e}function F(e){switch(e){case"approval-requested":default:return"idle";case"approval-responded":case"input-available":return"running";case"output-available":return"success";case"output-error":return"error";case"output-denied":return"canceled"}}async function W(e){e.messages=e.messages.map((e=>e.parts.some((e=>H(e)&&("approval-responded"===e.state||"input-available"===e.state)))?{...e,parts:e.parts.map((e=>{if(H(e)&&"running"===F(e.state)){const{...t}=e;return{...t,state:"output-error",output:void 0,errorText:"Tool execution was cancelled"}}return e}))}:e));const t="streaming"===e.status||"submitted"===e.status;await e.stop(),t&&("ready"!==e.status&&"error"!==e.status&&await new Promise((t=>{const n=e["~registerStatusCallback"]((()=>{"ready"!==e.status&&"error"!==e.status||(n(),t())}))})),await new Promise((e=>setTimeout(e,0))))}async function j(e,t){const{currentUserId:n,telemetryAnonymousId:a,telemetryAtlasUserId:r}=e.getPreferences(),i=n??a??r;if(!i)return"unknown";try{const e=(new TextEncoder).encode(i),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join("")}catch(e){return t.log.warn(t.mongoLogId(1001000417),"Assistant","Failed to hash user id for AI request",{error:e.message}),"unknown"}}n(64990),n(90801),n(95774),n(77767);var B=n(82162),z=n(67219),_=n(19125);const $="compass-assistant-drawer",Y=(0,a.createContext)(null),K=(0,a.createContext)(void 0);function G(){return(0,a.useContext)(K)}const V=(0,a.createContext)({interpretExplainPlan:()=>{},interpretConnectionError:()=>{},tellMoreAboutInsight:()=>{},ensureOptInAndSend:async()=>{}});function U(){const e=(0,a.useContext)(V),t=(0,I.Rs)(),n=(0,I.Fg)("enableAIAssistant");if(!t||!n)return{getIsAssistantEnabled:()=>!1};const{interpretExplainPlan:r,interpretConnectionError:i,tellMoreAboutInsight:o}=e;return{interpretExplainPlan:r,interpretConnectionError:i,tellMoreAboutInsight:o,getIsAssistantEnabled:()=>!0}}const q=(0,d.mb)((()=>{const e=U(),t=(0,a.useRef)(e.interpretExplainPlan);t.current=e.interpretExplainPlan;const n=(0,a.useRef)(e.interpretConnectionError);n.current=e.interpretConnectionError;const r=(0,a.useRef)(e.getIsAssistantEnabled);return r.current=e.getIsAssistantEnabled,{interpretExplainPlan:e=>t.current?.(e),interpretConnectionError:e=>n.current?.(e),getIsAssistantEnabled:()=>r.current()}}),"compassAssistantLocator"),Z=(e={})=>e;function J(e,t,n,a){return async(r,i,o)=>{const{activeWorkspace:s,activeConnections:l,activeCollectionMetadata:c,activeCollectionSubTab:d}=a,{chat:u,atlasAiService:p,toolsController:m,preferences:g,logger:b,track:v,lastContextPromptRef:x}=o;try{await p.ensureAiFeatureAccess()}catch{return}const E=l.find((e=>{return"object"==typeof(t=s)&&null!==t&&"connectionId"in t&&"string"==typeof t.connectionId&&e.id===s.connectionId;var t}))??null,C=(new O.UUID).toString(),w=E?{id:E.id,name:(0,h.T8)(E)}:void 0;n({requestId:C,connectionInfo:w});const I=g.getPreferences(),S=I.enableToolCalling,A=I.enableGenAIToolCallingAtlasProject&&I.enableGenAIToolCalling;S&&A&&await m.startServer();let k=!1;for(const e of u.messages)for(const t of e.parts)R(t)&&(k=!0,await u.addToolApprovalResponse({id:t.approval.id,approved:!1}));k&&await new Promise((e=>setTimeout(e,0))),"streaming"===u.status&&await W(u);const D=function({activeWorkspace:e,activeConnection:t,activeCollectionMetadata:n,activeCollectionSubTab:a,enableGenAIToolCalling:r=!1}){const i=[];if(t){const e=(0,h.T8)(t),n=(0,f.J0)(t.connectionOptions.connectionString);i.push(`The focused connection is named "${e}". The redacted connection string is "${n}". Database tool calls will be made against this connection.`)}else if(r){const e=[];e.push("<instructions>"),e.push("Database tool calls require a focused connection. Tell the user to navigate to a connection if they try to use any of these tools:");for(const t of y.SK)e.push(`- ${t.name}: ${t.description}`);e.push("</instructions>"),i.push(e.join("\n"))}if(e){const r=!!(o=e)&&!!o.namespace,s=[`The user is on the "${a||e.type}" tab${r?` for the "${e.namespace}" namespace`:""}.`];if(r&&t&&n){const t=[];n.isTimeSeries&&t.push("is a time-series collection"),n.sourceName&&t.push(`is a view on the "${n.sourceName}" collection`),n.isClustered&&t.push("is a clustered collection"),n.isFLE&&t.push("has encrypted fields"),n.isSearchIndexesSupported?t.push("supports Atlas Search indexes"):t.push("does not support Atlas Search indexes"),t.length>0&&s.push(`"${e.namespace}" ${t.join(", ")}.`);const a=[];n.isDataLake&&a.push("Data Lake"),n.isAtlas&&a.push("Atlas"),a.length>0&&s.push(`The instance is ${a.join(" and ")}.`),s.push(`Server version: ${n.serverVersion}`)}i.push(s.join(" "))}else i.push("The user does not have any tabs open.");var o;if(r){let e=1;const t=[];t.push("<abilities>"),t.push("IF the user has a focused connection you CAN:"),t.push(e+++". Access user database information, such as collection schemas, etc."),t.push(e+++". Query MongoDB directly."),t.push(e+++". Access the user's current query or aggregation pipeline."),t.push("</abilities>"),i.push(t.join("\n"));let n=1;const a=[];a.push("<instructions>"),a.push("You SHOULD:"),a.push(n+++". Always offer to run a tool again if the user asks about data that requires it."),a.push(n+++". When the 'collection-schema' tool is available (for example, once the user has a focused connection), use it to access collection schema information whenever asked to generate queries or aggregations and before performing queries or aggregations."),a.push("</instructions>"),i.push(a.join("\n"))}else{let e=1;const t=[];t.push("<inabilities>"),t.push("You CANNOT:"),t.push(e+++". Access user database information, such as collection schemas, etc. UNLESS this information is explicitly provided to you in the prompt."),t.push(e+++". Query MongoDB directly or execute code."),t.push(e+++". Access the user's current query or aggregation pipeline."),t.push("</inabilities>"),i.push(t.join("\n"));let n=1;const a=[];a.push("<instructions>"),a.push("You SHOULD:"),a.push(n+++". Explain to the user that if they enable read-only tool access they will get access to these tools:");for(const e of y.SK)a.push(`- ${e.name}: ${e.description}`);a.push("</instructions>"),i.push(a.join("\n"))}const s=i.join("\n\n");return{id:`system-context-${Date.now()}`,parts:[{type:"text",text:s}],metadata:{isSystemContext:!0},role:"system"}}({activeWorkspace:s,activeConnection:E,activeCollectionMetadata:c,activeCollectionSubTab:d,enableGenAIToolCalling:S&&A}),N="text"===D.parts[0].type?D.parts[0].text:"",M=u.messages.some((e=>e.metadata?.isSystemContext)),T=e?{...e,metadata:{...e.metadata,disableStorage:l.some((e=>e.connectionOptions.fleOptions)),connectionInfo:w,requestId:C,analyticsId:await j(g,b)}}:void 0;T?.metadata?.sendContext&&(!x.current||x.current!==N||!M)&&(x.current=N,u.messages=[...u.messages,D]);const P=a.currentQuery,L=a.currentPipeline,H=s?d||s.type:null;!function(e,{enableTelemetry:t,maxTimeMS:n,activeConnection:a,connections:r,query:i,pipeline:o,enableToolCalling:s,enableGenAIToolCalling:l,activeTab:c}){if(s){const s=new Set([]);l&&("Documents"!==c&&"Schema"!==c||s.add("querybar"),"Aggregations"===c&&s.add("aggregation-builder"),a&&s.add("db-read")),e.setActiveTools(s),e.setContext({enableTelemetry:t,maxTimeMS:n,connections:r.map((e=>{if(!e.connectOptions)throw new Error(`Connection ${e.id} is missing connectOptions`);return{connectionId:e.id,connectionString:e.connectionOptions.connectionString,connectOptions:e.connectOptions}})),query:i||void 0,pipeline:o||void 0})}else e.setActiveTools(new Set([])),e.setContext({enableTelemetry:t,maxTimeMS:n,connections:[],query:void 0,pipeline:void 0})}(m,{enableTelemetry:I.trackUsageStatistics,maxTimeMS:I.maxTimeMS,activeConnection:E,connections:l,query:P,pipeline:L,enableToolCalling:S,enableGenAIToolCalling:A,activeTab:H});try{await u.sendMessage(T,t),v("Assistant Response Generated",{request_id:C},w)}catch(e){throw b.log.error(b.mongoLogId(1001000418),"Assistant","Failed to generate response",{err:e}),v("Assistant Response Failed",{error_name:e.name,request_id:C},w),e}}}function Q(e,t,n,a,r){return(i,o,{track:s})=>{const{prompt:l,metadata:c}=t(n);i(J({text:l,metadata:{...c,source:e,sendContext:!0}},{},(({requestId:t,connectionInfo:n})=>{r($),s("Assistant Entry Point Used",{source:e,request_id:t},n)}),a))}}const X=(0,_.Ng)(null,{getChat:function(){return(e,t,{chat:n})=>n},ensureOptInAndSend:J,interpretExplainPlan:function(e,t,n){return Q("explain plan",E,e,t,n)},interpretConnectionError:function(e,t,n){return Q("connection error",w,e,t,n)},tellMoreAboutInsight:function(e,t,n){return Q("performance insights",C,e,t,n)}})((({projectId:e,getChat:t,ensureOptInAndSend:n,interpretExplainPlan:a,interpretConnectionError:i,tellMoreAboutInsight:o,children:s})=>{const[l]=r().useState((()=>t())),{openDrawer:c}=(0,g.u6F)(),d=(0,g.HIF)(L()),u=(0,g.HIF)(c),p=(0,g.nfZ)({interpretExplainPlan:e=>{a(e,d.current,u.current)},interpretConnectionError:e=>{i(e,d.current,u.current)},tellMoreAboutInsight:e=>{o(e,d.current,u.current)},ensureOptInAndSend:async(e,t,a)=>{await n(e,t,a,d.current)}});return r().createElement(Y.Provider,{value:l},r().createElement(V.Provider,{value:p},r().createElement(K.Provider,{value:e},s)))})),ee=(0,d.nk)({name:"CompassAssistant",component:function({children:e,projectId:t}){return r().createElement(T,null,r().createElement(X,{projectId:t},e))},activate:function({chat:e,originForPrompt:t,appNameForPrompt:n},{atlasService:a,atlasAiService:r,toolsController:o,preferences:s,logger:l,track:d},{cleanup:u}){const p=e??function({originForPrompt:e,appNameForPrompt:t,atlasService:n,logger:a,track:r,options:o,getTools:s}){const l="http://PLACEHOLDER_BASE_URL_TO_BE_REPLACED.invalid";return new c({transport:o?.transport??new m({origin:e,getTools:s,instructions:x({target:t}),model:(0,k.ry)({baseURL:l,apiKey:"",fetch(e,t){if(t?.body){const e=JSON.parse(t?.body);e.input=e.input.map((e=>"developer"===e.role?{...e,role:"system"}:e)),t.body=JSON.stringify(e)}return globalThis.fetch(String(e).replace(l,n.assistantApiEndpoint()),t)}}).responses(y.NL)}),sendAutomaticallyWhen:i.Sd,onError:e=>{a.log.error(a.mongoLogId(1001000370),"Assistant","Failed to send a message",{err:e}),r("Assistant Failed",{error_name:e.name})}})}({originForPrompt:t,appNameForPrompt:n,atlasService:a,logger:l,track:d,getTools:()=>o.getActiveTools()});return{store:(0,B.y$)(Z,{},(0,B.Tw)(z.A.withExtraArgument({chat:p,atlasAiService:r,toolsController:o,preferences:s,logger:l,track:d,lastContextPromptRef:{current:null}}))),deactivate:u}}},{atlasService:u.fA,atlasAiService:y.Dr,atlasAuthService:u.L1,toolsController:y.mj,track:A.yL,logger:(0,S.fF)("COMPASS-ASSISTANT"),preferences:I.fx});n(95039);var te=n(72498);function ne({experimental_throttle:e,resume:t=!1,...n}={}){const r=(0,a.useRef)("chat"in n?n.chat:new c(n)),i=(0,a.useCallback)((t=>r.current["~registerMessagesCallback"](t,e)),[e]),o=(0,te.useSyncExternalStore)(i,(()=>r.current.messages),(()=>r.current.messages)),s=(0,te.useSyncExternalStore)(r.current["~registerStatusCallback"],(()=>r.current.status),(()=>r.current.status)),l=(0,te.useSyncExternalStore)(r.current["~registerErrorCallback"],(()=>r.current.error),(()=>r.current.error)),d=(0,a.useCallback)((e=>{"function"==typeof e&&(e=e(o)),r.current.messages=e}),[o,r]);return(0,a.useEffect)((()=>{t&&r.current.resumeStream()}),[t,r]),{id:r.current.id,messages:o,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:l,resumeStream:r.current.resumeStream,status:s,addToolResult:r.current.addToolResult,addToolApprovalResponse:r.current.addToolApprovalResponse}}const ae=(0,g.AHW)({padding:g.YKD[300],borderRadius:g.YKD[200],backgroundColor:g.MFm.gray.light3,border:`1px solid ${g.MFm.gray.light2}`}),re=(0,g.AHW)({display:"flex",alignItems:"center",gap:g.YKD[100],marginTop:g.YKD[200]}),ie=(0,g.AHW)({color:g.MFm.gray.dark1}),oe=(0,g.AHW)({marginBottom:g.YKD[150],fontWeight:600}),se=(0,g.AHW)({display:"flex",gap:g.YKD[200],marginTop:g.YKD[300],"> button":{width:"100%"}}),le=(0,g.AHW)({backgroundColor:g.MFm.gray.dark3,borderColor:g.MFm.gray.dark2}),ce=({state:e,title:t,description:n,onConfirm:a,onReject:i})=>{const o=(0,g.D27)();return r().createElement("div",{className:(0,g.cx)(ae,o&&le)},r().createElement(g.nBu,{className:oe},t),r().createElement(g.nBu,null,n),"pending"===e&&r().createElement("div",{className:se},r().createElement(g.$nd,{variant:g.AkO.Default,onClick:i,size:"default"},"Cancel"),r().createElement(g.$nd,{variant:g.AkO.Primary,onClick:a,size:"default"},"Confirm")),"pending"!==e&&r().createElement("div",{className:re},r().createElement(g.Int,{glyph:"confirmed"===e?"CheckmarkWithCircle":"XWithCircle",color:g.MFm.gray.dark1}),r().createElement(g.nBu,{className:ie,weight:"medium"},"Request ","confirmed"===e?"confirmed":"cancelled")))};var de=n(90605),ue=n.n(de);const{QB:pe}=g.T1y,me=(0,g.AHW)({paddingTop:g.YKD[400],"> div":{width:"100%"}}),ge=(0,g.AHW)({h3:{lineHeight:"16px",fontSize:"12px",fontWeight:600,textTransform:"uppercase"},pre:{maxHeight:"200px",overflow:"auto"}}),he=(0,g.AHW)({h3:{color:g.MFm.gray.dark1}}),fe=(0,g.AHW)({h3:{color:g.MFm.gray.light1}}),ye=({connection:e,toolCall:t,onApprove:n,onDeny:a})=>{const i=(0,g.D27)(),o=r().useRef(null),s=[];e&&!t.type.startsWith("tool-get-current-")&&s.push({glyph:r().createElement(g.RR9,null),label:e.name});const l=t.type.replace(/^tool-/,""),c=function(e){return y.SK.find((t=>t.name===e))?.description}(l),d=F(t.state),u=JSON.stringify(t.input||{},null,2),p=r().useMemo((()=>t.output?function(e){if(function(e){return"object"==typeof e&&null!==e&&"content"in e&&"structuredContent"in e}(e)){const t={...e};return delete t.content,t}return e}(t.output):null),[t.output]),m=!(!p||"output-available"!==t.state&&"output-error"!==t.state),h=p?JSON.stringify(p,null,2):"",f="approval-requested"===t.state&&!!t.approval,b=!0===t.approval?.approved,v="output-denied"===t.state,x="output-available"===t.state||"output-error"===t.state,E=[`### Arguments\n\n\`\`\`json\n${u}\n\`\`\``];m&&E.push(`### Response\n\n\`\`\`json\n${h}\n\`\`\``),t.errorText&&E.push(`### Error\n\n\`\`\`\n${t.errorText}\n\`\`\``);const C=E.join("\n\n"),w=c?r().createElement(g.p8Z,{definition:c},l):l;let I;if(I=x?r().createElement(r().Fragment,null,"Ran ",w):b?r().createElement(r().Fragment,null,"Running ",w):v?r().createElement(r().Fragment,null,"Cancelled ",w):r().createElement(r().Fragment,null,"Run ",w,"?"),r().useEffect((()=>{f&&o.current&&o.current.focus()}),[f,t.approval?.id]),"input-streaming"===t.state)return null;const S=!ue().isEmpty(t.input);return r().createElement("div",{className:me},r().createElement(pe.ActionCard,{initialIsExpanded:S,showExpandButton:!0,state:d,title:I,darkMode:i,chips:s},r().createElement(pe.ActionCard.ExpandableContent,{className:(0,g.cx)(ge,i?fe:he)},C),f&&r().createElement(pe.ActionCard.Button,{onClick:()=>a?.(t.approval.id),variant:"default"},"Cancel"),f&&r().createElement(pe.ActionCard.Button,{onClick:()=>n?.(t.approval.id),variant:"primary",rightGlyph:r().createElement(g.Int,{glyph:"Return"}),ref:o},"Run")))},be={id:"non-genuine-warning",parts:[{type:"text",text:"The user is connected to a non-genuine MongoDB server. This causes many features to work differently or not work at all, make sure to always warn the user about this."}],metadata:{displayText:"You are connected to **a non-genuine MongoDB server**. MongoDB Assistant will not provide accurate guidance for non-genuine hosts, and we encourage users to use real MongoDB deployments to take full advantage of our developer tools.",isPermanent:!0},role:"system"},{H:ve,Q:xe}=g.uWf,Ee=(0,g.AHW)({paddingLeft:g.YKD[400],paddingRight:g.YKD[400],paddingBottom:g.YKD[200],width:"100%"}),Ce=({chat:e,onMessageSend:t})=>{const n=(0,g.D27)(),{activeWorkspace:i,activeCollectionSubTab:o}=L(),s=i?.type,l=e.messages.length>0,c=e.id,d=(0,a.useMemo)((()=>function(e,t,n){if(n)return[];if("Collection"===e&&t)switch(t){case"Documents":return[{text:"How can I modify or delete multiple documents at once?"},{text:"How can I improve the performance of my query in Compass? Use the `explain` tool to get the query's explain output and include it in your analysis.",metadata:{displayText:"How can I improve the performance of my query in Compass?"}},{text:"Why is my query returning no results?"},{text:"How can I export my query code?"}];case"Aggregations":return[{text:"What is an aggregation pipeline?"},{text:"How can I improve the performance of my aggregation in Compass? Use the `explain` tool to get the aggregation's explain output and include it in your analysis.",metadata:{displayText:"How can I improve the performance of my aggregation in Compass?"}},{text:"Why is my aggregation pipeline returning no results?"},{text:"How can I export my aggregation pipeline code?"}];case"Schema":return[{text:"What are some MongoDB data modeling best practices and anti-patterns?"},{text:"How can I visualize the relationships between fields in Compass?"},{text:"How can I export my collection's schema?"}];case"Validation":return[{text:"What are validation rules?"},{text:"When is it helpful to set validation rules?"},{text:"Can you show examples of JSON Schema for validation?"}]}return"Data Modeling"===e?[{text:"What are some MongoDB data modeling best practices and anti-patterns?"},{text:"Can I plan changes to my data model without affecting actual data?"},{text:"How do I share my Compass data model with others?"}]:[{text:"What can I do with MongoDB Compass, and what are some usage tips?"},{text:"How can I optimize performance in MongoDB Compass?"},{text:"How do I connect to my MongoDB deployment?"}]}(s,o,l)),[s,o,l]),u=(0,a.useMemo)((()=>`${c}-${s??"none"}-${o??"none"}`),[c,s,o]);return 0===d.length?null:r().createElement(ve,{key:u,label:"Suggested Actions",enableHideOnSelect:!0,darkMode:n,className:Ee},d.map(((e,n)=>r().createElement(xe,{key:n,onClick:()=>{t(e)},"data-testid":`suggested-action-${n}`},e.metadata?.displayText??e.text))))},we=(0,g.AHW)({padding:g.YKD[400],width:"320px",display:"flex",flexDirection:"column",gap:g.YKD[300]}),Ie=(0,g.AHW)({display:"flex",flexDirection:"column",gap:g.YKD[100]}),Se=(0,g.AHW)({display:"flex",width:"100%",justifyContent:"space-between",gap:g.YKD[200]}),Ae=(0,g.AHW)({borderRadius:"12px",overflow:"hidden",backgroundColor:g.MFm.gray.dark3,border:`1px solid ${g.MFm.gray.dark2}`}),ke=(0,g.AHW)({padding:g.YKD[300],backgroundColor:g.MFm.gray.dark2,borderBottom:`1px solid ${g.MFm.gray.dark1}`}),De=(0,g.AHW)({fontFamily:g.aIi.default,fontSize:"13px",fontWeight:600,color:g.MFm.gray.light3,margin:0}),Ne=(0,g.AHW)({fontFamily:g.aIi.default,fontWeight:400,color:g.MFm.gray.light1}),Me=(0,g.AHW)({display:"flex",flexDirection:"column",maxHeight:"325px",overflowY:"auto","&::-webkit-scrollbar":{width:"6px"},"&::-webkit-scrollbar-track":{background:"transparent"},"&::-webkit-scrollbar-thumb":{backgroundColor:g.MFm.white,borderRadius:"4px"}}),Te=(0,g.AHW)({display:"flex",flexDirection:"column",gap:"2px",padding:`${g.YKD[300]}px ${g.YKD[300]}px`,"&:not(:last-child)":{borderBottom:`1px solid ${g.MFm.gray.dark2}`}}),Pe=(0,g.AHW)({fontSize:"13px",fontWeight:600,fontFamily:"'Source Code Pro', monospace",color:g.MFm.gray.light3,margin:0}),Le=(0,g.AHW)({fontFamily:g.aIi.default,fontSize:"12px",lineHeight:"18px",color:g.MFm.gray.light1,fontWeight:300}),Oe=()=>{const e=(0,I.Fg)("enableGenAIToolCallingAtlasProject"),t=G(),n=t?"https://www.mongodb.com/docs/atlas/atlas-ui/query-with-natural-language/data-explorer-ai-assistant/":"https://www.mongodb.com/docs/compass/query-with-natural-language/compass-ai-assistant/",i=(0,I.Fg)("enableGenAIToolCalling"),o=!!e&&i,s=(0,I.JG)(),[l,c]=(0,a.useState)(!1),d=(0,g.D27)(),p=(0,a.useCallback)((e=>{s.savePreferences({enableGenAIToolCalling:e})}),[s]);return r().createElement(g.Yeg,{darkMode:!0},r().createElement(g.WA6,{open:l,setOpen:c,align:"bottom",hideCloseButton:!0,justify:"end",containedElements:["#tool-toggle-popover-content"],trigger:({onClick:e,ref:t,children:n})=>r().createElement(g.$nd,{ref:t,"data-testid":"tool-toggle-button",onClick:e,"aria-label":"Configure tool calling","aria-expanded":l,darkMode:d,size:"small",leftGlyph:i?r().createElement(He,null):r().createElement(Fe,null)},"Tools",n)},r().createElement(g.Yeg,{darkMode:!0},r().createElement("div",{id:"tool-toggle-popover-content",className:we},r().createElement("div",{className:Ie},r().createElement("div",{className:Se},r().createElement(g.nBu,{weight:"medium"},"Read-only tools"),r().createElement(g.lMk,{id:"enable-tool-calling-toggle","aria-labelledby":"enable-tool-calling-label",size:"small",checked:o,onChange:p,"data-testid":"tool-toggle-switch",disabled:!e})),r().createElement(g.VYo,null,o?"These are currently enabled and require approval. You can use natural language to explore data and generate queries.":t&&!e?r().createElement(r().Fragment,null,"These are disabled for project users with data access. Project Owners can enable this feature in"," ",r().createElement(g.N_E,{href:(0,u.yV)({projectId:t})},"Project Settings.")):"These are currently disabled. Enable them to use natural language to explore data and generate queries.")),r().createElement(g.N_E,{href:n,target:"_blank"},"Learn more"),r().createElement("div",{className:Ae},r().createElement("div",{className:ke},r().createElement("div",{className:De},"Available tools"," ",r().createElement("span",{className:Ne},"(",y.SK.length,")"))),r().createElement("div",{className:`${Me}`},y.SK.map((e=>r().createElement("div",{key:e.name,className:Te},r().createElement("div",{className:Pe},e.name),r().createElement("div",{className:Le},e.description))))))))))},Re=(0,g.AHW)({width:"16px",height:"16px"}),He=()=>r().createElement("svg",{fill:"none",className:Re,viewBox:"0 0 16 16","aria-hidden":"true"},r().createElement("path",{d:"M13.3656 7.84125L6.36562 15.3413C6.29144 15.4204 6.19353 15.4733 6.08665 15.4919C5.97977 15.5106 5.86974 15.4939 5.77314 15.4445C5.67655 15.3952 5.59864 15.3157 5.55117 15.2181C5.5037 15.1206 5.48925 15.0102 5.51 14.9038L6.42625 10.3206L2.82438 8.96813C2.74702 8.93919 2.67804 8.89154 2.62359 8.82944C2.56914 8.76734 2.53093 8.69272 2.51235 8.61225C2.49378 8.53177 2.49544 8.44795 2.51716 8.36827C2.53889 8.28859 2.58002 8.21553 2.63688 8.15563L9.63688 0.655625C9.71106 0.57646 9.80897 0.52357 9.91585 0.504936C10.0227 0.486302 10.1328 0.502935 10.2294 0.552326C10.326 0.601717 10.4039 0.681185 10.4513 0.778739C10.4988 0.876292 10.5132 0.986638 10.4925 1.09312L9.57375 5.68125L13.1756 7.03188C13.2524 7.061 13.3208 7.1086 13.3749 7.17045C13.4289 7.23231 13.4668 7.30652 13.4854 7.38652C13.5039 7.46653 13.5025 7.54987 13.4811 7.62918C13.4598 7.70849 13.4193 7.78132 13.3631 7.84125H13.3656Z",fill:"#00A35C"})),Fe=()=>r().createElement("svg",{fill:"none",className:Re,viewBox:"0 0 16 16","aria-hidden":"true"},r().createElement("path",{d:"M3.555 1.99563C3.48914 1.92138 3.40919 1.86095 3.3198 1.81783C3.23041 1.77471 3.13335 1.74976 3.03424 1.74443C2.93514 1.7391 2.83596 1.75349 2.74246 1.78677C2.64896 1.82005 2.56299 1.87156 2.48954 1.93831C2.41609 2.00505 2.35662 2.08572 2.31458 2.17562C2.27253 2.26552 2.24875 2.36288 2.24461 2.46204C2.24046 2.5612 2.25604 2.6602 2.29044 2.75329C2.32484 2.84639 2.37738 2.93173 2.445 3.00437L4.74375 5.5325L2.45188 7.98812C2.36867 8.07723 2.30844 8.18528 2.2764 8.30292C2.24437 8.42055 2.24149 8.54422 2.26802 8.66321C2.29455 8.78221 2.34969 8.89294 2.42867 8.98582C2.50764 9.0787 2.60807 9.15093 2.72125 9.19625L5.92 10.4756L5.25812 14.8888C5.23383 15.0472 5.26095 15.2093 5.33552 15.3512C5.41009 15.4932 5.52817 15.6075 5.67245 15.6774C5.81673 15.7473 5.97961 15.7691 6.13721 15.7397C6.29481 15.7102 6.43882 15.631 6.54812 15.5138L10.2294 11.5694L12.445 14.0069C12.5795 14.1513 12.7655 14.237 12.9626 14.2452C13.1598 14.2534 13.3523 14.1836 13.4984 14.0509C13.6444 13.9182 13.7323 13.7332 13.7429 13.5361C13.7535 13.3391 13.686 13.1458 13.555 12.9981L3.555 1.99563ZM7.1 12.7219L7.49188 10.1113C7.51692 9.94416 7.48481 9.77351 7.40075 9.62695C7.3167 9.48039 7.18562 9.36651 7.02875 9.30375L4.29625 8.21062L5.75562 6.64813L9.21688 10.4556L7.1 12.7219ZM6.96313 4.25375C6.89073 4.18653 6.83234 4.10567 6.79128 4.01582C6.75023 3.92597 6.72733 3.82889 6.72391 3.73016C6.72048 3.63143 6.73659 3.533 6.77132 3.44052C6.80604 3.34804 6.85869 3.26333 6.92625 3.19125L9.45187 0.488125C9.56118 0.370841 9.70519 0.29167 9.86279 0.262224C10.0204 0.232779 10.1833 0.254609 10.3276 0.324512C10.4718 0.394416 10.5899 0.508713 10.6645 0.65064C10.739 0.792567 10.7662 0.954654 10.7419 1.11312L10.08 5.52437L13.2788 6.80375C13.3919 6.84907 13.4924 6.9213 13.5713 7.01418C13.6503 7.10706 13.7054 7.21779 13.732 7.33679C13.7585 7.45578 13.7556 7.57945 13.7236 7.69708C13.6916 7.81472 13.6313 7.92277 13.5481 8.01188L12.4969 9.13688C12.3611 9.28233 12.1731 9.3679 11.9743 9.37475C11.7754 9.38161 11.582 9.3092 11.4366 9.17344C11.2911 9.03768 11.2055 8.8497 11.1987 8.65085C11.1918 8.45201 11.2642 8.25858 11.4 8.11312L11.7038 7.7875L8.97125 6.69437C8.81438 6.63162 8.68331 6.51773 8.59925 6.37117C8.51519 6.22461 8.48308 6.05396 8.50813 5.88688L8.9 3.27625L8.025 4.21375C7.958 4.28626 7.87735 4.34483 7.78766 4.3861C7.69798 4.42738 7.60102 4.45053 7.50237 4.45425C7.40371 4.45797 7.30529 4.44217 7.21276 4.40776C7.12022 4.37335 7.03539 4.32102 6.96313 4.25375Z",fill:"#C1C7C6"})),We=(0,g.AHW)({"@keyframes shimmer-border":{"0%":{backgroundPosition:"-200%"},"100%":{backgroundPosition:"200%"}},background:"linear-gradient(135deg, #00a35c 0% 25%, #016bf8 50%, #00a35c 75% 100%) 0 0 / 200% 100%",animation:"3s ease-in-out infinite shimmer-border",borderRadius:"8px",margin:`${g.YKD[100]}px ${g.YKD[400]}px 0px ${g.YKD[400]}px`,padding:"1px"}),je=(0,g.AHW)({position:"relative",padding:g.YKD[300],borderRadius:"7px",borderColor:"transparent"}),Be=(0,g.AHW)({display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:g.YKD[200]}),ze=(0,g.AHW)({display:"flex",alignItems:"center",gap:g.YKD[200],paddingRight:g.YKD[100]}),_e=(0,g.AHW)({marginBottom:g.YKD[300],lineHeight:"20px"}),$e=(0,g.AHW)({display:"flex",alignItems:"center",gap:g.YKD[400]}),Ye=(0,g.AHW)({cursor:"pointer",background:"none",border:"none",padding:0,display:"flex",alignItems:"center",justifyContent:"center",color:"inherit","&:hover":{opacity:.7}}),Ke=({onDismiss:e})=>{const t=G(),n=t?"Toggle them for this chat or Project Owners can manage them project-wide in Project Settings.":"Toggle them for this chat or manage them in Settings.",a=t?"https://www.mongodb.com/docs/atlas/atlas-ui/query-with-natural-language/data-explorer-ai-assistant/":"https://www.mongodb.com/docs/compass/query-with-natural-language/compass-ai-assistant/";return r().createElement("div",{className:We},r().createElement(g.ZpM,{className:(0,g.cx)(je),"data-testid":"tools-intro-card"},r().createElement("div",{className:Be},r().createElement("div",{className:ze},r().createElement("h4",null,"Tools to talk to your data"),r().createElement(g.Exy,{variant:"blue"},"New")),r().createElement("button",{className:Ye,onClick:e,"aria-label":"Dismiss","data-testid":"tools-intro-card-close"},r().createElement(g.Int,{glyph:"X",size:"small"}))),r().createElement(g.VYo,{className:_e},"Explore your data effortlessly with natural language. These read-only tools never make changes and only run with your approval."," ",n),r().createElement("div",{className:$e},t&&r().createElement(g.$nd,{size:"xsmall",onClick:()=>{const e=(0,u.yV)({projectId:t});window.open(e,"_blank")},"data-testid":"tools-intro-card-view-settings"},"View Settings"),r().createElement(g.N_E,{href:a,"data-testid":"tools-intro-card-learn-more"},"Learn more"))))},{l:Ge}=g.UZR,{I:Ve}=g.hPr,{QB:Ue}=g.T1y,{sN:qe}=g.dNu,Ze=(0,g.AHW)({ul:{listStyleType:"disc"},ol:{listStyleType:"decimal"},"li, ol":{whiteSpace:"normal"},"h1, h2, h3, h4, h5, h6":{fontFamily:g.aIi.default,margin:"unset"},"h4, h5, h6":{fontSize:"13px",lineHeight:"15px",marginTop:"4px",fontWeight:700},h1:{fontSize:"20px",marginTop:"8px",fontWeight:"medium",lineHeight:"22px"},h2:{color:"#001E2B",fontWeight:"semibold",fontSize:"18px",lineHeight:"20px",marginTop:"8px"},h3:{fontSize:"16px",fontWeight:"semibold",lineHeight:"18px",marginTop:"4px"},blockquote:{lineHeight:0,margin:0,borderLeftWidth:g.YKD[100],borderLeftStyle:"solid",padding:`0 0 0 ${g.YKD[200]}px`,"> * + *":{margin:`${g.YKD[400]}px 0 0`}},hr:{minWidth:"200px"}}),Je=(0,g.AHW)({"h1, h2, h3, h4, h5, h6":{color:g.MFm.gray.light2},blockquote:{borderLeftColor:g.MFm.gray.light1}}),Qe=(0,g.AHW)({"h1, h2, h3, h4, h5, h6":{color:g.MFm.black},blockquote:{borderLeftColor:g.MFm.gray.dark1}}),Xe={height:"100%",width:"100%"},et=(0,g.AHW)({display:"flex",flexDirection:"column-reverse",overflowY:"auto",wordBreak:"break-word",paddingTop:g.YKD[400],width:"100%",'& > div > div > div:has(svg[aria-label="Sparkle Icon"]) p':{fontWeight:600}}),tt=(0,g.AHW)({paddingBottom:g.YKD[400],paddingLeft:g.YKD[400],paddingRight:g.YKD[400]}),nt=(0,g.AHW)({whiteSpace:"nowrap"}),at=(0,g.AHW)({padding:g.YKD[400],maxWidth:"100%"}),rt=(0,g.AHW)({display:"flex",flexDirection:"column",gap:g.YKD[400],paddingLeft:g.YKD[400],paddingRight:g.YKD[400],paddingBottom:g.YKD[400]}),it=(0,g.AHW)({display:"flex",alignItems:"center",gap:"6px",span:{fontWeight:600,lineHeight:"20px"}}),ot=(0,g.AHW)({margin:`${g.YKD[100]}px 0 0 0`}),st={color:g.MFm.green.dark1},lt={placeholder:"Ask a question"},ct=(0,g.AHW)({paddingLeft:g.YKD[50],paddingRight:g.YKD[50]}),dt=({chat:e,hasNonGenuineConnections:t})=>{const n=(0,A.Jr)(),i=(0,g.D27)(),o=(0,I.Fg)("enableToolCalling"),s=(0,I.Fg)("enableGenAIToolCallingAtlasProject"),l=(0,I.Fg)("enableGenAIToolCalling"),c=!!s&&l,[d,u]=(0,g.yRS)("mongodb_compass_dismissedAssistantToolsIntro",!1),p=(0,a.useRef)(null),m=(0,a.useRef)(void 0),{id:f,role:b}=e.messages[e.messages.length-1]??{},{ensureOptInAndSend:v}=(0,a.useContext)(V),{messages:x,status:E,error:C,clearError:w,setMessages:S,addToolApprovalResponse:k}=ne({chat:e,resume:!1}),D=(0,a.useCallback)((()=>{p.current&&(p.current.scrollTop=0)}),[]);(0,a.useEffect)((()=>{f&&void 0!==m.current&&f!==m.current&&"user"===b&&D(),m.current=f}),[f,b,D]),(0,a.useEffect)((()=>{const n=e.messages.some((e=>"non-genuine-warning"===e.id));t&&!n?S((e=>[be,...e])):n&&!t&&S((e=>e.filter((e=>"non-genuine-warning"!==e.id))))}),[t,e,S]);const{activeConnections:N,activeWorkspace:M}=L(),T=N.find((e=>{return!(!(t=M)||!t.connectionId||e.id!==M.connectionId);var t}))??null,P=function(e,t){if("submitted"===e)return!0;if("streaming"===e){if(0===t.length)return!0;const e=t[t.length-1];if("user"===e.role)return!0;if(0===e.parts.length)return!0;const n=e.parts[e.parts.length-1];return"step-start"===n.type||!!H(n)||"text"===n.type&&""===n.text.trim()}return!!function(e){return e.some((e=>e.parts.some((e=>!!H(e)&&"running"===F(e.state)))))}(t)}(E,x),O=(0,y.dL)();(0,a.useEffect)((()=>{let t=!1;const n=e.messages.map((e=>{const n=void 0!==e.metadata?.connectionInfo?e.metadata.connectionInfo:T?{id:T.id,name:(0,h.T8)(T)}:null,a=e.parts.filter(H).map((e=>e.toolCallId)).filter(Boolean),r=e.metadata?.registeredToolCallIds??[],i=a.filter((e=>!r.includes(e)));if(n&&i.length>0)for(const e of i)O.setConnectionIdForToolCall({toolCallId:e,connectionId:n.id});const o=void 0===e.metadata?.connectionInfo&&n,s=n&&i.length>0;return o||s?(t=!0,{...e,metadata:{...e.metadata,...o?{connectionInfo:n}:{},...s?{registeredToolCallIds:[...r,...i]}:{}}}):e}));t&&S((()=>n))}),[T,e,S,O]);const j=(0,a.useRef)(c);(0,a.useEffect)((()=>{if(j.current&&!c)for(const t of e.messages)for(const e of t.parts)R(e)&&k({id:e.approval.id,approved:!1});j.current=c}),[c,e,k]);const B=(0,a.useCallback)((async({text:t,metadata:a})=>{const r=t.trim();r&&(await W(e),v?.({text:r,metadata:{sendContext:!0,...a}},{},(({requestId:e,connectionInfo:t})=>{n("Assistant Prompt Submitted",{user_input_length:r.length,request_id:e},t)})))}),[n,v,e]),z=(0,a.useCallback)((({state:e,message:t})=>{if(!e)return;const{rating:a}=e,r="feedback"in e?e.feedback:void 0;n("Assistant Feedback Submitted",{feedback:"liked"===a?"positive":"negative",text:r,request_id:t.metadata?.requestId,source:t.metadata?.source??"chat response"},t.metadata?.connectionInfo??void 0)}),[n]),_=(0,a.useCallback)(((e,t)=>{S((n=>{const a=n.map((n=>n.id===e.id&&n.metadata?.confirmation?{...n,metadata:{...n.metadata,confirmation:{...n.metadata.confirmation,state:t}}}:n));return"confirmed"===t&&a.push({...e,id:`${e.id}-confirmed`,metadata:{...e.metadata,confirmation:void 0}}),a})),n("Assistant Confirmation Submitted",{status:t,source:e.metadata?.source??"chat response",request_id:e.metadata?.requestId},e.metadata?.connectionInfo??void 0),"confirmed"===t&&v?.(void 0,{},(()=>{}))}),[v,S,n]),$=(0,a.useCallback)((({message:e,type:t,approvalId:a,approved:r})=>{k({id:a,approved:r}),n("Assistant Tool Call Approval",{approved:r,type:t,approval_id:a,request_id:e.metadata?.requestId},e.metadata?.connectionInfo??void 0)}),[k,n]),Y=(0,a.useCallback)((async()=>{await W(e)}),[e]),K=(0,a.useCallback)((()=>{u(!0)}),[u]),G=x.filter((e=>!e.metadata?.isSystemContext));return r().createElement("div",{"data-testid":"assistant-chat",className:(0,g.cx)(Ze,i?Je:Qe),style:Xe},r().createElement(Ve,null,r().createElement(Ge,null,r().createElement("div",{"data-testid":"assistant-chat-messages",className:et,ref:p},r().createElement("div",{className:rt},G.map(((e,t)=>{const{id:n,role:a,metadata:i,parts:o}=e,s=new Set,l=[],c=[];for(const e of o)"source-url"===e.type&&e.url&&e.title&&(s.has(e.title)||(s.add(e.title),l.push({children:e.title,href:e.url,variant:"Docs"}))),H(e)&&c.push(e);if(i?.confirmation){const{description:a,state:o}=i.confirmation,s=t===G.length-1;return r().createElement(ce,{key:`${n}-confirmation`,state:s||"pending"!==o?o:"rejected",title:"Please confirm your request",description:a,onConfirm:()=>_(e,"confirmed"),onReject:()=>_(e,"rejected")})}const d=e.metadata?.displayText||e.parts?.filter((e=>"text"===e.type)).map((e=>e.text)).join(""),u="user"===a,p=e.metadata?.connectionInfo??null;return r().createElement(r().Fragment,{key:`${n}-${t}`},c.map(((t,a)=>{const i=t.toolCallId||`${n}-${t.type}`;return r().createElement(ye,{connection:p,key:`${i}-${a}`,toolCall:t,onApprove:n=>$({message:e,type:t.type,approvalId:n,approved:!0}),onDeny:n=>$({message:e,type:t.type,approvalId:n,approved:!1})})})),d&&r().createElement(Ue,{key:`${n}-text`,sourceType:"markdown",isSender:u,messageBody:d,"data-role":e.role,"data-testid":`assistant-message-${n}`},!1===u&&r().createElement(Ue.Actions,{onRatingChange:(t,n)=>z({message:e,state:n}),onSubmitFeedback:(t,n)=>z({message:e,state:n}),className:nt}),l.length>0&&r().createElement(Ue.Links,{className:nt,links:l})))}))),0===x.length&&r().createElement(r().Fragment,null,r().createElement("div",null,r().createElement("div",{className:tt},r().createElement("h4",{className:it},r().createElement(g.Int,{glyph:"Sparkle",size:"large",style:st}),r().createElement("span",null,"MongoDB Assistant")),r().createElement("p",{className:ot},"Welcome to the MongoDB Assistant!",r().createElement("br",null),"Ask any question about MongoDB to receive expert guidance and documentation.")),r().createElement(Ce,{chat:e,onMessageSend:B}),!d&&r().createElement(Ke,{onDismiss:K})))),C&&r().createElement("div",{className:at},r().createElement(g.lZ$,{variant:"danger",dismissible:!0,onClose:w},"An error occurred. Try clearing the chat if the error persists.")),r().createElement(qe,{"data-testid":"assistant-chat-input",onMessageSend:e=>{B({text:e})},state:P?"loading":void 0,textareaProps:lt,onClickStopButton:()=>{Y()}},o&&r().createElement(qe.AdditionalActions,null,r().createElement("div",{className:ct},r().createElement(Oe,null)))))))},ut=(0,g.AHW)({display:"flex",alignItems:"center",justifyContent:"space-between"}),pt=(0,g.AHW)({display:"flex",alignItems:"center",flexWrap:"wrap",transition:"transform 0.16s ease-in","@container (width < 320px)":{"&":{transform:"scale(0.8) translateX(-10%)"}}}),mt=(0,g.AHW)({marginRight:g.YKD[200]}),gt=({appName:e,autoOpen:t,hasNonGenuineConnections:n=!1})=>{const i=(0,a.useContext)(Y),o=(0,I.Fg)("enableAIAssistant"),s=(0,I.Rs)();if(!o||!s)return null;if(!i)throw new Error("CompassAssistantDrawer must be used within an CompassAssistantProvider");return r().createElement(g.TmU,{id:$,title:r().createElement("div",{className:ut},r().createElement("div",{className:pt},r().createElement("span",{className:mt},"MongoDB Assistant")),r().createElement(ht,{chat:i})),label:"MongoDB Assistant",glyph:"Assistant",autoOpen:t,guideCue:{cueId:"assistant-drawer",title:"Introducing MongoDB Assistant",description:`AI-powered assistant to intelligently guide you through your database tasks. Get expert MongoDB help and streamline your workflow directly within ${e}.`,buttonText:"Got it",tooltipAlign:"left",tooltipJustify:"start"}},r().createElement(dt,{chat:i,hasNonGenuineConnections:n}))},ht=({chat:e})=>{const{clearError:t}=ne({chat:e}),n=(0,a.useCallback)((async()=>{await(0,g.$TK)({title:"Clear this chat?",description:"The current chat will be cleared, and chat history will not be retrievable.",buttonText:"Clear chat",variant:"danger","data-testid":"assistant-confirm-clear-chat-modal"})&&(await W(e),t(),e.id=e.generateId(),e.messages=e.messages.filter((e=>e.metadata?.isPermanent)))}),[t,e]);return 0===e.messages.filter((e=>!e.metadata?.isPermanent)).length?null:r().createElement(g.m_M,{trigger:r().createElement(g.K0,{onClick:()=>{n()},title:"Clear chat","aria-label":"Clear chat","aria-hidden":!0,"data-testid":"assistant-clear-chat"},r().createElement(g.Int,{glyph:"Eraser"}))},"Clear chat")}},22007:(e,t,n)=>{n.d(t,{M:()=>f});var a=n(96652),r=n.n(a),i=n(44142),o=n(62183),s=n(44457),l=n(91399),c=n(17855),d=n(51295),u=n(34426);function p(e){const t=[];for(const n of e.values())t.push({address:n.address,type:n.type,tags:n.tags});return t}function m(e){if(e)return{type:e.type,servers:p(e.servers),setName:e.setName}}var g=n(60783),h=n(20625);const f=(0,o.nk)({name:"CompassInstanceStore",component:function({children:e,instancesManager:t}){return r().createElement(s.r$.Provider,{value:t},e)},activate(e,{connections:t,logger:n,preferences:a,globalAppRegistry:r},i){const o=function({globalAppRegistry:e,connections:t,logger:{log:n,mongoLogId:a},preferences:r},{on:i,cleanup:o,addCleanup:s}){const p=new u._,g=async({connectionId:e}={})=>{try{if(!e)throw new Error("No connectionId provided");const n=p.getMongoDBInstanceForConnection(e),a=t.getDataServiceForConnection(e);await n.fetchDatabases({dataService:a}),await Promise.all(n.databases.map((e=>e.fetchCollections({dataService:a}))))}catch(t){n.warn(a(1001000324),"Instance Store","Failed to respond to fetch all collections",{message:t.message,connectionId:e})}},h=async(e={},{connectionId:r}={})=>{try{if(!r)throw new Error("No connectionId provided");const n=p.getMongoDBInstanceForConnection(r),a=t.getDataServiceForConnection(r);await n.refresh({dataService:a,...e})}catch(t){if(n.warn(a(1001000295),"Instance Store","Failed to refresh instance",{message:t.message,connectionId:r,isFirstRun:e.firstRun}),e.firstRun){const{name:e,message:n}=t;(0,d.c3r)("instance-refresh-failed",{title:"Failed to retrieve server info",description:`${e}: ${n}`,variant:"important"})}}},f=async({connectionId:e}={})=>{try{if(!e)throw new Error("No connectionId provided in the event parameters");const n=p.getMongoDBInstanceForConnection(e),a=t.getDataServiceForConnection(e);await n.fetchDatabases({dataService:a,force:!0}),await Promise.allSettled(n.databases.map((e=>e.fetchCollections({dataService:a,force:!0}))))}catch(t){n.warn(a(1001000296),"Instance Store","Failed to refresh databases",{message:t.message,connectionId:e})}},y=async({ns:e},{connectionId:r}={})=>{try{if(!r)throw new Error("No connectionId provided in the event parameters");const n=p.getMongoDBInstanceForConnection(r),a=t.getDataServiceForConnection(r),{database:i}=(0,c.Ay)(e),o=n.databases.get(i),s=o?.collections.get(e);await Promise.allSettled([o?.fetch({dataService:a,force:!0}),s?.fetch({dataService:a,force:!0})])}catch(e){n.warn(a(1001000319),"Instance Store","Failed to refresh databases",{message:e.message,connectionId:r})}},b=async(e,{connectionId:r}={})=>{try{if(!r)throw new Error("connectionId not provided");const n=p.getMongoDBInstanceForConnection(r),a=t.getDataServiceForConnection(r),{database:i}=(0,c.Ay)(e),o=n.databases.get(i)??n.databases.add({_id:i,name:i});let s=!1,l=o.collections.get(e,"_id");l||(s=!0,l=o.collections.add({_id:e})),await o.fetch({dataService:a,force:!0}).then((()=>l?.fetch({dataService:a,force:!0,fetchInfo:s}))).catch((()=>{}))}catch(e){n.warn(a(1001000320),"Instance Store","Failed to refresh collection model",{message:e.message,connectionId:r})}};return r.onPreferenceValueChanged("enableDbAndCollStats",(e=>{e&&Array.from(p.listMongoDBInstances().keys()).forEach((e=>{h({fetchDbStats:!0},{connectionId:e})}))})),r.onPreferenceValueChanged("inferNamespacesFromPrivileges",(()=>{const e=Array.from(p.listMongoDBInstances().keys());for(const t of e)f({connectionId:t})})),i(t,"disconnected",(function(e){try{p.getMongoDBInstanceForConnection(e).removeAllListeners()}catch(t){n.warn(a(1001000322),"Instance Store","Failed to remove instance listeners upon disconnect",{message:t.message,connectionId:e})}p.removeMongoDBInstanceForConnection(e)})),i(t,"connected",(function(e,n,a){const o=t.getDataServiceForConnection(e),l=o.getConnectionString().hosts[0]||"",[c,d]=l.startsWith("[")?l.slice(1).split("]"):l.split(":"),u={...a,status:"ready",statusError:null,_id:l,hostname:c,port:d?+d:void 0,topologyDescription:m(o.getLastSeenTopology()),preferences:r},g=p.createMongoDBInstanceForConnection(e,u);s((()=>{g.removeAllListeners()})),h({fetchDatabases:!0,fetchDbStats:!0,firstRun:!0},{connectionId:e}),i(o,"topologyDescriptionChanged",(({newDescription:e})=>{g.set({topologyDescription:m(e)})}))})),i(e,"sidebar-expand-database",((e,{connectionId:r}={})=>{try{if(!r)throw new Error("connectionId is not provided");const n=p.getMongoDBInstanceForConnection(r),a=t.getDataServiceForConnection(r);n.databases.get(e)?.fetchCollections({dataService:a})}catch(e){n.warn(a(1001000323),"Instance Store","Failed to respond to sidebar-expand-database",{message:e.message,connectionId:r})}})),i(e,"sidebar-filter-navigation-list",(()=>{const e=Array.from(p.listMongoDBInstances().keys());for(const t of e)g({connectionId:t})})),i(e,"refresh-data",(e=>{for(const[t]of p.listMongoDBInstances())h(e,{connectionId:t})})),i(e,"database-dropped",((e,{connectionId:t}={})=>{try{if(!t)throw new Error("No connectionId provided in event parameters");const n=p.getMongoDBInstanceForConnection(t).databases.remove(e);n&&l.MongoDBInstance.removeAllListeners(n)}catch(e){n.warn(a(1001000325),"Instance Store","Failed to respond to database-dropped",{message:e.message,connectionId:t})}})),i(e,"collection-dropped",((e,{connectionId:r}={})=>{try{if(!r)throw new Error("No connectionId provided in event parameters");const n=p.getMongoDBInstanceForConnection(r),a=t.getDataServiceForConnection(r),{database:i}=(0,c.Ay)(e),o=n.databases.get(i),s=o?.collections.get(e,"_id");if(!o||!s)return;1===o.collections.length?(n.databases.remove(o),l.MongoDBInstance.removeAllListeners(o)):(o.collections.remove(s),l.MongoDBInstance.removeAllListeners(s),o?.fetch({dataService:a,force:!0}).catch((()=>{})))}catch(e){n.warn(a(1001000317),"Instance Store","Failed to respond to collection-dropped",{message:e.message,connectionId:r})}})),i(e,"refresh-databases",f),i(e,"collection-renamed",(({from:e,to:t},{connectionId:r}={})=>{try{if(!r)throw new Error("No connectionId provided in the event parameters");const n=p.getMongoDBInstanceForConnection(r),{database:a,collection:i}=(0,c.Ay)(e);n.databases.get(a)?.collections.get(i,"name")?.set({_id:t})}catch(e){n.warn(a(1001000318),"Instance Store","Failed to respond to collection-renamed",{message:e.message,connectionId:r})}})),i(e,"document-deleted",y),i(e,"documents-deleted",y),i(e,"document-inserted",y),i(e,"documents-refreshed",y),i(e,"import-finished",y),i(e,"collection-created",b),i(e,"view-created",b),i(e,"agg-pipeline-out-executed",((e,{connectionId:t}={})=>{e&&b(e,{connectionId:t})})),i(e,"view-edited",((e,{connectionId:r}={})=>{try{if(!r)throw new Error("No connectionId provided in the event parameters");const n=p.getMongoDBInstanceForConnection(r),a=t.getDataServiceForConnection(r),{database:i}=(0,c.Ay)(e);n.databases.get(i)?.collections.get(e,"_id")?.fetch({dataService:a,force:!0})}catch(e){n.warn(a(1001000321),"Instance Store","Failed to respond to view-edited",{message:e.message,connectionId:r})}})),{state:{instancesManager:p},getState:()=>({instancesManager:p}),deactivate:o}}({connections:t,logger:n,preferences:a,globalAppRegistry:r},i);return{store:o,deactivate:()=>{o.deactivate()}}}},{logger:(0,i.fF)("COMPASS-INSTANCE-STORE"),preferences:h.fx,connections:g.u4})},23412:(e,t,n)=>{n.d(t,{w:()=>be}),n(95039);var a=n(96652),r=n.n(a),i=n(35115);const o=1/0,s=1/0;var l=n(60783);function c(e){return"placeholder"===e.type?"":"connection"===e.type?e.connectionInfo.id:e.connectionId}function d({connections:e,expandedItems:t={},preferencesReadOnly:n,preferencesReadWrite:a,preferencesShellEnabled:r}){return e.flatMap(((i,c)=>i.connectionStatus===l.vk.Connected?(({connection:{connectionInfo:e,connectionStatus:t,name:n,databases:a,databasesStatus:r,databasesLength:i,isPerformanceTabAvailable:l,isPerformanceTabSupported:c,isDataLake:d,isWritable:u,isGenuineMongoDB:p,csfleMode:m},connectionIndex:g,connectionsLength:h,expandedItems:f={},preferencesReadOnly:y,preferencesReadWrite:b,preferencesShellEnabled:v})=>{const x=!!f[e.id],E=e.favorite?.color,C=y||d||!u,w={id:e.id,level:1,name:n,type:"connection",setSize:h,posInSet:g+1,isExpanded:x,isExpandable:!0,colorCode:E,connectionInfo:e,connectionStatus:t,isPerformanceTabAvailable:l,isPerformanceTabSupported:c,hasWriteActionsDisabled:C,isShellEnabled:v,isGenuineMongoDB:p,csfleMode:m},I=[w];if(!x)return I;const S=["ready","refreshing","error"].includes(r),A=Math.max(Math.min(i,s),5);return S?I.concat(a.flatMap(((t,n)=>(({database:{_id:e,name:t,collections:n,collectionsLength:a,collectionsStatus:r,inferredFromPrivileges:i},connectionId:s,connectionItem:l,expandedItems:c={},level:d,colorCode:u,databaseIndex:p,databasesLength:m,hasWriteActionsDisabled:g,canDeleteDatabase:h,canEditCollection:f})=>{const y=!!c[e],b={id:`${s}.${e}`,level:d,name:t,type:"database",setSize:m,posInSet:p+1,isExpanded:y,colorCode:u,connectionId:s,connectionItem:l,dbName:e,isExpandable:!0,hasWriteActionsDisabled:g,inferredFromPrivileges:i,canDeleteDatabase:h},v=[b];if(!y)return v;const x=["ready","refreshing","error"].includes(r),E=Math.min(a,o);return x?v.concat(n.map((({_id:e,name:t,type:n,inferredFromPrivileges:r},i)=>({id:`${s}.${e}`,level:d+1,name:t,type:n,setSize:a,posInSet:i+1,colorCode:u,connectionId:s,databaseItem:b,namespace:e,hasWriteActionsDisabled:g,isExpandable:!1,inferredFromPrivileges:r,canEditCollection:f})))):v.concat(Array.from({length:E},((t,n)=>({level:d+1,type:"placeholder",colorCode:u,id:`${s}.${e}.placeholder.${n}`}))))})({connectionId:e.id,connectionItem:w,database:t,expandedItems:f[e.id]||{},level:2,colorCode:E,databasesLength:i,databaseIndex:n,hasWriteActionsDisabled:C,canDeleteDatabase:!b,canEditCollection:!b})))):I.concat(Array.from({length:A},((t,n)=>({level:2,type:"placeholder",colorCode:E,id:`${e.id}.placeholder.${n}`}))))})({connection:i,expandedItems:t,connectionIndex:c,connectionsLength:e.length,preferencesReadOnly:n,preferencesReadWrite:a,preferencesShellEnabled:r}):(({connection:{name:e,connectionInfo:t,connectionStatus:n},connectionIndex:a,connectionsLength:r})=>[{id:t.id,level:1,name:e,type:"connection",setSize:r,posInSet:a+1,colorCode:t.favorite?.color,connectionInfo:t,connectionStatus:n,isExpandable:!0}])({connection:i,connectionsLength:e.length,connectionIndex:c})))}var u=n(55712),p=n(51295);function m(e){return"type"in e&&"placeholder"===e.type}function g(e,t,n,a=0){for(let r=e+1,i=t.length;r<i;r++){const e=t[(r+a)%i];if(!m(e)&&(!n||n(e)))return e}return null}function h(e,t,n,a=0){const r=t.length;for(let i=e-1;i>=0;i--){const e=t[(i+a)%r];if(!m(e)&&(!n||n(e)))return e}return null}function f(e){return g(-1,e)}var y=n(87903);const b=(0,p.AHW)({flex:"1 0 auto"});function v({dataTestId:e,activeItemId:t,items:n,width:i,height:o,itemHeight:s,getItemKey:l,renderItem:c,onDefaultAction:d,onItemExpand:v,onItemAction:E,getItemActions:C,getContextMenuGroups:w,__TEST_OVER_SCAN_COUNT:I}){const S=(0,a.useRef)(null),A=function(e){const t=(0,p.HIF)(e);return(0,a.useMemo)((()=>e=>t.current(e)),[t])}(c),k=(0,a.useCallback)((e=>{const t=n.findIndex((t=>!m(t)&&t.id===e.id));t>=0&&S.current?.scrollToItem(t)}),[n]),[D,N,M]=function({items:e,activeItemId:t,onExpandedChange:n,onFocusMove:r=()=>{}}){const i=(0,a.useRef)(null),o=t||f(e)?.id,[s,l]=(0,a.useState)(o),[c,d]=(0,a.useState)(0),[u,y]=(0,p.$vP)(),b=(0,a.useCallback)((e=>{i.current?.querySelector(`[role="treeitem"][data-id="${e}"]`)?.focus()}),[i]);(0,p.wTI)((()=>{l(o)}),[o]),(0,p.wTI)((()=>{y===p.X1w.NoFocus?d(0):d(-1)}),[y]),(0,a.useEffect)((()=>{if(y===p.X1w.FocusVisible){const t=g(-1,e,(e=>e.id===s));if(t)return r(t),(0,p.Rbc)((()=>{b(t.id)}))}}),[s,b,y,e,r]);const v=(0,a.useCallback)((t=>{const a=t.target;if("treeitem"!==a.getAttribute("role"))return;const i=a.dataset.id;if(!i)throw new Error("treeitems should have data-id attribute provided to work correctly");const o=g(-1,e,(e=>e.id===i));if(!o)throw new Error("key event caught on an item that is not part of the items list");const s=e.indexOf(o);let c=null;if("Home"===t.key&&(t.stopPropagation(),c=f(e)),"End"===t.key&&(t.stopPropagation(),c=function(e){return h(e.length,e)}(e)),"ArrowDown"===t.key&&(t.preventDefault(),t.stopPropagation(),c=g(s,e)),"ArrowUp"===t.key&&(t.preventDefault(),t.stopPropagation(),c=h(s,e)),"ArrowRight"===t.key&&(t.stopPropagation(),o.isExpandable&&!1===o.isExpanded&&n(o,!0),o.isExpandable&&!0===o.isExpanded)){const t=g(s,e);t?.level===o.level+1&&(c=t)}if("ArrowLeft"===t.key&&(t.stopPropagation(),o.isExpandable&&!0===o.isExpanded?n(o,!1):c=function(e,t,n){return h(t,n,(t=>t.level===e.level-1))}(o,s,e)),"*"===t.key){t.stopPropagation();const a=function(e,t,n){const a=[e];for(let r=t-1;r>=0;r--){const t=n[r];if(!m(t)&&(t.level===e.level&&a.push(t),t.level===e.level-1))break}for(let r=t+1,i=n.length;r<i;r++){const t=n[r];if(!m(t)&&(t.level===e.level&&a.push(t),t.level===e.level-1))break}return a}(o,s,e);for(const e of a)o.isExpandable&&!1===e.isExpanded&&n(e,!0)}if(/^\p{Letter}$/u.test(t.key)){t.stopPropagation();const n=t.key.toLocaleLowerCase();c=g(0,e,(e=>e.name.toLocaleLowerCase().startsWith(n)),s)}if(c&&c!==o){const e=c.id;r(c),l(e),requestAnimationFrame((()=>{b(e)}))}}),[n,r,b,e]),x={ref:i,tabIndex:c,onKeyDown:v,...u},E=y===p.X1w.FocusWithinVisible;return[x,s,E]}({items:n,activeItemId:t,onExpandedChange:v,onFocusMove:k}),T=(0,p.BiT)(),P=(0,a.useMemo)((()=>({items:n,currentTabbable:N,isTreeItemFocused:M,activeItemId:t,renderItem:A,onDefaultAction:d,onItemAction:E,onItemExpand:v,getItemActions:C,getContextMenuGroups:w})),[n,A,N,d,t,M,E,C,v,w]),L=(0,a.useCallback)(((e,t)=>l?l(t.items[e]):e),[l]);return r().createElement("div",(0,u.A)({"data-testid":e,role:"tree","aria-labelledby":T,className:b},D),r().createElement(y.Y1,{ref:S,width:i,height:o,itemData:P,itemCount:n.length,itemSize:s,itemKey:L,overscanCount:I??5},x))}function x({index:e,data:t,style:n}){const{renderItem:i,items:o,activeItemId:s}=t,l=(0,a.useMemo)((()=>o[e]),[o,e]),c=(0,p.ogd)(),d=(0,a.useMemo)((()=>i({index:e,item:l,isActive:!m(l)&&l.id===s,isFocused:t.isTreeItemFocused&&!m(l)&&l.id===t.currentTabbable,onItemAction:t.onItemAction,onItemExpand:t.onItemExpand,getItemActions:t.getItemActions,getContextMenuGroups:t.getContextMenuGroups})),[i,e,l,s,t.currentTabbable,t.isTreeItemFocused,t.onItemAction,t.getItemActions,t.onItemExpand,t.getContextMenuGroups]),g=function(e,t){return{onClick:(0,a.useCallback)((n=>{n.stopPropagation(),t(e,n)}),[t,e]),onKeyDown:(0,a.useCallback)((n=>{n.target===n.currentTarget&&[" ","Enter"].includes(n.key)&&(n.preventDefault(),n.stopPropagation(),t(e,n))}),[t,e])}}(l,t.onDefaultAction);if(m(l))return r().createElement("div",{style:n},d);const h=(0,p.v63)({role:"treeitem","aria-level":l.level,"aria-setsize":l.setSize,"aria-posinset":l.posInSet,"aria-expanded":!!l.isExpanded,tabIndex:t.currentTabbable===l.id?0:-1},g,c,{style:n});return r().createElement("div",(0,u.A)({"data-id":l.id,"data-testid":l.id},h),d)}const E=({level:e,isExpandable:t})=>{const n=p.YKD[400],a=p.YKD[400]+p.YKD[50];return{paddingLeft:n+(t?0:a)+(e-1)*a}},C=(0,p.AHW)({display:"flex",alignItems:"center",height:28,backgroundColor:"var(--item-bg-color)",color:"var(--item-color)"}),w={gradientStart:"var(--item-bg-color-active)",gradientEnd:"var(--item-bg-color)",style:{filter:"brightness(0.98)"}},I=({level:e,style:t})=>{const n=(0,a.useMemo)((()=>E({level:e,isExpandable:!1})),[e]);return r().createElement("div",{className:C,style:{...t,...n}},r().createElement(p.OrA,w))};(0,p.AHW)({maskImage:"linear-gradient(to bottom, black 30%, transparent 95%)"});var S=n(34615),A=n(20625);function k({item:e,children:t}){const n=!!(0,A.Fg)("showDisabledConnections"),i=(0,p.D27)(),{connectionColorToHex:o,connectionColorToHexActive:s}=(0,S.DM)(),{colorCode:d}=e,u=(0,a.useMemo)((()=>i?p.MFm.gray.light1:p.MFm.gray.dark1),[i]),m=(0,l._j)(),g=(0,a.useMemo)((()=>{const t={},a=c(e),r=!n||m(a),i="connection"===e.type&&"connected"!==e.connectionStatus,l=("database"===e.type||"collection"===e.type)&&e.inferredFromPrivileges;return d&&d!==S._E&&(t["--item-bg-color"]=o(d),t["--item-bg-color-hover"]=s(d),t["--item-bg-color-active"]=s(d)),(i||l||!r)&&(t["--item-color"]=u),!l&&r||(t["--item-color-active"]=u),t}),[u,e,d,m,n,o,s]);return r().createElement("div",{style:g},t)}const D=(0,p.AHW)({padding:0,margin:0,background:"none",border:"none"}),N=(0,p.AHW)({display:"flex",transition:"transform .16s linear",transform:"rotate(0deg)",minWidth:p.YKD[400],height:p.YKD[400],alignItems:"center",justifyContent:"center"}),M=(0,p.AHW)({transform:"rotate(90deg)"}),T=(0,p.AHW)({cursor:"pointer"}),P=({onClick:e,isExpanded:t,disabled:n=!1})=>r().createElement("button",{type:"button",tabIndex:-1,onClick:e,className:(0,p.cx)(D,N,{[M]:t,[T]:!n}),disabled:n},r().createElement(p.Int,{width:14,height:14,glyph:"CaretRight",size:"small"})),L=(0,p.AHW)({width:"240px",maxHeight:"unset",marginLeft:"auto"}),O=(0,p.AHW)({color:"var(--item-color)",backgroundColor:"var(--item-bg-color)",'&[data-is-active="true"] .item-wrapper':{fontWeight:600,color:"var(--item-color-active)",backgroundColor:"var(--item-bg-color-active)"},'&:hover:not([data-is-active="true"]) .item-wrapper':{backgroundColor:"var(--item-bg-color-hover)"},svg:{flexShrink:0}}),R=(0,p.AHW)({cursor:"pointer"}),H=(0,p.AHW)({display:"flex",height:28,alignItems:"center",paddingRight:p.YKD[400],gap:p.YKD[50]}),F=(0,p.AHW)({width:"100%",display:"flex",gap:p.YKD[150],overflow:"hidden",alignItems:"center","& span":{overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},fontSize:"12px"}),W=(0,p.AHW)({display:"flex",marginLeft:"auto",alignItems:"center",gap:p.YKD[100]}),j=({state:e})=>{const t="CREATING"===e?p.xUU.Blue:"DELETED"===e?p.xUU.Red:p.xUU.LightGray,n="DELETING"===e?"TERMINATING":"DELETED"===e?"TERMINATED":e;return r().createElement(p.Exy,{variant:t,"data-testid":"navigation-item-state-badge"},n)},B=({item:e})=>{const t=(0,p.D27)(),n=e.connectionInfo.atlasMetadata?.clusterState;return"PAUSED"===n?r().createElement(p.m_M,{enabled:!0,darkMode:t,trigger:({children:e,...t})=>r().createElement("div",t,r().createElement(j,{state:n}),e)},r().createElement(p.nBu,null,"Unpause your cluster to connect to it")):"DELETING"===n||"CREATING"===n||"DELETED"===n?r().createElement(j,{state:n}):null},z=r().forwardRef((function({item:e,isActive:t,actionProps:n,name:a,style:i,icon:o,dataAttributes:s,isExpandVisible:l,isExpandDisabled:c,isExpanded:d,isFocused:m,hasDefaultAction:g,toggleExpand:h,children:f},y){const[b,v]=(0,p.v69)();return r().createElement("div",(0,u.A)({ref:y,"data-testid":"base-navigation-item",className:(0,p.cx)(O,{[R]:g})},b,s),r().createElement("div",{className:(0,p.cx)("item-wrapper",H),style:i},l&&r().createElement(P,{onClick:e=>{e.stopPropagation(),h()},isExpanded:d,disabled:c}),r().createElement("div",{className:F},o,r().createElement("span",{title:a},a)),"connection"===e.type&&r().createElement(B,{item:e}),r().createElement("div",{className:W},r().createElement(p.eDW,(0,u.A)({menuClassName:L,isVisible:t||v||m,"data-testid":"sidebar-navigation-item-actions",iconSize:"xsmall"},n)),f)))})),_=p.i7C`
9
+ 0% {
10
+ transform: rotate(0deg);
11
+ }
12
+ 100% {
13
+ transform: rotate(360deg);
14
+ }
15
+ `,$=p.AHW`
16
+ animation: ${_} 1.5s linear infinite;
17
+ `,Y=(0,p.AHW)({width:p.YKD[200],height:p.YKD[200]});function K(){return r().createElement("div",{className:Y})}const G={connected:function(){return r().createElement("svg",{width:p.YKD[200],height:p.YKD[200],viewBox:"0 0 8 8",fill:"none",xmlns:"http://www.w3.org/2000/svg"},r().createElement("circle",{cx:"4.25",cy:"4.25",r:"3.5",fill:p.MFm.green.dark1}))},connecting:function(){return r().createElement("svg",{className:$,width:p.YKD[200],height:p.YKD[200],viewBox:"0 0 8 8",fill:"none",xmlns:"http://www.w3.org/2000/svg"},r().createElement("rect",{width:"8",height:"8",rx:"4",fill:"#F9FBFA"}),r().createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M1.64712 6.14088C1.79974 6.34283 2.09302 6.34006 2.27132 6.16038C2.44962 5.9807 2.44376 5.69245 2.30279 5.48221C2.0538 5.1109 1.91667 4.67113 1.91667 4.20833C1.91667 2.94268 2.94268 1.91667 4.20833 1.91667C4.74833 1.91667 5.25651 2.10387 5.65961 2.4344C5.85535 2.5949 6.14175 2.62823 6.33763 2.4679C6.53351 2.30757 6.56426 2.0159 6.37782 1.84468C5.80668 1.32018 5.0449 1 4.20833 1C2.43642 1 1 2.43642 1 4.20833C1 4.93399 1.24091 5.60338 1.64712 6.14088Z",fill:p.MFm.green.dark1}))},failed:function(){return r().createElement("svg",{width:p.YKD[200],height:p.YKD[200],viewBox:"0 0 7 6",fill:"none",xmlns:"http://www.w3.org/2000/svg"},r().createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M3.62796 0.412185C3.46455 0.112605 3.03545 0.112605 2.87204 0.412185L0.240953 5.23572C0.0839275 5.5236 0.291686 5.875 0.618909 5.875H5.88109C6.20831 5.875 6.41607 5.5236 6.25905 5.23572L3.62796 0.412185ZM2.8125 1.9375C2.8125 1.69588 3.00838 1.5 3.25 1.5C3.49162 1.5 3.6875 1.69588 3.6875 1.9375V3.6875C3.6875 3.92912 3.49162 4.125 3.25 4.125C3.00838 4.125 2.8125 3.92912 2.8125 3.6875V1.9375ZM3.6875 5C3.6875 5.24162 3.49162 5.4375 3.25 5.4375C3.00838 5.4375 2.8125 5.24162 2.8125 5C2.8125 4.75838 3.00838 4.5625 3.25 4.5625C3.49162 4.5625 3.6875 4.75838 3.6875 5Z",fill:p.MFm.red.base}))},disconnected:K,initial:K,canceled:K},V=(0,p.AHW)({position:"relative",display:"flex"}),U=(0,p.AHW)({position:"absolute",display:"flex",right:"0px",bottom:"0px"});function q({status:e,children:t}){const n=G[e];return r().createElement("div",{className:V},t,r().createElement("span",{className:U},r().createElement(n,null)))}var Z=n(29603);const J="Your privileges grant you access to this namespace, but it might not currently exist",Q=(0,p.AHW)({display:"flex"}),X=({text:e,glyph:t})=>r().createElement(p.m_M,{align:"bottom",justify:"start",trigger:r().createElement("div",{className:Q},r().createElement(p.Int,{glyph:t}))},e),ee=({item:e})=>{if("database"===e.type)return e.inferredFromPrivileges?r().createElement(X,{text:J,glyph:"EmptyDatabase"}):r().createElement(p.Int,{glyph:"Database"});if("collection"===e.type)return e.inferredFromPrivileges?r().createElement(X,{text:J,glyph:"EmptyFolder"}):r().createElement(p.Int,{glyph:"Folder"});if("view"===e.type)return r().createElement(p.Int,{glyph:"Visibility"});if("timeseries"===e.type)return r().createElement(p.Int,{glyph:"TimeSeries"});if("connection"===e.type){const t=e.connectionInfo.atlasMetadata?.clusterState;return"DELETING"===t||"CREATING"===t?r().createElement(q,{status:"disconnected"},r().createElement(p.Int,{glyph:"Refresh"})):"PAUSED"===t||"DELETED"===t?r().createElement(q,{status:"disconnected"},r().createElement(p.RR9,null)):"favorite"===e.connectionInfo.savedConnectionType?r().createElement(q,{status:e.connectionStatus},r().createElement(p.Int,{glyph:"Favorite"})):(0,Z.M8)(e.connectionInfo.connectionOptions.connectionString)?r().createElement(q,{status:e.connectionStatus},r().createElement(p.Int,{glyph:"Laptop"})):r().createElement(q,{status:e.connectionStatus},r().createElement(p.RR9,null))}return null},te=(0,p.AHW)({color:p.MFm.yellow.dark2,background:p.MFm.yellow.light3,border:`1px solid ${p.MFm.yellow.light2}`,"&:focus":{color:p.MFm.yellow.dark2},"&:focus::before":{background:p.MFm.yellow.light3},"&:hover":{color:p.MFm.yellow.dark2},"&:hover::before":{background:p.MFm.yellow.light3}}),ne=(0,p.AHW)({color:p.MFm.yellow.light2,background:p.MFm.yellow.dark3,border:`1px solid ${p.MFm.yellow.dark2}`,"&:focus":{color:p.MFm.yellow.light2},"&:focus::before":{background:p.MFm.yellow.dark3},"&:hover":{color:p.MFm.yellow.light2},"&:hover::before":{background:p.MFm.yellow.dark3}}),ae=(0,p.AHW)({color:p.MFm.gray.dark1,background:p.MFm.gray.light3,border:`1px solid ${p.MFm.gray.light2}`,"&:focus":{color:p.MFm.gray.dark1},"&:focus::before":{background:p.MFm.gray.light3},"&:hover":{color:p.MFm.gray.dark1},"&:hover::before":{background:p.MFm.gray.light3}}),re=(0,p.AHW)({color:p.MFm.gray.light3,background:p.MFm.gray.dark1,border:`1px solid ${p.MFm.gray.base}`,"&:focus":{color:p.MFm.gray.light3},"&:focus::before":{background:p.MFm.gray.dark1},"&:hover":{color:p.MFm.gray.light3},"&:hover::before":{background:p.MFm.gray.dark1}});function ie({item:e,isActive:t,isFocused:n,onItemAction:i,onItemExpand:o,getItemActions:s,getContextMenuGroups:c}){const d=(0,p.D27)(),u=(0,a.useCallback)((t=>{"placeholder"!==e.type&&i(e,t)}),[e,i]),m=(0,a.useMemo)((()=>E(e)),[e]),g=(0,a.useMemo)((()=>{const{actions:t,config:n}=s(e);return{actions:t,onAction:u,..."number"==typeof n?.collapseAfter&&{collapseAfter:n?.collapseAfter},..."database"===e.type&&{collapseToMenuThreshold:3}}}),[s,e,u]),h=(0,p.MdH)((()=>c(e)),[e,c]),f=(0,a.useMemo)((()=>"placeholder"===e.type?{}:"connection"===e.type?{"data-is-active":t.toString(),"data-connection-id":e.connectionInfo.id,"data-connection-name":e.name,"data-is-connected":("connected"===e.connectionStatus).toString()}:"database"===e.type?{"data-is-active":t.toString(),"data-connection-id":e.connectionId,"data-database-name":e.dbName}:{"data-is-active":t.toString(),"data-connection-id":e.connectionId,"data-namespace":e.namespace}),[e,t]),y=(0,a.useMemo)((()=>{if("connection"!==e.type||e.connectionStatus!==l.vk.Connected)return[];const t=[];return e.isGenuineMongoDB||t.push({action:"open-non-genuine-mongodb-modal",label:"Non-Genuine MongoDB",tooltip:"Non-Genuine MongoDB detected",icon:"Warning",className:(0,p.cx)(te,{[ne]:d})}),e.csfleMode&&"unavailable"!==e.csfleMode&&t.push({action:"open-csfle-modal",label:"In-Use Encryption",tooltip:"Configure In-Use Encryption",icon:"enabled"===e.csfleMode?"Lock":"Unlock",className:(0,p.cx)(ae,{[re]:d})}),t}),[e,d]),b=(0,a.useCallback)((()=>{"placeholder"!==e.type&&o(e,!e.isExpanded)}),[o,e]);return r().createElement(k,{item:e},"placeholder"===e.type?r().createElement(I,{level:e.level}):r().createElement(z,{ref:h,item:e,isActive:t,isFocused:n,isExpanded:!!e.isExpanded,hasDefaultAction:"connection"!==e.type||"connected"===e.connectionStatus,icon:r().createElement(ee,{item:e}),name:e.name,style:m,dataAttributes:f,isExpandVisible:e.isExpandable,isExpandDisabled:"connection"===e.type&&"connected"!==e.connectionStatus,toggleExpand:b,actionProps:g},!!y.length&&r().createElement(p.eDW,{iconSize:"xsmall",actions:y,onAction:u,collapseAfter:y.length})))}const oe=(0,p.AHW)({minWidth:"max-content"}),se=(0,a.forwardRef)((function({action:e,glyph:t,...n},a){return r().createElement(p.Drp,(0,u.A)({as:"button","data-action":e,className:oe,glyph:r().createElement(p.Int,{glyph:t})},n,{ref:a}))}));function le({setHidable:e,action:t,tooltip:n,label:i,iconSize:o,iconStyle:s,isDisabled:l,onClick:c,className:d,"data-testid":u}){const[m,g]=(0,a.useState)(!1);return(0,a.useEffect)((()=>{e&&e(!m)}),[e,m]),r().createElement(p.fkD,{key:t,title:n?void 0:i,label:i,size:o,"data-action":t,"data-testid":u,onClick:c,className:d,style:s,disabled:l,renderDarkMenu:!1,darkMode:!1,open:m,setOpen:g,triggerAriaLabel:"see more connection options",menuItems:[r().createElement(se,{key:"connection-connect",action:"connection-connect",glyph:"Connect",onClick:c},"Connect"),r().createElement(se,{key:"connection-connect-in-new-window",action:"connection-connect-in-new-window",glyph:"OpenNewTab",onClick:c},"In New Window")]},i)}function ce(e){if((0,A.Fg)("enableConnectInNewWindow"))return r().createElement(le,e);{const{action:t,tooltip:n,label:a,iconSize:i,iconStyle:o,isDisabled:s,onClick:l,className:c,"data-testid":d}=e;return r().createElement(p.$nd,{key:t,title:n?void 0:a,size:i,"data-action":t,"data-testid":d,onClick:l,className:c,style:o,disabled:s},a)}}function de(e){return e.filter((e=>null!==e))}se.displayName="MenuItem";const ue=({connectionInfo:e})=>{const t=!!e.atlasMetadata;return de([t?null:{action:"edit-connection",label:"Edit connection",icon:"Edit",disabledDescription:"Cannot edit an active connection"},t?{action:"show-connect-via-modal",label:"Connect via …",icon:"Connect"}:{action:"copy-connection-string",label:"Copy connection string",icon:"Copy"},t?null:{action:"connection-toggle-favorite",label:"favorite"===e.savedConnectionType?"Unfavorite connection":"Favorite connection",icon:"Favorite"},t?null:{action:"duplicate-connection",label:"Duplicate connection",icon:"Clone"},t?null:{action:"remove-connection",label:"Remove connection",icon:"Trash",variant:"destructive"}])},pe=({connectionInfo:e,connectionStatus:t})=>{const n=ue({connectionInfo:e});return"connecting"===t?n:[{action:"connection-connect",label:"Connect",icon:"Connect",expandedAs:ce},...n]},me=({hasWriteActionsDisabled:e,canDeleteDatabase:t})=>e?[]:de([{action:"create-collection",icon:"Plus",label:"Create collection"},t?{action:"drop-database",icon:"Trash",label:"Drop database"}:null]),ge=({hasWriteActionsDisabled:e,canEditCollection:t,type:n,isRenameCollectionEnabled:a})=>{const r=[{action:"open-in-new-tab",label:"Open in new tab",icon:"OpenNewTab"}];return e?de(r):"view"===n?(r.push({separator:!0}),r.push({action:"duplicate-view",label:"Duplicate view",icon:"Copy"},t?{action:"modify-view",label:"Modify view",icon:"Edit"}:null,t?{action:"drop-collection",label:"Drop view",icon:"Trash"}:null),de(r)):("timeseries"!==n&&t&&a&&(r.push({separator:!0}),r.push({action:"rename-collection",label:"Rename collection",icon:"Edit"})),t&&r.push({action:"drop-collection",label:"Drop collection",icon:"Trash"}),de(r))},he=({isPerformanceTabAvailable:e,isPerformanceTabSupported:t,isAtlas:n,isShellEnabled:a,hasWriteActionsDisabled:r,connectionInfo:i})=>de([...r||!i?[]:[...ue({connectionInfo:i}),{separator:!0}],a?{action:"open-shell",icon:"Shell",label:"Open MongoDB shell"}:null,e?{action:"connection-performance-metrics",icon:"Gauge",label:"View performance metrics",isDisabled:!t,disabledDescription:"Not supported"}:null,n?null:{action:"open-connection-info",icon:"InfoWithCircle",label:"Show connection info"},{action:"refresh-databases",label:"Refresh databases",icon:"Refresh"},{separator:!0},{action:"connection-disconnect",icon:"Disconnect",label:"Disconnect",variant:"destructive"}]);function fe(e,t,n,a){return(0,p.t4r)(a).map((a=>({telemetryLabel:e,items:a.map((({label:e,action:a})=>({label:e,onAction(){n({...t,entrypoint:"context-menu"},a)}})))})))}const ye=(0,p.AHW)({display:"flex",flex:"1 0 auto",height:`calc(100% - ${p.YKD[1600]}px - ${p.YKD[200]}px)`}),be=({connections:e,activeWorkspace:t,expanded:n,onItemExpand:o,onItemAction:s})=>{const{enableRenameCollectionModal:u,enableShell:m,readOnly:g,readWrite:h,showDisabledConnections:f}=(0,A.gc)(["enableShell","readOnly","readWrite","enableRenameCollectionModal","showDisabledConnections"]),y=u&&!h,b=(0,p.BiT)(),x=(0,l._j)(),E=(0,a.useMemo)((()=>d({connections:e,expandedItems:n,preferencesReadOnly:g,preferencesReadWrite:h,preferencesShellEnabled:m})),[e,n,g,h,m]),C=(0,a.useCallback)(((e,t)=>{if(f){const t=c(e);if(!x(t))return}"connection"===e.type?"connected"===e.connectionStatus&&s(e,"select-connection"):"database"===e.type?s(e,"select-database"):t.metaKey||t.ctrlKey?s(e,"open-in-new-tab"):s(e,"select-collection")}),[s,x,f]),w=(0,a.useMemo)((()=>{if(t){if("Collection"===t.type||"Collections"===t.type)return`${t.connectionId}.${t.namespace}`;if("Databases"===t.type)return t.connectionId}}),[t]),I=(0,a.useCallback)((e=>{const[,t,n]=e,a=e=>void 0===e.separator&&["refresh-databases","create-database","open-shell"].includes(e.action);return a(t)&&a(n)?3:a(t)||a(n)?2:1}),[]),S=(0,a.useCallback)((e=>{if(f){const t=c(e);if(!x(t))return{actions:[]}}switch(e.type){case"placeholder":return{actions:[]};case"connection":if("connected"===e.connectionStatus){const t=(({connectionInfo:e,hasWriteActionsDisabled:t,isPerformanceTabAvailable:n,isPerformanceTabSupported:a,isShellEnabled:r})=>{const i=!!e.atlasMetadata,o=ue({connectionInfo:e});return de([{action:"refresh-databases",label:"Refresh databases",icon:"Refresh"},t?null:{action:"create-database",icon:"Plus",label:"Create database"},r?{action:"open-shell",icon:"Shell",label:"Open MongoDB shell"}:null,n?{action:"connection-performance-metrics",icon:"Gauge",label:"View performance metrics",isDisabled:!a,disabledDescription:"Not supported"}:null,!n&&e.atlasMetadata?{action:"connection-atlas-performance-metrics",icon:"Gauge",label:"View performance metrics"}:null,e.atlasMetadata?{action:"connection-cluster-overview",icon:"Dashboard",label:"View cluster overview"}:null,e.atlasMetadata?{action:"connection-view-monitoring",icon:"TimeSeries",label:"View monitoring"}:null,e.atlasMetadata?{action:"connection-query-insights",icon:"Bulb",label:"View query insights"}:null,i?null:{action:"open-connection-info",icon:"InfoWithCircle",label:"Show connection info"},{action:"connection-disconnect",icon:"Disconnect",label:"Disconnect",variant:"destructive"},{separator:!0},...o])})({hasWriteActionsDisabled:e.hasWriteActionsDisabled,isShellEnabled:e.isShellEnabled,connectionInfo:e.connectionInfo,isPerformanceTabAvailable:e.isPerformanceTabAvailable,isPerformanceTabSupported:e.isPerformanceTabSupported});return{actions:t,config:{collapseAfter:I(t)}}}return{actions:pe({connectionInfo:e.connectionInfo,connectionStatus:e.connectionStatus}),config:{collapseAfter:1}};case"database":return{actions:me({hasWriteActionsDisabled:e.hasWriteActionsDisabled,canDeleteDatabase:e.canDeleteDatabase})};default:return{actions:ge({hasWriteActionsDisabled:e.hasWriteActionsDisabled,type:e.type,isRenameCollectionEnabled:y,canEditCollection:e.canEditCollection})}}}),[y,I,x,f]),k=(0,a.useCallback)((function(e){switch(e.type){case"placeholder":return[];case"connection":return fe("Connection Tree Item",e,s,"connected"===e.connectionStatus?he({hasWriteActionsDisabled:e.hasWriteActionsDisabled,isShellEnabled:e.isShellEnabled,connectionInfo:e.connectionInfo,isPerformanceTabAvailable:e.isPerformanceTabAvailable,isPerformanceTabSupported:e.isPerformanceTabSupported,isAtlas:!!e.connectionInfo.atlasMetadata}):pe({connectionInfo:e.connectionInfo,connectionStatus:e.connectionStatus}));case"database":{const{isPerformanceTabAvailable:t,isPerformanceTabSupported:n,isShellEnabled:a,hasWriteActionsDisabled:r,connectionInfo:i}=e.connectionItem;return fe("Database Tree Item",e,s,(({hasWriteActionsDisabled:e,canDeleteDatabase:t,isShellEnabled:n,isPerformanceTabAvailable:a,isPerformanceTabSupported:r,isAtlas:i})=>de([e?null:{action:"create-collection",icon:"Plus",label:"Create collection"},{separator:!0},e?null:{action:"create-database",icon:"Plus",label:"Create database"},e||!t?null:{action:"drop-database",icon:"Trash",label:"Drop database"},{separator:!0},...he({isShellEnabled:n,isPerformanceTabAvailable:a,isPerformanceTabSupported:r,isAtlas:i,hasWriteActionsDisabled:e,connectionInfo:void 0})]))({hasWriteActionsDisabled:r,isShellEnabled:a,isPerformanceTabAvailable:t,isPerformanceTabSupported:n,isAtlas:!!i.atlasMetadata,canDeleteDatabase:e.canDeleteDatabase}))}default:{const{isPerformanceTabAvailable:t,isPerformanceTabSupported:n,isShellEnabled:a,hasWriteActionsDisabled:r,connectionInfo:i}=e.databaseItem.connectionItem;return fe("Collection Tree Item",e,s,(({hasWriteActionsDisabled:e,canEditCollection:t,type:n,isRenameCollectionEnabled:a,isPerformanceTabAvailable:r,isPerformanceTabSupported:i,isAtlas:o,isShellEnabled:s})=>{let l=[];return e||(l="view"===n&&t?[{separator:!0},{action:"duplicate-view",label:"Duplicate view",icon:"Copy"},{action:"modify-view",label:"Modify view",icon:"Edit"},{action:"drop-collection",label:"Drop view",icon:"Trash"}]:de([{separator:!0},"timeseries"!==n&&t&&a?{action:"rename-collection",label:"Rename collection",icon:"Edit"}:null,{action:"create-collection",icon:"Plus",label:"Create collection"},t?{action:"drop-collection",label:"Drop collection",icon:"Trash"}:null])),[{action:"open-in-new-tab",label:"Open in new tab",icon:"OpenNewTab"},...l,{separator:!0},...he({isShellEnabled:s,isPerformanceTabAvailable:r,isPerformanceTabSupported:i,isAtlas:o,hasWriteActionsDisabled:e,connectionInfo:void 0})]})({hasWriteActionsDisabled:r,type:e.type,isRenameCollectionEnabled:y,isShellEnabled:a,isPerformanceTabAvailable:t,isPerformanceTabSupported:n,isAtlas:!!i.atlasMetadata,canEditCollection:e.canEditCollection}))}}}),[s,y]),D=!1;return r().createElement("div",{className:ye},r().createElement(p.s6o,{id:b},"Databases and Collections"),r().createElement(i.Ay,{disableWidth:D,disableHeight:D},(({width:e="",height:t=""})=>r().createElement(v,{dataTestId:"sidebar-navigation-tree",activeItemId:w,items:E,width:e,height:t,itemHeight:28,onDefaultAction:C,onItemAction:s,onItemExpand:o,getItemActions:S,getItemKey:e=>e.id,getContextMenuGroups:k,renderItem:({item:e,isActive:t,isFocused:n,onItemAction:a,onItemExpand:i,getItemActions:o,getContextMenuGroups:s})=>r().createElement(ie,{item:e,isActive:t,isFocused:n,getItemActions:o,onItemExpand:i,onItemAction:a,getContextMenuGroups:s})}))))}},25540:(e,t,n)=>{n.d(t,{sJ:()=>sn,Ay:()=>ln,hx:()=>Oe,fE:()=>Le,PW:()=>Pe,L0:()=>Te,vE:()=>De});var a=n(96652),r=n.n(a),i=n(62183),o=n(82162),s=n(67219),l=n(9174);const c={filter:void 0,project:void 0,collation:void 0,sort:void 0,hint:void 0,skip:void 0,limit:void 0,maxTimeMS:void 0},d={filter:l.$Z,project:l.ol,collation:l.e1,sort:l.r4,hint:l.GH,skip:l.Yr,limit:l.eH,maxTimeMS:l.mj};n(95039);var u=n(90605),p=n(70724);const m=["filter","project","collation","sort","hint","skip","limit","maxTimeMS"];function g(e){return{filter:{},...Object.fromEntries(Object.entries(e).map((([e,t])=>[e,t.value])).filter((([,e])=>void 0!==e)))}}function h(e){if(!e)return!1;for(const t of m)if("filter"!==t&&!(0,u.isEqual)(e[t].value,d[t])&&!(0,u.isEqual)(e[t].value,c[t]))return!0;return!1}function f(e,t,n=!0){return Object.fromEntries(Object.entries(t??{}).map((([t,a])=>{if(!b(t))return null;let r=void 0===a?"":(0,l.AO)(a,0)||"";r=(0,p.G8)(r,"javascript-expression");const i=v(t,r,e),o=!1!==i;return n&&!o?null:[t,{string:r,value:o?i:null,valid:o}]})).filter((e=>null!==e)))}function y(e){return m.every((t=>e[t].valid))}function b(e){return m.includes(e)}function v(e,t,{maxTimeMS:n,maxTimeMSEnvLimit:a}){const r=(0,l.tf)(e,t);if(("filter"===e||"hint"===e)&&""===r)return!1;if("maxTimeMS"===e){const e=Number(t);if(a&&!Number.isNaN(e)&&e>a)return!1;if(void 0!==n&&t&&e>(n??c.maxTimeMS))return!1}return r}function x(e){return(0,u.isEqual)(g(e),d)}n(59509),n(25691),n(23177),n(3142),n(51615),n(84217),n(25953),n(42319),n(28465),n(12887),n(36106),n(84542),n(57068),n(69517);var E=n(26250),C=n(17855),w=n(13353);const I=e=>{navigator.clipboard.writeText(e)},S=e=>(0,l.AO)(e)||"",A=({filter:e,collation:t,sort:n,project:a,limit:r,skip:i,update:o,hint:s})=>{const l={filter:e,collation:t,sort:n,project:a,limit:r,skip:i,update:o,hint:s};return Object.keys(l).forEach((e=>{const t=e;(!l[t]||(0,u.isObject)(l[t])&&(0,u.isEmpty)(l[t]))&&delete l[t]})),l};function k(e,t){return e.type===t}function D(e,t){return e===t||(0,u.isEqual)(w.BSON.serialize(e),w.BSON.serialize(t))}var N=n(51295),M=n(44142),T=n(15088).process;const P={status:"ready",aiPromptText:"",errorMessage:void 0,errorCode:void 0,isInputVisible:!1,aiQueryRequestId:null,lastAIQueryRequestId:null},L="compass-query-bar/ai-query/AIQueryStarted",O="compass-query-bar/ai-query/AIQueryFailed",R="compass-query-bar/ai-query/AIQuerySucceeded",H="compass-query-bar/ai-query/CancelAIQuery",F="compass-query-bar/ai-query/ShowInput",W="compass-query-bar/ai-query/HideInput",j="compass-query-bar/ai-query/ChangeAIPromptText",B=new Map;function z(e){const t=B.get(e);return t?.abort(),B.delete(e)}function _({statusCode:e,errorCode:t,errorName:n,errorMessage:a,log:r,track:i,requestId:o,connectionInfo:s}){r.warn((0,M.oW)(1001000198),"AIQuery","AI query request failed",{statusCode:e,errorMessage:a,errorName:n,errorCode:t,requestId:o}),i("AI Response Failed",(()=>({editor_view_type:"find",error_name:n,status_code:e,error_code:t??"",request_id:o})),s)}const $=()=>(e,t)=>{const n=t().aiQuery.aiQueryRequestId;null!==n&&z(n),e({type:H})};var Y=n(81358);const K=n(69692).rv.filter((e=>e.geospatial)).map((e=>e.value));function G(e){return!!(0,u.isPlainObject)(e)&&0!==(0,u.intersection)(Object.keys(e),K).length}function V(e,t){const n=(0,u.clone)(e);return delete n[t.field],n}function U(e,t){const n=(0,u.clone)(e),a=(0,u.get)(n,t.field,void 0);if(void 0===a)return n[t.field]=t.value,n;if((0,u.isPlainObject)(a)){if((0,u.has)(a,"$in")){const e=n[t.field].$in;return(0,u.includes)(e,t.value)||n[t.field].$in.push(t.value),n}return n[t.field]=t.value,n}return n[t.field]={$in:[a,t.value]},n}function q(e,t){const n=(0,u.clone)(e),a=(0,u.get)(n,t.field,void 0);if(void 0!==a){if((0,u.isPlainObject)(a)&&(0,u.has)(a,"$in")){const e=n[t.field].$in,a=(0,u.pull)(e,t.value);return a.length>1?n[t.field].$in=a:1===a.length?n[t.field]=a[0]:delete n[t.field],n}return(0,u.isEqualWith)(a,t.value,Y.VU)?(delete n[t.field],n):n}}const Z={clearValue:V,setValue:function(e,t){const n=(0,u.clone)(e);return t.unsetIfSet&&(0,u.isEqualWith)(n[t.field],t.value,Y.VU)?delete n[t.field]:n[t.field]=t.value,n},setDistinctValues:function(e,t){let n=(0,u.clone)(e);return(0,u.isArray)(t.value)?(t.value.length>1?n[t.field]={$in:t.value}:1===t.value.length?n[t.field]=t.value[0]:n=V(n,{field:t.field}),n):(n[t.field]=t.value,n)},setRangeValues:function(e,t){let n=(0,u.clone)(e);const a={};let r;const i=(0,u.get)(t,"min",void 0),o=(0,u.get)(t,"max",void 0);return void 0===i&&void 0===o?(n=V(n,{field:t.field}),n):(void 0!==i&&(r=(0,u.get)(t,"minInclusive",!0)?"$gte":"$gt",a[r]=i),void 0!==o&&(r=(0,u.get)(t,"maxInclusive",!1)?"$lte":"$lt",a[r]=o),t.unsetIfSet&&(0,u.isEqualWith)(n[t.field],a,Y.VU)?delete n[t.field]:n[t.field]=a,n)},addDistinctValue:U,removeDistinctValue:q,toggleDistinctValue:function(e,t){const n=(0,u.get)(e,t.field,void 0);return((0,Y.mC)(n,t.value)?q:U)(e,t)},mergeGeoQuery:function(e,t){return function(e,t){const n={...e};for(const[e,t]of Object.entries(n))G(t)&&delete n[e];Array.isArray(n.$or)&&(n.$or=n.$or.filter((e=>!function(e){return!!(0,u.isPlainObject)(e)&&void 0!==Object.values(e).find(G)}(e))),n.$or.length||delete n.$or);for(const[e,a]of Object.entries(t))G(a)&&(n[e]=a);return t.$or&&(n.$or=[...Array.isArray(n.$or)?n.$or:[],...t.$or]),n}((0,u.clone)(e),t)},setGeoWithinValue:function(e,t){const n=(0,u.clone)(e),a={},r=(0,u.get)(t,"radius",0),i=(0,u.get)(t,"center",null);return r&&i?(a.$geoWithin={$centerSphere:[[i[0],i[1]],r]},n[t.field]=a,n):V(n,{field:t.field})}};function J(e,...t){return Z[e](...t)}const Q={isReadonlyConnection:!1,fields:f({maxTimeMSEnvLimit:0},c),expanded:!1,serverVersion:"3.6.0",lastAppliedQuery:{source:null,query:{}},applyId:0,namespace:"",recentQueries:[],favoriteQueries:[]},X="compass-query-bar/ChangeReadonlyConnectionStatus",ee="compass-query-bar/ToggleQueryOptions",te="compass-query-bar/ChangeField",ne="compass-query-bar/SetQuery",ae="compass-query-bar/ApplyQuery",re="compass-query-bar/ResetQuery",ie="compass-query-bar/ApplyFromHistory",oe="compass-query-bar/RecentQueriesFetched",se="compass-query-bar/FavoriteQueriesFetched",le=e=>(t,n)=>{const a=n().queryBar.fields.filter.value;var r;t((r={filter:J(e.type,a,e.payload)},(e,t,{preferences:n})=>{const a=f(n.getPreferences(),r);e({type:ne,fields:a})}))},ce=(e,t=[])=>(n,a,{localAppRegistry:r,preferences:i})=>{const o=a().queryBar.fields,s=t.reduce(((e,t)=>{const{value:n}=o[t];return n&&(e[t]=n),e}),{}),l=f(i.getPreferences(),{...c,...e,...s});n({type:ie,fields:l}),e.update&&r?.emit("favorites-open-bulk-update-favorite",e)},de=()=>async(e,t,{recentQueryStorage:n,logger:{debug:a},preferences:r})=>{try{const{enableMyQueries:a}=r.getPreferences();if(!a)return void e({type:oe,recents:[]});const{queryBar:{namespace:i}}=t(),o=await(n?.loadAll(i))??[];e({type:oe,recents:o})}catch(e){a("Failed to fetch recent queries",e)}},ue=()=>(e,t,{preferences:n})=>{const{enableMyQueries:a}=n.getPreferences();a&&(e(de()),e(pe()))},pe=()=>async(e,t,{favoriteQueryStorage:n,logger:{debug:a},preferences:r})=>{try{const{enableMyQueries:a}=r.getPreferences();if(!a)return void e({type:se,favorites:[]});const{queryBar:{namespace:i}}=t(),o=await(n?.loadAll(i))??[];e({type:se,favorites:o})}catch(e){a("Failed to fetch favorite queries",e)}},me=(e="visual-tree")=>(t,n,{localAppRegistry:a})=>{const{queryBar:{fields:r}}=n(),{project:i,...o}=g(r),s={query:{...o,projection:i}};"interpret"!==e?a?.emit("open-explain-plan-modal",{...s,..."raw-output"===e?{initialViewType:"json"}:{}}):a?.emit("open-explain-plan-for-interpret",s)},ge=e=>async(t,n,{recentQueryStorage:a,logger:{debug:r}})=>{try{return await(a?.delete(e)),t(de())}catch(e){r("Failed to delete recent query",e)}},he=e=>async(t,n,{recentQueryStorage:a,logger:{debug:r}})=>{try{const{queryBar:{recentQueries:r,host:i,namespace:o}}=n(),s=A(e);if((0,u.isEmpty)(s))return;const l=r.find((e=>D(A(e),s)));if(l){const e={_host:l._host??i,_lastExecuted:new Date};return await(a?.updateAttributes(l._id,e)),void t(ue())}await(a?.saveQuery({...s,_ns:o,_host:i??""})),t(ue())}catch(e){r("Failed to save recent query",e)}},fe=e=>async(t,n,{favoriteQueryStorage:a,logger:{debug:r}})=>{try{const{queryBar:{host:r}}=n(),i=A(e);if((0,u.isEmpty)(i))return;const o={_host:e._host??r,_lastExecuted:new Date};await(a?.updateAttributes(e._id,o)),t(pe())}catch(e){r("Failed to update favorite query",e)}};var ye=n(19125);const be=r().createContext(null),ve=(0,ye.Nk)(be),xe=((0,ye.iI)(be),(0,ye.jO)(be)),Ee=(e,t=null,n=null)=>(0,ye.Ng)(e,t,n,{context:be}),Ce=(0,o.HY)({queryBar:(e=Q,t)=>k(t,X)?{...e,isReadonlyConnection:t.readonly}:k(t,ee)?{...e,expanded:t.force??!e.expanded}:k(t,te)?{...e,fields:{...e.fields,[t.name]:t.value}}:k(t,ne)?{...e,fields:{...e.fields,...t.fields}}:k(t,ae)?{...e,lastAppliedQuery:{source:t.source,query:{...e.lastAppliedQuery.query,[t.source]:t.query}},applyId:(e.applyId+1)%Number.MAX_SAFE_INTEGER}:k(t,re)?{...e,fields:t.fields,lastAppliedQuery:{source:t.source,query:{...e.lastAppliedQuery.query,[t.source]:null}}}:k(t,ie)||k(t,R)?{...e,expanded:e.expanded||h(t.fields),fields:t.fields}:k(t,oe)?{...e,recentQueries:t.recents}:k(t,se)?{...e,favoriteQueries:t.favorites}:e,aiQuery:(e=P,t)=>k(t,L)?{...e,status:"fetching",errorMessage:void 0,aiQueryRequestId:t.requestId}:k(t,O)?401===t.statusCode?{...P}:{...e,status:"ready",aiQueryRequestId:null,errorMessage:t.errorMessage,errorCode:t.errorCode}:k(t,R)?{...e,status:"success",aiQueryRequestId:null,lastAIQueryRequestId:t.requestId}:k(t,H)?{...e,status:"ready",aiQueryRequestId:null}:k(t,F)?{...e,isInputVisible:!0}:k(t,W)?{...e,isInputVisible:!1}:k(t,j)?{...e,status:"success"===e.status?"ready":e.status,aiPromptText:t.text}:e});var we=n(60783),Ie=n(44457);function Se(){return r().createElement(r().Fragment,null)}const Ae=r().createContext(Se),ke=Ae.Provider;function De(){const e=xe((e=>e.queryBar.fields));return(0,a.useMemo)((()=>g(e)),[e])}const Ne=(0,u.cloneDeep)(d);function Me(e,t=null){return t??=e.queryBar.lastAppliedQuery.source,t?e.queryBar.lastAppliedQuery.query[t]??Ne:Ne}function Te(e=null){return xe((t=>Me(t,e)))}function Pe(e){return xe((t=>!D(Me(t),Me(t,e))))}function Le(){const e=ve();return(0,a.useCallback)(((t,n)=>{e.dispatch(le({type:t,payload:n}))}),[e])}const Oe=(0,i.mb)((function(){const e=ve();return{getCurrentQuery:()=>g(e.getState().queryBar.fields),getLastAppliedQuery:(t=null)=>Me(e.getState(),t),changeQuery:Le()}}),"queryBarServiceLocator");var Re=n(42279),He=n(20625),Fe=n(28508);const We={filter:{name:"filter",type:"document",placeholder:"Type a query: { field: 'value' }",link:"https://docs.mongodb.com/compass/current/query/filter/"},project:{name:"project",type:"document",placeholder:"{ field: 0 }",link:"https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/"},sort:{name:"sort",type:"document",placeholder:"{ field: -1 } or [['field', -1]]",link:"https://docs.mongodb.com/manual/reference/method/cursor.sort/"},hint:{name:"hint",label:"Index Hint",type:"document",placeholder:'{ field: -1 } or "indexName"',link:"https://docs.mongodb.com/manual/reference/method/cursor.hint/"},collation:{name:"collation",type:"document",placeholder:"{ locale: 'simple' }",link:"https://docs.mongodb.com/master/reference/collation/"},skip:{name:"skip",type:"numeric",placeholder:"0",link:"https://docs.mongodb.com/manual/reference/method/cursor.skip/"},limit:{name:"limit",type:"numeric",placeholder:"0",link:"https://docs.mongodb.com/manual/reference/method/cursor.limit/"},maxTimeMS:{name:"maxTimeMS",label:"Max Time MS",type:"numeric",placeholder:"60000",link:"https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/",extraTextInputProps(){const e=(0,He.Fg)("maxTimeMS"),t=(0,He.Fg)("maxTimeMSEnvLimit"),n=t?e?Math.min(e,t):t:e,a={max:n};return n&&n<6e4&&(a.placeholder=""+ +n),a}}};var je=n(55712);function Be(e){try{return!!(0,l.Ay)(e)}catch{return!1}}var ze=n(25607);const _e=(0,N.AHW)({position:"relative",display:"flex",width:"100%",minWidth:N.YKD[7],paddingTop:1,paddingBottom:1,paddingLeft:4,paddingRight:0,border:"1px solid transparent",borderRadius:N.YKD[100],overflow:"visible"}),$e=(0,N.AHW)({"&:after":{position:"absolute",top:-1,left:-1,right:-1,bottom:-1,zIndex:2,borderRadius:N.YKD[100],border:`1px solid ${N.MFm.red.base}`,pointerEvents:"none"},"&:focus-within":{borderColor:N.MFm.gray.base}});function Ye(e,t,n){return n.map((n=>({type:t,lastExecuted:n._lastExecuted,queryProperties:A("filter"!==e?{[e]:n[e]}:n)}))).filter(((e,t,n)=>{const a="update"in e.queryProperties;return!(0===Object.keys(e.queryProperties).length||a||t!==n.findIndex((t=>JSON.stringify(t.queryProperties)===JSON.stringify(e.queryProperties))))})).sort(((e,t)=>e.lastExecuted.getTime()-t.lastExecuted.getTime())).slice(-5)}const Ke=Ee((({queryBar:{namespace:e,serverVersion:t,recentQueries:n,favoriteQueries:a}})=>({namespace:e,serverVersion:t,recentQueries:n,favoriteQueries:a})),{onApplyQuery:ce})((({optionName:e,namespace:t,id:n,hasError:i=!1,insertEmptyDocOnFocus:o=!0,onChange:s,onApply:l,onBlur:d,placeholder:u,serverVersion:g="3.6.0",value:h="","data-testid":y,disabled:b=!1,recentQueries:v,favoriteQueries:x,onApplyQuery:E})=>{const C=(0,a.useRef)(null),w=(0,a.useRef)(null),I=(0,N.ogd)({outer:!0,focusWithin:!0,hover:!0}),S=(0,N.D27)(),A=(0,a.useRef)(l);A.current=l;const k=(0,a.useMemo)((()=>[{key:"Enter",run:()=>(A.current?.(),!0),preventDefault:!0}]),[]),D=(0,ze.jv)(t),M=(0,He.Fg)("maxTimeMS"),T=(0,a.useMemo)((()=>[...Ye(e,"recent",v),...Ye(e,"favorite",x)]),[e,v,x]),P=(0,a.useMemo)((()=>(0,p.Xv)({queryProperty:e,savedQueries:T,options:{fields:D,serverVersion:g},onApply:t=>{const n="filter"===e?[]:m.filter((t=>t!==e));if(E(t,n),!t[e])return;const a=f({maxTimeMS:M},{...c,...t})[e];a?.string&&w.current?.cursorDocEnd()},theme:S?"dark":"light"})),[M,T,D,g,E,S,e]);return r().createElement("div",{className:(0,N.cx)(_e,!b&&I.className,i&&$e),ref:C},r().createElement(p.Fv,{ref:w,id:n,text:h,onChangeText:s,placeholder:u,completer:P,commands:k,"data-testid":y,disabled:b,onFocus:()=>{o&&(0,N.Rbc)((()=>{""!==w.current?.editorContents&&"{}"!==w.current?.editorContents||(w.current?.applySnippet("\\{${}}"),w.current?.editor&&w.current?.startCompletion())}))},onPaste:e=>{if(o&&w.current){const{main:t}=w.current.editor?.state.selection??{};if("{}"===w.current.editorContents&&t&&1===t.from&&1===t.to){const t=function(e){if(""===(e=e.trim()))return"\\{${}}";let t=!1;const n=function(e){const t=e.match(/^{([0-9a-fA-F]{24})}$/);if(t)return`{ _id: ObjectId("${t[1]}") }`}(e);n&&(t=!0,e=n);const a=function(e){if(!Be(e))if(e.startsWith("{")&&e.endsWith("}")){const t=e.substring(1,e.length-1);if(Be(t))return t}else{const t=`{${e}}`;if(Be(t))return t}}(e);if(a&&(t=!0,e=a),!t)return!1;const r=(e=e.replaceAll("{","\\{")).lastIndexOf("}");return e.substring(0,r)+"${}"+e.substring(r)}(`{${e.clipboardData.getData("text")}}`);t&&(e.preventDefault(),w.current.applySnippet(t))}}},onBlur:d}))})),Ge=(0,N.AHW)({display:"flex",position:"relative",alignItems:"flex-start"}),Ve=(0,N.AHW)({flexGrow:1}),Ue=(0,N.AHW)({marginRight:N.YKD[200]}),qe=(0,N.AHW)(Ue,{minWidth:2*N.YKD[800]}),Ze=(0,N.AHW)({minWidth:N.YKD[7],display:"flex",flexGrow:1}),Je=(0,N.AHW)({input:{borderColor:"transparent"}}),Qe=(0,N.AHW)({input:{borderColor:"transparent"}}),Xe=(0,N.AHW)({input:{borderColor:N.MFm.red.base}}),et=(0,N.AHW)({height:N.YKD[600]+N.YKD[100],textTransform:"capitalize",display:"flex",alignItems:"center"}),tt=(0,N.AHW)(et,{minWidth:2*N.YKD[800]}),nt=({definition:e,children:t})=>{let n={};return"numeric"===e.type&&(n.inputMode="numeric",n.pattern="[0-9]*"),n={...n,...e.extraTextInputProps?.()},t({props:n})},at=Ee(((e,t)=>{const n=e.queryBar.fields[t.name];return{value:n.string,hasError:!n.valid}}),{onChange:(e,t)=>(n,a,{preferences:r})=>{const i=v(e,t,{maxTimeMS:r.getPreferences().maxTimeMS??void 0,maxTimeMSEnvLimit:r.getPreferences().maxTimeMSEnvLimit}),o=!1!==i;n({type:te,name:e,value:{string:t,valid:o,value:o?i:a().queryBar.fields[e].value}})}})((({hasError:e,onChange:t,id:n,placeholder:i,name:o,value:s,onApply:l,disabled:c=!1})=>{const d=(0,Fe.Jr)(),u=(0,we.jj)(),p=(0,N.D27)(),m=(0,a.useRef)(s),g=(0,N.HIF)(s),h=We[o],f="document"===h.type;i??=h.placeholder,s??="";const y=(0,a.useCallback)((e=>t(o,e)),[o,t]),b=(0,a.useCallback)((()=>{g.current&&g.current!==m.current&&(m.current||"{}"!==g.current)&&(d("Query Edited",{option_name:o},u.current),m.current=g.current)}),[g,d,o,u]),v=(0,He.Fg)("maxTimeMSEnvLimit"),x=(0,a.useMemo)((()=>{if(!s)return 0;const e=Number(s);return Number.isNaN(e)?0:e}),[s]),E=(0,a.useMemo)((()=>"maxTimeMS"===o&&v&&x>=v),[o,v,x]);return r().createElement("div",{className:(0,N.cx)(Ge,f&&Ve),"data-testid":`query-bar-option-${o}`},"filter"!==o&&r().createElement("div",{className:f?tt:et},r().createElement(N.JU7,{htmlFor:n,id:`query-bar-option-input-${o}-label`,disabled:c,className:f?qe:Ue},h.label??o)),r().createElement("div",{className:(0,N.cx)(f&&Ze)},f?r().createElement(Ke,{optionName:o,hasError:e,id:n,onChange:y,onBlur:b,placeholder:i,value:s,"data-testid":`query-bar-option-${o}-input`,onApply:l,disabled:c}):r().createElement(nt,{definition:h},(({props:t})=>{const a=r().createElement(N.ksK,(0,je.A)({"aria-labelledby":`query-bar-option-input-${o}-label`,id:n,"data-testid":`query-bar-option-${o}-input`,className:(0,N.cx)(p?Qe:Je,e&&Xe),type:"text",sizeVariant:"small",state:e?"error":"none",value:s,onChange:e=>y(e.currentTarget.value),onBlur:b,placeholder:i,disabled:c},t));return E?r().createElement(N.m_M,{enabled:!0,open:!0,trigger:({children:e,...t})=>r().createElement("div",t,a,e)},"Operations longer than 5 minutes are not supported in the web environment"):a}))))})),rt=(0,N.AHW)({display:"block",flexShrink:0,fontSize:"16px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",lineHeight:`${N.YKD[600]}px`,marginBottom:N.YKD[400]}),it=(0,N.AHW)({color:N.MFm.green.light2}),ot=(0,N.AHW)({color:N.MFm.green.dark2}),st=(0,N.AHW)({padding:N.YKD[400],paddingBottom:0,paddingRight:N.YKD[800]}),lt=(0,N.AHW)({marginTop:N.YKD[100]});function ct({tab:e,onChange:t,namespace:n}){const a=(0,N.D27)(),i=(0,N.BiT)(),o=(0,N.BiT)();return r().createElement("div",{className:st},r().createElement(N.JU7,{className:rt,id:i,htmlFor:o},"Queries in"," ",r().createElement("span",{className:a?it:ot,title:n},n)),r().createElement(N.IzF,{className:lt,id:o,"aria-labelledby":i,value:e,onChange:e=>t(e)},r().createElement(N.Zib,{"aria-controls":"recent",value:"recent","data-testid":"past-queries-recent",glyph:r().createElement(N.Int,{glyph:"Clock"})},"Recents"),r().createElement(N.Zib,{"aria-controls":"favorite",value:"favorite","data-testid":"past-queries-favorites",glyph:r().createElement(N.Int,{glyph:"Favorite"})},"Favorites")))}const dt=(0,N.AHW)({display:"flex",flexDirection:"column",gap:N.YKD[200],padding:N.YKD[400],textAlign:"center",marginTop:N.YKD[400]}),ut=(0,N.AHW)({margin:"0 auto"}),pt=(0,N.AHW)({maxWidth:3*N.YKD[7],margin:"0 auto"});function mt({text:e}){return r().createElement("div",{className:dt},r().createElement("div",{className:ut},r().createElement(N.m3F,{size:2*N.YKD[600]})),r().createElement(N.nBu,{className:pt},e))}const gt=(0,N.AHW)({padding:N.YKD[400],marginTop:N.YKD[400]}),ht=(0,N.AHW)({border:`1px solid ${N.MFm.blue.base}`,cursor:"pointer"}),ft=(0,N.AHW)({cursor:"not-allowed"}),yt=({children:e,onClick:t,header:n,disabled:a,"data-testid":i})=>{const[o,s]=(0,N.v69)();let l=ft;return s&&!a&&(l=ht),r().createElement(N.yY_,(0,je.A)({onClick:t,"data-testid":i,className:(0,N.cx)(gt,l)},o),n(s),e)},bt=(0,N.AHW)({display:"flex"}),vt=(0,N.AHW)({fontSize:"16px",lineHeight:`${N.YKD[800]}px`,fontWeight:"bold",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexGrow:1}),xt=(0,N.AHW)({display:"none",whiteSpace:"nowrap"}),Et=(0,N.AHW)({display:"block"}),Ct=({title:e,isHovered:t,children:n})=>r().createElement("div",{"data-testid":"query-history-query-hoveritems",className:bt},r().createElement(N.nBu,{className:vt,"data-testid":"query-history-query-title"},e),r().createElement("div",{className:(0,N.cx)(xt,t?Et:void 0)},n)),wt=(0,N.AHW)({textTransform:"capitalize",fontWeight:"bold",margin:`${N.YKD[200]}px 0`}),It=(0,N.AHW)({maxHeight:"30vh"}),St=({query:e})=>r().createElement("div",{"data-testid":"query-history-query-attributes"},Object.entries(e).map((([e,t],n)=>r().createElement("div",{key:n,"data-testid":"query-history-query-attribute"},r().createElement(N.nBu,{"data-testid":"query-history-query-label",className:wt},e),r().createElement(N.CyN,{className:It,"data-testid":"query-history-query-code",language:"javascript",copyButtonAppearance:"none"},S(t)))))),At=e=>t=>{t.stopPropagation(),e()},kt=({onClick:e})=>r().createElement(N.K0,{"data-testid":"query-history-button-fav","aria-label":"Favorite Query",title:"Favorite Query",onClick:At(e)},r().createElement(N.Int,{glyph:"Favorite"})),Dt=({onClick:e})=>r().createElement(N.K0,{"data-testid":"query-history-button-copy-query","aria-label":"Copy Query to Clipboard",title:"Copy Query to Clipboard",onClick:At(e)},r().createElement(N.Int,{glyph:"Copy"})),Nt=({onClick:e})=>r().createElement(N.K0,{"data-testid":"query-history-button-delete-recent","aria-label":"Delete Query from List",title:"Delete Query from List",onClick:At(e)},r().createElement(N.Int,{glyph:"Trash"})),Mt=({onClick:e})=>r().createElement(N.K0,{"data-testid":"query-opens-in-modal-button","aria-label":"Open in Modal",title:"Open in Modal",onClick:At(e)},r().createElement(N.Int,{glyph:"OpenNewTab"})),Tt=(0,N.AHW)({display:"flex"}),Pt=(0,N.AHW)({display:"none"}),Lt=(0,N.AHW)({flex:1}),Ot=(0,N.AHW)({marginLeft:"6px",marginRight:N.YKD[100]}),Rt=(0,a.forwardRef)((({onSave:e,onCancel:t},n)=>{const[i,o]=(0,a.useState)(""),s=(0,N.BiT)(),l=(0,N.BiT)();return r().createElement("form",{"data-testid":"query-history-favorite-form",ref:n,className:Tt,onSubmit:t=>{t.preventDefault(),t.stopPropagation(),e(i)}},r().createElement(N.JU7,{id:s,htmlFor:l,className:Pt}),r().createElement(N.ksK,{autoFocus:!0,placeholder:"Favorite Name",className:Lt,id:l,"aria-labelledby":s,onChange:e=>{o(e.target.value)},"data-testid":"recent-query-save-favorite-name"}),r().createElement(N.$nd,{"data-testid":"recent-query-save-favorite-submit",className:Ot,type:"submit",variant:"primary"},"Save"),r().createElement(N.$nd,{"data-testid":"recent-query-save-favorite-cancel",type:"button",onClick:t},"Cancel"))}));Rt.displayName="SaveQueryForm";const Ht=({query:e,isReadonly:t,onFavorite:n,onDelete:i,onApply:o,onUpdateRecentChoosen:s})=>{const l=(0,Fe.Jr)(),c=(0,we.jj)(),d=(0,He.Fg)("readOnly"),u=!!e.update,p=u&&(t||d),m=r().useRef(null),[g,h]=(0,a.useState)(!1),f=(0,a.useMemo)((()=>A(e)),[e]),y=(0,N.Unm)(e._lastExecuted.getTime()),b=(0,a.useCallback)((()=>{p||(u&&s(),l("Query History Recent Used",{isUpdateQuery:u},c.current),o(f))}),[p,u,l,o,f,s,c]),v=(0,a.useCallback)((e=>{m.current?.contains(e.target)||b()}),[b]),x=(0,a.useCallback)((t=>{l("Query History Favorite Added",{isUpdateQuery:u},c.current),n(e,t)}),[l,u,n,e,c]);return r().createElement(yt,{onClick:v,disabled:p,"data-testid":"recent-query-list-item",header:n=>g?r().createElement(Rt,{ref:m,onSave:x,onCancel:()=>h(!1)}):r().createElement(Ct,{title:y,isHovered:n},r().createElement(kt,{onClick:()=>h(!0)}),r().createElement(Dt,{onClick:()=>I(S(f))}),r().createElement(Nt,{onClick:()=>i(e._id)}),u&&!t&&!d&&r().createElement(Mt,{onClick:b}))},r().createElement(St,{query:f}))},Ft=Ee((({queryBar:{recentQueries:e,isReadonlyConnection:t}})=>({queries:e,isReadonly:t})),{onDelete:ge,onFavorite:(e,t)=>async(n,a,{favoriteQueryStorage:r,logger:{debug:i}})=>{try{const i=new Date,{_id:o,_host:s,_lastExecuted:l,_ns:c,...d}=e,u={...A(d),_id:o,_ns:c,_lastExecuted:l,_host:s??a().queryBar.host,_name:t,_dateSaved:i,_dateModified:i};return await(r?.saveQuery(u,u._id)),n(pe()),n(ge(o)),!0}catch(e){return i("Failed to save recent query as favorite",e),!1}},onApply:ce})((({queries:e,onDelete:t,onFavorite:n,onApply:i,onSaveFavorite:o,onUpdateRecentChoosen:s,isReadonly:l})=>{const c=(0,a.useCallback)((async(e,t)=>{const a=await n(e,t);return a&&o(),a}),[n,o]);if(0===e.length)return r().createElement(mt,{text:"Your recent queries will appear here."});const d=e.map((e=>r().createElement(Ht,{key:e._id,query:e,onApply:i,onFavorite:c,onDelete:t,onUpdateRecentChoosen:s,isReadonly:l})));return r().createElement(r().Fragment,null,d)})),Wt=({query:e,isReadonly:t,onApply:n,onDelete:i,onUpdateFavoriteChoosen:o})=>{const s=(0,Fe.Jr)(),l=(0,we.jj)(),c=(0,He.Fg)("readOnly"),d=!!e.update,u=d&&(t||c),p=(0,a.useMemo)((()=>A(e)),[e]),m=(0,a.useCallback)((()=>{s("Query History Favorite Used",{id:e._id,screen:"documents",isUpdateQuery:d},l.current),u||(d&&o(),n(p))}),[s,e._id,d,u,n,p,o,l]),g=(0,a.useCallback)((()=>{s("Query History Favorite Removed",{id:e._id,screen:"documents",isUpdateQuery:d},l.current),i(e._id)}),[s,e._id,d,i,l]);return r().createElement(yt,{key:e._id,disabled:u,onClick:m,"data-testid":"favorite-query-list-item",header:n=>r().createElement(Ct,{title:e._name,isHovered:!0},n&&r().createElement(Dt,{onClick:()=>I(S(p))}),n&&r().createElement(Nt,{onClick:g}),d&&!t&&!c&&r().createElement(Mt,{onClick:m}))},r().createElement(St,{query:p}))},jt=Ee((({queryBar:{favoriteQueries:e,isReadonlyConnection:t}})=>({queries:e,isReadonly:t})),{onApply:ce,onDelete:e=>async(t,n,{favoriteQueryStorage:a,logger:{debug:r}})=>{try{return await(a?.delete(e)),t(pe())}catch(e){r("Failed to delete favorite query",e)}}})((({queries:e,isReadonly:t,onApply:n,onDelete:a,onUpdateFavoriteChoosen:i})=>{if(0===e.length)return r().createElement(mt,{text:"Your favorite queries will appear here."});const o=e.map((e=>r().createElement(Wt,{key:e._id,query:e,isReadonly:t,onApply:n,onDelete:a,onUpdateFavoriteChoosen:i})));return r().createElement(r().Fragment,null,o)})),Bt=(0,N.AHW)({display:"flex",flexDirection:"column",flex:1,width:"388px",maxHeight:"100%"}),zt=(0,N.AHW)({overflowY:"auto",padding:N.YKD[400],paddingTop:0}),_t=Ee((({queryBar:{namespace:e}})=>({namespace:e})))((({namespace:e,onUpdateFavoriteChoosen:t,onUpdateRecentChoosen:n})=>{const[i,o]=(0,a.useState)("recent"),s=(0,we.jj)();return(0,Fe.ou)((e=>{const t=s.current;e("favorite"===i?"Query History Favorites":"Query History Recent",{},t)}),[i,s],void 0),r().createElement("div",{"data-testid":"query-history",className:Bt},r().createElement(ct,{tab:i,onChange:o,namespace:e}),r().createElement("div",{className:zt},"recent"===i&&r().createElement(Ft,{onUpdateRecentChoosen:n,onSaveFavorite:()=>o("favorite")}),"favorite"===i&&r().createElement(jt,{onUpdateFavoriteChoosen:t})))})),$t=(0,N.AHW)({border:"none",backgroundColor:"transparent",display:"inline-flex",alignItems:"center",padding:N.YKD[200]-2,"&:hover":{cursor:"pointer"}},N.Rg),Yt=(0,N.AHW)({maxHeight:"calc(100vh - 270px)",marginTop:N.YKD[100],display:"flex"}),Kt=Ee(null,{onOpenPopover:ue})((({onOpenPopover:e})=>{const[t,n]=r().useState(!1),i=(0,we.jj)();(0,Fe.ou)((e=>{const n=i.current;e(t?"Query History Opened":"Query History Closed",{},n)}),[t,i],void 0);const o=(0,a.useCallback)((t=>{t&&e(),n(t)}),[e]),s=(0,a.useCallback)((()=>{n(!1)}),[n]);return r().createElement(N.WA6,{className:Yt,trigger:({onClick:e,ref:n,children:a})=>r().createElement(r().Fragment,null,r().createElement("button",{"data-testid":"query-history-button",onClick:e,className:$t,"aria-label":"Open query history","aria-haspopup":"true",title:"Query History",tabIndex:0,"aria-expanded":!!t||void 0,type:"button",ref:n},r().createElement(N.Int,{glyph:"Clock"}),r().createElement(N.Int,{glyph:"CaretDown"})),a),open:t,setOpen:o},r().createElement(_t,{onUpdateRecentChoosen:s,onUpdateFavoriteChoosen:s}))})),Gt=(0,N.AHW)({alignItems:"flex-start",display:"flex",flexGrow:1,position:"relative",gap:N.YKD[200]}),Vt=({queryOptionsLayout:e,onApply:t,placeholders:n,disabled:a})=>r().createElement("div",{className:Gt},"string"==typeof e?r().createElement(at,{key:e,name:e,id:`query-bar-option-input-${e}`,onApply:t,placeholder:n?.[e],disabled:a}):e.map((e=>r().createElement(at,{key:e,name:e,id:`query-bar-option-input-${e}`,onApply:t,placeholder:n?.[e],disabled:a})))),Ut=Ee((e=>({aiPromptText:e.aiQuery.aiPromptText,isFetching:"fetching"===e.aiQuery.status,lastAIQueryRequestId:e.aiQuery.lastAIQueryRequestId,didGenerateEmptyResults:"success"===e.aiQuery.status&&x(e.queryBar.fields),didSucceed:"success"===e.aiQuery.status,errorMessage:e.aiQuery.errorMessage,errorCode:e.aiQuery.errorCode})),{onChangeAIPromptText:e=>({type:j,text:e}),onCancelRequest:$,onSubmitText:e=>async(t,n,{dataService:a,localAppRegistry:r,preferences:i,atlasAiService:o,logger:{log:s},connectionInfoRef:l,track:d,collection:u})=>{const p=i.getPreferences().enableGenAISampleDocumentPassing,m=new AbortController,{id:g,signal:h}=function(){const e=(new w.UUID).toString(),t=new AbortController;return B.set(e,t),{id:e,signal:t.signal}}(),y=l.current;d("AI Prompt Submitted",(()=>({editor_view_type:"find",user_input_length:e.length,has_sample_documents:p,request_id:g})),y);const{aiQuery:{aiQueryRequestId:x},queryBar:{namespace:I}}=n();let S;null!==x&&z(x),t({type:L,requestId:g});try{const t=await a.sample(I,{query:{},size:4},{maxTimeMS:i.getPreferences().maxTimeMS,promoteValues:!1},{abortSignal:h}),n=await(0,E.Cv)(t),{isFLE:r}=await u.fetchMetadata({dataService:a}),{collection:s,database:l}=(0,C.Ay)(I);S=await o.getQueryFromUserInput({signal:m.signal,userInput:e,collectionName:s,databaseName:l,schema:n,...p?{sampleDocuments:t}:void 0,requestId:g,enableStorage:!r},y)}catch(e){if(h.aborted)return;return _({errorName:"request_error",statusCode:e.statusCode||e?.code,errorCode:e.errorCode||e?.name,errorMessage:e.message,log:s,track:d,requestId:g,connectionInfo:y}),401===e.statusCode&&(0,N.c3r)("ai-unauthorized",{variant:"important",title:"Network Error",description:"Unauthorized",timeout:5e3}),void t({type:O,errorMessage:e.message,statusCode:e.statusCode??-1,errorCode:e.errorCode})}finally{A=g,B.delete(A)}var A;if(h.aborted)return void s.info((0,M.oW)(1001000197),"AIQuery","Cancelled ai query request",{requestId:g});let k,D;try{k=S?.content?.query,D=function(e,t){return Object.fromEntries(Object.entries(e).map((([e,n])=>{if(!b(e)||"string"!=typeof n)return null;const a=v(e,n,t),r=!1!==a;return[e,{string:n,value:r?a:null,valid:r}]})).filter((e=>null!==e)))}(k,i.getPreferences())}catch(e){return _({errorName:"could_not_parse_fields",statusCode:e.statusCode,errorMessage:e?.message,log:s,track:d,requestId:g,connectionInfo:y}),void t({type:O,errorMessage:e?.message})}if(!D||0===Object.keys(D).length){const n=S?.content?.aggregation;if(n)return r?.emit("generate-aggregation-from-query",{userInput:e,aggregation:n,requestId:g}),void _({errorName:"ai_generated_aggregation_instead_of_query",errorMessage:"Query requires stages from aggregation framework therefore an aggregation was generated.",log:s,track:d,requestId:g,connectionInfo:y});const a="No query was returned from the ai. Consider re-wording your prompt.";return _({errorName:"no_usable_query_from_ai",errorMessage:a,log:s,track:d,requestId:g,connectionInfo:y}),void t({type:O,errorMessage:a})}const T={...f(i.getPreferences(),c),...D};s.info((0,M.oW)(1001000199),"AIQuery","AI query request succeeded",{requestId:g,shape:Object.keys(D)}),d("AI Response Generated",(()=>({editor_view_type:"find",query_shape:Object.keys(D),request_id:g})),y),t({type:R,fields:T,requestId:g})}})((function(e){const t=(0,He.Fg)("trackUsageStatistics"),n=(e=>{const t=(0,M.Ul)("AI-QUERY-UI"),n=(0,Fe.Jr)(),r=(0,we.jj)();return(0,a.useCallback)(((a,i)=>{const{log:o,mongoLogId:s}=t;o.info(s(1001000224),"AIQuery","AI query feedback",{feedback:a,requestId:e,text:i}),n("AI Query Feedback",(()=>({feedback:a,text:i,request_id:e})),r.current),(0,N.c3r)("query-ai-feedback-submitted",{variant:"success",title:"Your feedback has been submitted.",timeout:1e4})}),[t,e,n,r])})(e.lastAIQueryRequestId);return r().createElement(Re.HM,(0,je.A)({onSubmitFeedback:t?n:void 0},e))}));var qt=n(2155),Zt=n(21119);const Jt=(0,N.AHW)({display:"flex",flexDirection:"column",flexGrow:1,background:N.MFm.white,border:`1px solid ${N.MFm.gray.light2}`,borderRadius:"6px",padding:N.YKD[200]}),Qt=(0,N.AHW)({background:N.MFm.black,borderColor:N.MFm.gray.dark2}),Xt=(0,N.AHW)({display:"flex",alignItems:"flex-start",gap:N.YKD[200]}),en=(0,N.AHW)({display:"flex",position:"relative",flexGrow:1,alignItems:"flex-start",gap:N.YKD[200]}),tn=(0,N.AHW)({display:"flex",alignItems:"center",height:N.YKD[600]+N.YKD[100]}),nn=(0,N.AHW)({display:"flex",flexDirection:"column",marginTop:N.YKD[200],padding:`0 ${N.YKD[200]}px`,gap:N.YKD[200]}),an=Ee((e=>({isExpanded:e.queryBar.expanded})),{onToggleOptions:e=>({type:ee,force:e})})(N.bft),rn=Ee((({queryBar:{expanded:e,fields:t,applyId:n},aiQuery:a})=>({expanded:e,queryChanged:!x(t),filterHasContent:""!==t.filter.string,valid:y(t),applyId:n,isAIInputVisible:a.isInputVisible,isAIFetching:"fetching"===a.status})),((e,t)=>({onExplain:()=>{e(me())},onExplainRawOutput:()=>{e(me("raw-output"))},onExplainInterpret:()=>{e(me("interpret"))},onOpenExportToLanguage:()=>{e(((e,t,{localAppRegistry:n})=>{n?.emit("open-query-export-to-language",Object.fromEntries(Object.entries(t().queryBar.fields).map((([e,t])=>[e,t.string]))),"Query")}))},onApply:()=>{const n=e((a=t.source,(e,t,{preferences:n})=>{const{queryBar:{fields:r,favoriteQueries:i}}=t();if(!function(e,t){return Object.entries(e).every((([e,n])=>!1!==v(e,n.string,t)))}(r,n.getPreferences()))return!1;const o=g(r);e({type:ae,query:o,source:a});const s=A(o),l=i.find((e=>D(A(e),s)));return e(l?fe(l):he(o)),o}));var a;!1!==n&&t.onApply?.(n)},onReset:()=>{const n=e((a=t.source,(e,t,{preferences:n})=>{if(x(t().queryBar.fields))return!1;const r=f(n.getPreferences(),c);return e({type:re,fields:r,source:a}),(0,u.cloneDeep)(d)}));var a;!1!==n&&t.onReset?.(n)},onShowAIInputClick:()=>{e((async(e,t,{atlasAiService:n})=>{try{"true"!==T.env.COMPASS_E2E_SKIP_AI_OPT_IN&&await n.ensureAiFeatureAccess(),e({type:F})}catch{}}))},onHideAIInputClick:()=>{e((e=>{e($()),e({type:W})}))}})))((({buttonLabel:e="Apply",onApply:t,onReset:n,queryOptionsLayout:i=["project",["sort","maxTimeMS"],["collation","skip","limit"],"hint"],queryChanged:o,resultId:s,applyId:c,filterHasContent:d,showExplainButton:u=!1,valid:p,expanded:m,placeholders:g,onExplain:h,onExplainRawOutput:f,onExplainInterpret:y,isAIInputVisible:b=!1,isAIFetching:v=!1,onShowAIInputClick:x,onHideAIInputClick:E,source:C})=>{const w=(0,N.D27)(),I=(0,He.Rs)(),S=(0,Fe.Jr)(),A=(0,He.Fg)("enableSearchActivationProgramP2"),{getIsAssistantEnabled:k}=(0,Zt.hb)(),D=k(),M=(0,a.useMemo)((()=>[{action:"interpret",label:"Interpret",icon:"Sparkle",isDisabled:!D},{action:"visual-tree",label:"Visual tree",icon:"Diagram"},{action:"raw-output",label:"Raw output",icon:"CurlyBraces"}]),[D]),T=(0,a.useCallback)((e=>{"interpret"===e?y?.():"visual-tree"===e?h?.():f?.()}),[h,f,y]),P=(0,a.useCallback)((e=>{e.preventDefault(),t()}),[t]),L=(0,a.useMemo)((()=>I&&!b?(0,Re.gs)({onClickAI:()=>{x()},darkMode:w,placeholderText:We.filter.placeholder,track:S}):g?.filter),[I,b,w,g?.filter,x,S]),O=(0,a.useMemo)((()=>!(b||!I)&&d),[I,b,d]),R=!!(0,qt.n_)(),H=!!(0,qt.gp)(),F=(0,He.Fg)("enableMyQueries"),W=R&&H&&F,j=De();(0,Zt.ZX)("currentQuery",(0,l.AO)(j)||null);const B=(0,we.jj)(),z=(0,a.useCallback)((()=>{S("Query Reset Clicked",{source:C},B.current),n()}),[B,n,C,S]);return r().createElement("form",{className:(0,N.cx)(Jt,w&&Qt),"data-testid":"query-bar",onSubmit:P,noValidate:!0,"data-result-id":s,"data-apply-id":c},I&&r().createElement(Ut,{onClose:()=>{E?.()},show:b}),r().createElement("div",{className:Xt},W&&r().createElement(Kt,null),r().createElement("div",{className:en},r().createElement(at,{name:"filter",id:"query-bar-option-input-filter",onApply:t,placeholder:L,disabled:v}),O&&r().createElement("div",{className:tn},r().createElement(Re.dq,{"data-testid":"ai-experience-query-entry-button",onClick:x,type:"query"}))),u&&(A?r().createElement(N.F1Z,{"data-testid":"query-bar-explain-dropdown-button",buttonText:"Explain",buttonProps:{size:"small",disabled:!p||v},actions:M,onAction:T,hideOnNarrow:!1}):r().createElement(N.$nd,{"aria-label":"Explain query",title:"View the execution plan for the current query","data-testid":"query-bar-explain-button",onClick:h,disabled:!p||v,size:"small",type:"button"},"Explain")),r().createElement(N.$nd,{"aria-label":"Reset query","data-testid":"query-bar-reset-filter-button",onClick:z,disabled:!o||v,size:"small",type:"button"},"Reset"),r().createElement(N.$nd,{"data-testid":"query-bar-apply-filter-button",disabled:!p||v,variant:"primary",size:"small",type:"submit",onClick:P},e),i&&i.length>0&&r().createElement("div",null,r().createElement(an,{"aria-controls":"additional-query-options-container","data-testid":"query-bar-options-toggle"}))),m&&i&&i.length>0&&r().createElement("div",{className:nn,id:"additional-query-options-container"},i.map(((e,n)=>r().createElement(Vt,{queryOptionsLayout:e,key:`query-bar-row-${n}`,onApply:t,disabled:v,placeholders:g})))))})),on=(0,i.nk)({name:"QueryBar",component:function({children:e}){return r().createElement(ke,{value:rn},e)},activate:function(e,t,{on:n,cleanup:a}){const{serverVersion:r,query:i,namespace:l}=e,{localAppRegistry:d,globalAppRegistry:u,instance:p,dataService:m,preferences:g,logger:h,track:y,connectionInfoRef:b,atlasAiService:v,favoriteQueryStorageAccess:x,recentQueryStorageAccess:E,collection:C}=t,w=x?.getStorage(),I=E?.getStorage(),S=function(e={},t){return(0,o.y$)(Ce,{queryBar:{...Q,...e}},(0,o.Tw)(s.A.withExtraArgument(t)))}({namespace:l??"",host:m?.getConnectionString().hosts.join(","),serverVersion:r??"3.6.0",fields:f(g.getPreferences(),{...c,...A(i??{})}),isReadonlyConnection:!p.isWritable},{dataService:t.dataService??{sample:()=>Promise.resolve([])},localAppRegistry:d,globalAppRegistry:u,recentQueryStorage:I,favoriteQueryStorage:w,preferences:g,logger:h,track:y,connectionInfoRef:b,atlasAiService:v,collection:C});return n(p,"change:isWritable",(()=>{S.dispatch({type:X,readonly:!p.isWritable})})),S.dispatch(ue()),{store:S,deactivate:a,context:be}}},{dataService:we.S1,instance:Ie.A$,preferences:He.fx,logger:(0,M.fF)("COMPASS-QUERY-BAR-UI"),track:Fe.yL,connectionInfoRef:we.wj,atlasAiService:Re.Dr,favoriteQueryStorageAccess:qt.yS,recentQueryStorageAccess:qt.HP,collection:Ie.KK}),sn=e=>{const t=(0,a.useContext)(Ae);return r().createElement(t,e)},ln=on},25607:(e,t,n)=>{n.d(t,{Ay:()=>M,bM:()=>N,jv:()=>D,EK:()=>k});var a=n(96652),r=n.n(a),i=n(62183),o=n(82162),s=n(90605),l=n(26250);const c=["name","path","count","type"];function d(e,t){return(0,s.mergeWith)(e,t,(function(e,t,n){return"count"===n?(0,s.isNumber)(e)&&(0,s.isNumber)(t)?e+t:t:"type"===n?e===t?e:(0,s.isString)(e)?(0,s.uniq)([e,t]):(0,s.isArray)(e)?(0,s.uniq)(e.concat(t)):t:void 0}))}function u(e,t){for(const n of t)"Document"===n.name&&p(e,n.fields),"Array"===n.name&&u(e,n.types)}function p(e,t){if(t)for(const n of t){const t=n.path.join("."),a=e[t]||{},r=(0,s.pick)(n,c);e[t]=d(a,r);for(const t of n.types)"Document"===t.name&&p(e,t.fields),"Array"===t.name&&u(e,t.types)}}function m(e,t){return e.type===t}const g="field-store/CONNECTION_DISCONNECTED",h="field-store/DOCUMENTS_UPDATED",f="field-store/SCHEMA_UPDATED",y=(e={},t)=>{if(m(t,h)||m(t,f)){const n=(e[t.connectionInfoId]??{})[t.namespace]??{},{fields:a,topLevelFields:r}=function(e,t){e=(0,s.cloneDeep)(e);const n=[];for(const e of t)n.push(e.name);return p(e,t),{fields:e,topLevelFields:n}}(n.fields??{},t.schemaFields);return{...e,[t.connectionInfoId]:{...e[t.connectionInfoId],[t.namespace]:{fields:a,topLevelFields:(0,s.uniq)((n.topLevelFields??[]).concat(r))}}}}return m(t,g)?(0,s.omit)(e,t.connectionInfoId):e};var b=n(19125);const v=r().createContext(null),x=(0,b.Nk)(v),E=(0,b.iI)(v),C=(0,b.jO)(v);var w=n(67219),I=n(60783),S=n(44142);const A=Object.create(null);function k(e){const{id:t}=(0,I.qm)();let n=A;try{n=C((n=>n[t]?.[e]?.fields??A))}catch(e){throw e}return n}function D(e){const t=k(e);return(0,a.useMemo)((()=>function(e){return Object.entries(e).map((([e,t])=>{return{name:e,value:e,score:1,meta:"field",version:"0.0.0",description:(n=t.type,"string"==typeof n?n:(0,s.uniq)(n.flat()).join(" | "))};var n}))}(t)),[t])}const N=(0,i.mb)((function(){const e=E(),t=x(),n=(0,I.jj)();return function(e,t,n){return{async updateFieldsFromDocuments(t,a){await e(((e,t,n)=>async(a,r,{logger:{mongoLogId:i,log:o}})=>{try{const{fields:r}=await(0,l.D0)(n);a({type:h,connectionInfoId:e,namespace:t,schemaFields:r})}catch(e){o.warn(i(1001000328),"Field Store","Failed to generate schema for documents",{error:e.message})}})(n.current.id,t,a))},updateFieldsFromSchema(t,a){e(((e,t,n)=>({type:f,connectionInfoId:e,namespace:t,schemaFields:n.fields}))(n.current.id,t,a))},getSchemaFieldsForNamespace(e){const a=t();return a[n.current.id]?.[e]?.fields}}}(e,t.getState.bind(t),n)}),"fieldStoreServiceLocator"),M=(0,i.nk)({name:"FieldStore",component:({children:e})=>r().createElement(r().Fragment,null,e),activate:function(e,{connections:t,logger:n},{on:a,cleanup:r}){const i=(0,o.y$)(y,(0,o.Tw)(w.A.withExtraArgument({logger:n})));return a(t,"disconnected",(e=>{i.dispatch((e=>({type:g,connectionInfoId:e}))(e))})),{store:i,deactivate:r,context:v}}},{connections:I.u4,logger:(0,S.fF)("COMPASS-FIELDS-STORE")})},26544:(e,t,n)=>{n.d(t,{h:()=>d});var a=n(64424),r=n.n(a),i=n(78268),o=n(45863),s=n.n(o),l=n(15088).process;function c(e,t,n){e?.callQuiet?.(t,n),void 0!==l&&"function"==typeof l.emit&&l.emit(t,n)}function d(e){const t=r()?n(88992).ipcRenderer:null;return function(e,t){const n={write(e,n){t("compass:log",{line:e}),n()},end(e){e()}},a=new i.MongoLogWriter("",null,n),r=a.bindComponent(e),o=s()(`mongodb-compass:${e.toLowerCase()}`);return a.on("log",(({s:e,ctx:t,msg:n,attr:a})=>{o(n,a?{s:e,ctx:t,...a}:{s:e,ctx:t})})),{log:r,mongoLogId:i.mongoLogId,debug:o}}(e,c.bind(null,t))}s()("mongodb-compass")},26783:(e,t,n)=>{n.d(t,{EE:()=>I,Gv:()=>S,Ng:()=>h,PM:()=>b,Pj:()=>p,Ul:()=>k,VW:()=>D,cy:()=>v,d4:()=>g,n5:()=>w,tI:()=>y,u4:()=>x,w2:()=>C,wA:()=>u,xO:()=>A,y2:()=>N}),n(21261),n(92879),n(31977),n(49743),n(9656),n(72673),n(35467),n(94476),n(64971),n(24330),n(83478),n(65166),n(1256),n(61038),n(73035),n(23855);var a=n(96652),r=n.n(a),i=n(19125),o=n(44969),s=n(96452),l=n(62183),c=n(90605),d=n(51295);const u=r().createContext(null),p=(0,i.Nk)(u),m=(0,i.iI)(u),g=(0,i.jO)(u),h=(e,t=null,n=null)=>(0,i.Ng)(e,t,n,{context:u}),f=(0,a.createContext)(null),y=({children:e})=>{const t=m(),[n]=(0,a.useState)((()=>function(e){return{connect:t=>e((0,o.Ng)(t)),connectInNewWindow:t=>e((0,o.GK)(t)),saveAndConnect:t=>e((0,o.F)(t)),disconnect:t=>e((0,o.Zf)(t)),createNewConnection:()=>e((0,o.Pj)()),editConnection:t=>e((0,o.FS)(t)),duplicateConnection:(t,n)=>e((0,o.WH)(t,n)),saveEditedConnection:t=>e((0,o.RW)(t)),cancelEditConnection:t=>{e((0,o.vS)(t))},toggleFavoritedConnectionStatus:t=>e((0,o.J)(t)),removeConnection:t=>e((0,o.zN)(t)),removeAllRecentConnections:()=>e((0,o.GQ)()),showNonGenuineMongoDBWarningModal:t=>e((0,o.hL)(t)),importConnections:t=>e((0,o.zz)(t)),refreshConnections:()=>e((0,o.n7)())}}(t)));return r().createElement(f.Provider,{value:n},e)};function b(){const e=(0,a.useContext)(f);if(!e)throw new Error("Can't find connection actions in context. Are you using useConnectionActions hook in correct environment?");return e}function v(){const e=(0,a.useRef)(p()),[t]=(0,a.useState)((()=>({getConnectionById(t){const n=e.current.getState().connections.byId[t];if(n)return{...n,title:(0,s.T8)(n.info)}},get current(){return Object.values(e.current.getState().connections.byId).map((e=>({...e,title:(0,s.T8)(e.info)})))}})));return t}const x=(0,l.mb)((function(){const e=b(),t=v();return(0,d.nfZ)({...e,...t,getDataServiceForConnection:o.HP,on:o.Kw.on,off:o.Kw.off,removeListener:o.Kw.removeListener})}),"connectionsLocator");function E(e,t){if(null===e||null===t)return e===t;const n=new Set(Object.keys(e).concat(Object.keys(t)));for(const a of n)if(e[a]!==t[a])return!1;return!0}function C(e){return g((t=>t.connections.ids.filter((n=>e?.(t.connections.byId[n])??!0))),((e,t)=>(0,c.isEqual)(e,t)))}function w(e){return g((t=>t.connections.ids.filter((n=>e?.(t.connections.byId[n])??!0)).map((e=>{const n=t.connections.byId[e];return{...n,title:(0,s.T8)(n.info)}}))),((e,t)=>e.length===t.length&&(0===e.length||e.every(((e,n)=>E(e,t[n]))))))}function I(e){return g((t=>{const n=t.connections.byId[e];return n?{...n,title:(0,s.T8)(n.info)}:null}),((e,t)=>E(e,t)))}function S(e){return g((t=>{if(!e)return null;const n=t.connections.byId[e];return n?{...n.info,title:(0,s.T8)(n.info)}:null}),((e,t)=>E(e,t)))}function A(e){const t=p(),[n]=(0,a.useState)((()=>({get current(){const n=t.getState().connections.byId[e];return n?{...n.info,title:(0,s.T8)(n.info)}:null}})));return n}function k(){return g((e=>Object.values(e.connections.byId).map((e=>({id:e.info.id,color:e.info.favorite?.color})))),c.isEqual)}function D(){return g((e=>{const t=e.connections.status;return{status:t,error:e.connections.error?.message??null,isInitialLoad:"initial"===t||"loading"===t}}),c.isEqual)}const N=(0,c.memoize)((e=>Object.values(e).filter((e=>"connected"===e.status))))},28592:(e,t,n)=>{n.d(t,{S:()=>r,m:()=>a});const a=[{name:"find",description:"Retrieves specific documents that match your search criteria."},{name:"aggregate",description:"Performs complex data processing, grouping, and calculations."},{name:"count",description:"Quickly returns the total number of documents matching a query."},{name:"list-databases",description:"Displays all available databases in the connected cluster."},{name:"list-collections",description:"Shows all collections within a specified database."},{name:"collection-schema",description:"Describes the schema structure of a collection."},{name:"collection-indexes",description:"Lists all indexes defined on a collection."},{name:"collection-storage-size",description:"Returns the storage size information for a collection."},{name:"db-stats",description:"Provides database statistics including size and usage."},{name:"explain",description:"Provides execution statistics and query plan information."},{name:"mongodb-logs",description:"Returns the most recent logged mongod events."}],r=[...a,{name:"get-current-query",description:"Get the current query from the querybar."},{name:"get-current-pipeline",description:"Get the current pipeline from the aggregation builder."}]},29794:e=>{e.exports={getProperties:function(e){const t=[];return e.collation&&t.push({id:"collation",options:e.collation}),"timeseries"===e.type&&t.push({id:"timeseries"}),"view"===e.type&&t.push({id:"view"}),e.is_capped&&t.push({id:"capped"}),e.clustered&&t.push({id:"clustered"}),e.readonly&&t.push({id:"read-only"}),e.fle2&&t.push({id:"fle2"}),t}}},29851:(e,t,n)=>{n.d(t,{l:()=>d});var a=n(96652),r=n.n(a);function i(e,t){return{...t({...e}),...e.submenu?{submenu:e.submenu.map((e=>i(e,t)))}:void 0}}n(70140),n(41652),n(13353);const o=new WeakMap;let s=0;function l(e){let t=o.get(e);return void 0===t&&(t=++s,o.set(e,t)),t}const c=r().createContext({showApplicationMenu:()=>()=>{},handleMenuRole:()=>()=>{}});function d({menu:e,roles:t}){const{showApplicationMenu:n,handleMenuRole:r}=(0,a.useContext)(c);(0,a.useEffect)((()=>{const a=[e&&n(e),...Object.entries(t??{}).map((([e,t])=>r(e,t)))];return()=>{for(const e of a)e?.()}}),[n,r,e?JSON.stringify(i(e,(e=>({...e,click:e.click&&l(e.click)})))):void 0,t?JSON.stringify(Object.values(t).map(l)):void 0])}},34426:(e,t,n)=>{n.d(t,{_:()=>o,h:()=>i}),n(59509),n(25691),n(23177),n(3142),n(51615),n(84217),n(25953),n(42319),n(28465),n(12887),n(36106),n(84542),n(57068),n(69517);var a=n(4580),r=n(91399);const i={InstanceCreated:"instance-started",InstanceRemoved:"instance-removed"};class o extends a.EventEmitter{instances=new Map;createMongoDBInstanceForConnection(e,t){const n=new r.MongoDBInstance(t);return this.instances.set(e,n),this.emit(i.InstanceCreated,e,n),n}listMongoDBInstances(){return new Map(this.instances)}getMongoDBInstanceForConnection(e){const t=this.instances.get(e);if(!t)throw new Error(`MongoDBInstance for connectionId - ${e} not present in InstancesManager.`);return t}removeMongoDBInstanceForConnection(e){this.instances.delete(e),this.emit(i.InstanceRemoved,e)}on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}removeListener(e,t){return super.removeListener(e,t)}emit(e,...t){return super.emit(e,...t)}}},36214:(e,t,n)=>{n.d(t,{U5:()=>c,c5:()=>d,jo:()=>l});var a=n(96652),r=n.n(a),i=n(62183);const o={status:"INITIAL",error:null,items:[],save:()=>Promise.resolve(!1),delete:()=>Promise.resolve(!1),loadAll:()=>Promise.resolve([]),load:()=>Promise.resolve(null)},s=r().createContext(o),l=({storage:e,children:t})=>{const n=(0,a.useRef)(e),[i,o]=(0,a.useState)({status:"INITIAL",error:null,items:[]}),l=(0,a.useMemo)((()=>({...i,save:async e=>(o((t=>{const n=t.items.findIndex((t=>t.id===e.id));return-1===n?t.items.push(e):t.items[n]=e,{...t,items:[...t.items]}})),n.current.save(e)),delete:async e=>(o((t=>({...t,items:t.items.filter((t=>t.id!==e))}))),n.current.delete(e)),async loadAll(){o((e=>({...e,status:"INITIAL"===e.status?"LOADING":"REFRESHING"})));try{const e=await n.current.loadAll();return o((t=>({...t,items:e,error:null,status:"READY"}))),e}catch(e){throw o((t=>({...t,error:e,status:"ERROR"}))),e}},async load(e){return(await this.loadAll()).find((t=>t.id===e))??null}})),[i]),c=(0,a.useRef)(l);return(0,a.useEffect)((()=>{c.current.loadAll().catch((()=>{}))}),[]),r().createElement(s.Provider,{value:l},t)};function c(){const{status:e,error:t,items:n}=(0,a.useContext)(s);return{status:e,error:t,items:n}}const d=(0,i.mb)((()=>{const e=(0,a.useContext)(s);return{save:e.save.bind(e),delete:e.delete.bind(e),loadAll:e.loadAll.bind(e),load:e.load.bind(e)}}),"dataModelStorageServiceLocator")},37334:(e,t,n)=>{n.d(t,{R:()=>Qe});var a=n(96652),r=n.n(a),i=n(62183),o=n(19125),s=n(51295);function l(e,t){return e.type===t}const c="global-writes/ManagedNamespaceFetched",d="global-writes/NamespaceShardingErrorFetched",u="global-writes/NamespaceShardKeyFetched",p="global-writes/ShardZonesFetched",m="global-writes/ShardZonesFetchedError",g="global-writes/SubmittingForShardingStarted",h="global-writes/SubmittingForShardingFinished",f="global-writes/SubmittingForShardingErrored",y="global-writes/CancellingShardingStarted",b="global-writes/CancellingShardingFinished",v="global-writes/CancellingShardingErrored",x="global-writes/UnmanagingNamespaceStarted",E="global-writes/UnmanagingNamespaceFinished",C="global-writes/UnmanagingNamespaceErrored",w="global-writes/LoadingFailed",I="NOT_READY",S="LOADING_ERROR",A="UNSHARDED",k="INCOMPLETE_SHARDING_SETUP",D="SHARDING",N="SHARDING_ERROR",M="SHARD_KEY_INVALID",T="SHARD_KEY_MISMATCH",P="SHARD_KEY_CORRECT",L={namespace:"",status:I,shardZones:[]},O=e=>async(t,n,{atlasGlobalWritesService:a,logger:r,connectionInfoRef:i})=>{const{namespace:o,userActionInProgress:l}=n();if(l)r.log.warn(r.mongoLogId(1001000337),"Global writes duplicate action",`SubmittingForSharding triggered while another action is in progress - ${l}`);else{t({type:g});try{const n=await a.manageNamespace(o,e);t(F(n))}catch(n){r.log.error(r.mongoLogId(1001000331),"AtlasFetchError","Error creating cluster shard key",{error:n.message,data:e}),(0,s.c3r)(`global-writes-create-shard-key-error-${i.current.id}-${o}`,{title:`Failed to create shard key: ${n.message}`,dismissible:!0,timeout:5e3,variant:"important"}),t({type:f})}}},R=s.$TK,H=()=>async(e,t,{atlasGlobalWritesService:n,logger:a,pollingTimeoutRef:r})=>{if(!await R({title:"Confirmation",description:"Are you sure you want to cancel the sharding request?"}))return;const{namespace:i,status:o,userActionInProgress:l}=t();if(l)a.log.warn(a.mongoLogId(1001000335),"Global writes duplicate action",`CancelSharding triggered while another action is in progress - ${l}`);else{o===D&&j(r),e({type:y});try{await n.unmanageNamespace(i),e({type:b})}catch(t){a.log.error(a.mongoLogId(1001000334),"AtlasFetchError","Error cancelling the sharding process",{error:t.message}),(0,s.c3r)("global-writes-cancel-sharding-error",{title:`Failed to cancel the sharding process: ${t.message}`,dismissible:!0,timeout:5e3,variant:"important"}),e({type:v})}}},F=e=>t=>{t({type:h,managedNamespace:e}),t(W())},W=()=>(e,t,{pollingTimeoutRef:n})=>{n.current||(n.current=setTimeout((()=>{e(z())}),5e3))},j=e=>{e.current&&clearTimeout(e.current)},B=({error:e,id:t,description:n})=>(a,r)=>{const{status:i}=r(),o=i===D,l=i===I,c=`${n}: ${e.message}`;l||o?a({type:w,error:c}):(0,s.c3r)(t,{title:c,dismissible:!0,timeout:5e3,variant:"important"})},z=()=>async(e,t,{atlasGlobalWritesService:n,logger:a,connectionInfoRef:r,pollingTimeoutRef:i})=>{i.current=null;const{namespace:o,managedNamespace:s}=t();try{const[t,a]=await Promise.all([n.getShardingError(o),n.getShardingKeys(o)]);if(s&&!a)return t?void e({type:d,error:t}):void e(F());if(e({type:u,shardKey:a}),!a)return;e(_())}catch(t){a.log.error(a.mongoLogId(1001000333),"AtlasFetchError","Error fetching shard key / deployment status",t.message),e(B({error:t,id:`global-writes-fetch-shard-key-error-${r.current.id}-${o}`,description:"Failed to fetch shard key or deployment status"}))}},_=()=>async(e,t,{atlasGlobalWritesService:n,connectionInfoRef:a})=>{const{shardZones:r}=t();if(!(r.length>0))try{const t=await n.getShardingZones();e({type:p,shardZones:t})}catch(t){e({type:m}),(0,s.c3r)(`global-writes-fetch-sharding-zones-error-${a.current.id}`,{title:`Failed to fetch sharding zones: ${t.message}`,dismissible:!0,timeout:5e3,variant:"important"})}},$=()=>async(e,t,{atlasGlobalWritesService:n,connectionInfoRef:a,logger:r})=>{const{namespace:i,userActionInProgress:o}=t();if(o)r.log.warn(r.mongoLogId(1001000336),"Global writes duplicate action",`UnmanageNamespace triggered while another action is in progress - ${o}`);else{e({type:x});try{await n.unmanageNamespace(i),e({type:E})}catch(t){e({type:C}),(0,s.c3r)(`global-writes-unmanage-namespace-error-${a.current.id}-${i}`,{title:`Failed to unmanage namespace: ${t.message}`,dismissible:!0,timeout:5e3,variant:"important"})}}};function Y(e,t){const[n,a]=e.fields;return"location"===n.name&&"RANGE"===n.type&&a?t?t&&t.isShardKeyUnique===e.isUnique&&a.name===t.customShardKey&&a.type===(t.isCustomShardKeyHashed?"HASHED":"RANGE")?P:T:k:M}const K=(e=L,t)=>l(t,c)&&e.status===I?{...e,managedNamespace:t.managedNamespace}:!l(t,d)||e.status!==I&&e.status!==D?l(t,u)&&(e.status===I||e.status===D)&&t.shardKey?{...e,status:Y(t.shardKey,e.managedNamespace),userActionInProgress:void 0,shardKey:t.shardKey,shardingError:void 0}:!l(t,u)||e.status!==I||t.shardKey||e.managedNamespace?l(t,p)?{...e,shardZones:t.shardZones}:l(t,m)?{...e,shardZones:[]}:l(t,v)||l(t,C)||l(t,f)?{...e,userActionInProgress:void 0}:!l(t,g)||e.status!==A&&e.status!==N&&e.status!==k?!l(t,h)||e.status!==A&&e.status!==N&&e.status!==k&&e.status!==I?!l(t,y)||e.status!==D&&e.status!==N&&e.status!==k?!l(t,b)||e.status!==D&&e.status!==N||e.shardKey?l(t,b)&&e.status===D&&e.shardKey?{...e,userActionInProgress:void 0,managedNamespace:void 0,shardKey:e.shardKey,shardingError:void 0,status:k}:!l(t,x)||e.status!==P&&e.status!==T?!l(t,E)||e.status!==P&&e.status!==T?!l(t,w)||e.status!==I&&e.status!==D?e:{...e,userActionInProgress:void 0,status:S,loadingError:t.error}:{...e,userActionInProgress:void 0,managedNamespace:void 0,status:k}:{...e,userActionInProgress:"unmanageNamespace"}:{...e,userActionInProgress:void 0,managedNamespace:void 0,shardKey:e.shardKey,shardingError:void 0,status:A}:{...e,userActionInProgress:"cancelSharding"}:{...e,userActionInProgress:void 0,shardingError:void 0,managedNamespace:t.managedNamespace||e.managedNamespace,status:D}:{...e,userActionInProgress:"submitForSharding"}:{...e,status:A}:{...e,status:N,shardKey:void 0,shardingError:t.error};var G=n(25607);const V=(0,s.AHW)({textAlign:"justify"}),U=((0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[100]}),(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[400],marginBottom:s.YKD[400],textAlign:"justify"})),q=(0,s.AHW)({float:"right",height:`${s.YKD[600]}px`}),Z=(0,s.AHW)({listStyle:"disc",paddingLeft:"auto",marginTop:0}),J=(0,s.AHW)({display:"flex",flexDirection:"row",gap:s.YKD[400]}),Q=(0,s.AHW)({width:"300px"}),X=(0,s.AHW)({marginLeft:s.YKD[1200],marginTop:s.YKD[400]}),ee=(0,s.AHW)({paddingLeft:s.YKD[500]}),te=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[100]}),ne=(0,s.AHW)({paddingLeft:s.YKD[400]});function ae(){return r().createElement("div",{className:U,"data-testid":"unsharded-text-description"},r().createElement(s.Pds,null,"Configure compound shard key"),r().createElement(s.nBu,null,"To properly configure Global Writes, your collections must be sharded using a compound shard key made up of a ‘location’ field and a second field of your choosing."),r().createElement(s.nBu,null,"All documents in your collection should contain both the ‘location’ field and your chosen second field."),r().createElement("ul",{className:Z},r().createElement("li",null,r().createElement(s.nBu,null,"The second field should represent a well-distributed and immutable value to ensure that data is equally distributed across shards in a particular zone."," ",r().createElement("strong",null,"Note that the value of this field cannot be an array.")," ","For more information, read our documentation on"," ",r().createElement(s.N_E,{hideExternalIcon:!0,href:"https://www.mongodb.com/docs/manual/core/sharding-shard-key/#choosing-a-shard-key"},"selecting a shard key"),"."))),r().createElement(s.nBu,{weight:"medium"},"Once you shard your collection, it cannot be unsharded."))}const re=(0,o.Ng)((e=>({namespace:e.namespace,isSubmittingForSharding:"submitForSharding"===e.userActionInProgress,isCancellingSharding:"cancelSharding"===e.userActionInProgress})),{onCreateShardKey:O})((function({namespace:e,isSubmittingForSharding:t,isCancellingSharding:n,onCreateShardKey:i}){const[o,l]=(0,a.useState)(!1),[c,d]=(0,a.useState)("default"),u=(0,G.jv)(e),[p,m]=(0,a.useState)(null),[g,h]=(0,a.useState)(),[f,y]=(0,a.useState)(!1),b=(0,a.useCallback)((()=>{if(!p)return;const e="hashed-index"===c,t=e&&f,n={customShardKey:p,isShardKeyUnique:"unique-index"===c,isCustomShardKeyHashed:e,presplitHashedZones:t,numInitialChunks:t&&g?Number(g):null};i(n)}),[f,g,p,c,i]);return r().createElement(r().Fragment,null,r().createElement(ae,null),r().createElement("div",{className:U,"data-testid":"shard-collection-form"},r().createElement("div",{className:J},r().createElement("div",null,r().createElement(s.JU7,{htmlFor:"first-shard-key"},"First shard key field",r().createElement(s.CAb,{"aria-label":"Connection String Documentation","data-testid":"connectionStringDocsButton",href:"https://docs.mongodb.com/manual/core/sharding-shard-key"})),r().createElement(s.ksK,{id:"first-shard-key","aria-labelledby":"First shard key field",placeholder:"location",disabled:!0})),r().createElement("div",null,r().createElement(s.JU7,{htmlFor:"second-shard-key"},"Second shard key field",r().createElement(s.CAb,{"aria-label":"Connection String Documentation","data-testid":"connectionStringDocsButton",href:"https://docs.mongodb.com/manual/core/zone-sharding/#shard-key"})),r().createElement(s.WqN,{id:"second-shard-key","data-testid":"second-shard-key","aria-label":"Second shard key field",placeholder:"Second shard key field",size:"default",clearable:!1,overflow:"scroll-x",onChange:m,options:u.map((({value:e})=>({value:e}))),className:Q,value:p,searchEmptyMessage:"No fields found. Please enter a valid field name.",renderOption:(e,t,n)=>r().createElement(s.jOs,{key:`field-option-${t}`,value:e.value,displayName:n?`Field: "${e.value}"`:e.value})}))),r().createElement(s.nD3,{"data-testid":"advanced-shard-key-configuration",text:"Advanced Shard Key Configuration",open:o,setOpen:l,className:ne},r().createElement(s.z6M,{className:ee,onChange:e=>{d(e.target.value)}},r().createElement(s.sxL,{value:"default",checked:"default"===c},"Default"),r().createElement(s.sxL,{id:"unique-index","data-testid":"unique-index",value:"unique-index",checked:"unique-index"===c},r().createElement("div",null,r().createElement(s.JU7,{htmlFor:"unique-index"},"Use unique index as the shard key"),r().createElement(s.nBu,null,"Enforce a uniqueness constraint on the shard key of this Global Collection."," ",r().createElement(s.N_E,{href:"https://docs.atlas.mongodb.com/data-explorer/global-writes/#optional-expand-advanced-shard-key-configuration-section-to-specify-how-to-shard-the-collection"},"Learn more")))),r().createElement(s.sxL,{id:"hashed-index","data-testid":"hashed-index",value:"hashed-index",checked:"hashed-index"===c},r().createElement("div",null,r().createElement(s.JU7,{htmlFor:"hashed-index"},"Use hashed index as the shard key"),r().createElement(s.nBu,null,"Improve even distribution of the sharded data by hashing the second field of the shard key."," ",r().createElement(s.N_E,{href:"https://docs.atlas.mongodb.com/data-explorer/global-writes/#optional-expand-advanced-shard-key-configuration-section-to-specify-how-to-shard-the-collection"},"Learn more"))))),"hashed-index"===c&&r().createElement("div",{className:(0,s.cx)(U,X)},r().createElement(s.Sc0,{"data-testid":"presplit-data-checkbox",onChange:()=>y(!f),label:"Pre-split data for even distribution.",checked:f}),r().createElement("div",{className:te},r().createElement(s.ksK,{"data-testid":"chunks-per-shard-input",id:"chunks-per-shard","aria-labelledby":"Chunks per shard",disabled:!f,type:"number",placeholder:"Chunks",min:0,value:g,onChange:e=>h(e.target.value)}),r().createElement(s.nBu,null,"chunks per shard.")))),r().createElement("div",null,r().createElement(s.$nd,{"data-testid":"shard-collection-button",onClick:b,disabled:!p||t||n,variant:"primary",isLoading:t,loadingIndicator:r().createElement(s.Q0K,null)},"Shard Collection"))))})),ie=function(){return r().createElement("div",{className:U},r().createElement(s.lZ$,{variant:s.uAY.Warning,className:V},r().createElement("strong",null,"To use Global Writes, this collection must be configured with a compound shard key made up of both a ‘location’ field and an identifier field that you should provide.")," ","See the instructions below for details."),r().createElement(re,null))},oe=(0,o.Ng)((e=>({isCancellingSharding:"cancelSharding"===e.userActionInProgress})),{onCancelSharding:H})((function({isCancellingSharding:e,onCancelSharding:t}){return r().createElement("div",{className:U},r().createElement(s.lZ$,{variant:s.uAY.Info,className:V},r().createElement("strong",null,"Sharding your collection …")," ","this should not take too long.",r().createElement(s.$nd,{className:q,"data-testid":"cancel-sharding-btn",onClick:t,isLoading:e,loadingIndicator:r().createElement(s.Q0K,null)},"Cancel Request")),r().createElement(s.nBu,null,"Once your collection is sharded, this tab will show instructions on document ‘location’ field formatting, and provide some common command examples."),r().createElement(s.N_E,{href:"https://www.mongodb.com/docs/atlas/global-clusters/",hideExternalIcon:!0},"You can read more about Global Writes in our documentation."))}));n(95039);var se=n(60783);const le=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[100]});function ce(){const{atlasMetadata:e}=(0,se.qm)();return r().createElement(r().Fragment,null,r().createElement(s.Pds,null,"Location Codes"),r().createElement("div",{className:le},r().createElement(s.nBu,null,"Each document’s first field should include an ISO 3166-1 Alpha-2 code for the location it belongs to."),r().createElement(s.nBu,null,"We also support ISO 3166-2 subdivision codes for countries containing a cloud provider data center (both ISO 3166-1 and ISO 3166-2 codes may be used for these countries). All valid country codes and the zones to which they map are listed in the table below. Additionally, you can view a list of all location codes"," ",r().createElement(s.N_E,{href:"/static/atlas/country_iso_codes.txt"},"here"),"."),r().createElement(s.nBu,null,e?.projectId&&e?.clusterName&&r().createElement(r().Fragment,null,"Locations’ zone mapping can be changed by navigating to this clusters"," ",r().createElement(s.N_E,{href:`/v2/${e?.projectId}#/clusters/edit/${e?.clusterName}`},"Edit Configuration")," ","page and clicking the Configure Location Mappings’ link above the map."))))}const de=(0,s.AHW)({height:"400px",overflow:"auto"}),ue=[{accessorKey:"locationName",header:"Location Name",enableSorting:!0},{accessorKey:"zone",header:"Zone",enableSorting:!0,enableGlobalFilter:!1}],pe=({isoCode:e,readableName:t,zoneName:n,zoneLocations:a})=>({locationName:`${t} (${e})`,zone:`${n} (${a.join(", ")})`});function me({shardZones:e}){const[t,n]=(0,a.useState)(""),[i,o]=(0,a.useState)({}),l=(0,a.useMemo)((()=>(e=>{const t=e.reduce(((e,t)=>{const{typeOneIsoCode:n,isoCode:a}=t;return e[n]??={...pe(t),subRows:[]},n===a?Object.assign(e[n],pe(t)):e[n].subRows.push(pe(t)),e}),{});return Object.values(t)})(e)),[e]),c=(0,s.iXE)({data:l,columns:ue,state:{globalFilter:t,expanded:""!==t||i},onGlobalFilterChange:n,onExpandedChange:o,enableGlobalFilter:!0,getFilteredRowModel:(0,s.hMH)(),getExpandedRowModel:(0,s.D0p)(),getIsRowExpanded:e=>t&&(e=>e.subRows.some((e=>Object.values(e.columnFilters).includes(!0))))(e)||"boolean"!=typeof i&&i[e.id],globalFilterFn:"auto",filterFromLeafRows:!0,maxLeafRowFilterDepth:2}),d=(0,s.HIF)(c),u=(0,a.useCallback)((e=>{d.current.setGlobalFilter(e.currentTarget?.value||"")}),[d]),{rows:p}=c.getRowModel();return r().createElement(r().Fragment,null,r().createElement(ce,null),r().createElement(s.DOo,{value:t,onChange:u,"aria-label":"Search for a location",placeholder:"Search for a location"}),r().createElement(s.XIK,{className:de,title:"Zone Mapping",table:c},r().createElement(s.ndF,{isSticky:!0},c.getHeaderGroups().map((e=>r().createElement(s.Syw,{key:e.id},e.headers.map((e=>r().createElement(s.A3f,{key:e.id,header:e},(0,s.KvR)(e.column.columnDef.header,e.getContext())))))))),r().createElement(s.BFY,null,p.map((e=>r().createElement(s.fI1,{key:e.id,row:e},e.getVisibleCells().map((e=>r().createElement(s.fhW,{key:e.id,cell:e},(0,s.KvR)(e.column.columnDef.cell,e.getContext()))))))))))}const ge=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[100]}),he=function({namespace:e,shardKey:t,showMetaData:n,type:a="existing"}){let i=t.fields.map((e=>`"${e.name}"`+(n?` (${e.type.toLowerCase()})`:""))).join(", ");return n&&(i+=` - unique: ${String(t.isUnique)}`),r().createElement("div",{className:ge},r().createElement(s.nBu,{"data-testid":`${a}-shardkey-description-title`},"existing"===a?r().createElement(r().Fragment,null,r().createElement("strong",null,e)," is configured with the following shard key:"):r().createElement(r().Fragment,null,"You requested to use the shard key:")),r().createElement(s.CyN,{language:"js","data-testid":`${a}-shardkey-description-content`},i))};var fe=n(17855);const ye=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[100]}),be=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[100]}),ve=function({namespace:e,shardKey:t}){const n=(0,a.useMemo)((()=>t.fields[1].name),[t]),i=(0,a.useMemo)((()=>{const{collection:t,database:a}=(0,fe.Ay)(e);return{findingDocuments:`use ${a}\ndb[${JSON.stringify(t)}].find({"location": "US-NY", "${n}": "<id_value>"})`,insertingDocuments:`use ${a}\ndb[${JSON.stringify(t)}].insertOne({"location": "US-NY", "${n}": "<id_value>",...<other fields>})`}}),[e,n]);return r().createElement(r().Fragment,null,r().createElement(s.Pds,null,"Example commands"),r().createElement("div",{className:be},r().createElement(s.nBu,null,"Start querying your database with some of the most"," ",r().createElement(s.N_E,{href:"https://www.mongodb.com/docs/atlas/global-clusters",hideExternalIcon:!0},"common commands")," ","for Global Writes."),r().createElement(s.nBu,null,"Replace the text to perform operations on different documents. US-NY is an ISO 3166 location code referring to New York, United States. You can look up other ISO 3166 location codes below.")),r().createElement("div",{className:ye},r().createElement(s.JU7,{htmlFor:"finding-documents"},"Finding documents"),r().createElement(s.CyN,{language:"js","data-testid":"sample-finding-documents",id:"finding-documents"},i.findingDocuments)),r().createElement("div",{className:ye},r().createElement(s.JU7,{htmlFor:"inserting-documents"},"Inserting documents"),r().createElement(s.CyN,{language:"js","data-testid":"sample-inserting-documents",id:"inserting-documents"},i.insertingDocuments)))},xe=(0,o.Ng)((e=>{if(!e.shardKey)throw new Error("Shard key not found in ShardKeyCorrect");return{namespace:e.namespace,shardKey:e.shardKey,shardZones:e.shardZones,isUnmanagingNamespace:"unmanageNamespace"===e.userActionInProgress}}),{onUnmanageNamespace:$})((function({namespace:e,shardKey:t,shardZones:n,isUnmanagingNamespace:i,onUnmanageNamespace:o}){const l=(0,a.useMemo)((()=>t.fields[1].name),[t]);return r().createElement("div",{className:U},r().createElement(s.lZ$,{variant:s.uAY.Info,className:V},r().createElement("strong",null,"All documents in your collection should contain both the ‘location’ field (with a ISO country or subdivision code) and your"," ",l," field at insert time.")," ","We have included a table for reference below."),r().createElement(he,{namespace:e,shardKey:t}),r().createElement(ve,{namespace:e,shardKey:t}),r().createElement(me,{shardZones:n}),r().createElement(s.Pds,null,"Unmanage this collection"),r().createElement(s.nBu,null,"Documents belonging to this collection will no longer be distributed across the shards of your global clusters."),r().createElement("div",null,r().createElement(s.$nd,{"data-testid":"unmanage-collection-button",onClick:o,variant:s.AkO.Default,isLoading:i,loadingIndicator:r().createElement(s.Q0K,null)},"Unmanage collection")))})),Ee=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[100]}),Ce=(0,o.Ng)((e=>{if(!e.shardKey)throw new Error("Shard key not found in ShardKeyInvalid");return{namespace:e.namespace,shardKey:e.shardKey}}))((function({shardKey:e,namespace:t}){return r().createElement("div",{className:U},r().createElement(s.lZ$,{variant:s.uAY.Danger,className:V},r().createElement("strong",null,'To configure Global Writes, the first shard key of this collection must be "location" with ranged sharding and you must also specify a second shard key.')," ","Please migrate the data in this collection to a new collection and reshard it using a valid compound shard key."),r().createElement(he,{namespace:t,shardKey:e,showMetaData:!0}),r().createElement("div",{className:Ee},"Documents in this collection will be distributed across your shards without being mapped to specific zones."))})),we=(0,o.Ng)((e=>{if(!e.shardKey)throw new Error("Shard key not found in ShardKeyMismatch");return{namespace:e.namespace,shardKey:e.shardKey,requestedShardKey:e.managedNamespace&&(t=e.managedNamespace,{fields:[{name:"location",type:"RANGE"},{name:t.customShardKey,type:t.isCustomShardKeyHashed?"HASHED":"RANGE"}],isUnique:t.isShardKeyUnique}),isUnmanagingNamespace:"unmanageNamespace"===e.userActionInProgress};var t}),{onUnmanageNamespace:$})((function({shardKey:e,requestedShardKey:t,namespace:n,onUnmanageNamespace:a,isUnmanagingNamespace:i}){return r().createElement("div",{className:U},r().createElement(s.lZ$,{variant:s.uAY.Danger,className:V},r().createElement("strong",null,"Your requested shard key cannot be configured because the collection has already been sharded with a different key.")," ","Please click the button below to unmanage this collection. If the existing shard key is valid, you can enable Global Writes for this collection on the next screen.",r().createElement("div",null,r().createElement(s.$nd,{"data-testid":"unmanage-collection-button",onClick:a,variant:s.AkO.Default,isLoading:i,loadingIndicator:r().createElement(s.Q0K,null),className:q},"Unmanage collection"))),r().createElement(he,{namespace:n,shardKey:e,showMetaData:!0}),t&&r().createElement(he,{namespace:n,shardKey:t,showMetaData:!0,type:"requested"}))})),Ie=(0,s.AHW)({marginTop:s.YKD[200],whiteSpace:"pre-wrap",textAlign:"left"}),Se=(0,o.Ng)((e=>{if(!e.shardingError)throw new Error("No shardingError found in ShardingError component");return{shardingError:e.shardingError,isCancellingSharding:"cancelSharding"===e.userActionInProgress,isSubmittingForSharding:"submitForSharding"===e.userActionInProgress}}),{onCancelSharding:H})((function({shardingError:e,isCancellingSharding:t,isSubmittingForSharding:n,onCancelSharding:a}){return r().createElement("div",{className:U},r().createElement(s.lZ$,{variant:s.uAY.Danger,className:V},"There was an error sharding your collection. Please cancel the request, make any necessary changes to your collection, and try again.",r().createElement("div",{className:Ie},e),r().createElement(s.$nd,{className:q,"data-testid":"cancel-sharding-btn",disabled:t||n,isLoading:t,loadingIndicator:r().createElement(s.Q0K,null),onClick:a},"Cancel Request")),r().createElement(re,null))})),Ae=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[400],marginBottom:s.YKD[400]}),ke=(0,o.Ng)((e=>{if(!e.shardKey)throw new Error("Shard key not found in IncompleteShardingSetup");return{namespace:e.namespace,shardKey:e.shardKey,shardZones:e.shardZones,isSubmittingForSharding:"submitForSharding"===e.userActionInProgress}}),{onResume:()=>async(e,t)=>{const{shardKey:n}=t();if(!n)throw new Error("Cannot resume managed namespace without a shardKey");const a={customShardKey:n.fields[1].name,isShardKeyUnique:n.isUnique,isCustomShardKeyHashed:"HASHED"===n.fields[1].type,numInitialChunks:null,presplitHashedZones:!1};await e(O(a))}})((function({shardKey:e,shardZones:t,namespace:n,onResume:a,isSubmittingForSharding:i}){return r().createElement("div",{className:Ae},r().createElement(s.lZ$,{variant:s.uAY.Warning},r().createElement("strong",null,"It looks like you've chosen a Global Writes shard key for this collection, but your configuration is incomplete.")," ","Please enable Global Writes for this collection to ensure that documents are associated with the appropriate zone. ",r().createElement(s.N_E,{href:"https://www.mongodb.com/docs/atlas/global-clusters/",target:"_blank",rel:"noreferrer"},"Read more about Global Writes"),r().createElement("div",null,r().createElement(s.$nd,{"data-testid":"manage-collection-button",onClick:a,variant:s.AkO.Default,isLoading:i,loadingIndicator:r().createElement(s.Q0K,null),className:q},"Enable Global Writes"))),r().createElement(he,{namespace:n,shardKey:e}),r().createElement(ve,{namespace:n,shardKey:e}),r().createElement(me,{shardZones:t}))})),De=(0,o.Ng)((e=>{if(e.status!==S)throw new Error("Error not found in LoadingError");return{error:e.loadingError}}))((function({error:e}){return r().createElement("div",{className:U},r().createElement(s.dFH,{errors:e}))})),Ne=(0,s.AHW)({display:"flex",width:"100%",paddingTop:s.YKD[400],paddingLeft:s.YKD[400],paddingRight:s.YKD[400],maxWidth:"700px"}),Me=(0,s.AHW)({display:"flex",alignItems:"flex-start",justifyContent:"center",width:"100%",marginTop:2*s.YKD[1800]});function Te({shardingStatus:e}){return e===A?r().createElement(ie,null):e===D?r().createElement(oe,null):e===N?r().createElement(Se,null):e===P?r().createElement(xe,null):e===M?r().createElement(Ce,null):e===T?r().createElement(we,null):e===k?r().createElement(ke,null):e===String(S)?r().createElement(De,null):null}const Pe=(0,o.Ng)((e=>({shardingStatus:e.status})))((function({shardingStatus:e}){return e===I?r().createElement("div",{className:Me,"data-status":e.toLowerCase()},r().createElement(s.iyS,{progressText:"Loading …"})):r().createElement(s.XvC,{"data-status":e.toLowerCase()},r().createElement(s.ETl,null,r().createElement("div",{className:Ne},r().createElement(Te,{shardingStatus:e}))))})),Le=(0,s.AHW)({display:"flex",gap:s.YKD[200],alignItems:"center"}),Oe=(0,s.AHW)({display:"flex"}),Re=(0,s.AHW)({color:s.MFm.red.dark2}),He=(0,s.AHW)({color:s.MFm.red.base}),Fe=(0,s.AHW)({color:s.MFm.yellow.dark2}),We=(0,s.AHW)({color:s.MFm.yellow.base}),je=({darkMode:e})=>r().createElement(s.Int,{glyph:"Warning","aria-label":"warning",className:(0,s.cx)(Oe,Re,e&&He)}),Be=({darkMode:e})=>r().createElement(s.Int,{glyph:"ImportantWithCircle","aria-label":"important",className:(0,s.cx)(Oe,Fe,e&&We)}),ze=(0,o.Ng)((({status:e})=>{const t=[I,P],n=[S,N,T,M].includes(e);return{showError:n,showWarning:!n&&!t.includes(e)}}))((({showError:e,showWarning:t})=>{const n=!!(0,s.D27)();return r().createElement("div",{"data-testid":"global-writes-tab-title",className:Le},"Global Writes"," ",(e||t)&&r().createElement(s.m_M,{"data-testid":"collection-stats-tooltip",align:"bottom",justify:"middle",trigger:r().createElement("span",{onClick:()=>{}},e?r().createElement(je,{darkMode:n}):r().createElement(Be,{darkMode:n}))},r().createElement(s.nBu,null,"Collections in Atlas Global Clusters with Atlas-managed sharding must be configured with a compound shard key made up of both a 'location' field and an identifier field that you provide. Please configure sharding here.")))}));var _e=n(82162),$e=n(67219),Ye=n(33692),Ke=n.n(Ye);const Ge=/\[\d{1,2}:\d{2}:\d{2}\.\d{3}\]/;function Ve(e){if(!Array.isArray(e?.geoSharding?.managedNamespaces))throw new Error("Invalid cluster details API response geoSharding.managedNamespaces");if("object"!=typeof e?.geoSharding?.customZoneMapping)throw new Error("Invalid cluster details API response geoSharding.customZoneMapping");if(!Array.isArray(e?.replicationSpecList))throw new Error("Invalid cluster details API response replicationSpecList")}class Ue{atlasService;connectionInfo;constructor(e,t){this.atlasService=e,this.connectionInfo=t}getAtlasMetadata(){if(!this.connectionInfo.current?.atlasMetadata)throw new Error("Atlas metadata is not available");return this.connectionInfo.current.atlasMetadata}async getClusterDetails(){const{projectId:e,clusterName:t}=this.getAtlasMetadata(),n=this.atlasService.cloudEndpoint(`nds/clusters/${e}/${t}`),a=await this.atlasService.authenticatedFetch(n),r=await a.json();return Ve(r),r}async getManagedNamespace(e){const t=await this.getClusterDetails(),{database:n,collection:a}=(0,fe.Ay)(e);return t.geoSharding.managedNamespaces.find((e=>e.db===n&&e.collection===a))}async manageNamespace(e,t){const n=await this.getClusterDetails(),{database:a,collection:r}=(0,fe.Ay)(e),i={...n.geoSharding,managedNamespaces:[...n.geoSharding.managedNamespaces,{db:a,collection:r,...t}]},{projectId:o,clusterName:s}=this.getAtlasMetadata(),l=this.atlasService.cloudEndpoint(`nds/clusters/${o}/${s}/geoSharding`),c=await this.atlasService.authenticatedFetch(l,{method:"PATCH",body:JSON.stringify(i),headers:{"Content-Type":"application/json"}});Ve(await c.json());const d=i.managedNamespaces.find((e=>e.db===a&&e.collection===r));if(!d)throw new Error("Managed namespace not found");return d}async getShardingError(e){const{projectId:t}=this.getAtlasMetadata(),n=this.atlasService.cloudEndpoint(`/automation/deploymentStatus/${t}`),a=await this.atlasService.authenticatedFetch(n),r=await a.json();!function(e){if(!Array.isArray(e?.automationStatus?.processes))throw new Error("Invalid automation agent deployment status API response automationStatus.processes")}(r);const i=r.automationStatus.processes.find((t=>"ERROR"===t.statusType&&"ShardCollections"===t.workingOnShort&&-1!==t.errorText.indexOf(e)));if(!i)return;const o=i.errorText.split(Ge);return o[o.length-1].trim()}async getShardingKeys(e){const{database:t,collection:n}=(0,fe.Ay)(e),a=this.getAtlasMetadata(),r=await this.atlasService.automationAgentRequest(a,"getShardKey",{db:t,collection:n});if(!r)throw new Error("Unexpected response from the automation agent backend: expected to get the request metadata, got undefined");const i=(await this.atlasService.automationAgentAwait(a,r.requestType,r._id)).response;if(0===i.length)return;const{key:o,unique:s}=i[0];return{fields:Object.keys(o).map((e=>({name:e,type:"hashed"===o[e]?"HASHED":"RANGE"}))),isUnique:!!s}}async getShardingZones(){const{projectId:e}=this.getAtlasMetadata(),{replicationSpecList:t,geoSharding:{customZoneMapping:n}}=await this.getClusterDetails(),a=this.atlasService.cloudEndpoint(`/nds/geoSharding/${e}/newFormLocationMapping`),r=await this.atlasService.authenticatedFetch(a,{method:"POST",body:JSON.stringify({replicationSpecs:t,customZoneMapping:n}),headers:{"Content-Type":"application/json"}}),i=await r.json();return function(e){if("object"!=typeof e)throw new Error("Invalid shard zones API response")}(i),function(e,t){const n=Ke()(t,"zoneId");return e.map((e=>({zoneId:e.zoneId,country:e.country,readableName:e.readableName,isoCode:e.isoCode,typeOneIsoCode:e.typeOneIsoCode,zoneName:n[e.zoneId].zoneName,zoneLocations:n[e.zoneId].regionConfigs.map((e=>e.regionView.location))})))}(Object.values(i),t)}async unmanageNamespace(e){const t=await this.getClusterDetails(),{database:n,collection:a}=(0,fe.Ay)(e),r=t.geoSharding.managedNamespaces.filter((e=>e.db!==n||e.collection!==a)),i={...t.geoSharding,managedNamespaces:r},{projectId:o,clusterName:s}=this.getAtlasMetadata(),l=this.atlasService.cloudEndpoint(`nds/clusters/${o}/${s}/geoSharding`);await this.atlasService.authenticatedFetch(l,{method:"PATCH",body:JSON.stringify(i),headers:{"Content-Type":"application/json"}})}}var qe=n(44142),Ze=n(28508),Je=n(70002);const Qe={name:"GlobalWrites",provider:(0,i.nk)({name:"CompassGlobalWrites",component:function({children:e}){return r().createElement(r().Fragment,null,e)},activate:function(e,{connectionInfoRef:t,logger:n,track:a,atlasService:r},{cleanup:i}){const o=new Ue(r,t),s=(0,_e.y$)(K,{namespace:e.namespace,status:I,shardZones:[]},(0,_e.Tw)($e.A.withExtraArgument({logger:n,track:a,connectionInfoRef:t,atlasGlobalWritesService:o,pollingTimeoutRef:{current:null}})));return s.dispatch((async(e,t,{atlasGlobalWritesService:n,logger:a,connectionInfoRef:r})=>{const{namespace:i}=t();try{const t=await n.getManagedNamespace(i);e({type:c,managedNamespace:t}),e(z())}catch(t){a.log.error(a.mongoLogId(1001000330),"AtlasFetchError","Error fetching cluster sharding data",t.message),e(B({error:t,id:`global-writes-fetch-shard-info-error-${r.current.id}-${i}`,description:"Failed to fetch sharding information"}))}})),{store:s,deactivate:()=>i()}}},{logger:(0,qe.fF)("COMPASS-GLOBAL-WRITES-UI"),track:Ze.yL,connectionInfoRef:se.wj,atlasService:Je.fA}),content:Pe,header:ze}},37983:(e,t,n)=>{function a(e,t){return e.type===t}function r(e,t,n){const a=e[0];return a?"Document"===a.bsonType?i(a.fields,t,`${n}.`):"Array"===a.bsonType?r(a.types,t,n):(t[n]=`${a.bsonType}[]`,t):t}function i(e,t,n=""){for(const[a,o]of Object.entries(e)){const e=`${n}${a}`,s=o.types[0];s&&("Document"===s.bsonType?0===Object.keys(s.fields).length?t[e]="Document":i(s.fields,t,`${e}.`):"Array"===s.bsonType?r(s.types,t,e):s.bsonType&&(t[e]=s.bsonType))}return t}function o(e){return i(e,{})}n.d(t,{_:()=>o,v:()=>a})},38659:(e,t,n)=>{n.d(t,{Bf:()=>c,KA:()=>s});var a=n(82162),r=n(67219),i=n(68526);let o;function s(){if(!o)throw new Error("CompassGenerativeAIPlugin not activated");return o}const l=(0,a.HY)({optIn:i.Ay});function c(e,t,{cleanup:n}){return o=function({atlasAuthService:e,atlasAiService:t,preferences:n}){return(0,a.y$)(l,(0,a.Tw)(r.A.withExtraArgument({atlasAuthService:e,atlasAiService:t,preferences:n})))}(t),{store:o,deactivate:n}}},40220:(e,t,n)=>{var a=n(84917),r=n(84917).Collection;e.exports=a,e.exports.Collection=r},42279:(e,t,n)=>{n.d(t,{dq:()=>oe.dq,NL:()=>N,SK:()=>Q.S,Q9:()=>le,HM:()=>oe.HM,fP:()=>ue,Dr:()=>ce,gs:()=>oe.gs,mj:()=>me,dL:()=>ge});var a=n(96652),r=n.n(a),i=(n(95039),n(64990),n(90801),n(95774),n(77767),n(20625)),o=n(7588),s=n(13353),l=n(33868);const c=l.KC([l.Ik({json:l.Yj()}),l.Yj(),l.ai(),l.zM()]),d=l.Ik({fieldPath:l.Yj().describe('Dot-notation path to the field (e.g., "facility.name", "modifications[]")'),fakerMethod:l.Yj().describe('Faker.js method (e.g., "person.firstName", "helpers.arrayElement")'),fakerArgs:l.YO(c).describe('Array of arguments for the faker method. Use empty [] when defaults are sufficient. Use {"json": "..."} format for object/array arguments.')}),u=l.Ik({fields:l.YO(d).describe("Array of field-to-faker mappings")});var p=n(9174),m=n(65315),g=n.n(m),h=n(38659),f=n(68526),y=n(89213),b=n(16924),v=n(33997),x=n(28226),E=n(37983);class C extends o.xb{constructor(e){super("ServerError",500,e,"INVALID_RESPONSE"),this.name="AiChatbotInvalidResponseError"}}class w extends o.xb{constructor(e){super("NetworkError",400,e,"PROMPT_TOO_LARGE"),this.name="AiChatbotPromptTooLargeError"}}const I=25e4;function S(){return(new Date).toLocaleString("en-US",{weekday:"short",year:"numeric",month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:"short",hour12:!1})}function A(e){return["","```",e,"```"].join("\n")}function k({type:e,userInput:t,databaseName:n,collectionName:a,schema:r,sampleDocuments:i}){const o=[],s=["find"===e?"Write a query":"Generate an aggregation","that does the following:",`<user_prompt>${l=t,l.replace("<user_prompt>","&lt;user_prompt&gt;").replace("</user_prompt>","&lt;/user_prompt&gt;")}</user_prompt>`].join(" ");var l;if(n&&o.push(`Database name: "${n}"`),a&&o.push(`Collection name: "${a}"`),r){const e=(0,p.AO)((0,E._)(r));o.push(`Schema from a sample of documents from the collection:${A(`<user_schema>${e}</user_schema>`)}`)}if(i){const e=(0,p.AO)(i),t=(0,p.AO)(i.slice(0,1)),n=o.join("\n").length+s.length;e&&e.length+n<=I?o.push(`Sample documents from the collection:${A(`<sample_documents>${e}</sample_documents>`)}`):t&&t.length+n<=I&&o.push(`Sample document from the collection:${A(`<sample_documents>${t}</sample_documents>`)}`)}o.push(s);const c=o.join("\n");if(c.length>I)throw new w("Sorry, your request is too large. Please use a smaller prompt or try using this feature on a collection with smaller documents.");return c}function D({type:e,analyticsId:t,requestId:n,enableStorage:a}){return{instructions:"find"===e?["Reduce prose to the minimum, your output will be parsed by a machine. You generate MongoDB find query arguments. Provide filter, project, sort, skip, limit and aggregation in shell syntax, wrap each argument with XML delimiters as follows:","<filter>{}</filter>","<project>{}</project>","<sort>{}</sort>","<skip>0</skip>","<limit>0</limit>","<aggregation>[]</aggregation>","Additional instructions:","- Only use the aggregation field when the request cannot be represented with the other fields.","- Do not use the aggregation field if a find query fulfills the objective.","- If specifying latitude and longitude coordinates, list the longitude first, and then latitude.",`- The current date is ${S()}`].join("\n"):["Reduce prose to the minimum, your output will be parsed by a machine. You generate MongoDB aggregation pipelines. Provide only the aggregation pipeline contents in an array in shell syntax, wrapped with XML delimiters as follows:","<aggregation>[]</aggregation>","Additional instructions:","- If specifying latitude and longitude coordinates, list the longitude first, and then latitude.","- Only pass the contents of the aggregation, no surrounding syntax.","- Do not use database-level aggregation stages such as $documents, $changeStream, $changeStreamSplitLargeEvent, $currentOp, $listLocalSessions, or $queryStats. This aggregation runs against a collection, not a database.",`- The current date is ${S()}`].join("\n"),analyticsId:t,requestId:n,sensitiveStorage:a?"true":"false"}}const N="mongodb-chat-2.1-mini-reasoning",M="mongodb-slim-2.1-mini";var T=n(15088).process,P=n(21655).URLSearchParams;const L=(0,v.z6)({description:"Generate faker.js mappings for MongoDB schema fields to create realistic mock data",inputSchema:u,strict:!0}),O=512e4;function R(e,t){return Object.keys(e).some((e=>!t.includes(e)))}function H(e){const{content:t}=e??{};if("object"!=typeof t||null===t)throw new Error("Unexpected response: expected content to be an object");if(R(t,["query","aggregation"]))throw new Error("Unexpected keys in response: expected query and aggregation");const{query:n,aggregation:a}=t;if(!n&&!a)throw new Error("Unexpected response: expected query or aggregation, got none");if(n&&"object"!=typeof n)throw new Error("Unexpected response: expected query to be an object");if(R(n,["filter","project","collation","sort","skip","limit"]))throw new Error("Unexpected keys in response: expected filter, project, collation, sort, skip, limit, aggregation");for(const e of["filter","project","collation","sort","skip","limit"])if(n[e]&&"string"!=typeof n[e])throw new Error(`Unexpected response: expected field ${e} to be a string, got ${JSON.stringify(n[e],null,2)}`);if(a&&"string"!=typeof a.pipeline)throw new Error(`Unexpected response: expected aggregation pipeline to be a string, got ${JSON.stringify(a,null,2)}`)}function F(e){const{content:t}=e;if("object"!=typeof t||null===t)throw new Error("Unexpected response: expected content to be an object");if(R(t,["aggregation"]))throw new Error("Unexpected keys in response: expected aggregation");if(t.aggregation&&"string"!=typeof t.aggregation.pipeline)throw new Error(`Unexpected response: expected aggregation to be a string, got ${String(t.aggregation.pipeline)}`)}const W={"admin-api":{aggregation:"unauth/ai/api/v1/mql-aggregation",query:"unauth/ai/api/v1/mql-query"},cloud:{aggregation:e=>`ai/v1/groups/${e}/mql-aggregation`,query:e=>`ai/v1/groups/${e}/mql-query`}};async function j(e,t){const{currentUserId:n,telemetryAnonymousId:a,telemetryAtlasUserId:r}=e.getPreferences(),i=n??a??r;if(!i)return"unknown";try{const e=(new TextEncoder).encode(i),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join("")}catch(e){return t.log.warn(t.mongoLogId(1001000385),"AtlasAiService","Failed to hash user id for AI request",{error:e.message}),"unknown"}}class B{initPromise=null;apiURLPreset;atlasService;preferences;logger;nlqAiModel;mockDataAiModel;constructor({apiURLPreset:e,atlasService:t,preferences:n,logger:a}){this.apiURLPreset=e,this.atlasService=t,this.preferences=n,this.logger=a,this.initPromise=this.setupAIAccess();const r="http://PLACEHOLDER_BASE_URL_TO_BE_REPLACED.invalid";this.nlqAiModel=(0,b.ry)({apiKey:"",baseURL:r,fetch:(e,t)=>{const n=String(e).replace(r,this.atlasService.assistantApiEndpoint());return this.atlasService.authenticatedFetch(n,t)}}).responses(M),this.mockDataAiModel=(0,b.ry)({apiKey:"",baseURL:r,fetch:(e,t)=>{const n=String(e).replace(r,this.atlasService.assistantApiEndpoint());return this.atlasService.authenticatedFetch(n,t)}}).responses(M)}getUrlForEndpoint(e,{atlasMetadata:t}){if(t)return this.atlasService.cloudEndpoint(W.cloud[e](t.projectId));const n=W["admin-api"][e];return this.atlasService.adminApiEndpoint(n)}throwIfAINotEnabled(){if("true"!==T.env.COMPASS_E2E_SKIP_AI_OPT_IN&&!(0,i.aC)(this.preferences.getPreferences()))throw new Error("Compass' AI functionality is not currently enabled. Please try again later.")}async setupAIAccess(){await this.preferences.savePreferences({cloudFeatureRolloutAccess:{GEN_AI_COMPASS:!0}})}async ensureAiFeatureAccess({signal:e}={}){return(0,h.KA)().dispatch((0,f.XG)({signal:e,isCloudOptIn:"cloud"===this.apiURLPreset}))}getQueryOrAggregationFromUserInput=async({urlId:e,input:t,connectionInfo:n},a)=>{await this.initPromise,this.throwIfAINotEnabled();const{signal:r,requestId:i,...l}=t,c=function(e){const t=e.sampleDocuments?s.EJSON.serialize(e.sampleDocuments,{relaxed:!1}):void 0;let n=JSON.stringify({...e,sampleDocuments:t});if(n.length>O&&t&&(n=JSON.stringify({...e,sampleDocuments:s.EJSON.serialize(e.sampleDocuments?.slice(0,1)||[],{relaxed:!1})})),n.length>O)throw new Error("Sorry, your request is too large. Please use a smaller prompt or try using this feature on a collection with smaller documents.");return n}(l),d=`${this.getUrlForEndpoint(e,n)}?request_id=${encodeURIComponent(i)}`;this.logger.log.info(this.logger.mongoLogId(1001000308),"AtlasAIService","Running AI query generation request",{url:d,userInput:t.userInput,collectionName:t.collectionName,databaseName:t.databaseName,messageBodyLength:c.length,requestId:i});const u=await this.atlasService.authenticatedFetch(d,{signal:r,method:"POST",body:c,headers:{"Content-Type":"application/json",Accept:"application/json"}}),p=await u.text();let m;try{m=JSON.parse(p)}catch{throw this.logger.log.info(this.logger.mongoLogId(1001000310),"AtlasAIService","Failed to parse the response from AI API",{text:p,requestId:i}),new o.xb("ServerError",500,"Internal server error","INTERNAL_SERVER_ERROR")}return a(m),m};async getAggregationFromUserInput(e,t){if(this.preferences.getPreferences().enableChatbotEndpointForGenAI){const t=function({analyticsId:e,enableStorage:t,requestId:n,...a}){const r="aggregate";return{prompt:k({type:r,...a}),metadata:D({type:r,analyticsId:e,requestId:n,enableStorage:t})}}({...e,analyticsId:await j(this.preferences,this.logger)});return this.generateQueryUsingChatbot(t,F,{signal:e.signal,type:"aggregate"})}return this.getQueryOrAggregationFromUserInput({connectionInfo:t,urlId:"aggregation",input:e},F)}async getQueryFromUserInput(e,t){if(this.preferences.getPreferences().enableChatbotEndpointForGenAI){const t=function({analyticsId:e,enableStorage:t,requestId:n,...a}){const r="find";return{prompt:k({type:r,...a}),metadata:D({type:r,analyticsId:e,requestId:n,enableStorage:t})}}({...e,analyticsId:await j(this.preferences,this.logger)});return this.generateQueryUsingChatbot(t,H,{signal:e.signal,type:"find"})}return this.getQueryOrAggregationFromUserInput({urlId:"query",input:e,connectionInfo:t},H)}async getMockDataSchema(e,t){if(await this.initPromise,this.throwIfAINotEnabled(),!t.atlasMetadata)throw new y.c("Can't perform generative ai request: mock-data-schema requires Atlas connection");const{collectionName:n,databaseName:a,signal:r}=e;let i=e.schema;if(!e.includeSampleValues){const e=Object.create(null);for(const[t,n]of Object.entries(i))e[t]={type:n.type};i=e}this.logger.log.info(this.logger.mongoLogId(1001000419),"AtlasAiService","Running mock data schema generation via Knowledge Server",{namespace:`${a}.${n}`,requestId:e.requestId,fieldCount:Object.keys(i).length});try{!function(e){const t=Object.keys(e).length;if(t>450)throw new Error(`Schema too large: ${t} fields exceeds maximum of 450 fields`)}(i)}catch{throw new y.c("The provided schema is too large to process. Please reduce the schema size and try again.")}if(o=i,!(Object.keys(o).length>30))return this.generateSchemaForSingleChunk(a,n,i,e.validationRules,e.requestId,r);var o;const s=function(e,t=30){return g()(Object.entries(e),t).map((e=>Object.fromEntries(e)))}(i),l=await Promise.all(s.map((t=>this.generateSchemaForSingleChunk(a,n,t,e.validationRules,e.requestId,r))));return function(e){return 0===e.length?{fields:[]}:{fields:e.flatMap((e=>e.fields))}}(l)}async generateSchemaForSingleChunk(e,t,n,a,r,i){const o=function(e,t,n,a){const r=(0,p.AO)(n)??"{}";let i="";return null!=a&&(i="\n\nPlease also include the following MongoDB schema validation rules that are applied to each document:\n\n```\n"+((0,p.AO)(a)??"{}")+"\n```"),`Generate a JSON Schema for a faker-js factory function for the following collection's schema.\n\nThe database name is \`${e}\`\nThe collection name is \`${t}\`\n\nDocuments in the collection are described by the following schema:\n\n\`\`\`\n${r}\n\`\`\`\n\n${i}\n`}(e,t,n,a),s=(0,x.gM)({model:this.mockDataAiModel,messages:[{role:"user",content:o}],tools:{mockDataSchema:L},toolChoice:{type:"tool",toolName:"mockDataSchema"},providerOptions:{openai:{instructions:'\n# Identity\nYou are an expert programmer specializing in MongoDB schema analysis and faker.js library integration. You analyze MongoDB collection schemas (including complex nested structures) and generate accurate faker.js factory function mappings that produce realistic synthetic data.\n\n# Core Task\nTransform the provided MongoDB collection schema into a JSON response containing faker.js field mappings. Each mapping must accurately preserve the field path, select an appropriate faker.js method, and provide valid arguments.\n\n# Critical Requirements\n\n## 1. Field Path Preservation (Highest Priority)\n**MANDATORY**: The `fieldPath` must exactly match the schema field key.\n* Preserve exact field names from input schema (e.g., `car_id` → `fieldPath: "car_id"`)\n* Use dot notation for nested fields (e.g., `facility.name`, `address.street`)\n* Use array notation `[]` for arrays (e.g., `tags[]`, `modifications[]`)\n* **DO NOT** modify, shorten, or transform field names\n\n## 2. Faker Method Selection\n* Use valid faker.js methods from version ^10.4.0\n* Format: `<module>.<method>` (e.g., `person.firstName`, `date.past`, `number.int`)\n* **DO NOT** invent methods that don\'t exist in faker.js\n* **DO NOT** use "unrecognized" unless no reasonable faker.js method exists - prefer a reasonable guess\n\n### Available Faker.js Methods by MongoDB Type\n\n**String fields**: person.firstName, person.lastName, person.fullName, person.jobTitle, internet.email, internet.username, internet.url, image.url, internet.domainName, internet.password, internet.displayName, internet.emoji, location.city, location.country, location.streetAddress, location.state, location.zipCode, company.name, company.catchPhrase, color.human, commerce.productName, commerce.department, finance.accountName, finance.currencyCode, phone.number, git.commitSha, string.uuid, string.alpha, string.alphanumeric, lorem.word, lorem.words, lorem.sentence, lorem.paragraph, system.fileName, system.filePath, system.mimeType, book.title, music.songName, food.dish, animal.type, vehicle.model, vehicle.manufacturer, hacker.phrase, science.chemicalElement\n\n**Number/Int32 fields**: number.int, number.float, number.binary, number.octal, number.hex, date.weekday, internet.port, location.latitude, location.longitude\n\n**Long fields**: number.int, number.bigInt\n\n**Decimal128 fields**: number.float\n\n**Date/Timestamp fields**: date.recent, date.past, date.future, date.soon, date.anytime, date.birthdate, date.between\n\n**Boolean fields**: datatype.boolean\n\n**ObjectId fields**: database.mongodbObjectId\n\n**Binary fields**: string.hexadecimal, string.binary\n\n**Array fields**: helpers.arrayElement. **DO NOT** use `helpers.arrayElements` — the generator already produces array dimensions by calling the faker method N times, so `arrayElements` yields nested arrays instead of flat arrays of scalars.\n\n### Example Method Selection Guidelines\n* For string fields containing email patterns → use `internet.email`\n* For string fields containing URLs → use `internet.url`\n* For string fields containing names → use `person.firstName`, `person.lastName`, or `person.fullName`\n* For string fields containing locations → use `location.city`, `location.country`, or `location.streetAddress`\n* For numeric fields with ranges → use `number.int` or `number.float` with min/max arguments\n* For date fields → use `date.past`, `date.future`, or `date.recent` depending on context\n\n### Field-Type vs. Field-Name Conflicts (IMPORTANT)\nThe declared `type` of the field is authoritative — the method you pick MUST produce a value of that type:\n* If `type` is `Number` / `Int32` / `Long` / `Decimal128`, the method must return a number, even when the field name suggests a date or timestamp (e.g. `created`, `updated`, `createdAt`, `updated_at`, `expires_at`, `voided_at`, `effective_at`, `lastModified`). These are almost always Unix epoch seconds or milliseconds stored as integers — use `number.int` with a plausible epoch range (e.g. `{"min": 1600000000, "max": 1800000000}` for seconds-since-epoch). **DO NOT** use `date.past`/`date.future`/`date.recent`/`date.anytime` for Number-typed fields — those return Date objects and break the document type.\n* If `type` is `Date` or `Timestamp`, use a `date.*` method.\n* If `type` is `String` but the name suggests a number (e.g. an ID like `order_id: "ORD-12345"`), still produce a string via `string.*` methods; do not use `number.*`.\n\n### GeoJSON Coordinate Arrays (IMPORTANT)\nFor 2-element coordinate arrays in GeoJSON Point format — typically a numeric array field named `coordinates[]` whose sibling/parent has `type: "Point"` (e.g. `address.location.coordinates[]`, `geometry.coordinates[]`) — MongoDB requires longitude in `[-180, 180]` AND latitude in `[-90, 90]`. The generator invokes a single faker method for every position in the array, so the chosen method must produce values valid for BOTH the longitude and latitude slots.\n* **Use `location.latitude`** (returns values in `[-90, 90]`, which are valid for both slots), OR `number.float` with `{"min": -90, "max": 90, "fractionDigits": 6}`.\n* **DO NOT** use `location.longitude` or `number.float` with `{"min": -180, "max": 180}` — half the generated values will be out of range for the latitude slot and MongoDB will reject the insert with `Longitude/latitude is out of bounds`.\n\n## 3. Using Sample Values\nWhen `sampleValues` are provided in the schema:\n* **If sample values indicate an enum-like pattern** (limited distinct values), use `helpers.arrayElement` with the sample values\n* **If sample values show a pattern** (e.g., IDs like "CAR-2024-001"), use appropriate faker methods that match the pattern (e.g., `string.alphanumeric` for IDs)\n* **If sample values are numeric ranges**, infer min/max from samples and use `number.int` with range arguments\n* **For monetary fields (prices, costs, amounts, fees, etc.)**, use `number.float` with `fractionDigits: 2` and appropriate `min`/`max` arguments. **DO NOT** use `commerce.price` or `finance.amount` for Number-typed fields — they return strings, not numbers.\n* **Match sample-value format precisely**:\n * Country fields: ISO-3166 alpha-2 codes like `"US"`, `"CA"`, `"GB"` → use `location.countryCode`. Full names like `"United States"`, `"France"` → use `location.country`.\n * State fields: 2-letter codes like `"OR"`, `"CA"` → use `location.state` with `{"abbreviated": true}`. Full names like `"Oregon"` → use `location.state` without abbreviated.\n * Currency fields: 3-letter ISO codes like `"USD"`, `"EUR"` → use `finance.currencyCode`.\n * Language fields: ISO codes like `"en"`, `"fr"` → use `location.language` or similar; full names like `"English"` → use `helpers.arrayElement` with plausible full-name values.\n * Strings consisting entirely of digits like `"7849302847561234"` → use `string.numeric` (NOT `string.alphanumeric` — those are strictly digits). If mixed letters and digits, use `string.alphanumeric`.\n* **DO NOT** ignore sample values - they provide crucial context for method selection\n\n## 4. Validation Rules\nWhen MongoDB schema validation rules are provided:\n* **Respect constraints**: Use method arguments that honor min/max values, string length limits, etc.\n* **Apply patterns**: If validation includes regex patterns, select faker methods that generate matching data\n* **Enforce types**: Ensure selected methods generate the correct MongoDB type\n* **Incorporate constraints**: Use `fakerArgs` to apply validation constraints (e.g., `number.int` with min/max matching validation rules)\n\n## 5. Faker Arguments Formatting\n**When to Include Arguments:**\n* **Only include `fakerArgs` if they add value** - prefer empty array `[]` when method defaults are sufficient\n* **If `sampleValues` are provided** and indicate constraints (e.g., enum values, numeric ranges, patterns), use them in arguments\n* **If no `sampleValues` are provided**, most faker methods work well without arguments - prefer `[]`\n* Only include arguments if they make generated data more realistic, match validation rules, or constrain to specific sample values\n\n**Format rules:**\n* **`fakerArgs` must always be an array (list)** - never use a single value, always wrap in `[]`\n* Use empty arrays `[]` for methods requiring no arguments OR when arguments are not helpful\n* Array element position corresponds to method parameter position\n* For primitive arguments (string, number, boolean): use the value directly (rare - most methods take options objects)\n * Example: `[10]` for a numeric argument (though uncommon)\n* For object or array arguments: **MUST** use `{"json": "<JSON_STRING>"}` format\n * Object example: `{"json": "{\\"min\\": 1, \\"max\\": 10}"}`\n * Array example: `{"json": "[\\"value1\\", \\"value2\\"]"}`\n * Example with sample values: `[{json: "{\\"min\\": 18, \\"max\\": 99}"}]` for `number.int` when samples show age range\n* **CRITICAL - DO NOT**: Serialize primitives as JSON strings (e.g., `{"json": "3"}` is WRONG)\n* **CRITICAL - DO NOT**: Use unescaped quotes in JSON strings - always escape inner quotes with `\\"`\n* **CRITICAL - DO NOT**: Include unnecessary arguments - if no sample values or constraints, use `[]`\n* **CRITICAL - DO NOT**: Pass a format template string to `phone.number` (e.g. `"+1-###-###-####"`). Faker v10 removed the positional format-string signature — always use `fakerArgs: []` for `phone.number`.\n* **CRITICAL - DO NOT**: Use `string.word` — that method does not exist in faker.js. For a single short word use `lorem.word` (returns a string). The `string.*` family is for structural/character-set strings (`string.alpha`, `string.alphanumeric`, `string.numeric`, `string.uuid`, `string.nanoid`, `string.hexadecimal`).\n\n### JSON Escaping Examples\n* Simple object: `{"json": "{\\"min\\": 1, \\"max\\": 10}"}`\n* Object with nested strings: `{"json": "{\\"name\\": \\"test\\", \\"value\\": \\"example\\"}"}`\n* Array of strings: `{"json": "[\\"option1\\", \\"option2\\", \\"option3\\"]"}`\n* Array of numbers: `{"json": "[1, 2, 3, 4, 5]"}`\n* Complex nested: `{"json": "{\\"items\\": [\\"a\\", \\"b\\"], \\"count\\": 2}"}`\n\n**Escaping rule**: Inside the JSON string, all double quotes must be escaped as `\\"` and backslashes as `\\\\`\n\n### JSON Formatting Requirements (CRITICAL)\nWhen using `{"json": "<JSON_STRING>"}` format, the JSON string must be valid, well-formed JSON:\n* Objects: Use curly braces `{}` with quoted keys - `{"json": "{\\"min\\": 1, \\"max\\": 10}"}`\n* Arrays: Use square brackets `[]` - `{"json": "[\\"value1\\", \\"value2\\"]"}`\n* Bracket matching: All opening brackets `{` `[` must have matching closing brackets `}` `]`\n* Valid syntax: Keys must be in double quotes; values must be properly typed (strings, numbers, booleans, null, objects, arrays)\n* Nested structures: Inner structures must be closed before outer ones - `{"json": "{\\"items\\": [\\"a\\", \\"b\\"], \\"count\\": 2}"}`\n* Commas: No trailing commas - `{"json": "{\\"min\\": 1, \\"max\\": 10}"}` not `{"json": "{\\"min\\": 1, \\"max\\": 10,}"}`\n* Validation: JSON string must be parseable by `JSON.parse()` - validate bracket balance before outputting\n* **CRITICAL - DO NOT**: Output incomplete or partial JSON strings - banned patterns include:\n * `{"json": "{"}` - incomplete object\n * `{"json": "["}` - incomplete array\n* Use `[]` when no arguments are needed.\n\n## 6. When to Use "unrecognized"\n* **ONLY** use "unrecognized" when no reasonable faker.js method exists for the field type\n* **DO NOT** use "unrecognized" if you can make a reasonable guess - prefer using a related method\n* **DO NOT** use "unrecognized" for common types (string, number, date, boolean) - methods exist for these\n\nReturn your response as a JSON object where fields are collectively mapped into a schema that\nencodes a fakerjs factory function.\n\n# Example\n\n<user_query>\nGenerate a JSON Schema for a faker-js factory function for the following collection\'s schema.\n\nThe database name is `automotive`\nThe collection name is `cars_manufactured`\n\nDocuments in the collection are described by the following schema:\n\n{\n "schema": {\n "car_id": {\n "type": "string",\n "probability": 1.0,\n "sampleValues": ["CAR-2024-001", "CAR-2024-002", "CAR-2023-156"]\n },\n "maker": {\n "type": "string",\n "probability": 1.0,\n "sampleValues": ["Toyota", "Honda", "Ford", "BMW"]\n },\n "year": {\n "type": "number",\n "probability": 1.0,\n "sampleValues": [2024, 2023, 2022, 2021]\n },\n "model": {\n "type": "string",\n "probability": 1.0,\n "sampleValues": ["Camry", "Civic", "F-150", "X3"]\n },\n "facility.name": {\n "type": "string",\n "probability": 1.0,\n "sampleValues": ["Detroit Assembly Plant", "Georgetown Manufacturing"]\n },\n "facility.location": {\n "type": "string",\n "probability": 1.0,\n "sampleValues": ["Detroit, MI", "Georgetown, KY"]\n },\n "facility.established": {\n "type": "number",\n "probability": 1.0,\n "sampleValues": [1985, 1988]\n },\n "modifications[]": {\n "type": "string",\n "probability": 0.8,\n "sampleValues": [\n "Leather Seats", "Sunroof", "Premium Sound System",\n "Sport Package", "Navigation System",\n "Cold Weather Package", "Heated Seats"\n ]\n }\n }\n}\n</user_query>\n\n<structured_output_response>\n{\n "fields": [\n {\n "fieldPath": "car_id",\n "fakerMethod": "string.alphanumeric",\n "fakerArgs": [{"json": "{\\"length\\": 12, \\"casing\\": \\"upper\\"}"}]\n },\n {\n "fieldPath": "maker",\n "fakerMethod": "helpers.arrayElement",\n "fakerArgs": [{"json": "[\\"Toyota\\", \\"Honda\\", \\"Ford\\", \\"BMW\\"]"}]\n },\n {\n "fieldPath": "year",\n "fakerMethod": "number.int",\n "fakerArgs": [{"json": "{\\"min\\": 2020, \\"max\\": 2024}"}]\n },\n {\n "fieldPath": "model",\n "fakerMethod": "vehicle.model",\n "fakerArgs": []\n },\n {\n "fieldPath": "facility.name",\n "fakerMethod": "company.name",\n "fakerArgs": []\n },\n {\n "fieldPath": "facility.location",\n "fakerMethod": "location.city",\n "fakerArgs": []\n },\n {\n "fieldPath": "facility.established",\n "fakerMethod": "number.int",\n "fakerArgs": [{"json": "{\\"min\\": 1950, \\"max\\": 2020}"}]\n },\n {\n "fieldPath": "modifications[]",\n "fakerMethod": "helpers.arrayElement",\n "fakerArgs": [\n {"json": "[\\"Leather Seats\\", \\"Sunroof\\", \\"Premium Sound System\\", \\"Sport Package\\", \\"Navigation System\\", \\"Cold Weather Package\\", \\"Heated Seats\\", \\"Tinted Windows\\", \\"Alloy Wheels\\", \\"Backup Camera\\"]"}\n ]\n }\n ]\n}\n</structured_output_response>\n\n<explanation>\n\nKey observations:\n- `fieldPath` preserves exact schema field keys (e.g., "car_id", "facility.name", "modifications[]")\n- `fakerArgs` is always an array `[]` - never a single value\n- **When to include args**: `maker` uses `helpers.arrayElement` with sampleValues since they indicate an enum-like pattern; `year` uses `number.int` with min/max derived from sampleValues range; `modifications[]` uses `helpers.arrayElement` with the flat list of sampleValues — the generator handles the array dimension by calling the method N times per document\n- **When to use empty args**: `model`, `facility.name`, `facility.location` use `[]` because no sample values provided and method defaults are sufficient\n- JSON-serialized arguments properly escape quotes: `{"json": "{\\"min\\": 2020, \\"max\\": 2024}"}`\n- Only include `fakerArgs` when they add value (constraints from sample values, validation rules) - otherwise prefer `[]`\n\nNotice the \'structured_output_response\' can be parsed to produce the following fakerjs factory function used to generate sample documents.\n\nfunction createMockDocument() {\n return {\n \'car_id\': faker.string.alphanumeric({ length: 12, casing: \'upper\' }),\n \'maker\': faker.helpers.arrayElement([\'Toyota\', \'Honda\', \'Ford\', \'BMW\']),\n \'year\': faker.number.int({ min: 2020, max: 2024 }),\n \'model\': faker.vehicle.model(),\n \'facility.name\': faker.company.name(),\n \'facility.location\': faker.location.city(),\n \'facility.established\': faker.number.int({ min: 1950, max: 2020 }),\n \'modifications\': Array.from({ length: 3 }, () =>\n faker.helpers.arrayElement([\n \'Leather Seats\', \'Sunroof\', \'Premium Sound System\', \'Sport Package\',\n \'Navigation System\', \'Cold Weather Package\', \'Heated Seats\',\n \'Tinted Windows\', \'Alloy Wheels\', \'Backup Camera\'\n ])\n )\n }\n}\n</explanation>\n',store:!1}},headers:{"X-Client-Request-Id":r,"X-Assistant-Entrypoint":"mock-data-generator"},abortSignal:i}),l=await s.toolCalls;if(!l||0===l.length)throw this.logger.log.error(this.logger.mongoLogId(1001000311),"AtlasAiService","Mock data schema generation did not return tool call",{namespace:`${e}.${t}`}),new y.R("AI did not return expected mock data schema tool call");const c=l[0];if("tool-call"!==c.type||"mockDataSchema"!==c.toolName)throw new y.R(`Unexpected tool called: ${"tool-call"===c.type?c.toolName:"unknown"}`);return c.input}async optIntoGenAIFeatures(){"cloud"===this.apiURLPreset&&await this.atlasService.authenticatedFetch(this.atlasService.cloudEndpoint("settings/optInDataExplorerGenAIFeatures"),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new P([["value","true"]])}),await this.preferences.savePreferences({optInGenAIFeatures:!0})}async generateQueryUsingChatbot(e,t,n){this.throwIfAINotEnabled();const a=await async function(e,t,n){const{instructions:a,requestId:r,analyticsId:i,sensitiveStorage:o}=t.metadata,s=(0,x.gM)({model:e,messages:[{role:"user",content:t.prompt}],providerOptions:{openai:{instructions:a,metadata:{analytics_id:i,sensitive_storage:o},store:!1}},headers:{"X-Client-Request-Id":r,"X-Assistant-Entrypoint":"natural-language-to-mql"},abortSignal:n}).toUIMessageStream(),l=[];for await(const e of s)if("text-delta"===e.type&&l.push(e.delta),"error"===e.type)throw new C(e.errorText);return l.join("")}(this.nlqAiModel,e,n.signal),r=function(e,{logger:t,type:n}){const a=["filter","project","sort","skip","limit","aggregation"],r=(new DOMParser).parseFromString(`<root>${e}</root>`,"text/xml"),i={filter:null,project:null,sort:null,skip:null,limit:null,aggregation:null};for(const e of a){const n=r.querySelector(e)?.textContent?.trim();if(n)try{const t=(0,p.Ay)(n);!t||"object"==typeof t&&0===Object.keys(t).length?i[e]=null:i[e]=(0,p.AO)(t,0)??null}catch(a){t.log.warn(t.mongoLogId(1001000384),"AtlasAiService",`Failed to parse value for tag <${e}>: ${n}`,{error:a}),i[e]=null}}const{aggregation:o,...s}=i,l={pipeline:o??""};return"aggregate"===n?{content:{aggregation:l}}:{content:{query:s,aggregation:l}}}(a,{logger:this.logger,type:n.type});return t(r),r}}n(21261),n(92879),n(31977),n(49743),n(9656),n(72673),n(35467),n(94476),n(64971),n(24330),n(83478),n(65166),n(1256),n(61038),n(73035),n(23855);var z=n(89670),_=n(65143);class $ extends _.Cc{_logger;type="console";constructor(e,t){super(e),this._logger=t}logCore(e,t){const n=this.mapToMongoDBLogLevel(e);this._logger.log[n](this._logger.mongoLogId(1001000400),"Compass Database Tools",`${t.id.__value} - ${t.context}: ${t.message}`,...t.attributes?[t.attributes]:[])}mapToMongoDBLogLevel(e){switch(e){case"debug":return"debug";case"info":default:return"info";case"warning":return"warn";case"error":return"error"}}}var Y=n(32178),K=n(23409),G=n(46729),V=n(44142);const U="Database Tools",q="MongoDB Compass";class Z extends _.cb{logger;getTelemetryAnonymousId;activeConnection=null;constructor({logger:e,getTelemetryAnonymousId:t}){super(),this.logger=e,this.getTelemetryAnonymousId=t}connect(){return Promise.reject(new Error("Database Tools in MongoDB Compass makes use of the connection that MongoDB Compass is connected to. To connect, choose a connection from Compass's connection sidebar - https://www.mongodb.com/docs/compass/connect/"))}async disconnect(){try{await(this.activeConnection?.provider?.close())}catch(e){this.logger.error({id:(0,V.oW)(1001000411),context:"compass-tools-connection-manager",message:`Error disconnecting from Compass connection - ${e instanceof Error?e.message:String(e)}`,attributes:{error:e.stack}})}return this.activeConnection=null,this.changeState("connection-close",{tag:"disconnected"})}async close(){await this.disconnect(),this._events.emit("close",this.currentConnectionState)}async connectToCompassConnection(e){if(this.activeConnection)throw new Error("Already connected to a Compass connection");if((0,K.qY)(e.connectionString))return this.logger.warning({id:(0,V.oW)(1001000413),context:"compass-tools-connection-manager",message:"Attempting a connection to an Atlas Stream."}),void this.changeState("connection-error",{tag:"errored",errorReason:"Database Tools does not support connecting to Atlas Streams"});const{connectionId:t,connectOptions:n,connectionString:a}=this.overridePresetAppName(e);try{const e=await Y.NodeDriverServiceProvider.connect(a,{timeoutMS:3e4,readPreference:"secondaryPreferred",readConcern:{level:"local"},...n});return this.activeConnection={id:t,provider:e},void this.changeState("connection-success",new _.d8(e))}catch(e){return this.logger.error({id:(0,V.oW)(1001000412),context:"compass-tools-connection-manager",message:`Error connecting to Compass connection - ${e instanceof Error?e.message:String(e)}`,attributes:{error:e.stack}}),void this.changeState("connection-error",{tag:"errored",errorReason:e instanceof Error?e.message:String(e)})}}overridePresetAppName(e){const t=new G.Ay(e.connectionString),n={...e.connectOptions},a=t.typedSearchParams(),r=a.get("appName");if(!r||r.startsWith(q)&&!r.includes(U)){const t=`${q} ${U}`,r=this.getTelemetryAnonymousId(),i=e.connectionId,o=(0,K.mu)(e.connectionString)?`${t}${r?`--${r}`:""}--${i}`:t;a.set("appName",o),n.appName=o}return{connectionId:e.connectionId,connectionString:t.toString(),connectOptions:n}}}function J(e){if("object"!=typeof(t=e)||null===t||!("_zod"in t)||"object"!=typeof t._zod||null===t._zod||!("def"in t._zod))throw new Error("removeZodTransforms: expected a Zod v4 schema but received "+typeof e);var t;const n=e._zod.def;if("pipe"===n.type){const e=n.in._zod.def;if("transform"===n.out._zod.def.type)return J(n.in);if("transform"===e.type)return J(n.out);const t=J(n.in),a=J(n.out);return t.pipe(a)}if("object"===n.type){const e=n.shape,t=Object.create(null);for(const n in e)t[n]=J(e[n]);let a=z.Ay$.object(t);if("catchall"in n){const e=n.catchall;a=void 0===e?a.strip():"never"===e._zod.def.type?a.strict():"unknown"===e._zod.def.type?a.loose():a.catchall(J(e))}return a}return"array"===n.type?z.Ay$.array(J(n.element)):"optional"===n.type?J(n.innerType).optional():"nullable"===n.type?J(n.innerType).nullable():"default"===n.type?J(n.innerType).default(n.defaultValue):"union"===n.type?z.Ay$.union(n.options.map(J)):"tuple"===n.type?z.Ay$.tuple(n.items.map(J)):"record"===n.type?z.Ay$.record(J(n.keyType),J(n.valueType)):"lazy"===n.type?z.Ay$.lazy((()=>J(n.getter()))):e}var Q=n(28592);class X{observe(){}}class ee{constructor(){}get(e){return new X}getMetrics(){return Promise.resolve("")}}class te extends _.n1{server;userConfig;constructor(e){super(e),this.userConfig=e.userConfig}async start(){this.server=await this.setupServer()}async closeTransport(){await(this.server?.close())}}class ne{logger;toolGroups=new Set;context=Object.create(null);runner;connectionManager;connectionIdByToolCallId=Object.create(null);constructor({logger:e,getTelemetryAnonymousId:t,enableTelemetry:n,maxTimeMS:a}){this.logger=e;const r=_.fq.parse({disabledTools:["connect"],loggers:["mcp"],readOnly:!0,telemetry:n?"enabled":"disabled",maxTimeMS:a});this.runner=new te({userConfig:r,createConnectionManager:()=>Promise.resolve(this.connectionManager),connectionErrorHandler:function(){return{errorHandled:!1}},additionalLoggers:[new $(_.PH.root,this.logger)],telemetryProperties:{hosting_mode:"compass"},metrics:new ee}),this.connectionManager=new Z({logger:this.runner.logger,getTelemetryAnonymousId:t}),this.connectionManager.events.on("close",(()=>{this.logger.log.info(this.logger.mongoLogId(1001000405),"Tools Controller","MCPConnectionManager closed. Performing cleanup",{connectionManagerClientName:this.connectionManager.clientName})}))}setActiveTools(e){this.toolGroups=e}getActiveTools(){const e=Object.create(null);if(this.toolGroups.has("querybar")&&(e["get-current-query"]={description:"Get the query from the focused tab.",inputSchema:z.Ay$.object({}),needsApproval:!0,strict:!1,execute:()=>(this.logger.log.info(this.logger.mongoLogId(1001000386),"ToolsController","Executing get-current-query tool"),Promise.resolve({query:this.context.query}))}),this.toolGroups.has("aggregation-builder")&&(e["get-current-pipeline"]={description:"Get the pipeline from the focused tab.",inputSchema:z.Ay$.object({}),needsApproval:!0,strict:!1,execute:()=>(this.logger.log.info(this.logger.mongoLogId(1001000416),"ToolsController","Executing get-current-pipeline tool"),Promise.resolve({pipeline:this.context.pipeline}))}),this.toolGroups.has("db-read")&&this.runner.server){const t=Q.m.map((e=>e.name));0===this.runner.server.tools.length&&this.runner.server.registerTools();const n=this.runner.server.tools??[];for(const a of n)t.includes(a.name)&&(e[a.name]=(0,v.z6)({description:ae(a),inputSchema:z.Ay$.object(Object.fromEntries(Object.entries(a.argsShape).map((([e,t])=>[e,J(t)])))),needsApproval:!0,strict:!0,execute:async(e,t)=>{const n=this.connectionIdByToolCallId[t.toolCallId];if(!n){const e=new Error("Can't find connection for tool call");throw this.logger.log.error(this.logger.mongoLogId(1001000415),"ToolsController",e.message,{toolCallId:t.toolCallId}),e}const r=this.context.connections.find((e=>e.connectionId===n));if(!r){const e=new Error("No active connection to execute tool");throw this.logger.log.error(this.logger.mongoLogId(1001000414),"ToolsController",e.message),e}try{await this.connectionManager.connectToCompassConnection(r)}catch(e){throw this.logger.log.error(this.logger.mongoLogId(1001000410),"ToolsController","Error when attempting to connect to Compass connection before executing tool",{error:e.message}),e}let i;try{i=await a.invoke(e,{signal:t.abortSignal??new AbortSignal})}finally{await this.connectionManager.disconnect()}return i}}))}return e}setContext(e){this.runner.userConfig.telemetry=e.enableTelemetry?"enabled":"disabled",this.runner.userConfig.maxTimeMS=e.maxTimeMS,this.context=e}setConnectionIdForToolCall({toolCallId:e,connectionId:t}){this.connectionIdByToolCallId[e]=t}get server(){return this.runner?.server}async startServer(){if(!this.runner.server)try{this.logger.log.info(this.logger.mongoLogId(1001000402),"ToolsController","Starting in-memory MCP server with config",{...this.runner.userConfig,apiClientId:"<redacted>",apiClientSecret:"<redacted>"}),await this.runner.start(),this.logger.log.info(this.logger.mongoLogId(1001000403),"ToolsController","In-memory MCP server started successfully")}catch(e){this.logger.log.error(this.logger.mongoLogId(1001000404),"ToolsController","Error when attempting to start MCP server",{error:e.message})}}async stopServer(){try{if(!this.runner.server)return void this.logger.log.info(this.logger.mongoLogId(1001000406),"ToolsController","MCP server stop requested. No MCP server running, nothing to stop.");await this.runner.server.close(),this.logger.log.info(this.logger.mongoLogId(1001000407),"ToolsController","MCP server stopped successfully")}catch(e){this.logger.log.error(this.logger.mongoLogId(1001000408),"ToolsController","Error when attempting to close the MCP server",{error:e.message})}}}function ae(e){switch(e.name){case"collection-schema":return e.description+" Always use this tool to access collection schema information whenever asked to generate queries or aggregations and before performing queries or aggregations.";case"find":return e.description+" Always use the collection-schema tool to access collection schema information before using this tool to perform queries.";case"aggregate":return e.description+" Always use the collection-schema tool to access collection schema information before using this tool to perform aggregations.";default:return e.description}}var re=n(70002),ie=n(62183),oe=n(736);const se=(0,a.createContext)(null),le=(0,ie.xw)((function({apiURLPreset:e,children:t}){const n=(0,V.Ul)("ATLAS-AI-SERVICE"),o=(0,i.fx)(),s=(0,re.fA)(),l=(0,a.useMemo)((()=>new B({apiURLPreset:e,atlasService:s,preferences:o,logger:n})),[e,o,n,s]);return r().createElement(se.Provider,{value:l},t)})),ce=(0,ie.mb)((function(){const e=(0,a.useContext)(se);if(!e)throw new Error("No AtlasAiService available in this context");return e}),"atlasAiServiceLocator"),de=(0,a.createContext)(null),ue=(0,ie.xw)((function({children:e}){const t=(0,V.Ul)("TOOLS-CONTROLLER"),n=(0,i.Fg)("telemetryAnonymousId"),o=(0,a.useMemo)((()=>new ne({logger:t,getTelemetryAnonymousId:()=>n??"",enableTelemetry:!1})),[t,n]);return(0,a.useEffect)((()=>()=>{o.stopServer()}),[o]),r().createElement(de.Provider,{value:o},e)}));function pe(){const e=(0,a.useContext)(de);if(!e)throw new Error("No ToolsController available in this context");return e}const me=(0,ie.mb)(pe,"toolsControllerLocator"),ge=pe},42463:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(71520),r=n.n(a)()(!1);r.push([e.id,"/**\n ****************************\n * Generic Styles\n ****************************\n*/\nag-grid,\nag-grid-angular,\nag-grid-ng2,\nag-grid-polymer,\nag-grid-aurelia {\n display: block;\n}\n\n.ag-hidden {\n display: none !important;\n}\n\n.ag-invisible {\n visibility: hidden !important;\n}\n\n.ag-faded {\n opacity: 0.3;\n}\n\n.ag-width-half {\n display: inline-block;\n width: 50% !important;\n}\n\n.ag-unselectable {\n -webkit-user-select: none !important;\n user-select: none !important;\n}\n\n.ag-selectable {\n -webkit-user-select: text !important;\n user-select: text !important;\n}\n\n.ag-select-agg-func-popup {\n position: absolute;\n}\n\n.ag-input-text-wrapper {\n display: flex;\n align-items: center;\n height: 100%;\n line-height: normal;\n position: relative;\n}\n\n.ag-shake-left-to-right {\n animation-direction: alternate;\n animation-duration: 0.2s;\n animation-iteration-count: infinite;\n animation-name: ag-shake-left-to-right;\n}\n\n@keyframes ag-shake-left-to-right {\n from {\n padding-left: 6px;\n padding-right: 2px;\n }\n to {\n padding-left: 2px;\n padding-right: 6px;\n }\n}\n\n/* icons are used outside of the grid root (in the ghost) */\n.ag-icon-aggregation {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTkuNSAyLjVoLTZsMiAzLjUtMiAzLjVoNiIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2U9IiMwMDAiIGZpbGw9Im5vbmUiLz48L3N2Zz4=)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-arrows {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAiIGhlaWdodD0iMjAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTE2IDZsLTEuNDEgMS40MUwxNi4xNyA5SDR2MmgxMi4xN2wtMS41OCAxLjU5TDE2IDE0bDQtNHoiLz48cGF0aCBkPSJNNCA2bDEuNDEgMS40MUwzLjgzIDlIMTZ2MkgzLjgzbDEuNTggMS41OUw0IDE0bC00LTR6Ii8+PHBhdGggZD0iTTYgMTZsMS40MS0xLjQxTDkgMTYuMTdWNGgydjEyLjE3bDEuNTktMS41OEwxNCAxNmwtNCA0eiIvPjxwYXRoIGQ9Ik0xNCA0bC0xLjQxIDEuNDFMMTEgMy44M1YxNkg5VjMuODNMNy40MSA1LjQxIDYgNGw0LTR6Ii8+PC9zdmc+)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-asc {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxkZWZzPjxwYXRoIGlkPSJhIiBkPSJNNSAzaDJ2OUg1eiIvPjxwYXRoIGQ9Ik04Ljk5MyA1LjJWMy40OTNoLTZ2Nkg0LjdWNS4yaDQuMjkzeiIgaWQ9ImIiLz48L2RlZnM+PGcgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj48dXNlIGZpbGw9IiNEOEQ4RDgiIHhsaW5rOmhyZWY9IiNhIi8+PHBhdGggc3Ryb2tlPSIjMDAwIiBkPSJNNS41IDMuNWgxdjhoLTF6Ii8+PGcgdHJhbnNmb3JtPSJyb3RhdGUoNDUgNS45OTMgNi40OTMpIj48dXNlIGZpbGw9IiNEOEQ4RDgiIHhsaW5rOmhyZWY9IiNiIi8+PHBhdGggc3Ryb2tlPSIjMDAwIiBkPSJNOC40OTMgNC43di0uNzA3aC01djVINC4yVjQuN2g0LjI5M3oiLz48L2c+PC9nPjwvc3ZnPg==)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-checkbox-checked-readonly {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxkZWZzPjxyZWN0IGlkPSJhIiB4PSIwIiB5PSIwIiB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHJ4PSIxIi8+PC9kZWZzPjxnIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+PHVzZSBmaWxsPSIjRDhEOEQ4IiB4bGluazpocmVmPSIjYSIvPjxyZWN0IHN0cm9rZT0iIzAwMCIgeD0iLjUiIHk9Ii41IiB3aWR0aD0iMTEiIGhlaWdodD0iMTEiIHJ4PSIxIi8+PHBhdGggc3Ryb2tlPSIjMDAwIiBkPSJNOSAzTDYgOC41bC0yLjUtMiIvPjwvZz48L3N2Zz4=)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-checkbox-checked {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxkZWZzPjxyZWN0IGlkPSJhIiB4PSIwIiB5PSIwIiB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHJ4PSIxIi8+PC9kZWZzPjxnIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+PHVzZSBmaWxsPSIjRkZGIiB4bGluazpocmVmPSIjYSIvPjxyZWN0IHN0cm9rZT0iIzAwMCIgeD0iLjUiIHk9Ii41IiB3aWR0aD0iMTEiIGhlaWdodD0iMTEiIHJ4PSIxIi8+PHBhdGggc3Ryb2tlPSIjMDAwIiBkPSJNOSAzTDYgOC41bC0yLjUtMiIvPjwvZz48L3N2Zz4=)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-checkbox-indeterminate-readonly {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxkZWZzPjxyZWN0IGlkPSJhIiB4PSIwIiB5PSIwIiB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHJ4PSIxIi8+PC9kZWZzPjxnIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+PHVzZSBmaWxsPSIjRDhEOEQ4IiB4bGluazpocmVmPSIjYSIvPjxyZWN0IHN0cm9rZT0iIzAwMCIgeD0iLjUiIHk9Ii41IiB3aWR0aD0iMTEiIGhlaWdodD0iMTEiIHJ4PSIxIi8+PHBhdGggZmlsbD0iIzAwMCIgZD0iTTQgNWg0djJINHoiLz48L2c+PC9zdmc+)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-checkbox-indeterminate {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxkZWZzPjxyZWN0IGlkPSJhIiB4PSIwIiB5PSIwIiB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHJ4PSIxIi8+PC9kZWZzPjxnIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+PHVzZSBmaWxsPSIjRkZGIiB4bGluazpocmVmPSIjYSIvPjxyZWN0IHN0cm9rZT0iIzAwMCIgeD0iLjUiIHk9Ii41IiB3aWR0aD0iMTEiIGhlaWdodD0iMTEiIHJ4PSIxIi8+PHBhdGggZmlsbD0iIzAwMCIgZD0iTTQgNWg0djJINHoiLz48L2c+PC9zdmc+)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-checkbox-unchecked-readonly {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxkZWZzPjxyZWN0IGlkPSJhIiB4PSIwIiB5PSIwIiB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHJ4PSIxIi8+PC9kZWZzPjxnIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+PHVzZSBmaWxsPSIjRDhEOEQ4IiB4bGluazpocmVmPSIjYSIvPjxyZWN0IHN0cm9rZT0iIzAwMCIgeD0iLjUiIHk9Ii41IiB3aWR0aD0iMTEiIGhlaWdodD0iMTEiIHJ4PSIxIi8+PC9nPjwvc3ZnPg==)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-checkbox-unchecked {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxkZWZzPjxyZWN0IGlkPSJhIiB4PSIwIiB5PSIwIiB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHJ4PSIxIi8+PC9kZWZzPjxnIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+PHVzZSBmaWxsPSIjRkZGIiB4bGluazpocmVmPSIjYSIvPjxyZWN0IHN0cm9rZT0iIzAwMCIgeD0iLjUiIHk9Ii41IiB3aWR0aD0iMTEiIGhlaWdodD0iMTEiIHJ4PSIxIi8+PC9nPjwvc3ZnPg==)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-column {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEgMWg0djJIMXptMCAzaDR2N0gxeiIgZmlsbC1ydWxlPSJldmVub2RkIi8+PC9zdmc+)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-columns {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEgMWg0djJIMXptNiAwaDR2Mkg3ek0xIDVoNHYySDF6bTYgMGg0djJIN3pNMSA5aDR2Mkgxem02IDBoNHYySDd6IiBmaWxsLXJ1bGU9ImV2ZW5vZGQiLz48L3N2Zz4=)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-contracted {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj48cmVjdCBzdHJva2Utb3BhY2l0eT0iLjUiIHN0cm9rZT0iIzAwMCIgeD0iMS41IiB5PSIxLjUiIHdpZHRoPSI5IiBoZWlnaHQ9IjkiIHJ4PSIxIi8+PHBhdGggZmlsbD0iIzAwMCIgZD0iTTkgNXYySDNWNXoiLz48L2c+PC9zdmc+)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-copy {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgc3Ryb2tlPSIjMDAwIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxwYXRoIGQ9Ik00LjUgNC41aDV2NWgtNXoiLz48cGF0aCBkPSJNNy41IDIuNWgtNXY1aDJ2Mmg1di01aC0ydi0yeiIvPjwvZz48L3N2Zz4=)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-cut {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgc3Ryb2tlPSIjMDAwIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxwYXRoIGQ9Ik0zIDMuMTJjLjY2Ny4wNzggMyAxLjc0NSA3IDUtLjMyNi4yMDQtLjY1OS4yMDQtMSAwLS4zNDEtLjIwNi0xLjY3NC0xLjIwNi00LTMgMCAuNjY2LS42NjcuNjY2LTIgMC0yLTEtMS0yLjEyIDAtMnoiLz48cGF0aCBkPSJNMyA4LjI2NGMuNjY3LS4wOCAzLTEuNzQ2IDctNS0uMzI2LS4yMDUtLjY1OS0uMjA1LTEgMC0uMzQxLjIwNC0xLjY3NCAxLjIwNC00IDMgMC0uNjY3LS42NjctLjY2Ny0yIDAtMiAxLTEgMi4xMTkgMCAyeiIvPjwvZz48L3N2Zz4=)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-desc {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxkZWZzPjxwYXRoIGlkPSJhIiBkPSJNNSAyaDJ2OUg1eiIvPjxwYXRoIGQ9Ik04Ljk5MyA2LjFWNC4zOTNoLTZ2Nkg0LjdWNi4xaDQuMjkzeiIgaWQ9ImIiLz48L2RlZnM+PGcgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj48dXNlIGZpbGw9IiNEOEQ4RDgiIHhsaW5rOmhyZWY9IiNhIi8+PHBhdGggc3Ryb2tlPSIjMDAwIiBkPSJNNS41IDIuNWgxdjhoLTF6Ii8+PGcgdHJhbnNmb3JtPSJyb3RhdGUoLTEzNSA1Ljk5MyA3LjM5MykiPjx1c2UgZmlsbD0iI0Q4RDhEOCIgeGxpbms6aHJlZj0iI2IiLz48cGF0aCBzdHJva2U9IiMwMDAiIGQ9Ik04LjQ5MyA1LjZ2LS43MDdoLTV2NUg0LjJWNS42aDQuMjkzeiIvPjwvZz48L2c+PC9zdmc+)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-expanded {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj48cmVjdCBzdHJva2Utb3BhY2l0eT0iLjUiIHN0cm9rZT0iIzAwMCIgeD0iMS41IiB5PSIxLjUiIHdpZHRoPSI5IiBoZWlnaHQ9IjkiIHJ4PSIxIi8+PHBhdGggZmlsbD0iIzAwMCIgZD0iTTUgM2gydjZINXoiLz48cGF0aCBmaWxsPSIjMDAwIiBkPSJNOSA1djJIM1Y1eiIvPjwvZz48L3N2Zz4=)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-eye-slash {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj48cGF0aCBkPSJNMy4wMDEgMy45MDhMMyA0YTMgMyAwIDEgMCA1Ljk5OS0uMDkyQTUuMjQ4IDUuMjQ4IDAgMCAwIDYgM2MtMS4xIDAtMi4xLjMwMy0yLjk5OS45MDh6IiBmaWxsPSIjMDAwIi8+PHBhdGggZD0iTTQgNC41Yy42NjctLjMzMyAxLjY2Ny0uNSAzLS41IiBzdHJva2U9IiM5Nzk3OTciLz48cGF0aCBkPSJNMSA2YzEuMzMzLTIgMy0zIDUtM3MzLjY2NyAxIDUgM0M5LjY2NyA4IDggOSA2IDlTMi4zMzMgOCAxIDZ6IiBzdHJva2U9IiMwMDAiLz48cGF0aCBkPSJNNC4wMDQgMi44MzVsNC45OTIgNi4zMyIgc3Ryb2tlPSIjMDAwIiBzdHJva2UtbGluZWNhcD0ic3F1YXJlIi8+PHBhdGggZD0iTTMuMDA0IDIuODM1bDQuOTkyIDYuMzMiIHN0cm9rZT0iI0ZGRiIgc3Ryb2tlLWxpbmVjYXA9InNxdWFyZSIvPjwvZz48L3N2Zz4=)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-eye {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj48cGF0aCBkPSJNMy4wMDEgMy45MDhMMyA0YTMgMyAwIDEgMCA1Ljk5OS0uMDkyQTUuMjQ4IDUuMjQ4IDAgMCAwIDYgM2MtMS4xIDAtMi4xLjMwMy0yLjk5OS45MDh6IiBmaWxsPSIjMDAwIi8+PHBhdGggZD0iTTQgNC41Yy42NjctLjMzMyAxLjY2Ny0uNSAzLS41IiBzdHJva2U9IiM5Nzk3OTciLz48cGF0aCBkPSJNMSA2YzEuMzMzLTIgMy0zIDUtM3MzLjY2NyAxIDUgM0M5LjY2NyA4IDggOSA2IDlTMi4zMzMgOCAxIDZ6IiBzdHJva2U9IiMwMDAiLz48L2c+PC9zdmc+)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-filter {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEgMmgxMEw3IDZ2NUw1IDlWNkwxIDJ6bTQgNHYxaDJWNkg1eiIgZmlsbC1ydWxlPSJldmVub2RkIi8+PC9zdmc+)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-group {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj48cGF0aCBzdHJva2U9IiMwMDAiIGQ9Ik03LjUgMS41aDN2MmgtM3ptMCA0aDN2MmgtM3ptMCA0aDN2MmgtM3oiLz48cGF0aCBmaWxsPSIjMDAwIiBkPSJNMiAzaDF2OEgyem0xIDNoNHYxSDN6bTItNGgzdjFINXoiLz48cGF0aCBmaWxsPSIjMDAwIiBkPSJNMiAxMGg1djFIMnoiLz48cGF0aCBzdHJva2U9IiMwMDAiIGQ9Ik0xLjUgMS41aDN2MmgtM3oiLz48L2c+PC9zdmc+)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-indeterminate {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj48cGF0aCBkPSJNMy4wNTYgNC41ODFhMy4wMDEgMy4wMDEgMCAwIDAgNS44ODggMEM4LjA1OSA0LjE5NCA3LjA3OCA0IDYgNGMtMS4wNzggMC0yLjA2LjE5NC0yLjk0NC41ODF6IiBmaWxsPSIjMDAwIi8+PHBhdGggZD0iTTQgNS41Yy42NjctLjMzMyAxLjY2Ny0uNSAzLS41IiBzdHJva2U9IiM5Nzk3OTciLz48cGF0aCBkPSJNMSA2YzEuMzMzLTEuMzMzIDMtMiA1LTJzMy42NjcuNjY3IDUgMkM5LjY2NyA3LjMzMyA4IDggNiA4cy0zLjY2Ny0uNjY3LTUtMnoiIHN0cm9rZT0iIzAwMCIvPjwvZz48L3N2Zz4=)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-left {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxkZWZzPjxwYXRoIGlkPSJhIiBkPSJNNS41IDEuNWgydjloLTJ6Ii8+PHBhdGggZD0iTTcuOTkzIDQuN1YyLjk5M2gtNnY2SDMuN1Y0LjdoNC4yOTN6IiBpZD0iYiIvPjwvZGVmcz48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIHRyYW5zZm9ybT0icm90YXRlKDkwIDYuNSA2KSI+PHVzZSBmaWxsPSIjRDhEOEQ4IiB4bGluazpocmVmPSIjYSIvPjxwYXRoIHN0cm9rZT0iIzAwMCIgZD0iTTYgMmgxdjhINnoiLz48L2c+PGcgdHJhbnNmb3JtPSJyb3RhdGUoLTQ1IDQuOTkzIDUuOTkzKSI+PHVzZSBmaWxsPSIjRDhEOEQ4IiB4bGluazpocmVmPSIjYiIvPjxwYXRoIHN0cm9rZT0iIzAwMCIgZD0iTTcuNDkzIDQuMnYtLjcwN2gtNXY1SDMuMlY0LjJoNC4yOTN6Ii8+PC9nPjwvZz48L3N2Zz4=)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-loading {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxkZWZzPjxwYXRoIGlkPSJhIiBkPSJNNSAxaDJ2M0g1eiIvPjxwYXRoIGlkPSJiIiBkPSJNNSA4aDJ2M0g1eiIvPjxwYXRoIGlkPSJjIiBkPSJNMSA1aDN2MkgxeiIvPjxwYXRoIGlkPSJkIiBkPSJNOCA1aDN2Mkg4eiIvPjxwYXRoIGlkPSJlIiBkPSJNNCAwaDJ2M0g0eiIvPjxwYXRoIGlkPSJmIiBkPSJNNCA3aDJ2M0g0eiIvPjxwYXRoIGlkPSJnIiBkPSJNMCA0aDN2MkgweiIvPjxwYXRoIGlkPSJoIiBkPSJNNyA0aDN2Mkg3eiIvPjwvZGVmcz48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjx1c2UgZmlsbD0iI0Q4RDhEOCIgeGxpbms6aHJlZj0iI2EiLz48cGF0aCBzdHJva2U9IiM5Nzk3OTciIGQ9Ik01LjUgMS41aDF2MmgtMXoiLz48dXNlIGZpbGw9IiNEOEQ4RDgiIHhsaW5rOmhyZWY9IiNiIi8+PHBhdGggc3Ryb2tlPSIjOTc5Nzk3IiBkPSJNNS41IDguNWgxdjJoLTF6Ii8+PHVzZSBmaWxsPSIjRDhEOEQ4IiB4bGluazpocmVmPSIjYyIvPjxwYXRoIHN0cm9rZT0iIzk3OTc5NyIgZD0iTTEuNSA1LjVoMnYxaC0yeiIvPjx1c2UgZmlsbD0iI0Q4RDhEOCIgeGxpbms6aHJlZj0iI2QiLz48cGF0aCBzdHJva2U9IiM5Nzk3OTciIGQ9Ik04LjUgNS41aDJ2MWgtMnoiLz48ZyBvcGFjaXR5PSIuNzE0Ij48ZyB0cmFuc2Zvcm09InJvdGF0ZSg0NSA0LjI5MyA2LjcwNykiPjx1c2UgZmlsbD0iI0Q4RDhEOCIgeGxpbms6aHJlZj0iI2UiLz48cGF0aCBzdHJva2U9IiM5Nzk3OTciIGQ9Ik00LjUuNWgxdjJoLTF6Ii8+PC9nPjxnIHRyYW5zZm9ybT0icm90YXRlKDQ1IDQuMjkzIDYuNzA3KSI+PHVzZSBmaWxsPSIjRDhEOEQ4IiB4bGluazpocmVmPSIjZiIvPjxwYXRoIHN0cm9rZT0iIzk3OTc5NyIgZD0iTTQuNSA3LjVoMXYyaC0xeiIvPjwvZz48ZyB0cmFuc2Zvcm09InJvdGF0ZSg0NSA0LjI5MyA2LjcwNykiPjx1c2UgZmlsbD0iI0Q4RDhEOCIgeGxpbms6aHJlZj0iI2ciLz48cGF0aCBzdHJva2U9IiM5Nzk3OTciIGQ9Ik0uNSA0LjVoMnYxaC0yeiIvPjwvZz48ZyB0cmFuc2Zvcm09InJvdGF0ZSg0NSA0LjI5MyA2LjcwNykiPjx1c2UgZmlsbD0iI0Q4RDhEOCIgeGxpbms6aHJlZj0iI2giLz48cGF0aCBzdHJva2U9IiM5Nzk3OTciIGQ9Ik03LjUgNC41aDJ2MWgtMnoiLz48L2c+PC9nPjwvZz48L3N2Zz4=)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-menu {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEgMWgxMHYySDF6bTAgNGgxMHYySDF6bTAgNGgxMHYySDF6IiBmaWxsLXJ1bGU9ImV2ZW5vZGQiLz48L3N2Zz4=)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-minus {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTIgNWg4djJIMnoiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvc3ZnPg==)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-none {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxkZWZzPjxwYXRoIGlkPSJhIiBkPSJNNSAzaDJ2Nkg1eiIvPjxwYXRoIGQ9Ik04LjE0NiA4LjE4MlY2LjQ3NWgtNXY1aDEuNzA4VjguMTgyaDMuMjkyeiIgaWQ9ImIiLz48cGF0aCBkPSJNOC41IDIuOTE0VjEuMjA3aC01djVoMS43MDdWMi45MTRIOC41eiIgaWQ9ImMiLz48L2RlZnM+PGcgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj48dXNlIGZpbGw9IiNEOEQ4RDgiIHhsaW5rOmhyZWY9IiNhIi8+PHBhdGggc3Ryb2tlPSIjMDAwIiBkPSJNNS41IDMuNWgxdjVoLTF6Ii8+PGcgdHJhbnNmb3JtPSJyb3RhdGUoLTEzNSA1LjY0NiA4LjQ3NSkiPjx1c2UgZmlsbD0iI0Q4RDhEOCIgeGxpbms6aHJlZj0iI2IiLz48cGF0aCBzdHJva2U9IiMwMDAiIGQ9Ik03LjY0NiA3LjY4MnYtLjcwN2gtNHY0aC43MDhWNy42ODJoMy4yOTJ6Ii8+PC9nPjxnIHRyYW5zZm9ybT0icm90YXRlKDQ1IDYgMy43MDcpIj48dXNlIGZpbGw9IiNEOEQ4RDgiIHhsaW5rOmhyZWY9IiNjIi8+PHBhdGggc3Ryb2tlPSIjMDAwIiBkPSJNOCAyLjQxNHYtLjcwN0g0djRoLjcwN1YyLjQxNEg4eiIvPjwvZz48L2c+PC9zdmc+)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-not-allowed {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgc3Ryb2tlPSIjMDAwIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxjaXJjbGUgY3g9IjYiIGN5PSI2IiByPSI0Ii8+PHBhdGggZD0iTTguNSAzLjVMMy40MDEgOC41OTkiIHN0cm9rZS1saW5lY2FwPSJzcXVhcmUiLz48L2c+PC9zdmc+)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-paste {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgc3Ryb2tlPSIjMDAwIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxwYXRoIGQ9Ik0yLjUgMi41aDd2N2gtN3oiLz48cGF0aCBkPSJNNi41IDEuNWgtMXYyaC0xdjFoM3YtMWgtMXYtMnoiLz48L2c+PC9zdmc+)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-pin {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj48cGF0aCBmaWxsPSIjMDAwIiBkPSJNMyAyaDZ2MUg4djRsMiAxSDdsLTEgMy0xLTNIMmwyLTFWM0gzeiIvPjxwYXRoIGZpbGwtb3BhY2l0eT0iLjUiIGZpbGw9IiNGRkYiIGQ9Ik01IDNoMXY0SDV6Ii8+PHBhdGggZmlsbC1vcGFjaXR5PSIuMjgiIGZpbGw9IiNGRkYiIGQ9Ik00IDNoMXYzSDR6Ii8+PC9nPjwvc3ZnPg==)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-pivot {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgc3Ryb2tlPSIjMDAwIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxyZWN0IHg9IjEuNSIgeT0iMS41IiB3aWR0aD0iOSIgaGVpZ2h0PSI5IiByeD0iMSIvPjxwYXRoIGQ9Ik0xMC41IDMuNWgtOW0yLTJ2OSIgc3Ryb2tlLWxpbmVjYXA9InNxdWFyZSIvPjxwYXRoIGQ9Ik03LjUgNi41bDEtMSAxIDFtLTMgMWwtMSAxIDEgMSIvPjxwYXRoIGQ9Ik04LjUgNS41djNoLTMiLz48L2c+PC9zdmc+)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-plus {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgZmlsbC1ydWxlPSJldmVub2RkIj48cGF0aCBkPSJNNSAyaDJ2OEg1eiIvPjxwYXRoIGQ9Ik0yIDVoOHYySDJ6Ii8+PC9nPjwvc3ZnPg==)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-right {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxkZWZzPjxwYXRoIGlkPSJhIiBkPSJNNC41IDEuNWgydjloLTJ6Ii8+PHBhdGggZD0iTTkuOTkzIDQuN1YyLjk5M2gtNnY2SDUuN1Y0LjdoNC4yOTN6IiBpZD0iYiIvPjwvZGVmcz48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIHRyYW5zZm9ybT0icm90YXRlKDkwIDUuNSA2KSI+PHVzZSBmaWxsPSIjRDhEOEQ4IiB4bGluazpocmVmPSIjYSIvPjxwYXRoIHN0cm9rZT0iIzAwMCIgZD0iTTUgMmgxdjhINXoiLz48L2c+PGcgdHJhbnNmb3JtPSJzY2FsZSgtMSAxKSByb3RhdGUoLTQ1IDAgMjIuODc0KSI+PHVzZSBmaWxsPSIjRDhEOEQ4IiB4bGluazpocmVmPSIjYiIvPjxwYXRoIHN0cm9rZT0iIzAwMCIgZD0iTTkuNDkzIDQuMnYtLjcwN2gtNXY1SDUuMlY0LjJoNC4yOTN6Ii8+PC9nPjwvZz48L3N2Zz4=)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-small-left {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTMgNmw0LTR2OHoiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvc3ZnPg==)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-small-right {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTUgMmw0IDQtNCA0eiIgZmlsbC1ydWxlPSJldmVub2RkIi8+PC9zdmc+)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-small-up {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTIgN2w0LTQgNCA0eiIgZmlsbC1ydWxlPSJldmVub2RkIi8+PC9zdmc+)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-small-down {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTIgNWg4TDYgOXoiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvc3ZnPg==)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-tick {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEuNSA1LjVsMyAzIDYtNiIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2U9IiMwMDAiIGZpbGw9Im5vbmUiLz48L3N2Zz4=)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-cross {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTIgMTBsOC04bTAgOEwyIDIiIHN0cm9rZT0iIzAwMCIgc3Ryb2tlLXdpZHRoPSIyIiBmaWxsPSJub25lIi8+PC9zdmc+)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-tree-open {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTIgNWg4TDYgOXoiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvc3ZnPg==)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-tree-closed {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTUgMmw0IDQtNCA0eiIgZmlsbC1ydWxlPSJldmVub2RkIi8+PC9zdmc+)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-icon-tree-indeterminate {\n display: inline-block;\n background: transparent\n url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTIgNWg4djJIMnoiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvc3ZnPg==)\n center no-repeat;\n background-size: 12px 12px;\n filter: 'initial';\n height: 12px;\n width: 12px;\n}\n\n.ag-root-wrapper {\n position: relative;\n display: flex;\n flex-direction: column;\n box-sizing: border-box;\n overflow: hidden;\n}\n.ag-root-wrapper *,\n.ag-root-wrapper *:before,\n.ag-root-wrapper *:after {\n box-sizing: border-box;\n}\n.ag-root-wrapper.ag-layout-normal {\n height: 100%;\n}\n.ag-root-wrapper .ag-watermark {\n position: absolute;\n bottom: 10px;\n right: 25px;\n opacity: 0.5;\n transition: opacity 1s ease-out 3s;\n}\n.ag-root-wrapper .ag-watermark:before {\n content: '';\n background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iNDk0cHgiIGhlaWdodD0iMjM5cHgiIHZpZXdCb3g9IjAgMCA0OTQgMjM5IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogICAgPCEtLSBHZW5lcmF0b3I6IFNrZXRjaCA0Ny4xICg0NTQyMikgLSBodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2ggLS0+CiAgICA8dGl0bGU+TG9nbzwvdGl0bGU+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxkZWZzPgogICAgICAgIDxwYXRoIGQ9Ik0wLjYxMjg0OTkzMSwxMDggTDAuNjEyODQ5OTMxLDY3LjQ1OTYzNzQgTDAuNjEyODQ5OTMxLDY3LjQ1OTYzNzQgQzAuNjEyODQ5OTMxLDYyLjEwMDY1MzYgMy40NzE4MzM3OCw1Ny4xNDg3NDgzIDguMTEyODQ5OTMsNTQuNDY5MjU2NCBMOTguMzA2NDI1LDIuMzk1OTcxNTcgTDk4LjMwNjQyNSwyLjM5NTk3MTU3IEMxMDIuOTQ3NDQxLC0wLjI4MzUyMDM1OCAxMDguNjY1NDA5LC0wLjI4MzUyMDM1OCAxMTMuMzA2NDI1LDIuMzk1OTcxNTcgTDExMy4zMDY0MjUsMi4zOTU5NzE1NyBMMjAzLjUsNTQuNDY5MjU2NCBMMjAzLjUsNTQuNDY5MjU2NCBDMjA4LjE0MTAxNiw1Ny4xNDg3NDgzIDIxMSw2Mi4xMDA2NTM2IDIxMSw2Ny40NTk2Mzc0IEwyMTEsMTM4IEwxODEsMTM4IEwxODAuOTk3MDQxLDkzLjk5OTk5OTggTDE4MC45OTYwMzIsOTMuOTk5OTk5OSBDMTgwLjk5NTQ3NSw4NS43MTYxMjI2IDE3NC4yNzk5MDksNzkuMDAxMDA4NyAxNjUuOTk2MDMyLDc5LjAwMTAwODcgTDEyMiw3OC45OTk5OTk5IEMxMTMuNzE1NzI5LDc4Ljk5OTk5OTkgMTA3LDg1LjcxNTcyODYgMTA3LDkzLjk5OTk5OTkgTDEwNywxMzYuMDE1NjIzIEwxMDcsMTM2LjAxNTYyMyBDMTA3LDE0NC4yOTk4OTUgMTEzLjcxNTcyOSwxNTEuMDE1NjIzIDEyMiwxNTEuMDE1NjIzIEwxNjgsMTUxLjAxNTYyMyBMMTY4LDE2MyBDMTY4LDE2NC42NTY4NTQgMTY2LjY1Njg1NCwxNjYgMTY1LDE2NiBMMTIwLDE2NiBMMTIwLDE3OSBMMTY1Ljk5NjAzMiwxNzkgTDE2NS45OTYwMzIsMTc4Ljk5Nzg3NyBDMTc0LjI3OTQ3NCwxNzguOTk3ODc3IDE4MC45OTQ4NiwxNzIuMjgzNDQyIDE4MC45OTYwMzIsMTY0IEwxODEsMTUwLjk2MDU1NCBMMjExLDE1MC45NjA1NTQgTDIxMSwxNzEuNjA2MjA3IEwyMTEsMTcxLjYwNjIwNyBDMjExLDE3Ni45NjUxOTEgMjA4LjE0MTAxNiwxODEuOTE3MDk2IDIwMy41LDE4NC41OTY1ODggTDExMy4zMDY0MjUsMjM2LjY2OTg3MyBMMTEzLjMwNjQyNSwyMzYuNjY5ODczIEMxMDguNjY1NDA5LDIzOS4zNDkzNjUgMTAyLjk0NzQ0MSwyMzkuMzQ5MzY1IDk4LjMwNjQyNSwyMzYuNjY5ODczIEw4LjExMjg0OTkzLDE4NC41OTY1ODggTDguMTEyODQ5OTMsMTg0LjU5NjU4OCBDMy40NzE4MzM3OCwxODEuOTE3MDk2IDAuNjEyODQ5OTMxLDE3Ni45NjUxOTEgMC42MTI4NDk5MzEsMTcxLjYwNjIwNyBMMC42MTI4NDk5MzEsMTIxIEwyNywxMjEgTDI3LDEzNiBDMjcsMTQ0LjI4NDI3MSAzMy43MTU3Mjg3LDE1MSA0MiwxNTEgTDQyLDE1MSBMMTAwLDE1MSBMMTAwLDk0IEMxMDAsODUuNzE1NzI4OCA5My4yODQyNzEyLDc5IDg1LDc5IEwyNyw3OSBMMjcsOTIgTDg0LDkyIEM4NS42NTY4NTQyLDkyIDg3LDkzLjM0MzE0NTggODcsOTUgTDg3LDk1IEw4NywxMDggTDAuNjEyODQ5OTMxLDEwOCBaIiBpZD0icGF0aC0xIj48L3BhdGg+CiAgICA8L2RlZnM+CiAgICA8ZyBpZD0iU3ltYm9scyIgc3Ryb2tlPSJub25lIiBzdHJva2Utd2lkdGg9IjEiIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCI+CiAgICAgICAgPGcgaWQ9IkxvZ28iPgogICAgICAgICAgICA8cGF0aCBkPSJNNDc3LDU1IEw0OTQsNTUgTDQ5NCwxNTEgTDQzNSwxNTEgQzQyNi43MTU3MjksMTUxIDQyMCwxNDQuMjg0MjcxIDQyMCwxMzYgTDQyMCw5NiBDNDIwLDg3LjcxNTcyODggNDI2LjcxNTcyOSw4MSA0MzUsODEgTDQzNSw4MSBMNDc3LDgxIEw0NzcsNTUgWiBNNDQwLDk4IEM0MzguMzQzMTQ2LDk4IDQzNyw5OS4zNDMxNDU4IDQzNywxMDEgTDQzNywxMzEgQzQzNywxMzIuNjU2ODU0IDQzOC4zNDMxNDYsMTM0IDQ0MCwxMzQgTDQ3NywxMzQgTDQ3Nyw5OCBMNDQwLDk4IFoiIGlkPSJkIiBmaWxsPSIjRkZGRkZGIj48L3BhdGg+CiAgICAgICAgICAgIDxnIGlkPSJpIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgzOTYuMDAwMDAwLCA1NS4wMDAwMDApIj4KICAgICAgICAgICAgICAgIDxwb2x5Z29uIGlkPSJQYXRoLTYiIGZpbGw9IiNGRkZGRkYiIHBvaW50cz0iMCAyNiAxNyAyNiAxNyA5NiAwIDk2Ij48L3BvbHlnb24+CiAgICAgICAgICAgICAgICA8cG9seWdvbiBpZD0iUGF0aC03IiBmaWxsPSIjRTExRjIyIiBwb2ludHM9IjAgMS4xMzY4NjgzOGUtMTMgMTcgMS4xMzY4NjgzOGUtMTMgMTcgMTcgMCAxNyI+PC9wb2x5Z29uPgogICAgICAgICAgICA8L2c+CiAgICAgICAgICAgIDxwYXRoIGQ9Ik0zMzEsMTUxIEwzNDgsMTUxIEwzNDgsMTAxIEwzNDgsMTAxIEMzNDgsOTkuMzQzMTQ1OCAzNDkuMzQzMTQ2LDk4IDM1MSw5OCBMMzg5LDk4IEwzODksODEgTDM0Niw4MSBMMzQ2LDgxIEMzMzcuNzE1NzI5LDgxIDMzMSw4Ny43MTU3Mjg4IDMzMSw5NiBMMzMxLDE1MSBaIiBpZD0iciIgZmlsbD0iI0ZGRkZGRiI+PC9wYXRoPgogICAgICAgICAgICA8cGF0aCBkPSJNMzI0LDg2IEwzMjQsNzYgTDMyNCw3NiBDMzI0LDY3LjcxNTcyODggMzE3LjI4NDI3MSw2MSAzMDksNjEgTDI0OSw2MSBMMjQ5LDYxIEMyNDAuNzE1NzI5LDYxIDIzNCw2Ny43MTU3Mjg4IDIzNCw3NiBMMjM0LDEzNiBMMjM0LDEzNiBDMjM0LDE0NC4yODQyNzEgMjQwLjcxNTcyOSwxNTEgMjQ5LDE1MSBMMzA5LDE1MSBMMzA5LDE1MSBDMzE3LjI4NDI3MSwxNTEgMzI0LDE0NC4yODQyNzEgMzI0LDEzNiBMMzI0LDEwMCBMMjg3LDEwMCBMMjg3LDExNyBMMzA3LDExNyBMMzA3LDEzMSBMMzA3LDEzMSBDMzA3LDEzMi42NTY4NTQgMzA1LjY1Njg1NCwxMzQgMzA0LDEzNCBMMjU0LDEzNCBMMjU0LDEzNCBDMjUyLjM0MzE0NiwxMzQgMjUxLDEzMi42NTY4NTQgMjUxLDEzMSBMMjUxLDgxIEwyNTEsODEgQzI1MSw3OS4zNDMxNDU4IDI1Mi4zNDMxNDYsNzggMjU0LDc4IEwzMDQsNzggTDMwNCw3OCBDMzA1LjY1Njg1NCw3OCAzMDcsNzkuMzQzMTQ1OCAzMDcsODEgTDMwNyw4NiBMMzI0LDg2IFoiIGlkPSJHIiBmaWxsPSIjRkZGRkZGIj48L3BhdGg+CiAgICAgICAgICAgIDxnIGlkPSJhZyI+CiAgICAgICAgICAgICAgICA8ZyBpZD0iQ29tYmluZWQtU2hhcGUiPgogICAgICAgICAgICAgICAgICAgIDxtYXNrIGlkPSJtYXNrLTIiIGZpbGw9IndoaXRlIj4KICAgICAgICAgICAgICAgICAgICAgICAgPHVzZSB4bGluazpocmVmPSIjcGF0aC0xIj48L3VzZT4KICAgICAgICAgICAgICAgICAgICA8L21hc2s+CiAgICAgICAgICAgICAgICAgICAgPHVzZSBmaWxsPSIjRTExRjIyIiB4bGluazpocmVmPSIjcGF0aC0xIj48L3VzZT4KICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJnIiBmaWxsPSIjRTExRjIyIiB4PSIxMjAiIHk9IjkyIiB3aWR0aD0iNDgiIGhlaWdodD0iNDYiIHJ4PSIzIj48L3JlY3Q+CiAgICAgICAgICAgICAgICA8cGF0aCBkPSJNNDAsMTIxIEw4NywxMjEgTDg3LDEzOCBMNDMsMTM4IEw0MywxMzggQzQxLjM0MzE0NTgsMTM4IDQwLDEzNi42NTY4NTQgNDAsMTM1IEw0MCwxMjEgWiIgaWQ9IkNvbWJpbmVkLVNoYXBlIiBmaWxsPSIjRTExRjIyIj48L3BhdGg+CiAgICAgICAgICAgIDwvZz4KICAgICAgICA8L2c+CiAgICA8L2c+Cjwvc3ZnPg==);\n filter: invert(50%);\n background-repeat: no-repeat;\n background-size: 110px 60px;\n display: block;\n height: 60px;\n width: 110px;\n}\n.ag-root-wrapper .ag-watermark:after {\n content: 'Invalid License Key';\n font-weight: bold;\n font-family: Impact;\n font-size: 19px;\n}\n\n.ag-root-wrapper-body {\n display: flex;\n flex-direction: row;\n}\n.ag-root-wrapper-body.ag-layout-normal {\n flex: 1 1 auto;\n height: 0;\n min-height: 0;\n}\n\n.ag-root {\n cursor: default;\n position: relative;\n display: flex;\n flex-direction: column;\n}\n.ag-root.ag-layout-normal,\n.ag-root.ag-layout-auto-height {\n overflow: hidden;\n flex: 1 1 auto;\n width: 0;\n}\n.ag-root.ag-layout-normal {\n height: 100%;\n}\n\n/**\n ****************************\n * Viewports\n ****************************\n*/\n.ag-header-viewport,\n.ag-floating-top-viewport,\n.ag-body-viewport,\n.ag-pinned-left-cols-viewport,\n.ag-center-cols-viewport,\n.ag-pinned-right-cols-viewport,\n.ag-floating-bottom-viewport,\n.ag-body-horizontal-scroll-viewport,\n.ag-virtual-list-viewport {\n position: relative;\n height: 100%;\n min-width: 0px;\n overflow: hidden;\n flex: 1 1 auto;\n}\n\n.ag-body-viewport {\n display: flex;\n}\n.ag-body-viewport.ag-layout-normal {\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n}\n.ag-body-viewport:not(.ag-layout-print).ag-force-vertical-scroll {\n overflow-y: scroll;\n}\n\n.ag-pinned-left-cols-viewport,\n.ag-pinned-right-cols-viewport {\n flex-grow: 1000;\n}\n\n.ag-center-cols-viewport {\n width: 100%;\n overflow-x: auto;\n}\n\n.ag-body-horizontal-scroll-viewport {\n overflow-x: scroll;\n}\n\n.ag-virtual-list-viewport {\n overflow: auto;\n width: 100%;\n}\n\n/**\n ****************************\n * Containers\n ****************************\n*/\n.ag-header-container,\n.ag-floating-top-container,\n.ag-body-container,\n.ag-pinned-right-cols-container,\n.ag-center-cols-container,\n.ag-pinned-left-cols-container,\n.ag-floating-bottom-container,\n.ag-body-horizontal-scroll-container,\n.ag-full-width-container,\n.ag-floating-bottom-full-width-container,\n.ag-virtual-list-container {\n position: relative;\n}\n\n.ag-header-container,\n.ag-floating-top-container,\n.ag-floating-bottom-container {\n height: 100%;\n white-space: nowrap;\n}\n\n.ag-body-viewport .ag-center-cols-clipper {\n min-height: 100%;\n}\n\n.ag-body-viewport.ag-layout-auto-height .ag-center-cols-clipper,\n.ag-body-viewport.ag-layout-auto-height .ag-center-cols-container {\n min-height: 50px;\n}\n\n.ag-body-viewport .ag-center-cols-container {\n display: block;\n}\n\n.ag-body-viewport.ag-layout-print {\n flex: none;\n}\n.ag-body-viewport.ag-layout-print .ag-center-cols-clipper {\n min-width: 100%;\n}\n\n.ag-pinned-right-cols-container {\n display: block;\n}\n\n.ag-body-horizontal-scroll-container {\n height: 100%;\n}\n\n.ag-full-width-container,\n.ag-floating-top-full-width-container,\n.ag-floating-bottom-full-width-container {\n position: absolute;\n top: 0px;\n left: 0px;\n pointer-events: none;\n}\n\n.ag-full-width-container {\n width: 100%;\n}\n\n.ag-floating-bottom-full-width-container,\n.ag-floating-top-full-width-container {\n display: inline-block;\n overflow: hidden;\n height: 100%;\n width: 100%;\n}\n\n.ag-virtual-list-container {\n overflow: hidden;\n}\n\n/**\n ****************************\n * Scrollers\n ****************************\n*/\n.ag-center-cols-clipper {\n flex: 1;\n min-width: 0;\n overflow: hidden;\n}\n\n.ag-body-horizontal-scroll {\n min-height: 0;\n min-width: 0;\n width: 100%;\n display: flex;\n position: relative;\n}\n\n.ag-layout-print .ag-body-horizontal-scroll {\n display: none;\n}\n\n.ag-horizontal-left-spacer,\n.ag-horizontal-right-spacer {\n height: 100%;\n min-width: 0;\n flex-grow: 1000;\n overflow-x: scroll;\n}\n.ag-horizontal-left-spacer.ag-scroller-corner,\n.ag-horizontal-right-spacer.ag-scroller-corner {\n overflow-x: hidden;\n}\n\n/**\n ****************************\n * Headers\n ****************************\n*/\n.ag-header,\n.ag-pinned-left-header,\n.ag-pinned-right-header {\n display: inline-block;\n overflow: hidden;\n}\n.ag-header .ag-header-cell-sortable,\n.ag-pinned-left-header .ag-header-cell-sortable,\n.ag-pinned-right-header .ag-header-cell-sortable {\n cursor: pointer;\n}\n\n.ag-header {\n display: flex;\n width: 100%;\n white-space: nowrap;\n}\n\n.ag-pinned-left-header {\n height: 100%;\n}\n\n.ag-pinned-right-header {\n height: 100%;\n}\n\n.ag-header-row {\n position: absolute;\n}\n\n.ag-header-overlay {\n display: block;\n position: absolute;\n}\n\n.ag-header-cell {\n display: inline-block;\n height: 100%;\n position: absolute;\n vertical-align: bottom;\n -webkit-user-select: none;\n user-select: none;\n}\n\n.ag-header-group-cell-label {\n overflow: hidden;\n text-overflow: ellipsis;\n display: flex;\n}\n\n.ag-header-cell-label {\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.ag-header-cell-resize {\n position: absolute;\n z-index: 4;\n cursor: col-resize;\n height: 100%;\n width: 4px;\n}\n\n.ag-header-expand-icon {\n padding-left: 4px;\n}\n\n.ag-header-cell-menu-button {\n float: right;\n}\n\n.ag-primary-cols-header-panel .ag-column-name-filter {\n flex-grow: 1;\n flex-shrink: 1;\n}\n\n.ag-primary-cols-header-panel .ag-primary-cols-filter-wrapper {\n width: 100%;\n}\n\n.ag-primary-cols-header-panel {\n display: flex;\n flex-direction: row;\n}\n\n/**\n ****************************\n * Columns\n ****************************\n*/\n.ag-column-moving .ag-cell {\n transition: left 0.2s;\n}\n\n.ag-column-moving .ag-header-cell {\n transition: left 0.2s;\n}\n\n.ag-column-moving .ag-header-group-cell {\n transition: left 0.2s, width 0.2s;\n}\n\n.ag-column-drop {\n width: 100%;\n}\n\n.ag-column-drop-vertical {\n display: flex;\n flex-direction: column;\n flex-grow: 1;\n height: 50px;\n overflow: hidden;\n}\n.ag-column-drop-vertical .ag-column-drop-list {\n flex-grow: 1;\n height: 20px;\n overflow-x: auto;\n}\n.ag-column-drop-vertical .ag-column-drop-cell {\n display: flex;\n}\n.ag-column-drop-vertical .ag-column-drop-cell .ag-column-drop-cell-text {\n overflow: hidden;\n flex: 1;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.ag-column-drop-vertical .ag-column-drop-empty-message {\n display: block;\n}\n.ag-column-drop-vertical .ag-column-drop-cell-button {\n line-height: 16px;\n}\n\n.ag-ltr .ag-column-drop-vertical .ag-column-drop-cell-button {\n float: right;\n}\n\n.ag-rtl .ag-column-drop-vertical .ag-column-drop-cell-button {\n float: left;\n}\n\n.ag-column-drop-horizontal {\n white-space: nowrap;\n overflow: hidden;\n}\n.ag-column-drop-horizontal .ag-column-drop-cell {\n display: inline-block;\n}\n.ag-column-drop-horizontal .ag-column-drop-empty-message {\n display: inline-block;\n}\n.ag-column-drop-horizontal .ag-column-drop-list {\n height: 100%;\n}\n\n.ag-column-select-indent {\n display: inline-block;\n}\n\n.ag-column-panel {\n display: flex;\n min-height: 400px;\n flex-direction: column;\n flex-grow: 1;\n overflow-x: hidden;\n max-height: 100vh;\n}\n\n/**\n ****************************\n * Rows\n ****************************\n*/\n.ag-row-animation .ag-row {\n transition: transform 0.4s, top 0.4s, height 0.4s, background-color 0.1s,\n opacity 0.2s;\n}\n\n.ag-row-no-animation .ag-row {\n transition: background-color 0.1s;\n}\n\n.ag-row {\n white-space: nowrap;\n width: 100%;\n}\n\n.ag-row-position-absolute {\n position: absolute;\n}\n\n.ag-row-position-relative {\n position: relative;\n}\n\n.ag-full-width-row {\n overflow: hidden;\n pointer-events: all;\n}\n\n.ag-row-inline-editing {\n z-index: 1;\n}\n\n/**\n ****************************\n * Cells\n ****************************\n*/\n.ag-cell {\n display: inline-block;\n overflow: hidden;\n position: absolute;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.ag-cell-with-height {\n height: 100%;\n}\n\n.ag-cell-edit-input {\n height: 100%;\n width: 100%;\n line-height: normal;\n}\n\n.ag-group-cell-entire-row {\n display: inline-block;\n height: 100%;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n width: 100%;\n}\n\n.ag-footer-cell-entire-row {\n display: inline-block;\n height: 100%;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n width: 100%;\n}\n\n/**\n ****************************\n * Filters\n ****************************\n*/\n.ag-set-filter-item {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.ag-filter-filter {\n width: 100%;\n}\n\n.ag-filter .ag-filter-checkbox {\n pointer-events: none;\n}\n\n.ag-filter-select {\n margin: 4px 4px 0 4px;\n width: 110px;\n}\n\n/**\n ****************************\n * Floating Filter\n ****************************\n*/\n.ag-floating-filter-full-body .ag-react-container,\n.ag-floating-filter-body .ag-react-container {\n height: 100%;\n}\n\n.ag-floating-filter-body input {\n height: 19px;\n margin: 0;\n width: 100%;\n}\n\n.ag-floating-filter-full-body input {\n height: 19px;\n margin: 0;\n width: 100%;\n}\n\n.ag-floating-filter-full-body input[type='range'] {\n height: 100%;\n}\n\n.ag-floating-filter {\n display: inline-block;\n position: absolute;\n}\n\n.ag-floating-filter-body {\n height: 20px;\n margin-right: 25px;\n}\n\n.ag-floating-filter-full-body {\n height: 100%;\n width: 100%;\n}\n\n.ag-floating-filter-input {\n width: 100%;\n}\n\n.ag-floating-filter-input:read-only {\n background-color: #eee;\n}\n\n.ag-floating-filter-menu {\n position: absolute;\n -webkit-user-select: none;\n user-select: none;\n}\n\n/**\n ****************************\n * Drag & Drop\n ****************************\n*/\n.ag-dnd-ghost {\n background: #e8edeb;\n border: 1px solid #001e2b;\n cursor: grabbing;\n font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;\n font-size: 14px;\n line-height: 1.4;\n overflow: hidden;\n padding: 3px;\n position: absolute;\n text-overflow: ellipsis;\n -webkit-user-select: none;\n user-select: none;\n}\n\n.ag-dnd-ghost-icon {\n display: inline-block;\n padding: 2px;\n}\n\n.ag-dnd-ghost-label {\n display: inline-block;\n}\n\n/**\n ****************************\n * Overlay\n ****************************\n*/\n.ag-overlay {\n height: 100%;\n left: 0;\n pointer-events: none;\n position: absolute;\n top: 0;\n width: 100%;\n}\n\n.ag-overlay-panel {\n display: flex;\n height: 100%;\n pointer-events: none;\n width: 100%;\n}\n\n.ag-overlay-wrapper {\n display: flex;\n flex: none;\n width: 100%;\n height: 100%;\n align-items: center;\n justify-content: center;\n text-align: center;\n}\n.ag-overlay-wrapper.ag-overlay-loading-wrapper {\n pointer-events: all;\n}\n\n.ag-overlay-no-rows-wrapper.ag-layout-auto-height {\n padding-top: 30px;\n}\n\n/**\n ****************************\n * Popup\n ****************************\n*/\n.ag-popup-backdrop {\n height: 100%;\n left: 0;\n position: fixed;\n top: 0;\n width: 100%;\n}\n\n.ag-popup-editor {\n position: absolute;\n -webkit-user-select: none;\n user-select: none;\n}\n\n/**\n ****************************\n * Virtual Lists\n ****************************\n*/\n.ag-virtual-list-item {\n position: absolute;\n width: 100%;\n}\n.ag-virtual-list-item span:empty:not(.ag-icon) {\n border-left: 1px solid transparent;\n}\n\n/**\n ****************************\n * Floating Top and Bottom\n ****************************\n*/\n.ag-floating-top {\n overflow: hidden;\n white-space: nowrap;\n width: 100%;\n position: relative;\n display: flex;\n}\n\n.ag-pinned-left-floating-top {\n display: inline-block;\n overflow: hidden;\n position: relative;\n min-width: 0px;\n flex-grow: 1000;\n}\n\n.ag-pinned-right-floating-top {\n display: inline-block;\n overflow: hidden;\n position: relative;\n min-width: 0px;\n flex-grow: 1000;\n}\n\n.ag-floating-bottom {\n overflow: hidden;\n white-space: nowrap;\n width: 100%;\n position: relative;\n display: flex;\n}\n\n.ag-pinned-left-floating-bottom {\n display: inline-block;\n overflow: hidden;\n position: relative;\n min-width: 0px;\n flex-grow: 1000;\n}\n\n.ag-pinned-right-floating-bottom {\n display: inline-block;\n overflow: hidden;\n position: relative;\n min-width: 0px;\n flex-grow: 1000;\n}\n\n/**\n ****************************\n * Tooltip\n ****************************\n*/\n.ag-tooltip {\n position: absolute;\n pointer-events: none;\n z-index: 99999;\n}\n\n/**\n ****************************\n * Animations\n ****************************\n*/\n.ag-value-slide-out {\n margin-right: 5px;\n opacity: 1;\n transition: opacity 3s, margin-right 3s;\n transition-timing-function: linear;\n}\n\n.ag-value-slide-out-end {\n margin-right: 10px;\n opacity: 0;\n}\n\n.ag-opacity-zero {\n opacity: 0 !important;\n}\n\n/**\n ****************************\n * Menu\n ****************************\n*/\n.ag-menu {\n max-height: 100%;\n overflow-y: auto;\n position: absolute;\n -webkit-user-select: none;\n user-select: none;\n}\n\n.ag-tab {\n box-sizing: content-box;\n}\n\n.ag-menu-column-select-wrapper {\n height: 265px;\n overflow: auto;\n width: 200px;\n}\n\n.ag-menu-list {\n border-collapse: collapse;\n display: table;\n}\n\n.ag-menu-option {\n display: table-row;\n}\n\n.ag-menu-option-text {\n display: table-cell;\n white-space: nowrap;\n}\n\n.ag-menu-option-shortcut {\n display: table-cell;\n}\n\n.ag-menu-option-icon {\n display: table-cell;\n}\n\n.ag-menu-option-popup-pointer {\n display: table-cell;\n}\n\n.ag-menu-separator {\n display: table-row;\n}\n\n.ag-menu-separator-cell {\n display: table-cell;\n}\n\n.ag-menu-column-select-wrapper .ag-column-select-panel {\n height: 100%;\n}\n\n/**\n ****************************\n * Rich Select\n ****************************\n*/\n.ag-rich-select {\n cursor: default;\n outline: none;\n}\n\n.ag-rich-select-row {\n white-space: nowrap;\n}\n\n.ag-rich-select-list {\n height: 200px;\n width: 200px;\n}\n\n.ag-set-filter-list {\n height: 200px;\n width: 200px;\n}\n\n/**\n ****************************\n * Tool Panel\n ****************************\n*/\n.ag-tool-panel-wrapper {\n display: flex;\n overflow-y: auto;\n cursor: default;\n -webkit-user-select: none;\n user-select: none;\n width: 200px;\n}\n.ag-tool-panel-wrapper .ag-filter-toolpanel-header {\n cursor: pointer;\n}\n\n.ag-primary-cols-list-panel {\n flex-grow: 1;\n height: 50px;\n overflow: auto;\n}\n\n.ag-ltr .ag-column-tool-panel-column {\n margin-left: 16px;\n}\n\n.ag-rtl .ag-column-tool-panel-column {\n margin-right: 16px;\n}\n\n.ag-column-tool-panel-column,\n.ag-column-tool-panel-column-group {\n align-items: stretch;\n display: flex;\n flex-direction: row;\n flex-wrap: nowrap;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.ag-column-tool-panel-column .ag-column-tool-panel-column,\n.ag-column-tool-panel-column .ag-column-tool-panel-column-group,\n.ag-column-tool-panel-column-group .ag-column-tool-panel-column,\n.ag-column-tool-panel-column-group .ag-column-tool-panel-column-group {\n flex-grow: 1;\n flex-shrink: 1;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n.ag-column-tool-panel-column .ag-column-drag,\n.ag-column-tool-panel-column-group .ag-column-drag {\n min-width: 16px;\n flex-grow: 0;\n flex-shrink: 0;\n}\n\n.ag-column-select-panel {\n display: flex;\n flex-direction: column;\n overflow: hidden;\n}\n\n.ag-side-bar .ag-column-select-panel {\n flex-grow: 4;\n}\n\n.ag-tool-panel-horizontal-resize {\n cursor: col-resize;\n height: 100%;\n position: absolute;\n top: 0;\n width: 5px;\n z-index: 1;\n}\n\n.ag-rtl .ag-tool-panel-horizontal-resize {\n float: right;\n transform: translateX(3px);\n}\n\n.ag-ltr .ag-tool-panel-horizontal-resize {\n float: left;\n transform: translateX(-3px);\n}\n\n.loading-filter {\n background-color: #e8edeb;\n height: 100%;\n padding: 5px;\n position: absolute;\n top: 34px;\n width: 100%;\n z-index: 1;\n}\n\n.ag-details-row {\n height: 100%;\n width: 100%;\n}\n\n.ag-details-grid {\n height: 100%;\n width: 100%;\n}\n\n.ag-header-group-cell {\n display: inline-block;\n height: 100%;\n overflow: hidden;\n position: absolute;\n text-overflow: ellipsis;\n}\n\n/**\n ****************************\n * Side Bar\n ****************************\n*/\n.ag-side-bar {\n display: flex;\n flex-direction: row-reverse;\n}\n.ag-side-bar .ag-side-buttons {\n width: 20px;\n}\n.ag-side-bar .ag-side-buttons div button {\n display: block;\n white-space: nowrap;\n outline: none;\n cursor: pointer;\n}\n.ag-side-bar .ag-side-buttons div button span {\n writing-mode: tb;\n writing-mode: vertical-lr;\n}\n.ag-side-bar .panel-container {\n width: 180px;\n}\n.ag-side-bar.full-width .panel-container {\n width: 200px;\n}\n\n.ag-rtl .ag-side-bar .ag-side-buttons button span {\n writing-mode: tb-rl;\n writing-mode: vertical-rl;\n}\n\n/**\n ****************************\n * Status Bar\n ****************************\n*/\n.ag-status-bar {\n display: flex;\n justify-content: space-between;\n overflow: hidden;\n}\n.ag-status-bar .ag-status-panel {\n display: inline-flex;\n}\n\n.ag-status-bar-left {\n display: inline-flex;\n}\n\n.ag-status-bar-center {\n display: inline-flex;\n}\n\n.ag-status-bar-right {\n display: inline-flex;\n}\n\n.ag-ltr .ag-toolpanel-indent-1 {\n padding-left: 10px;\n}\n\n.ag-rtl .ag-toolpanel-indent-1 {\n padding-right: 10px;\n}\n\n.ag-ltr .ag-row-group-indent-1 {\n padding-left: 10px;\n}\n\n.ag-rtl .ag-row-group-indent-1 {\n padding-right: 10px;\n}\n\n.ag-ltr .ag-toolpanel-indent-2 {\n padding-left: 20px;\n}\n\n.ag-rtl .ag-toolpanel-indent-2 {\n padding-right: 20px;\n}\n\n.ag-ltr .ag-row-group-indent-2 {\n padding-left: 20px;\n}\n\n.ag-rtl .ag-row-group-indent-2 {\n padding-right: 20px;\n}\n\n.ag-ltr .ag-toolpanel-indent-3 {\n padding-left: 30px;\n}\n\n.ag-rtl .ag-toolpanel-indent-3 {\n padding-right: 30px;\n}\n\n.ag-ltr .ag-row-group-indent-3 {\n padding-left: 30px;\n}\n\n.ag-rtl .ag-row-group-indent-3 {\n padding-right: 30px;\n}\n\n.ag-ltr .ag-toolpanel-indent-4 {\n padding-left: 40px;\n}\n\n.ag-rtl .ag-toolpanel-indent-4 {\n padding-right: 40px;\n}\n\n.ag-ltr .ag-row-group-indent-4 {\n padding-left: 40px;\n}\n\n.ag-rtl .ag-row-group-indent-4 {\n padding-right: 40px;\n}\n\n.ag-ltr .ag-toolpanel-indent-5 {\n padding-left: 50px;\n}\n\n.ag-rtl .ag-toolpanel-indent-5 {\n padding-right: 50px;\n}\n\n.ag-ltr .ag-row-group-indent-5 {\n padding-left: 50px;\n}\n\n.ag-rtl .ag-row-group-indent-5 {\n padding-right: 50px;\n}\n\n.ag-ltr .ag-toolpanel-indent-6 {\n padding-left: 60px;\n}\n\n.ag-rtl .ag-toolpanel-indent-6 {\n padding-right: 60px;\n}\n\n.ag-ltr .ag-row-group-indent-6 {\n padding-left: 60px;\n}\n\n.ag-rtl .ag-row-group-indent-6 {\n padding-right: 60px;\n}\n\n.ag-ltr .ag-toolpanel-indent-7 {\n padding-left: 70px;\n}\n\n.ag-rtl .ag-toolpanel-indent-7 {\n padding-right: 70px;\n}\n\n.ag-ltr .ag-row-group-indent-7 {\n padding-left: 70px;\n}\n\n.ag-rtl .ag-row-group-indent-7 {\n padding-right: 70px;\n}\n\n.ag-ltr .ag-toolpanel-indent-8 {\n padding-left: 80px;\n}\n\n.ag-rtl .ag-toolpanel-indent-8 {\n padding-right: 80px;\n}\n\n.ag-ltr .ag-row-group-indent-8 {\n padding-left: 80px;\n}\n\n.ag-rtl .ag-row-group-indent-8 {\n padding-right: 80px;\n}\n\n.ag-ltr .ag-toolpanel-indent-9 {\n padding-left: 90px;\n}\n\n.ag-rtl .ag-toolpanel-indent-9 {\n padding-right: 90px;\n}\n\n.ag-ltr .ag-row-group-indent-9 {\n padding-left: 90px;\n}\n\n.ag-rtl .ag-row-group-indent-9 {\n padding-right: 90px;\n}\n\n.ag-ltr .ag-toolpanel-indent-10 {\n padding-left: 100px;\n}\n\n.ag-rtl .ag-toolpanel-indent-10 {\n padding-right: 100px;\n}\n\n.ag-ltr .ag-row-group-indent-10 {\n padding-left: 100px;\n}\n\n.ag-rtl .ag-row-group-indent-10 {\n padding-right: 100px;\n}\n\n.ag-ltr .ag-toolpanel-indent-11 {\n padding-left: 110px;\n}\n\n.ag-rtl .ag-toolpanel-indent-11 {\n padding-right: 110px;\n}\n\n.ag-ltr .ag-row-group-indent-11 {\n padding-left: 110px;\n}\n\n.ag-rtl .ag-row-group-indent-11 {\n padding-right: 110px;\n}\n\n.ag-ltr .ag-toolpanel-indent-12 {\n padding-left: 120px;\n}\n\n.ag-rtl .ag-toolpanel-indent-12 {\n padding-right: 120px;\n}\n\n.ag-ltr .ag-row-group-indent-12 {\n padding-left: 120px;\n}\n\n.ag-rtl .ag-row-group-indent-12 {\n padding-right: 120px;\n}\n\n.ag-ltr .ag-toolpanel-indent-13 {\n padding-left: 130px;\n}\n\n.ag-rtl .ag-toolpanel-indent-13 {\n padding-right: 130px;\n}\n\n.ag-ltr .ag-row-group-indent-13 {\n padding-left: 130px;\n}\n\n.ag-rtl .ag-row-group-indent-13 {\n padding-right: 130px;\n}\n\n.ag-ltr .ag-toolpanel-indent-14 {\n padding-left: 140px;\n}\n\n.ag-rtl .ag-toolpanel-indent-14 {\n padding-right: 140px;\n}\n\n.ag-ltr .ag-row-group-indent-14 {\n padding-left: 140px;\n}\n\n.ag-rtl .ag-row-group-indent-14 {\n padding-right: 140px;\n}\n\n.ag-ltr .ag-toolpanel-indent-15 {\n padding-left: 150px;\n}\n\n.ag-rtl .ag-toolpanel-indent-15 {\n padding-right: 150px;\n}\n\n.ag-ltr .ag-row-group-indent-15 {\n padding-left: 150px;\n}\n\n.ag-rtl .ag-row-group-indent-15 {\n padding-right: 150px;\n}\n\n.ag-ltr .ag-toolpanel-indent-16 {\n padding-left: 160px;\n}\n\n.ag-rtl .ag-toolpanel-indent-16 {\n padding-right: 160px;\n}\n\n.ag-ltr .ag-row-group-indent-16 {\n padding-left: 160px;\n}\n\n.ag-rtl .ag-row-group-indent-16 {\n padding-right: 160px;\n}\n\n.ag-ltr .ag-toolpanel-indent-17 {\n padding-left: 170px;\n}\n\n.ag-rtl .ag-toolpanel-indent-17 {\n padding-right: 170px;\n}\n\n.ag-ltr .ag-row-group-indent-17 {\n padding-left: 170px;\n}\n\n.ag-rtl .ag-row-group-indent-17 {\n padding-right: 170px;\n}\n\n.ag-ltr .ag-toolpanel-indent-18 {\n padding-left: 180px;\n}\n\n.ag-rtl .ag-toolpanel-indent-18 {\n padding-right: 180px;\n}\n\n.ag-ltr .ag-row-group-indent-18 {\n padding-left: 180px;\n}\n\n.ag-rtl .ag-row-group-indent-18 {\n padding-right: 180px;\n}\n\n.ag-ltr .ag-toolpanel-indent-19 {\n padding-left: 190px;\n}\n\n.ag-rtl .ag-toolpanel-indent-19 {\n padding-right: 190px;\n}\n\n.ag-ltr .ag-row-group-indent-19 {\n padding-left: 190px;\n}\n\n.ag-rtl .ag-row-group-indent-19 {\n padding-right: 190px;\n}\n\n.ag-ltr .ag-toolpanel-indent-20 {\n padding-left: 200px;\n}\n\n.ag-rtl .ag-toolpanel-indent-20 {\n padding-right: 200px;\n}\n\n.ag-ltr .ag-row-group-indent-20 {\n padding-left: 200px;\n}\n\n.ag-rtl .ag-row-group-indent-20 {\n padding-right: 200px;\n}\n\n.ag-ltr .ag-toolpanel-indent-21 {\n padding-left: 210px;\n}\n\n.ag-rtl .ag-toolpanel-indent-21 {\n padding-right: 210px;\n}\n\n.ag-ltr .ag-row-group-indent-21 {\n padding-left: 210px;\n}\n\n.ag-rtl .ag-row-group-indent-21 {\n padding-right: 210px;\n}\n\n.ag-ltr .ag-toolpanel-indent-22 {\n padding-left: 220px;\n}\n\n.ag-rtl .ag-toolpanel-indent-22 {\n padding-right: 220px;\n}\n\n.ag-ltr .ag-row-group-indent-22 {\n padding-left: 220px;\n}\n\n.ag-rtl .ag-row-group-indent-22 {\n padding-right: 220px;\n}\n\n.ag-ltr .ag-toolpanel-indent-23 {\n padding-left: 230px;\n}\n\n.ag-rtl .ag-toolpanel-indent-23 {\n padding-right: 230px;\n}\n\n.ag-ltr .ag-row-group-indent-23 {\n padding-left: 230px;\n}\n\n.ag-rtl .ag-row-group-indent-23 {\n padding-right: 230px;\n}\n\n.ag-ltr .ag-toolpanel-indent-24 {\n padding-left: 240px;\n}\n\n.ag-rtl .ag-toolpanel-indent-24 {\n padding-right: 240px;\n}\n\n.ag-ltr .ag-row-group-indent-24 {\n padding-left: 240px;\n}\n\n.ag-rtl .ag-row-group-indent-24 {\n padding-right: 240px;\n}\n\n.ag-ltr .ag-toolpanel-indent-25 {\n padding-left: 250px;\n}\n\n.ag-rtl .ag-toolpanel-indent-25 {\n padding-right: 250px;\n}\n\n.ag-ltr .ag-row-group-indent-25 {\n padding-left: 250px;\n}\n\n.ag-rtl .ag-row-group-indent-25 {\n padding-right: 250px;\n}\n\n.ag-ltr .ag-toolpanel-indent-26 {\n padding-left: 260px;\n}\n\n.ag-rtl .ag-toolpanel-indent-26 {\n padding-right: 260px;\n}\n\n.ag-ltr .ag-row-group-indent-26 {\n padding-left: 260px;\n}\n\n.ag-rtl .ag-row-group-indent-26 {\n padding-right: 260px;\n}\n\n.ag-ltr .ag-toolpanel-indent-27 {\n padding-left: 270px;\n}\n\n.ag-rtl .ag-toolpanel-indent-27 {\n padding-right: 270px;\n}\n\n.ag-ltr .ag-row-group-indent-27 {\n padding-left: 270px;\n}\n\n.ag-rtl .ag-row-group-indent-27 {\n padding-right: 270px;\n}\n\n.ag-ltr .ag-toolpanel-indent-28 {\n padding-left: 280px;\n}\n\n.ag-rtl .ag-toolpanel-indent-28 {\n padding-right: 280px;\n}\n\n.ag-ltr .ag-row-group-indent-28 {\n padding-left: 280px;\n}\n\n.ag-rtl .ag-row-group-indent-28 {\n padding-right: 280px;\n}\n\n.ag-ltr .ag-toolpanel-indent-29 {\n padding-left: 290px;\n}\n\n.ag-rtl .ag-toolpanel-indent-29 {\n padding-right: 290px;\n}\n\n.ag-ltr .ag-row-group-indent-29 {\n padding-left: 290px;\n}\n\n.ag-rtl .ag-row-group-indent-29 {\n padding-right: 290px;\n}\n\n.ag-ltr .ag-toolpanel-indent-30 {\n padding-left: 300px;\n}\n\n.ag-rtl .ag-toolpanel-indent-30 {\n padding-right: 300px;\n}\n\n.ag-ltr .ag-row-group-indent-30 {\n padding-left: 300px;\n}\n\n.ag-rtl .ag-row-group-indent-30 {\n padding-right: 300px;\n}\n\n.ag-ltr .ag-toolpanel-indent-31 {\n padding-left: 310px;\n}\n\n.ag-rtl .ag-toolpanel-indent-31 {\n padding-right: 310px;\n}\n\n.ag-ltr .ag-row-group-indent-31 {\n padding-left: 310px;\n}\n\n.ag-rtl .ag-row-group-indent-31 {\n padding-right: 310px;\n}\n\n.ag-ltr .ag-toolpanel-indent-32 {\n padding-left: 320px;\n}\n\n.ag-rtl .ag-toolpanel-indent-32 {\n padding-right: 320px;\n}\n\n.ag-ltr .ag-row-group-indent-32 {\n padding-left: 320px;\n}\n\n.ag-rtl .ag-row-group-indent-32 {\n padding-right: 320px;\n}\n\n.ag-ltr .ag-toolpanel-indent-33 {\n padding-left: 330px;\n}\n\n.ag-rtl .ag-toolpanel-indent-33 {\n padding-right: 330px;\n}\n\n.ag-ltr .ag-row-group-indent-33 {\n padding-left: 330px;\n}\n\n.ag-rtl .ag-row-group-indent-33 {\n padding-right: 330px;\n}\n\n.ag-ltr .ag-toolpanel-indent-34 {\n padding-left: 340px;\n}\n\n.ag-rtl .ag-toolpanel-indent-34 {\n padding-right: 340px;\n}\n\n.ag-ltr .ag-row-group-indent-34 {\n padding-left: 340px;\n}\n\n.ag-rtl .ag-row-group-indent-34 {\n padding-right: 340px;\n}\n\n.ag-ltr .ag-toolpanel-indent-35 {\n padding-left: 350px;\n}\n\n.ag-rtl .ag-toolpanel-indent-35 {\n padding-right: 350px;\n}\n\n.ag-ltr .ag-row-group-indent-35 {\n padding-left: 350px;\n}\n\n.ag-rtl .ag-row-group-indent-35 {\n padding-right: 350px;\n}\n\n.ag-ltr .ag-toolpanel-indent-36 {\n padding-left: 360px;\n}\n\n.ag-rtl .ag-toolpanel-indent-36 {\n padding-right: 360px;\n}\n\n.ag-ltr .ag-row-group-indent-36 {\n padding-left: 360px;\n}\n\n.ag-rtl .ag-row-group-indent-36 {\n padding-right: 360px;\n}\n\n.ag-ltr .ag-toolpanel-indent-37 {\n padding-left: 370px;\n}\n\n.ag-rtl .ag-toolpanel-indent-37 {\n padding-right: 370px;\n}\n\n.ag-ltr .ag-row-group-indent-37 {\n padding-left: 370px;\n}\n\n.ag-rtl .ag-row-group-indent-37 {\n padding-right: 370px;\n}\n\n.ag-ltr .ag-toolpanel-indent-38 {\n padding-left: 380px;\n}\n\n.ag-rtl .ag-toolpanel-indent-38 {\n padding-right: 380px;\n}\n\n.ag-ltr .ag-row-group-indent-38 {\n padding-left: 380px;\n}\n\n.ag-rtl .ag-row-group-indent-38 {\n padding-right: 380px;\n}\n\n.ag-ltr .ag-toolpanel-indent-39 {\n padding-left: 390px;\n}\n\n.ag-rtl .ag-toolpanel-indent-39 {\n padding-right: 390px;\n}\n\n.ag-ltr .ag-row-group-indent-39 {\n padding-left: 390px;\n}\n\n.ag-rtl .ag-row-group-indent-39 {\n padding-right: 390px;\n}\n\n.ag-ltr .ag-toolpanel-indent-40 {\n padding-left: 400px;\n}\n\n.ag-rtl .ag-toolpanel-indent-40 {\n padding-right: 400px;\n}\n\n.ag-ltr .ag-row-group-indent-40 {\n padding-left: 400px;\n}\n\n.ag-rtl .ag-row-group-indent-40 {\n padding-right: 400px;\n}\n\n.ag-ltr .ag-toolpanel-indent-41 {\n padding-left: 410px;\n}\n\n.ag-rtl .ag-toolpanel-indent-41 {\n padding-right: 410px;\n}\n\n.ag-ltr .ag-row-group-indent-41 {\n padding-left: 410px;\n}\n\n.ag-rtl .ag-row-group-indent-41 {\n padding-right: 410px;\n}\n\n.ag-ltr .ag-toolpanel-indent-42 {\n padding-left: 420px;\n}\n\n.ag-rtl .ag-toolpanel-indent-42 {\n padding-right: 420px;\n}\n\n.ag-ltr .ag-row-group-indent-42 {\n padding-left: 420px;\n}\n\n.ag-rtl .ag-row-group-indent-42 {\n padding-right: 420px;\n}\n\n.ag-ltr .ag-toolpanel-indent-43 {\n padding-left: 430px;\n}\n\n.ag-rtl .ag-toolpanel-indent-43 {\n padding-right: 430px;\n}\n\n.ag-ltr .ag-row-group-indent-43 {\n padding-left: 430px;\n}\n\n.ag-rtl .ag-row-group-indent-43 {\n padding-right: 430px;\n}\n\n.ag-ltr .ag-toolpanel-indent-44 {\n padding-left: 440px;\n}\n\n.ag-rtl .ag-toolpanel-indent-44 {\n padding-right: 440px;\n}\n\n.ag-ltr .ag-row-group-indent-44 {\n padding-left: 440px;\n}\n\n.ag-rtl .ag-row-group-indent-44 {\n padding-right: 440px;\n}\n\n.ag-ltr .ag-toolpanel-indent-45 {\n padding-left: 450px;\n}\n\n.ag-rtl .ag-toolpanel-indent-45 {\n padding-right: 450px;\n}\n\n.ag-ltr .ag-row-group-indent-45 {\n padding-left: 450px;\n}\n\n.ag-rtl .ag-row-group-indent-45 {\n padding-right: 450px;\n}\n\n.ag-ltr .ag-toolpanel-indent-46 {\n padding-left: 460px;\n}\n\n.ag-rtl .ag-toolpanel-indent-46 {\n padding-right: 460px;\n}\n\n.ag-ltr .ag-row-group-indent-46 {\n padding-left: 460px;\n}\n\n.ag-rtl .ag-row-group-indent-46 {\n padding-right: 460px;\n}\n\n.ag-ltr .ag-toolpanel-indent-47 {\n padding-left: 470px;\n}\n\n.ag-rtl .ag-toolpanel-indent-47 {\n padding-right: 470px;\n}\n\n.ag-ltr .ag-row-group-indent-47 {\n padding-left: 470px;\n}\n\n.ag-rtl .ag-row-group-indent-47 {\n padding-right: 470px;\n}\n\n.ag-ltr .ag-toolpanel-indent-48 {\n padding-left: 480px;\n}\n\n.ag-rtl .ag-toolpanel-indent-48 {\n padding-right: 480px;\n}\n\n.ag-ltr .ag-row-group-indent-48 {\n padding-left: 480px;\n}\n\n.ag-rtl .ag-row-group-indent-48 {\n padding-right: 480px;\n}\n\n.ag-ltr .ag-toolpanel-indent-49 {\n padding-left: 490px;\n}\n\n.ag-rtl .ag-toolpanel-indent-49 {\n padding-right: 490px;\n}\n\n.ag-ltr .ag-row-group-indent-49 {\n padding-left: 490px;\n}\n\n.ag-rtl .ag-row-group-indent-49 {\n padding-right: 490px;\n}\n\n.ag-ltr {\n direction: ltr;\n}\n.ag-ltr .ag-body,\n.ag-ltr .ag-floating-top,\n.ag-ltr .ag-floating-bottom,\n.ag-ltr .ag-header,\n.ag-ltr .ag-body-viewport,\n.ag-ltr .ag-body-horizontal-scroll {\n flex-direction: row;\n}\n.ag-ltr .ag-header-cell-resize {\n right: -4px;\n}\n.ag-ltr .ag-pinned-right-header .ag-header-cell-resize {\n left: -4px;\n}\n.ag-ltr .ag-header-select-all {\n float: left;\n}\n\n.ag-rtl {\n direction: rtl;\n}\n.ag-rtl .ag-body,\n.ag-rtl .ag-floating-top,\n.ag-rtl .ag-floating-bottom,\n.ag-rtl .ag-header,\n.ag-rtl .ag-body-viewport,\n.ag-rtl .ag-body-horizontal-scroll {\n flex-direction: row-reverse;\n}\n.ag-rtl .ag-header-cell-resize {\n left: -4px;\n}\n.ag-rtl .ag-pinned-left-header .ag-header-cell-resize {\n right: -4px;\n}\n.ag-rtl .ag-header-select-all {\n float: right;\n}\n\n@media print {\n .ag-body-viewport {\n display: block;\n }\n .ag-row {\n page-break-inside: avoid;\n }\n}\n\n.ag-body .ag-pinned-left-cols-viewport,\n.ag-body .ag-body-viewport,\n.ag-body .ag-pinned-right-cols-viewport {\n -webkit-overflow-scrolling: touch;\n}\n",""]);const i=r},44142:(e,t,n)=>{n.d(t,{IB:()=>c,Ul:()=>u,V_:()=>p,ZQ:()=>s,fF:()=>d,oW:()=>m});var a=n(96652),r=n.n(a),i=n(62183);const o=()=>{};function s(e="NOOP-LOGGER"){return{log:{component:e,get unbound(){return this},write:()=>!0,info:o,warn:o,error:o,fatal:o,debug:o},debug:o,mongoLogId:m}}const l=r().createContext({createLogger:s}),c=l.Provider;function d(e){return(0,i.mb)(u.bind(null,e),"createLoggerLocator")}function u(e){const t=r().useContext(l);if(!t)throw new Error("Logger service is missing from React context");const n=(0,a.useRef)();return n.current||(n.current=t.createLogger(e)),n.current}function p(e,t){return n=>{const a=u(t);return r().createElement(e,{...n,logger:a})}}function m(e){return{__value:e}}},44457:(e,t,n)=>{n.d(t,{A$:()=>u,Hr:()=>f,KK:()=>h,Q3:()=>d,bV:()=>p,hV:()=>s.h,p8:()=>g,r$:()=>c});var a=n(60783),r=n(62183),i=(n(91399),n(96652)),o=n.n(i),s=n(34426),l=n(17855);s._;const c=(0,i.createContext)(null),d=(c.Provider,(0,r.mb)((function(){const e=(0,i.useContext)(c);if(!e)throw new Error("No MongoDBInstancesManager available in this context, provider was not setup correctly");return e}),"mongoDBInstancesManagerLocator")),u=(0,r.mb)((function(){const e=(0,a.qm)();return d().getMongoDBInstanceForConnection(e.id)}),"mongoDBInstanceLocator");function p(){const e=(0,i.useContext)(c),t=(0,i.useCallback)((function(){return!!e&&Array.from(e.listMongoDBInstances().values()).some((e=>!e.genuineMongoDB.isGenuine))}),[e]),[n,a]=(0,i.useState)(t);return(0,i.useEffect)((()=>{if(e){const n=()=>{a(t)};return e.on("instance-started",n),e.on("instance-removed",n),()=>{e.off("instance-started",n),e.off("instance-removed",n)}}}),[e,a,t]),n}const m=o().createContext(null),g=(0,r.mb)((function(){const e=(0,i.useContext)(m);if(!e||"Database"!==e.modelType)throw new Error(`Tried to locate Database model, but got ${e?"Collection model":"undefined"} instead. Are you trying to use databaseModelLocator outside of database namespace scope?`);return e}),"databaseModelLocator"),h=(0,r.mb)((function(){const e=(0,i.useContext)(m);if(!e||"Collection"!==e.modelType)throw new Error(`Tried to locate Collection model, but got ${e?"Database model":"undefined"} instead. Are you trying to use collectionModelLocator outside of collection namespace scope?`);return e}),"collectionModelLocator"),f=(0,r.xw)((function({children:e,namespace:t,onNamespaceFallbackSelect:n}){const r=(0,i.useRef)(n);r.current=n;const s=(0,a.S1)(),c=u(),d=(0,i.useMemo)((()=>(0,l.Ay)(t)),[t]),[p,g]=(0,i.useState)((()=>(d.collection?c.databases.get(d.database)?.collections.get(d.ns):c.databases.get(d.database))??null));return(0,i.useEffect)((()=>{let e=!1;return(async()=>{if(p&&p._id===d.ns)return;g(null),await c.fetchDatabases({dataService:s}).catch((()=>{}));const t=c.databases.get(d.database);if(!t)return void r.current?.(null);if(!d.collection)return void(e||g(t));await t.fetchCollections({dataService:s}).catch((()=>{}));const n=t.collections.get(d.ns);n?e||g(n):r.current?.(t._id)})(),()=>{e=!0}}),[s,c,p,d.collection,d.database,d.ns]),p?o().createElement(m.Provider,{value:p},e):null}))},44969:(e,t,n)=>{n.d(t,{c7:()=>He,vS:()=>tt,U1:()=>pt,Ng:()=>Ge,GK:()=>Ke,Kw:()=>J,Pj:()=>Qe,Zf:()=>at,WH:()=>et,FS:()=>Xe,HP:()=>we,zz:()=>dt,K7:()=>Le,gH:()=>ut,n7:()=>Oe,GQ:()=>st,zN:()=>rt,F:()=>Ve,RW:()=>Je,hL:()=>lt,J:()=>it}),n(95039),n(59509),n(25691),n(23177),n(3142),n(51615),n(84217),n(25953),n(42319),n(28465),n(12887),n(36106),n(84542),n(57068),n(69517),n(21261),n(92879),n(31977),n(49743),n(9656),n(72673),n(35467),n(94476),n(64971),n(24330),n(83478),n(65166),n(1256),n(61038),n(73035),n(23855);var a=n(82162),r=n(67219),i=n(96452),o=n(33364),s=n(13353),l=n(90605),c=n(20625),d=n(96652),u=n.n(d),p=n(51295),m=n(46729);const g=(0,p.AHW)({gap:0,'[data-testid="lg-toast-content"] > div, [data-testid="lg-toast-content"] > div > p + p':{overflow:"visible"}}),h=(0,p.AHW)({display:"grid",gridAutoFlow:"column",gap:p.YKD[200]}),f=(0,p.AHW)({display:"flex",flexDirection:"column",textAlign:"right",marginRight:p.YKD[100],gap:p.YKD[100],justifyContent:"center"}),y=(0,p.AHW)({display:"flex",flexDirection:"column",wordBreak:"break-word"}),b=(0,p.AHW)({fontWeight:"bold"}),v=(0,p.AHW)({display:"flex",alignItems:"center",gap:p.YKD[100],justifyContent:"left",textWrap:"nowrap"});function x({info:e,error:t,onReview:n,onDebug:a}){return u().createElement("span",{className:h},u().createElement("span",{className:y},u().createElement("span",{"data-testid":"connection-error-title",className:b},e?(0,i.T8)(e):"Connection failed"),u().createElement("span",{"data-testid":"connection-error-text"},t.message)),u().createElement("span",{className:f},e&&n&&u().createElement("span",null,u().createElement(p.$nd,{onClick:n,"data-testid":"connection-error-review",size:"small"},"Review")),e&&a&&u().createElement("span",{className:v},u().createElement(p.Int,{glyph:"Sparkle",size:"small"}),u().createElement(p.N_E,{hideExternalIcon:!0,onClick:a,"data-testid":"connection-error-debug"},"Debug"))))}const E=(0,p.AHW)({textAlign:"center","& > *:not(:last-child)":{paddingBottom:p.YKD[150]}}),C=(e,t)=>{const{title:n,description:a}=function(e){var t;return{title:`Connecting to ${(0,i.T8)(e)}`,description:(t=e.connectionOptions.connectionString,"MONGODB-OIDC"===(new m.Ay(t).searchParams.get("authMechanism")||"").toUpperCase()?"Go to the browser to complete authentication":"")}}(e);(0,p.c3r)(`connection-status--${e.id}`,{title:n,description:a,dismissible:!0,variant:"progress",actionElement:u().createElement(p.N_E,{hideExternalIcon:!0,onClick:()=>{(0,p.cQH)(`connection-status--${e.id}`),t()},"data-testid":"cancel-connection-button"},"CANCEL")})},w=e=>{(0,p.c3r)(`connection-status--${e.id}`,{title:`Connected to ${(0,i.T8)(e)}`,variant:"success",timeout:3e3})},I=({connectionInfo:e,error:t,onReviewClick:n,onDebugClick:a})=>{const r=e?.id??"failed";(0,p.c3r)(`connection-status--${r}`,{title:"",description:u().createElement(x,{info:e,error:t,onReview:n?()=>{(0,p.cQH)(`connection-status--${r}`),n()}:void 0,onDebug:a?()=>{(0,p.cQH)(`connection-status--${r}`),a()}:void 0}),variant:"warning",className:g})},S=e=>{const t=`Only ${e} connection${e>1?"s":""} can be connected to at the same time. First disconnect from another connection.`;(0,p.c3r)("max-connections-reached",{title:"Maximum concurrent connections limit reached",description:t,variant:"warning",timeout:5e3})},A=(e,t,n,a,r)=>{(0,p.$TK)({title:"Complete authentication in the browser",description:u().createElement("div",{className:E},u().createElement(p.nBu,null,"Visit the following URL to complete authentication for"," ",u().createElement("b",null,(0,i.T8)(e)),":"),u().createElement(p.nBu,null,u().createElement(p.N_E,{href:t,target:"_blank"},t)),u().createElement("br",null),u().createElement(p.nBu,null,"Enter the following code on that page:"),u().createElement(p.nBu,{as:"div"},u().createElement(p.CyN,{language:"none"},n))),hideConfirmButton:!0,signal:r}).then((e=>{!1===e&&a?.()}),(()=>{}))};function k(){return{openNotifyDeviceAuthModal:A,openConnectionStartedToast:C,openConnectionSucceededToast:w,openConnectionFailedToast:I,openMaximumConnectionsReachedToast:S,closeConnectionStatusToast:e=>(0,p.cQH)(`connection-status--${e}`)}}var D=n(34615),N=n(29603),M=n(4580),T=n.n(M);const P=(0,p.AHW)({marginTop:p.YKD[400],marginBottom:p.YKD[200]}),L=(0,p.AHW)({marginTop:p.YKD[400],marginBottom:p.YKD[200]});var O=n(60254),R=n(77008),H=n.n(R),F=n(52416),W=n.n(F),j=n(26544),B=n(15088).process;const{mongoLogId:z,log:_,debug:$}=(0,j.h)("END-OF-LIFE-SERVER"),Y="6.x",{HADRON_AUTO_UPDATE_ENDPOINT:K=B.env.HADRON_AUTO_UPDATE_ENDPOINT_OVERRIDE}=B.env;let G=null;async function V(e=!0){return e?K?(G||(_.debug(z(1001000353),"getLatestEndOfLifeServerVersion","Fetching EOL server version"),G=fetch(`${K}/api/v2/eol-server`).then((async e=>{if(e.ok){const t=await e.text();return _.debug(z(1001000354),"getLatestEndOfLifeServerVersion","Got EOL server version response",{result:t}),t}throw G=null,new Error(`Expected an OK response, got ${e.status} '${e.statusText}'`)})).catch((e=>(_.error(z(1001000355),"getLatestEndOfLifeServerVersion","Failed to fetch EOL server version",{error:e}),Y)))),G):(_.debug(z(1001000356),"getLatestEndOfLifeServerVersion","HADRON_AUTO_UPDATE_ENDPOINT is not set"),Y):Y}function U(e,t=Y){try{const n=W()(e);return!!n&&H()(n,`<=${t}`)}catch(e){return $("Error comparing versions",{error:e}),!1}}function q(e){const t=[];let n=e;for(;n&&"object"==typeof n;)"code"in n&&n.code?t.push(n.code):"codeName"in n&&n.codeName&&t.push(n.codeName),n=n.cause;if(0!==t.length)return t}const Z=new(T()),J={emit:(e,...t)=>{try{return Z.emit(e,...t)}catch{return!1}},on:(e,t)=>(Z.on(e,t),J),off:(e,t)=>(Z.on(e,t),J),removeListener:(e,t)=>(Z.on(e,t),J),once:(e,t)=>(Z.on(e,t),J)},Q="ConnectionsLoadStart",X="ConnectionsLoadSuccess",ee="ConnectionsLoadError",te="ConnectionsRefreshStart",ne="ConnectionsRefreshSuccess",ae="ConnectionsRefreshError",re="ConnectionsImportFinish",ie="ConnectionAutoconnectCheck",oe="ConnectionAttemptStart",se="ConnectionAttemptSuccess",le="ConnectionAttemptError",ce="Disconnect",de="CreateNewConnection",ue="DuplicateConnection",pe="EditConnection",me="ToggleFavoriteConnection",ge="CancelEditConnection",he="SaveEditedConnection",fe="SaveConnectionInfo",ye="RemoveConnection",be="RemoveAllRecentConnections";function ve(e,t){return e.type===t}const xe=new Map,Ee=new Map,Ce=new Map;function we(e){const t=Ce.get(e);if(!t)throw new Error(`Failed to locate DataService instance for connection ${e}`);return t}const Ie=new Map;function Se(e=function(){return{id:(new s.UUID).toString(),connectionOptions:{connectionString:"mongodb://localhost:27017"}}}()){return{info:e,status:"initial",error:null}}const Ae={connections:{ids:[],byId:{},status:"initial",error:null},editingConnectionInfoId:null,isEditingConnectionInfoModalOpen:!1};function ke(e){if(!e)return{byId:{},ids:[],status:"initial",error:null};const t=Object.fromEntries(e.map((e=>[e.id,Se(e)])));return{byId:t,ids:De(Object.values(t)),status:"ready",error:null}}function De(e){return e.slice().sort(((e,t)=>{const n=(0,i.T8)(e.info).toLocaleLowerCase(),a=(0,i.T8)(t.info).toLocaleLowerCase();return function(e,t){const n="favorite"===e.savedConnectionType,a="favorite"===t.savedConnectionType;return n===a?0:n&&!a?-1:1}(e.info,t.info)||n.localeCompare(a)||e.info.id.localeCompare(t.info.id)})).map((e=>e.info.id))}function Ne(e,t){t=Array.isArray(t)?t:[t];const n=new Set(e.ids);let a=e.byId;for(const e of t){n.delete(e.id);const t=a[e.id];t||(a={...a,[e.id]:Se(e)}),t&&!(0,l.isEqual)(t.info,e)&&(a={...a,[e.id]:{...t,info:e}})}for(const e of n){const t=a[e];t.info.atlasMetadata&&(a={...a,[e]:{...t,info:{...t.info,atlasMetadata:{...t.info.atlasMetadata,clusterState:"DELETED"}}}})}if(a===e.byId)return e;const r=De(Object.values(a));return{...e,byId:a,ids:(0,l.isEqual)(e.ids,r)?e.ids:r}}function Me(e,t,n,{shallowMerge:a=!1}={}){const r=e.byId[t],i=(a?l.assign:l.merge)(r?(0,l.cloneDeep)(r):Se(),n);if(r&&(0,l.isEqual)(r,i))return e;const o={...e.byId,[i.info.id]:i},s=De(Object.values(o));return{...e,byId:o,ids:(0,l.isEqual)(s,e.ids)?e.ids:s}}function Te(e,t){return!!e.connections.byId[t]}const Pe=(e=Ae,t)=>{if(ve(t,Q))return{...e,connections:{...e.connections,status:"loading"}};if(ve(t,X))return{...e,connections:{...Ne(e.connections,t.connections),status:"ready",error:null}};if(ve(t,ee))return{...e,connections:{...e.connections,status:"loading-error",error:t.error}};if(ve(t,te))return{...e,connections:{...e.connections,status:"refreshing"}};if(ve(t,ne))return{...e,connections:{...Ne(e.connections,t.connections),status:"ready",error:null}};if(ve(t,ae))return{...e,connections:{...e.connections,status:"refreshing-error",error:t.error}};if(ve(t,re))return{...e,connections:Ne(e.connections,t.connections)};if(ve(t,ie)){if(!t.connectionInfo)return e;const n=Se(t.connectionInfo);return{...e,connections:Me(e.connections,n.info.id,{...n,isAutoconnectInfo:!0})}}if(ve(t,oe))return{...e,connections:Me(e.connections,t.connectionInfo.id,{...We(e,t.connectionInfo.id)||t.options.forceSave?{info:t.connectionInfo}:{info:{favorite:t.connectionInfo.favorite,savedConnectionType:t.connectionInfo.savedConnectionType}},status:"connecting",error:null},{shallowMerge:t.options.forceSave}),isEditingConnectionInfoModalOpen:e.editingConnectionInfoId!==t.connectionInfo.id&&e.isEditingConnectionInfoModalOpen};if(ve(t,se))return{...e,connections:Me(e.connections,t.connectionId,{isBeingCreated:!1,status:"connected",error:null})};if(ve(t,le)){let n=t.connectionId?e.connections.byId[t.connectionId]:null;return n||(n=Se(),n.isAutoconnectInfo=!0),{...e,connections:Me(e.connections,n.info.id,{...n,isBeingCreated:!1,status:"failed",error:t.error}),editingConnectionInfoId:n.info.id}}if(ve(t,ce))return{...e,connections:Me(e.connections,t.connectionId,{status:"disconnected"})};if(ve(t,de)){const t=Se();return t.isBeingCreated=!0,{...e,connections:Me(e.connections,t.info.id,t),editingConnectionInfoId:t.info.id,isEditingConnectionInfoModalOpen:!0}}if(ve(t,ue))return{...e,connections:Me(e.connections,t.duplicateInfo.id,{info:t.duplicateInfo,isBeingCreated:!t.isAutoDuplicate}),editingConnectionInfoId:t.duplicateInfo.id,...!t.isAutoDuplicate&&{isEditingConnectionInfoModalOpen:!0}};if(ve(t,pe))return Te(e,t.connectionId)?{...e,editingConnectionInfoId:t.connectionId,isEditingConnectionInfoModalOpen:!0}:e;if(ve(t,me))return{...e,connections:Me(e.connections,t.connectionId,{info:{savedConnectionType:"favorite"===e.connections.byId[t.connectionId].info.savedConnectionType?"recent":"favorite"}})};if(ve(t,ge)){if(!Te(e,t.connectionId))return e;let n=e.connections;const a=e.editingConnectionInfoId;if(e.connections.byId[t.connectionId].isBeingCreated){const a={...e.connections.byId};delete a[t.connectionId];const r=n.ids.filter((e=>e!==t.connectionId));n={...n,byId:a,ids:r}}return{...e,connections:n,editingConnectionInfoId:a,...e.editingConnectionInfoId===t.connectionId&&{isEditingConnectionInfoModalOpen:!1}}}if(ve(t,he))return Te(e,t.connectionId)?{...e,...e.editingConnectionInfoId===t.connectionId&&{isEditingConnectionInfoModalOpen:!1}}:e;if(ve(t,fe))return Te(e,t.connectionInfo.id)?{...e,connections:Me(e.connections,t.connectionInfo.id,{info:t.connectionInfo,isBeingCreated:!1},{shallowMerge:!0})}:e;if(ve(t,ye)){if(!Te(e,t.connectionId))return e;let n={...e.connections,byId:{...e.connections.byId}};delete n.byId[t.connectionId];const a=e.editingConnectionInfoId===t.connectionId,r=a?Se():void 0;return r?(r.isBeingCreated=!0,n=Me(n,r.info.id,r)):n.ids=n.ids.filter((e=>e!==t.connectionId)),{...e,connections:n,...a&&{editingConnectionInfoId:r?.info.id??e.editingConnectionInfoId,isEditingConnectionInfoModalOpen:!1}}}if(ve(t,be)){const t=Object.values(e.connections.byId).filter((e=>ot(e))).map((e=>e.info.id));if(0===t.length)return e;let n={...e.connections,byId:{...e.connections.byId}};for(const e of t)delete n.byId[e];const a=!!e.editingConnectionInfoId&&t.some((t=>t===e.editingConnectionInfoId)),r=a?Se():void 0;return r?(r.isBeingCreated=!0,n=Me(n,r.info.id,r)):n.ids=n.ids.filter((e=>!t.includes(e))),{...e,connections:n,...a&&{editingConnectionInfoId:r?.info.id??e.editingConnectionInfoId,isEditingConnectionInfoModalOpen:!1}}}return e},Le=()=>async(e,t,{connectionStorage:n})=>{if("initial"===t().connections.status){e({type:Q});try{const t=await n.loadAll();e({type:X,connections:t})}catch(t){(0,p.c3r)("failed-to-load-connections",{title:"Failed to load connections",description:t.message,variant:"warning"}),e({type:ee,error:t})}}},Oe=()=>async(e,t,{connectionStorage:n})=>{if("ready"===t().connections.status||"loading-error"===t().connections.status||"refreshing-error"===t().connections.status){e({type:te});try{const t=await n.loadAll();e({type:ne,connections:t})}catch(t){e({type:ae,error:t})}}},Re=(e,t)=>(n,a,{track:r,getExtraConnectionData:i,compassAssistant:o})=>{const{openConnectionFailedToast:s}=k(),l=!!e&&!e.atlasMetadata;s({connectionInfo:e,error:t,onReviewClick:l?()=>{e&&n(Xe(e.id))}:void 0,onDebugClick:o.getIsAssistantEnabled()&&e?()=>{o.interpretConnectionError({connectionInfo:e,error:t})}:void 0}),r("Connection Failed",(async()=>{const n={error_code:t.code,error_code_cause_chain:q(t),error_name:t.codeName??t.name};if(e){const[t]=await i(e);Object.assign(n,t)}return n}),e??void 0),n({type:le,connectionId:e?.id??null,error:t})},He=(e,t=!1)=>async(n,a,{logger:{log:r,mongoLogId:i},connectionStorage:o})=>{try{r.info(i(1001000160),"Connection Store","Performing automatic connection attempt");const a=await e(o);if(t&&"disconnected"===function(e="-1"){try{return window.sessionStorage.getItem(`CONNECTION_STATUS:${e}`)}catch{return null}}(a?.id))return;n({type:ie,connectionInfo:a}),a&&n(Ge(a))}catch(e){n(Re(null,e))}};function Fe(e,t){return e.connections.byId[t]&&!!e.connections.byId[t].isAutoconnectInfo}function We(e,t){return!e.connections.byId[t]||!!e.connections.byId[t].isBeingCreated}function je(e,t){return e.connections.byId[t]?.info}function Be(e,t){return e.connections.byId[t]?.status}function ze(e){return Object.values(e.byId).filter((e=>["connected","connecting"].includes(e.status))).length}const _e=[3e3,3003,4004,1008],$e={3e3:"Unauthorized",3003:"Forbidden",4004:"Not Found",1008:"Violated policy"};function Ye(e){const t=e.message.match(/code: \d+, reason: (.*)$/)?.[1];return t&&t.length>0?t.endsWith(".")?t.slice(0,-1):t:$e[Number(e.message.match(/code: (\d+),/)?.[1])]??"Unknown"}const Ke=e=>(t,n,{globalAppRegistry:a})=>{a.emit("connect-in-new-window",e.id)},Ge=e=>Ue(e,{forceSave:!1}),Ve=e=>Ue(e,{forceSave:!0}),Ue=(e,t)=>async(n,a,{preferences:r,logger:{log:s,debug:d,mongoLogId:u},track:m,appName:g,getExtraConnectionData:h,connectFn:f})=>{let y=xe.get(e.id);return y||(y=(async()=>{const y=new AbortController;try{if("connected"===Be(a(),e.id))return;if(!(0,O.x)(e))return;const b=Fe(a(),e.id);e=(0,l.cloneDeep)(e);const{forceConnectionOptions:v,browserCommandForOIDCAuth:x,maximumNumberOfActiveConnections:E,telemetryAnonymousId:C}=r.getPreferences(),w=k();if(void 0!==E&&ze(a().connections)>=E)return void w.openMaximumConnectionsReachedToast(E);n({type:oe,connectionInfo:e,options:{forceSave:t.forceSave}}),m("Connection Attempt",{is_favorite:"favorite"===e.savedConnectionType,is_new:We(a(),e.id)},e),d("connecting with connectionInfo",e),s.info(u(1001000004),"Connection UI","Initiating connection attempt",{isAutoconnectAttempt:b}),qe(e.connectionOptions.connectionString),w.openConnectionStartedToast(e,(()=>{n(at(e.id))}));const{connectionOptions:I,...S}=e,A=(0,l.merge)((0,l.cloneDeep)(S),{connectionOptions:(0,D.hl)({connectionOptions:(0,l.merge)((0,l.cloneDeep)(I),Ie.get(e.id)??{}),connectionId:e.id,defaultAppName:g,preferences:{forceConnectionOptions:v??[],browserCommandForOIDCAuth:x,telemetryAnonymousId:C},notifyDeviceFlow:t=>{w.openNotifyDeviceAuthModal(e,t.verificationUrl,t.userCode,(()=>{n(at(e.id))}),y.signal)}})});if(function(e){try{return(0,N.qY)(e.connectionOptions.connectionString)}catch{return!1}}(A))throw new Error("Atlas Stream Processing is not yet supported on MongoDB Compass. To work with your Stream Processing Instance, connect with mongosh or MongoDB for VS Code.");s.info(u(1001000005),"Compass Connection Attempt Started","Connection attempt started",{clusterName:e.atlasMetadata?.clusterName,connectionId:e.id});const M=(0,o.mZ)({logger:s.unbound,proxyOptions:(0,c.nV)(r.getPreferences().proxy),connectFn:f});Ee.set(e.id,M);const T=await M.connect(A.connectionOptions);if(!T||M.isClosed())return s.info(u(1001000007),"Compass Connection Attempt Cancelled","Connection attempt cancelled",{clusterName:e.atlasMetadata?.clusterName,connectionId:e.id}),void n({type:"ConnectionAttemptCancelled",connectionId:e.id});const P=await T.instance();let L=!1;T.on("serverHeartbeatFailed",(t=>{(function(e){return _e.some((t=>e.failure.message.includes(`code: ${t},`)))})(t)&&T.isConnected()&&!L&&(((e,t)=>{(0,p.c3r)(`non-retryable-error-encountered--${e.id}`,{title:`Unable to connect to ${(0,i.T8)(e)}`,description:`Reason: ${Ye(t)}. To continue to use this connection either disconnect and reconnect, or refresh your page.`,variant:"warning"})})(e,t.failure),L=!0,T.disconnect())})),T.on("oidcAuthFailed",(t=>{(0,p.c3r)("oidc-auth-failed",{title:`Failed to authenticate for ${(0,i.T8)(e)}`,description:t,variant:"important"})})),T.on("connectionInfoSecretsChanged",(()=>{T.getUpdatedSecrets().then((t=>{if(Ie.set(e.id,t),!r.getPreferences().persistOIDCTokens)return;const i=je(a(),e.id);i&&n(Ze((0,l.merge)((0,l.cloneDeep)(i),{connectionOptions:t})))}),(()=>{}))})),T.addReauthenticationHandler((()=>async function(e){if(!await(0,p.$TK)({title:`Authentication expired for ${(0,i.T8)(e)}`,description:"You need to re-authenticate to the database in order to continue."}))throw new Error("Reauthentication declined by user")}(e))),Ce.set(e.id,T);try{await n(Ze((0,l.merge)((0,l.cloneDeep)(je(a(),e.id)),{lastUsed:new Date,...r.getPreferences().persistOIDCTokens?{connectionOptions:await T.getUpdatedSecrets()}:{}})))}catch(e){d("failed to update connection info after successful connect",e)}m("New Connection",(async()=>{const{dataLake:t,genuineMongoDB:n,host:r,build:i,isAtlas:o,isLocalAtlas:s}=P,[l,c]=await h(e),d=a().connections,u=Object.values(d.byId).filter((({isBeingCreated:e})=>!e)).length,p=ze(d),m=u-p;return{is_atlas:o,atlas_hostname:o?c:null,is_local_atlas:s,is_dataLake:t.isDataLake,is_enterprise:i.isEnterprise,is_genuine:n.isGenuine,non_genuine_server_name:n.serverName,server_version:i.version,server_arch:r.arch,server_os_family:r.os_family,topology_type:T.getCurrentTopologyType(),num_active_connections:p,num_inactive_connections:m,user_language:globalThis.navigator?.language??"unknown",user_languages:[...globalThis.navigator?.languages??[]],...l}}),e),d("connection attempt succeeded with connection info",e),s.info(u(1001000006),"Compass Connection Attempt Succeeded","Connection attempt succeeded",{clusterName:e.atlasMetadata?.clusterName,connectionId:e.id}),w.openConnectionSucceededToast(e),J.emit("connected",e.id,e,P),n({type:se,connectionId:e.id}),P.genuineMongoDB.isGenuine?await async function(e,t,n){try{const n=await V(t.getPreferences().networkTraffic);return t.getPreferences().showEndOfLifeConnectionModal&&U(e,n)}catch(e){return n("failed to get instance details to determine if the server version is end-of-life",e),!1}}(P.build.version,r,d)&&n(ct(e.id,P.build.version)):n(lt(e.id))}catch(t){s.info(u(1001000008),"Compass Connection Attempt Failed","Connection attempt failed",{clusterName:e.atlasMetadata?.clusterName,connectionId:e.id,error:t.message}),n(Re(e,t))}finally{y.abort(),Ee.delete(e.id),xe.delete(e.id)}})(),xe.set(e.id,y),y)};function qe(e){new m.Ay(e)}const Ze=e=>async(t,n,{connectionStorage:a,track:r,logger:{debug:i}})=>{if(Fe(n(),e.id))return null;try{qe(e.connectionOptions.connectionString);const i=await(a.save?.({connectionInfo:e}))??e;return We(n(),e.id)&&r("Connection Created",{color:i.favorite?.color},i),t({type:fe,connectionInfo:i}),i}catch(t){return i(`error saving connection with id ${e.id}`,t),(0,p.c3r)(`save-connection-error-${e.id}`,{title:"An error occurred while saving the connection",description:t.message,variant:"warning"}),null}},Je=e=>async t=>{await t(Ze(e)),t({type:he,connectionId:e.id})},Qe=()=>(e,t)=>{t().isEditingConnectionInfoModalOpen||e({type:de})},Xe=e=>(t,n)=>{n().isEditingConnectionInfoModalOpen||t({type:pe,connectionId:e})},et=(e,{autoDuplicate:t}={autoDuplicate:!1})=>(n,a)=>{if(a().isEditingConnectionInfoModalOpen)return;const r=je(a(),e);if(!r)return;const o=function(e,t){function n(e){const{groups:t={}}=e.match(/^(?<name>.+?)(\s\((?<count>\d+)\))?$/)??{};return[t.name??e,t.count?Number(t.count):0]}const a={...(0,l.cloneDeep)(e),id:(new s.UUID).toString()};a.favorite&&a.favorite.name||(a.favorite={...a.favorite,name:(0,i.T8)(a)});const[r,o]=n(a.favorite.name),c=t.reduce(((e,t)=>{if(t.favorite?.name){const[a,i]=n(t.favorite.name);return a===r&&i>=e?i+1:e}return e}),o+1);return a.favorite.name=`${r} (${c})`,delete a.lastUsed,a}(r,Object.values(a().connections.byId).map((e=>e.info)));n({type:ue,duplicateInfo:o,isAutoDuplicate:t}),t&&n(Ze(o))},tt=e=>({type:ge,connectionId:e}),nt=e=>(t,n,{logger:{log:a,debug:r,mongoLogId:i},track:o})=>{a.info(i(1001000313),"Connection UI","Initiating disconnect attempt");const s=Be(n(),e);"connected"!==s&&"connecting"!==s||o("Connection Disconnected",{},je(n(),e));const{closeConnectionStatusToast:l}=k(),c=je(n(),e);l(e);const d=Ee.get(e),u=Ce.get(e);d?.cancelConnectionAttempt(),u?.disconnect().then((()=>{r("connection closed",e)}),(e=>{a.error(i(1001000314),"Connection UI","Disconnect attempt failed",{error:e.message})})),Ee.delete(e),Ce.delete(e),J.emit("disconnected",e,c)},at=e=>(t,n,{logger:{debug:a}})=>{a("closing connection with connectionId",e),n().connections.byId[e]?.isAutoconnectInfo&&function(e){try{return window.sessionStorage.setItem(`CONNECTION_STATUS:${e}`,"disconnected")}catch{return!1}}(e),t(nt(e)),t({type:ce,connectionId:e})},rt=e=>(t,n,{connectionStorage:a,track:r,logger:{debug:i}})=>{const o=je(n(),e);o&&(t(nt(o.id)),a.delete?.({id:e}).catch((e=>{i("failed to delete connection",e)})),t({type:ye,connectionId:e}),r("Connection Removed",{},o))},it=e=>(t,n)=>{if(Fe(n(),e))return;if(!Te(n(),e))return;t({type:me,connectionId:e});const a=je(n(),e);if(!a)throw new Error("No connection info to save");t(Ze(a))};function ot(e){return!e.info.savedConnectionType||"recent"===e.info.savedConnectionType}const st=()=>(e,t,{connectionStorage:n,track:a})=>{const r=Object.values(t().connections.byId).filter((e=>ot(e)));Promise.allSettled(r.map((t=>(e(nt(t.info.id)),a("Connection Removed",{},t.info),n.delete?.({id:t.info.id})??Promise.resolve())))),e({type:be})},lt=e=>(t,n,{track:a})=>{const r=je(n(),e);a("Screen",{name:"non_genuine_mongodb_modal"},r),function(e){(0,p.$TK)({title:"Non-Genuine MongoDB Detected",hideCancelButton:!0,description:u().createElement(u().Fragment,null,u().createElement(p.lZ$,{variant:p.uAY.Warning},e?`Server or service "${(0,i.T8)(e)}"`:"This server or service"," ","appears to be an emulation of MongoDB rather than an official MongoDB product."),u().createElement(p.nBu,{className:P},"Some documented MongoDB features may work differently, be entirely missing or incomplete, or have unexpected performance characteristics."," "),u().createElement(p.N_E,{href:"https://www.mongodb.com/docs/compass/master/faq/#why-am-i-seeing-a-warning-about-a-non-genuine-mongodb-server-",target:"_blank","data-testid":"non-genuine-warning-modal-learn-more-link"},"Learn more"))})}(r)},ct=(e,t)=>(n,a,{track:r,preferences:o})=>{const s=new AbortController,l=o.onPreferenceValueChanged("showEndOfLifeConnectionModal",(e=>{e||(s.abort(),l())})),c=je(a(),e);r("Screen",{name:"end_of_life_mongodb_modal"},c),function(e,t,n){(0,p.$TK)({title:"End-of-life MongoDB Detected",hideCancelButton:!0,description:u().createElement(u().Fragment,null,u().createElement(p.lZ$,{variant:p.uAY.Warning},e?`Server or service "${(0,i.T8)(e)}"`:"This server or service"," ","appears to be running a version of MongoDB that is no longer supported."),u().createElement(p.nBu,{className:L},"Server version",t?` (${t})`:""," is considered end-of-life, consider upgrading to get the latest features and performance improvements."," "),u().createElement(p.N_E,{href:"https://www.mongodb.com/legal/support-policy/lifecycles",target:"_blank","data-testid":"end-of-life-warning-modal-learn-more-link"},"Learn more from the MongoDB Lifecycle Schedules.")),signal:n})}(c,t,s.signal)},dt=e=>async(t,n,{connectionStorage:a})=>{t({type:"ConnectionsImportStart"});let r,i=[];try{a.importConnections&&(await a.importConnections(e),i=await a.loadAll())}catch(e){r=e}if(t({type:re,connections:i}),r)throw r},ut=e=>(t,n,{globalAppRegistry:a})=>{a.emit("open-compass-settings",e)};function pt(e,t){return(0,a.y$)(Pe,{...Ae,connections:ke(e)},(0,a.Tw)(r.A.withExtraArgument(t)))}},47799:(e,t,n)=>{n.d(t,{Fg:()=>p,JG:()=>d,fx:()=>u,gc:()=>m,tC:()=>g,wb:()=>c});var a=n(96652),r=n(55469),i=n(62183),o=n(90605);const s=(0,a.createContext)(null);let l;const c=s.Provider;function d(){return(0,a.useContext)(s)??(l??=new r.U)}const u=(0,i.mb)(d,"preferencesLocator");function p(e){const t=d(),[n,r]=(0,a.useState)(t.getPreferences()[e]);return(0,a.useEffect)((()=>t.onPreferenceValueChanged(e,(e=>{r(e)}))),[e,t]),n}function m(e){const t=d(),n=(0,a.useRef)(e);n.current=e;const[r,i]=(0,a.useState)((()=>(0,o.pick)(t.getPreferences(),e))),s=(0,a.useCallback)(((e,t)=>{i((n=>t===n[e]?n:{...n,[e]:t}))}),[]);return(0,a.useEffect)((()=>{const e=n.current.map((e=>t.onPreferenceValueChanged(e,(t=>{s(e,t)}))));return()=>{e.forEach((e=>{e()}))}}),[n.current.join(""),t]),r}function g(e,t){return function(n){const r=Object.fromEntries(t.map((e=>[e,p(e)])));return(0,a.createElement)(e,{...r,...n})}}},51295:(e,t,n)=>{n.d(t,{nD3:()=>Ot,XYu:()=>f.XY,sPs:()=>is,Exy:()=>c.Ex,xUU:()=>c.KT,lZ$:()=>d.lZ,uAY:()=>d.KT,nBu:()=>H.nB,BIu:()=>cd,$nd:()=>J,MpK:()=>_.or,AkO:()=>_.KT,yao:()=>yt,ZpM:()=>p.Zp,fhW:()=>D.fh,Sc0:()=>u.Sc,pzy:()=>dd,CyN:()=>m.Cy,V7r:()=>jt,G3_:()=>F.G3,jOs:()=>F.jO,WqN:()=>vc,Gf9:()=>ed,ETl:()=>Bl,WlR:()=>g.KT,awP:()=>l.aw,VYo:()=>H.VY,yFB:()=>Ld.yF,Fp_:()=>Ld.Fp,MWq:()=>H.MW,pyG:()=>Na,gD8:()=>a,fDz:()=>$c,TmU:()=>Kc,F1Z:()=>Da,HYq:()=>Ii,tHk:()=>Di,dFH:()=>at,bHD:()=>D.bH,buA:()=>Mi,h8q:()=>Le,SxS:()=>Pd,X1w:()=>wn,GEW:()=>Ht,k5W:()=>dr,H3:()=>H.H3,A3f:()=>D.A3,Syw:()=>D.Sy,d$:()=>gc,Int:()=>ie,K0:()=>Q,sAP:()=>yc,OHu:()=>Ya,K7:()=>bc,WhU:()=>pr,Ls4:()=>b.Ls,R0E:()=>H.R0,p8Z:()=>Ze,CAb:()=>Wi,WA6:()=>Cr,eDW:()=>da,ful:()=>la,pNw:()=>ra,yY_:()=>dc,$uG:()=>La._9,JU7:()=>H.JU,TMK:()=>m.TM,Yeg:()=>de.Ay,UZR:()=>X,dNu:()=>ee,hPr:()=>te,T1y:()=>ne,uWf:()=>ae,N_E:()=>q,qQS:()=>_i,_U_:()=>se,W1t:()=>y.W1,Drp:()=>y.Dr,aFV:()=>Va,cwr:()=>Xa,jlY:()=>x.wi,rQ0:()=>sr,FHx:()=>f.FH,m3F:()=>Ta,c$x:()=>k.c$,zQr:()=>k.zQ,bft:()=>Ve,bz9:()=>H.bz,Zkm:()=>m.Zk,qpO:()=>Cc,$Un:()=>C.$U,OrA:()=>Gi,x4h:()=>Pa,vA_:()=>bt,sxL:()=>S.sx,VCA:()=>I.VC,E99:()=>ot,z6M:()=>S.z6,q$V:()=>Un,fI1:()=>D.fI,DOo:()=>P.DO,IzF:()=>A.Iz,Zib:()=>A.Zi,l6P:()=>k.l6,Bq0:()=>Md,AJJ:()=>k.or,RR9:()=>Gt,gIH:()=>hi,Q0K:()=>ht,iyS:()=>ft,fkD:()=>Oa.fk,BIq:()=>C.BI,Pds:()=>H.Pd,ozo:()=>N.oz,keb:()=>Hi,mUA:()=>Ut,XIK:()=>D.XI,BFY:()=>D.BF,ndF:()=>D.nd,tUM:()=>N.tU,fs1:()=>M.fs,ksK:()=>T.ks,BDt:()=>ue,t8G:()=>$a,AF4:()=>Ac,lMk:()=>O.lM,m_M:()=>re,Q$5:()=>ro,wjn:()=>yd,s6o:()=>Ra.s,rpn:()=>rt,XvC:()=>Aa,N81:()=>vn,A6A:()=>$n,PVz:()=>Ld.PV,cQH:()=>Ba,pNb:()=>m.u5,V0R:()=>ud,$Mb:()=>pd,cXL:()=>h.cX,AHW:()=>r.AH,cx:()=>r.cx,q$X:()=>Vn,KvR:()=>D.Kv,Rg:()=>Fe,aIi:()=>ce.aI,Yq5:()=>vo,a3k:()=>Io,Mf6:()=>Mn,LP5:()=>Ld.LP,D0p:()=>D.D0,hMH:()=>D.hM,JoD:()=>Ld.Jo,R4u:()=>Ld.R4,i7C:()=>r.i7,aa2:()=>xn.a,v63:()=>$e,c3r:()=>ja,MFm:()=>le.M,Rbc:()=>Tr,B3q:()=>xn.B3,$TK:()=>Rl,a0R:()=>$l,q9R:()=>zl,YKD:()=>ce.YK,t4r:()=>Jn,No6:()=>xn.No,EJm:()=>V,MdH:()=>rn,HIF:()=>St,D27:()=>pe,pR2:()=>_t,rNO:()=>Ld.rN,u6F:()=>Gc,YUc:()=>Vc,qac:()=>Wr,ogd:()=>ze,$vP:()=>In,Ely:()=>An,Unm:()=>Ao,vCs:()=>Nn,v69:()=>kn,BiT:()=>_e.Bi,nfZ:()=>ge,iXE:()=>D.iX,bQl:()=>D.bQ,SVd:()=>L.SV,yRS:()=>xc,GUC:()=>U,yv$:()=>lo,Vdw:()=>co,wTI:()=>So,EqB:()=>gr,U6i:()=>me});var a={};n.r(a),n.d(a,{yo:()=>Ll,YO:()=>gs,eQ:()=>ec,ec:()=>No});var r=n(89863);r.yi.speedy(!0);var i=n(55712),o=n(96652),s=n.n(o),l=n(63353),c=n(8221),d=n(61804),u=n(26301),p=n(34988),m=n(55281),g=n(15137),h=n(5989),f=(n(36036),n(94183)),y=n(74871),b=n(8643),v=n(20395),x=n(91379),E=n(596),C=n(61041),w=n(42783),I=n(27519),S=n(19591),A=n(72016),k=n(78910),D=n(82900),N=n(62458),M=n(11685),T=n(52412),P=n(27596),L=n(21480),O=n(55498),R=n(79077),H=n(19743),F=n(43627);const W=(0,o.createContext)(null),j=({zIndex:e,children:t})=>{const n=(0,o.useMemo)((()=>({zIndex:e})),[e]);return s().createElement(W.Provider,{value:n},t)},B=()=>(0,o.useContext)(W),z=function(e){const t=(t,n)=>{const a=B(),r=(0,o.useMemo)((()=>a?.zIndex?{style:{zIndex:a.zIndex,...t.style}}:{}),[a,t]);return s().createElement(e,(0,i.A)({ref:n},t,r))},n=e.displayName||e.name||"Component";return t.displayName=`WithStackedStyles(${n})`,s().forwardRef(t)};var _=n(17425),$=n(17060),Y=n(21655).URL;const K=s().createContext({}),G=({utmSource:e,utmMedium:t,children:n})=>{const a={utmSource:e,utmMedium:t};return s().createElement(K.Provider,{value:a},n)},V=(e,{utmSource:t,utmMedium:n})=>{try{const a=new Y(e);return/^(.*\.)?mongodb\.com$/.test(a.hostname)&&(t&&!a.searchParams.has("utm_source")&&a.searchParams.set("utm_source",t),n&&!a.searchParams.has("utm_medium")&&a.searchParams.set("utm_medium",n)),a.toString()}catch{return e}};function U(){return(0,o.useContext)(K)}const q=({href:e,children:t,...n})=>{const{utmSource:a,utmMedium:r}=U(),l=(0,o.useMemo)((()=>{if(e)return V(e,{utmSource:a,utmMedium:r})}),[e,a,r]);return s().createElement(H.N_,(0,i.A)({href:l},n),t)};function Z(e){if("string"==typeof e.href)return e.href}const J=(0,o.forwardRef)((({children:e,...t},n)=>{const{utmSource:a,utmMedium:r}=U(),l=Z(t),c=(0,o.useMemo)((()=>{if(l)return V(l,{utmSource:a,utmMedium:r})}),[l,a,r]);return s().createElement(_.Ay,(0,i.A)({},t,{href:c,ref:n}),e)})),Q=(0,o.forwardRef)((({children:e,...t},n)=>{const{utmSource:a,utmMedium:r}=U(),l=Z(t),c=(0,o.useMemo)((()=>{if(l)return V(l,{utmSource:a,utmMedium:r})}),[l,a,r]);return s().createElement($.Ay,(0,i.A)({},t,{href:c,ref:n}),e)}));n(76057),n(59916);var X=n(55265),ee=n(78958),te=n(76422),ne=n(15563),ae=n(32412);y.Dr.defaultProps={...y.Dr.defaultProps,type:"button"};const re=z(R.m_),ie=({size:e,...t})=>(e="xsmall"===e?12:e,s().createElement(h.In,(0,i.A)({size:e},t)));ie.isGlyph=!0,delete E._U.propTypes,delete u.Sc.propTypes;const oe=z((function({children:e,...t}){return s().createElement(g.Rw,t,s().createElement(H.nB,{as:"div"},e))})),se=z((function({children:e,...t}){return s().createElement(E._U,t,s().createElement(H.nB,{as:"div"},e))}));n(95039);var le=n(87221),ce=n(62184),de=n(23616);const ue={Light:"Light",Dark:"Dark"};function pe(e){return(0,de.D2)(e).darkMode}const me=function(e){const t=(t,n)=>{const a=pe();return s().createElement(e,(0,i.A)({darkMode:a,ref:n},t))},n=e.displayName||e.name||"Component";return t.displayName=`WithDarkMode(${n})`,s().forwardRef(t)};function ge(e){const[t]=(0,o.useState)(e);return t}const{base:he}=le.M.red,fe=(0,r.AH)({marginTop:ce.YK[200],marginBottom:ce.YK[200],marginRight:"auto",marginLeft:"auto"}),ye=(0,r.AH)({display:"flex",alignItems:"center",gap:ce.YK[100]}),be=(0,r.AH)({display:"flex"}),ve=(0,r.AH)({display:"flex",flexDirection:"row",alignItems:"center"}),xe=(0,r.AH)({marginLeft:ce.YK[100]}),Ee=(0,r.AH)({border:"none",background:"none",fontWeight:"normal",marginLeft:ce.YK[200],"&:hover":{background:"none",boxShadow:"none"},"&:active":{background:"none",boxShadow:"none"}}),Ce=(0,r.AH)({width:"100% !important"}),we=(0,r.AH)({textOverflow:"ellipsis",overflow:"hidden",wordBreak:"normal",whiteSpace:"nowrap"}),Ie=(0,r.AH)({color:`${he} !important`}),Se=(0,r.AH)({width:"90%",paddingRight:ce.YK[400]}),Ae=(0,r.AH)({color:le.M.gray.base,marginTop:ce.YK[100],fontStyle:"italic",fontWeight:"normal",fontSize:12}),ke=(0,r.AH)({"&:link, &:active, &:hover":{textDecoration:"none"}}),De=(0,r.AH)({display:"inline-block",verticalAlign:"middle",fontSize:"inherit",textRendering:"auto",margin:"0 0 0 5px",cursor:"pointer",color:le.M.gray.light1,"&:link, &:active":{color:le.M.gray.light1},"&:link, &:active, &:hover":{textDecoration:"none"},"&:hover":{color:le.M.yellow.base}}),Ne=(0,r.AH)({color:le.M.gray.dark1}),Me=(0,r.AH)({color:le.M.gray.light1}),Te=(0,r.AH)({display:"none"}),Pe=(0,o.createContext)(null),Le=function({autoOpen:e=!1,id:t,label:n,dataTestId:a,onChange:i,disabled:l,optional:c=!1,optionalMessage:d,error:u=!1,errorMessage:p,variant:m="default",showFileOnNewLine:g=!1,link:h,description:f,values:y,className:b,multi:v=!1,mode:x="save",accept:E,title:C,defaultPath:w,filters:I,buttonLabel:S,properties:A}){const k=pe(),D=s().useRef(null),N=function(){const e=(0,o.useContext)(Pe);return ge((()=>e?e():null))}(),M=s().useMemo((()=>Array.isArray(y)&&y.length>0?y.map((e=>e.replace(/(\/|\\)$/,"").split(/(\/|\\)/).pop()??"")).join(", "):v?"Select files…":"Select a file…"),[y,v]),T=s().useCallback((e=>{const t=Array.from(e.currentTarget.files??[]).map((e=>N?.getPathForFile(e)??""));i(t)}),[N,i]),P=(0,o.useCallback)((()=>{l||(N?N.openFileChooser({multi:v,mode:x,accept:E,title:C,defaultPath:w,filters:I,buttonLabel:S,properties:A}):D.current&&D.current.click())}),[l,N,v,x,E,C,w,I,S,A]),L=(0,o.useRef)((()=>{e&&P()}));(0,o.useEffect)((()=>{L.current()}),[]),(0,o.useEffect)((()=>N?.onFilesChosen?.(i)),[N,i]);const O=(0,o.useMemo)((()=>JSON.stringify(y)),[y]),R="small"===m?void 0:s().createElement(ie,{glyph:"AddFile",title:null,fill:"currentColor"}),F="small"===m?s().createElement(ie,{glyph:"Edit",title:null,fill:"currentColor"}):void 0;return s().createElement("div",{className:(0,r.cx)(fe,b)},s().createElement("div",{className:(0,r.cx)({[ye]:"small"===m,[be]:"default"===m})},s().createElement("div",{className:(0,r.cx)({[Se]:"default"===m})},s().createElement(H.JU,{htmlFor:`${t}_file_input`,disabled:l},s().createElement("span",{className:(0,r.cx)({[k?Me:Ne]:l})},n)),c&&s().createElement("div",{className:Ae},d||"Optional"),h||f?h?s().createElement(q,{"data-testid":"file-input-link",href:h,className:(0,r.cx)(f?ke:De),hideExternalIcon:!f},f??""):s().createElement(H.VY,{"data-testid":"file-input-description"},f):null),s().createElement("input",{"data-testid":a??"file-input",className:Te,ref:D,id:`${t}_file_input`,name:t,type:"file",multiple:v,onChange:T,key:O,"data-filenames":O,accept:E}),s().createElement(J,{id:t,"data-testid":"file-input-button",className:"small"===m?Ee:Ce,disabled:l,onClick:P,title:"Select a file",leftGlyph:R,rightGlyph:F},s().createElement("span",{className:we},M))),g&&y&&y.length>0&&y.map(((e,t)=>s().createElement("div",{className:ve,key:e},s().createElement("div",null,e),s().createElement(Q,{className:xe,"aria-label":"Remove file",onClick:()=>{const e=[...y];e.splice(t,1),i(e)}},s().createElement(ie,{glyph:"X"}))))),u&&p&&s().createElement(H.JU,{"data-testid":"file-input-error",className:Ie,htmlFor:""},p))},Oe=(0,r.AH)({position:"relative",outline:"none","&::after":{position:"absolute",content:'""',pointerEvents:"none",top:3,right:3,bottom:3,left:3,borderRadius:ce.YK[100],boxShadow:"0 0 0 0 transparent",transition:"box-shadow .16s ease-in",zIndex:1}}),Re=(0,r.AH)({"&::after":{boxShadow:`0 0 0 3px ${le.M.blue.light1} !important`,transitionTimingFunction:"ease-out"}}),He=e=>(0,r.AH)({"&::after":{boxShadow:`0 0 0 3px ${e?le.M.gray.dark2:le.M.gray.light2}`,transitionTimingFunction:"ease-out"}}),Fe=(0,r.AH)(Oe,{"&:focus-visible":Re}),We=(0,r.AH)({"&::after":{top:0,right:0,bottom:0,left:0}}),je=(0,r.AH)({"&:focus-within":Re}),Be=e=>(0,r.AH)({"&:hover":He(e)});function ze({outer:e=!1,focusWithin:t=!1,hover:n=!1,radius:a}={}){const i=pe(),s=(0,o.useMemo)((()=>e&&We),[e]),l=(0,o.useMemo)((()=>"number"==typeof a&&(0,r.AH)({"&::after":{borderRadius:a}})),[a]),c=(0,o.useMemo)((()=>t&&je),[t]),d=(0,o.useMemo)((()=>n&&Be(!!i)),[n,i]);return{className:(0,r.cx)(Fe,s,l,c,d)}}var _e=n(45383);function $e(...e){const t=e.filter((e=>e.ref));return{...(0,_e.v6)(...e),...t.length>0&&{ref(e){t.forEach((({ref:t})=>{"function"==typeof t?t(e):t&&"object"==typeof t&&(t.current=e)}))}}}}const Ye=(0,r.AH)({textAlign:"center"}),Ke=(0,r.AH)({backgroundColor:"transparent",border:"none",paddingTop:ce.YK[100],paddingBottom:ce.YK[100],paddingLeft:ce.YK[200],paddingRight:ce.YK[200]}),Ge=(0,r.AH)({display:"flex",alignItems:"center"}),Ve=({"aria-controls":e,isExpanded:t,id:n,"data-testid":a,onToggleOptions:r,label:l=()=>"Options","aria-label":c=e=>e?"Fewer Options":"More Options"})=>{const d=(0,o.useMemo)((()=>t?"CaretDown":"CaretRight"),[t]),u=l(t),p=(0,o.useMemo)((()=>({width:`calc(${Math.max(l(!0).length,l(!1).length)}ch + ${ce.YK[400]}px + ${ce.YK[200]}px)`})),[l]),m=c(t),g=ze(),h=$e({className:Ke},g),f=(0,o.useCallback)((()=>{r()}),[r]);return s().createElement("div",{className:Ye,style:p},s().createElement(q,(0,i.A)({"aria-label":m,"aria-expanded":t,"aria-controls":e,as:"button",type:"button",hideExternalIcon:!0,"data-testid":a,id:n,onClick:f},h),s().createElement("div",{className:Ge},u,s().createElement(ie,{glyph:d}))))},Ue=(0,r.AH)({backgroundRepeat:"repeat-x",backgroundPosition:"center bottom",backgroundSize:"3px 2px",backgroundImage:"radial-gradient( circle closest-side, currentColor 75%, transparent 25%)"}),qe=(0,r.AH)({maxWidth:"360px"}),Ze=({children:e,definition:t,tooltipProps:n,...a})=>s().createElement(re,(0,i.A)({justify:"middle",spacing:5,trigger:s().createElement("span",(0,i.A)({className:Ue},a),e)},n),s().createElement(H.nB,{className:qe},t)),Je=(0,r.AH)({width:"100%",overflowWrap:"anywhere"}),Qe=(0,r.AH)({padding:0,margin:0,listStylePosition:"inside"}),Xe=(0,r.AH)({display:"flex"}),et=(0,r.AH)({marginLeft:"auto"});function tt({messages:e}){if(1===e.length)return s().createElement("div",null,e[0]);if(2===e.length)return s().createElement("div",null,s().createElement("ol",{className:Qe},e.map(((e,t)=>s().createElement("li",{key:t},e)))));const t=s().createElement("ol",{className:Qe},e.map(((e,t)=>s().createElement("li",{key:t},e)))),n=e[0].endsWith(".")?e[0].slice(0,e[0].length-1):e[0];return s().createElement("div",null,s().createElement("span",null,n,", and other ",e.length-1," problems.")," ",s().createElement(Ze,{tooltipProps:{align:"top",justify:"start"},definition:t},"View all"))}const nt=({"data-testid":e,messages:t,onAction:n,actionText:a,variant:i,className:l,dismissible:c,onClose:u})=>{const p=(0,o.useMemo)((()=>Array.isArray(t)?t:[t]),[t]);return s().createElement(d.lZ,{"data-testid":e,variant:i,className:(0,r.cx)(Je,l),dismissible:c,onClose:u},s().createElement("div",{className:Xe},s().createElement(tt,{messages:p}),n&&a&&s().createElement(J,{"data-testid":"banner-action",size:"xsmall",onClick:n,className:et},a)))},at=({className:e,errors:t,...n})=>s().createElement(nt,(0,i.A)({className:e,messages:t,variant:d.KT.Danger},n)),rt=({className:e,warnings:t,...n})=>s().createElement(nt,(0,i.A)({className:e,messages:t,variant:d.KT.Warning},n)),it=(0,r.AH)({marginTop:ce.YK[100]});function ot(e){return s().createElement(I.E9,(0,i.A)({},e,{className:`${it}${e.className?` ${e.className}`:""}`}))}const st=(0,r.AH)({display:"flex",gap:ce.YK[200],flexDirection:"column",justifyContent:"center",alignItems:"center",maxWidth:8*ce.YK[1600]}),lt=(0,r.AH)({width:"100%",height:"100%",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",maxWidth:8*ce.YK[1600],gap:ce.YK[500],margin:"0 auto"}),ct=(0,r.AH)({color:le.M.green.dark2,textAlign:"center"}),dt=(0,r.AH)({color:le.M.green.light2}),ut=r.i7`
18
+ 0% { transform: rotate(0deg); }
19
+ 100% { transform: rotate(360deg); }
20
+ `,pt=r.AH`
21
+ border: 2px solid transparent;
22
+ border-radius: 50%;
23
+ padding: 0;
24
+ margin: 0;
25
+ box-sizing: border-box;
26
+ display: inline-block;
27
+
28
+ animation: ${ut} 700ms ease infinite;
29
+ `,mt=(0,r.AH)({borderTop:`2px solid ${le.M.gray.dark3}`}),gt=(0,r.AH)({borderTop:`2px solid ${le.M.gray.light3}`});function ht({size:e=12,title:t,darkMode:n}){const a=pe(n);return s().createElement("div",{className:(0,r.cx)(pt,a?gt:mt),style:{width:e,height:e},title:t})}function ft({className:e,progressText:t,"data-testid":n,children:a,darkMode:o,...l}){const c=pe(o);return s().createElement("div",{className:(0,r.cx)(st,e),"data-testid":n},s().createElement(ht,(0,i.A)({size:ce.YK[600],darkMode:c},l)),s().createElement(H.Pd,{className:(0,r.cx)(ct,c&&dt)},t),a)}function yt({cancelText:e="Cancel",onCancel:t,...n}){return s().createElement(ft,n,s().createElement(J,{variant:"primaryOutline",onClick:t,"data-testid":`${n["data-testid"]??"spin-loader"}-button`},e))}function bt({cancelText:e="Cancel",className:t,onCancel:n,...a}){return s().createElement("div",{className:(0,r.cx)(lt,t)},s().createElement(v.z2,a),s().createElement(J,{variant:"primaryOutline",onClick:n,"data-testid":`${a["data-testid"]??"spin-loader"}-button`},e))}const vt="TOP",xt="RIGHT",Et=(0,r.AH)({all:"unset",position:"absolute",background:"transparent",padding:0,transition:"opacity 250ms ease",transitionDelay:"0ms",backgroundColor:le.M.blue.light1,opacity:"0",outline:"none",zIndex:100,"&:focus":{opacity:1},"&:hover":{transitionDelay:"250ms",opacity:1},WebkitAppearance:"none","&::-moz-range-thumb":{width:0,height:0},"&::-webkit-slider-thumb":{WebkitAppearance:"none"},"&::-ms-track":{background:"none",borderColor:"none",color:"none"}}),Ct=(0,r.AH)({height:"100%",width:"4px !important",right:"-2px",bottom:0,top:0,":hover":{cursor:"col-resize"}}),wt=(0,r.AH)({width:"100%",height:"4px !important",top:"-2px",right:0,left:0,":hover":{cursor:"row-resize"}});function It({direction:e,step:t=10,value:n,minValue:a,maxValue:i,onChange:l,title:c}){const d=(0,o.useRef)(!1);function u(e){return Math.min(i,Math.max(a,e))}let p="vertical",m="Width",g=Ct;return e===vt&&(p="horizontal",m="Height",g=wt),s().createElement("input",{type:"range","aria-roledescription":`${p} splitter`,"aria-label":`${m} of the ${c}, resize using arrow keys`,className:(0,r.cx)(Et,g),min:a,max:i,value:n,step:t,onChange:e=>{d.current||l(u(Number(e.target.value)))},onMouseDown:()=>{d.current=!0},onMouseMove:t=>{d.current&&(e===xt?l(u(n+t.movementX)):e===vt&&l(u(n-t.movementY)))},onMouseUp:t=>{t.currentTarget.blur(),d.current=!1,e===xt?l(u(n+t.movementX)):e===vt&&l(u(n-t.movementY))}})}function St(e){const t=(0,o.useRef)(e);return t.current=e,t}const At=(0,r.AH)({fontWeight:"bold",display:"flex",alignItems:"center",paddingLeft:0,paddingRight:0,border:"none",background:"none",borderRadius:"6px",boxShadow:"none",transition:"box-shadow 150ms ease-in-out","&:hover":{cursor:"pointer"},"&:focus-visible":{outline:"none",boxShadow:`0 0 0 3px ${le.M.blue.light1}`}}),kt={default:(0,r.AH)({fontSize:14,lineHeight:`${ce.YK[500]}px`}),small:(0,r.AH)({fontSize:ce.YK[300],lineHeight:`${ce.YK[500]}px`})},Dt={default:ce.YK[400],small:14},Nt=(0,r.AH)({color:le.M.gray.dark2}),Mt=(0,r.AH)({color:le.M.white}),Tt=(0,r.AH)({fontSize:0,lineHeight:0,padding:0,paddingRight:ce.YK[150]}),Pt=(0,r.AH)({textAlign:"left"}),Lt=(0,r.AH)({margin:0,marginLeft:ce.YK[100],padding:0,display:"inline"});function Ot({text:e,hintText:t,textClassName:n,buttonTextClassName:a,open:l,setOpen:c,defaultOpen:d=!1,size:u="default",...p}){const m=pe(),[g,h]=(0,o.useState)(l??d),f=St(void 0!==l?l:g),y=St(c),b=(0,o.useCallback)((()=>{const e=!f.current;h(e),y.current?.(e)}),[y,f]),v=(0,_e.Bi)(),x=(0,_e.Bi)(),E=void 0!==l?l:g;return s().createElement(s().Fragment,null,s().createElement("button",(0,i.A)({},p,{className:(0,r.cx)(m?Mt:Nt,At,kt[u],n),id:x,type:"button","aria-expanded":E?"true":"false","aria-controls":v,onClick:b}),s().createElement("span",{className:Tt},s().createElement(ie,{glyph:E?"ChevronDown":"ChevronRight",size:Dt[u]})),s().createElement("div",{className:(0,r.cx)(Pt,a)},e,t&&s().createElement(H.VY,{className:Lt},t))),E&&s().createElement("div",{role:"region","aria-labelledby":x,id:v},p.children))}const Rt=(0,r.AH)({margin:`${ce.YK[600]}px 0`}),Ht=function({className:e="",children:t,...n}){return s().createElement("div",{className:(0,r.cx)(Rt,e),"data-testid":n["data-testid"]},t)},Ft=(0,r.AH)({marginLeft:ce.YK[100]}),Wt=(0,r.AH)({paddingLeft:ce.YK[600]}),jt=({description:e,disabled:t,helpUrl:n,label:a,onToggle:r,toggled:i,children:o,"data-testid":l,id:c})=>{const d=(0,_e.Bi)(),p=c??d;return s().createElement(Ht,{"data-testid":l},s().createElement(u.Sc,{"data-testid":l&&`${l}-checkbox`,onChange:e=>{r(e.target.checked)},disabled:t,label:s().createElement(H.JU,{htmlFor:p,"data-testid":l&&`${l}-label`},a),description:e?s().createElement(s().Fragment,null,e,!!n&&s().createElement(q,{className:Ft,href:n,"aria-label":a},"Learn More")):"",checked:i,id:p}),i&&s().createElement("fieldset",{className:Wt},o))};var Bt=n(84357),zt=n(68037);function _t(e){return{onClick:(0,o.useCallback)((t=>{t.stopPropagation(),e(t)}),[e]),onKeyDown:(0,o.useCallback)((t=>{t.target===t.currentTarget&&[" ","Enter"].includes(t.key)&&(t.preventDefault(),t.stopPropagation(),e(t))}),[e])}}const $t=(0,r.AH)({flex:"none",width:"auto"}),Yt=({color:e,className:t,height:n,...a})=>{const o=pe(),l=e||(o?le.M.white:le.M.black);return s().createElement("svg",(0,i.A)({className:(0,r.cx)($t,t),height:n,viewBox:"0 0 15 32",fill:"none",xmlns:"http://www.w3.org/2000/svg"},a),s().createElement("path",{d:"M10.2779 3.56801C8.93285 1.97392 7.76219 0.354933 7.52557 0.0186807C7.50066 -0.00622689 7.4633 -0.00622689 7.43839 0.0186807C7.20177 0.354933 6.04357 1.97392 4.69856 3.56801C-6.8461 18.2759 6.51681 28.1891 6.51681 28.1891L6.6289 28.2639C6.72853 29.7957 6.9776 32 6.9776 32H7.47576H7.97391C7.97391 32 8.22298 29.8081 8.32261 28.2639L8.4347 28.1767C8.44715 28.1891 21.8225 18.2759 10.2779 3.56801ZM7.48821 27.9774C7.48821 27.9774 6.89043 27.4668 6.72853 27.2053V27.1804L7.45085 11.1648C7.45085 11.115 7.52557 11.115 7.52557 11.1648L8.24789 27.1804V27.2053C8.08599 27.4668 7.48821 27.9774 7.48821 27.9774Z",fill:l}))},Kt=(0,r.AH)({flex:"none"}),Gt=({color:e,size:t=16,className:n})=>{const a=pe(),i=e||(a?le.M.white:le.M.gray.dark2);return s().createElement("svg",{className:(0,r.cx)(Kt,n),width:t,height:t,viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",role:"img"},s().createElement("g",{clipPath:"url(#clip0_842_15453)"},s().createElement("path",{d:"M11.6665 1.1665H2.33317C1.68884 1.1665 1.1665 1.68884 1.1665 2.33317V4.6665C1.1665 5.31084 1.68884 5.83317 2.33317 5.83317H11.6665C12.3108 5.83317 12.8332 5.31084 12.8332 4.6665V2.33317C12.8332 1.68884 12.3108 1.1665 11.6665 1.1665Z",stroke:i,strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"}),s().createElement("path",{d:"M11.6665 8.1665H2.33317C1.68884 8.1665 1.1665 8.68884 1.1665 9.33317V11.6665C1.1665 12.3108 1.68884 12.8332 2.33317 12.8332H11.6665C12.3108 12.8332 12.8332 12.3108 12.8332 11.6665V9.33317C12.8332 8.68884 12.3108 8.1665 11.6665 8.1665Z",stroke:i,strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"}),s().createElement("path",{d:"M3.5 3.5H3.50667",stroke:i,strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"}),s().createElement("path",{d:"M3.5 10.5H3.50667",stroke:i,strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})),s().createElement("defs",null,s().createElement("clipPath",{id:"clip0_842_15453"},s().createElement("rect",{width:"14",height:"14",fill:"white"}))))},Vt=s().createContext(null),Ut=({children:e,theme:t})=>s().createElement(Vt.Provider,{value:t},e),qt=Symbol("context_menus"),Zt="compass-context-menu",Jt=(0,o.createContext)(null),Qt={display:"contents"};function Xt({disabled:e=!1,children:t,menuWrapper:n,onContextMenuOpen:a}){const r=(0,o.useContext)(Jt),i=(0,o.useRef)(null),[l,c]=(0,o.useState)({isOpen:!1,itemGroups:[],position:{x:0,y:0}}),d=(0,o.useCallback)((()=>c((e=>({...e,isOpen:!1})))),[c]),u=(0,o.useRef)(a);u.current=a;const p=(0,o.useCallback)((e=>{e.defaultPrevented||d()}),[d]);(0,o.useEffect)((()=>{const{current:t}=i;if(!r&&!e&&t)return t.addEventListener("contextmenu",n),window.addEventListener("resize",p),window.addEventListener("scroll",(e=>{e.target instanceof HTMLElement&&e.target.classList.contains(Zt)||p(e)}),{capture:!0}),()=>{t.removeEventListener("contextmenu",n),window.removeEventListener("resize",p),window.removeEventListener("scroll",p,{capture:!0})};function n(e){const t=function(e){return e[qt]??[]}(e);0===t.length||e.shiftKey||(e.preventDefault(),u.current?.(t),c({isOpen:!0,itemGroups:t,position:{x:e.clientX,y:e.clientY}}))}}),[e,i,p,u,r]);const m=(0,o.useMemo)((()=>({close:d})),[d]);return r?s().createElement(s().Fragment,null,t):s().createElement(Jt.Provider,{value:m},s().createElement("div",{ref:i,"data-testid":"context-menu-children-container",style:Qt},t),s().createElement(n,{menu:{...l,close:d}}))}const en=(0,r.AH)({paddingTop:ce.YK[150],paddingBottom:ce.YK[150]}),tn=(0,r.AH)({paddingTop:0,paddingBottom:0,fontSize:".8em"});function nn({children:e,disabled:t,onContextMenuItemClick:n,onContextMenuOpen:a}){return s().createElement(Xt,{disabled:t,menuWrapper:e=>s().createElement(an,(0,i.A)({},e,{onContextMenuItemClick:n})),onContextMenuOpen:a},e)}function an({menu:e,onContextMenuItemClick:t}){const n=(0,o.useRef)(null),a=(0,o.useRef)(null),{position:i,itemGroups:l}=e;return(0,o.useLayoutEffect)((()=>{a.current&&(a.current.style.left=`${i.x}px`,a.current.style.top=`${i.y}px`)}),[i]),s().createElement("div",{"data-testid":"context-menu-container"},s().createElement("div",{"data-testid":"context-menu-anchor",ref:a,style:{position:"fixed",left:i.x,top:i.y,width:1,height:1}}),s().createElement(y.W1,{"data-testid":"context-menu",refEl:a,ref:n,open:e.isOpen,setOpen:e.close,justify:"start",className:(0,r.cx)(en,Zt),maxHeight:Number.MAX_SAFE_INTEGER},l.map(((n,a)=>s().createElement("div",{key:`menu-group-${a}`,"data-testid":`menu-group-${a}`},n.items.map(((r,i)=>s().createElement(y.Dr,{key:`menu-group-${a}-item-${i}`,"data-text":r.label,"data-testid":`menu-group-${a}-item-${i}`,className:tn,onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:a=>{r.onAction?.(a),t?.(n,r),e.close()}},r.label))),a<l.length-1&&s().createElement("div",{key:`menu-group-${a}-separator`,"data-testid":`menu-group-${a}-separator`},s().createElement(y.bX,null)))))))}function rn(e,t=[]){const n=St(e),a=(0,o.useMemo)((()=>n.current().filter((e=>void 0!==e&&void 0!==e.items&&e.items.length>0)).map((({items:e,telemetryLabel:t})=>({items:e?.filter((e=>void 0!==e)),telemetryLabel:t})))),[n,...t]);return function(){const e=(0,o.useContext)(Jt),t=(0,o.useRef)(null);return(0,o.useMemo)((()=>{if(!e)throw new Error("useContextMenu called outside of the provider");return{close:e.close.bind(e),registerItemGroups(e){function n(t){!function(e,...t){e[qt]||(e[qt]=[]),e[qt].push(...t)}(t,...e)}return e=>{if(t.current){const[e,n]=t.current;e.removeEventListener("contextmenu",n)}e&&(e.addEventListener("contextmenu",n),t.current=[e,n])}}}}),[e])}().registerItemGroups(a)}function on(e){return`&:hover ${e}, &:focus-visible ${e}, &:focus-within:not(:focus) ${e}`}const sn=(0,r.AH)({display:"grid",gridTemplateAreas:'\n "top top top"\n "icon text close"\n ',gridRowGap:0,gridColumnGap:ce.YK[200],gridTemplateRows:`${ce.YK[100]}px 1fr`,gridTemplateColumns:"min-content 1fr min-content","&:hover, &:focus-visible, &:focus-within:not(:focus)":{gridTemplateColumns:"min-content 1fr min-content"},alignItems:"center",paddingBottom:ce.YK[100],maxWidth:6*ce.YK[800],minWidth:ce.YK[1600]+ce.YK[800],height:ce.YK[1e3],position:"relative",outline:"none",backgroundColor:"var(--workspace-tab-background-color)",color:"var(--workspace-tab-color)",boxShadow:"inset -1px -1px 0 0 var(--workspace-tab-border-color)","&:hover":{backgroundColor:"inherit",cursor:"pointer",zIndex:1},"&:focus-visible":{boxShadow:"inset 0 0 0 1px var(--workspace-tab-border-color)"},[on(".workspace-tab-title-container")]:{maxWidth:`calc(100% - ${ce.YK[600]}px - ${ce.YK[150]}px)`},[on(".workspace-tab-close-button")]:{display:"inline-block",position:"absolute",right:ce.YK[100],bottom:ce.YK[100]+ce.YK[50]},"&::before":{content:'""',backgroundColor:"var(--workspace-tab-top-border-color)",height:ce.YK[100],width:"100%",display:"block",gridArea:"top"}}),ln=(0,r.AH)({"--workspace-tab-background-color":le.M.gray.light3,"--workspace-tab-selected-background-color":le.M.white,"--workspace-tab-border-color":le.M.gray.light2,"--workspace-tab-top-border-color":"transparent","--workspace-tab-color":le.M.gray.base,"--workspace-tab-selected-color":le.M.gray.dark3,"--workspace-tab-selected-border-color":"transparent","&:focus-visible":{"--workspace-tab-selected-color":le.M.blue.base,"--workspace-tab-border-color":le.M.blue.base}}),cn=(0,r.AH)({"--workspace-tab-background-color":le.M.gray.dark3,"--workspace-tab-selected-background-color":le.M.black,"--workspace-tab-border-color":le.M.gray.dark2,"--workspace-tab-top-border-color":"transparent","--workspace-tab-color":le.M.gray.base,"--workspace-tab-selected-color":le.M.white,"--workspace-tab-selected-border-color":"transparent","&:focus-visible":{"--workspace-tab-selected-color":le.M.blue.light1,"--workspace-tab-`border-color`":le.M.blue.light1}}),dn=(0,r.AH)({color:"var(--workspace-tab-selected-color)",backgroundColor:"var(--workspace-tab-selected-background-color)",boxShadow:"inset -1px 0 0 0 var(--workspace-tab-border-color)","&:hover":{backgroundColor:"var(--workspace-tab-selected-background-color)",cursor:"default"},"&::before":{backgroundColor:"var(--workspace-tab-selected-top-border-color)",filter:"brightness(0.85) saturate(2)"}}),un=(0,r.AH)({}),pn=(0,r.AH)({cursor:"grabbing !important"}),mn=(0,r.AH)({color:le.M.gray.base}),gn=(0,r.AH)({color:"currentColor",marginLeft:ce.YK[300]}),hn=(0,r.AH)({position:"relative",minWidth:0,marginRight:ce.YK[100]}),fn=(0,r.AH)({fontSize:"12px",lineHeight:"16px",fontWeight:"normal",color:"currentColor",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",transform:"translateY(0)",transition:".16s ease-in-out",transitionProperty:"opacity, transform"}),yn=(0,r.AH)({display:"none",marginRight:ce.YK[100]}),bn=(0,r.AH)({overflowWrap:"anywhere",textWrap:"wrap"});function vn({connectionName:e,type:t,title:n,tooltip:a,inferredFromPrivileges:l,isSelected:c,isDragging:d,onSelect:u,onDuplicate:p,onClose:m,onCloseAllOthers:g,tabContentId:h,iconGlyph:f,className:y,...b}){const v=pe(),x=_t(u),{listeners:E,setNodeRef:C,transform:w,transition:I}=(0,Bt.gl)({id:h}),S=(0,o.useContext)(Vt),A=$e(x,E??{},b),k=(0,o.useMemo)((()=>S?(0,r.AH)(S):v?cn:ln),[S,v]),D=rn((()=>[{telemetryLabel:"Workspace Tab",items:[{label:"Close all other tabs",onAction:g},{label:"Duplicate",onAction:p}]}]),[g,p]),N=(0,L.SV)([C,D]),M={transform:zt.Ks.Transform.toString(w),transition:I,cursor:"grabbing !important"},T=(0,_e.Bi)();return s().createElement(re,{enabled:!!a,align:"bottom",justify:"start",trigger:s().createElement("div",(0,i.A)({ref:N,style:M,className:(0,r.cx)(sn,k,l&&mn,c&&dn,c&&S&&un,d&&pn,y),"aria-selected":c,role:"tab",tabIndex:c?0:-1,"aria-controls":h,"data-testid":"workspace-tab-button","data-connection-name":e,"data-type":t,id:T},A),"Logo"===f&&s().createElement(Yt,{height:16,color:c?"var(--workspace-tab-selected-color)":"var(--workspace-tab-color)",role:"presentation",className:gn,"data-testid":`workspace-tab-icon-${f}`}),"Server"===f&&s().createElement(Gt,{color:c?"var(--workspace-tab-selected-color)":"var(--workspace-tab-color)",className:gn,"data-testid":`workspace-tab-icon-${f}`}),!["Logo","Server"].includes(f)&&s().createElement(ie,{size:"small",role:"presentation",className:gn,glyph:f,"data-testid":`workspace-tab-icon-${f}`}),s().createElement("div",{className:(0,r.cx)(hn,"workspace-tab-title-container")},s().createElement("div",{className:(0,r.cx)(fn,"workspace-tab-title")},n)),s().createElement(Q,{as:"button",className:(0,r.cx)(yn,"workspace-tab-close-button"),onClick:e=>{e.stopPropagation(),m()},"aria-label":"Close Tab","data-testid":"close-workspace-tab"},s().createElement(ie,{glyph:"X",role:"presentation"})))},a&&s().createElement("div",{"data-testid":"workspace-tab-tooltip"},a.map((([e,t])=>s().createElement("div",{key:e,className:bn},s().createElement("b",null,e,":")," ",t)))))}var xn=n(20327),En=n(72179),Cn=n(18047);const wn={NoFocus:"NoFocus",FocusVisible:"FocusVisible",Focus:"Focus",FocusWithinVisible:"FocusWithinVisible",FocusWithin:"FocusWithin"};function In(){const e=(0,o.useRef)(wn.NoFocus),[t,n]=(0,o.useState)(!1),[a,r]=(0,o.useState)(!1),{isFocusVisible:i}=(0,Cn.Y0)(),{focusWithinProps:s}=(0,Cn.Rb)({onFocusWithinChange:r}),{focusProps:l}=(0,Cn.iQ)({onFocusChange:n}),c=(0,o.useMemo)((()=>(0,_e.v6)(l,s)),[l,s]);return e.current=function(e,t,n){return e&&n?wn.FocusVisible:e?wn.Focus:t&&n?wn.FocusWithinVisible:t?wn.FocusWithin:wn.NoFocus}(t,a,i),[c,e.current,e]}function Sn(){const{documentElement:e,activeElement:t,body:n}=document;return t===e||t===n||!t}function An(){const e=(0,o.useRef)(wn.NoFocus),[t,n]=In(),a=function(){const[e,t]=(0,o.useState)(Sn());return(0,o.useEffect)((()=>{const e=[],n=()=>{t(Sn())};for(const t of[document.body,document.documentElement])for(const a of["focus","blur","focusin","focusout"])t.addEventListener(a,n),e.push((()=>t.removeEventListener(a,n)));return()=>{for(const t of e)t()}}),[t]),e}()?"Unfocused":n;return e.current=a,[t,a,e]}function kn(){const[e,t]=(0,o.useState)(!1);return[{onMouseEnter(){t(!0)},onMouseLeave(){t(!1)}},e,t]}var Dn=n(82543);(0,r.AH)({display:"flex",gap:ce.YK[100]});const Nn=(e,t,n,a)=>(0,Dn.vC)(e,t,n,a),Mn=e=>{let t=e.toLowerCase();return t=-1!==navigator.userAgent.indexOf("Mac")?t.replace(/\bmeta\b/,"⌘").replace(/\balt\b/,"option").replace(/\bmod\b/,"⌘"):t.replace(/\bmod\b/,"ctrl"),t.replace(/\+/g," + ").replace(/\s+/g," ").replace("arrowup","↑").replace("arrowdown","↓").replace(/\b\w/g,(e=>e.toUpperCase())).trim()},Tn=(0,xn.B3)(le.M.gray.base,.65),Pn=(0,xn.B3)(le.M.gray.base,.65),Ln=(0,r.AH)({margin:0,padding:0,flexShrink:0,position:"relative",overflow:"overlay",whiteSpace:"nowrap","::-webkit-scrollbar":{":horizontal":{height:ce.YK[100]}},minHeight:36}),On=(0,r.AH)({background:le.M.gray.light3,boxShadow:`inset 0px -1px 0 0 ${le.M.gray.light2}`,"::-webkit-scrollbar-thumb":{backgroundColor:Tn}}),Rn=(0,r.AH)({backgroundColor:le.M.gray.dark3,boxShadow:`inset 0px -1px 0 0 ${le.M.gray.dark2}`,"::-webkit-scrollbar-thumb":{backgroundColor:Pn}}),Hn=(0,r.AH)({display:"flex",flexDirection:"row"}),Fn=(0,r.AH)({display:"inline-flex"}),Wn=(0,r.AH)({flex:"none",alignSelf:"center"}),jn=(0,r.AH)({margin:ce.YK[100]}),Bn=(0,r.AH)({display:"inline-flex"}),zn=({tabs:e,onMove:t,onSelect:n,selectedTabIndex:a,onDuplicate:r,onClose:i,onCloseAllOthers:l})=>{const c=e.map((e=>e.id)),[d,u]=(0,o.useState)(null),p=(0,En.FR)((0,En.MS)(En.cA,{activationConstraint:{distance:10}}),(0,En.MS)(En.IG,{activationConstraint:{delay:250,tolerance:5}})),m=(0,o.useCallback)((({oldIndex:n,newIndex:a})=>{const r=e.findIndex((e=>e.id===n)),i=e.findIndex((e=>e.id===a));t(r,i)}),[t,e]);return s().createElement(En.Mp,{sensors:p,autoScroll:!1,onDragStart:({active:e})=>{e&&u(e.id)},onDragEnd:({active:e,over:t})=>{u(null),t&&e.id!==t.id&&m({oldIndex:e.id,newIndex:t.id})},onDragCancel:()=>u(null)},s().createElement(Bt.gB,{items:c,strategy:Bt.m$},s().createElement("div",{className:Bn},e.map(((e,t)=>s().createElement(_n,{key:e.id,index:t,tab:e,activeId:d,onSelect:n,onDuplicate:r,onClose:i,onCloseAllOthers:l,selectedTabIndex:a}))))))},_n=({tab:{id:e,renderTab:t},index:n,selectedTabIndex:a,activeId:r,onSelect:i,onDuplicate:s,onClose:l,onCloseAllOthers:c})=>{const d=(0,o.useCallback)((()=>{i(n)}),[i,n]),u=(0,o.useCallback)((()=>{s(n)}),[s,n]),p=(0,o.useCallback)((()=>{l(n)}),[l,n]),m=(0,o.useCallback)((()=>{c(n)}),[c,n]);return t({isSelected:(0,o.useMemo)((()=>a===n),[a,n]),isDragging:(0,o.useMemo)((()=>e===r),[e,r]),tabContentId:e,onSelect:d,onDuplicate:u,onClose:p,onCloseAllOthers:m})};function $n({"aria-label":e,onCreateNewTab:t,onDuplicateTab:n,onCloseTab:a,onCloseAllOtherTabs:l,onMoveTab:c,onSelectTab:d,onSelectNextTab:u,onSelectPrevTab:p,tabs:m,selectedTabIndex:g}){const h=pe(),f=function({currentTabbable:e}){const t=(0,o.useRef)(null),[n,a]=In(),r=(0,o.useCallback)((()=>{const n=`[role="tab"]:nth-child(${e+1})`;t.current?.querySelector(n)?.focus()}),[t,e]);return(0,o.useEffect)((()=>{[wn.Focus,wn.FocusVisible,wn.FocusWithin,wn.FocusWithinVisible].includes(a)&&r()}),[a,r]),{ref:t,...n}}({currentTabbable:g}),[y]=function({tabsCount:e,onSelectTab:t,selectedTabIndex:n}){return[{onKeyDown:(0,o.useCallback)((a=>{let r=-1;"ArrowLeft"===a.key&&(a.stopPropagation(),r=n-1),"ArrowRight"===a.key&&(a.stopPropagation(),r=n+1),"Home"===a.key&&(a.preventDefault(),a.stopPropagation(),r=0),"End"===a.key&&(a.preventDefault(),a.stopPropagation(),r=e-1),e>0&&r!==n&&r>=0&&r<e&&t(r)}),[n,e,t])}]}({selectedTabIndex:g,onSelectTab:d,tabsCount:m.length}),b=$e(f,y);return Nn("ctrl + tab",(e=>{e.preventDefault(),e.stopPropagation(),u()}),[u]),Nn("ctrl + shift + tab",(e=>{e.preventDefault(),e.stopPropagation(),p()}),[p]),Nn("mod + shift + ]",(e=>{e.preventDefault(),e.stopPropagation(),u()}),[u]),Nn("mod + shift + [",(e=>{e.preventDefault(),e.stopPropagation(),p()}),[p]),Nn("mod + w",(e=>{e.preventDefault(),e.stopPropagation(),a(g)}),[a,g]),Nn("mod + t",(e=>{e.preventDefault(),e.stopPropagation(),t()}),[t]),s().createElement("div",{className:(0,r.cx)(Ln,h?Rn:On)},s().createElement("div",{className:Hn},s().createElement("div",(0,i.A)({className:Fn,role:"tablist","aria-label":e,"aria-orientation":"horizontal"},b),s().createElement(zn,{tabs:m,onMove:c,onSelect:d,onDuplicate:n,onClose:a,onCloseAllOthers:l,selectedTabIndex:g})),s().createElement("div",{className:Wn},s().createElement(Q,{className:jn,"aria-label":"Create new tab",onClick:t},s().createElement(ie,{role:"presentation",glyph:"Plus"})))))}const Yn=(0,r.AH)({display:"flex",flexDirection:"column",margin:0,padding:0,height:"100%",position:"relative"}),Kn=(0,r.AH)({"--color":le.M.white,"--bg-color":le.M.gray.dark4,"--title-color":le.M.gray.dark3,"--title-color-hover":le.M.white,"--title-bg-color":le.M.green.light1,"--icon-color":le.M.white,"--item-color":le.M.white,"--item-color-active":le.M.green.base,"--item-bg-color":le.M.gray.dark4,"--item-bg-color-hover":le.M.gray.dark2,"--item-bg-color-active":le.M.black,color:"var(--color)",backgroundColor:"var(--bg-color)"}),Gn=(0,r.AH)({"--color":le.M.gray.dark3,"--bg-color":le.M.gray.light3,"--title-color":le.M.white,"--title-color-hover":le.M.gray.dark3,"--title-bg-color":le.M.green.dark2,"--icon-color":le.M.gray.dark3,"--item-color":le.M.gray.dark3,"--item-color-active":le.M.green.dark2,"--item-bg-color":le.M.gray.light3,"--item-bg-color-hover":le.M.gray.light2,"--item-bg-color-active":le.M.green.light3,color:"var(--color)",backgroundColor:"var(--bg-color)"}),Vn=300,Un=({initialWidth:e=Vn,minWidth:t=210,children:n,className:a,style:l,useNewTheme:c,...d})=>{const u=pe(),[p,m]=(0,o.useState)(e),g=c?{"--item-color-active":u?le.M.white:le.M.gray.dark3,"--item-bg-color-active":u?le.M.gray.dark2:le.M.gray.light2}:{},h=(0,o.useCallback)((()=>Math.max(t,600)),[t]),f=(0,o.useCallback)((e=>{const n=h();return Math.min(n,Math.max(t,e))}),[h,t]),y=f(p);return s().createElement("div",(0,i.A)({className:(0,r.cx)(Yn,u?Kn:Gn,a),style:{...l,minWidth:t,width:y,flex:"none",...g}},d),n,s().createElement(It,{onChange:m,direction:xt,value:p,minValue:t,maxValue:h(),title:"sidebar"}))};function qn(e){return"object"==typeof e&&null!==e&&"separator"in e&&!0===e.separator}function Zn(e,t){return e?`${e}-${t}-action`:void 0}function Jn(e){const t=[];let n=[];for(const a of e)qn(a)?n.length>0&&(t.push(n),n=[]):n.push(a);return n.length>0&&t.push(n),t}const Qn={XSmall:"xsmall",Small:"small",Default:"default"},Xn=({glyph:e,size:t,...n})=>"string"==typeof e?s().createElement(ie,(0,i.A)({size:t,glyph:e},n)):s().isValidElement(e)?e:null,ea=(0,r.AH)({display:"block",flex:"none",fontSize:0,lineHeight:0}),ta={default:void 0,small:(0,r.AH)({flex:"none",width:`${ce.YK[600]}px !important`,height:`${ce.YK[600]}px !important`}),xsmall:(0,r.AH)({flex:"none",width:"20px !important",height:"20px !important"})},na=(0,o.forwardRef)((function({glyph:e,size:t,label:n,children:a,className:o,...l},c){return s().createElement(Q,(0,i.A)({ref:c,className:(0,r.cx)(ta[t],o),"aria-label":n},l),s().createElement("span",{role:"presentation",className:ea},s().createElement(Xn,{glyph:e,size:t})),a)})),aa=(0,r.AH)({flex:"none",marginLeft:"auto",alignItems:"center",display:"flex"});function ra({actions:e,isVisible:t=!0,setHidable:n,onAction:a,className:i,menuClassName:l,renderMode:c,iconClassName:d,iconStyle:u,iconSize:p=Qn.Default,"data-testid":m}){const g=(0,o.useRef)(null),[h,f]=(0,o.useState)(!1),b=(0,o.useCallback)((e=>{e.stopPropagation(),e.currentTarget.dataset.menuitem&&f(!1);const t=e.currentTarget.dataset.action;if("string"!=typeof t)throw new Error('Expected element to have a "data-action" attribute');a(t)}),[a]);return(0,o.useEffect)((()=>{n&&n(!h)}),[n,h]),h||t&&e.length>0?s().createElement("div",{className:(0,r.cx)(aa,i)},s().createElement(y.W1,{className:l,open:h,setOpen:f,refEl:g,renderMode:c,"data-testid":m,trigger:({onClick:e,children:t})=>s().createElement(na,{ref:g,size:p,glyph:"Ellipsis",label:"Show actions",title:"Show actions","data-testid":m?`${m}-show-actions`:void 0,onClick:t=>{t.stopPropagation(),e?.(t)},className:d,style:u},t)},e.map(((e,t)=>{if(qn(e))return s().createElement(y.bX,{key:`separator-${t}`});const{action:n,label:a,icon:r,variant:i,isDisabled:o,disabledDescription:l}=e;return s().createElement(y.Dr,{key:n,"data-testid":Zn(m,n),"data-action":n,"data-menuitem":!0,glyph:s().createElement(Xn,{glyph:r,size:p}),onClick:b,variant:i||"default",disabled:o,description:o?l:""},a)})))):null}function ia({action:e,icon:t=s().createElement(s().Fragment,null),label:n,tooltip:a,iconSize:i=Qn.Default,onClick:o,iconClassName:l,className:c,iconStyle:d,isDisabled:u,"data-testid":p}){return s().createElement(na,{key:e,glyph:t,label:n,title:a?void 0:n,size:i,"data-action":e,"data-testid":p,onClick:o,className:(0,r.cx)(l,c),style:d,disabled:u})}const oa=(0,r.AH)({flex:"none",marginLeft:"auto",alignItems:"center",display:"flex",gap:ce.YK[100]}),sa=(0,r.AH)({display:"inherit"});function la({actions:e,onAction:t,isVisible:n=!0,setHidable:a,className:l,iconClassName:c,iconStyle:d,iconSize:u=Qn.Default,"data-testid":p}){const m=(0,o.useCallback)((e=>{e.stopPropagation();const n=e.currentTarget.dataset.action;if("string"!=typeof n)throw new Error('Expected element to have a "data-action" attribute');t(n)}),[t]);return n&&0!==e.length?s().createElement("div",{className:(0,r.cx)(oa,l),"data-testid":p},e.map(((e,t)=>{if(qn(e))return s().createElement(y.bX,{key:`separator-${t}`});const{expandedAs:n=ia,tooltip:r,tooltipProps:o,...l}=e,g=s().createElement(n,(0,i.A)({key:l.action},l,{tooltip:r,iconSize:u,iconStyle:d,iconClassName:c,onClick:m,"data-testid":Zn(p,l.action),setHidable:a}));return r?s().createElement(re,(0,i.A)({key:l.action},o,{trigger:s().createElement("div",{className:sa},g)}),r):g}))):null}const ca=(0,r.AH)({flex:"none",marginLeft:"auto",alignItems:"center",display:"flex",gap:ce.YK[100]});function da({isVisible:e=!0,actions:t,onAction:n,className:a,menuClassName:l,iconClassName:c,iconStyle:d,iconSize:u=Qn.Default,renderMode:p,collapseAfter:m=0,collapseToMenuThreshold:g=2,"data-testid":h}){const[f,y]=(0,o.useState)(!0),b={setHidable:y,onAction:n,className:(0,r.cx)("item-action-controls",a),iconClassName:c,iconStyle:d,iconSize:u,"data-testid":h},v={menuClassName:l,renderMode:p};if(0===t.length||f&&!e)return null;if(m>0){const e=t.slice(0,m),n=t.slice(m);return s().createElement("div",{className:ca},s().createElement(la,(0,i.A)({},b,{actions:e})),s().createElement(ra,(0,i.A)({},b,v,{actions:n})))}return t.length>=g?s().createElement(ra,(0,i.A)({actions:t},b,v)):s().createElement(la,(0,i.A)({actions:t},b))}var ua=n(84896);const pa="compass-workspace-container",ma=(0,r.AH)({height:"100%",width:"100%",display:"flex",flexDirection:"column",overflow:"hidden"}),ga=(0,r.AH)({flex:"none",containerName:pa,containerType:"inline-size"}),ha=(0,r.AH)({flex:1,width:"100%",minHeight:0,position:"relative",zIndex:0}),fa=ce.YK[600],ya=(0,r.i7)({from:{opacity:0},to:{opacity:1}}),ba=(0,r.AH)({overflow:"hidden",position:"absolute",top:0,display:"block",width:"100%",height:2*fa,flex:"none",zIndex:1,pointerEvents:"none",animation:`${ya} .1s linear`}),va=e=>`0px 2px ${fa}px -1px ${e}`,xa=(0,r.AH)({height:fa,borderRadius:ce.YK[200],width:`calc(100% - ${fa}px)`,margin:"0 auto",marginTop:-fa}),Ea=(0,r.AH)({boxShadow:va((0,xn.B3)(le.M.black,.15))}),Ca=(0,r.AH)({boxShadow:va((0,xn.B3)(le.M.black,.4))}),wa=(0,r.AH)({overflow:"auto",height:"100%",width:"100%",display:"block",position:"relative",zIndex:0}),Ia=(0,r.AH)({backgroundColor:le.M.white,color:le.M.gray.dark2}),Sa=(0,r.AH)({backgroundColor:le.M.black,color:le.M.white});function Aa({className:e,children:t,toolbar:n,toolbarRef:a,scrollableContainerRef:l,initialTopInView:c=!0,"data-testid":d,...u}){const p=pe(),[m,g]=(0,o.useState)(null),[h,f]=(0,ua.Wx)({root:m,initialInView:c});return s().createElement("div",(0,i.A)({className:(0,r.cx)(ma,p?Sa:Ia,e),"data-testid":d},u),n&&s().createElement("div",{ref:a,className:ga},"function"==typeof n?n():n),s().createElement("div",{className:ha,ref:g},f||s().createElement("div",{className:ba},s().createElement("div",{className:(0,r.cx)(xa,p?Ca:Ea)})),s().createElement("div",{ref:l,className:wa},"function"==typeof t?t(h):s().createElement(s().Fragment,null,s().createElement("div",{ref:h}),t))))}Aa.toolbarContainerQueryName=pa;const ka=e=>(0,r.AH)({[`@container ${Aa.toolbarContainerQueryName} (width < ${e})`]:{display:"none"}});function Da({isVisible:e=!0,actions:t,onAction:n,renderMode:a,activeAction:r,buttonText:l,buttonProps:c,iconSize:d=Qn.Default,"data-testid":u,hideOnNarrow:p=!0,narrowBreakpoint:m="900px"}){const g=(0,o.useRef)(null),[h,f]=(0,o.useState)(!1),b=(0,o.useCallback)((e=>{e.stopPropagation(),e.currentTarget.dataset.menuitem&&f(!1);const t=e.currentTarget.dataset.action;if("string"!=typeof t)throw new Error('Expected element to have a "data-action" attribute');n(t)}),[n]);return h||e&&t.length>0?s().createElement(y.W1,{open:h,setOpen:f,justify:"start",refEl:g,renderMode:a,"data-testid":u,trigger:({onClick:e,children:t})=>s().createElement(J,(0,i.A)({as:"button",ref:g,"data-testid":u?`${u}-show-actions`:void 0,onClick:t=>{t.stopPropagation(),e?.(t)},rightGlyph:s().createElement(ie,{glyph:"CaretDown"}),title:l},c),l&&s().createElement("span",{className:p?ka(m):void 0},l),t)},t.map(((e,t)=>{if(qn(e))return s().createElement(y.bX,{key:`separator-${t}`});const{action:n,label:a,icon:i,isDisabled:o,disabledDescription:l}=e;return s().createElement(y.Dr,{active:r===n,key:n,"data-testid":Zn(u,n),"data-action":n,"data-menuitem":!0,glyph:i?s().createElement(Xn,{glyph:i,size:d}):void 0,onClick:b,disabled:o,description:o&&l?l:void 0},a)}))):null}const Na=()=>{const e=pe(),t=(0,o.useMemo)((()=>e?le.M.white:le.M.black),[e]);return s().createElement("svg",{width:"72",height:"72",viewBox:"0 0 72 72",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s().createElement("path",{d:"M62 19.995H48C46.9 19.995 46 19.095 46 17.995V3.995L62 19.995Z",fill:le.M.green.base}),s().createElement("path",{d:"M36.5 49.545H17.5V50.545H36.5V49.545Z",fill:t}),s().createElement("path",{d:"M54.5 40.545H17.5V41.545H54.5V40.545Z",fill:t}),s().createElement("path",{d:"M54.5 31.545H17.5V32.545H54.5V31.545Z",fill:t}),s().createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M10 55.185C10.28 55.185 10.5 54.965 10.5 54.685V47.215C10.5 46.935 10.28 46.715 10 46.715C9.72 46.715 9.5 46.935 9.5 47.215V54.685C9.5 54.965 9.72 55.185 10 55.185Z",fill:t}),s().createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M16.08 67.495H12.1C11.99 67.495 11.88 67.485 11.77 67.465C11.75 67.465 11.73 67.455 11.71 67.445C11.21 67.315 10.81 66.955 10.62 66.505C10.54 66.315 10.5 66.105 10.5 65.895V62.155C10.5 61.875 10.28 61.655 10 61.655C9.72 61.655 9.5 61.875 9.5 62.155V65.895C9.5 66.065 9.52 66.235 9.55 66.405C9.57 66.485 9.6 66.555 9.62 66.635C9.65 66.715 9.66 66.805 9.7 66.885V66.905C9.96 67.515 10.45 68.025 11.08 68.285C11.16 68.325 11.25 68.345 11.34 68.375C11.41 68.395 11.48 68.425 11.55 68.445C11.72 68.485 11.9 68.495 12.08 68.495H16.06C16.34 68.495 16.56 68.275 16.56 67.995C16.56 67.715 16.34 67.495 16.06 67.495H16.08Z",fill:t}),s().createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M10 40.235C10.28 40.235 10.5 40.015 10.5 39.735V32.265C10.5 31.985 10.28 31.765 10 31.765C9.72 31.765 9.5 31.985 9.5 32.265V39.735C9.5 40.015 9.72 40.235 10 40.235Z",fill:t}),s().createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M24.81 4.495H33.28C33.56 4.495 33.78 4.275 33.78 3.995C33.78 3.715 33.56 3.495 33.28 3.495H24.81C24.53 3.495 24.31 3.715 24.31 3.995C24.31 4.275 24.53 4.495 24.81 4.495Z",fill:t}),s().createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M16.34 3.495H12.1C11.93 3.495 11.76 3.515 11.59 3.545C11.51 3.565 11.44 3.595 11.36 3.615C11.28 3.645 11.19 3.655 11.11 3.695H11.1C11.1 3.695 11.1 3.705 11.09 3.705C10.48 3.965 9.97 4.455 9.71 5.085C9.68 5.175 9.66 5.265 9.63 5.355C9.61 5.425 9.58 5.49499 9.56 5.565C9.52 5.735 9.51 5.91499 9.51 6.095V9.835C9.51 10.115 9.73 10.335 10.01 10.335C10.29 10.335 10.51 10.115 10.51 9.835V6.095C10.51 5.985 10.52 5.87499 10.54 5.765C10.54 5.745 10.55 5.725 10.56 5.705C10.69 5.205 11.05 4.805 11.5 4.615C11.69 4.535 11.9 4.495 12.11 4.495H16.34C16.62 4.495 16.84 4.275 16.84 3.995C16.84 3.715 16.62 3.495 16.34 3.495Z",fill:t}),s().createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M10 25.285C10.28 25.285 10.5 25.065 10.5 24.785V17.315C10.5 17.035 10.28 16.815 10 16.815C9.72 16.815 9.5 17.035 9.5 17.315V24.785C9.5 25.065 9.72 25.285 10 25.285Z",fill:t}),s().createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M62 61.575C61.72 61.575 61.5 61.795 61.5 62.075V65.905C61.5 66.015 61.49 66.125 61.47 66.235C61.47 66.255 61.46 66.275 61.45 66.295C61.32 66.795 60.96 67.195 60.51 67.385C60.32 67.465 60.11 67.505 59.9 67.505H55.92C55.64 67.505 55.42 67.725 55.42 68.005C55.42 68.285 55.64 68.505 55.92 68.505H59.9C60.07 68.505 60.24 68.485 60.41 68.455C60.49 68.435 60.56 68.405 60.64 68.385C60.72 68.355 60.81 68.345 60.89 68.305H60.9C60.9 68.305 60.9 68.295 60.91 68.295C61.52 68.035 62.03 67.545 62.29 66.915C62.32 66.825 62.34 66.735 62.37 66.645C62.39 66.575 62.42 66.505 62.43 66.435C62.47 66.265 62.48 66.085 62.48 65.905V62.075C62.48 61.795 62.26 61.575 61.98 61.575H62Z",fill:t}),s().createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M62 46.275C61.72 46.275 61.5 46.495 61.5 46.775V54.425C61.5 54.705 61.72 54.925 62 54.925C62.28 54.925 62.5 54.705 62.5 54.425V46.775C62.5 46.495 62.28 46.275 62 46.275Z",fill:t}),s().createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M62 30.965C61.72 30.965 61.5 31.185 61.5 31.465V39.115C61.5 39.395 61.72 39.615 62 39.615C62.28 39.615 62.5 39.395 62.5 39.115V31.465C62.5 31.185 62.28 30.965 62 30.965Z",fill:t}),s().createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M32.02 67.495H24.05C23.77 67.495 23.55 67.715 23.55 67.995C23.55 68.275 23.77 68.495 24.05 68.495H32.02C32.3 68.495 32.52 68.275 32.52 67.995C32.52 67.715 32.3 67.495 32.02 67.495Z",fill:t}),s().createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M62.49 19.935C62.49 19.935 62.49 19.895 62.48 19.875C62.46 19.795 62.42 19.715 62.36 19.645L46.35 3.645C46.29 3.585 46.21 3.545 46.12 3.525C46.1 3.525 46.08 3.525 46.06 3.515C46.04 3.515 46.02 3.505 46 3.505H41.76C41.48 3.505 41.26 3.725 41.26 4.005C41.26 4.285 41.48 4.505 41.76 4.505H45.5V17.995C45.5 19.375 46.62 20.495 48 20.495H61.5V23.825C61.5 24.105 61.72 24.325 62 24.325C62.28 24.325 62.5 24.105 62.5 23.825V19.995C62.5 19.995 62.5 19.955 62.49 19.935ZM48 19.495C47.18 19.495 46.5 18.815 46.5 17.995V5.205L60.8 19.505H48.01L48 19.495Z",fill:t}),s().createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M47.95 67.495H39.98C39.7 67.495 39.48 67.715 39.48 67.995C39.48 68.275 39.7 68.495 39.98 68.495H47.95C48.23 68.495 48.45 68.275 48.45 67.995C48.45 67.715 48.23 67.495 47.95 67.495Z",fill:t}))},Ma=3*ce.YK[600],Ta=({size:e=Ma})=>{const t=pe(),n=(0,o.useMemo)((()=>t?le.M.white:le.M.black),[t]);return s().createElement("svg",{width:e,height:e,viewBox:"0 0 72 72",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s().createElement("path",{d:"M47 53C54.1797 53 60 47.1797 60 40C60 32.8203 54.1797 27 47 27C39.8203 27 34 32.8203 34 40C34 47.1797 39.8203 53 47 53Z",fill:le.M.green.base,stroke:n,strokeMiterlimit:"10",strokeLinecap:"round",strokeLinejoin:"round"}),s().createElement("path",{d:"M56 49L68 61",stroke:n}),s().createElement("path",{d:"M4 35.9501H6.2M6.2 35.9501C9.4 35.9501 12.1 33.3553 12.1 30.0619V19.5828C12.1 14.8922 15.9 11 20.7 11M6.2 35.9501C9.4 35.9501 12.1 38.5449 12.1 41.8383V52.4172C12.1 57.1078 15.9 61 20.7 61M54.0001 35.9501H51.8001M51.8001 35.9501C48.6001 35.9501 45.9001 38.5449 45.9001 41.8383V52.4172C45.9001 57.1078 42.1001 61 37.3001 61M51.8001 35.9501C48.6001 35.9501 45.9 33.3553 45.9 30.0619V19.5828C45.9 14.8922 42.1 11 37.3 11",stroke:n,strokeMiterlimit:"10"}))};function Pa(){const e=pe(),t=(0,o.useMemo)((()=>e?le.M.white:le.M.black),[e]);return s().createElement("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s().createElement("path",{d:"M3.5 8.75H2.5C2.30109 8.75 2.11032 8.82902 1.96967 8.96967C1.82902 9.11032 1.75 9.30109 1.75 9.5V13C1.75 13.1989 1.82902 13.3897 1.96967 13.5303C2.11032 13.671 2.30109 13.75 2.5 13.75C2.69891 13.75 2.88968 13.671 3.03033 13.5303C3.17098 13.3897 3.25 13.1989 3.25 13V12.75H3.5C4.03043 12.75 4.53914 12.5393 4.91421 12.1642C5.28929 11.7891 5.5 11.2804 5.5 10.75C5.5 10.2196 5.28929 9.71086 4.91421 9.33579C4.53914 8.96071 4.03043 8.75 3.5 8.75ZM3.5 11.25H3.25V10.25H3.5C3.63261 10.25 3.75979 10.3027 3.85355 10.3964C3.94732 10.4902 4 10.6174 4 10.75C4 10.8826 3.94732 11.0098 3.85355 11.1036C3.75979 11.1973 3.63261 11.25 3.5 11.25ZM14.5 12.5544C14.5001 12.7476 14.4255 12.9335 14.2919 13.0731C14.0945 13.285 13.856 13.4544 13.5908 13.5708C13.3257 13.6872 13.0396 13.7482 12.75 13.75C11.5094 13.75 10.5 12.6281 10.5 11.25C10.5 9.87187 11.5094 8.75 12.75 8.75C13.1673 8.75121 13.5746 8.87748 13.9194 9.1125C14.0034 9.1665 14.0759 9.23676 14.1324 9.31914C14.1889 9.40152 14.2284 9.49436 14.2486 9.59222C14.2687 9.69008 14.2691 9.79098 14.2497 9.88899C14.2304 9.98701 14.1916 10.0802 14.1357 10.163C14.0798 10.2458 14.008 10.3166 13.9243 10.3713C13.8407 10.426 13.747 10.4634 13.6487 10.4813C13.5504 10.4992 13.4495 10.4974 13.352 10.4758C13.2544 10.4542 13.1622 10.4134 13.0806 10.3556C12.9836 10.2879 12.8683 10.2511 12.75 10.25C12.3438 10.25 12 10.7081 12 11.25C12 11.7919 12.3438 12.25 12.75 12.25C12.8073 12.2499 12.8642 12.241 12.9187 12.2238C12.8292 12.1138 12.7726 11.9807 12.7556 11.8399C12.7386 11.6991 12.7619 11.5563 12.8227 11.4282C12.8836 11.3001 12.9795 11.1919 13.0994 11.1161C13.2193 11.0403 13.3582 11 13.5 11H13.75C13.9489 11 14.1397 11.079 14.2803 11.2197C14.421 11.3603 14.5 11.5511 14.5 11.75V12.5544ZM10 9.5V13C10 13.1589 9.94955 13.3138 9.85586 13.4422C9.76218 13.5706 9.63012 13.6659 9.47875 13.7144C9.40477 13.7379 9.32762 13.7499 9.25 13.75C9.13081 13.7501 9.0133 13.7219 8.90722 13.6675C8.80113 13.6132 8.70953 13.5343 8.64 13.4375L7.5 11.84V13C7.5 13.1989 7.42098 13.3897 7.28033 13.5303C7.13968 13.671 6.94891 13.75 6.75 13.75C6.55109 13.75 6.36032 13.671 6.21967 13.5303C6.07902 13.3897 6 13.1989 6 13V9.5C5.99976 9.34104 6.05002 9.18612 6.14354 9.05759C6.23706 8.92905 6.369 8.83356 6.52032 8.78488C6.67164 8.7362 6.83451 8.73686 6.98543 8.78676C7.13636 8.83666 7.26752 8.93322 7.36 9.0625L8.5 10.6594V9.5C8.5 9.30109 8.57902 9.11032 8.71967 8.96967C8.86032 8.82902 9.05109 8.75 9.25 8.75C9.44891 8.75 9.63968 8.82902 9.78033 8.96967C9.92098 9.11032 10 9.30109 10 9.5ZM3 7.5C3.19891 7.5 3.38968 7.42098 3.53033 7.28033C3.67098 7.13968 3.75 6.94891 3.75 6.75V2.75H8.5V5.75C8.5 5.94891 8.57902 6.13968 8.71967 6.28033C8.86032 6.42098 9.05109 6.5 9.25 6.5H12.25V6.75C12.25 6.94891 12.329 7.13968 12.4697 7.28033C12.6103 7.42098 12.8011 7.5 13 7.5C13.1989 7.5 13.3897 7.42098 13.5303 7.28033C13.671 7.13968 13.75 6.94891 13.75 6.75V5.5C13.7501 5.40148 13.7307 5.30391 13.6931 5.21286C13.6555 5.12182 13.6003 5.03908 13.5306 4.96938L10.0306 1.46938C9.96092 1.39975 9.87818 1.34454 9.78714 1.3069C9.69609 1.26926 9.59852 1.24992 9.5 1.25H3.5C3.16848 1.25 2.85054 1.3817 2.61612 1.61612C2.3817 1.85054 2.25 2.16848 2.25 2.5V6.75C2.25 6.94891 2.32902 7.13968 2.46967 7.28033C2.61032 7.42098 2.80109 7.5 3 7.5ZM10 3.5625L11.4375 5H10V3.5625Z",fill:t}))}var La=n(97930),Oa=n(58079),Ra=(n(93384),n(19786)),Ha=(n(59509),n(25691),n(23177),n(3142),n(51615),n(84217),n(25953),n(42319),n(28465),n(12887),n(36106),n(84542),n(57068),n(69517),n(85189));const Fa={dismissible:!0},Wa=new class{timeouts=new Map;toasts=new Map;onToastsChange=()=>{};openToast(e,t){this.clearTimeout(e);const n={...Fa,...t,"data-testid":`toast-${e}`,onClose:n=>{this.closeToast(e),t.onClose?.(n)}};if(this.toasts.set(e,n),n.timeout){const t=setTimeout((()=>{this.closeToast(e)}),n.timeout);this.timeouts.set(e,t),t.unref?.()}this.onToastsChange("push",{id:e,...n},this.toasts)}closeToast(e){this.clearTimeout(e),this.toasts.delete(e),this.onToastsChange("pop",{id:e},this.toasts)}clearTimeout(e){e?this.timeouts.has(e)&&(clearTimeout(this.timeouts.get(e)),this.timeouts.delete(e)):(this.timeouts.forEach((e=>{clearTimeout(e)})),this.timeouts.clear())}clear(){this.clearTimeout();const e=Array.from(this.toasts.keys());return this.toasts.clear(),e}},ja=Wa.openToast.bind(Wa),Ba=Wa.closeToast.bind(Wa),za=({children:e})=>{const t=St((0,Ha.dj)()),n=ge((()=>(Wa.onToastsChange=(e,n)=>{"push"===e&&t.current.pushToast({...n,timeout:null}),"pop"===e&&t.current.popToast(n.id)},Wa)));return(0,o.useEffect)((()=>()=>{const e=n.clear();e?.forEach((e=>{t.current.popToast(e)}))}),[n,t]),s().createElement(s().Fragment,null,e)},_a=s().createContext(!1),$a=({children:e})=>{const t=B(),n=(0,o.useMemo)((()=>{const e=t?.zIndex?t.zIndex-1:1;return(0,r.AH)({zIndex:e})}),[t]);return(0,o.useContext)(_a)?s().createElement(s().Fragment,null,e):s().createElement(_a.Provider,{value:!0},s().createElement(Ha.tE,{portalClassName:n},s().createElement(za,null,e)))},Ya=({className:e,direction:t})=>1===t?s().createElement(h.Ay,{className:e,glyph:"ArrowUp",size:"small","aria-label":"Ascending index"}):-1===t?s().createElement(h.Ay,{className:e,glyph:"ArrowDown",size:"small","aria-label":"Descending index"}):s().createElement("span",{className:e},"(",String(t),")"),Ka=(0,r.AH)({maxHeight:`calc(100vh - 2 * ${ce.YK[600]}px)`,maxWidth:`calc(100vw - 2 * ${ce.YK[800]}px)`,letterSpacing:0,padding:0,transform:"none","&:not([open])":{pointerEvents:"none"}}),Ga=(0,r.AH)({height:"auto",width:"100%","& > div":{height:"100%",maxHeight:"100%"}}),Va=z((function({className:e,children:t,fullScreen:n=!1,...a}){return s().createElement(x.aF,(0,i.A)({className:(0,r.cx)(Ka,{[Ga]:n&&a.open},e),initialFocus:null},a),s().createElement(H.nB,{as:"div"},t))})),Ua=_.KT.Primary,qa=_.KT.Danger,Za=(0,r.AH)({padding:`0 ${ce.YK[800]}px`,paddingBottom:ce.YK[100],fontFamily:ce.aI.default,fontSize:"13px",lineHeight:"20px",maxHeight:`calc(100vh - ${5*ce.YK[1600]}px)`,overflow:"auto","&:first-child":{paddingTop:ce.YK[800]}}),Ja={[Ua]:(0,r.AH)({}),[qa]:(0,r.AH)({paddingLeft:"78px"})},Qa=(0,r.AH)({paddingBottom:ce.YK[400]}),Xa=(0,o.forwardRef)((function({variant:e=Ua,className:t,scroll:n=!0,minHeight:a,children:i},o){const l=pe(),c={};return a&&(c.minHeight=`${a}px`),!1===n&&(c.overflow="visible"),s().createElement("div",{className:(0,r.cx)(Za,Ja[e],l&&Qa,t),style:c,ref:o},i)})),er={Default:_.KT.Primary,Danger:_.KT.Danger},tr=(0,r.AH)({padding:ce.YK[800],paddingBottom:0}),nr={[er.Default]:(0,r.AH)({}),[er.Danger]:(0,r.AH)({paddingLeft:"78px"})},ar=(0,r.AH)({fontSize:"24px",fontWeight:700,lineHeight:"32px",margin:0,marginBottom:"10px",color:le.M.black}),rr=(0,r.AH)({fontWeight:"bold",color:le.M.gray.light2}),ir=(0,r.AH)({width:"32px",height:"32px",borderRadius:"50%",background:`${le.M.red.light3}`,display:"flex",alignItems:"center",justifyContent:"center",position:"absolute",left:"36px",top:"32px",svg:{marginTop:"-3px"}}),or=(0,r.AH)({background:`${le.M.red.dark2}`});function sr({title:e,subtitle:t,variant:n=er.Default}){const a=pe();return s().createElement("div",{className:(0,r.cx)(tr,nr[n])},n===er.Danger&&s().createElement("div",{className:(0,r.cx)(ir,a&&or)},s().createElement(ie,{glyph:"Warning",fill:a?le.M.red.light3:le.M.red.base,role:"presentation"})),s().createElement("h1",{className:(0,r.cx)(ar,a&&rr),"data-testid":"modal-title",id:"modal-title"},e),t&&s().createElement(H.nB,null,t))}const lr=(0,r.AH)({display:"flex",justifyContent:"flex-end",gap:ce.YK[200]}),cr={Default:_.KT.Primary,Danger:_.KT.Danger};function dr({title:e,subtitle:t,submitButtonText:n,cancelButtonText:a="Cancel",submitDisabled:r=!1,variant:o=cr.Default,scroll:l=!0,minBodyHeight:c,onSubmit:d,onCancel:u,children:p,...m}){return s().createElement(Va,(0,i.A)({setOpen:u},m),s().createElement("form",{onSubmit:e=>{e.preventDefault(),d()}},s().createElement(sr,{title:e,subtitle:t,variant:o}),s().createElement(Xa,{variant:o,scroll:l,minHeight:c},p),s().createElement(x.wi,{className:lr},s().createElement(J,{"data-testid":"cancel-button",onClick:u,variant:"default"},a),s().createElement(J,{"data-testid":"submit-button",variant:o,type:"submit",disabled:r},n))))}const ur=(0,r.AH)({paddingBottom:ce.YK[800]});function pr({title:e,subtitle:t,showCloseButton:n=!0,closeButtonText:a="Close",onClose:o,children:l,...c}){return s().createElement(Va,(0,i.A)({setOpen:o,className:(0,r.cx)(!n&&ur)},c),s().createElement(sr,{title:e,subtitle:t}),s().createElement(Xa,null,l),n&&s().createElement(x.wi,null,s().createElement(J,{"data-testid":"close-button",onClick:o,variant:"default"},a)))}n(64424);const mr=(0,r.AH)({"*::-webkit-scrollbar-thumb":{backgroundColor:"transparent",borderRadius:"10px"},"*::-webkit-scrollbar-track":{backgroundColor:"transparent"},"*::-webkit-scrollbar":{width:"10px","&:horizontal":{height:"10px"}},"*::-webkit-scrollbar-corner":{background:"transparent"}});(0,r.AH)({"*:active::-webkit-scrollbar-thumb, *:focus::-webkit-scrollbar-thumb, *:hover::-webkit-scrollbar-thumb":{backgroundColor:(0,xn.B3)(le.M.black,.12),"&:hover":{backgroundColor:(0,xn.B3)(le.M.black,.2)}},"*::-webkit-scrollbar-thumb":{"&:horizontal":{backgroundColor:(0,xn.B3)(le.M.black,.12)}},"*::-webkit-scrollbar-track":{"&:hover":{backgroundColor:(0,xn.B3)(le.M.black,.04)}}},mr),(0,r.AH)({"*:active::-webkit-scrollbar-thumb, *:focus::-webkit-scrollbar-thumb, *:hover::-webkit-scrollbar-thumb":{backgroundColor:(0,xn.B3)(le.M.white,.2),"&:hover":{backgroundColor:(0,xn.B3)(le.M.white,.25)}},"*::-webkit-scrollbar-thumb":{"&:horizontal":{backgroundColor:(0,xn.B3)(le.M.white,.2)}},"*::-webkit-scrollbar-track":{"&:hover":{backgroundColor:(0,xn.B3)(le.M.white,.1)}}},mr);const gr=(e,t=250)=>{const n=(0,o.useRef)(0),a=(0,o.useRef)(null),[r,i]=(0,o.useState)(e);return(0,o.useEffect)((()=>{const r=Date.now()-n.current,o=()=>{n.current=Date.now(),i(e)};if(r>=t)o();else{a.current&&clearTimeout(a.current);const e=t-r;a.current=setTimeout(o,e)}return()=>{a.current&&(clearTimeout(a.current),a.current=null)}}),[e,t]),r};n(21261),n(92879),n(31977),n(49743),n(9656),n(72673),n(35467),n(94476),n(64971),n(24330),n(83478),n(65166),n(1256),n(61038),n(73035),n(23855);var hr=n(50022),fr=n.n(hr);const yr=ce.YK[200],br=(0,r.AH)({display:"flex",flexDirection:"column",height:"100%",alignItems:"center",borderRadius:yr,boxShadow:`0px 2px 4px -1px ${(0,xn.B3)(le.M.black,.15)}`,border:"1px solid",overflow:"hidden",width:"fit-content"}),vr=(0,r.AH)({borderColor:le.M.gray.light2,backgroundColor:le.M.gray.light3,color:le.M.gray.dark2}),xr=(0,r.AH)({borderColor:le.M.gray.dark2,backgroundColor:le.M.black,color:le.M.white}),Er=(0,r.AH)({position:"absolute",top:ce.YK[200],right:ce.YK[200]});function Cr({className:e,children:t,trigger:n,hideCloseButton:a=!1,customFocusTrapFallback:i,open:l,setOpen:c,containedElements:d=[],align:u,justify:p,spacing:m,popoverZIndex:g,containerClassName:h,closeButtonClassName:f}){const y=pe(),b=(0,o.useRef)(null),v=(0,o.useRef)(null),x=(0,o.useRef)(null),E=(0,o.useCallback)((()=>{c(!1),setTimeout((()=>{b.current?.focus()}))}),[c]),C=(0,o.useCallback)((e=>{if(l){if(d.some((t=>document.querySelector(t)?.contains(e.target))))return;E()}else c(!l)}),[l,c,E,d]);(0,o.useEffect)((()=>{if(!l)return;const e=e=>{x.current&&!x.current.contains(e.target)&&b.current&&!b.current.contains(e.target)&&(d.some((t=>document.querySelector(t)?.contains(e.target)))||E())};return window.addEventListener("mousedown",e),window.addEventListener("touchstart",e),()=>{window.removeEventListener("mousedown",e),window.removeEventListener("touchstart",e)}}),[l,E,d]),Nn("Escape",E,{enabled:l},[E]);const I="close-button-id";return n({onClick:C,ref:b,children:s().createElement(w.AM,{align:u??"bottom",justify:p??"start",active:l,adjustOnMutation:!0,renderMode:"portal",spacing:m??0,className:e,refEl:b,popoverZIndex:g},s().createElement(fr(),{active:l,focusTrapOptions:{clickOutsideDeactivates:!0,fallbackFocus:i||`#${I}`}},s().createElement("div",{className:(0,r.cx)(br,y?xr:vr,h),ref:x},t,!a&&s().createElement(Q,{as:"button",className:(0,r.cx)(Er,f),"data-testid":"interactive-popover-close-button",onClick:e=>{e.stopPropagation(),E()},"aria-label":"Close",id:I,ref:v},s().createElement(ie,{glyph:"X"})))))})}class wr extends Error{name="UnregisteredGroup";constructor(e){super(`Group ${e} not registered.`)}}class Ir extends Error{name="GroupStepsComplete";constructor(e,t){super(`Group ${e} has already ${t} step(s). Can not add another one.`)}}class Sr extends Error{name="InvalidCueStep";constructor(e,t,n){super(`Group ${e} has only ${t} steps. Can not add another with step:${n}.`)}}class Ar extends Error{name="DuplicateCueStep";constructor(e,t){super(`Group ${e} already has Cue with step ${t} registered.`)}}const kr=new Map([].map((({id:e,steps:t})=>[e,t])));var Dr=n(90605);class Nr extends EventTarget{_cues=[];_activeGroupId=null;_activeCue=null;_storage;constructor(e){super(),this._storage=e}addCue(e){if(-1===this.getCueIndex(e.cueId,e.groupId))return e.groupId&&this.validateCueData(e.groupId,e.step),this._cues.push({...e,isVisited:this._storage.isCueVisited(e.cueId,e.groupId)}),this._activeCue?this.dispatchShowCueEvent():this.onNext();console.warn(`The Cue ${e.cueId} is already added.`)}dispatchShowCueEvent(){if(this._activeCue)return this.dispatchEvent(new CustomEvent("show-cue",{detail:{cueId:this._activeCue.cueId,groupId:this._activeCue.groupId}}))}validateCueData(e,t){if(!kr.has(e))throw new wr(e);const n=this._cues.filter((t=>t.groupId===e)),a=kr.get(e);if(n.length>=a)throw new Ir(e,a);if(t>a)throw new Sr(e,a,t);if(n.find((e=>e.step===t)))throw new Ar(e,t)}removeCue(e,t){const n=this._cues.findIndex((n=>n.cueId===e&&n.groupId===t));-1!==n&&(this._cues.splice(n,1),this._activeCue?.cueId===e&&this._activeCue.groupId===t&&(this._activeCue=null))}onNext(){return this._activeCue=this.findNextCue(),this.dispatchShowCueEvent()}getCountOfSteps(e){return e&&this._cues.filter((t=>t.groupId===e)).length||1}findNextCue(){if(this._activeGroupId){const e=this.getNextCueFromGroup(this._activeGroupId);if(e)return e}const e=this.getNextCueFromNextGroup();return this._activeGroupId=e?.groupId||null,e}getNextCueFromGroup(e){const t=this._cues.filter((t=>t.groupId===e));if(t.length!==kr.get(e))return null;const n=t.filter((e=>!e.isVisited&&e.isIntersecting));return 0===n.length?null:(n.sort(((e,t)=>e.step-t.step)),n[0])}getNextCueFromNextGroup(){let e=0;for(;e<this._cues.length;){const t=this._cues[e];if(t.groupId){const e=this.getNextCueFromGroup(t.groupId);if(e)return e}else if(!t.isVisited&&t.isIntersecting)return t;e++}return null}getCueIndex(e,t){return this._cues.findIndex((n=>n.cueId===e&&n.groupId===t))}markCueAsVisited(e,t){const n=this.getCueIndex(e,t);-1!==n&&(this._cues[n].isVisited=!0,this._storage.markCueAsVisited(e,t),this._activeCue=null)}markGroupAsVisited(e){const t=this._cues.filter((t=>t.groupId===e));t.length===kr.get(e)&&t.forEach((({cueId:t})=>{this.markCueAsVisited(t,e)})),this._activeGroupId=null,this._activeCue=null}markAllCuesAsVisited(){this._cues.filter((e=>!e.groupId)).forEach((({cueId:e,groupId:t})=>{this.markCueAsVisited(e,t)})),(0,Dr.uniq)(this._cues.map((e=>e.groupId))).filter(Boolean).forEach((e=>this.markGroupAsVisited(e)))}onCueIntersectionChange(e,t,n){const a=this.getCueIndex(t,n);if(-1===a)return;this._cues[a].isIntersecting=e;const r=!this._activeCue&&e;return this._activeCue?.cueId===t&&this._activeCue.groupId===n&&!e||r?this.onNext():void 0}addEventListener(e,t){return super.addEventListener(e,t)}removeEventListener(e,t){return super.removeEventListener(e,t)}}const Mr=new Nr(new class{storage;key;constructor(e=globalThis.localStorage,t="compass_guide_cues"){this.storage=e,this.key=t}get data(){try{return JSON.parse(this.storage.getItem(this.key)??"[]")}catch{return[]}}set data(e){this.storage.setItem(this.key,JSON.stringify(e))}isCueVisited(e,t){return!!this.data.find((n=>n.cueId===e&&n.groupId===t))}markCueAsVisited(e,t){if(!this.isCueVisited(e,t)){const n=this.data;n.push({groupId:t,cueId:e}),this.data=n}}});function Tr(e){const t=new AbortController;return requestAnimationFrame((()=>{requestAnimationFrame((n=>{t.signal.aborted||e(n)}))})),()=>{t.abort()}}const Pr=(0,r.AH)({display:"none !important",opacity:"0 !important",transition:"none !important"}),Lr=s().createContext({}),Or=({children:e,disabled:t=!1,...n})=>{const a=St(n),r=(0,o.useMemo)((()=>({onNext(e){a.current.onNext?.(e)},onNextGroup(e){a.current.onNextGroup?.(e)},disabled:t})),[t,a]);return s().createElement(Lr.Provider,{value:r},e)},Rr=({cueId:e,groupId:t})=>`guide-cue-${e}${t?`-${t}`:""}`,Hr=({description:e,trigger:t,triggerNode:n,cueId:a,groupId:l,step:c,onPrimaryButtonClick:d,onDismiss:u,onOpenChange:p,...m})=>{const[g,h]=(0,o.useState)(!1),[f,y]=(0,o.useState)(!0),b=(0,o.useRef)(n??null),[v,x]=(0,o.useState)(!1),E=(0,o.useContext)(Lr),C=(0,o.useMemo)((()=>l?{cueId:a,groupId:l,step:c}:{cueId:a,step:1}),[a,l,c]),w=(0,o.useCallback)((e=>{h(e),p?.(e)}),[p]);(0,o.useEffect)((()=>{if(!b.current)return;const e=b.current,t=new IntersectionObserver((e=>{const[t]=e;y(t.isIntersecting),t.isIntersecting||w(!1),Mr.onCueIntersectionChange(t.isIntersecting,C.cueId,C.groupId)}),{threshold:.5});return t.observe(e),()=>{t.unobserve(e),t.disconnect()}}),[C,w]),(0,o.useEffect)((()=>{const e=({detail:e})=>{w(C.cueId===e.cueId&&C.groupId===e.groupId&&f)};return Mr.addEventListener("show-cue",e),()=>{Mr.removeEventListener("show-cue",e)}}),[C,f,w]),(0,o.useEffect)((()=>{if(b.current)return Mr.addCue({...C,isIntersecting:f}),()=>{Mr.removeCue(C.cueId,C.groupId)}}),[C,f]),(0,o.useEffect)((()=>Tr((()=>{x(!0)}))),[]);const I=(0,o.useCallback)((()=>{C.groupId&&(Mr.markGroupAsVisited(C.groupId),Mr.onNext(),E.onNextGroup?.({...C,groupSteps:kr.get(C.groupId)??0}))}),[C,E.onNextGroup]),S=(0,o.useCallback)((()=>{Mr.markCueAsVisited(C.cueId,C.groupId),Mr.onNext(),E.onNext?.(C)}),[C,E.onNext]);(0,o.useEffect)((()=>{if(!g||!b.current)return;const e=e=>{const t=document.querySelector(`[data-cueid="${Rr(C)}"]`);if(t&&!e.composedPath().includes(t)){if(e.composedPath().includes(b.current))return w(!1),S();Mr.markAllCuesAsVisited(),w(!1)}};return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}}),[g,C,S,w]);const A=E.disabled;return s().createElement(s().Fragment,null,v&&s().createElement(La._9,(0,i.A)({},m,{open:!A&&g,numberOfSteps:Mr.getCountOfSteps(C.groupId),onDismiss:()=>{u?.(),I()},onPrimaryButtonClick:()=>{d?.(),S()},setOpen:()=>w(!1),currentStep:C.step||1,refEl:b,"data-cueid":Rr(C),tooltipClassName:(0,r.cx)(!f&&Pr)}),e),t?.({ref:b}))},Fr=Symbol("Value changed");function Wr(e,t){const n=(0,o.useRef)(t),a=(0,o.useRef)(e);var r;return a.current=e,(0,o.useEffect)((()=>{if(t!==n.current)return n.current=Fr,a.current()}),(r=t,(0,o.useMemo)((()=>Array.isArray(r)?r:[r]),Array.isArray(r)?r:[r]))),(0,o.useRef)(t)}const jr=s().createContext({onSignalMount(){},onSignalOpen(){},onSignalLinkClick(){},onSignalPrimaryActionClick(){},onSignalClose(){},onAssistantButtonClick(){}}),Br=({children:e,...t})=>{const n=St(t),a=(0,o.useMemo)((()=>({onSignalMount(e){n.current.onSignalMount?.(e)},onSignalOpen(e){n.current.onSignalOpen?.(e)},onSignalLinkClick(e){n.current.onSignalLinkClick?.(e)},onSignalPrimaryActionClick(e){n.current.onSignalPrimaryActionClick?.(e)},onSignalClose(e){n.current.onSignalClose?.(e)},onAssistantButtonClick(){n.current.onAssistantButtonClick?.()}})),[n]);return s().createElement(jr.Provider,{value:a},e)},zr=(0,r.AH)({"--signalCardBackgroundColor":le.M.white,width:"100%",display:"grid",gridTemplateColumns:"1fr",gridTemplateRows:"auto 1fr auto",paddingTop:ce.YK[600],paddingBottom:ce.YK[600],paddingLeft:ce.YK[600],paddingRight:ce.YK[600],backgroundColor:"var(--signalCardBackgroundColor)"}),_r=(0,r.AH)({"--signalCardBackgroundColor":le.M.gray.dark4}),$r=(0,r.AH)({marginBottom:ce.YK[200],fontSize:ce.YK[400]}),Yr=(0,r.AH)({paddingRight:18}),Kr=(0,r.AH)({marginBottom:ce.YK[400]}),Gr=(0,r.AH)({display:"flex",justifyContent:"space-between",gap:ce.YK[200]}),Vr=(0,r.AH)({flex:"none",whiteSpace:"nowrap"}),Ur=(0,r.AH)({flex:"none"}),qr=({id:e,title:t,description:n,learnMoreLink:a,learnMoreLabel:i,primaryActionButtonLabel:l,primaryActionButtonIcon:c,primaryActionButtonVariant:d,primaryActionButtonIsLoading:u,primaryActionButtonLink:p,onAssistantButtonClick:m,darkMode:g,onPrimaryActionButtonClick:h,hasMultiSignals:f})=>{const y=pe(g),b=(0,o.useContext)(jr);return s().createElement("div",{className:(0,r.cx)(zr,y&&_r),"data-testid":"insight-signal-card","data-signal-id":e},s().createElement("strong",{className:(0,r.cx)($r,{[Yr]:!f})},t),s().createElement(H.nB,{as:"div",baseFontSize:13,className:Kr},n,m&&a&&s().createElement(s().Fragment,null," ",s().createElement(q,{"data-testid":"insight-signal-link",className:Ur,href:a,target:"_blank",onClick:()=>{b.onSignalLinkClick(e)}},i??"Learn more"))),s().createElement("div",{className:Gr},(l||u)&&s().createElement(J,{size:"small",as:p?"a":"button",target:p?"_blank":void 0,href:p,"data-testid":"insight-signal-primary-action",variant:d??"primaryOutline",className:Vr,isLoading:u,leftGlyph:c?s().createElement(ie,{glyph:c}):void 0,onClick:t=>{b.onSignalPrimaryActionClick(e),h?.(t)}},l),m?s().createElement(J,{size:"small",variant:"default",className:Vr,leftGlyph:s().createElement(ie,{glyph:"Sparkle",style:{color:le.M.green.dark1}}),"data-testid":"tell-me-more-button",onClick:m},"Tell me more"):a?s().createElement(q,{"data-testid":"insight-signal-link",className:Ur,href:a,target:"_blank",onClick:()=>{b.onSignalLinkClick(e)}},i??"Learn more"):null))},Zr=(0,r.AH)({"--multiSignalHeaderBorderColor":le.M.gray.light2,"--multiSignalHeaderBackgroundColor":le.M.gray.light3,display:"flex",alignItems:"center",paddingTop:ce.YK[100],paddingBottom:ce.YK[100],paddingLeft:ce.YK[200],paddingRight:ce.YK[600],gap:ce.YK[100],backgroundColor:"var(--multiSignalHeaderBackgroundColor)",boxShadow:"inset 0 -1px 0 var(--multiSignalHeaderBorderColor)",fontVariantNumeric:"tabular-nums"}),Jr=(0,r.AH)({"--multiSignalHeaderBorderColor":le.M.gray.dark2,"--multiSignalHeaderBackgroundColor":le.M.gray.dark3}),Qr=({currentIndex:e,total:t,onIndexChange:n,darkMode:a})=>{const i=pe(a);return s().createElement("div",{className:(0,r.cx)(Zr,i&&Jr)},s().createElement(Q,{as:"button","data-testid":"insight-signal-show-prev-button","aria-label":"Show previous insight",title:"Show previous insight",onClick:t=>{t.stopPropagation(),n(e-1)},disabled:0===e},s().createElement(ie,{glyph:"ChevronLeft"})),s().createElement("span",null,"Insight ",s().createElement("strong",null,e+1)," of ",s().createElement("strong",null,t)),s().createElement(Q,{as:"button","data-testid":"insight-signal-show-next-button","aria-label":"Show next insight",title:"Show next insight",onClick:t=>{t.stopPropagation(),n(e+1)},disabled:e===t-1},s().createElement(ie,{glyph:"ChevronRight"})))},Xr=(0,r.AH)({width:315}),ei=(0,r.AH)({display:"none !important",opacity:"0 !important",transition:"none !important"}),ti=(0,r.AH)({display:"block"}),ni=(0,r.AH)({transitionProperty:"opacity, width, border-radius, color, box-shadow, background-color",transitionTimingFunction:"linear",transitionDuration:"150ms"}),ai=(0,r.AH)({padding:0,border:"none",background:"none"},{position:"relative",display:"block",width:18,height:18,color:"var(--badgeColor)",backgroundColor:"var(--badgeBackgroundColor)",boxShadow:"inset 0 0 0 1px var(--badgeBorderColor)",borderRadius:"9px",fontSize:"12px",lineHeight:"14px",fontWeight:700,overflow:"hidden",cursor:"pointer"},ni),ri=(0,r.AH)({"--badgeBackgroundColor":le.M.blue.light3,"--badgeBorderColor":le.M.blue.light2,"--badgeColor":le.M.blue.dark1}),ii=(0,r.AH)({"--badgeBackgroundColor":le.M.blue.dark2,"--badgeBorderColor":le.M.blue.dark1,"--badgeColor":le.M.blue.light2}),oi=(0,r.AH)({borderRadius:5}),si=(0,r.AH)({"--badgeBackgroundColor":le.M.blue.light1,"--badgeBorderColor":le.M.blue.dark1,"--badgeColor":le.M.white,borderRadius:5}),li=(0,r.AH)({"--badgeBackgroundColor":le.M.blue.dark1,"--badgeBorderColor":le.M.blue.base,"--badgeColor":le.M.blue.light3}),ci=(0,r.AH)({}),di=(0,r.AH)({position:"absolute",top:2,left:2},ni),ui=(0,r.AH)({position:"absolute",display:"flex",alignItems:"center",justifyContent:"center",textTransform:"uppercase",top:2},ni),pi=(0,r.AH)({justifyContent:"flex-start",paddingLeft:2}),mi=(0,r.AH)({top:18,right:18}),gi=(0,r.AH)({top:5,right:5}),hi=({signals:e,darkMode:t,onPopoverOpenChange:n,className:a})=>{const l=(0,o.useContext)(jr),c=pe(t),[d,u]=(0,o.useState)(!0),[p,m]=(0,o.useState)(!1),[g,h,f]=kn(),[y,b]=(0,o.useState)(0),v=Array.isArray(e)?e:[e],x=v[y],E=v.length>1,C=h||p,w=(0,o.useRef)(null),I=ge(new Set);v.forEach((({id:e})=>{I.has(e)||(l.onSignalMount(e),I.add(e))})),Wr((()=>{p?l.onSignalOpen(x.id):l.onSignalClose(x.id)}),[x.id,p]),(0,o.useLayoutEffect)((()=>{if(!w.current)return;const e=new IntersectionObserver((e=>{const t=e[0].isIntersecting;u(t),t||m(!1)}));return e.observe(w.current),e.disconnect.bind(e)}),[]);const S=(0,o.useCallback)((e=>{m(e),n?.(e),!0===e&&b(0)}),[n]),A=E?s().createElement(s().Fragment,null,v.length," insights"):s().createElement(s().Fragment,null,s().createElement(ie,{glyph:"Bulb",size:"small"})," insight"),k=E?`${`${v.length} insights`.length}ch`:"calc(14px + 8ch)";return s().createElement(Cr,{className:(0,r.cx)(Xr,!d&&ei),containerClassName:(0,r.cx)(ti),closeButtonClassName:E?gi:mi,open:p,setOpen:S,spacing:ce.YK[200],trigger:({children:e,...t})=>{const n=e=>{e.stopPropagation(),t.onClick(e)};return s().createElement(Hr,{cueId:"insights",title:"Introducing insights",description:"Across Compass, you may now see icons like this to clue you in on potential areas of improvement for your data.",buttonText:"See insights in action",onPrimaryButtonClick:()=>{f(!0),setTimeout((()=>{Tr((()=>{w.current?.click()}))}),150)},trigger:({ref:o})=>{const l=$e(g,t,{className:(0,r.cx)(ai,C&&oi,...c?[ii,C&&li]:[ri,C&&si],a),style:{width:C?k:18},ref:w},{ref:o});return s().createElement(s().Fragment,null,s().createElement("button",(0,i.A)({},l,{onClick:n,"data-testid":"insight-badge-button",type:"button"}),s().createElement(ie,{glyph:"Bulb",size:"small",className:(0,r.cx)(ci,di),"data-testid":"insight-badge-icon",style:{opacity:C?0:1}}),s().createElement("strong",{className:(0,r.cx)(ui,!E&&pi),"data-testid":"insight-badge-text",style:{width:k,opacity:C?1:0}},A)),e)}})}},s().createElement("div",{onMouseDown:e=>{e.stopPropagation()}},E&&s().createElement(Qr,{currentIndex:y,total:v.length,onIndexChange:b,darkMode:c}),s().createElement(qr,(0,i.A)({},x,{onAssistantButtonClick:x.onAssistantButtonClick?e=>{x.onAssistantButtonClick?.(e),m(!1)}:void 0,darkMode:c,hasMultiSignals:E}))))},fi=(0,r.AH)({display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center",margin:`${ce.YK[400]}px auto`,marginTop:ce.YK[7],padding:`0 ${ce.YK[400]}px`}),yi=(0,r.AH)({flex:"none",maxWidth:"80px",maxHeight:"80px"}),bi=(0,r.AH)({marginTop:ce.YK[200]}),vi=(0,r.AH)({color:le.M.green.dark2}),xi=(0,r.AH)({color:le.M.green.light1}),Ei=(0,r.AH)({marginTop:ce.YK[200],maxWidth:6*ce.YK[1600]}),Ci=(0,r.AH)({marginTop:ce.YK[600],maxWidth:"600px"}),wi=(0,r.AH)({marginTop:ce.YK[400],maxWidth:"600px"}),Ii=({icon:e,title:t,subTitle:n,callToAction:a,callToActionLink:i,containerClassName:o,titleClassName:l,subTitleClassName:c})=>{const d=pe();return s().createElement("div",{"data-testid":"empty-content",className:(0,r.cx)(fi,o)},e&&s().createElement("div",{className:(0,r.cx)(yi,"darkreader-ignore-child-inline-style")},s().createElement(e,null)),s().createElement(H.Pd,{className:(0,r.cx)(bi,d?xi:vi,l)},t),n&&s().createElement(H.nB,{className:(0,r.cx)(Ei,c)},n),!!a&&s().createElement("div",{className:Ci},"string"==typeof a?s().createElement(H.nB,null,a):s().createElement(s().Fragment,null,a)),!!i&&s().createElement("div",{className:a?wi:Ci},i))};var Si=n(15088).process;const Ai=(0,r.AH)({padding:ce.YK[400],width:"100%"});class ki extends s().Component{state={error:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){this.props.onError&&this.props.onError(e,t)}render(){const{className:e,displayName:t}=this.props,{error:n}=this.state;return n?s().createElement("div",{className:(0,r.cx)(Ai,e)},s().createElement(d.lZ,{variant:"danger"},"An error occurred while rendering",t?` ${t}`:"",": ",n.message)):this.props.children}}const Di=e=>"true"===Si?.env?.COMPASS_DISABLE_ERROR_BOUNDARY?s().createElement(s().Fragment,null,e.children):s().createElement(ki,e),Ni=(0,r.AH)({minWidth:4*ce.YK[7]}),Mi=({onSubmitFeedback:e,label:t,placeholder:n,setOpen:a,refEl:r,open:l,...c})=>{const[d,u]=(0,o.useState)(""),p=(0,_e.Bi)();(0,o.useEffect)((()=>{if(!l)return;const t=t=>{const n=document.querySelector(`[data-popoverid="feedback-popover-${p}"]`);n&&(t.composedPath().includes(n)||t.composedPath().includes(r.current)||(e(""),a(!1)))};return document.addEventListener("mousedown",t),()=>{document.removeEventListener("mousedown",t)}}),[p,l,a,r]);const m=(0,o.useCallback)((t=>{"Enter"!==t.key||t.shiftKey?"Escape"===t.key&&(t.preventDefault(),e(""),a(!1)):(t.preventDefault(),e(d))}),[d,a,e]);return s().createElement(La._9,(0,i.A)({tooltipClassName:Ni,numberOfSteps:1,currentStep:1,"data-popoverid":`feedback-popover-${p}`,title:"",tooltipAlign:"bottom",refEl:r,onPrimaryButtonClick:()=>e(d),buttonText:"Submit",setOpen:a,open:l},c),s().createElement(M.fs,{label:t,"data-testid":"feedback-popover-textarea",placeholder:n,value:d,onChange:e=>u(e.target.value),onKeyDown:m}))},Ti=(0,r.AH)({flexGrow:1,display:"flex",flexDirection:"column",alignItems:"stretch",overflow:"hidden"}),Pi=(0,r.AH)({flex:"none",padding:`0 ${ce.YK[400]}px`}),Li=(0,r.AH)({background:le.M.black}),Oi=(0,r.AH)({background:le.M.white}),Ri=(0,r.AH)({display:"flex",flex:1,minHeight:0});function Hi({"data-testid":e,"aria-label":t,activeTabIndex:n,onTabClicked:a,tabs:i}){const o=pe();return s().createElement("div",{className:Ti},s().createElement("div",{className:(0,r.cx)(Pi,o?Li:Oi)},s().createElement(N.tU,{"data-testid":e,"aria-label":t,className:"test-tab-nav-bar-tabs",onValueChange:a,value:n},i.map((({name:e,title:t},n)=>s().createElement(N.oz,{className:"test-tab-nav-bar-tab",key:`tab-${n}`,"data-testid":`${e}-tab-button`,name:t}))))),i.map((({name:e,content:t},a)=>{if(a===n)return s().createElement("div",{className:Ri,key:`tab-content-${e}`,"data-testid":`${e.toLowerCase().replace(/ /g,"-")}-content`},t)})))}const Fi=(0,r.AH)({marginTop:-ce.YK[200],marginBottom:-ce.YK[200]});function Wi(e){const{"aria-label":t,href:n}=e;return s().createElement(s().Fragment,null,s().createElement(Q,{as:"a",className:Fi,"aria-label":t,href:n,target:"_blank"},s().createElement(ie,{glyph:"InfoWithCircle",size:"small"})))}const ji=(0,r.AH)({display:"flex",flexDirection:"column",gap:ce.YK[200]}),Bi=(0,r.AH)({alignItems:"center",display:"flex",gap:ce.YK[100]}),zi=(0,r.AH)({flexGrow:1});function _i({disableAddButton:e,disableRemoveButton:t,items:n,renderItem:a,onAddItem:i,onRemoveItem:o,addButtonTestId:l,removeButtonTestId:c,className:d,itemTestId:u,itemKey:p}){return s().createElement("div",{className:(0,r.cx)(ji,d)},n.map(((r,d)=>s().createElement("div",{"data-testid":u?.(d),className:Bi,key:p?.(r)??d},s().createElement("div",{className:zi},a(r,d)),e?.(r,d,n)?null:s().createElement(Q,{"aria-label":"Add",type:"button","data-testid":l,disabled:e?.(r,d,n),onClick:()=>i(d)},s().createElement(ie,{glyph:"Plus"})),t?.(r,d,n)||1===n.length?null:s().createElement(Q,{"aria-label":"Remove",type:"button","data-testid":c,disabled:t?.(r,d,n),onClick:()=>o(d)},s().createElement(ie,{glyph:"Minus"}))))))}const $i=e=>(100*e).toFixed(3)+"%",Yi=(0,r.i7)({from:{backgroundPosition:`${$i(4)} 0`},to:{backgroundPosition:"0 0"}}),Ki=(0,r.AH)({alignSelf:"center",borderRadius:3,maxWidth:"80%",backgroundColor:"var(--gradient-start)",backgroundImage:`linear-gradient(\n to right,\n var(--gradient-start) 0%,\n var(--gradient-end) ${$i(.125)},\n var(--gradient-start) ${$i(1/4)},\n var(--gradient-start) 100%\n )`,backgroundSize:`${$i(4)} 100%`,backgroundPosition:"0 0",animation:`${Yi} 4s infinite linear`}),Gi=({className:e,minChar:t=5,maxChar:n=15,width:a,height:l=ce.YK[400],gradientStart:c,gradientEnd:d,style:u,...p})=>{const m=pe(),g=(0,o.useMemo)((()=>{return a||`${Math.round((e=t,r=n,Math.random()*(r-e)+e))}ch`;var e,r}),[t,n,a]),h=(0,o.useMemo)((()=>({width:g,height:l,"--gradient-start":c||(m?le.M.gray.dark2:le.M.gray.light2),"--gradient-end":d||(m?le.M.gray.dark4:le.M.gray.light3),...u})),[m,g,l,c,d,u]);return s().createElement("div",(0,i.A)({},p,{role:"presentation","data-testid":p["data-testid"]??"placeholder",className:(0,r.cx)(Ki,e),style:h}))};var Vi=n(87903);function Ui(e,t){if("string"==typeof t)return e?.closest(t)??null;let n=e;for(;n;){if(t(n))return n;n=n.parentElement}return null}function qi(e){return e?`[data-vlist-item-idx="${e}"]`:"[data-vlist-item-idx]"}function Zi(e){if(!e.dataset.vlistItemIdx)throw new Error("Trying to get vgrid item index from an non-item element");return Number(e.dataset.vlistItemIdx)}const Ji=(0,o.createContext)({headerHeight:0,renderHeader:()=>null,renderItem:()=>null,renderEmptyList:()=>null,itemsCount:0,rowCount:0,colCount:0,currentTabbable:0,gridProps:{}}),Qi=(0,o.forwardRef)((function({style:e,children:t,...n},a){const{headerHeight:r,renderHeader:l,gridProps:c,classNames:d,renderEmptyList:u,itemsCount:p}=(0,o.useContext)(Ji);return s().createElement("div",(0,i.A)({ref:a,style:{...e,height:e.height+r}},n),s().createElement("div",{style:{height:r},className:d?.header},s().createElement(l,{})),s().createElement("div",(0,i.A)({style:{height:e.height}},c),0===p&&u?s().createElement(u,{}):t))})),Xi=(0,r.AH)({display:"grid",alignItems:"stretch",gridTemplateRows:"auto",gridTemplateColumns:"1fr",gridAutoColumns:"1fr",gridAutoFlow:"column"}),eo=(0,r.AH)({width:"100%",minWidth:0}),to=({style:e,index:t})=>{const{colCount:n,itemsCount:a,renderItem:i,currentTabbable:l,classNames:c,itemKey:d}=(0,o.useContext)(Ji),u=t*n,p=(0,o.useMemo)((()=>Array.from({length:n},((e,t)=>{const n=u+t;return n>=a?s().createElement("div",{className:(0,r.cx)(eo,c?.cell),key:`empty${t}`}):s().createElement(i,{key:d?.(n)??n,role:"gridcell",className:(0,r.cx)(eo,c?.cell),tabIndex:n===l?0:-1,"data-vlist-item-idx":n,index:n})}))),[n,u,a,c?.cell,i,d,l]);return s().createElement("div",{style:e,className:(0,r.cx)(Xi,c?.row),role:"row","aria-rowindex":t+1},p)},no=(0,r.AH)({width:"100%",flex:1,overflow:"hidden",display:"grid",gridTemplateRows:"auto 1fr",gridTemplateColumns:"100%",outline:"none"}),ao=(0,r.AH)({position:"relative"}),ro=(0,o.forwardRef)((function({itemMinWidth:e,itemHeight:t,itemsCount:n,colCount:a,renderItem:i,headerHeight:l=0,renderHeader:c=()=>null,renderEmptyList:d,overscanCount:u=3,classNames:p,itemKey:m,resetActiveItemOnBlur:g,...h},f){const y=(0,o.useRef)(null),[b,{width:v,height:x}]=function(){const[e,t]=(0,o.useState)((()=>new DOMRectReadOnly)),n=(0,o.useRef)(null),a=(0,o.useRef)(null);return null===a.current&&(a.current=new ResizeObserver((e=>{t(e[0].contentRect)}))),(0,o.useLayoutEffect)((()=>{if(n.current){const e=n.current;return a.current?.observe(n.current),()=>{a.current?.unobserve(e)}}}),[]),[{ref:n},e]}(),E=Math.max(v,e),C=a??Math.max(1,Math.floor(E/e)),w=Math.ceil(n/C),I=(0,o.useCallback)((e=>{const t=Math.floor(e/C);y.current?.scrollToItem(t)}),[y,C]),[S,A]=function({colCount:e,rowCount:t,itemsCount:n,resetActiveItemOnBlur:a=!0,pageSize:r=3,defaultCurrentTabbable:i=0,onFocusMove:s}){const l=(0,o.useRef)(null),[c,d]=(0,o.useState)(0),[u,p]=(0,o.useState)(i),m={tabIndex:c,onFocus:(0,o.useCallback)((e=>{if(e.target===e.currentTarget)d(-1);else{const t=Ui(e.target,qi());t&&(d(-1),p(Zi(t)))}}),[i]),onBlur:(0,o.useCallback)((()=>{null!==Ui(document.activeElement,(e=>e===l.current))||(d(0),a&&p(i))}),[a,i]),onMouseDown:(0,o.useCallback)((e=>{Ui(e.target,qi())||(e.preventDefault(),document.activeElement?.blur())}),[])},g=(0,o.useCallback)((a=>{const i=a.target;if(l.current&&l.current.contains(i)&&i.dataset.vlistItemIdx){let i=-1;if("ArrowUp"===a.key&&(a.preventDefault(),a.stopPropagation(),i=1===t?u-1:u-e),"ArrowDown"===a.key&&(a.preventDefault(),a.stopPropagation(),i=1===t?u+1:u+e),"ArrowLeft"===a.key&&(a.stopPropagation(),i=u-1),"ArrowRight"===a.key&&(a.stopPropagation(),i=u+1),"Home"===a.key&&(a.preventDefault(),a.stopPropagation(),i=a.ctrlKey?0:e*Math.floor(u/e)),"End"===a.key&&(a.preventDefault(),a.stopPropagation(),i=a.ctrlKey?n-1:e*Math.floor(u/e)+(e-1)),"PageUp"===a.key){a.preventDefault(),a.stopPropagation();const t=Math.floor(u/e),n=Math.min(t,r);i=u-e*n}if("PageDown"===a.key){a.preventDefault(),a.stopPropagation();const n=Math.floor(u/e),o=Math.min(t-1-n,r);i=u+e*o}i!==u&&i>=0&&i<n&&p(i)}}),[u,n,t,e,r]),h=0===c?-1:u;return(0,o.useEffect)((()=>{if(h>=0){const e=Ui(document.activeElement,qi());if(!e||Zi(e)!==h)return s(h),Tr((()=>{l.current?.querySelector(qi(u))?.focus()}))}}),[h]),[{ref:l,onKeyDown:g,...m},h]}({itemsCount:n,colCount:C,rowCount:w,onFocusMove:I,resetActiveItemOnBlur:g}),k=$e({ref:f,className:(0,r.cx)(no,p?.container)},h,b);return s().createElement(Ji.Provider,{value:{rowCount:w,colCount:C,itemsCount:n,renderItem:i,headerHeight:l,renderHeader:c,currentTabbable:A,classNames:p,gridProps:$e({role:"grid","aria-rowcount":w,className:(0,r.cx)(ao,p?.grid)},S),itemKey:m,renderEmptyList:d}},s().createElement("div",k,s().createElement(Vi.Y1,{ref:y,width:E,height:x,innerElementType:Qi,itemCount:w,itemSize:t,overscanCount:u},to)))})),io=(0,r.AH)({display:"flex",alignItems:"center",gap:ce.YK[200]}),oo=(0,r.AH)({margin:"0 !important",padding:"0 !important"}),so=(0,r.AH)({"& > button":{margin:0}});function lo(e,t){const n="sort-by",a=(0,_e.Bi)(),[r,i]=(0,o.useReducer)(((e,t)=>"change-name"===t.type&&t.name!==e.name?{...e,name:t.name}:"change-order"===t.type?{...e,order:-1*e.order}:e),t?.initialState??{name:e[0]?.name??null,order:1});return Wr((()=>{t?.onChange?.(r)}),r),[(0,o.useMemo)((()=>{const o=-1===r.order?"SortDescending":1===r.order?"SortAscending":"Unsorted",l=Math.max(...e.map((e=>e.label.length)));return s().createElement("div",{className:io},s().createElement(H.JU,{id:n,htmlFor:a,className:oo},"Sort by"),s().createElement(k.l6,{disabled:t?.isDisabled,id:a,"aria-labelledby":n,allowDeselect:!1,className:so,style:{minWidth:`calc(${l}ch + ${ce.YK[1600]}px)`},onChange:e=>{i({type:"change-name",name:e||null})},defaultValue:r.name??void 0},e.map((e=>s().createElement(k.c$,{key:e.name,value:e.name},e.label)))),s().createElement(J,{"aria-label":o,title:o,rightGlyph:s().createElement(ie,{glyph:o}),onClick:()=>{i({type:"change-order"})},disabled:null===r.name||t?.isDisabled}))}),[r,e,n,a,t?.isDisabled]),t?.isDisabled?{name:null,order:1}:r]}function co(e,{name:t,order:n},a=null){return(0,o.useMemo)((()=>[...e].sort(((e,r)=>{if(!t)return 0;if(void 0===e[t])return 1;const i=a&&a[t];return i?i(e[t],r[t],n):"string"==typeof e[t]?function(e,t,n){return e.localeCompare(t)*n}(e[t],r[t],n):function(e,t,n){return(e===t?0:e<t?-1:1)*n}(e[t],r[t],n)}))),[e,t,a,n])}const uo=6e4,po=60*uo,mo=24*po,go=7*mo,ho=4*go,fo=new Intl.RelativeTimeFormat("en",{numeric:"auto"}),yo=new Intl.DateTimeFormat("en",{dateStyle:"long"}),bo={second:1e3,minute:uo,hour:po,day:mo,week:go};function vo(e){const t=Date.now()-e;let n=null;if(t<uo)n="second";else if(t<po)n="minute";else if(t<mo)n="hour";else if(t<go)n="day";else{if(!(t<ho))return yo.format(e);n="week"}return fo.format(-Math.round(t/bo[n]),n)}const xo=60,Eo=60*xo,Co=24*Eo,wo=7*Co;function Io(e){const t=e%xo,n=Math.floor(e%Eo/xo),a=Math.floor(e%Co/Eo),r=Math.floor(e%wo/Co),i=Math.floor(e/wo);return new Intl.DurationFormat(void 0,{style:"narrow"}).format({weeks:i,days:r,hours:a,minutes:n,seconds:t})}function So(e,t,n=(e,t)=>e===t){const[a,r]=(0,o.useState)(t);a.some(((e,a)=>!n(e,t[a])))&&(e(),r(t))}function Ao(e){const[t,n]=(0,o.useState)((()=>"number"==typeof e?vo(e):void 0));return So((()=>{n("number"==typeof e?vo(e):void 0)}),[e]),(0,o.useEffect)((()=>{const t=setInterval((()=>{n("number"==typeof e?vo(e):void 0)}),6e4);return()=>{clearInterval(t)}}),[e]),t}var ko=n(67092),Do=n(13353);const No=(0,o.createContext)("");function Mo(){return(0,o.useContext)(No)}function To(e,t=70){const n=e.slice(0,t);return t<e.length?`${n}…`:e}const Po={[ue.Dark]:{Int32:m.u5.dark[9],Double:m.u5.dark[9],Decimal128:m.u5.dark[9],Date:m.u5.dark[9],Boolean:m.u5.dark[10],String:m.u5.dark[7],ObjectId:m.u5.dark[5]},[ue.Light]:{Int32:m.u5.light[9],Double:m.u5.light[9],Decimal128:m.u5.light[9],Date:m.u5.light[9],Boolean:m.u5.light[10],String:m.u5.light[7],ObjectId:m.u5.light[5]}},Lo=(0,r.AH)({whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),Oo=(0,r.AH)({whiteSpace:"pre-wrap"}),Ro=({type:e,children:t,className:n,...a})=>{const l=pe(),c=(0,o.useMemo)((()=>{if(e)return{color:Po[l?ue.Dark:ue.Light][e]}}),[e,l]);return s().createElement("div",(0,i.A)({},a,{className:(0,r.cx)(n,Lo,"String"===e&&Oo,`element-value element-value-is-${e?e.toLowerCase():"unknown"}`),style:c}),t)},Ho=(0,r.AH)({userSelect:"none"}),Fo=(0,r.AH)({color:"inherit",marginLeft:ce.YK[100]}),Wo=({value:e})=>{const t=(0,o.useMemo)((()=>String(e)),[e]);return s().createElement(Ro,{type:"ObjectId",title:t},s().createElement("span",{className:Ho},"ObjectId('"),t,s().createElement("span",{className:Ho},"')"))},jo=({value:e})=>{const t=e.toString("hex"),n=(0,ko.j$)(t);return"LegacyJavaUUID('"+(0,ko.P6)(n)+"')"},Bo=({value:e})=>{const t=e.toString("hex"),n=(0,ko.q2)(t);return"LegacyCSharpUUID('"+(0,ko.P6)(n)+"')"},zo=({value:e})=>{const t=e.toString("hex");return"LegacyPythonUUID('"+(0,ko.P6)(t)+"')"},_o=e=>{const t=Mo(),n=(0,o.useMemo)((()=>{if(16===e.value.buffer.length)try{if("LegacyJavaUUID"===t)return jo(e);if("LegacyCSharpUUID"===t)return Bo(e);if("LegacyPythonUUID"===t)return zo(e)}catch{}return`Binary.createFromBase64('${To(e.value.toString("base64"),100)}', ${e.value.sub_type})`}),[t,e]);return s().createElement(Ro,{type:"Binary",title:n},n)},$o=({value:e})=>{const t=(0,o.useMemo)((()=>{if("string"==typeof e)return e;if(!e||!e.buffer)return String(e);try{return e.toUUID().toString()}catch{return e.toString("hex")}}),[e]);return s().createElement(Ro,{type:"Binary",title:t},s().createElement("span",{className:Ho},"UUID('"),t,s().createElement("span",{className:Ho},"')"))},Yo=({value:e})=>{const t=(0,o.useMemo)((()=>"string"==typeof e?`LegacyJavaUUID('${e}')`:e&&e.buffer?jo({value:e}):String(e)),[e]);return s().createElement(Ro,{type:"Binary",title:t},t)},Ko=({value:e})=>{const t=(0,o.useMemo)((()=>"string"==typeof e?`LegacyCSharpUUID('${e}')`:e&&e.buffer?Bo({value:e}):String(e)),[e]);return s().createElement(Ro,{type:"Binary",title:t},t)},Go=({value:e})=>{const t=(0,o.useMemo)((()=>"string"==typeof e?`LegacyPythonUUID('${e}')`:e&&e.buffer?zo({value:e}):String(e)),[e]);return s().createElement(Ro,{type:"Binary",title:t},t)},Vo=({value:e})=>{const{stringifiedValue:t,title:n,additionalHints:a}=(0,o.useMemo)((()=>{if(e.sub_type===Do.Binary.SUBTYPE_ENCRYPTED)return{stringifiedValue:"*********",title:"Encrypted",additionalHints:s().createElement(q,{className:Fo,hideExternalIcon:!0,href:"https://www.mongodb.com/docs/compass/current/in-use-encryption-tutorial/","aria-label":"Compass In-Use Encryption documentation",title:"Compass In-Use Encryption documentation","data-testid":"bson-value-in-use-encryption-docs-link"},s().createElement(ie,{size:"small",glyph:"QuestionMarkWithCircle"}))};if(e.sub_type===Do.Binary.SUBTYPE_UUID){let t;try{t=e.toUUID().toString()}catch{t=e.toString("hex")}return{stringifiedValue:`UUID('${t}')`}}if(e.sub_type===Do.Binary.SUBTYPE_VECTOR){const t=e.buffer[0];if(t===Do.Binary.VECTOR_TYPE.Int8)return{stringifiedValue:`Binary.fromInt8Array(new Int8Array([${To(e.toInt8Array().slice(0,100).join(", "),100)}]))`};if(t===Do.Binary.VECTOR_TYPE.Float32)return{stringifiedValue:`Binary.fromFloat32Array(new Float32Array([${To([...e.toFloat32Array().slice(0,100)].map((e=>e.toPrecision(8).replace(/\.?0+$/,""))).join(", "),100)}]))`};if(t===Do.Binary.VECTOR_TYPE.PackedBit)return{stringifiedValue:`Binary.fromPackedBits(new Uint8Array([${To(e.toPackedBits().slice(0,100).join(", "),100)}]))`}}return{stringifiedValue:`Binary.createFromBase64('${To(e.toString("base64"),100)}', ${e.sub_type})`}}),[e]);return s().createElement(Ro,{type:"Binary",title:n??t},t,a)},Uo=({value:e})=>{const t=(0,o.useMemo)((()=>`Code('${String(e.code)}'${e.scope?`, ${JSON.stringify(e.scope)}`:""})`),[e.code,e.scope]);return s().createElement(Ro,{type:"Code",title:t},t)},qo=({value:e})=>{const t=(0,o.useMemo)((()=>{try{return new Date(e).toISOString().replace("Z","+00:00")}catch{return String(e)}}),[e]);return s().createElement(Ro,{type:"Date",title:t},t)},Zo=({type:e,value:t})=>{const n=(0,o.useMemo)((()=>String(t.valueOf())),[t]);return s().createElement(Ro,{type:e,title:n},n)},Jo=({value:e})=>{const t=(0,o.useMemo)((()=>To(e,70)),[e]);return s().createElement(Ro,{type:"String",title:e},'"',t,'"')},Qo=({value:e})=>{const t=(0,o.useMemo)((()=>`/${e.pattern}/${e.options}`),[e.pattern,e.options]);return s().createElement(Ro,{type:"BSONRegExp",title:t},t)},Xo=({value:e})=>{const t=(0,o.useMemo)((()=>`Timestamp({ t: ${e.getHighBits()}, i: ${e.getLowBits()} })`),[e]);return s().createElement(Ro,{type:"Timestamp",title:t},t)},es=({type:e})=>{const t=(0,o.useMemo)((()=>`${e}()`),[e]);return s().createElement(Ro,{type:e,title:t},t)},ts=({value:e})=>{const t=(0,o.useMemo)((()=>`DBRef('${e.collection}', '${String(e.oid)}'${e?.db?`, '${e.db}'`:""})`),[e.collection,e.oid,e.db]);return s().createElement(Ro,{type:"DBRef",title:t},t)},ns=({value:e})=>{const t=(0,o.useMemo)((()=>`Symbol('${String(e)}')`),[e]);return s().createElement(Ro,{type:"BSONSymbol",title:t},t)},as=({value:e})=>{const t=(0,o.useMemo)((()=>String(e)),[e]);return s().createElement(Ro,{title:t},t)},rs=({value:e})=>{const t=(0,o.useMemo)((()=>`(${e.length>0?e.length:"empty"})`),[e.length]);return s().createElement(Ro,{title:`Array ${t}`},"Array ",t)},is=e=>{switch(e.type){case"ObjectId":return s().createElement(Wo,{value:e.value});case"Date":return s().createElement(qo,{value:e.value});case"Binary":return e.value.sub_type===Do.Binary.SUBTYPE_UUID_OLD?s().createElement(_o,{value:e.value}):s().createElement(Vo,{value:e.value});case"UUID":return s().createElement($o,{value:e.value});case"LegacyJavaUUID":return s().createElement(Yo,{value:e.value});case"LegacyCSharpUUID":return s().createElement(Ko,{value:e.value});case"LegacyPythonUUID":return s().createElement(Go,{value:e.value});case"Int32":case"Double":return s().createElement(Zo,{type:e.type,value:e.value});case"String":return s().createElement(Jo,{value:e.value});case"BSONRegExp":return s().createElement(Qo,{value:e.value});case"Code":return s().createElement(Uo,{value:e.value});case"MinKey":case"MaxKey":return s().createElement(es,{type:e.type});case"DBRef":return s().createElement(ts,{value:e.value});case"Timestamp":return s().createElement(Xo,{value:e.value});case"BSONSymbol":return s().createElement(ns,{value:e.value});case"Array":return s().createElement(rs,{value:e.value});case"Object":return s().createElement(as,{type:e.type,value:e.type});default:return s().createElement(as,{type:e.type,value:e.value})}},os=(0,r.AH)({position:"absolute",display:"flex",alignItems:"center",gap:ce.YK[200],width:"100%",top:ce.YK[300],paddingLeft:ce.YK[300],paddingRight:ce.YK[300],pointerEvents:"none"}),ss=(0,r.AH)({flex:"none",pointerEvents:"all"}),ls=(0,r.AH)({flex:"1 0 auto",pointerEvents:"none"}),cs=(0,r.AH)({"& > [data-action-item]":{display:"none"}}),ds=(0,r.AH)({"& > [data-action-item]":{display:"block"}}),us=(0,r.AH)({display:"block !important"}),ps=(0,r.AH)({"& > div:has(svg)":{paddingLeft:3,paddingRight:3}});function ms({tooltipText:e,tooltipEnabled:t,...n}){return s().createElement(re,{enabled:t,trigger:s().createElement("div",{"data-action-item":!0},s().createElement(J,n)),justify:"middle"},e)}const gs=({onEdit:e,onCopy:t,onClone:n,onRemove:a,onExpand:i,expanded:l,onlyShowOnHover:c=!0,insights:d})=>{const[u,p]=(0,o.useState)(!1),m=(0,o.useRef)(null),g=function(e){const[t,n]=(0,o.useState)(!1);return(0,o.useEffect)((()=>{const t=e.current?.parentElement,a=()=>{n(!0)},r=()=>{n(!1)};return t?.addEventListener("mouseenter",a),t?.addEventListener("mouseleave",r),()=>{t?.removeEventListener("mouseenter",a),t?.removeEventListener("mouseleave",r)}}),[e]),t}(m),[h,f]=(0,o.useState)(!1),y=g||u;return(0,o.useEffect)((()=>{if(!0===h){const e=setTimeout((()=>{f(!1)}),1200);return()=>{clearTimeout(e)}}}),[h]),s().createElement("div",{ref:m,className:(0,r.cx)(os,c&&(y?ds:cs))},i&&s().createElement(ms,{size:"xsmall",tooltipEnabled:y,rightGlyph:s().createElement(ie,{role:"presentation",glyph:l?"CaretDown":"CaretRight"}),"aria-label":l?"Collapse all":"Expand all","aria-pressed":l,"data-testid":"expand-document-button",onClick:i,className:(0,r.cx)(ss,ps),tooltipText:l?"Collapse all":"Expand all"}),s().createElement("span",{className:ls}),d&&s().createElement("div",{className:(0,r.cx)(ss,us),"data-action-item":!0},s().createElement(hi,{signals:d,onPopoverOpenChange:p})),e&&s().createElement(ms,{tooltipEnabled:y,size:"xsmall",rightGlyph:s().createElement(ie,{role:"presentation",glyph:"Edit"}),"aria-label":"Edit document","data-testid":"edit-document-button",onClick:e,className:ss,tooltipText:"Edit document"}),t&&s().createElement(re,{open:h,trigger:s().createElement("div",{"data-action-item":!0},s().createElement(ms,{tooltipEnabled:y,size:"xsmall",rightGlyph:s().createElement(ie,{role:"presentation",glyph:"Copy"}),"aria-label":"Copy document to clipboard","data-testid":"copy-document-button",onClick:()=>{f(!0),t()},className:ss,tooltipText:"Copy to clipboard"})),justify:"middle"},"Copied!"),n&&s().createElement(ms,{size:"xsmall",tooltipEnabled:y,rightGlyph:s().createElement(ie,{role:"presentation",glyph:"Clone"}),"aria-label":"Clone document","data-testid":"clone-document-button",onClick:n,className:ss,tooltipText:"Clone document"}),a&&s().createElement(ms,{size:"xsmall",tooltipEnabled:y,rightGlyph:s().createElement(ie,{role:"presentation",glyph:"Trash"}),"aria-label":"Remove document","data-testid":"remove-document-button",onClick:a,className:ss,tooltipText:"Remove document"}))},hs={fontFamily:ce.aI.code,fontSize:12,lineHeight:16},fs=(0,r.AH)({display:"flex",gap:ce.YK[200],paddingTop:ce.YK[200]}),ys=(0,r.AH)({border:"none",background:"none",padding:0,fontFamily:hs.fontFamily,fontSize:`${hs.fontSize}px`,lineHeight:`${hs.lineHeight}px`,"& > span":{display:"inline-flex",alignItems:"center",gap:ce.YK[100]}}),bs=({showHideButton:e=!0,buttonClassName:t,parentFieldName:n,currentSize:a,totalSize:i,minSize:l=25,step:c=1e3,style:d,onSizeChange:u})=>{const p=(0,o.useMemo)((()=>Math.min(i-a,c)),[a,c,i]),m=(0,o.useMemo)((()=>Math.max(a-l,0)),[a,l]),g=(0,o.useMemo)((()=>p>0),[p]),h=(0,o.useMemo)((()=>e&&m>0),[m,e]),f=(0,o.useCallback)((()=>{u(a+p)}),[a,u,p]),y=(0,o.useCallback)((()=>{u(a-m)}),[a,m,u]);if(!g&&!h)return null;const b=`Show ${p} more ${1===p?"field":"fields"}${n?` in ${n}`:""}`,v=`Hide ${m} ${1===m?"field":"fields"}${n?` in ${n}`:""}`;return s().createElement("div",{className:fs,style:d},g&&s().createElement(q,{as:"button",hideExternalIcon:!0,className:(0,r.cx)(ys,t),onClick:f,"aria-label":b,"data-testid":"show-more-fields-button"},s().createElement(ie,{size:"small",glyph:"CaretDown"}),b),h&&s().createElement(q,{as:"button",hideExternalIcon:!0,className:(0,r.cx)(ys,t),onClick:y,"aria-label":v,"data-testid":"hide-fields-button"},s().createElement(ie,{size:"small",glyph:"CaretUp"}),v))};var vs=n(39059);const xs=(0,o.createContext)(null);function Es(){const[,e]=(0,o.useState)({});return(0,o.useCallback)((()=>{e({})}),[])}const Cs=(0,r.AH)({maxWidth:"100%",overflowX:"hidden",textOverflow:"ellipsis"}),ws=(0,r.AH)({padding:0,margin:0,border:"none",boxShadow:"none",outline:"none",backgroundColor:"transparent",maxWidth:"100%"}),Is=(0,r.AH)({"&:focus, &:active":{borderRadius:"2px",boxShadow:`0 0 0 2px ${le.M.blue.light1}`}}),Ss=(0,r.AH)({"&:focus, &:active":{boxShadow:`0 0 0 2px ${le.M.red.dark2}`}}),As=(0,r.AH)({backgroundColor:le.M.red.light2,color:le.M.red.dark2}),ks=(0,r.AH)({backgroundColor:le.M.red.dark2,color:le.M.red.light2}),Ds=({editing:e,value:t,valid:n,validationMessage:a,onChange:o,autoFocus:l,onEditStart:c})=>{const d=pe(),u=`${Math.max(t.length,1)}.5ch`;return s().createElement(s().Fragment,null,e?s().createElement(re,{darkMode:!0,enabled:!n,trigger:({className:e,children:a,onDragStart:c,onPointerUp:p,onPointerDown:m,onMouseDown:g,...h})=>s().createElement("div",{className:e},s().createElement("input",(0,i.A)({type:"text","data-testid":"hadron-document-key-editor",value:t,onChange:e=>{o(e.currentTarget.value)},autoFocus:l,className:(0,r.cx)(Cs,ws,Is,!n&&Ss,!n&&(d?ks:As)),style:{width:u},spellCheck:"false"},h)),a)},a):s().createElement("div",{"data-testid":"hadron-document-clickable-key",onDoubleClick:c,className:Cs,style:{width:u}},t))},Ns=(0,r.AH)({width:"100%",maxWidth:"100%","&::before, &::after":{content:"'\"'",userSelect:"none"}}),Ms=(0,r.AH)({display:"inline-block",whiteSpace:"nowrap",minWidth:"5ch",maxWidth:"calc(100% - 2ch)",verticalAlign:"top",color:"inherit"}),Ts=(0,r.AH)({display:"inline-flex",alignItems:"center",maxWidth:"100%"}),Ps=(0,r.AH)({display:"inline-block",whiteSpace:"nowrap",verticalAlign:"top",color:"inherit"}),Ls=(0,r.AH)({userSelect:"none",whiteSpace:"nowrap"}),Os=({editing:e,onEditStart:t,type:n,value:a,valid:l,validationMessage:c,originalValue:d,autoFocus:u,onChange:p,onFocus:m,onBlur:g})=>{const h=String(a),f=pe(),y=(0,o.useMemo)((()=>{if("String"===n){const e=h.split("\n");let t=0;for(const n of e){const e=n.length;e>t&&(t=e)}const n=`${Math.min(t+1,70)}ch`,a=Math.max(e.length,t>70?2:1),r=Math.min(a,10);return{width:n,minHeight:hs.lineHeight*Math.min(a,r),height:hs.lineHeight*r}}return{width:`${Math.max(h.length,1)}ch`}}),[h,n]),b=(0,o.useMemo)((()=>({width:`${Math.max(h.length,36)}ch`})),[h]);return s().createElement(s().Fragment,null,e?s().createElement(re,{darkMode:!0,enabled:!l,trigger:({className:e,children:t,onDragStart:a,onPointerUp:o,onPointerDown:c,onMouseDown:d,...v})=>{const x=$e(v,{onBlur:g,onFocus:m});return s().createElement("div",{className:e},"String"===n?s().createElement(Ro,{type:"String",className:(0,r.cx)(Ns)},s().createElement("textarea",(0,i.A)({"data-testid":"hadron-document-value-editor",value:h,onChange:e=>{p(e.currentTarget.value)},autoFocus:u,className:(0,r.cx)(ws,Is,Ms,!l&&Ss),spellCheck:"false",style:y},x))):(0,ko.IM)(n)?s().createElement("div",{className:Ts},s().createElement("span",{className:Ls},n,"('"),s().createElement("input",(0,i.A)({type:"text","data-testid":"hadron-document-value-editor",value:h,placeholder:"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",onChange:e=>{p(e.currentTarget.value)},autoFocus:u,className:(0,r.cx)(ws,Is,Ps,!l&&Ss,!l&&(f?ks:As)),spellCheck:"false",style:b},x)),s().createElement("span",{className:Ls},"')")):s().createElement("input",(0,i.A)({type:"text","data-testid":"hadron-document-value-editor",value:h,onChange:e=>{p(e.currentTarget.value)},autoFocus:u,className:(0,r.cx)(ws,Is,!l&&Ss,!l&&(f?ks:As)),style:y,spellCheck:"false"},x)),t)}},c):s().createElement("div",{"data-testid":"hadron-document-clickable-value",onDoubleClick:t},s().createElement(is,{type:n,value:d})))},Rs=ko.Ay.castableTypes(!0),Hs=Math.max(...Rs.map((e=>e.length))),Fs=(0,r.AH)({color:le.M.gray.base,appearance:"none",paddingLeft:ce.YK[100],width:`calc(${Hs}ch + ${ce.YK[600]}px)`,"&:hover":{color:"inherit",cursor:"pointer"}}),Ws=(0,r.AH)({appearance:"auto",paddingLeft:0}),js=(0,r.AH)({position:"absolute",right:4,top:2,pointerEvents:"none",display:"none"}),Bs=(0,r.AH)({backgroundColor:le.M.white}),zs=(0,r.AH)({backgroundColor:le.M.black}),_s=(0,r.AH)({[`&:hover .${js}`]:{display:"block"},position:"relative",cursor:"pointer"}),$s=({editing:e,autoFocus:t,type:n,onChange:a,visuallyActive:i})=>{const o=pe();return s().createElement(s().Fragment,null,e&&s().createElement("div",{className:_s},s().createElement("select",{value:n,"data-testid":"hadron-document-type-editor",autoFocus:t,onChange:e=>{a(e.currentTarget.value)},className:(0,r.cx)(ws,Is,Fs,i&&Ws),onClick:e=>{e.stopPropagation()}},Rs.map((e=>s().createElement("option",{key:e,value:e,className:o?zs:Bs},e)))),s().createElement(ie,{glyph:"ChevronDown",size:"xsmall",className:js})))},Ys=(0,r.AH)({margin:0,padding:0,border:"none",background:"none",cursor:"pointer"}),Ks=(0,r.AH)({position:"absolute",top:2,right:0}),Gs=({editing:e,onRemove:t,onRevert:n})=>s().createElement(s().Fragment,null,e&&(n?s().createElement("button",{type:"button","data-testid":"hadron-document-revert",className:Ys,"aria-label":"Revert changes",title:"Revert changes",onClick:e=>{e.stopPropagation(),n()}},s().createElement(ie,{size:"xsmall",className:Ks,glyph:"Undo"})):t?s().createElement("button",{type:"button","data-testid":"hadron-document-remove",className:Ys,title:"Remove field","aria-label":"Remove field",onClick:e=>{e.stopPropagation(),t()}},s().createElement(ie,{size:"xsmall",glyph:"Trash",className:Ks})):null)),Vs=(0,r.AH)({display:"block",width:hs.lineHeight,height:hs.lineHeight,marginLeft:"auto",boxShadow:"inset 0 0 0 1px currentColor",borderRadius:"2px",userSelect:"none"}),Us=(0,r.AH)({width:"auto",minWidth:3*ce.YK[1600]}),qs=(0,r.AH)({whiteSpace:"nowrap"}),Zs=(0,o.forwardRef)((function({onClick:e,...t},n){return s().createElement("button",(0,i.A)({type:"button","data-testid":"hadron-document-add-element",title:"Add field",className:(0,r.cx)(Ys,Vs),onClick:t=>{t.stopPropagation(),e?.(t)}},t,{ref:n}),"+")})),Js=({editing:e,type:t,parentType:n,keyName:a,onAddFieldToElement:r,onAddFieldAfterElement:l})=>{const[c,d]=(0,o.useState)(!1);return e?l&&!r?s().createElement(Zs,{onClick:l}):s().createElement(y.W1,{open:c,setOpen:d,align:"bottom",justify:"start",className:Us,trigger:({children:e,onClick:t,ref:n,...a})=>s().createElement(s().Fragment,null,s().createElement(Zs,(0,i.A)({onClick:t,ref:n},a)),e)},r&&s().createElement(y.Dr,{"data-testid":"hadron-document-add-child",onClick:()=>{d(!1),r()},glyph:s().createElement(ie,{glyph:"Relationship"}),className:qs},s().createElement("div",null,"Add ","Array"===t?"item":"field"," to ",s().createElement("b",null,a))),s().createElement(y.Dr,{"data-testid":"hadron-document-add-sibling",onClick:()=>{d(!1),l()},glyph:s().createElement(ie,{glyph:"PlusWithCircle"}),className:qs},s().createElement("div",null,"Add ","Array"===n?"item":"field"," after ",s().createElement("b",null,a)))):null};var Qs=n(81358),Xs=n(21655).URL;const el=(0,r.AH)({margin:0,padding:0,border:"none",background:"none","&:hover":{cursor:"pointer"},display:"flex"}),tl=(0,r.AH)({display:"flex",paddingLeft:ce.YK[50],paddingRight:ce.YK[50],marginTop:1}),nl=(0,r.AH)({"&:hover":{backgroundColor:le.M.gray.light2}}),al=(0,r.AH)({"&:hover":{backgroundColor:le.M.gray.dark4}}),rl=(0,r.AH)({backgroundColor:le.M.yellow.light3,"&:hover":{backgroundColor:le.M.yellow.light2}}),il=(0,r.AH)({backgroundColor:le.M.red.light3,"&:hover":{backgroundColor:le.M.red.light2}}),ol=(0,r.AH)({backgroundColor:le.M.yellow.dark3,"&:hover":{backgroundColor:le.M.yellow.dark2}}),sl=(0,r.AH)({backgroundColor:le.M.red.dark3,"&:hover":{backgroundColor:le.M.red.dark2}}),ll=(0,r.AH)({flex:"none",width:ce.YK[300],position:"relative"}),cl=(0,r.AH)({flex:"none",position:"relative",marginLeft:ce.YK[100],boxSizing:"content-box"}),dl=(0,r.AH)({position:"absolute",top:0,right:0}),ul=(0,r.AH)({"&::before":{display:"block",width:"100%",counterIncrement:"line-number",content:"counter(line-number)",textAlign:"end",color:le.M.gray.base}}),pl=(0,r.AH)({backgroundColor:le.M.yellow.base,"&::before":{color:le.M.yellow.dark2}}),ml=(0,r.AH)({backgroundColor:le.M.red.base,color:le.M.red.light3,"&::before":{color:le.M.red.light3}}),gl=(0,r.AH)({backgroundColor:le.M.yellow.dark2,"&::before":{color:le.M.yellow.base}}),hl=(0,r.AH)({backgroundColor:le.M.red.light3,color:le.M.red.base,"&::before":{color:le.M.red.base}}),fl=(0,r.AH)({flex:"none"}),yl=(0,r.AH)({width:ce.YK[400],flex:"none",display:"flex",alignItems:"center"}),bl=(0,r.AH)({flex:"none",fontWeight:"bold",maxWidth:"60%"}),vl=(0,r.AH)({color:le.M.gray.base}),xl=(0,r.AH)({flex:"none",userSelect:"none"}),El=(0,r.AH)({flex:1,minWidth:0,maxWidth:"100%"}),Cl=(0,r.AH)({flex:"none",marginLeft:ce.YK[100]}),wl=(0,r.AH)({display:"none"}),Il=(0,r.AH)({'[data-document-element="true"]:hover &, [data-document-element="true"]:focus-within &':{display:"block"}}),Sl=(0,r.AH)({'[data-document-element="true"]:hover &::before, [data-document-element="true"]:focus-within &::before':{visibility:"hidden"}}),Al=(0,r.AH)({color:le.M.gray.light2}),kl=(e,t,n)=>(e?ce.YK[100]:0)+n+ce.YK[400]*t,Dl=({editable:e,level:t,alignWithNestedExpandIcon:n,extraGutterWidth:a=0})=>kl(e,t,a)+(e?ce.YK[300]+ce.YK[400]+ce.YK[100]:0)+(n?ce.YK[400]:0),Nl=e=>{try{const t=new Xs(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}},Ml=e=>{const t=[];let n=e;for(;n&&"parent"in n&&n.parent;)"Array"!==n.parent.currentType&&t.unshift(n.currentKey.toString()),n=n.parent;return t.join(".")},Tl=({value:e,editable:t,editingEnabled:n,onEditStart:a,lineNumberSize:l,onAddElement:c,extraGutterWidth:d=0,onUpdateQuery:u,query:p})=>{const m=pe(),g=(0,o.useContext)(xs),{id:h,key:f,value:y,type:b,revert:v,remove:x,expandable:E,children:C,visibleChildren:w,level:I,parentType:S,removed:A,internal:k,expanded:D,expand:N,collapse:M}=function(e){const t=Es(),n=Mo(),a=(0,vs.Ho)(e,n),r=function(e,t){return(0,o.useMemo)((()=>new((0,vs.ZL)(t))(e,t)),[e,t])}(e,a),[i,s]=(0,o.useState)((()=>e.isDuplicateKey(e.currentKey))),l=(0,o.useCallback)((n=>{e.uuid===n.uuid&&t()}),[e,t]),c=(0,o.useCallback)(((n,a)=>{e===a&&t()}),[e,t]),d=(0,o.useCallback)((n=>{e.uuid===n.uuid&&(s(e.isDuplicateKey(e.key)),t())}),[e,t]);So((()=>{t()}),[e]),(0,o.useEffect)((()=>(e.on(vs.IM.Converted,l),e.on(vs.IM.Edited,l),e.on(vs.IM.Reverted,d),e.on(vs.IM.Invalid,l),e.on(vs.IM.Valid,l),e.on(vs.IM.Added,c),e.on(vs.IM.Removed,c),e.on(vs.IM.Expanded,l),e.on(vs.IM.Collapsed,l),e.on(vs.IM.VisibleElementsChanged,l),()=>{e.off(vs.IM.Converted,l),e.off(vs.IM.Edited,l),e.off(vs.IM.Reverted,d),e.off(vs.IM.Valid,l),e.off(vs.IM.Added,c),e.off(vs.IM.Removed,c),e.off(vs.IM.Expanded,l),e.off(vs.IM.Collapsed,l),e.off(vs.IM.VisibleElementsChanged,l)})),[e,l,c,d]);const u=e.isCurrentTypeValid();return{id:e.uuid,key:{value:String(e.currentKey),change(t){s(e.isDuplicateKey(t)),e.rename(t)},editable:e.isKeyEditable()&&"Array"!==e.parent?.currentType,valid:!i,validationMessage:i?`Duplicate key "${e.currentKey}" - this will overwrite previous values`:null},value:{value:r.value(),originalValue:"Array"===e.currentType?[...e.elements||[]]:e.currentValue,change(e){r.edit(e)},editable:e.isValueEditable()&&"Object"!==e.currentType&&"Array"!==e.currentType,decrypted:e.isValueDecrypted(),valid:u,validationMessage:u?null:e.invalidTypeMessage??null,startEdit:r.start.bind(r),completeEdit:r.complete.bind(r)},type:{value:a,change(t){e.changeType(t)}},revert:e.isRevertable()?e.revert.bind(e):null,remove:e.isNotActionable()?null:e.remove.bind(e),expandable:Boolean(e.elements),children:e.elements?[...e.elements]:[],visibleChildren:e.getVisibleElements(),level:e.level,parentType:e.parent?.currentType,removed:e.isRemoved(),internal:e.isInternalField(),expanded:e.expanded,expand:e.expand.bind(e),collapse:e.collapse.bind(e)}}(e),T=(0,o.useCallback)(((e,t)=>(0,Qs.mC)(p?.[e],t)),[p]),P=rn((()=>[{telemetryLabel:"Element Field",items:[u?{label:T(Ml(e),e.generateObject())?"Remove from query":"Add to query",onAction:()=>{u(Ml(e),e.generateObject())}}:void 0,{label:"Copy field & value",onAction:()=>{navigator.clipboard.writeText(`${f.value}: ${e.toEJSON()}`)}},"String"===b.value&&Nl(y.value)?{label:"Open URL in browser",onAction:()=>{window.open(y.value,"_blank","noopener")}}:void 0]}]),[e,f.value,y.value,b.value,u,T]),L=()=>{D?M():N()},O=(0,o.useMemo)((()=>{if(n){const e=String(l).length;return{minWidth:e>2?`${e}.5ch`:ce.YK[400]}}return{minWidth:ce.YK[400]}}),[l,n]),R=(0,o.useMemo)((()=>({width:kl(t,I,d)})),[t,I,d]),H=(0,o.useMemo)((()=>({paddingLeft:Dl({editable:t,level:I,alignWithNestedExpandIcon:!0,extraGutterWidth:d})})),[t,I,d]),F=f.valid&&y.valid,W=n,j=m?sl:il,B=m?ol:rl,z={ref:P,className:(0,r.cx)(tl,m?al:nl,A?j:n&&!F&&B),onClick:L},_={className:(0,r.cx)(bl,k&&vl,m&&Al)},$=m?hl:ml,Y=m?gl:pl,K=(0,o.useCallback)((t=>{e.setMaxVisibleElementsCount(t)}),[e]);return s().createElement(s().Fragment,null,s().createElement("div",(0,i.A)({"data-document-element":"true","data-testid":"hadron-document-element","data-field":f.value,"data-id":e.uuid},z),t&&s().createElement("div",{className:ll},s().createElement("div",{className:(0,r.cx)(wl,W&&Il)},s().createElement(Gs,{onRevert:v,onRemove:x,editing:n}))),t&&s().createElement("div",{className:(0,r.cx)(cl,n&&ul,W&&Sl,A?$:n&&!F&&Y),style:O},s().createElement("div",{className:(0,r.cx)(wl,dl,W&&Il)},s().createElement(Js,{editing:n,type:b.value,parentType:S&&"Document"===S?"Object":S,keyName:f.value,onAddFieldAfterElement:()=>{const t=e.insertSiblingPlaceholder();c(t)},onAddFieldToElement:"Object"===b.value||"Array"===b.value?()=>{const t=e.insertPlaceholder();c(t),N()}:void 0}))),s().createElement("div",{className:fl,style:R}),s().createElement("div",{className:yl},E&&s().createElement("button",{type:"button",className:el,"aria-pressed":D,"aria-label":D?"Collapse field items":"Expand field items",onClick:e=>{e.stopPropagation(),L()}},s().createElement(ie,{size:"xsmall",glyph:D?"CaretDown":"CaretRight"}))),s().createElement("div",(0,i.A)({},_,{"data-testid":"hadron-document-element-key"}),f.editable?s().createElement(Ds,{value:f.value,valid:f.valid,validationMessage:f.validationMessage,onChange:e=>{f.change(e)},autoFocus:g?.id===h&&"key"===g?.type,editing:n,onEditStart:()=>{a?.(e.uuid,"key")}}):s().createElement("span",null,f.value)),s().createElement("div",{className:xl,role:"presentation"},": "),s().createElement("div",{className:xl,role:"presentation"},y.decrypted&&s().createElement("span",{"data-testid":"hadron-document-element-decrypted-icon",title:"Encrypted Field"},s().createElement(ie,{glyph:"Key",size:"small"}))),s().createElement("div",{className:El,"data-testid":"hadron-document-element-value"},y.editable?s().createElement(Os,{type:b.value,originalValue:y.originalValue,value:y.value,valid:y.valid,validationMessage:y.validationMessage,onChange:e=>{y.change(e)},autoFocus:g?.id===h&&"value"===g?.type,editing:n,onEditStart:()=>{a?.(e.uuid,"value")},onFocus:()=>{y.startEdit()},onBlur:()=>{y.completeEdit()}}):s().createElement("div",{"data-testid":t&&!n?"hadron-document-clickable-value":void 0,onDoubleClick:()=>{t&&!n&&a?.(e.uuid,"type")}},s().createElement(is,{type:b.value,value:y.originalValue}))),t&&s().createElement("div",{className:Cl,"data-testid":"hadron-document-element-type"},s().createElement($s,{editing:n,type:b.value,autoFocus:g?.id===h&&"type"===g?.type,onChange:e=>{b.change(e),"Array"!==e&&"Object"!==e||N()}}))),E&&D&&s().createElement(s().Fragment,null,w.map(((e,r)=>s().createElement(Tl,{key:r,value:e,editable:t,editingEnabled:n,onEditStart:a,lineNumberSize:l,onAddElement:c,extraGutterWidth:d,onUpdateQuery:u,query:p}))),s().createElement(bs,{parentFieldName:f.value,showHideButton:!n,currentSize:e.maxVisibleElementsCount,totalSize:C.length,minSize:vs.rp,step:n?vs.rp:1e3,onSizeChange:K,style:H})))},Pl=(0,r.AH)({position:"relative",fontFamily:hs.fontFamily,fontSize:`${hs.fontSize}px`,lineHeight:`${hs.lineHeight}px`,counterReset:"line-number"}),Ll=({value:e,editable:t=!1,editing:n=!1,onEditStart:a,extraGutterWidth:r,onUpdateQuery:i,query:l,className:c=""})=>{const{elements:d,visibleElements:u}=function(e){const t=Es(),n=(0,o.useCallback)((n=>{n===e&&t()}),[e,t]),a=(0,o.useCallback)(((n,a)=>{e===a&&t()}),[e,t]);return So((()=>{t()}),[e]),(0,o.useEffect)((()=>(e.on(vs.Tx.VisibleElementsChanged,n),e.on(vs.IM.Added,a),e.on(vs.IM.Removed,a),()=>{e.off(vs.Tx.VisibleElementsChanged,n),e.off(vs.IM.Added,a),e.off(vs.IM.Removed,a)})),[e,a,n]),{elements:[...e.elements],visibleElements:e.getVisibleElements()}}(e),[p,m]=(0,o.useState)(null),g=(0,o.useCallback)((t=>{e.setMaxVisibleElementsCount(t)}),[e]),h=(0,o.useMemo)((()=>Dl({editable:t,level:0,alignWithNestedExpandIcon:!1,extraGutterWidth:r})),[t,r]);return s().createElement("div",{className:c},s().createElement("div",{className:Pl,"data-testid":"hadron-document","data-id":e.uuid},s().createElement(xs.Provider,{value:n?p:null},u.map(((e,o)=>s().createElement(Tl,{key:o,value:e,editable:t,editingEnabled:n,onEditStart:t?(e,t)=>{m({id:e,type:t}),a?.()}:void 0,lineNumberSize:u.length,onAddElement:e=>{m({id:e.uuid,type:"Array"===e.parent?.currentType?"value":"key"})},extraGutterWidth:r,onUpdateQuery:i,query:l}))))),s().createElement(bs,{showHideButton:!n,currentSize:e.maxVisibleElementsCount,totalSize:d.length,minSize:vs.H8,step:n?100:1e3,onSizeChange:g,style:{paddingLeft:h}}))},Ol=new class{confirmationId=0;onShowCallback=null;showConfirmation(e){return new Promise(((t,n)=>{this.onShowCallback?.({props:e,resolve:t,reject:n,confirmationId:++this.confirmationId})}))}},Rl=Ol.showConfirmation.bind(Ol),Hl=(0,r.AH)({display:"none !important"}),Fl=(0,r.AH)({marginTop:ce.YK[400]}),Wl=({children:e})=>{const[t,n]=(0,o.useState)({open:!1,confirmationId:-1}),a=(0,o.useRef)(),r=ge((()=>(Ol.onShowCallback=({props:e,resolve:t,reject:r,confirmationId:i})=>{n({open:!0,confirmationId:i,...e});const o=()=>{n((e=>({...e,open:!1}))),r(e.signal?.reason)};a.current=n=>{e.signal?.removeEventListener("abort",o),t(n)},e.signal?.addEventListener("abort",o)},Ol)));(0,o.useEffect)((()=>()=>{a.current?.(!1),r&&(r.onShowCallback=null)}),[r]);const i=(0,o.useCallback)((e=>{n((e=>({...e,open:!1}))),a.current?.(e),a.current=void 0}),[]),l=(0,o.useCallback)((()=>{i(!0)}),[i]),c=(0,o.useCallback)((()=>{i(!1)}),[i]),u=(0,_e.Bi)();return s().createElement(s().Fragment,null,e,s().createElement(oe,{key:t.confirmationId,"data-testid":t["data-testid"]??"confirmation-modal",open:t.open,title:t.title??"Are you sure?",variant:t.variant??g.KT.Default,confirmButtonProps:{id:t.hideCancelButton?u:void 0,className:t.hideConfirmButton?Hl:void 0,children:t.buttonText??"Confirm",onClick:l,...t.confirmButtonProps},cancelButtonProps:{id:t.hideCancelButton?void 0:u,className:t.hideCancelButton?Hl:void 0,onClick:c},requiredInputText:t.requiredInputText??void 0,initialFocus:t.initialFocus??(t.requiredInputText?"auto":`#${u}`)},t.description,t.warning&&s().createElement(d.lZ,{variant:"warning",className:Fl},t.warning)))},jl=s().createContext(!1),Bl=({children:e})=>(0,o.useContext)(jl)?s().createElement(s().Fragment,null,e):s().createElement(jl.Provider,{value:!0},s().createElement(Wl,null,e));async function zl(e){let t=e.defaultValue??"";return await Rl({...e,description:s().createElement(s().Fragment,null,e.description&&s().createElement("div",null,e.description),s().createElement("div",null,s().createElement(Ht,null,s().createElement(T.ks,{label:e.label,defaultValue:t,onChange:e=>{t=e.currentTarget.value}}))))})?t:null}const _l=(0,r.AH)({paddingTop:ce.YK[400],maxHeight:"60vh",overflow:"auto"}),$l=function({details:e,closeAction:t}){Rl({title:"Error details",description:s().createElement("div",{className:_l},s().createElement(m.Cy,{language:"json","data-testid":"error-details-json",id:"error-details-json"},JSON.stringify(e,void 0,2))),hideCancelButton:!0,buttonText:t.replace(/\b\w/g,(e=>e.toUpperCase())),variant:g.KT.Default})};function Yl(e){return["Deleting","DeleteStart","DeleteSuccess","DeleteError"].includes(e)}function Kl(e){return["DeleteSuccess","UpdateSuccess"].includes(e)}function Gl(e){return["Editing","ContainsErrors","UpdateStart","UpdateSuccess","DeleteStart","DeleteSuccess"].includes(e)}function Vl(e){return["UpdateStart","UpdateSuccess","DeleteStart","DeleteSuccess"].includes(e)}const Ul={Initial:"",Editing:"",Deleting:"Document flagged for deletion.",Modified:"Document modified.",ContainsErrors:"Update not permitted while document contains errors.",UpdateStart:"Updating document…",UpdateError:"",UpdateBlocked:"Document was modified in the background or it no longer exists. Do you wish to continue and possibly overwrite new changes?",UpdateSuccess:"Document updated.",DeleteStart:"Removing document…",DeleteError:"",DeleteSuccess:"Document deleted."},ql=(0,r.AH)({display:"flex",paddingTop:ce.YK[200],paddingRight:ce.YK[200],paddingBottom:ce.YK[200],paddingLeft:ce.YK[400],alignItems:"center",gap:ce.YK[200],borderBottomLeftRadius:"inherit",borderBottomRightRadius:"inherit"}),Zl=(0,r.AH)({overflow:"scroll"}),Jl=(0,r.AH)({display:"flex",marginLeft:"auto",gap:ce.YK[200],flexShrink:0}),Ql=(0,r.AH)({flex:"none"});function Xl(e,t){switch(e){case"Editing":return{backgroundColor:t?le.M.black:le.M.gray.light2};case"ContainsErrors":case"UpdateError":case"UpdateBlocked":case"Deleting":case"DeleteError":case"DeleteStart":return{backgroundColor:t?le.M.red.dark3:le.M.red.light2,color:t?le.M.red.light2:le.M.red.dark3};case"UpdateStart":return{backgroundColor:le.M.blue.light2,color:le.M.blue.dark3};case"DeleteSuccess":case"UpdateSuccess":return{backgroundColor:le.M.green.light2,color:le.M.green.dark3};default:return{backgroundColor:le.M.yellow.light2,color:le.M.yellow.dark3}}}const ec=({doc:e,editing:t,deleting:n,modified:a=!1,validationError:r=null,alwaysForceUpdate:i=!1,onUpdate:l,onDelete:c,onCancel:d})=>{const{status:u,updateStatus:p,error:m}=function(e,t,n,a=null){const[r,i]=(0,o.useState)((()=>t?e.isModified()?"Modified":"Editing":n?"Deleting":"Initial")),[s,l]=(0,o.useState)(null),c=(0,o.useRef)(new Set),d=(0,o.useCallback)(((e,t=null,n)=>{i(e),l(t?{message:t?.message,details:n}:null)}),[]);(0,o.useEffect)((()=>{const t=()=>{d(0===c.current.size?e.isModified()?"Modified":"Editing":"ContainsErrors")},n=e=>{c.current.delete(e),t()},a=e=>{c.current.add(e),t()},r=()=>{d("UpdateStart")},i=()=>{d("UpdateBlocked")},o=()=>{d("UpdateSuccess")},s=(e,t)=>{d("UpdateError",e,t)},l=()=>{d("DeleteStart")},u=()=>{d("DeleteSuccess")},p=(e,t)=>{d("DeleteError",e,t)},m=()=>{d("Initial")};return e.on(vs.IM.Added,t),e.on(vs.IM.Edited,t),e.on(vs.IM.Removed,t),e.on(vs.IM.Reverted,t),e.on(vs.IM.Invalid,a),e.on(vs.IM.Valid,n),e.on(vs.Tx.UpdateStarted,r),e.on(vs.Tx.UpdateBlocked,i),e.on(vs.Tx.UpdateSuccess,o),e.on(vs.Tx.UpdateError,s),e.on(vs.Tx.RemoveStarted,l),e.on(vs.Tx.RemoveSuccess,u),e.on(vs.Tx.RemoveError,p),e.on(vs.Tx.EditingFinished,m),()=>{e.off(vs.IM.Added,t),e.off(vs.IM.Edited,t),e.off(vs.IM.Removed,t),e.off(vs.IM.Reverted,t),e.off(vs.IM.Invalid,a),e.off(vs.IM.Valid,n),e.off(vs.Tx.UpdateStarted,r),e.off(vs.Tx.UpdateBlocked,i),e.off(vs.Tx.UpdateSuccess,o),e.off(vs.Tx.UpdateError,s),e.off(vs.Tx.RemoveStarted,l),e.off(vs.Tx.RemoveSuccess,u),e.off(vs.Tx.RemoveError,p),e.off(vs.Tx.EditingFinished,m)}}),[e,d]),(0,o.useEffect)((()=>{if(Kl(r)){const e=setTimeout((()=>{d("Initial")}),2e3);return()=>{clearTimeout(e)}}}),[r,d]);const u=(0,o.useMemo)((()=>"Initial"!==r?r:t?"Editing":n?"Deleting":r),[r,t,n]),p=(0,o.useMemo)((()=>s||(a?{message:a.message}:null)),[s,a]);return{status:u,updateStatus:d,error:p}}(e,t,n,r),g=pe(),h=r?"ContainsErrors":a?"Modified":u,f=Ul[h];return"Initial"===h?null:s().createElement("div",{className:ql,style:Xl(h,g),"data-testid":"document-footer","data-status":h},s().createElement("div",{className:Zl,"data-testid":"document-footer-message"},m?.message??f),!Kl(h)&&s().createElement("div",{className:Jl},m?.details&&s().createElement(J,{className:Ql,size:"xsmall",onClick:()=>$l({details:m.details,closeAction:"close"}),"data-testid":"edit-actions-footer-error-details-button"},"VIEW ERROR DETAILS"),s().createElement(J,{type:"button",size:"xsmall",className:Ql,"data-testid":"cancel-button",onClick:()=>{e.cancel(),d?.(),p("Initial")},disabled:Vl(h)},"Cancel"),s().createElement(J,{type:"button",size:"xsmall",className:Ql,"data-testid":Yl(h)?"delete-button":"update-button",onClick:()=>{Yl(h)?c():l(i||"UpdateBlocked"===h)},disabled:Gl(h)},Yl(h)?"Delete":i||"UpdateBlocked"===h?"Replace":"Update")))},tc=(0,r.AH)({border:`1px solid ${le.M.gray.light2}`,borderRadius:ce.YK[200],transition:`${ce.KP.default}ms ease-in-out`,transitionProperty:"border, box-shadow"}),nc=(0,r.AH)({background:le.M.white}),ac=(0,r.AH)({background:le.M.black,borderColor:le.M.gray.dark2}),rc=`0 4px 10px -4px ${(0,xn.No)(.7,le.M.black)}`,ic=`0 4px 20px -4px ${le.M.black}`,oc=`0 4px 20px -4px ${(0,xn.No)(.8,le.M.black)}`,sc=`0 4px 20px -4px ${(0,xn.No)(.3,le.M.black)}`,lc=(0,r.AH)({cursor:"pointer",boxShadow:rc,"&:hover":{border:`1px solid ${le.M.gray.light2}`,boxShadow:oc},"&:active":{boxShadow:"none"}}),cc=(0,r.AH)({cursor:"pointer",boxShadow:ic,"&:hover":{boxShadow:sc}}),dc=(0,o.forwardRef)((function({className:e,contentStyle:t,...n},a){const o=pe(),l=ze(),c=$e("clickable"===t?{role:"button",tabIndex:0,...l}:{},{className:(0,r.cx)(tc,o?ac:nc,"clickable"===t&&(o?cc:lc),e)},n);return s().createElement("div",(0,i.A)({ref:a},c))})),uc=(0,r.AH)({height:0,width:"100%",display:"block",borderTopWidth:1,borderTopStyle:"solid"}),pc=(0,r.AH)({borderTopColor:le.M.gray.light2}),mc=(0,r.AH)({borderTopColor:le.M.gray.dark2}),gc=(0,o.forwardRef)((({className:e,...t},n)=>{const a=pe();return s().createElement("div",(0,i.A)({ref:n,className:(0,r.cx)(uc,a?mc:pc,e)},t))}));gc.displayName="HorizontalRule";const hc=(0,r.AH)({display:"inline-flex",gap:ce.YK[100],marginTop:ce.YK[200],marginBottom:ce.YK[200],paddingLeft:ce.YK[1600],paddingRight:ce.YK[1600]}),fc=(0,r.AH)({textTransform:"none",gap:ce.YK[100]}),yc=({field:e,value:t})=>s().createElement(c.Ex,{"data-testid":`${e}-key`,variant:c.KT.LightGray,className:fc,role:"listitem"},e,s().createElement(Ya,{direction:t})),bc=({keys:e,"data-testid":t})=>s().createElement("div",{className:hc,role:"list","data-testid":t},e.map((({field:e,value:t})=>s().createElement(c.Ex,{key:e,"data-testid":`${e}-key`,variant:c.KT.LightGray,className:fc,role:"listitem"},e,s().createElement(Ya,{direction:t}))))),vc=({onChange:e,options:t,multiselect:n=!1,renderOption:a,...r})=>{const[l,c]=(0,o.useState)([]),[d,u]=(0,o.useState)(""),p=(0,o.useMemo)((()=>{const e=[...t,...l],n=e.map(((e,t)=>a(e,t,!1)));return d&&!e.find((e=>e.value.includes(d)))&&n.push(a({value:d},e.length+1,!0)),n}),[t,l,d,a]),m=a=>{if(e&&a)if(n){const n=a,r=n.filter((e=>!t.find((t=>t.value===e)))).map((e=>({value:e})));c(r),e(n)}else{const n=a;n&&!t.find((e=>e.value===n))&&c([{value:n}]),e(n)}};return s().createElement(F.G3,(0,i.A)({},r,{multiselect:n,onFilter:u,onBlur:e=>{n||m(e.target.value)},onChange:m}),p)};function xc(e,t,n=globalThis.localStorage){const a=(0,o.useRef)(e),r=(0,o.useRef)(n),[i,s]=(0,o.useState)((()=>{const a=n.getItem(e);if(a)try{return JSON.parse(a)}catch(e){throw new Error("Failed to parse stored value, usePersistedState only supports serializeable values. "+e.message)}return"function"==typeof t?t():t}));return(0,o.useEffect)((()=>{r.current.setItem(a.current,JSON.stringify(i))}),[i]),[i,s]}const Ec=[{id:"aggregation-executed-without-index",title:"Aggregation executed without index",description:s().createElement(s().Fragment,null,"This aggregation ran without an index. If you plan on using this query"," ",s().createElement("strong",null,"heavily")," in your application, you should create an index that covers this aggregation."),learnMoreLink:"https://www.mongodb.com/docs/manual/data-modeling/schema-design-process/create-indexes/",primaryActionButtonLabel:"Create index",primaryActionButtonIcon:"Plus"},{id:"atlas-text-regex-usage-in-view",title:"Alternate text search options available",description:"In many cases, Atlas Search is MongoDB's most efficient full text search option. Convert your view’s query to $search for a wider range of functionality.",learnMoreLink:"https://www.mongodb.com/docs/atlas/atlas-search/best-practices/",primaryActionButtonLink:"https://www.mongodb.com/cloud/atlas/lp/search-1",primaryActionButtonLabel:"Try Atlas Search"},{id:"non-atlas-text-regex-usage-in-view",title:"Alternate text search options available",description:"In many cases, Atlas Search is MongoDB's most efficient full text search option. Connect with Atlas to explore the power of Atlas Search.",learnMoreLink:"https://www.mongodb.com/docs/atlas/atlas-search/best-practices/",primaryActionButtonLink:"https://www.mongodb.com/cloud/atlas/lp/search-1",primaryActionButtonLabel:"Try Atlas Search"},{id:"lookup-in-view",title:"$lookup usage",description:"$lookup operations can be resource-intensive because they perform operations on two collections instead of one. In certain situations, embedding documents or arrays can enhance read performance.",learnMoreLink:"https://www.mongodb.com/docs/atlas/schema-suggestions/reduce-lookup-operations/#std-label-anti-pattern-denormalization"},{id:"atlas-with-search-text-regex-usage-in-stage",title:"Alternate text search options available",description:"In many cases, Atlas Search is MongoDB's most efficient full text search option. Convert your query to $search for a wider range of functionality.",learnMoreLink:"https://www.mongodb.com/docs/atlas/atlas-search/best-practices/",primaryActionButtonLabel:"Create Search Index"},{id:"atlas-without-search-text-regex-usage-in-stage",title:"Alternate text search options available",description:"In many cases, Atlas Search is MongoDB's most efficient full text search option. Convert your query to $search for a wider range of functionality.",learnMoreLink:"https://www.mongodb.com/docs/atlas/atlas-search/best-practices/",primaryActionButtonLink:"https://www.mongodb.com/cloud/atlas/lp/search-1",primaryActionButtonLabel:"Try Atlas Search"},{id:"non-atlas-text-regex-usage-in-stage",title:"Alternate text search options available",description:"In many cases, Atlas Search is MongoDB's most efficient full text search option. Connect with Atlas to explore the power of Atlas Search.",learnMoreLink:"https://www.mongodb.com/docs/atlas/atlas-search/best-practices/",primaryActionButtonLink:"https://www.mongodb.com/cloud/atlas/lp/search-1",primaryActionButtonLabel:"Try Atlas Search"},{id:"lookup-in-stage",title:"$lookup usage",description:"$lookup operations can be resource-intensive because they perform operations on two collections instead of one. In certain situations, embedding documents or arrays can enhance read performance.",learnMoreLink:"https://www.mongodb.com/docs/atlas/schema-suggestions/reduce-lookup-operations/#std-label-anti-pattern-denormalization"},{id:"query-executed-without-index",title:"Query executed without index",description:s().createElement(s().Fragment,null,"This query ran without an index. If you plan on using this query"," ",s().createElement("strong",null,"heavily")," in your application, you should create an index that covers this query."),learnMoreLink:"https://www.mongodb.com/docs/manual/data-modeling/schema-design-process/create-indexes/",primaryActionButtonLabel:"Create index",primaryActionButtonIcon:"Plus"},{id:"atlas-text-regex-usage-in-query",title:"Alternate text search options available",description:"In many cases, Atlas Search is MongoDB's most efficient full text search option. Convert your query to $search for a wider range of functionality.",learnMoreLink:"https://www.mongodb.com/cloud/atlas/lp/search-1",primaryActionButtonLabel:"Create Search index"},{id:"bloated-document",title:"Possibly bloated document",description:"Large documents can slow down queries by decreasing the number of documents that can be stored in RAM. Consider breaking up your data into more collections with smaller documents, and using references to consolidate the data you need.",learnMoreLink:"https://www.mongodb.com/docs/atlas/schema-suggestions/reduce-document-size/"},{id:"explain-plan-without-index",title:"Query executed without index",description:s().createElement(s().Fragment,null,"This query ran without an index. If you plan on using this query"," ",s().createElement("strong",null,"heavily")," in your application, you should create an index that covers this aggregation."),learnMoreLink:"https://www.mongodb.com/docs/manual/data-modeling/schema-design-process/create-indexes/",primaryActionButtonLabel:"Create index",primaryActionButtonIcon:"Plus"},{id:"too-many-indexes",title:"High number of indexes on collection",description:"Consider reviewing your indexes to remove any that are unnecessary. Learn more about this anti-pattern",learnMoreLink:"https://www.mongodb.com/docs/manual/data-modeling/design-antipatterns/unnecessary-indexes/"},{id:"too-many-collections",title:"Databases with too many collections",description:"An excessive number of collections and their associated indexes can drain resources and impact your database's performance. In general, try to limit your replica set to 10,000 collections.",learnMoreLink:"https://www.mongodb.com/docs/manual/data-modeling/design-antipatterns/reduce-collections/"},{id:"unbound-array",title:"Large array detected",description:"As arrays get larger, queries and indexes on that array field become less efficient. Ensure your arrays are bounded to maintain optimal query performance.",learnMoreLink:"https://www.mongodb.com/docs/atlas/schema-suggestions/avoid-unbounded-arrays/"},{id:"rerank-without-search",title:"Using $rerank without a search stage",description:"$rerank is the first stage with no preceding search stage. This is expensive and increases strain. We recommend using $rerank as the second stage to $search, $vectorSearch, $rankFusion, or $scoreFusion."}],Cc=new Map(Ec.map((e=>[e.id,e]))),wc=(0,r.AH)({display:"flex",flexDirection:"row"}),Ic=(0,r.AH)({flexGrow:1}),Sc=(0,r.AH)({textTransform:"uppercase",flexGrow:0,alignSelf:"center",border:"none",padding:0,margin:0,background:"none"});function Ac({statusMessage:e,actionHandler:t,actionText:n}){return s().createElement("div",{className:wc},s().createElement(H.nB,{className:Ic},e),!!t&&s().createElement(q,{as:"button","data-testid":`toast-action-${n??"none"}`,onClick:t,hideExternalIcon:!0,className:Sc},n))}var kc=n(46410),Dc=n.n(kc),Nc=n(14396);const Mc=s().createContext([]),Tc=s().createContext(!1),Pc=s().createContext((()=>{})),Lc=s().createContext(null),Oc=s().createContext((()=>{})),Rc=s().createContext({current:{openDrawer:()=>{},closeDrawer:()=>{},updateToolbarData:()=>{},removeToolbarData:()=>{},setCurrent:()=>{}}}),Hc=s().createContext({callbacks:{current:{}},register:()=>{},unregister:()=>{},checkBeforeHide:()=>Promise.resolve(!0)}),Fc=({onDrawerSectionOpen:e,onDrawerSectionHide:t,children:n})=>{const[a,r]=(0,o.useState)([]),[i,l]=(0,o.useState)(!1),[c,d]=(0,o.useState)(null),u=(0,o.useRef)({openDrawer:()=>{},closeDrawer:()=>{},updateToolbarData:e=>{r((t=>{const n=t.findIndex((t=>t.id===e.id));if(-1===n)return[...t,e];const a=[...t];return a[n]=e,a}))},removeToolbarData:e=>{r((t=>t.filter((t=>t.id!==e))))},setCurrent:e=>{e(u.current)}}),p=(0,o.useRef)({}),m=ge((()=>({callbacks:p,register:(e,t)=>{p.current[e]=t},unregister:e=>{delete p.current[e]},checkBeforeHide:async e=>{if(!e)return!0;const t=p.current[e];if(!t)return!0;try{return await t()}catch{return!0}}}))),g=s().useRef(null);return(0,o.useEffect)((()=>{c!==g.current&&(c&&e?.(c),g.current&&t?.(g.current),g.current=c)}),[c,t,e]),s().createElement(Mc.Provider,{value:a},s().createElement(Tc.Provider,{value:i},s().createElement(Pc.Provider,{value:l},s().createElement(Lc.Provider,{value:c},s().createElement(Oc.Provider,{value:d},s().createElement(Rc.Provider,{value:u},s().createElement(Hc.Provider,{value:m},n)))))))},Wc=({children:e})=>{const t=(0,Nc.V9)(),n=(0,o.useContext)(Pc),a=(0,o.useContext)(Oc);return(0,o.useContext)(Rc).current.setCurrent((e=>{e.openDrawer=t.openDrawer,e.closeDrawer=t.closeDrawer})),(0,o.useEffect)((()=>{n(t.isDrawerOpen)}),[t.isDrawerOpen,n]),(0,o.useEffect)((()=>{const e=t.getActiveDrawerContent()?.id??null;a(e)}),[t,a]),s().createElement(s().Fragment,null,e)},jc=(0,r.AH)({"& > div:nth-child(1)":{display:"flex",alignItems:"stretch",overflow:"auto"},"& > div:nth-child(2) > div":{borderTop:"none",borderBottom:"none",containerType:"inline-size"},"& > div:nth-child(2) > div:nth-child(2) > div:nth-child(2) > div:first-child > div:first-child > div:first-child":{minWidth:0}}),Bc=(0,r.AH)({transition:"none",gridTemplateAreas:'"content drawer"',gridTemplateColumns:"auto 0 !important","& > div:nth-child(2)":{width:"0 !important",overflow:"hidden"}}),zc=(0,r.AH)({minWidth:"100%",minHeight:"100%",height:"100%"}),_c=(0,r.AH)({width:"100%",fontSize:ce.aM.Body2,fontWeight:ce.NM.bold}),$c=({children:e})=>{const t=(0,o.useContext)(Rc),n=(0,o.useContext)(Mc),a=(0,o.useContext)(Lc),{callbacks:l,checkBeforeHide:c}=(0,o.useContext)(Hc),d=(0,o.useRef)([]);(0,o.useEffect)((()=>{const e=new Set(d.current.map((e=>e.id)));for(const a of n)!e.has(a.id)&&a.autoOpen&&Tr((()=>{t.current.openDrawer(a.id)}));d.current=n}),[t,n]);const u=(0,o.useMemo)((()=>n.map((e=>({hasPadding:!1,...e,title:s().createElement("div",{key:e.id,className:_c},e.title),content:s().createElement("div",{key:e.id,"data-drawer-section":e.id,className:zc})}))).sort((({order:e=1/0},{order:t=1/0})=>t<e?1:t>e?-1:0))),[n]),[p,m]=(0,o.useState)({});return(0,o.useLayoutEffect)((function(){const e=document.querySelector(".compass-drawer-anchor");if(!e)return;let n=!1;const r=e=>{const r=e.target.closest("button[aria-label]");if(!r)return;if(!(r.closest('[data-lgid$="-toolbar"]')||r.matches('[data-lgid$="-close_button"]')||r.closest('[data-lgid$="-close_button"]')))return;const i=r.getAttribute("aria-label"),o=u.find((e=>e.label===i)),s="Close drawer"===i;(o||s)&&a&&l.current[a]&&(n||(e.stopPropagation(),e.preventDefault(),n=!0,s?c(a).then((e=>{e&&t.current.closeDrawer()})).catch((()=>{t.current.closeDrawer()})).finally((()=>{n=!1})):o&&(o.id===a?c(a).then((e=>{e&&t.current.closeDrawer()})).catch((()=>{t.current.closeDrawer()})).finally((()=>{n=!1})):c(a).then((e=>{e&&t.current.openDrawer(o.id)})).catch((()=>{t.current.openDrawer(o.id)})).finally((()=>{n=!1})))))};return e.addEventListener("click",r,!0),()=>{e.removeEventListener("click",r,!0)}}),[u,a,l,c,t]),(0,o.useLayoutEffect)((function(){const e=document.querySelector(".compass-drawer-anchor");if(!e)throw new Error("Can not use DrawerSection without DrawerAnchor being mounted on the page");function t(){if(!e)return;const t=Object.create(null);for(const n of u){if(!n.guideCue)continue;const a=e.querySelector(`button[aria-label="${n.label}"]`);a&&(t[n.id]=a)}m((e=>{for(const n of Object.keys({...e,...t}))if(t[n]!==e[n])return t;return e}))}t();const n=new MutationObserver((()=>{t()}));return n.observe(e,{subtree:!0,childList:!0}),()=>{n.disconnect()}}),[u]),s().createElement(s().Fragment,null,u.map((e=>p[e.id]&&e.guideCue&&s().createElement(Hr,(0,i.A)({key:e.id},e.guideCue,{triggerNode:p[e.id]})))),s().createElement(Nc.cO,{displayMode:Nc.q5.Embedded,resizable:!0,toolbarData:u,className:(0,r.cx)(jc,0===u.length&&Bc,"compass-drawer-anchor")},s().createElement(Wc,null,e)))};function Yc(e,t){return e?.querySelector(`[data-drawer-section${t?`=${t}`:""}]`)??null}const Kc=({children:e,...t})=>{const[n,a]=(0,o.useState)((()=>Yc(document,t.id))),r=(0,o.useContext)(Rc),i=(0,o.useRef)();So((()=>{a(Yc(document,t.id))}),[t.id]),(0,o.useEffect)((()=>{(0,Dr.isEqual)(i.current,t)||(r.current.updateToolbarData({autoOpen:!1,...t}),i.current=t)})),(0,o.useLayoutEffect)((()=>{const e=document.querySelector(".compass-drawer-anchor > div:nth-child(2)");if(!e)throw new Error("Can not use DrawerSection without DrawerAnchor being mounted on the page");const n=new MutationObserver((e=>{for(const n of e)if("childList"===n.type)for(const e of Array.from(n.addedNodes)){const n=Yc(e.parentElement,t.id);n&&a(n)}}));return n.observe(e,{subtree:!0,childList:!0}),()=>{n.disconnect()}}),[t.id]),(0,o.useEffect)((()=>{const e=r.current;return()=>{e.removeToolbarData(t.id)}}),[r,t.id]);const{register:s,unregister:l}=(0,o.useContext)(Hc);return(0,o.useEffect)((()=>(t.beforeSectionHide&&s(t.id,t.beforeSectionHide),()=>{l(t.id)})),[s,l,t.id,t.beforeSectionHide]),n?Dc().createPortal(e,n):null};function Gc(){const e=(0,o.useContext)(Rc),t=(0,o.useContext)(Lc),{checkBeforeHide:n}=(0,o.useContext)(Hc),a=St(t),r=(0,o.useRef)(!1);return ge({openDrawer:t=>{Tr((()=>{if(a.current&&a.current!==t){if(r.current)return;r.current=!0,n(a.current).then((n=>{n&&e.current.openDrawer(t)})).catch((()=>{e.current.openDrawer(t)})).finally((()=>{r.current=!1}))}else e.current.openDrawer(t)}))},closeDrawer:()=>{r.current||(r.current=!0,n(a.current).then((t=>{t&&e.current.closeDrawer()})).catch((()=>{e.current.closeDrawer()})).finally((()=>{r.current=!1})))}})}const Vc=()=>{const e=(0,o.useContext)(Tc),t=(0,o.useContext)(Mc);return{isDrawerOpen:e&&t.length>0}},Uc=["checkbox","radio","submit","button","image","file","color","range"],qc=["selectionchange","focusin","focusout","input","keyup","mouseup","contextmenu"],Zc=e=>!(!e||(e instanceof HTMLInputElement?Uc.includes(e.type.toLowerCase())||e.readOnly:e instanceof HTMLTextAreaElement?e.readOnly:"true"!==e.getAttribute("contenteditable"))),Jc={display:"contents"};function Qc({children:e}){const t=function(){const[e,t]=(0,o.useState)({canCut:!1,canCopy:!1,canPaste:!1}),[n,a]=(0,o.useState)(null);(0,o.useEffect)((()=>{if(!navigator.clipboard||"function"!=typeof navigator.clipboard.writeText)return;const e=()=>{const e=(()=>{const e=document.activeElement,t=window.getSelection();let n=0,a=0,r="";var i;return(i=e)&&(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement)?(n=e.selectionStart||0,a=e.selectionEnd||0,r=e.value.substring(n,a)):t&&(r=t.toString()),{activeElement:e,selectionStart:n,selectionEnd:a,selectedText:r}})();a(e);const n=e.selectedText.length>0,r=Zc(e.activeElement);t({canCopy:n,canCut:n&&r,canPaste:r})};for(const t of qc)document.addEventListener(t,e);return e(),()=>{for(const t of qc)document.removeEventListener(t,e)}}),[]);const r=(0,o.useCallback)((async()=>{if(!n?.selectedText||!n.activeElement)return;const e=n.selectedText;await navigator.clipboard.writeText(e),document.execCommand("delete")}),[n]),i=(0,o.useCallback)((async()=>{n?.selectedText&&await navigator.clipboard.writeText(n.selectedText)}),[n]),s=(0,o.useCallback)((async()=>{if(!n?.activeElement)return;const e=n.activeElement;if(Zc(e))try{const e=await navigator.clipboard.readText();document.execCommand("insertText",!1,e)}catch{}}),[n]);return rn((()=>[{telemetryLabel:"Edit Menu",items:[e.canCut?{label:"Cut",onAction:r}:void 0,e.canCopy?{label:"Copy",onAction:i}:void 0,e.canPaste?{label:"Paste",onAction:s}:void 0].filter(Boolean)}]),[e.canCut,e.canCopy,e.canPaste,r,i,s])}();return s().createElement("div",{"data-testid":"copy-paste-context-menu-container",ref:t,style:Jc},e)}const Xc="undefined"!=typeof window&&window.matchMedia?window.matchMedia("(prefers-color-scheme: dark)"):{matches:!1,addEventListener(){},removeEventListener(){}},ed=({darkMode:e,children:t,legacyUUIDDisplayEncoding:n,onNextGuideGue:a,onNextGuideCueGroup:r,onContextMenuOpen:i,onContextMenuItemClick:l,onDrawerSectionOpen:c,onDrawerSectionHide:d,utmSource:u,utmMedium:p,stackedElementsZIndex:m,popoverPortalContainer:g,disableContextMenus:h,disableGuideCues:f,...y})=>{const b=function(e){const t=void 0!==e,[n,a]=(0,o.useState)(e??Xc.matches);return(0,o.useEffect)((()=>{const e=()=>{a(Xc.matches)};return Xc.addEventListener("change",e),()=>{Xc.removeEventListener("change",e)}}),[]),t?e:n}(e),[v,x]=(0,o.useState)(g??null),[E,C]=(0,o.useState)(null),w=(0,o.useMemo)((()=>({portalContainer:v,scrollContainer:E})),[v,E]);return s().createElement(de.Ay,{darkMode:b,popoverPortalContainer:w},s().createElement(No.Provider,{value:n??""},s().createElement(Fc,{onDrawerSectionOpen:c,onDrawerSectionHide:d},s().createElement(j,{zIndex:m},s().createElement(G,{utmSource:u,utmMedium:p},s().createElement(Or,{onNext:a,onNextGroup:r,disabled:f},s().createElement(Br,y,s().createElement(Bl,null,s().createElement(nn,{disabled:h,onContextMenuOpen:i,onContextMenuItemClick:l},s().createElement(Qc,null,s().createElement($a,null,"function"==typeof t?t({darkMode:b,portalContainerRef:x,scrollContainerRef:C}):t)))))))))))},td=(0,r.AH)({display:"flex",gap:ce.YK[100],alignItems:"center",minWidth:0}),nd=(0,r.AH)({color:le.M.green.dark2}),ad=(0,r.AH)({color:le.M.green.base}),rd=(0,r.AH)({border:"none",background:"none",padding:0,display:"block"}),id=(0,r.AH)({fontWeight:"bold",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),od=(0,r.AH)({color:le.M.gray.dark1}),sd=(0,r.AH)({color:le.M.gray.base}),ld=(0,r.AH)({flexShrink:0}),cd=({items:e,className:t})=>{const n=pe();if(0===e.length)return s().createElement("div",{className:(0,r.cx)(td,t),"data-testid":"breadcrumbs"});const a=e[e.length-1],i=e.slice(0,-1);return s().createElement("div",{className:(0,r.cx)(td,t),"data-testid":"breadcrumbs"},i.map(((e,t)=>s().createElement(o.Fragment,{key:`${t}-${e.name}`},s().createElement(q,{as:"button",hideExternalIcon:!0,className:(0,r.cx)(rd,id),onClick:e.onClick,title:e.name},s().createElement(H.nB,{className:(0,r.cx)(id,n?ad:nd)},e.name)),s().createElement(ie,{glyph:"ChevronRight",size:"small",color:le.M.gray.light1,className:ld})))),s().createElement(H.nB,{key:[e.length-1,a.name].join(""),className:(0,r.cx)(id,n?sd:od)},a.name))},dd=(0,h.cX)("ChevronCollapse",(e=>{const t=pe()?le.M.gray.light1:le.M.gray.dark1;return s().createElement("svg",(0,i.A)({width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg"},e),s().createElement("path",{d:"M4.25 3.25L8 6.5L11.75 3.25M4.25 12.75L8 9.5L11.75 12.75",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}))}));function ud(e,t=!0,n=2){const a=e<0,r=Math.abs(e);if(0===r)return"0 B";const i=t?1e3:1024,o=t?["B","kB","MB","GB","TB","PB","EB","ZB","YB"]:["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"];let s=Math.floor(Math.log(r)/Math.log(i));return s>=o.length&&(s=o.length-1),`${a?"-":""}${(r/Math.pow(i,s)).toFixed(n)} ${o[s]}`}function pd(e){return new Intl.NumberFormat("en",{notation:"compact"}).formatToParts(e).reduce(((e,t)=>`${e}${t.value}`),"")}var md=n(35115);n(70140),n(41652);const gd=({listRef:e,items:t,rowGap:n,estimateItemInitialHeight:a})=>{const[r,i]=(0,o.useState)(t.map(a)),s=(0,o.useRef)(r);s.current=r;const l=(0,o.useRef)(new WeakMap),c=(0,o.useRef)(),d=(0,o.useMemo)((()=>new ResizeObserver((t=>{c.current&&(cancelAnimationFrame(c.current),c.current=void 0),c.current=requestAnimationFrame((()=>{const n=[];for(const{target:e,contentRect:a}of t)if(e instanceof HTMLDivElement){const t=l.current.get(e);void 0!==t&&(n[t]=a.height)}const a=[...s.current],r=Object.assign(new Array,a,n);if((0,Dr.isEqual)(a,r))return void(c.current=void 0);i(r);const o=n.findIndex((e=>"number"==typeof e));-1!==o&&e.current?.resetAfterIndex(o),c.current=void 0}))}))),[]),u=(0,o.useCallback)((e=>{const i=r[e]??a(t[e],e);return void 0!==n&&e!==t.length-1?i+n:i}),[n,r,t,a]),p=(0,o.useMemo)((()=>t.reduce(((e,t,n)=>e+u(n)),0)/t.length),[t,u]),m=(0,o.useMemo)((()=>({observe(e,t){l.current.set(e,t),d.observe(e)},unobserve(e){l.current.delete(e),d.unobserve(e)}})),[d]);return(0,o.useEffect)((()=>()=>{c.current&&(cancelAnimationFrame(c.current),c.current=void 0),d.disconnect()}),[]),{observer:m,getItemSize:u,estimatedItemSize:p}},hd=(0,r.AH)({width:"100%",height:"100%",position:"relative",display:"flex",overflow:"hidden"}),fd=(0,r.AH)({flex:1});function yd({items:e,estimateItemInitialHeight:t,renderItem:n,overScanCount:a,rowGap:r,listOuterContainerClassName:i,dataTestId:l,itemDataTestId:c,initialScrollTop:d,scrollableContainerRef:u,listRef:p,__TEST_LIST_WIDTH:m=1024,__TEST_LIST_HEIGHT:g=768}){const h=(0,o.useRef)(null),f=p??h,{observer:y,estimatedItemSize:b,getItemSize:v}=gd({listRef:f,rowGap:r,items:e,estimateItemInitialHeight:t}),x=(0,o.useMemo)((()=>({items:e,observer:y,itemDataTestId:c,renderItem:n})),[e,y,c,n]),E=!1;return s().createElement("div",{className:hd,"data-testid":l},s().createElement("div",{className:fd},s().createElement(md.Ay,{disableWidth:E,disableHeight:E},(({width:t,height:n})=>s().createElement(Vi._m,{ref:f,width:t,height:n,itemData:x,itemCount:e.length,estimatedItemSize:b,itemSize:v,overscanCount:a,initialScrollOffset:d,outerRef:u,innerElementType:xd,className:i},bd)))))}function bd({index:e,style:t,data:n}){const a=(0,o.useRef)(null),{items:r,observer:i,itemDataTestId:l,renderItem:c}=n,d=r[e];return(0,o.useLayoutEffect)((()=>{const t=a.current;return t&&i.observe(t,e),()=>{t&&i.unobserve(t,e)}}),[i,e]),s().createElement("div",{"data-testid":l,key:e,style:t},c(d,a,e))}const vd=(0,r.AH)({position:"relative"}),xd=(0,o.forwardRef)((function({style:e,...t},n){return s().createElement("div",(0,i.A)({"data-testid":"virtual-list-inner-container",className:vd,ref:n,style:e},t))})),Ed=(0,r.AH)({padding:ce.YK[100]}),Cd=(0,r.AH)({paddingRight:0}),wd=(0,r.AH)({display:"flex",flexDirection:"column"}),Id=(0,r.AH)({backgroundColor:le.M.gray.dark3}),Sd=(0,r.AH)({backgroundColor:le.M.gray.light3}),Ad=(0,r.AH)({display:"flex",alignItems:"center",fontWeight:600,borderBottom:`${ce.YK[100]}px solid ${le.M.gray.light2}`,flexShrink:0,padding:`${ce.YK[100]}px 0px`}),kd=(0,r.AH)({overflow:"auto"}),Dd=(0,r.AH)({padding:`${ce.YK[100]}px 0px`}),Nd=(0,r.AH)({lineHeight:"16px"});function Md(e){const{items:t,label:n,disabled:a,onChange:i}=e,l=pe()?Id:Sd,c=t.every((e=>e.selected)),d=t.every((e=>!e.selected)),p=t.every((e=>e.disabled)),m=(0,o.useCallback)((e=>{i(t.map((t=>({...t,selected:t.disabled?t.selected:!!e.target.checked}))))}),[t,i]),g=(0,o.useCallback)((e=>{i(t.map((t=>e.target.name===`select-${t.id}`?{...t,selected:t.disabled?t.selected:!!e.target.checked}:t)))}),[t,i]);return s().createElement("div",{className:(0,r.cx)(e.className,wd)},s().createElement("div",{className:Ad},s().createElement(u.Sc,{className:(0,r.cx)(Ed,Cd),"data-testid":"select-list-all-checkbox","aria-label":"Select all",onChange:m,checked:c,indeterminate:!c&&!d,disabled:a||p}),s().createElement("div",{className:Nd},n.name)),s().createElement("div",{className:kd},t.map(((e,t)=>s().createElement("div",{className:(0,r.cx)(Dd,t%2==0&&l),key:`select-list-item-${e.id}`,"data-testid":`select-list-item-${e.id}`},s().createElement(u.Sc,{className:Ed,key:`select-${e.id}`,name:`select-${e.id}`,"data-testid":`select-${e.id}`,label:e[n.displayLabelKey],"aria-label":e[n.ariaLabelKey??n.displayLabelKey],onChange:g,checked:e.selected,disabled:e.disabled||a}))))))}n(24355),(0,r.AH)({"--chipBackgroundColor":le.M.blue.light3,"--chipBorderColor":le.M.blue.light2,"--chipColor":le.M.blue.dark1}),(0,r.AH)({"--chipBackgroundColor":le.M.blue.dark2,"--chipBorderColor":le.M.blue.dark1,"--chipColor":le.M.blue.light2}),(0,r.AH)({fontWeight:ce.NM.bold,textTransform:"uppercase",color:"var(--chipColor)",backgroundColor:"var(--chipBackgroundColor)"});const Td=(0,r.AH)({display:"none !important"});function Pd({trigger:e,onSelect:t,...n}){const a=(0,o.useRef)(null),r=s().useCallback((e=>{t(Array.from(e.currentTarget.files??[]))}),[t]);return s().createElement(s().Fragment,null,s().createElement("input",(0,i.A)({},n,{ref:a,type:"file",onChange:r,className:Td})),e({onClick:()=>a.current?.click()}))}var Ld=n(21460)},55469:(e,t,n)=>{n.d(t,{U:()=>s});var a=n(44142),r=n(58886),i=n(65738),o=n(17565);class s{_preferences;constructor(e){this._preferences=new r.p({logger:(0,a.ZQ)(),preferencesStorage:new i._(e)})}savePreferences(e){return Promise.resolve(this._preferences.getPreferences())}refreshPreferences(){return Promise.resolve(this._preferences.getPreferences())}getPreferences(){return this._preferences.getPreferences()}getConfigurableUserPreferences(){return Promise.resolve(this._preferences.getConfigurableUserPreferences())}getPreferenceStates(){return Promise.resolve(this._preferences.getPreferenceStates())}onPreferenceValueChanged(e,t){return()=>{}}createSandbox(){return Promise.resolve(new s(this.getPreferences()))}getPreferencesUser(){return(0,o.sq)(this)}}},56128:(e,t,n)=>{n.d(t,{N:()=>r,e:()=>i});var a=n(56900);const r=[{name:"enableOidc",stage:"released",description:{short:"Enable OIDC Authentication"}},{name:"newExplainPlan",stage:"released",description:{short:"Access explain plan from query bar",long:"Explain plan is now accessible right from the query bar. To view a query’s execution plan, click “Explain” as you would on an aggregation pipeline."}},{name:"showInsights",stage:"released",description:{short:"Show performance insights",long:"Surface visual signals in the Compass interface to highlight potential performance issues and anti-patterns."}},{name:"enableRenameCollectionModal",stage:"released",description:{short:"Enables renaming a collection",long:"Allows users to rename a collection from the sidebar"}},{name:"enableProxySupport",stage:"released",description:{short:"Enables support for explicit proxy configuration.",long:"Allows users to specify proxy configuration for the entire Compass application."}},{name:"showDisabledConnections",stage:"released",description:{short:'Show clusters that are not in a "connectable" state in Atlas Cloud'}},{name:"enableRollingIndexes",stage:"released",description:{short:"Enable creating indexes with the rolling build in Atlas Cloud"}},{name:"enableGlobalWrites",stage:"released",description:{short:"Enable Global Writes tab in Atlas Cloud"}},{name:"enableExportSchema",stage:"released",description:{short:"Enable schema export"}},{name:"enableDataModeling",stage:"released",description:{short:"Design, Visualize, and Evolve your Data Model"}},{name:"enableDataModelingCollapse",stage:"released",description:{short:"Enable Collapse / Expand functionality in Data Modeling"}},{name:"enableContextMenus",stage:"released",description:{short:"Enable context (right-click) menus"}},{name:"enableUnauthenticatedGenAI",stage:"released",description:{short:"Enable GenAI for unauthenticated users"}},{name:"enableSearchActivationProgramP1",stage:"development",description:{short:"Enable interface to view and modify search indexes"}},{name:"enableSearchActivationProgramP2",stage:"development",description:{short:"Enable AI-powered features for pipeline and query results"}},{name:"enableAIAssistant",stage:"released",description:{short:"Enable AI Assistant"}},{name:"enableToolCalling",stage:"released",description:{short:"Enable tool calling in the AI Assistant"}},{name:"enableRestoreWorkspaces",stage:"development",description:{short:"Enable restoring previous workspace tabs on startup"}},{name:"enableAutomaticRelationshipInference",stage:"released",description:{short:"Enable automatic relationship inference during data model generation"}},{name:"enableChatbotEndpointForGenAI",stage:"released",description:{short:"Enable Chatbot API for Generative AI"}},{name:"enableRerank",stage:"preview",description:{short:"Enable $rerank stage UI in Aggregation Pipeline Builder"}},{name:"enableAutoEmbeddingPublicPreview",stage:"preview",description:{short:"Adds UI for auto-embedded vector search indexes"}}],i=Object.fromEntries(r.map((e=>{return[e.name,(t=e,{cli:!0,global:!0,ui:!0,description:t.description,omitFromHelp:"preview"!==t.stage,deriveValue:(e,n)=>{return"released"===t.stage&&"set-cloud-org"!==(a=n(t.name))&&"set-cloud-project"!==a&&"set-cloud-user"!==a?{value:!0,state:"hardcoded"}:{value:e(t.name),state:n(t.name)};var a},validator:a.z.boolean().default(!1),type:"boolean"})];var t})))},58886:(e,t,n)=>{n.d(t,{p:()=>o});var a=n(56900),r=n(73190),i=n(65738);class o{_logger;_onPreferencesChangedCallbacks;_preferencesStorage;_globalPreferences;constructor({logger:e,globalPreferences:t,preferencesStorage:n=new i._}){this._logger=e,this._preferencesStorage=n,this._onPreferencesChangedCallbacks=[],this._globalPreferences={cli:{},global:{},hardcoded:{},atlasCloudUser:{},atlasCloudProject:{},atlasCloudOrg:{},...t},Object.keys(this._globalPreferences.hardcoded).length>0&&this._logger.log.info(this._logger.mongoLogId(1001000159),"preferences","Created Preferences object with hardcoded options",{options:this._globalPreferences.hardcoded})}setupStorage(){return this._preferencesStorage.setup()}async getPreferenceSandboxProperties(){const e={user:this._getUserPreferenceValues(),global:this._globalPreferences};return Promise.resolve(JSON.stringify(e))}static async CreateSandbox(e,t){const{user:n,global:a}=e?JSON.parse(e):{user:{},global:{}},r=new o({logger:t,globalPreferences:a,preferencesStorage:new i._});return await r.savePreferences(n),r}async savePreferences(e={}){const t=Object.keys(e),n=this.getPreferences();if(0===t.length)return n;try{await this._preferencesStorage.updatePreferences(e)}catch(e){if(this._logger.log.error(this._logger.mongoLogId(1001000157),"preferences","Failed to save preferences, error while saving models",{error:e.message}),e instanceof a.z.ZodError)throw e}const r=this.getPreferences();return this._afterPreferencesUpdate(n,r),r}_afterPreferencesUpdate(e,t){const n=Object.fromEntries(Object.entries(t).filter((([t,n])=>n!==e[t])));Object.keys(n).length>0&&this._callOnPreferencesChanged(n)}getPreferences(){return this._computePreferenceValuesAndStates().values}_getUserPreferenceValues(){return this._preferencesStorage.getPreferences()}_getStoredValues(){return{...this._getUserPreferenceValues(),...this._globalPreferences.cli,...this._globalPreferences.global,...this._globalPreferences.hardcoded}}_computePreferenceValuesAndStates(){const e=this._getStoredValues(),t={};for(const e of Object.keys(this._globalPreferences.cli))t[e]="set-cli";for(const e of Object.keys(this._globalPreferences.global))t[e]="set-global";for(const e of Object.keys(this._globalPreferences.atlasCloudUser))t[e]="set-cloud-user";for(const e of Object.keys(this._globalPreferences.atlasCloudProject))t[e]="set-cloud-project";for(const e of Object.keys(this._globalPreferences.atlasCloudOrg))t[e]="set-cloud-org";for(const e of Object.keys(this._globalPreferences.hardcoded))t[e]="hardcoded";const n={...e},a={...t};function i(e){const t=r.Mn[e];return t.deriveValue?t.deriveValue((t=>t===e?n[t]:i(t).value),(t=>t===e?a[t]:i(t).state)):{value:n[e],state:a[e]}}for(const n of Object.keys(r.Mn))(n=>{const a=i(n);e[n]=a.value,void 0!==a.state&&(t[n]=a.state)})(n);return{values:e,states:t}}getConfigurableUserPreferences(){const e=this.getPreferences();return Object.fromEntries(Object.entries(e).filter((([e])=>!0===r.Mn[e].ui)))}getPreferenceStates(){return this._computePreferenceValuesAndStates().states}_callOnPreferencesChanged(e){for(const t of this._onPreferencesChangedCallbacks)t(e)}onPreferencesChanged(e){return this._onPreferencesChangedCallbacks.push(e),()=>{const t=this._onPreferencesChangedCallbacks.indexOf(e);-1!==t&&this._onPreferencesChangedCallbacks.splice(t,1)}}}},60254:(e,t,n)=>{function a(e){const t=e.atlasMetadata?.clusterState;return"DELETED"!==t&&"DELETING"!==t&&"CREATING"!==t&&"PAUSED"!==t}function r(e,t){return"rollingIndexCreation"===t?function(e){const t=e.atlasMetadata;return!!t&&t.supports.rollingIndexes}(e):"globalWrites"===t&&function(e){const t=e.atlasMetadata;return!!t&&t.supports.globalWrites}(e)}n.d(t,{j:()=>r,x:()=>a})},60783:(e,t,n)=>{n.d(t,{Av:()=>d,vk:()=>S,n2:()=>x,wj:()=>m,Do:()=>b,u4:()=>o.u4,S1:()=>I,pV:()=>f,_j:()=>w,PM:()=>o.PM,EE:()=>o.EE,w2:()=>o.w2,qm:()=>u,Gv:()=>o.Gv,jj:()=>p,SA:()=>C,n5:()=>o.n5,VW:()=>o.VW,cy:()=>o.cy,tT:()=>h});var a=n(62183),r=n(96652),i=n.n(r),o=n(26783),s=n(51295);const l=(0,r.createContext)(null),c=(0,r.createContext)(null),d=(0,a.xw)((function({connectionInfoId:e,children:t}){const n=(0,o.EE)(e),a=(0,r.useContext)(c),s=n??a;return"connected"===s?.status?i().createElement(l.Provider,{value:s.info.id},"function"==typeof t?t(s.info):t):null}));function u(){const e=(0,r.useContext)(l),t=(0,r.useContext)(c),n=(0,o.Gv)(e??"")??t?.info;if(!n)throw new Error("Can not access connection info inside a `useConnectionInfo` hook. Make sure that you are only calling this hook inside connected application scope");return n}const p=()=>{const e=(0,r.useContext)(l),t=(0,r.useContext)(c),n=(0,s.HIF)(t?.info),a=(0,o.xO)(e??""),i=a.current?a:n;if(!i.current)throw new Error("Can not access connection info inside a `useConnectionInfoRef` hook. Make sure that you are only calling this hook inside connected application scope");return i},m=(0,a.mb)(p,"connectionInfoRefLocator");var g=n(44969);function h(){const e=(0,o.n5)((e=>!e.isBeingCreated));return(0,r.useMemo)((()=>e.map((e=>({connectionInfo:e.info,connectionStatus:e.status})))),[e])}function f(){const e=h();return(0,r.useMemo)((()=>e.filter((({connectionStatus:e})=>"connected"===e)).map((({connectionInfo:e})=>e))),[e])}class y{appRegistryEmitter;connectionInfoRef;constructor(e,t){this.appRegistryEmitter=e,this.connectionInfoRef=t}emit(e,...t){const n=this.connectionInfoRef.current.id;this.appRegistryEmitter(e,...t,{connectionId:n})}}const b=(0,a.mb)((function(){const e=(0,a.xW)(),t=m();return new y(e.emit.bind(e),t)}));var v=n(34615);const x=({children:e,connectionId:t})=>{const{connectionColorToHex:n,connectionColorToHexActive:a}=(0,v.DM)(),l=(0,o.Ul)(),c=(0,s.D27)(),d=(0,r.useMemo)((()=>{const e=l.find((e=>e.id===t))?.color,r=n(e),i=a(e);if(e&&r&&i)return{"--workspace-tab-background-color":r,"--workspace-tab-top-border-color":r,"--workspace-tab-border-color":c?s.MFm.gray.dark2:s.MFm.gray.light2,"--workspace-tab-color":c?s.MFm.gray.base:s.MFm.gray.dark1,"--workspace-tab-selected-background-color":c?s.MFm.black:s.MFm.white,"--workspace-tab-selected-top-border-color":i,"--workspace-tab-selected-color":c?s.MFm.white:s.MFm.gray.dark3,"&:focus-visible":{"--workspace-tab-border-color":c?s.MFm.blue.light1:s.MFm.blue.base,"--workspace-tab-selected-color":c?s.MFm.blue.light1:s.MFm.blue.base}}}),[t,l,n,a,c]);return i().createElement(s.mUA,{theme:d},e)};var E=n(60254);function C(e,t){return(0,o.d4)((n=>{const a=n.connections.byId[e];return!!a&&(0,E.j)(a.info,t)}))}function w(){const e=(0,o.Pj)();return(0,r.useCallback)((t=>{const n=e.getState().connections.byId[t];return!!n&&(0,E.x)(n.info)}),[e])}const I=(0,a.mb)((function(){const e=u();if(!e)throw new Error("ConnectionInfo for an active connection not available in context. Did you forget to setup ConnectionInfoProvider");return(0,g.HP)(e.id)})),S={Connected:"connected",Disconnected:"disconnected",Failed:"failed"}},62183:(e,t,n)=>{n.d(t,{GL:()=>g,Pe:()=>p,mb:()=>S,xw:()=>A,Ay:()=>N,nk:()=>D,xW:()=>h,TH:()=>f});var a=n(86214),r=n.n(a);class i{_emitter;plugins;constructor(){this._emitter=new(r()),this.plugins={}}static get AppRegistry(){return i}deregisterPlugin(e){return delete this.plugins[e],this}getPlugin(e){return this.plugins[e]}registerPlugin(e,t){return this.plugins[e]=t,this}deactivate(){for(const[e,t]of Object.entries(this.plugins))t.deactivate?.(),this.deregisterPlugin(e);for(const e of this.eventNames())this.removeAllListeners(e)}addListener(e,t){return this.on(e,t)}emit(e,...t){return this._emitter.emit(e,...t)}eventNames(){return this._emitter.eventNames()}listenerCount(e){return this._emitter.listeners(e).length}listeners(e){return this._emitter.listeners(e)}on(e,t){return this._emitter.on(e,t),this}once(e,t){return this._emitter.once(e,t),this}removeListener(e,t){return this._emitter.removeListener(e,t),this}removeAllListeners(e){return this._emitter.removeAllListeners(e),this}}const o=Object.freeze(new i);var s=n(96652),l=n.n(s),c=n(51295);const d=(0,s.createContext)(o),u=(0,s.createContext)(null);function p({value:e,children:t}){const n=(0,c.nfZ)(e??o);return l().createElement(d.Provider,{value:n},t)}function m(){return null===(0,s.useContext)(u)}function g({children:e,...t}){const n=(0,c.nfZ)(t),{localAppRegistry:a,deactivateOnUnmount:r=!0}=n,o=h(),p=m(),[g]=(0,s.useState)((()=>a??(p?o:new i)));return(0,s.useEffect)((()=>{const e=!a||r;return()=>{e&&g.deactivate()}}),[g,a,r]),l().createElement(d.Provider,{value:o},l().createElement(u.Provider,{value:g},e))}function h(){return(0,s.useContext)(d)}function f(){const e=(0,s.useContext)(u);if(!e)throw new Error("No local AppRegistry registered within this context");return e}n(21261),n(92879),n(31977),n(49743),n(9656),n(72673),n(35467),n(94476),n(64971),n(24330),n(83478),n(65166),n(1256),n(61038),n(73035),n(23855);var y=n(19125);class b{cleanupFns=new Set;deactivateController=new AbortController;constructor(){this.addCleanup((()=>{this.deactivateController.abort()}))}get signal(){return this.deactivateController.signal}on=(e,t,n)=>{const a=(...e)=>{n(...e)};e.on(t,a),this.addCleanup((()=>{e.removeListener(t,a)}))};addCleanup=e=>{e&&this.cleanupFns.add(e)};cleanup=()=>{for(const e of this.cleanupFns.values())e()}}function v({store:e,actions:t,children:n}){const a=(0,s.useRef)(e),[r,i]=(0,s.useState)((()=>e.state));return l().useEffect((()=>{const e=a.current.listen?.((e=>i({...e})),null);return()=>e?.()}),[]),l().cloneElement(n,{store:e,actions:t,...t,...r})}const x={pluginName:"$$root",mockedEnvironment:!1,mockServices:{},disableChildPluginRendering:!1},E=l().createContext(null),C=(e,t=x)=>(0,s.useContext)(E)?.[e]??t[e];let w=!1;const I=Symbol("CompassServiceLocatorFunction");function S(e,t=e.name){return Object.assign((function(...n){if(!w)throw new Error(`Using service locator function "${t}" outside of the service location lifecycle. Make sure that service locator function is passed as a second argument to the registerCompassPlugin method and is not used directly in a React render method.`);return e.call(this,...n)}),{[I]:!0})}function A(e){const t=`ServiceProvider(${e.displayName??e.name})`,n=function(t){let n;try{w=!0,n=e(t)}finally{w=!1}return l().createElement(l().Fragment,null,n)};return n.displayName=t,n}function k(e,t,n,a){const r=`${e.name}.Plugin`,i=C("mockedEnvironment",a),o=C("mockServices",a),l=h(),c=f();let d;try{w=!0,d=Object.fromEntries(Object.keys({...i?o:{},...t}).map((e=>{const n=i&&!!o?.[e];if(!n&&t?.[e]&&(a=t[e],!Object.prototype.hasOwnProperty.call(a,I)))throw new Error(`Function "${t[e].name}" that is being passed as a service locator can not be identified as one. Make sure that you created a service locator function using createServiceLocator helper function.`);var a;const s=n?o[e]:t?.[e]();try{return[e,s]}catch(t){throw t&&"object"==typeof t&&"message"in t&&"string"==typeof t.message&&(t.message+=` [locating service '${e}' for '${r}']`),t}})))}finally{w=!1}const[{store:u,actions:p,context:m}]=(0,s.useState)((()=>c.getPlugin(r)??(()=>{const t=e.activate(n,{globalAppRegistry:l,localAppRegistry:c,...d},new b);return c.registerPlugin(r,t),t})()));return{store:u,actions:p,context:m}}function D(e,t){const n=e.component,a=a=>{const r=C("mockedEnvironment"),i=C("pluginName"),o=C("disableChildPluginRendering");if(r&&i!==e.name&&o)return null;const{store:s,actions:c,context:d}=k(e,t,a);return function(e){return e&&"object"==typeof e&&Object.prototype.hasOwnProperty.call(e,"dispatch")}(s)?l().createElement(y.Kq,{context:d,store:s},l().createElement(n,a)):l().createElement(v,{store:s,actions:c},l().createElement(n,a))};return Object.assign(a,{displayName:e.name,useActivate:n=>k(e,t,n),withMockServices(n={},r){const{globalAppRegistry:o=new i,localAppRegistry:s=o,...c}=n,u={...x,mockedEnvironment:!0,pluginName:e.name,mockServices:c,...r};function p(e){const t=m(),n=!!c.localAppRegistry||!!c.globalAppRegistry,r=t||n;return l().createElement(E.Provider,{value:u},r?l().createElement(d.Provider,{value:o},l().createElement(g,{localAppRegistry:s},l().createElement(a,e))):l().createElement(a,e))}return Object.assign(p,{displayName:e.name,useActivate:n=>k(e,t,n,u),withMockServices:()=>p})}})}const N=i},65738:(e,t,n)=>{n.d(t,{_:()=>r});var a=n(73190);class r{preferences=(0,a.FX)();constructor(e){this.preferences={...this.preferences,...e}}getPreferences(){return this.preferences}async updatePreferences(e){this.preferences={...this.preferences,...e}}async setup(){}}},67305:(e,t,n)=>{n.d(t,{A:()=>i});var a=n(71520),r=n.n(a)()(!1);r.push([e.id,":root {\n --compass-ag-grid-background: #ffffff;\n --compass-ag-grid-header-background: #f9fbfa;\n --compass-ag-grid-header-background-hover: #e8edeb;\n --compass-ag-grid-background-hover: #f9fbfa;\n --compass-ag-grid-shadow: rgba(0, 30, 43, 0.15);\n --compass-ag-grid-border: #e8edeb;\n --compass-ag-grid-shadow-inset: #c1c7c6;\n --compass-ag-grid-breadcrumb-active-border: #00a35c;\n --compass-ag-grid-full-width-row-border: #0498ec;\n --compass-ag-grid-full-width-row-size: 2px;\n --compass-ag-grid-empty-cell-background: #f9fbfa;\n --compass-ag-grid-header-border: #c1c7c6;\n --compass-ag-grid-cell-editor-background: #ffffff;\n --compass-ag-grid-cell-editor-border: #c1c7c6;\n --compass-ag-grid-deleted-cell-background: #ffeae5;\n --compass-ag-grid-deleted-cell-border: #ffcdc7;\n --compass-ag-grid-edited-cell-background: #fef7db;\n --compass-ag-grid-edited-cell-border: #fef7db;\n --compass-ag-grid-added-cell-background: #e3fcf7;\n --compass-ag-grid-added-cell-border: #c0fae6;\n --compass-ag-grid-invalid-cell-background: #ffcdc7;\n --compass-ag-grid-invalid-cell-border: #db3030;\n}\n.document-table-view-container {\n width: 100%;\n height: 100%;\n}\n.document-table-view-container-darkmode {\n --compass-ag-grid-background: #1c2d38;\n --compass-ag-grid-header-background: #3d4f58;\n --compass-ag-grid-header-background-hover: #5c6c75;\n --compass-ag-grid-background-hover: #3d4f58;\n --compass-ag-grid-shadow: rgba(0, 30, 43, 0.15);\n --compass-ag-grid-border: #3d4f58;\n --compass-ag-grid-shadow-inset: #5c6c75;\n --compass-ag-grid-breadcrumb-active-border: #00a35c;\n --compass-ag-grid-full-width-row-border: transparent;\n --compass-ag-grid-full-width-row-size: 0;\n --compass-ag-grid-empty-cell-background: #001e2b;\n --compass-ag-grid-header-border: #3d4f58;\n --compass-ag-grid-cell-editor-background: #1c2d38;\n --compass-ag-grid-cell-editor-border: #3d4f58;\n --compass-ag-grid-deleted-cell-background: #5b0000;\n --compass-ag-grid-deleted-cell-border: #970606;\n --compass-ag-grid-edited-cell-background: #4c2100;\n --compass-ag-grid-edited-cell-border: #4c2100;\n --compass-ag-grid-added-cell-background: #023430;\n --compass-ag-grid-added-cell-border: #00684a;\n --compass-ag-grid-invalid-cell-background: #970606;\n --compass-ag-grid-invalid-cell-border: #db3030;\n}\n.document-table-view-container .ag-dnd-ghost {\n background: var(--compass-ag-grid-background);\n border-color: var(--compass-ag-grid-border);\n}\n.document-table-view-container .ag-parent {\n font-family: 'Source Code Pro', Menlo, monospace;\n font-size: 12px;\n height: 100%;\n}\n.document-table-view-container .ag-root {\n background-color: var(--compass-ag-grid-background);\n box-shadow: 0 0px 6px 0 var(--compass-ag-grid-shadow);\n border-radius: 0px 3px 3px 3px;\n}\n.document-table-view-container .ag-bl-full-height {\n background-color: var(--compass-ag-grid-background);\n box-shadow: 0 0px 6px 0 var(--compass-ag-grid-shadow);\n border-radius: 0px 3px 3px 3px;\n}\n.document-table-view-container .ag-header {\n background: var(--compass-ag-grid-header-background);\n box-shadow: 0 2px 10px 0 var(--compass-ag-grid-shadow), inset 0 -1px 0 0 var(--compass-ag-grid-shadow-inset);\n}\n.document-table-view-container .ag-header-cell {\n border: 0;\n line-height: 25px;\n padding-left: 7px;\n}\n.document-table-view-container .ag-header-cell:hover {\n background-color: var(--compass-ag-grid-header-background-hover);\n cursor: grab;\n}\n.document-table-view-container .ag-header-container {\n position: static;\n}\n.document-table-view-container .ag-header-breadcrumb-home-icon {\n margin-right: 5px;\n vertical-align: text-top;\n}\n.document-table-view-container .ag-header-breadcrumb-container {\n display: flex;\n}\n.document-table-view-container .ag-header-breadcrumb-tab {\n height: 25px;\n padding: 4px 10px;\n font-weight: bold;\n font-size: 12px;\n text-overflow: ellipsis;\n overflow: hidden;\n display: block;\n white-space: nowrap;\n background-color: var(--compass-ag-grid-header-background);\n border-radius: 3px 3px 0 0;\n border: none;\n box-shadow: 0 -1px 6px 0 var(--compass-ag-grid-shadow);\n cursor: pointer;\n}\n.document-table-view-container .ag-header-breadcrumb-tab-active {\n border-left: 5px solid var(--compass-ag-grid-breadcrumb-active-border);\n}\n.document-table-view-container .ag-header-viewport {\n margin-right: 0 !important;\n}\n.document-table-view-container .ag-row {\n box-sizing: border-box;\n background-color: var(--compass-ag-grid-background);\n}\n.document-table-view-container .ag-row-hover {\n background-color: var(--compass-ag-grid-background-hover);\n}\n.document-table-view-container .ag-row-hover .table-view-cell,\n.document-table-view-container .ag-row-hover .table-view-cell-row-number,\n.document-table-view-container .ag-row-hover .table-view-cell-is-empty,\n.document-table-view-container .ag-row-hover .table-view-cell-is-uneditable {\n background-color: var(--compass-ag-grid-background-hover);\n}\n.document-table-view-container .ag-row-hover .ag-cell-first-right-pinned {\n z-index: 4;\n}\n.document-table-view-container .ag-row-hover .table-view-row-actions-panel {\n visibility: visible;\n}\n.document-table-view-container .ag-row-focus {\n background-color: var(--compass-ag-grid-background);\n}\n.document-table-view-container .ag-full-width-row {\n background: var(--compass-ag-grid-background);\n border-bottom: var(--compass-ag-grid-full-width-row-size) solid var(--compass-ag-grid-full-width-row-border);\n}\n.document-table-view-container .ag-cell {\n border-right: 0.5px solid var(--compass-ag-grid-border);\n border-bottom: 0.5px solid var(--compass-ag-grid-border);\n position: absolute;\n outline: 0;\n}\n.document-table-view-container .ag-cell-focus {\n overflow: visible !important;\n}\n.document-table-view-container .ag-cell-subtable-objectid {\n border-right: 3px solid var(--compass-ag-grid-border);\n border-bottom: 0;\n}\n.document-table-view-container .ag-cell-subtable-objectid .table-view-cell {\n border-bottom: 0.5px solid var(--compass-ag-grid-border);\n}\n.document-table-view-container .ag-popup-editor {\n outline: 0;\n}\n.document-table-view-container .ag-pinned-right-header {\n width: 0 !important;\n}\n.document-table-view-container .ag-pinned-right-cols-container {\n margin-top: 1px;\n border-left: 1px solid var(--compass-ag-grid-border);\n}\n.document-table-view-container .ag-pinned-right-cols-container .ag-row {\n border: 0;\n background: transparent;\n}\n.document-table-view-container .ag-pinned-right-cols-container .ag-cell {\n border: 0;\n overflow: visible;\n}\n.document-table-view-container .ag-pinned-left-header {\n position: relative;\n}\n.document-table-view-container .ag-body-viewport {\n width: 100%;\n}\n.document-table-view-container .table-view-row-actions {\n position: absolute;\n display: flex;\n justify-content: flex-end;\n width: 100%;\n height: 28px;\n z-index: 100;\n margin-top: -1px;\n}\n.document-table-view-container .table-view-row-actions-panel {\n display: flex;\n justify-content: center;\n width: 100%;\n background: var(--compass-ag-grid-background);\n border-bottom: 0.5px solid var(--compass-ag-grid-border);\n padding: 0 8px;\n}\n.document-table-view-container .table-view-cell {\n padding: 0px 5px;\n margin: 1px;\n line-height: 26px;\n}\n.document-table-view-container .table-view-cell-circle-button {\n position: absolute;\n z-index: 100;\n display: flex;\n justify-content: center;\n align-items: center;\n opacity: 0;\n right: 4px;\n top: 4px;\n width: 20px;\n height: 20px;\n border: none;\n border-radius: 50%;\n background: var(--compass-ag-grid-background);\n box-shadow: 0 2px 5px 0 var(--compass-ag-grid-shadow);\n cursor: pointer;\n}\n.document-table-view-container .table-view-cell-circle-button-undo {\n top: 2px;\n}\n.document-table-view-container .table-view-cell-circle-button-left {\n right: 20px;\n}\n.document-table-view-container .table-view-cell .editable-element {\n text-overflow: ellipsis;\n overflow: hidden;\n white-space: nowrap;\n height: 100%;\n cursor: text;\n}\n.document-table-view-container .table-view-cell .editable-element .element-value-is-string {\n white-space: nowrap;\n}\n.document-table-view-container .table-view-cell .editable-element .element-value-is-objectid::before,\n.document-table-view-container .table-view-cell .editable-element .element-value-is-objectid::after {\n content: '';\n}\n.document-table-view-container .table-view-cell-is-empty {\n background-color: var(--compass-ag-grid-empty-cell-background);\n line-height: 26px;\n margin: 1px;\n padding-left: 5px;\n padding-right: 5px;\n}\n.document-table-view-container .table-view-cell-is-uneditable {\n background: var(--compass-ag-grid-background);\n}\n.document-table-view-container .table-view-cell:hover .table-view-cell-circle-button {\n opacity: 1;\n}\n.document-table-view-container .table-view-cell-is-deleted,\n.document-table-view-container .table-view-cell-is-edited,\n.document-table-view-container .table-view-cell-is-added,\n.document-table-view-container .table-view-cell-is-invalid,\n.document-table-view-container .table-view-cell-is-uneditable {\n height: 24px;\n line-height: 24px;\n margin: 2px 1px;\n padding-left: 5px;\n overflow-y: hidden;\n}\n.document-table-view-container .table-view-cell-is-deleted .table-view-cell-circle-button,\n.document-table-view-container .table-view-cell-is-edited .table-view-cell-circle-button,\n.document-table-view-container .table-view-cell-is-added .table-view-cell-circle-button,\n.document-table-view-container .table-view-cell-is-invalid .table-view-cell-circle-button,\n.document-table-view-container .table-view-cell-is-uneditable .table-view-cell-circle-button {\n margin-top: 2px;\n}\n.document-table-view-container .table-view-cell-is-deleted .editable-element,\n.document-table-view-container .table-view-cell-is-edited .editable-element,\n.document-table-view-container .table-view-cell-is-added .editable-element,\n.document-table-view-container .table-view-cell-is-invalid .editable-element,\n.document-table-view-container .table-view-cell-is-uneditable .editable-element {\n min-height: 24px;\n z-index: 1;\n}\n.document-table-view-container .table-view-cell-is-deleted:hover .table-view-cell-circle-button,\n.document-table-view-container .table-view-cell-is-edited:hover .table-view-cell-circle-button,\n.document-table-view-container .table-view-cell-is-added:hover .table-view-cell-circle-button,\n.document-table-view-container .table-view-cell-is-invalid:hover .table-view-cell-circle-button,\n.document-table-view-container .table-view-cell-is-uneditable:hover .table-view-cell-circle-button {\n opacity: 1;\n}\n.document-table-view-container .table-view-cell-is-deleted {\n background-color: var(--compass-ag-grid-deleted-cell-background);\n border: 1px solid var(--compass-ag-grid-deleted-cell-border);\n}\n.document-table-view-container .table-view-cell-is-edited {\n background-color: var(--compass-ag-grid-edited-cell-background);\n border: 1px solid var(--compass-ag-grid-edited-cell-border);\n}\n.document-table-view-container .table-view-cell-is-added {\n background-color: var(--compass-ag-grid-added-cell-background);\n border: 1px solid var(--compass-ag-grid-added-cell-border);\n}\n.document-table-view-container .table-view-cell-is-invalid {\n background-color: var(--compass-ag-grid-invalid-cell-background);\n border: 1px solid var(--compass-ag-grid-invalid-cell-border);\n}\n.document-table-view-container .table-view-cell-row-number {\n display: flex;\n align-items: center;\n justify-content: center;\n color: var(--compass-ag-grid-row-number-text);\n height: 27px;\n}\n.document-table-view-container .table-view-cell-header {\n text-overflow: ellipsis;\n white-space: nowrap;\n overflow: hidden;\n text-align: left;\n border-right: 0.5px solid var(--compass-ag-grid-border);\n user-select: none;\n}\n.document-table-view-container .table-view-cell-header > * {\n user-select: none;\n}\n.document-table-view-container .table-view-cell-header-icon {\n float: right;\n line-height: 25px;\n margin-right: 5px;\n}\n.document-table-view-container .table-view-cell-header-subtable-objectid {\n border-right: 3px solid var(--compass-ag-grid-header-border);\n position: relative;\n}\n.document-table-view-container .table-view-cell-editor {\n position: absolute;\n z-index: 500;\n display: flex;\n justify-content: center;\n align-items: center;\n height: 32px;\n background: var(--compass-ag-grid-cell-editor-background);\n border: 1px solid var(--compass-ag-grid-cell-editor-border);\n border-radius: 2px;\n box-shadow: 0 2px 6px 0 var(--compass-ag-grid-shadow);\n outline: 0;\n padding: 1px 5px;\n margin-top: -2px;\n margin-left: -8px;\n}\n.document-table-view-container .table-view-cell-editor-types {\n margin-left: 3px;\n}\n.document-table-view-container .table-view-cell-editor-actions {\n display: flex;\n}\n",""]);const i=r},68526:(e,t,n)=>{n.d(t,{Ay:()=>w,Cw:()=>x,XG:()=>y,Zk:()=>b}),n(95039),n(59509),n(25691),n(23177),n(3142),n(51615),n(84217),n(25953),n(42319),n(28465),n(12887),n(36106),n(84542),n(57068),n(69517);var a=n(12738),r=n(37983);const i="compass-generative-ai/atlas-optin/OpenOptInModal",o="compass-generative-ai/atlas-optin/CloseOptInModal",s="compass-generative-ai/atlas-optin/AttemptStart",l="compass-generative-ai/atlas-optin/AttemptEnd",c="compass-generative-ai/atlas-optin/AtlasOptInStart",d="compass-generative-ai/atlas-optin/AtlasOptInSuccess",u="compass-generative-ai/atlas-optin/AtlasOptInError",p="compass-generative-ai/atlas-optin/AtlasOptInCancel",m={state:"initial",isCloudOptIn:!0,error:null,isModalOpen:!1,attemptId:null},g=new Map;let h=0;function f(e){if(!e){e=++h;const t=new AbortController;let n,a;const r=new Promise(((e,t)=>{n=e,a=t}));n&&a&&g.set(e,{id:e,controller:t,promise:r,resolve:n,reject:a})}const t=g.get(e);if(!t)throw new Error("Trying to get the state for a non-existing opt in attempt");return t}const y=({signal:e,isCloudOptIn:t})=>(n,a,{preferences:r})=>{const{state:i}=a().optIn;if(("optin-success"===i||r.getPreferences().optInGenAIFeatures)&&r.getPreferences().enableGenAIFeaturesAtlasProject)return Promise.resolve();const o=n((c=()=>{n(v({isCloudOptIn:t}))},(e,t)=>{if(t().optIn.attemptId)throw new Error("Can't start opt in with prompt while another opt in attempt is in progress");const n=f();return e({type:s,attemptId:n.id}),n.promise.finally((()=>{e({type:l,attemptId:n.id})})).catch((()=>{})),setTimeout(c),n}));var c;return e?.addEventListener("abort",(()=>{n(x(e.reason))})),o.promise},b=()=>async(e,t,{atlasAiService:n})=>{if(["in-progress","optin-success"].includes(t().optIn.state))return;const{attemptId:r}=t().optIn;if(null===r)return;const{controller:{signal:i},resolve:o,reject:s}=f(t().optIn.attemptId);e({type:c,isCloudOptIn:t().optIn.isCloudOptIn});try{(0,a.Te)(i),await n.optIntoGenAIFeatures(),e(C()),g.clear(),o()}catch(t){if(i.aborted)return;e({type:u,error:t.message}),s(t)}},v=({isCloudOptIn:e})=>({type:i,isCloudOptIn:e}),x=e=>t=>{t(E(e)),t({type:o})},E=e=>(t,n)=>{if(null===n().optIn.attemptId)return;const a=f(n().optIn.attemptId);a.controller.abort(),a.reject(e??a.controller.signal.reason),t({type:p})},C=()=>({type:d}),w=(e={...m},t)=>(0,r.v)(t,s)?{...e,attemptId:t.attemptId}:(0,r.v)(t,l)?{...e,attemptId:null}:(0,r.v)(t,c)?{...e,state:"in-progress",isCloudOptIn:t.isCloudOptIn}:(0,r.v)(t,d)?{...e,state:"optin-success",error:null,isModalOpen:!1}:(0,r.v)(t,u)?{...e,state:"error",error:t.error,isModalOpen:!1}:(0,r.v)(t,p)?{...m,state:"canceled"}:(0,r.v)(t,i)?{...e,isModalOpen:!0}:(0,r.v)(t,o)?{...e,isModalOpen:!1}:e},68691:(e,t,n)=>{n.d(t,{RH:()=>Dm,tz:()=>Nm});var a=n(96652),r=n.n(a),i=n(62183),o=n(19125),s=n(51295);const l=6e4,c=1e5,d="The $out operator will cause the pipeline to persist the results to the specified location (collection, S3, or Atlas). If the collection exists it will be replaced.",u="The $merge operator will cause the pipeline to persist the results to the specified location.",p="https://www.mongodb.com/docs/manual/core/aggregation-pipeline/",m="https://www.mongodb.com/docs/manual/reference/operator/aggregation";var g=n(20625);const h="aggregation-comment-mode",f="aggregation-settings-comment-mode-description",y="aggregation-settings-comment-mode-label",b="aggregation-sample-size",v="aggregation-settings-sample-size-description",x="aggregation-settings-sample-size-label",E="aggregation-limit",C="aggregation-settings-limit-description",w="aggregation-settings-limit-label",I=(0,s.AHW)({display:"flex",padding:`${s.YKD[100]}px ${s.YKD[200]}px`,alignItems:"center",justifyContent:"space-between",borderBottom:`1px solid ${s.MFm.gray.light2}`,boxShadow:`1px 1px 1px ${s.MFm.gray.light2}`}),S=(0,s.AHW)({borderColor:s.MFm.gray.dark2,boxShadow:`1px 1px 1px ${s.MFm.gray.dark2}`}),A=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[200]}),k=(0,s.AHW)({borderLeft:`1px solid ${s.MFm.gray.light2}`,boxShadow:`1px 1px 1px ${s.MFm.gray.light2}`,background:s.MFm.gray.light3,position:"absolute",width:"580px",height:"100%",top:"0",right:"0px",transition:"right 0.20s ease-in-out",fontSize:"1em",zIndex:500}),D=(0,s.AHW)({background:s.MFm.gray.dark3,borderColor:s.MFm.gray.dark2,boxShadow:`1px 1px 1px ${s.MFm.gray.dark2}`}),N=(0,s.AHW)({margin:s.YKD[200],padding:`${s.YKD[200]}px ${s.YKD[400]}px`,backgroundColor:s.MFm.white,display:"flex",alignItems:"center",gap:s.YKD[200]}),M=(0,s.AHW)({backgroundColor:s.MFm.black}),T=(0,s.AHW)({flex:"none",width:2*s.YKD[1400],marginLeft:"auto",display:"flex",justifyContent:"flex-end"}),P=(0,s.AHW)({marginTop:s.YKD[200]}),L=function({isCommenting:e,isExpanded:t,largeLimit:n,limit:i,settings:o,applySettings:l,setSettingsLimit:c,setSettingsSampleSize:d,toggleSettingsIsCommentMode:u,toggleSettingsIsExpanded:p}){const m=(0,g.Fg)("enableAggregationBuilderExtraOptions"),L=(0,s.D27)(),O=(0,a.useCallback)((e=>{d(parseInt(e.currentTarget.value,10))}),[d]),R=(0,a.useCallback)((e=>{c(parseInt(e.currentTarget.value,10))}),[c]),H=(0,a.useCallback)((()=>{l(),p()}),[l,p]),F=(0,a.useMemo)((()=>o.isDirty?o.limit:n),[o,n]),W=(0,a.useMemo)((()=>o.isDirty?o.isCommentMode:e),[o,e]),j=(0,a.useMemo)((()=>o.isDirty?o.sampleSize:i),[o,i]);return t?r().createElement("div",{className:(0,s.cx)(k,L&&D)},r().createElement("div",{className:(0,s.cx)(I,L&&S)},r().createElement(s.nBu,{weight:"medium"},"Settings"),r().createElement("div",{className:A},r().createElement(s.$nd,{"data-testid":"aggregation-settings-cancel",size:"xsmall",onClick:p},"Cancel"),r().createElement(s.$nd,{"data-testid":"aggregation-settings-apply",size:"xsmall",variant:"primary",onClick:H},"Apply"))),r().createElement("div",{className:(0,s.cx)(N,L&&M)},r().createElement("div",null,r().createElement(s.JU7,{htmlFor:h,id:y},"Comment Mode"),r().createElement(s.VYo,{className:P,id:f},"When enabled, adds helper comments to each stage. Only applies to new stages.")),r().createElement("div",{className:T},r().createElement(s.Sc0,{id:h,"aria-labelledby":y,"aria-describedby":f,type:"checkbox",checked:W,onChange:u}))),r().createElement("div",{className:(0,s.cx)(N,L&&M)},r().createElement("div",null,r().createElement(s.JU7,{htmlFor:b,id:x},"Number of Preview Documents"),r().createElement(s.VYo,{className:P,id:v},"Specify the number of documents to show in the preview.")),r().createElement("div",{className:T},r().createElement(s.ksK,{id:b,"aria-labelledby":x,"aria-describedby":v,type:"number",min:"0",placeholder:"10",value:`${j}`,onChange:O}))),m&&r().createElement("div",{className:(0,s.cx)(N,L&&M)},r().createElement("div",null,r().createElement(s.JU7,{htmlFor:E,id:w},"Limit"),r().createElement("div",{id:C},r().createElement(s.VYo,{className:P},"Limits input documents before $group, $bucket, and $bucketAuto stages. Set a limit to make the preview run faster."),r().createElement(s.VYo,{className:P},"Note: this setting is only applied for the document previews, it is not applied when the pipeline is run."))),r().createElement("div",{className:T},r().createElement(s.ksK,{"data-testid":"aggregation-settings-limit-input",id:E,"aria-labelledby":w,"aria-describedby":C,type:"number",min:"0",placeholder:"100000",value:`${F}`,onChange:R})))):null};var O=n(28508);class R extends a.PureComponent{static displayName="SavingPipelineModalComponent";componentDidUpdate(e){e.isOpen!==this.props.isOpen&&this.props.isOpen&&this.props.track("Screen",{name:"save_pipeline_modal"},void 0)}onNameChanged(e){this.props.savingPipelineNameChanged(e.currentTarget.value)}save(){this.props.isSaveAs&&this.props.clonePipeline(),this.props.savingPipelineApply(),this.props.saveCurrentPipeline()}render(){const e=this.props.isSaveAs?"Save Pipeline As...":"Save Pipeline";return r().createElement(s.k5W,{title:e,open:this.props.isOpen,onSubmit:this.save.bind(this),onCancel:this.props.savingPipelineCancel,submitButtonText:"Save",submitDisabled:""===this.props.name,"data-testid":"save-pipeline-modal"},r().createElement(s.ksK,{id:"save-pipeline-name",value:this.props.name,onChange:this.onNameChanged.bind(this),label:"Name",name:"name"}))}}const H=(0,O.Ql)(R);var F=n(42279),W=(n(95039),n(39059));const j={promoteValues:!1,allowDiskUse:!0,bsonRegExp:!0};async function B({dataService:e,preferences:t,signal:n,namespace:a,pipeline:r,options:i,skip:o,limit:s}){const l={...j,...i,maxTimeMS:(0,g.Tv)(t,i.maxTimeMS)};return e.aggregate(a,r.concat(o?[{$skip:o}]:[]).concat(s?[{$limit:s}]:[]),l,{abortSignal:n})}n(59509),n(25691),n(23177),n(3142),n(51615),n(84217),n(25953),n(42319),n(28465),n(12887),n(36106),n(84542),n(57068),n(69517),n(21261),n(92879),n(31977),n(49743),n(9656),n(72673),n(35467),n(94476),n(64971),n(24330),n(83478),n(65166),n(1256),n(61038),n(73035),n(23855);var z=n(17855),_=n(69692),$=n(14552),Y=n(19461),K=n(70724);class G extends SyntaxError{loc;code;constructor(e,t,n){super(e),this.loc=t,this.code=n}}function V(e,t){return(0,K.G8)((0,$.Ay)(e).code,"javascript-expression",t)}function U(e){const t=(0,Y.Ay)(e,{mode:Y.X6.Strict,allowComments:!0,allowMethods:!0});if(!t||"object"!=typeof t)throw new Error("Source expression is invalid");return t}function q(e){return e?.every((e=>e===_.Ah))}const Z=new Map;function J(e){return Object.keys(e??{})[0]}function Q(e,t){if(!t)return null;const n=J(t),a=n&&t[n];return a?"$merge"===n?function(e,t){const{database:n}=(0,z.Ay)(e),a="string"==typeof t?t:t.into;return a?"string"==typeof a?`${n}.${a}`:a.atlas?null:a.db&&a.coll?`${a.db}.${a.coll}`:null:null}(e,a):"$out"===n?function(e,t){const{database:n}=(0,z.Ay)(e);return"string"==typeof t?`${n}.${t}`:t.s3||t.atlas?null:t.db&&t.coll?`${t.db}.${t.coll}`:null}(e,a):null:null}const X=new Set(_.BF.map((e=>e.value))),ee=new Set(_.n.filter((e=>q(e.env))).map((e=>e.value)));function te(e){return!!e&&X.has(e)}function ne(e){return!!e&&ee.has(e)}function ae(e){return!!e&&["$search","$searchMeta","$vectorSearch"].includes(e)}function re(e,t){if(!e||!t||!ae(e))return null;try{const n=U(`{${e}: ${t}}`),a=n[e]?.index;return"string"==typeof a?a:null}catch{return null}}function ie(e){const t={searchIndexName:null,searchStageOperator:null};try{const n=U(e);if(!Array.isArray(n)||0===n.length)return t;const a=n[0],r=J(a);if(!ae(r))return t;const i=a[r]?.index;return{searchIndexName:"string"==typeof i?i:null,searchStageOperator:r}}catch{return t}}function oe(e){return _.n.map((t=>"$vectorSearch"===t.name&&e?_.cn:t))}const se=new Map,le=e=>e?`${m}/${e.replace(/^\$/,"")}/`:null;const ce=e=>J(e[e.length-1])??"",de=e=>te(ce(e)),ue=(e,t,n)=>![_.Ub,_.Ah].includes(e)&&ne(t)&&[40324,31082,6047400,6047401,224].includes(Number(n?.code??-1));function pe(e){return!!e.syntaxError&&!!e.stageOperator&&!!e.value}n(81546);var me=n(13353);const ge="aggregations/CLONE_PIPELINE";var he=n(26250);function fe(e,t){return e.type===t}var ye=n(44142),be=n(15088).process;const ve={status:"ready",aiPromptText:"",errorMessage:void 0,errorCode:void 0,isInputVisible:!1,aiPipelineRequestId:null,lastAIPipelineRequestId:null,isAggregationGeneratedFromQuery:!1},xe="compass-aggregations/pipeline-builder/pipeline-ai/AIPipelineStarted",Ee="compass-aggregations/pipeline-builder/pipeline-ai/AIPipelineFailed",Ce="compass-aggregations/pipeline-builder/pipeline-ai/CancelAIPipelineGeneration",we="compass-aggregations/pipeline-builder/pipeline-ai/resetIsAggregationGeneratedFromQuery",Ie="compass-aggregations/pipeline-builder/pipeline-ai/ShowInput",Se="compass-aggregations/pipeline-builder/pipeline-ai/HideInput",Ae="compass-aggregations/pipeline-builder/pipeline-ai/ChangeAIPromptText",ke="compass-aggregations/pipeline-builder/pipeline-ai/LoadGeneratedPipeline",De="compass-aggregations/pipeline-builder/pipeline-ai/PipelineGeneratedFromQuery",Ne=new Map;function Me(e){const t=Ne.get(e);return t?.abort(),Ne.delete(e)}function Te({editor_view_type:e,statusCode:t,errorMessage:n,errorName:a,errorCode:r,log:i,requestId:o,connectionInfo:s,track:l}){i.warn((0,ye.oW)(1001000230),"AIPipeline","AI pipeline request failed",{statusCode:t,errorMessage:n,errorName:a,errorCode:r,requestId:o}),l("AI Response Failed",{editor_view_type:e,error_code:r||"",status_code:t,error_name:a,request_id:o},s)}const Pe=()=>(e,t)=>{const n=t().pipelineBuilder.aiPipeline.aiPipelineRequestId;null!==n&&Me(n),e({type:Ce})},Le=()=>async(e,t,{atlasAiService:n})=>{try{"true"!==be.env.COMPASS_E2E_SKIP_AI_OPT_IN&&await n.ensureAiFeatureAccess(),e({type:Ie})}catch{}},Oe="aggregations/id/CREATE_ID",Re="aggregations/saved-pipeline",He=`${Re}/ADD`,Fe=`${Re}/RESTORE_PIPELINE`,We={pipelines:[],isLoaded:!1},je={[He]:(e,t)=>({...e,pipelines:t.pipelines,isLoaded:!0}),[Fe]:e=>({...e,isListVisible:!1})},Be=()=>(e,t,{pipelineStorage:n,logger:{debug:a},globalAppRegistry:r})=>{const i=t();n?.loadAll().then((t=>{const n=t.filter((({namespace:e})=>e===i.namespace));e((e=>({type:He,pipelines:e}))(n)),r.emit("agg-pipeline-saved",{name:i.name})})).catch((e=>{a("Failed to load pipelines",e)}))},ze=(e,t=!0)=>(n,a,{pipelineBuilder:r,logger:{debug:i}})=>{try{if(r.reset(e.pipelineText),n(function(e,t){return{type:Fe,stages:t.stages,pipelineText:t.source,pipeline:t.pipeline,syntaxErrors:t.syntaxError,storedOptions:{id:e.id,name:e.name,collationString:e.collationString,comments:e.comments,autoPreview:e.autoPreview}}}(e,r)),t&&n(Zt()),r.syntaxError.length>0){let t=e.name.slice(0,20);t.length<e.name.length&&(t+="…"),(0,s.c3r)("restore-pipeline-with-errors",{title:"Can't parse pipeline source to stages",description:`Loaded pipeline "${t}" contains syntax errors`,variant:"warning",timeout:1e4})}}catch(e){i(e)}},_e=()=>async(e,t,{pipelineBuilder:n,pipelineStorage:a,track:r,connectionInfoRef:i})=>{""===t().id&&e({type:Oe});const{id:o,name:s,namespace:l,comments:c,autoPreview:d,collationString:{text:u},dataService:p}=t(),m={id:o,name:s,namespace:l,comments:c,autoPreview:d,collationString:u,pipelineText:Qt(t(),n),host:p.dataService?.getConnectionString().hosts.join(",")??null};await(a?.createOrUpdate(m.id,m));const g=(()=>{try{return Jt(t(),n).length}catch{return}})();r("Aggregation Saved",{id:m.id,num_stages:g,editor_view_type:nn(t())},i.current),e(Be())};var $e=n(12738),Ye=n(32050),Ke=n.n(Ye);const Ge=1e5,Ve=_.qp.map((e=>e.value)),Ue=_.DP.map((e=>e.value));function qe(e,t={}){if(de(e))throw new Error("Cannot preview pipeline with last stage as output stage");const n=[];for(const a of e)(!t.totalDocumentCount||t.totalDocumentCount>(t.sampleSize??Ge))&&Ve.includes(J(a)??"")&&n.push({$limit:t.sampleSize??Ge}),n.push(a);return Ue.includes(ce(n))||n.push({$limit:t.previewSize??10}),n}class Ze{queue=new Map;lastPipeline=new Map;dataService;preferences;constructor(e,t){this.dataService=e,this.preferences=t}async getPreviewForStage(e,t,n,{sampleSize:a,previewSize:r,totalDocumentCount:i,...o}={},s=!1){this.queue.get(e)?.abort();const l=new AbortController;this.queue.set(e,l),s||await(0,$e.Om)(o.debounceMs??700,l.signal),this.lastPipeline.set(e,n);const c=await B({dataService:this.dataService,preferences:this.preferences,signal:l.signal,namespace:t,pipeline:qe(n,{sampleSize:a,previewSize:r,totalDocumentCount:i}),options:o});return this.queue.delete(e),c}isLastPipelineEqual(e,t){return Ke()(t,this.lastPipeline.get(e))}cancelPreviewForStage(e){return this.queue.get(e)?.abort(),this.lastPipeline.delete(e),this.queue.delete(e)}clearQueue(e=0){for(const[t,n]of Array.from(this.queue.entries()))t>=e&&(n.abort(),this.lastPipeline.delete(t),this.queue.delete(t))}}function Je(e){const t=e[0];return t?.$search?[{$search:{...t.$search,scoreDetails:!0}},...e.slice(1),{$project:{_id:0,type:{$literal:"$search"},scores:{$meta:"searchScoreDetails"}}}]:e}const Qe="compass-aggregations/pipelineModeToggled";let Xe=0;function et(){return Xe++}var tt=n(32318);const nt="compass-aggregations/FETCH_EXPLAIN_PLAN_SUCCESS",at={isCollectionScan:!1},rt=new Map,it=()=>async(e,t,{pipelineBuilder:n})=>{const{id:a,namespace:r,dataService:i,maxTimeMS:o}=t(),s=function(e){rt.get(e)?.abort();const t=new AbortController;return rt.set(e,t),t.signal}(a);try{await(0,$e.Om)(300,s);const l=Jt(t(),n).filter((e=>!te(J(e)))),c=await(i.dataService?.explainAggregate?.(r,l,{maxTimeMS:o??void 0},{explainVerbosity:"queryPlanner",maxTimeMS:o??void 0,abortSignal:s})),d=new tt.d(c);e({type:nt,explainPlan:d}),rt.delete(a)}catch{}},ot="compass-aggregations/pipeline-builder/stage-editor/StagePreviewFetch",st="compass-aggregations/pipeline-builder/stage-editor/StagePreviewFetchSkipped",lt="compass-aggregations/pipeline-builder/stage-editor/StagePreviewFetchSuccess",ct="compass-aggregations/pipeline-builder/stage-editor/StagePreviewFetchError",dt="compass-aggregations/pipeline-builder/stage-editor/StageRun",ut="compass-aggregations/pipeline-builder/stage-editor/StageRunSuccess",pt="compass-aggregations/pipeline-builder/stage-editor/StageRunError",mt="compass-aggregations/pipeline-builder/stage-editor/StageValueChange",gt="compass-aggregations/pipeline-builder/stage-editor/StageOperatorChange",ht="compass-aggregations/pipeline-builder/stage-editor/StageCollapsedChange",ft="compass-aggregations/pipeline-builder/stage-editor/StageDisabledChange",yt="compass-aggregations/pipeline-builder/stage-editor/StageAdded",bt="compass-aggregations/pipeline-builder/stage-editor/StageRemoved",vt="compass-aggregations/pipeline-builder/stage-editor/StageMoved",xt="compass-aggregations/pipeline-builder/stage-wizard/WizardAdded",Et="compass-aggregations/pipeline-builder/stage-wizard/WizardRemoved",Ct="compass-aggregations/pipeline-builder/stage-wizard/WizardChanged",wt="compass-aggregations/pipeline-builder/stage-wizard/wizardToStageClicked";function It(e,t,{includeIndex:n}={includeIndex:!1}){const a=n?t+1:t,r=function(e){return e.filter((e=>"wizard"===e.type))}(e.slice(0,a));return t-r.length}function St(e){return e.filter((e=>"stage"===e.type))}function At(){let e=0;return function(t,n){return"wizard"===t.type?(e+=1,t):{...t,idxInPipeline:n-e}}}function kt(e,t){for(let n=0;n<t;n++){const t=e[n];if("stage"===t?.type&&null!==t?.serverError&&!t?.disabled)return n}return null}function Dt(e,t=!1){return!!e&&(e.disabled||!e.syntaxError&&!!e.value&&!!e.stageOperator&&(t||!te(e.stageOperator)))}const Nt=e=>(t,n)=>{const{inputDocuments:{documents:a},pipelineBuilder:{stageEditor:{stages:r}}}=n();if(-1===e)return void a.forEach((e=>e.expand()));const i=r[e];i&&"stage"===i.type&&i.previewDocs?.forEach((e=>e.expand()))},Mt=e=>(t,n)=>{const{inputDocuments:{documents:a},pipelineBuilder:{stageEditor:{stages:r}}}=n();if(-1===e)return void a.forEach((e=>e.collapse()));const i=r[e];i&&"stage"===i.type&&i.previewDocs?.forEach((e=>e.collapse()))},Tt=e=>(t,n)=>{n().pipelineBuilder.stageEditor.stages.slice(e).forEach(((n,a)=>{var r;t((r=e+a,async(e,t,{pipelineBuilder:n,preferences:a})=>{const{pipelineBuilder:{stageEditor:{stages:i}},dataService:o,autoPreview:s}=t(),c=i[r];if(!c||"stage"!==c.type)return;const{idxInPipeline:d}=c;n.cancelPreviewForStage(d);const u=St(i.slice(0,r+1)),p=s&&!c.disabled&&u.every((e=>Dt(e)));if(p)try{e({type:ot,id:r});const{namespace:i,maxTimeMS:s,collationString:c,limit:p,largeLimit:m,collectionStats:g}=t(),h=o.dataService,{enableSearchActivationProgramP2:f}=a.getPreferences(),y=!!f&&!!h&&1===u.length&&"$search"===u[0].stageOperator,b={maxTimeMS:s??l,collation:c.value??void 0},v={...b,sampleSize:m??Ge,previewSize:p??10,totalDocumentCount:g?.document_count},x=new AbortController,E=y&&h?(async()=>{try{return await(0,$e.Om)(700,x.signal),await B({dataService:h,preferences:a,signal:x.signal,namespace:i,pipeline:qe(Je(n.getPipelineFromStages(n.stages.slice(0,d+1))),v),options:b})}catch{return null}})():Promise.resolve(null);try{const[t,a]=await Promise.all([n.getPreviewForStage(d,i,v),E]),o=function(e){if(!e)return null;const t=e.map((e=>e.scores??null));return t.some((e=>null!==e))?{type:"$search",scores:t}:null}(a);e({type:lt,id:r,previewDocs:t.map((e=>new W.Ay(e))),stageMetadata:o})}finally{x.abort()}}catch(t){if(o.dataService?.isCancelError(t))return;for(let e=r+1;e<i.length;e++){const t=i[e];"stage"===t.type&&!t.disabled&&t.loading&&n.cancelPreviewForStage(t.idxInPipeline)}e({type:ct,id:r,error:t})}else e({type:st,id:r})}))}))},Pt=(e,t)=>(n,a,{pipelineBuilder:r})=>{const{pipelineBuilder:{stageEditor:{stages:i}}}=a(),o=i[e];if(!o||"stage"!==o.type)return;const{idxInPipeline:s}=o,l=r.getStage(s);l&&l.value!==t&&(l.changeValue(t),n({type:mt,id:e,stage:l}),n(Tt(e)),n(it()))},Lt=e=>e.replace(/\${[0-9]+:?([a-z0-9.()-]+)?}/gi,(function(e,t){return t??""}));function Ot(e,t,n,a=!1,r=!1){const i=a?function(e){return oe(e).map((e=>({...e,comment:Lt(e.comment),snippet:Lt(e.snippet)})))}(r):oe(r),o=i.filter((t=>t.value===e)),s=o.find((e=>e.env.includes(t)))??o[0];return s?[n&&s.comment,s.snippet??"{}"].filter(Boolean).join(""):"{}"}const Rt=(e,t)=>(n,a,{pipelineBuilder:r,track:i,connectionInfoRef:o,preferences:s})=>{const{env:l,comments:c,pipelineBuilder:{stageEditor:{stages:d}}}=a(),u=d[e];if(!u||"stage"!==u.type)return;const{idxInPipeline:p}=u,m=r.getStage(p);if(!m||m.operator===t)return;const g=Boolean(s.getPreferences().enableAutoEmbeddingPublicPreview),h=Ot(u.stageOperator,l,c,!0,g).trim(),f=u.value?.trim();let y;return m.changeOperator(t),i("Aggregation Edited",{num_stages:St(d).length,stage_action:"stage_renamed",stage_name:m.operator,stage_index:p+1,editor_view_type:nn(a())},o.current),f&&h!==f||(y=Ot(m.operator,l,c,!1,g)),n({type:gt,id:e,stage:m,newSnippet:!!y}),n(Tt(e)),n(it()),y},Ht=(e,t)=>(n,a,{pipelineBuilder:r})=>{const{pipelineBuilder:{stageEditor:{stages:i}}}=a(),o=i[e];if(!o||"stage"!==o.type)return;const{idxInPipeline:s}=o,l=r.getStage(s);l&&(l.changeDisabled(t),n({type:ft,id:e,disabled:t}),n(Tt(e)),n(it()))},Ft=e=>(t,n,{pipelineBuilder:a,track:r,connectionInfoRef:i})=>{const{pipelineBuilder:{stageEditor:{stages:o}}}=n(),s=e??o.length,l=It(o,s,{includeIndex:!0}),c=a.addStage(l);r("Aggregation Edited",{num_stages:St(o).length,stage_action:"stage_added",stage_index:c.id+1,editor_view_type:nn(n())},i.current),t({type:yt,after:s,stage:Bt(c,l)})},Wt=e=>(t,n)=>{t(Ft(e-1)),t(Rt(e,"$search"));const{env:a,comments:r}=n(),i=Ot("$search",a,r,!0);t(Pt(e,i))},jt=(e,t,n)=>(a,r)=>{const{pipelineBuilder:{stageEditor:{stages:i}}}=r();a({wizard:{id:et(),type:"wizard",useCaseId:e,stageOperator:t,value:null,syntaxError:null},type:xt,after:n??i.length})};function Bt(e,t){return{id:e.id,idxInPipeline:t,type:"stage",stageOperator:e.operator,value:e.value,syntaxError:e.syntaxError,disabled:e.disabled,serverError:null,loading:!1,previewDocs:null,stageMetadata:null,collapsed:!1,empty:e.isEmpty,fromSnippet:!1}}function zt(e){return e.map((({id:e,type:t})=>({id:e,type:t})))}const _t="compass-aggregations/pipeline-builder/text-editor-pipeline/TextEditorPreviewFetch",$t="compass-aggregations/pipeline-builder/text-editor-pipeline/EditorPreviewFetchSkipped",Yt="compass-aggregations/pipeline-builder/text-editor-pipeline/TextEditorPreviewFetchSuccess",Kt="compass-aggregations/pipeline-builder/text-editor-pipeline/TextEditorPreviewFetchError",Gt="compass-aggregations/pipeline-builder/text-editor-pipeline/TextEditorValueChange",Vt={pipelineText:"",pipeline:[],syntaxErrors:[],serverError:null,isLoading:!1,previewDocs:null,isPreviewStale:!1};function Ut(e,t){return e&&0===t.length}const qt=()=>async(e,t,{pipelineBuilder:n,preferences:a})=>{const{autoPreview:r,namespace:i,maxTimeMS:o,collationString:s,limit:c,largeLimit:d,collectionStats:u,dataService:p,pipelineBuilder:{textEditor:{pipeline:{pipeline:m}}}}=t();if(!n.isLastPipelinePreviewEqual(m,!0))if(n.cancelPreviewForPipeline(),Ut(r,n.syntaxError))try{e({type:_t});const t={maxTimeMS:(0,g.Tv)(a,o??l),collation:s.value??void 0,sampleSize:d??Ge,previewSize:c??10,totalDocumentCount:u?.document_count},r=await n.getPreviewForPipeline(i,t,!0);e({type:Yt,previewDocs:r.map((e=>new W.Ay(e)))})}catch(t){if(p.dataService?.isCancelError(t))return;e({type:Kt,serverError:t})}else e({type:$t})},Zt=()=>(e,t,{pipelineBuilder:n})=>{n.stopPreview(),"builder-ui"===t().pipelineBuilder.pipelineMode?e(Tt(0)):e(qt())};function Jt(e,t){return"builder-ui"===e.pipelineBuilder.pipelineMode?t.getPipelineFromStages():t.getPipelineFromSource()}function Qt(e,t){return"builder-ui"===e.pipelineBuilder.pipelineMode?t.getPipelineStringFromStages():t.getPipelineStringFromSource()}function Xt(e,t=!0){const n="builder-ui"===e.pipelineBuilder.pipelineMode?e.pipelineBuilder.stageEditor.stages.filter((e=>"stage"===e.type&&!e.disabled)).map((e=>e.stageOperator)):e.pipelineBuilder.textEditor.pipeline.pipeline.map((e=>J(e)??null));return t?n.filter(Boolean):n}function en(e,t){if(void 0!==t){const n=e.pipelineBuilder.stageEditor.stages,a=n[t],r="stage"===a?.type&&!a.disabled&&"$rerank"===a.stageOperator,i=!n.slice(0,t).some((e=>"stage"===e.type&&!e.disabled));return r&&i}const{pipeline:n,syntaxErrors:a,pipelineText:r}=e.pipelineBuilder.textEditor.pipeline;return n.length>0?"$rerank"===J(n[0]):a.length>0&&/^\s*\[\s*\{\s*\$rerank\b/.test(r)}function tn(e,t=!0){if("builder-ui"===e.pipelineBuilder.pipelineMode)return St(e.pipelineBuilder.stageEditor.stages).some((e=>!e.empty&&!e.disabled&&(e.syntaxError||e.serverError&&t)));const{serverError:n,syntaxErrors:a}=e.pipelineBuilder.textEditor.pipeline;return Boolean(n&&t||a.length>0)}function nn(e){return e.focusMode.isEnabled?"focus":"builder-ui"===e.pipelineBuilder.pipelineMode?"stage":"text"}const an={NewPipelineConfirmed:"compass-aggregations/is-new-pipeline-confirm/newPipelineConfirmed"},rn=({typeOfWrite:e,stage:t,ns:n})=>r().createElement("div",{"data-testid":"confirmation-description"},"This pipeline will execute a"," ",r().createElement(s.N_E,{hideExternalIcon:!1,href:t.link,target:"_blank"},t.name)," ","operation,"," ",n?r().createElement(r().Fragment,null,e,' "',r().createElement("b",null,n),'"'):r().createElement(r().Fragment,null,"that may alter or overwrite a collection"),". Do you wish to proceed?"),on={$merge:"https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge/",$out:"https://www.mongodb.com/docs/manual/reference/operator/aggregation/out/"},sn="overwriting",ln="compass-aggeregations/runAggregation",cn="compass-aggregations/aggregationStarted",dn="compass-aggregations/aggregationFinished",un="compass-aggregations/aggregationFailed",pn="compass-aggregations/aggregationCancelledByUser",mn="compass-aggregations/lastPageReached",gn="compass-aggregations/resultViewTypeChanged",hn={pipeline:[],documents:[],page:1,limit:20,isLast:!1,loading:!1,resultsViewType:"document"},fn=()=>(e,t,{track:n,connectionInfoRef:a})=>{n("Aggregation Canceled",{},a.current);const{aggregation:{abortController:r}}=t();yn(r),e({type:pn})},yn=e=>{e?.abort()},bn=(e=1)=>async(t,n,{preferences:a,logger:{log:r,mongoLogId:i},track:o,connectionInfoRef:s,connectionScopedAppRegistry:c})=>{const{namespace:d,maxTimeMS:u,dataService:{dataService:p},aggregation:{limit:m,abortController:g,pipeline:h},collationString:{value:f}}=n();if(p){yn(g);try{const n=new AbortController,r=n.signal;t({type:cn,abortController:n});const i={maxTimeMS:u??l,collation:f??void 0},o=h[h.length-1],s=["$merge","$out"].includes(J(o)??""),g=await B({dataService:p,preferences:a,signal:r,namespace:d,pipeline:h,options:i,...!s&&{skip:(e-1)*m,limit:m}});s&&c.emit("agg-pipeline-out-executed",Q(d,h[h.length-1])),0===g.length?t({type:mn,page:e}):t({type:dn,documents:g.map((e=>new W.Ay(e))),page:e,isLast:g.length<m})}catch(n){if(p.isCancelError(n))return;if(n.code)return t({type:un,error:(y=n,{message:y.message,info:y.errInfo}),page:e}),"MaxTimeMSExpired"===n.codeName&&o("Aggregation Timed Out",{max_time_ms:u??null},s.current),void r.warn(i(1001000106),"Aggregations","Failed to run aggregation",{message:n.message});throw n}var y}},vn="compass-aggregations/countStarted",xn="compass-aggregations/countFinished",En="compass-aggregations/countFailed",Cn={loading:!1},wn=()=>async(e,t,{pipelineBuilder:n,preferences:a})=>{const{namespace:r,maxTimeMS:i,dataService:{dataService:o},collationString:{value:s}}=t();if(!o)return;const c=Jt(t(),n);try{const t=new AbortController,n=t.signal;e({type:vn,abortController:t});const d={maxTimeMS:i??l,collation:s??void 0},[{count:u}]=await B({dataService:o,preferences:a,signal:n,namespace:r,pipeline:[...c,{$count:"count"}],options:d});e({type:xn,count:Number(u)})}catch{e({type:En})}},In={WorkspaceChanged:"compass-aggregations/workspaceChanged"},Sn="builder",An=(0,s.AHW)({display:"flex",gap:s.YKD[200],alignItems:"center"}),kn=(0,s.AHW)({display:"inline-block",marginLeft:s.YKD[100]}),Dn=(0,s.AHW)({padding:0,marginLeft:s.YKD[200]+s.YKD[100]}),Nn=(0,s.AHW)({border:"none",padding:0,backgroundColor:"transparent",span:{backgroundImage:"none !important"}}),Mn=({isResultsMode:e,stages:t,showAddNewStage:n,showAIEntry:a,onAddStageClick:i,onEditPipelineClick:o,onShowAIInputClick:l})=>{const c=(0,g.Rs)();return r().createElement("div",{className:An,"data-testid":"toolbar-pipeline-stages"},0===t.length?r().createElement(s.VYo,{className:Dn},"Your pipeline is currently empty.",n&&r().createElement(r().Fragment,null,c&&a?r().createElement(r().Fragment,null," ","Need help getting started?"):r().createElement(r().Fragment,null," ","To get started add the"," ",r().createElement(s.N_E,{className:Nn,as:"button",onClick:()=>i(),hideExternalIcon:!0,"data-testid":"pipeline-toolbar-add-stage-button"},"first stage."))),c&&a&&r().createElement("span",{className:kn},r().createElement(F.dq,{onClick:l,type:"aggregation"}))):r().createElement(s.$Un,{size:"small"},t.map(((e,t)=>r().createElement(s.BIq,{key:`${t}-${e}`},e)))),e&&r().createElement(s.$nd,{"data-testid":"pipeline-toolbar-edit-button",variant:"primaryOutline",size:"small",onClick:()=>o("builder"),leftGlyph:r().createElement(s.Int,{glyph:"Edit"})},"Edit"))},Tn={onAddStageClick:Ft,onEditPipelineClick:()=>e=>{e(fn()),e(((e,t)=>{const{countDocuments:{abortController:n}}=t();n?.abort()})),e({type:In.WorkspaceChanged,view:"builder"})},onShowAIInputClick:Le},Pn=(0,o.Ng)((e=>{const t=Xt(e,!1),n="results"===e.workspace,a="builder-ui"===e.pipelineBuilder.pipelineMode;return{showAIEntry:!e.pipelineBuilder.aiPipeline.isInputVisible&&!n,stages:t.filter(Boolean),showAddNewStage:!e.pipelineBuilder.aiPipeline.isInputVisible&&!n&&a&&0===t.length,isResultsMode:n}}),Tn)(r().memo(Mn)),Ln="LOADING",On="POLLING",Rn="READY",Hn="INITIAL_FETCH",Fn="POLL",Wn=[Ln,On],jn="compass-aggregations/search-indexes/FetchIndexesStarted",Bn="compass-aggregations/search-indexes/FetchIndexesFinished",zn="compass-aggregations/search-indexes/FetchIndexesFailed",_n={isSearchIndexesSupported:!1,indexes:[],status:"INITIAL"},$n=e=>async(t,n)=>{const{namespace:a,dataService:{dataService:r},searchIndexes:{status:i}}=n();if(r&&!Wn.includes(i)&&(e!==Hn||i!==Rn)){t({type:jn,reason:e});try{if(!r.getSearchIndexes)throw new Error("Cannot get search indexes in this environment");const e=await r.getSearchIndexes(a);t({type:Bn,indexes:e})}catch{t({type:zn})}}},Yn=()=>async e=>{await e($n(Fn))},Kn=()=>(e,t,{pollingIntervalRef:n})=>{null!==n.searchIndexes&&(clearInterval(n.searchIndexes),n.searchIndexes=null)},Gn=()=>(e,t,{localAppRegistry:n})=>{n.emit("open-create-search-index-modal")},Vn=e=>(t,n,{localAppRegistry:a})=>{a.emit("open-indexes-list-drawer-view",e)},Un=e=>(t,n,{localAppRegistry:a})=>{a.emit("open-edit-search-index-drawer-view",e)},qn=e=>(t,n,{localAppRegistry:a})=>{a.emit("open-create-search-index-drawer-view",e)},Zn="aggregations/update-view/ERROR_UPDATING_VIEW",Jn="aggregations/update-view/DISMISS_VIEW_UPDATE_ERROR",Qn=()=>({type:Jn}),Xn=s.$TK;var ea=n(21119);const ta=(0,s.AHW)({display:"flex",gap:s.YKD[200],alignItems:"center"}),na=({isOptionsVisible:e,showRunButton:t,isRunButtonDisabled:n,showUpdateViewButton:i,isUpdateViewButtonDisabled:o,isExplainButtonDisabled:l,showExplainButton:c,showAIEntry:d,onShowAIInputClick:u,onUpdateView:p,onRunAggregation:m,onToggleOptions:h,onExplainAggregation:f,showCollectionScanInsight:y,onCollectionScanInsightActionButtonClick:b,stages:v})=>{const{readWrite:x,enableAggregationBuilderExtraOptions:E,showInsights:C,enableSearchActivationProgramP2:w}=(0,g.gc)(["readWrite","enableAggregationBuilderExtraOptions","showInsights","enableSearchActivationProgramP2"]),I=(0,g.Rs)(),{tellMoreAboutInsight:S,getIsAssistantEnabled:A}=(0,ea.hb)(),k=A(),D=v.includes("$search"),N=(0,a.useMemo)((()=>[{action:"interpret",label:"Interpret",icon:"Sparkle",isDisabled:!k},{action:"visual-tree",label:"Visual tree",icon:"Diagram",isDisabled:D,disabledDescription:D?"Not supported for this query":void 0},{action:"raw-output",label:"Raw output",icon:"CurlyBraces"}]),[k,D]),M=(0,a.useCallback)((e=>{f(e)}),[f]);return r().createElement("div",{className:ta},I&&d&&r().createElement(F.dq,{onClick:u,type:"aggregation"}),C&&y&&r().createElement("div",null,r().createElement(s.gIH,{signals:{...s.qpO.get("aggregation-executed-without-index"),...x?{primaryActionButtonLabel:void 0}:{onPrimaryActionButtonClick:b},onAssistantButtonClick:S&&(()=>{S({id:"aggregation-executed-without-index",stages:v})})}})),i&&r().createElement(s.$nd,{"aria-label":"Update view","data-testid":"pipeline-toolbar-update-view-aggregation-button",variant:"primary",size:"small",onClick:p,disabled:o},"Update view"),c&&(w?r().createElement(s.F1Z,{"data-testid":"pipeline-toolbar-explain-aggregation-dropdown-button",buttonText:"Explain",buttonProps:{size:"small",variant:"default",disabled:l},actions:N,onAction:M,hideOnNarrow:!1}):r().createElement(s.$nd,{"aria-label":"Explain aggregation","data-testid":"pipeline-toolbar-explain-aggregation-button",variant:"default",size:"small",onClick:()=>f("visual-tree"),disabled:l},"Explain")),!i&&t&&r().createElement(s.$nd,{"aria-label":"Run aggregation","data-testid":"pipeline-toolbar-run-button",variant:"primary",size:"small",onClick:m,disabled:n},"Run"),E&&r().createElement(s.bft,{isExpanded:!!e,"aria-controls":"pipeline-options",id:"pipeline-toolbar-options","data-testid":"pipeline-toolbar-options-button",onToggleOptions:h}))},aa={onUpdateView:()=>async(e,t,{pipelineBuilder:n,workspaces:a,logger:{debug:r},track:i,connectionScopedAppRegistry:o,connectionInfoRef:s})=>{e(Qn());const l=t(),c=l.dataService.dataService,d=l.editViewName,u=l.serverVersion;if(!d)return;const p=s.current,m=Jt(t(),n);if(_.rd.isVersionSearchCompatibleForViewsCompass(u)&&c&&await(async(e,t)=>{try{if(!t.getSearchIndexes)throw new Error("Cannot get search indexes in this environment");return(await t.getSearchIndexes(e)).length>0}catch{return!1}})(d,c)){const e=_.rd.isPipelineSearchQueryable(m);if(!await Xn({title:"Are you sure you want to update the view?",description:e?"There are search indexes created on this view. Updating the view will result in an index rebuild, which will consume additional resources on your cluster.":"This update will make the view incompatible with search indexes and will cause all search indexes to fail. Only views containing $addFields, $set or $match stages with the $expr operator are compatible with search indexes.",buttonText:"Update",variant:e?"primary":"danger"}))return}const g={viewOn:(0,z.Ay)(l.namespace).collection,pipeline:m};try{await c.updateCollection(d,g),i("View Updated",{num_stages:m.length,editor_view_type:nn(l)},p),r("selecting namespace",d),o.emit("view-edited",d),a.openCollectionWorkspace(p.id,d)}catch(t){r("Unexpected error updating view",t),e({type:Zn,error:`${t}`})}},onRunAggregation:()=>async(e,t,{pipelineBuilder:n,instance:a,dataService:r,track:i,connectionInfoRef:o,preferences:l})=>{const c=Jt(t(),n);if(await(async({instance:e,dataService:t,namespace:n,pipeline:a})=>{const r=J(a[a.length-1]);let i;if(!r||!te(r))return!0;const o=Q(n,a[a.length-1]);if("$out"===r){let n;if(o){const{database:a,collection:r}=(0,z.Ay)(o);n=!!await e.getNamespace({dataService:t,database:a,collection:r})}else n=!0;i=n?sn:"creating"}else i="altering";return await(0,s.$TK)({variant:i===sn?s.WlR.Danger:s.WlR.Default,title:"A write operation will occur",description:rn({typeOfWrite:i,stage:{name:r,link:on[r]},ns:o}),buttonText:"Yes, run pipeline","data-testid":"write-operation-confirmation-modal"})})({instance:a,dataService:r,namespace:t().namespace,pipeline:c,preferences:l}))return e(it()),e({type:ln,pipeline:c}),i("Aggregation Executed",(()=>({num_stages:c.length,editor_view_type:nn(t()),stage_operators:c.map((e=>J(e)))})),o.current),e(bn())},onExplainAggregation:e=>(t,n,{pipelineBuilder:a,localAppRegistry:r})=>{const i=Jt(n(),a),{collationString:{value:o},maxTimeMS:s}=n(),l={aggregation:{pipeline:i,collation:o,maxTimeMS:s}};"interpret"!==e?r.emit("open-explain-plan-modal",{...l,..."raw-output"===e?{initialViewType:"json"}:{}}):r.emit("open-explain-plan-for-interpret",l)},onCollectionScanInsightActionButtonClick:()=>(e,t,{localAppRegistry:n})=>{n.emit("open-create-index-modal")},onShowAIInputClick:Le},ra=(0,o.Ng)((e=>{const t=Xt(e),n=tn(e,!1),a="builder"===e.workspace,r="fetching"===e.pipelineBuilder.aiPipeline.status;return{isRunButtonDisabled:n||r,isExplainButtonDisabled:n||r,showAIEntry:!e.pipelineBuilder.aiPipeline.isInputVisible&&t.length>0&&a,showUpdateViewButton:Boolean(e.editViewName),isUpdateViewButtonDisabled:!e.isModified||n||r,showCollectionScanInsight:e.insights.isCollectionScan,stages:t}}),aa)(r().memo(na)),ia=(0,s.AHW)({margin:s.YKD[200]}),oa=(0,s.AHW)({display:"flex",alignItems:"center",padding:s.YKD[200],"&:hover .controls":{visibility:"visible"}}),sa=(0,s.AHW)({flex:"none",marginLeft:"auto",display:"flex",alignItems:"center",gap:s.YKD[200],visibility:"hidden"}),la=(0,s.AHW)({flex:"none",transitionProperty:"background-color, box-shadow, border-color"}),ca=({id:e,name:t,onOpenPipeline:n,onDeletePipeline:a})=>r().createElement("div",{className:ia},r().createElement(s.yY_,{className:oa,"data-testid":"saved-pipeline-card","data-pipeline-object-id":e,"data-pipeline-object-name":t},r().createElement(s.nBu,{as:"div","data-testid":"saved-pipeline-card-name"},t),r().createElement("div",{className:(0,s.cx)(sa,"controls")},r().createElement(s.$nd,{className:la,size:"xsmall",onClick:n,"data-testid":"saved-pipeline-card-open-action"},"Open"),r().createElement(s.$nd,{className:la,size:"xsmall",onClick:a,"aria-label":"Delete","data-testid":"saved-pipeline-card-delete-action"},r().createElement(s.Int,{size:"small",glyph:"Trash"}))))),da=(0,s.AHW)({width:"400px",display:"flex",flexDirection:"column",height:"100%"}),ua=(0,s.AHW)({fontWeight:"bold",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),pa=(0,s.AHW)({color:s.MFm.green.light2}),ma=(0,s.AHW)({color:s.MFm.green.dark2}),ga=(0,s.AHW)({overflow:"hidden",display:"flex",flexDirection:"column",padding:s.YKD[400],paddingRight:s.YKD[800]}),ha=(0,s.AHW)({overflowY:"auto",flex:1}),fa=(0,s.AHW)({fontStyle:"italic",padding:s.YKD[400]}),ya={onOpenPipeline:e=>async(t,n,{track:a,connectionInfoRef:r})=>{const i=n().isModified,o=r.current;i&&(a("Screen",{name:"restore_pipeline_modal"},o),!await(0,s.$TK)({title:"Are you sure you want to open this pipeline?",description:"Opening this project will abandon unsaved changes to the current pipeline you are building.",buttonText:"Open Pipeline"}))||(a("Aggregation Opened",{id:e.id,editor_view_type:nn(n()),screen:"aggregations"},o),t(ze(e)))},onDeletePipeline:e=>async(t,n,{pipelineStorage:a,track:r,connectionInfoRef:i})=>{const o=i.current;r("Screen",{name:"delete_pipeline_modal"},o),await(0,s.$TK)({title:"Are you sure you want to delete this pipeline?",description:"Deleting this pipeline will remove it from your saved pipelines.",buttonText:"Delete Pipeline",variant:s.WlR.Danger})&&(r("Aggregation Deleted",{id:e,editor_view_type:nn(n()),screen:"aggregations"},o),await(a?.delete(e)),t(Be()))},onMount:()=>(e,t)=>{t().savedPipeline.isLoaded||e(Be())}},ba=(0,o.Ng)((e=>({namespace:e.namespace,savedPipelines:e.savedPipeline.pipelines})),ya)((({namespace:e,savedPipelines:t,onOpenPipeline:n,onDeletePipeline:i,onMount:o})=>{const l=(0,s.D27)(),c=(0,a.useRef)(o);return(0,a.useEffect)((()=>{c.current()}),[]),r().createElement("div",{className:da,"data-testid":"saved-pipelines"},r().createElement("div",{className:ga},r().createElement(s.nBu,{className:ua,"data-testid":"saved-pipeline-header-title",id:"saved-pipeline-header-title"},"Saved Pipelines in"," ",r().createElement("span",{className:l?pa:ma,title:e},e))),r().createElement("div",{className:ha},t.map((e=>r().createElement(ca,{key:e.id,name:e.name??"",id:e.id,onOpenPipeline:()=>{n(e)},onDeletePipeline:()=>{i(e.id)}}))),0===t.length&&r().createElement(s.nBu,{className:fa,"data-testid":"saved-pipelines-empty-state"},"No saved pipelines found.")))})),va=(0,s.AHW)({display:"flex",gap:s.YKD[200],alignItems:"center"}),xa=(0,s.cx)((0,s.AHW)({border:"none",backgroundColor:"transparent",display:"inline-flex",alignItems:"center",padding:s.YKD[200]-2,"&:hover":{cursor:"pointer"}}),s.Rg),Ea=(0,s.AHW)({display:"flex",flex:1}),Ca=(0,s.AHW)({display:"flex",flex:"none",marginLeft:"auto"}),wa=(0,s.AHW)({maxHeight:"calc(100vh - 260px)",display:"flex",marginLeft:-s.YKD[200]-1,marginTop:s.YKD[100]}),Ia=['[data-id="open-pipeline-confirmation-modal"]','[data-id="delete-pipeline-confirmation-modal"]'],Sa=()=>{const[e,t]=(0,a.useState)(!1);return r().createElement(s.WA6,{className:wa,containedElements:Ia,trigger:({onClick:t,ref:n,children:a})=>r().createElement(r().Fragment,null,r().createElement("button",{"data-testid":"pipeline-toolbar-open-pipelines-button",onClick:t,className:xa,"aria-label":"Open saved pipelines","aria-haspopup":"true","aria-expanded":!!e||void 0,title:"Saved Pipelines",type:"button",ref:n},r().createElement(s.Int,{glyph:"Folder"}),r().createElement(s.Int,{glyph:"CaretDown"})),a),open:e,setOpen:t},r().createElement(ba,null))},Aa=(0,o.Ng)((e=>({isOpenPipelineVisible:!e.editViewName})))((({showRunButton:e,showExplainButton:t,onToggleOptions:n,isOptionsVisible:a,isOpenPipelineVisible:i})=>{const o=(0,g.Fg)("enableMyQueries");return r().createElement("div",{className:va,"data-testid":"pipeline-header"},i&&o&&r().createElement("div",{"data-testid":"saved-pipelines-popover"},r().createElement(Sa,null)),r().createElement("div",{className:Ea},r().createElement(Pn,null)),r().createElement("div",{className:Ca},r().createElement(ra,{onToggleOptions:n,isOptionsVisible:a,showRunButton:e,showExplainButton:t})))}));var ka=n(9174);const Da="aggregations/collation/COLLATION_STRING_CHANGED",Na={text:"",value:null,isValid:!0};function Ma(e){const t=(0,ka.Kz)(e);return{text:e,value:!1===t?null:t,isValid:!1!==t}}const Ta="aggregations/max-time-ms/MAX_TIME_MS_CHANGED",Pa=e=>(t,n,{preferences:a})=>{const r=(0,g.Tv)(a,e);t({type:Ta,maxTimeMS:r})},La=(0,s.AHW)({paddingTop:s.YKD[100],display:"flex",alignItems:"center"}),Oa=(0,s.AHW)({padding:`${s.YKD[200]}px 0`,marginRight:s.YKD[200]}),Ra=(0,s.AHW)({flexGrow:1,marginRight:s.YKD[200]}),Ha=(0,s.AHW)({input:{borderColor:"transparent"}}),Fa=(0,s.AHW)({input:{borderColor:s.MFm.red.base}}),Wa="aggregations-collation-toolbar-input-label",ja="aggregations-collation-toolbar-input",Ba="aggregations-max-time-ms-toolbar-input-label",za="aggregations-max-time-ms-toolbar-input",_a={collationStringChanged:e=>({type:Da,value:e}),maxTimeMSChanged:Pa},$a=(0,o.Ng)((({collationString:e,maxTimeMS:t})=>({collationValue:e.text,collationHasError:!e.isValid,maxTimeMSValue:t})),_a)((({collationValue:e,collationHasError:t,collationStringChanged:n,maxTimeMSValue:i,maxTimeMSChanged:o})=>{const c=(0,g.Fg)("maxTimeMSEnvLimit"),d=(0,a.useCallback)((e=>{if(o){const t=Number(e.currentTarget.value),n=Number.isNaN(t)?0:t;o(c&&n>c?c:n)}}),[o,c]),u=(0,g.Fg)("maxTimeMS"),p=(0,a.useMemo)((()=>c?u?Math.min(u,c):c:u),[c,u]),m=Boolean((0,a.useMemo)((()=>c&&i&&i>=c),[c,i]));return r().createElement("div",{className:La,"data-testid":"collation-toolbar"},r().createElement(s.JU7,{"data-testid":"collation-toolbar-input-label",htmlFor:ja,id:Wa,className:Oa},"Collation"),r().createElement(s.ksK,{"aria-labelledby":Wa,id:ja,"data-testid":"collation-string",className:(0,s.cx)(Ra,Ha,t&&Fa),type:"text",sizeVariant:"small",state:t?"error":"none",value:`${e}`,onChange:e=>n(e.target.value),placeholder:"{ locale: 'simple' }"}),r().createElement(s.JU7,{"data-testid":"maxtimems-toolbar-input-label",htmlFor:za,id:Ba,className:Oa},"Max Time MS"),r().createElement(s.m_M,{enabled:m,open:m,trigger:({children:e,...t})=>r().createElement("div",t,r().createElement(s.ksK,{"aria-labelledby":Ba,id:za,"data-testid":"max-time-ms",className:Ha,placeholder:`${Math.min(l,p||1/0)}`,type:"number",min:"0",max:p,sizeVariant:"small",value:`${i??""}`,state:i&&p&&i>p||m?"error":"none",onChange:d}),e)},"Operations longer than 5 minutes are not supported in the web environment"))})),Ya=()=>r().createElement("div",{"data-testid":"pipeline-options",role:"region",id:"pipeline-options","aria-labelledby":"pipeline-toolbar-options"},r().createElement($a,null));var Ka=n(48783),Ga=n.n(Ka);const Va="aggregations/saving-pipeline/NAME_CHANGED",Ua="aggregations/saving-pipeline/APPLY",qa="aggregations/saving-pipeline/CANCEL",Za="aggregations/saving-pipeline/OPEN",Ja={isOpen:!1,name:"",isSaveAs:!1},Qa=({name:e="",isSaveAs:t=!1}={})=>({type:Za,isSaveAs:t,name:e}),Xa={onSave:e=>""===e?Qa():_e(),onSaveAs:e=>""===e?Qa():Qa({name:e,isSaveAs:!0}),onCreateView:()=>(e,t,{pipelineBuilder:n,globalAppRegistry:a,connectionInfoRef:r})=>{const i={source:t().namespace,pipeline:Jt(t(),n)},{id:o}=r.current;a.emit("open-create-view",i,{connectionId:o})}},er=(0,o.Ng)((e=>({pipelineName:e.name,isCreateViewEnabled:Ga().gte(e.serverVersion,"3.4.0")})),Xa)((({disabled:e,pipelineName:t,isSaveEnabled:n,isCreateViewEnabled:i,onSave:o,onSaveAs:l,onCreateView:c})=>{const d=(0,a.useMemo)((()=>{const e=[];return n&&e.push({action:"save",label:"Save"},{action:"saveAs",label:"Save as"}),i&&e.push({action:"createView",label:"Create view"}),e}),[n,i]);return 0===d.length?null:r().createElement(s.F1Z,{"data-testid":"save-menu",actions:d,onAction:e=>{switch(e){case"save":return o(t);case"saveAs":return l(t);case"createView":return c()}},buttonText:"Save",buttonProps:{size:"xsmall",variant:"primary",leftGlyph:r().createElement(s.Int,{glyph:"Save"}),disabled:e}})})),tr=(0,s.AHW)({display:"flex",alignItems:"center"}),nr=(0,s.AHW)({maxWidth:"100px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),ar=(0,s.AHW)({fontStyle:"italic",whiteSpace:"nowrap"}),rr=(0,o.Ng)((({name:e,isModified:t})=>({name:e,isModified:t})))((({name:e,isModified:t})=>r().createElement(s.nBu,{className:tr,"data-testid":"pipeline-name"},""===e?"Untitled":r().createElement(s.m_M,{trigger:r().createElement("span",{className:nr},e)},r().createElement(s.nBu,null,e)),t&&r().createElement("span",{className:ar}," – modified")))),ir="aggregations/settings",or=`${ir}/TOGGLE_IS_EXPANDED`,sr=`${ir}/TOGGLE_COMMENT_MODE`,lr=`${ir}/SET_SAMPLE_SIZE`,cr=`${ir}/SET_LIMIT`,dr=`${ir}/APPLY_SETTINGS`,ur={isExpanded:!1,isCommentMode:!0,isDirty:!1,sampleSize:10,limit:c},pr=()=>({type:or}),mr="compass-aggregations/autoPreviewToggled",gr="compass-aggregations/sidePanelToggled",hr="is_aggregation_side_panel_open",fr=()=>(e,t,{pipelineBuilder:n,track:a,connectionInfoRef:r})=>{const{sidePanel:{isPanelOpen:i}}=t(),o=!i;o&&a("Aggregation Side Panel Opened",{num_stages:Jt(t(),n).length},r.current),localStorage.setItem(hr,o?"true":"false"),e({type:gr})},yr=(0,s.AHW)({padding:s.YKD[400]}),br=(0,s.AHW)({display:"grid",gap:s.YKD[400],gridTemplateAreas:'\n "headerAndOptionsRow"\n "settingsRow"\n '}),vr=()=>`@container ${s.XvC.toolbarContainerQueryName} (width < 900px)`,xr=(0,s.AHW)({[vr()]:{display:"none"}}),Er=({children:e})=>r().createElement("div",{className:(0,s.cx)(yr,br),"data-testid":"pipeline-toolbar"},e),Cr=(0,s.AHW)({display:"flex",gap:s.YKD[200],justifyItems:"center"}),wr=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[100]}),Ir=(0,s.AHW)({marginBottom:0,padding:0,textTransform:"uppercase"}),Sr=(0,s.AHW)({[vr()]:{"& [data-segmented-control-icon] + span":{display:"none"}}}),Ar=(0,s.AHW)({margin:"auto"}),kr={onToggleAutoPreview:e=>t=>{t({type:mr,value:e}),t(Zt())},onChangePipelineMode:e=>(t,n,{pipelineBuilder:a,track:r,connectionInfoRef:i})=>{e!==n().pipelineBuilder.pipelineMode&&("as-text"===e?a.stagesToSource():a.sourceToStages(),t({type:Qe,mode:e,pipelineText:a.source,pipeline:a.pipeline,syntaxErrors:a.syntaxError,stages:a.stages}),r("Editor Type Changed",{num_stages:Jt(n(),a).length,editor_view_type:nn(n())},i.current),t(Zt()))},onToggleSettings:pr,onToggleSidePanel:fr},Dr=(0,o.Ng)((e=>({isAutoPreview:e.autoPreview,isPipelineModeDisabled:tn(e,!1),pipelineMode:e.pipelineBuilder.pipelineMode})),kr)((({isAutoPreview:e,isPipelineModeDisabled:t,pipelineMode:n,onToggleAutoPreview:a,onChangePipelineMode:i,onToggleSettings:o,onToggleSidePanel:l})=>r().createElement("div",{className:Cr,"data-testid":"pipeline-toolbar-extra-settings"},r().createElement("div",{className:wr},r().createElement(s.lMk,{id:"auto-preview",size:"xsmall","aria-label":"Toggle Auto Preview",onChange:e=>{a(e)},"data-testid":"pipeline-toolbar-preview-toggle",checked:e}),r().createElement(s.JU7,{className:Ir,htmlFor:"auto-preview"},"Preview")),r().createElement(s.IzF,{size:"xsmall","data-testid":"pipeline-builder-toggle",value:n,onChange:e=>{i(e)}},r().createElement(s.Zib,{disabled:t,"data-testid":"pipeline-builder-toggle-builder-ui",value:"builder-ui",glyph:r().createElement(s.Int,{"data-segmented-control-icon":!0,glyph:"CurlyBraces"}),className:Sr},"Stages"),r().createElement(s.Zib,{disabled:t,"data-testid":"pipeline-builder-toggle-as-text",value:"as-text",glyph:r().createElement(s.Int,{"data-segmented-control-icon":!0,glyph:"Code"}),className:Sr},"Text")),r().createElement(s.$nd,{size:"xsmall",leftGlyph:r().createElement(s.Int,{glyph:"Wizard"}),onClick:l,title:"Toggle Stage Wizard","aria-label":"Toggle Stage Wizard","data-testid":"pipeline-toolbar-side-panel-button",className:Ar,disabled:"as-text"===n},r().createElement("span",{className:xr},"Wizard")),r().createElement(s.K0,{title:"More Settings","aria-label":"More Settings",onClick:()=>o(),"data-testid":"pipeline-toolbar-settings-button"},r().createElement(s.Int,{glyph:"Settings"}))))),Nr=(0,s.AHW)({display:"inline-block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis"}),Mr=e=>{const t=`Modifying pipeline backing "${e.editViewName}"`;return r().createElement(s.Exy,{className:Nr,variant:s.xUU.Blue,"data-testid":"modify-source-banner",title:t},t)},Tr=(0,s.AHW)({whiteSpace:"nowrap"}),Pr=(0,s.AHW)({[`@container ${s.XvC.toolbarContainerQueryName} (width < 900px)`]:{display:"none"}}),Lr=(0,o.Ng)((e=>{const t=Xt(e),n=te(t[t.length-1]),a=tn(e,!1),r="fetching"===e.pipelineBuilder.aiPipeline.status;return{isExportToLanguageEnabled:!a&&!r,isMergeOrOutPipeline:n,isExportDataEnabled:!n&&!a&&!r}}),{onExportToLanguage:()=>(e,t,{pipelineBuilder:n,localAppRegistry:a})=>{const r=Qt(t(),n);a.emit("open-aggregation-export-to-language",r)},onExportData:()=>e=>{e(((e,t,{pipelineBuilder:n,connectionScopedAppRegistry:a})=>{const{namespace:r,maxTimeMS:i,countDocuments:{count:o},collationString:{value:s}}=t(),c=Jt(t(),n),d={maxTimeMS:i??l,allowDiskUse:!0,collation:s??void 0};a.emit("open-export",{namespace:r,aggregation:{stages:c,options:d},origin:"aggregations-toolbar",count:o})}))}})((({isExportToLanguageEnabled:e,isExportDataEnabled:t,isMergeOrOutPipeline:n,onExportToLanguage:a,onExportData:i})=>{const o=(0,g.Fg)("enableImportExport");return r().createElement(r().Fragment,null,o&&!n&&r().createElement(s.$nd,{size:"xsmall",leftGlyph:r().createElement(s.Int,{glyph:"Export"}),disabled:!t,onClick:i,"data-testid":"pipeline-toolbar-export-data-button",title:"Export pipeline results",className:Tr},r().createElement("span",{className:Pr},"Export Data")),r().createElement(s.$nd,{size:"xsmall",leftGlyph:r().createElement(s.Int,{glyph:"Code"}),onClick:a,"data-testid":"pipeline-toolbar-export-code-button",disabled:!e,title:"Export query to language",className:Tr},r().createElement("span",{className:Pr},"Export Code")))})),Or=(0,s.AHW)({display:"flex",gap:s.YKD[200],alignItems:"center",justifyContent:"space-between",whiteSpace:"nowrap"}),Rr=(0,s.AHW)({display:"flex",gap:s.YKD[200],alignItems:"center",flex:"none"}),Hr=(0,s.AHW)({display:"flex",flex:"none"}),Fr=(0,o.Ng)((e=>({editViewName:e.editViewName??void 0})),{onCreateNewPipeline:()=>async(e,t,{pipelineBuilder:n,track:a})=>{t().isModified&&(a("Screen",{name:"confirm_new_pipeline_modal"},void 0),!await(0,s.$TK)({title:"Are you sure you want to create a new pipeline?",description:"Creating this pipeline will abandon unsaved changes to the current pipeline."}))||(n.reset(),e({type:an.NewPipelineConfirmed,stages:n.stages,pipelineText:n.source,pipeline:n.pipeline,syntaxErrors:n.syntaxError}),e(Zt()))}})((({editViewName:e,onCreateNewPipeline:t})=>{const n=(0,g.Fg)("enableMyQueries"),a=!e&&!!n,i=!e;return r().createElement("div",{className:Or,"data-testid":"pipeline-settings"},r().createElement("div",{className:Rr},a&&r().createElement(rr,null),r().createElement(er,{isSaveEnabled:!!n}),i&&r().createElement(s.$nd,{size:"xsmall",variant:"primary",leftGlyph:r().createElement(s.Int,{glyph:"Plus"}),onClick:t,"data-testid":"pipeline-toolbar-create-new-button"},"Create new"),r().createElement(Lr,null)),e&&r().createElement(Mr,{editViewName:e}),r().createElement("div",{className:Hr},r().createElement(Dr,null)))}));var Wr=n(60783);const jr=(0,o.Ng)((e=>({isAIInputVisible:e.pipelineBuilder.aiPipeline.isInputVisible,isAggregationGeneratedFromQuery:e.pipelineBuilder.aiPipeline.isAggregationGeneratedFromQuery,lastAIPipelineRequestId:e.pipelineBuilder.aiPipeline.lastAIPipelineRequestId,aiPromptText:e.pipelineBuilder.aiPipeline.aiPromptText,isFetching:"fetching"===e.pipelineBuilder.aiPipeline.status,didGenerateEmptyResults:"success"===e.pipelineBuilder.aiPipeline.status&&0===Xt(e,!1).length,didSucceed:"success"===e.pipelineBuilder.aiPipeline.status,errorMessage:e.pipelineBuilder.aiPipeline.errorMessage,errorCode:e.pipelineBuilder.aiPipeline.errorCode})),{onChangeAIPromptText:e=>({type:Ae,text:e}),onCancelRequest:Pe,onSubmitText:e=>async(t,n,{atlasAiService:a,pipelineBuilder:r,preferences:i,logger:{log:o,mongoLogId:l},track:c,connectionInfoRef:d,collection:u})=>{const{pipelineBuilder:{aiPipeline:{aiPipelineRequestId:p},pipelineMode:m},namespace:g,dataService:{dataService:h}}=n(),f=d.current,y=i.getPreferences().enableGenAISampleDocumentPassing,b="builder-ui"===m?"stages":"text";null!==p&&Me(p);const v=new AbortController,{id:x,signal:E}=function(){const e=(new me.UUID).toString(),t=new AbortController;return Ne.set(e,t),{id:e,signal:t.signal}}();let C;c("AI Prompt Submitted",(()=>({editor_view_type:b,user_input_length:e.length,request_id:x,has_sample_documents:y})),f),t({type:xe,requestId:x});try{const t=await(h?.sample?.(g,{query:{},size:4},{maxTimeMS:i.getPreferences().maxTimeMS,promoteValues:!1},{abortSignal:E}))||[],n=await(0,he.Cv)(t),{isFLE:r}=await u.fetchMetadata({dataService:h}),{collection:o,database:s}=(0,z.Ay)(g);C=await a.getAggregationFromUserInput({signal:v.signal,userInput:e,collectionName:o,databaseName:s,schema:n,...y?{sampleDocuments:t}:void 0,requestId:x,enableStorage:!r},f)}catch(e){if(E.aborted)return;return Te({editor_view_type:b,statusCode:e.statusCode||e?.code,errorCode:e.errorCode||e?.name,errorMessage:e.message,errorName:"request_error",track:c,log:o,requestId:x,connectionInfo:f}),401===e.statusCode&&(0,s.c3r)("ai-unauthorized",{variant:"important",title:"Network Error",description:"Unauthorized",timeout:5e3}),void t({type:Ee,errorMessage:e.message,statusCode:e.statusCode??-1,errorCode:e.errorCode})}finally{!function(e){Ne.delete(e)}(x)}if(E.aborted)return void o.info(l(1001000231),"AIPipeline","Cancelled ai pipeline request",{requestId:x});const w=C.content.aggregation?.pipeline;try{if(!w)throw new Error("No pipeline was returned. Please try again with a different prompt.")}catch(e){return Te({editor_view_type:b,statusCode:e.statusCode,errorMessage:e.message,errorName:"empty_pipeline_error",track:c,log:o,requestId:x,connectionInfo:f}),void t({type:Ee,errorMessage:e.message})}r.reset(w),o.info(l(1001000228),"AIPipeline","AI pipeline request succeeded",{editorViewType:b,syntaxErrors:!!(r.syntaxError?.length>0),shape:r.stages.map((e=>e.operator)),requestId:x}),c("AI Response Generated",(()=>({editor_view_type:b,syntax_errors:!!(r.syntaxError?.length>0),query_shape:r.stages.map((e=>e.operator)),request_id:x})),f),t({type:ke,stages:r.stages,pipelineText:r.source,pipeline:r.pipeline,syntaxErrors:r.syntaxError,requestId:x}),t(Zt())},onResetIsAggregationGeneratedFromQuery:()=>e=>{e({type:we})},onHideAIInputClick:()=>e=>{e(Pe()),e({type:Se})}})((({isAIInputVisible:e,onHideAIInputClick:t,aiPromptText:n,onChangeAIPromptText:i,onSubmitText:o,isFetching:l,didGenerateEmptyResults:c,didSucceed:d,onCancelRequest:u,errorMessage:p,errorCode:m,isAggregationGeneratedFromQuery:h,lastAIPipelineRequestId:f,onResetIsAggregationGeneratedFromQuery:y})=>{const b=(0,g.Fg)("trackUsageStatistics"),v=(0,a.useRef)(y);(0,a.useEffect)((function(){return()=>{v.current()}}),[]);const x=(e=>{const t=(0,ye.Ul)("AI-PIPELINE-UI"),n=(0,O.Jr)(),r=(0,Wr.jj)();return(0,a.useCallback)(((a,i)=>{const{log:o,mongoLogId:l}=t;o.info(l(1001000232),"PipelineAI","AI pipeline feedback",{feedback:a,requestId:e,text:i}),n("PipelineAI Feedback",(()=>({feedback:a,request_id:e,text:i})),r.current),(0,s.c3r)("pipeline-ai-feedback-submitted",{variant:"success",title:"Your feedback has been submitted.",timeout:1e4})}),[t,n,e,r])})(f);return r().createElement(F.HM,{show:e,onClose:t,aiPromptText:n,onChangeAIPromptText:i,onSubmitText:o,isFetching:l,didGenerateEmptyResults:c,didSucceed:d,onCancelRequest:u,errorMessage:p,errorCode:m,isAggregationGeneratedFromQuery:h,onResetIsAggregationGeneratedFromQuery:y,placeholder:"Tell us what aggregation to build (e.g. count movies made each year) or paste one in another language (SQL, Java, etc.)",onSubmitFeedback:b?x:void 0})})),Br=jr,zr=(0,s.AHW)({backgroundColor:"transparent",border:"none",display:"inline",height:s.YKD[600]+s.YKD[100],":focus":{outline:`${s.YKD[100]}px auto ${s.MFm.blue.light1}`}}),_r=(0,s.AHW)({display:"flex",alignItems:"center"}),$r=(0,s.AHW)({width:s.YKD[600]+s.YKD[100],height:s.YKD[600]+s.YKD[100],display:"flex",justifyContent:"center",alignItems:"center"}),Yr="pipeline-pagination-count",Kr=({title:e})=>r().createElement("div",{className:$r,title:e},r().createElement(s.Q0K,null)),Gr={onCount:wn,onRefresh:wn},Vr=(0,o.Ng)((({countDocuments:{loading:e,count:t}})=>({loading:e,count:t})),Gr)((({loading:e,count:t,onCount:n,onRefresh:a})=>e&&void 0===t?r().createElement("div",{"data-testid":Yr},r().createElement(Kr,{title:"Counting documents"})):void 0!==t?r().createElement("div",{"data-testid":Yr,className:_r},r().createElement(s.nBu,null,"of ",t),e?r().createElement(Kr,{title:"Refreshing document count"}):r().createElement(s.K0,{"aria-label":"Refresh document count",title:"Refresh document count","data-testid":"pipeline-pagination-refresh-count-action",onClick:a},r().createElement(s.Int,{glyph:"Refresh"}))):r().createElement("div",{"data-testid":Yr},r().createElement(s.m_M,{trigger:r().createElement(s.N_E,{"aria-label":"count results",as:"button","data-testid":"pipeline-pagination-count-action",hideExternalIcon:!0,className:zr,onClick:()=>n()},"count results")},r().createElement(s.nBu,null,"\n In order to have the final count of documents we need to run the\n aggregation again. This will be the equivalent of adding a\n $count as the last stage of the pipeline.\n"))))),Ur=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[200]}),qr=(0,s.AHW)({display:"flex",gap:s.YKD[100],alignItems:"baseline"}),Zr=(0,s.AHW)({display:"flex",alignItems:"center"}),Jr={onPrev:()=>async(e,t)=>{const{aggregation:{page:n}}=t();if(!(n<=1))return e(bn(n-1))},onNext:()=>async(e,t)=>{const{aggregation:{isLast:n,page:a}}=t();if(!n)return e(bn(a+1))}},Qr=(0,o.Ng)((({aggregation:{documents:e,isLast:t,page:n,limit:a,loading:r,error:i},countDocuments:{count:o}})=>{const s=(({limit:e,page:t})=>(t-1)*e+1)({limit:a,page:n}),l=(({limit:e,page:t,documentCount:n})=>(t-1)*e+(n||e))({limit:a,page:n,documentCount:e.length});return{showingFrom:s,showingTo:l,isCountDisabled:Boolean(i),isPrevDisabled:n<=1||r||Boolean(i),isNextDisabled:t||r||Boolean(i)||o===l}}),Jr)((({showingFrom:e,showingTo:t,isCountDisabled:n,isPrevDisabled:a,isNextDisabled:i,onPrev:o,onNext:l})=>r().createElement("div",{className:Ur,"data-testid":"pipeline-pagination"},!n&&r().createElement("div",{className:qr},r().createElement(s.nBu,{"data-testid":"pipeline-pagination-desc"},"Showing ",e," – ",t),r().createElement(Vr,null)),r().createElement("div",{className:Zr},r().createElement(s.K0,{"data-testid":"pipeline-pagination-prev-action","aria-label":"Previous page",disabled:a,onClick:()=>o()},r().createElement(s.Int,{glyph:"ChevronLeft"})),r().createElement(s.K0,{"data-testid":"pipeline-pagination-next-action","aria-label":"Next page",disabled:i,onClick:()=>l()},r().createElement(s.Int,{glyph:"ChevronRight"})))))),Xr=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[200],flex:"none"}),ei=({value:e,onChange:t})=>{const n=(0,s.BiT)(),a=(0,s.BiT)();return r().createElement("div",{className:Xr,"data-testid":"pipeline-results-view-controls"},r().createElement(s.IzF,{id:a,"aria-labelledby":n,size:"xsmall",value:e,onChange:t},r().createElement(s.Zib,{"aria-label":"Document list",value:"document",glyph:r().createElement(s.Int,{glyph:"Menu"})}),r().createElement(s.Zib,{"aria-label":"JSON list",value:"json",glyph:r().createElement(s.Int,{glyph:"CurlyBraces"})})))},ti=[{action:"collapse",label:"Collapse all fields"},{action:"expand",label:"Expand all fields"}],ni=(0,s.AHW)({display:"flex",alignItems:"center",flex:"none"}),ai="Output Options",ri=({onChangeOption:e,buttonText:t})=>r().createElement("div",{className:ni},r().createElement(s.F1Z,{"data-testid":"pipeline-output-options",actions:ti,onAction:e,buttonText:t??ai,buttonProps:{size:"xsmall",title:t||ai,"aria-label":t||ai}})),ii=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[200]}),oi=(0,s.AHW)({display:"flex",gap:s.YKD[200]}),si=(0,s.AHW)({display:"flex",gap:s.YKD[200],marginLeft:"auto"}),li={onChangeResultsView:e=>({type:gn,viewType:e}),onExpand:()=>(e,t)=>{const{aggregation:{documents:n}}=t();n.forEach((e=>e.expand()))},onCollapse:()=>(e,t)=>{const{aggregation:{documents:n}}=t();n.forEach((e=>e.collapse()))}},ci=(0,o.Ng)((e=>{const{aggregation:{resultsViewType:t,pipeline:n}}=e;return{resultsViewType:t,isMergeOrOutPipeline:te(J(n[n.length-1])??"")}}),li)((({onChangeResultsView:e,resultsViewType:t,isMergeOrOutPipeline:n,onExpand:i,onCollapse:o})=>{const l=(0,a.useCallback)((e=>{"expand"===e?i():"collapse"===e&&o()}),[i,o]);return n?null:r().createElement("div",{className:ii,"data-testid":"pipeline-results-header"},r().createElement("div",{className:oi},r().createElement(s.bz9,null,"All Results"),r().createElement(Lr,null)),r().createElement("div",{className:si},r().createElement(Qr,null),r().createElement(ri,{buttonText:"",onChangeOption:l}),r().createElement(ei,{value:t,onChange:e})))})),di=(0,s.AHW)({gridArea:"headerAndOptionsRow",border:"1px solid",borderRadius:"6px",borderColor:s.MFm.gray.light2,padding:s.YKD[200],background:s.MFm.white}),ui=(0,s.AHW)({borderColor:s.MFm.gray.dark2,background:s.MFm.black}),pi=(0,s.AHW)({gridArea:"settingsRow"}),mi=(0,s.AHW)({marginTop:s.YKD[200]}),gi=(0,o.Ng)((e=>({isBuilderView:"builder"===e.workspace})))((({isBuilderView:e,showRunButton:t,showExplainButton:n})=>{const i=(0,s.D27)(),o=(0,g.Rs)(),[l,c]=(0,a.useState)(!1);return r().createElement(Er,null,r().createElement("div",{className:(0,s.cx)(di,i&&ui)},o&&e&&r().createElement(Br,null),r().createElement(Aa,{isOptionsVisible:l,onToggleOptions:()=>c(!l),showRunButton:t,showExplainButton:n}),l&&r().createElement("div",{className:mi},r().createElement(Ya,null))),e?r().createElement("div",{className:pi},r().createElement(Fr,null)):r().createElement("div",{className:pi},r().createElement(ci,null)))}));var hi=n(88984),fi=n(55712),yi=n(84357),bi=n(68037);const vi=(0,s.AHW)({position:"absolute",width:"1.1px",height:"100%",marginRight:s.YKD[100]}),xi=(0,s.AHW)({background:s.MFm.gray.dark2,"&:hover":{backgroundColor:s.MFm.gray.dark1},"&:active":{backgroundColor:s.MFm.gray.dark1}}),Ei=(0,s.AHW)({background:s.MFm.gray.light2,"&:hover":{backgroundColor:s.MFm.gray.light1},"&:active":{backgroundColor:s.MFm.gray.light1}}),Ci=function(){const e=(0,s.D27)();return r().createElement("div",{className:(0,s.cx)(vi,e?xi:Ei)})},wi=(0,o.Ng)(((e,t)=>({isEnabled:!e.pipelineBuilder.stageEditor.stages[t.index].disabled})),{onChange:Ht})((({index:e,isEnabled:t,className:n,onChange:a})=>{const i=t?"Exclude stage from pipeline":"Include stage in pipeline";return r().createElement(s.lMk,{className:n,id:"toggle-stage-button",checked:t,onChange:t=>a(e,!t),title:i,"aria-label":i,size:"xsmall"})})),Ii=(0,o.Ng)(((e,t)=>({isExpanded:!e.pipelineBuilder.stageEditor.stages[t.index].collapsed})),{onChange:(e,t)=>({type:ht,id:e,collapsed:t})})((({index:e,isExpanded:t,onChange:n})=>{const a=t?"Collapse":"Expand";return r().createElement(s.K0,{onClick:()=>n(e,t),title:a,"aria-label":a},r().createElement(s.Int,{glyph:t?"ChevronDown":"ChevronRight",size:"small"}))})),Si=3*s.YKD[1400],Ai=14*s.YKD[1200],ki=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[100],padding:`${s.YKD[100]}px 0`}),Di=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[200]}),Ni=({description:e})=>r().createElement("div",{className:ki},r().createElement("div",{className:Di},r().createElement("span",null,"$rerank"),r().createElement(s.Exy,{variant:s.xUU.Blue},"Preview"),r().createElement(s.Exy,{variant:s.xUU.Blue},"Start Free")),r().createElement(s.VYo,null,e)),Mi=(0,s.AHW)({width:Si,"> :popover-open":{width:Ai,whiteSpace:"normal",left:"var(--stage-op-popover-left, 0px) !important"},'> :popover-open [role="listbox"]':{maxHeight:"450px"}}),Ti=(0,g.tC)((0,o.Ng)(((e,t)=>{const n=e.pipelineBuilder.stageEditor.stages[t.index],a=(r=(({serverVersion:e,env:t,isTimeSeries:n,sourceName:a,preferencesReadOnly:r})=>{const i=n?_.MD:a?_.gR:_.nP,o=JSON.stringify({serverVersion:e,env:t,namespaceType:i,preferencesReadOnly:r});if(Z.has(o))return Z.get(o);const s=(0,_.zM)({serverVersion:e,meta:["stage"],stage:{namespace:i,env:t===_.L5?[t,_.Ah]:t}}).filter((e=>function(e,t){return!e?.outputStage||!t}(e,r)));return Z.set(o,s),s})({serverVersion:e.serverVersion,env:e.env,isTimeSeries:e.isTimeSeries,sourceName:e.sourceName,preferencesReadOnly:t.readOnly}),Boolean(t.enableAutoEmbeddingPublicPreview)?r.map((e=>"$vectorSearch"===e.name?{..._.cn,env:_.cn.env,meta:_.cn.meta}:e)):r);var r;return{selectedStage:n.stageOperator,isDisabled:n.disabled,stages:a,serverVersion:e.serverVersion,sourceName:e.sourceName,collectionStats:e.collectionStats}}),((e,t)=>({onChange(n,a){const r=e(Rt(n,a??""));t.onChange?.(n,a,r)}})))((({onChange:e,index:t,selectedStage:n,isDisabled:i,serverVersion:o,sourceName:l,collectionStats:c,stages:d})=>{const u=(0,a.useCallback)((n=>{e(t,n)}),[e,t]),p=(0,g.Fg)("enableRerank")?[...d].sort(((e,t)=>"$rerank"===e.name?-1:"$rerank"===t.name?1:0)):d.filter((e=>"$rerank"!==e.name)),m=!_.rd.isVersionSearchCompatibleForViewsCompass(o),h=!c?.pipeline||_.rd.isPipelineSearchQueryable(c.pipeline),f=!!l&&(!h||m),y=(0,a.useRef)(null);return(0,a.useEffect)((()=>{const e=y.current;e&&e.style.setProperty("--stage-op-popover-left",`${e.getBoundingClientRect().left}px`)}),[]),r().createElement("div",{ref:y},r().createElement(s.G3_,{value:n,disabled:i,"aria-label":"Select a stage operator",onChange:u,size:"xsmall",clearable:!1,"data-testid":"stage-operator-combobox",className:Mi},p.map((e=>{const t=((e,t,n,a,r)=>{if(t&&ae(e.name)){const i=_.rd.MIN_VERSION_FOR_VIEW_SEARCH_COMPATIBILITY_COMPASS.split(".").slice(0,2).join(".");if(a)return(e=>{try{return Ga().gte(e,"8.0.0")&&Ga().lt(e,"8.1.0")}catch{return!1}})(n)?`Atlas only. Requires MongoDB ${i}+ to run on a view. To use a search index on a view on MongoDB 8.0, query the view’s source collection ${t}. `+e.description:`Atlas only. Requires MongoDB ${i}+ to run on a view. `+e.description;if(!r)return"Atlas only. Only views containing $match stages with the $expr operator, $addFields, or $set are compatible with search indexes. "+e.description}return(q(e.env)?"Atlas only. ":"")+e.description})(e,l,o,m,h);return r().createElement(s.jOs,(0,fi.A)({"data-testid":`combobox-option-stage-${e.name}`,key:e.name,value:e.name,disabled:ae(e.name)&&f},"$rerank"===e.name?{customContent:r().createElement(Ni,{description:t})}:{description:t}))}))))})),["readOnly","enableAutoEmbeddingPublicPreview"]),Pi="compass-aggregations/focusModeEnabled",Li="compass-aggregations/focusModeDisabled",Oi="compass-aggregations/selectFocusModeStage",Ri={isEnabled:!1,stageIndex:-1,openedAt:null},Hi=()=>(e,t,{track:n,connectionInfoRef:a})=>{const r=t();n("Focus Mode Closed",{num_stages:St(r.pipelineBuilder.stageEditor.stages).length,duration:Number((Date.now()-(r.focusMode.openedAt??0)).toFixed(1))},a.current),e({type:Li})},Fi=e=>({type:Oi,index:e}),Wi=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[200]});function ji({label:e,onClick:t,setMenuOpen:n,icon:a}){return r().createElement(s.Drp,{"data-text":e,onClick:()=>{n(!1),t()}},r().createElement("div",{className:Wi},r().createElement(s.Int,{color:s.MFm.gray.dark2,glyph:a,size:"small"}),e))}const Bi=(0,o.Ng)(((e,t)=>({isExpanded:!e.pipelineBuilder.stageEditor.stages[t.index].collapsed})),{onAddStageClick:Ft,onDeleteStageClick:e=>(t,n,{pipelineBuilder:a,track:r,connectionInfoRef:i})=>{const{pipelineBuilder:{stageEditor:{stages:o}}}=n(),s=o[e];if(!s||"stage"!==s.type)return;const{idxInPipeline:l}=s;a.cancelPreviewForStage(l);const c=a.removeStage(l);r("Aggregation Edited",{num_stages:St(o).length,stage_action:"stage_deleted",stage_name:c.operator,stage_index:l+1,editor_view_type:nn(n())},i.current),t({type:bt,at:e}),t(Tt(e)),t(it())},onExpand:Nt,onCollapse:Mt})((({index:e,onAddStageClick:t,onDeleteStageClick:n,onExpand:i,onCollapse:o})=>{const[l,c]=(0,a.useState)(!1);return r().createElement(s.W1t,{open:l,setOpen:c,"data-testid":"stage-option-menu-content",trigger:({onClick:e,children:t})=>r().createElement(r().Fragment,null,r().createElement(s.K0,{"data-testid":"stage-option-menu-button",onClick:e,"aria-label":"Options",title:"Options"},r().createElement(s.Int,{glyph:"Ellipsis",size:"small"})),t)},r().createElement(ji,{label:"Add stage after",icon:"PlusWithCircle",onClick:()=>t(e),setMenuOpen:c}),r().createElement(ji,{label:"Add stage before",icon:"PlusWithCircle",onClick:()=>t(e-1),setMenuOpen:c}),r().createElement(ji,{label:"Delete stage",icon:"Trash",onClick:()=>n(e),setMenuOpen:c}),r().createElement(ji,{label:"Expand documents",icon:"ChevronDown",onClick:()=>i(e),setMenuOpen:c}),r().createElement(ji,{label:"Collapse documents",icon:"ChevronUp",onClick:()=>o(e),setMenuOpen:c}))})),zi=({stageOperator:e,value:t},n,a,r)=>{const i=[_.Ah,_.Ub].includes(n);return"$match"===e&&/\$(text|regex)\b/.test(t??"")?i?a?{...s.qpO.get("atlas-with-search-text-regex-usage-in-stage"),onPrimaryActionButtonClick:r}:s.qpO.get("atlas-without-search-text-regex-usage-in-stage"):s.qpO.get("non-atlas-text-regex-usage-in-stage"):"$lookup"===e?s.qpO.get("lookup-in-stage"):void 0};var _i=n(70002);const $i=()=>{const{tellMoreAboutInsight:e}=(0,ea.hb)(),t=(0,a.useCallback)((()=>{e?.({id:"rerank-first-stage"})}),[e]);return e?t:void 0},Yi=r().createElement(r().Fragment,null,r().createElement(s.N_E,{href:`${m}/search/`,target:"_blank",hideExternalIcon:!0},"$search"),", ",r().createElement(s.N_E,{href:`${m}/vectorSearch/`,target:"_blank",hideExternalIcon:!0},"$vectorSearch"),", ",r().createElement(s.N_E,{href:`${m}/rankFusion/`,target:"_blank",hideExternalIcon:!0},"$rankFusion"),", or ",r().createElement(s.N_E,{href:`${m}/scoreFusion/`,target:"_blank",hideExternalIcon:!0},"$scoreFusion")),Ki=r().createElement(r().Fragment,null,"$rerank is the first stage with no preceding search stage. This is expensive and increases strain. We recommend using $rerank as the second stage to ",Yi,"."),Gi=({isRerankFirstStage:e,hasSearchIndex:t,isSearchIndexesLoading:n,onAddSearchStageBefore:r})=>{const i=(0,g.Fg)("enableRerank"),o=$i(),{atlasMetadata:l}=(0,Wr.qm)();return(0,a.useMemo)((()=>{if(i&&e)return{...s.qpO.get("rerank-without-search"),description:Ki,primaryActionButtonIsLoading:n,primaryActionButtonLabel:n?void 0:t?"Add $search stage":"Learn about search",...t&&!n?{onPrimaryActionButtonClick:r}:n?{}:{primaryActionButtonLink:l?(0,_i.sC)({projectId:l.projectId}):"https://dochub.mongodb.org/core/atlas-search"},onAssistantButtonClick:o}}),[i,e,t,n,r,l,o])},Vi=(0,s.AHW)({borderRadius:0,border:"none","&::before":{display:"none"}}),Ui=(0,s.AHW)({display:"flex",justifyContent:"space-between",alignItems:"flex-end"}),qi=(0,s.AHW)({flex:1,minWidth:0}),Zi=(0,s.AHW)({flexShrink:0,whiteSpace:"nowrap",marginLeft:s.YKD[200]}),Ji=({"data-testid":e})=>{const t=(0,g.Fg)("enableRerank"),[n,a]=(0,s.yRS)("mongodb_compass_dismissed_rerank_first_stage_banner",!1),i=$i();return!t||n?null:r().createElement(s.lZ$,{variant:"warning","data-testid":e,className:Vi,dismissible:!0,onClose:()=>a(!0)},r().createElement("div",{className:Ui},r().createElement("div",{className:qi},r().createElement("strong",null,"$rerank works better following a search stage"),r().createElement("br",null),"If you're just trying out $rerank, there's a chance you may consume an excessive amount of tokens, which can be expensive. $rerank works best following a search stage like ",Yi,"."),i&&r().createElement(s.$nd,{size:"xsmall",className:Zi,onClick:i,leftGlyph:r().createElement(s.Int,{glyph:"Sparkle"}),"data-testid":"rerank-first-stage-learn-more-button"},"Learn more")))},Qi=(0,s.AHW)({width:"100%",display:"flex",alignItems:"center",borderBottomWidth:"1px",borderBottomStyle:"solid",padding:`0 ${s.YKD[200]}px`,height:s.YKD[800]+s.YKD[100],flexShrink:0,flexDirection:"row",justifyContent:"space-between",cursor:"grab","&:active":{cursor:"grabbing"}}),Xi=(0,s.AHW)({borderBottomWidth:0}),eo=(0,s.AHW)({borderBottomColor:s.MFm.gray.dark2}),to=(0,s.AHW)({borderBottomColor:s.MFm.gray.light2}),no=(0,s.AHW)({borderBottomColor:s.MFm.yellow.base}),ao=(0,s.AHW)({borderBottomColor:s.MFm.red.base}),ro=(0,s.AHW)({display:"flex",alignItems:"center",justifyContent:"flex-start",gap:3*s.YKD[100]}),io=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[100],whiteSpace:"nowrap"}),oo=(0,s.AHW)({whiteSpace:"nowrap"}),so=(0,s.AHW)({whiteSpace:"nowrap"}),lo=(0,s.AHW)({flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",paddingLeft:s.YKD[200]}),co=(0,s.AHW)({display:"flex",alignItems:"center",justifyContent:"flex-end",gap:s.YKD[100]}),uo=(0,o.Ng)(((e,t)=>{const{env:n,pipelineBuilder:{stageEditor:{stages:a}},searchIndexes:{isSearchIndexesSupported:r,indexes:i,status:o}}=e;return{stage:a[t.index],env:n,isSearchIndexesSupported:r,isRerankFirstStage:en(e,t.index),hasSearchIndex:i.length>0,isSearchIndexesLoading:"INITIAL"===o||"LOADING"===o||"POLLING"===o}}),{onOpenFocusMode:e=>(t,n,{track:a,connectionInfoRef:r})=>{a("Focus Mode Opened",{num_stages:St(n().pipelineBuilder.stageEditor.stages).length},r.current),t({type:Pi,stageIndex:e})},onCreateSearchIndex:Gn,onClickViewSearchIndexes:Vn,onAddSearchStageBefore:Wt,onRefreshSearchIndexes:Yn})((function({index:e,stage:t,env:n,isSearchIndexesSupported:i,isRerankFirstStage:o,hasSearchIndex:l,isSearchIndexesLoading:c,onCreateSearchIndex:d,onOpenFocusMode:u,onAddSearchStageBefore:p,onRefreshSearchIndexes:m,onStageOperatorChange:h,onClickViewSearchIndexes:f}){const y=(0,g.Fg)("showInsights"),b=(0,g.Fg)("enableRerank"),{enableSearchActivationProgramP1:v}=(0,O.p5)(),x=(0,s.D27)(),{openDrawer:E}=(0,s.u6F)(),C=(0,O.Jr)(),{atlasMetadata:w}=(0,Wr.qm)(),I=b&&"$rerank"===t.stageOperator?w?(0,_i.ZM)(w):"https://dochub.mongodb.org/core/$rerank#metrics":null,S=(0,a.useMemo)((()=>zi(t,n,i,d)),[t,n,i,d]),A=(0,a.useCallback)((()=>{p(e)}),[p,e]),k=Gi({isRerankFirstStage:o,hasSearchIndex:l,isSearchIndexesLoading:c,onAddSearchStageBefore:A})??S,D=(0,a.useCallback)((e=>{e&&o&&m()}),[o,m]);return r().createElement("div",{className:(0,s.cx)("stage-editor-toolbar",Qi,x?eo:to,pe(t)&&no,!!t.serverError&&ao,t.collapsed&&Xi)},r().createElement("div",{className:ro},r().createElement("div",{className:io},r().createElement(Ii,{index:e}),r().createElement(s.nBu,{weight:"medium"},"Stage ",t.idxInPipeline+1),r().createElement(Ti,{onChange:h,index:e})),r().createElement(wi,{index:e}),I&&r().createElement(s.N_E,{href:I,target:"_blank",className:so,"data-testid":"stage-toolbar-view-token-usage-link"},"View token usage"),v&&ae(t.stageOperator)&&r().createElement(s.$nd,{"data-testid":"stage-toolbar-view-indexes-button",size:"xsmall",className:oo,onClick:()=>{C("Search Index View Indexes Button Clicked",{context:"Stage Toolbar"}),E("compass-indexes-drawer"),f(re(t.stageOperator,t.value)??void 0)},title:"View Indexes"},"View Indexes"),y&&k&&r().createElement(s.gIH,{signals:k,onPopoverOpenChange:D})),r().createElement("div",{className:lo},t.disabled?"Stage disabled. Results not passed in the pipeline.":t.collapsed?"A sample of the aggregated results from this stage will be shown below.":null),r().createElement("div",{className:co},r().createElement(s.K0,{onClick:()=>u(e),"aria-label":"Open stage in focus mode",title:"Open stage in focus mode","data-testid":"focus-mode-button","data-guide-cue-ref":"focus-mode-button"},r().createElement(s.Int,{glyph:"FullScreenEnter",size:"small"})),r().createElement(Bi,{index:e})))}));var po=n(25607);const mo=[/geoWithin requires path '.*' to be indexed as 'geo'/i,/geoShape requires path '.*' to be indexed as 'geo' with indexShapes=true/i,/hasAncestor requires .* to be indexed as 'embeddedDocuments'/i,/hasAncestor requires path '%s' to be indexed as 'embeddedDocuments'/i,/HasRoot requires .* to be indexed as 'embeddedDocuments'/i,/returnScope path '.*' must be indexed as embeddedDocument with a non-empty storedSource definitionSyntax./i,/near with a geo point origin requires path '.*' to be indexed as 'geo'/i,/autocomplete index field definition not present at path .*/i,/embeddedDocument requires path '.*' to be indexed as 'embeddedDocuments'/i,/Path '.*' needs to be indexed as/i],go="8.3.0";function ho(e){const t=Ga().valid(Ga().coerce(e));return!!t&&Ga().gte(t,go)}function fo(e){if(!e)return!1;const t=e.toLowerCase();return t.includes("$rerank is not enabled")&&t.includes("enable the $rerank project setting")}const yo="Voyage API error",bo="EmbeddingProviderRateLimitException",vo="status: 429",xo="HTTP 429",Eo=/\(RPM\) rate limit of (\d[\d,]*)/i,Co=/\(TPM\) rate limit of (\d[\d,]*)/i,wo=/reduced rate limits of ([^.]+)/i;function Io(e){if(!e)return null;const t=e.includes(yo)||e.includes(bo),n=e.includes(vo)||e.includes(xo);if(!t||!n)return null;const a=wo.exec(e);if(a)return{type:"billing",limits:a[1].trim()};const r=Eo.exec(e);if(r)return{type:"rpm",limit:r[1]};const i=Co.exec(e);return i?{type:"tpm",limit:i[1]}:null}function So(e){return"$rerank"===e?"rerank":"$vectorSearch"===e?"autoEmbedding":null}const Ao={rerank:"$rerank",autoEmbedding:"auto embedding"},ko=(0,s.AHW)({width:"100%",textAlign:"left"});function Do({rateLimitInfo:e,searchExtensionType:t,dataTestId:n="rate-limit-exceeded-banner"}){const{atlasMetadata:a}=(0,Wr.qm)();if("billing"===e.type){const t=a?(0,_i.PC)({orgId:a.orgId}):null;return r().createElement(s.lZ$,{variant:s.uAY.Danger,"data-testid":n,className:ko},r().createElement("strong",null,"Query rate limits exceeded"),r().createElement("br",null),"You are currently on Tier 0 with reduced rate limits of"," ",e.limits,"."," ",t?r().createElement(s.N_E,{href:t,target:"_blank"},"Add a payment method"):"Add a payment method"," ","for your organization to unlock the higher tier.")}const i=t&&a?(0,_i.ns)({projectId:a.projectId,clusterName:a.clusterName,extensionType:t}):null;return r().createElement(s.lZ$,{variant:s.uAY.Danger,"data-testid":n,className:ko},r().createElement("strong",null,"autoEmbedding"===t?"Query rate limit exceeded":"Rate limit exceeded"),r().createElement("br",null),r().createElement("span",null,"Exceeded ",e.limit," ","rpm"===e.type?"requests":"tokens"," per minute rate limit",t?` for ${Ao[t]}`:"",".",i&&r().createElement(r().Fragment,null," ",r().createElement(s.N_E,{href:i,target:"_blank"},"View Rate Limit"))))}const No=(0,s.AHW)({textAlign:"left"}),Mo=(0,s.AHW)({display:"flex",justifyContent:"space-between",alignItems:"center",width:"100%"});function To({message:e,searchIndexName:t,onEditSearchIndexClick:n,searchExtensionType:a,dataTestId:i="server-error-banner"}){const{enableSearchActivationProgramP1:o}=(0,O.p5)(),{openDrawer:l}=(0,s.u6F)(),c=(0,O.Jr)(),{atlasMetadata:d}=(0,Wr.qm)(),u=fo(e),p=u?"Enable native reranking in project settings.":e,m=u&&d?(0,_i.yV)({projectId:d.projectId}):null,g=Io(e);return g?r().createElement(Do,{rateLimitInfo:g,searchExtensionType:a,dataTestId:i}):r().createElement(s.lZ$,{variant:"danger","data-testid":i,className:No},u?r().createElement(r().Fragment,null,r().createElement("strong",null,"Native reranking not enabled"),r().createElement("br",null),r().createElement("div",{className:Mo},r().createElement("span",null,p),m&&r().createElement(s.$nd,{size:"xsmall",href:m,target:"_blank",rightGlyph:r().createElement(s.Int,{glyph:"OpenNewTab"})},"Project Settings"))):e,o&&t&&!!(h=e)&&mo.some((e=>e.test(h)))&&n&&r().createElement(r().Fragment,null," ",r().createElement(s.N_E,{onClick:()=>{c("Search Index Edit Link Clicked",{context:"Server Error Banner"}),l("compass-indexes-drawer"),n(t)}},"Edit Search Index")));var h}const Po=(0,s.AHW)({flex:"none",marginTop:s.YKD[200],marginLeft:s.YKD[200],marginRight:s.YKD[200],textAlign:"left"});function Lo({searchIndexName:e,searchStageOperator:t,onViewIndexesClick:n,onCreateSearchIndexClick:a}){const{openDrawer:i}=(0,s.u6F)(),o=(0,O.Jr)(),l=function(e){return"$vectorSearch"===e?"vectorSearch":"search"}(t),c="vectorSearch"===l?"Vector search":"Search",d=e?`${c} index '${e}' doesn't exist.`:`${c} index doesn't exist.`;return r().createElement(s.lZ$,{variant:"warning","data-testid":"search-index-does-not-exist-banner",title:d,className:Po},d," ",n&&a&&r().createElement(r().Fragment,null,r().createElement(s.N_E,{onClick:()=>{o("Search Index View Indexes Link Clicked",{context:"Search Index Does Not Exist Banner"}),i("compass-indexes-drawer"),n()}},"View Search Indexes")," or ",r().createElement(s.N_E,{onClick:()=>{o("Search Index Create Link Clicked",{context:"Search Index Does Not Exist Banner",index_type:l}),i("compass-indexes-drawer"),a(l)}},"Create a New Index")))}const Oo=(0,s.AHW)({display:"flex",justifyContent:"space-between",alignItems:"center",gap:s.YKD[200],flexWrap:"nowrap"}),Ro=(0,s.AHW)({flexShrink:0,whiteSpace:"nowrap"}),Ho=({"data-testid":e})=>{const{atlasMetadata:t}=(0,Wr.qm)(),n=t?(0,_i.q9)(t):"https://www.mongodb.com/docs/atlas/tutorial/major-version-change/";return r().createElement(s.lZ$,{variant:"danger","data-testid":e},r().createElement("div",{className:Oo},r().createElement("span",null,"Upgrade your cluster to MongoDB ",go,"+ to use $rerank."),r().createElement(s.$nd,{size:"xsmall",href:n,target:"_blank",rightGlyph:r().createElement(s.Int,{glyph:"OpenNewTab"}),className:Ro},"Upgrade Cluster")))},Fo=(0,s.AHW)({display:"flex",flexDirection:"column",justifyContent:"space-between",alignItems:"stretch",overflow:"hidden",height:"100%"}),Wo=(0,s.AHW)({}),jo=(0,s.AHW)({background:s.MFm.gray.light3}),Bo=(0,s.AHW)({flex:1,flexShrink:0,margin:0,width:"100%",minHeight:"230px"}),zo=(0,s.AHW)({"& .cm-editor":{background:"transparent !important"}}),_o=(0,s.AHW)({flex:"none",marginTop:s.YKD[200],marginLeft:s.YKD[200],marginRight:s.YKD[200],textAlign:"left"}),$o=(0,o.Ng)(((e,t)=>{const n=e.pipelineBuilder.stageEditor.stages,a=n[t.index],r=St(n).length,i=nn(e),o=re(a.stageOperator,a.value),s=!!o&&["READY","POLLING"].includes(e.searchIndexes.status)&&e.searchIndexes.indexes.every((e=>e.name!==o)),l=!a.empty&&!a.fromSnippet;return{namespace:e.namespace,stageValue:a.value,stageOperator:a.stageOperator,syntaxError:l?a.syntaxError??null:null,serverError:l?a.serverError??null:null,serverErrorStageIdx:kt(n,t.index),serverVersion:e.serverVersion,num_stages:r,editor_view_type:i,searchIndexName:o,showSearchIndexDoesNotExistBanner:s}}),{onChange:Pt,onViewSearchIndexesClick:Vn,onCreateSearchIndexClick:qn,onEditSearchIndexClick:Un})((({namespace:e,stageValue:t,stageOperator:n,index:i,onChange:o,onViewSearchIndexesClick:l,onCreateSearchIndexClick:c,onEditSearchIndexClick:d,serverError:u,serverErrorStageIdx:p,syntaxError:m,className:h,serverVersion:f,num_stages:y,editor_view_type:b,searchIndexName:v,showSearchIndexDoesNotExistBanner:x,editorRef:E})=>{const C=(0,O.Jr)(),w=(0,Wr.jj)(),I=(0,s.D27)(),S=(0,a.useRef)(t),A=(0,s.HIF)(t),k=(0,po.jv)(e),{enableSearchActivationProgramP1:D}=(0,O.p5)(),N=(0,g.Fg)("enableRerank"),{utmSource:M,utmMedium:T}=(0,s.GUC)(),P=(0,a.useMemo)((()=>(0,K.xG)({serverVersion:f,stageOperator:n??void 0,fields:k,utmSource:M,utmMedium:T})),[k,f,n,M,T]),L=(0,a.useMemo)((()=>m?.loc?.index?[{message:m.message,severity:"error",from:m.loc.index,to:m.loc.index}]:[]),[m]),R=(0,a.useCallback)((()=>{A.current&&A.current!==S.current&&(C("Aggregation Edited",{num_stages:y,stage_index:i+1,stage_action:"stage_content_changed",stage_name:n,editor_view_type:b},w.current),S.current=A.current)}),[A,C,y,i,n,b,w]),H=(0,a.useCallback)((()=>{document.querySelector(`[data-stage-index="${p}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})}),[p]),F=null!==p&&p<i;return r().createElement("div",{"data-testid":"stage-editor",className:(0,s.cx)(Fo,I?Wo:jo,h)},r().createElement("div",{className:Bo},r().createElement(K.Jn,{ref:E,text:t??"",onChangeText:e=>{o(i,e)},className:zo,id:`aggregations-stage-editor-${i}`,completer:P,annotations:L,onBlur:R})),N&&"$rerank"===n&&!ho(f)&&r().createElement("div",{className:_o},r().createElement(Ho,{"data-testid":"stage-editor-rerank-version-warning"})),m&&r().createElement(s.lZ$,{variant:"warning","data-testid":"stage-editor-syntax-error",title:m.message,className:_o},n?t?m.message:"Stage value can not be empty":"Stage operator is required"),u&&!F&&r().createElement("div",{className:_o},r().createElement(To,{message:u.message,searchIndexName:v,dataTestId:"stage-editor-error-message",searchExtensionType:So(n),onEditSearchIndexClick:"focus"!==b?d:void 0})),F&&r().createElement(s.lZ$,{variant:"warning","data-testid":"stage-editor-upstream-error-message",className:_o},"An error occurred on"," ",r().createElement(s.N_E,{as:"button",onClick:H},"Stage ",p+1),"."),D&&!u&&!m&&x&&ae(n)&&r().createElement(Lo,{searchIndexName:v,searchStageOperator:n,onViewIndexesClick:"focus"!==b?l:void 0,onCreateSearchIndexClick:"focus"!==b?c:void 0}))})),Yo=$o,Ko=(0,s.AHW)({borderRadius:0,border:"none","&::before":{display:"none"}}),Go=({"data-testid":e})=>{const t=(0,g.Fg)("enableRerank"),[n,a]=(0,s.yRS)("mongodb_compass_dismissed_rerank_tokens_banner",!1);return!t||n?null:r().createElement(s.lZ$,{variant:"info","data-testid":e,className:Ko,dismissible:!0,onClose:()=>a(!0)},r().createElement("strong",null,"$rerank consumes tokens"),r().createElement("br",null),"Turn off the preview or disable the stage to avoid running $rerank while editing.")};var Vo=n(17156);const Uo=(0,s.AHW)({position:"absolute",top:0,left:0,bottom:0,right:0,zIndex:1,display:"flex",alignItems:"center",justifyContent:"center"}),qo=(0,s.AHW)({backgroundColor:s.MFm.black}),Zo=(0,s.AHW)({backgroundColor:"white"}),Jo=(0,s.AHW)({marginLeft:s.YKD[200]}),Qo=function({text:e}){const t=(0,s.D27)();return r().createElement("div",{className:(0,s.cx)(Uo,t?qo:Zo)},r().createElement(s.Q0K,null),r().createElement(s.nBu,{className:Jo},e))},Xo=(0,s.AHW)({display:"flex",flexDirection:"column",alignItems:"center",padding:s.YKD[800],gap:s.YKD[400],textAlign:"center"}),es=(0,s.AHW)({maxWidth:"400px"}),ts=({stageOperator:e})=>{const t=(0,O.Jr)();return r().createElement("div",{className:Xo,"data-testid":"atlas-only-stage-preview"},r().createElement(s.XYu,null),r().createElement(s.nBu,{"data-testid":"stage-preview-missing-search-support",className:es},"The ",e," stage is only available with MongoDB Atlas. Create a free cluster or connect to an Atlas cluster to build search indexes and use ",e," aggregation stage to run fast, relevant search queries."),r().createElement(s.$nd,{href:"https://www.mongodb.com/cloud/atlas/lp/search-1",target:"_blank",onClick:()=>{t("Atlas Link Clicked",{screen:"agg_builder"})},variant:"primary"},"Create free cluster"))},ns=e=>(t,n,{workspaces:a,connectionInfoRef:r})=>{const{outResultsFn:i}=n(),{id:o}=r.current;i?i(e):a.openCollectionWorkspace(o,e,{newTab:!0})},as=(0,s.AHW)({display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:s.YKD[200]}),rs=(0,s.AHW)({textAlign:"center"}),is=(0,s.AHW)({border:"none",padding:0,margin:0,background:"none"}),os=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[200]}),ss=({destinationNamespace:e})=>r().createElement("div",{className:as},r().createElement("div",{className:os},r().createElement(s.Q0K,null),"Persisting Documents"," ",e?`to ${e}`:"...")),ls=(0,o.Ng)(((e,t)=>{const n=e.pipelineBuilder.stageEditor.stages[t.index],a=n.stageOperator?Q(e.namespace,{[n.stageOperator]:n.value??""}):null;return{isLoading:n.loading,hasServerError:!!n.serverError,isFinishedPersistingDocuments:Boolean(n.previewDocs),destinationNamespace:a,operator:n.stageOperator}}),((e,t)=>({onRunOutputStage:()=>{return e((n=t.index,async(e,t,{pipelineBuilder:a,preferences:r,connectionScopedAppRegistry:i})=>{const{dataService:{dataService:o},namespace:s,maxTimeMS:c,collationString:d,pipelineBuilder:{stageEditor:{stages:u}}}=t(),p=u[n];if(!o||!p||"stage"!==p.type||p.disabled||!St(u.slice(0,n+1)).every((e=>Dt(e,!0))))return;const{idxInPipeline:m}=p;try{e({type:dt,id:n});const t=a.getPipelineFromStages(a.stages.slice(0,m+1)),u={maxTimeMS:c??l,collation:d.value??void 0},{signal:p}=new AbortController,g=await B({dataService:o,preferences:r,signal:p,namespace:s,pipeline:t,options:u});e({type:ut,id:n,previewDocs:g.map((e=>new W.Ay(e))),stageMetadata:null}),i.emit("agg-pipeline-out-executed",Q(s,t[t.length-1]))}catch(t){e({type:pt,id:n,error:t})}}));var n},onGoToOutputResults:()=>{return e((n=t.index,(e,t,{pipelineBuilder:a})=>{t().focusMode.isEnabled&&e(Hi());const r=t(),i=function(e,t){return"builder-ui"===e.pipelineBuilder.pipelineMode?t.stages.map((e=>e.toBSON())):t.getPipelineFromSource()}(r,a)[n],o=Q(r.namespace,i);o&&e(ns(o))}));var n}})))((({operator:e,isLoading:t,hasServerError:n,isFinishedPersistingDocuments:a,destinationNamespace:i,onRunOutputStage:o,onGoToOutputResults:l})=>{const c=!(0,g.Fg)("enableAggregationBuilderRunPipeline");if(!te(e??""))return null;if(c){if(n)return null;if(t)return r().createElement(ss,{destinationNamespace:i});if(a)return r().createElement("div",{className:as},r().createElement(s.nBu,{className:rs},"Documents persisted to "+((p=i)?`collection: ${p}`:"specified collection")),r().createElement(s.N_E,{"data-testid":"goto-output-collection",as:"button",className:is,onClick:l},"Go to collection."))}var p;return r().createElement("div",{className:as},r().createElement("div",{className:rs,"data-testid":"output-stage-text"},"$merge"===e?u:d),c&&r().createElement(s.$nd,{variant:"primary","data-testid":"save-output-documents",onClick:o},"$merge"===e?"Merge Documents":"Save Documents"))})),cs=({stageOperator:e,description:t,link:n})=>r().createElement("span",null,r().createElement(s.m_M,{enabled:!!t,trigger:r().createElement(s.N_E,{"data-testid":"stage-preview-toolbar-link",target:"_blank",href:n},e)},t)),ds=(0,o.Ng)(((e,t)=>{const n=e.pipelineBuilder.stageEditor.stages[t.index],a=function(e,t,n,a=!1){const r=t?function(e){let t=se.get(e);return t||(t=new Map(oe(e).map((e=>[e.value,e]))),se.set(e,t)),t}(a).get(t):void 0;return{description:r?.description,link:le(t),destination:t&&te(t)?(()=>{try{const a=U(`{${t}: ${n}}`);return a[t].s3?"S3 bucket":a[t].atlas||a[t].into?.atlas?"Atlas cluster":Q(e,a)}catch{return null}})():null}}(e.namespace,n.stageOperator,n.value,t.enableAutoEmbeddingPublicPreview);return{stageOperator:n.stageOperator,previewSize:n.previewDocs?.length??0,...a}}))((function({stageOperator:e,previewSize:t,description:n,link:a,destination:i}){return e?r().createElement(s.nBu,null,i?`Documents will be saved to ${i}.`:r().createElement(r().Fragment,null,r().createElement("span",null,"Output preview after"," ",r().createElement(cs,{stageOperator:e,description:n,link:a??void 0})," ","stage")," ",r().createElement("span",{"data-testid":"stage-preview-toolbar-tooltip"},"(Sample of ",t," ",1!==t?"documents":"document",")"))):null}));function us(e){const{enableAutoEmbeddingPublicPreview:t}=(0,g.gc)(["enableAutoEmbeddingPublicPreview"]);return r().createElement(ds,{index:e.index,enableAutoEmbeddingPublicPreview:Boolean(t)})}const ps=(0,s.AHW)({display:"flex",alignItems:"center",justifyContent:"center",height:"100%",padding:s.YKD[400],flexDirection:"column",textAlign:"center"}),ms=(0,s.AHW)({color:s.MFm.green.dark2}),gs=(0,s.AHW)({color:s.MFm.green.base});function hs(){const e=(0,s.D27)();return r().createElement("div",{className:ps},r().createElement(s.Pds,{className:e?gs:ms},"No preview documents"),r().createElement(s.nBu,null,"This may be because your search has no results or your search index does not exist."))}const fs=(0,s.AHW)({flex:"none",marginTop:s.YKD[200],marginLeft:s.YKD[200],marginRight:s.YKD[200],textAlign:"left"}),ys=(0,o.Ng)((e=>({namespace:e.namespace})))((function({searchIndexName:e,namespace:t}){const[n,a]=r().useState(!0),{atlasMetadata:i}=(0,Wr.qm)(),o=(0,O.Jr)(),l="Results shown are based on the most recently built index version.",c=i&&e?(0,_i.Yc)({atlasMetadata:i,namespace:t,indexName:e}):null;return n?r().createElement(s.lZ$,{variant:"info","data-testid":"search-index-stale-results-banner",title:l,className:fs,dismissible:!0,onClose:()=>a(!1)},l," ",c&&r().createElement(s.N_E,{href:c,onClick:()=>{o("Search Index View Definition Link Clicked",{context:"Search Index Stale Results Banner"})}},"View Index Definition")):null})),bs=(0,s.AHW)({display:"flex",alignItems:"center",justifyContent:"center",height:"100%",padding:s.YKD[400],flexDirection:"column"}),vs=(0,s.AHW)({margin:"auto",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fill:"none",textAlign:"center"}),xs=(0,s.AHW)({stroke:s.MFm.gray.base}),Es=(0,s.AHW)({stroke:s.MFm.gray.base});function Cs(){const e=(0,s.D27)();return r().createElement("div",{className:bs},r().createElement("div",{className:(0,s.cx)(vs,e?xs:Es)},r().createElement(s.nBu,null,r().createElement("span",{"data-testid":"stage-preview-empty"},"No Preview Documents"))))}const ws=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[400],width:"100%",height:"100%"}),Is=(0,s.AHW)({gap:s.YKD[200],display:"flex",alignItems:"stretch",overflowX:"auto"}),Ss=(0,s.AHW)({display:"flex",flexDirection:"column",flex:"none",flexShrink:0,width:"384px",marginBottom:s.YKD[200]}),As=(0,s.AHW)({flexBasis:"164px",flexGrow:1,flexShrink:0,overflow:"auto",padding:0});function ks({index:e,stageOperator:t,documents:n,isMissingAtlasOnlyStageSupport:a,shouldRenderStage:i,isLoading:o,showSearchIndexStaleResultsBanner:l,searchIndexName:c,serverErrorStageIdx:d}){const{enableSearchActivationProgramP1:u}=(0,O.p5)();if(!i)return r().createElement(Cs,null);if(a)return r().createElement("div",{className:bs},r().createElement(ts,{stageOperator:t??""}));if(te(t??""))return r().createElement("div",{className:bs},r().createElement(ls,{index:e}));if(o)return r().createElement("div",{className:bs},r().createElement(Qo,{text:"Loading Preview Documents..."}));if(null!==d)return r().createElement("div",{className:bs},r().createElement(s.nBu,null,r().createElement("span",{"data-testid":"stage-preview-upstream-error"},"Preview unavailable — error on"," ",r().createElement(s.N_E,{as:"button",onClick:()=>{document.querySelector(`[data-stage-index="${d}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})}},"Stage ",d+1),".")));if(!u&&ae(t)&&0===n?.length)return r().createElement(hs,null);if(n&&n.length>0){const e=n.map(((e,t)=>r().createElement(s.yY_,{key:t,className:Ss},r().createElement("div",{className:As},r().createElement(Vo.yo,{doc:e,editable:!1})))));return r().createElement("div",{className:ws},r().createElement("div",{className:Is},e),u&&l&&r().createElement(ys,{searchIndexName:c}))}return r().createElement(Cs,null)}const Ds=(0,s.AHW)({display:"flex",flexDirection:"column",padding:s.YKD[400],gap:s.YKD[200],flex:1}),Ns=(0,s.AHW)({alignItems:"stretch",position:"relative",flexGrow:1}),Ms=(0,o.Ng)(((e,t)=>{const n=e.pipelineBuilder.stageEditor.stages[t.index],a=ue(e.env,n.stageOperator,n.serverError),r=Boolean(!n.disabled&&!n.syntaxError&&!n.syntaxError&&n.value),i=re(n.stageOperator,n.value),o=!!i&&e.searchIndexes.indexes.some((e=>e.name===i&&"READY"!==e.status&&e.queryable));return{isLoading:n.loading,isDisabled:n.disabled,stageOperator:n.stageOperator,shouldRenderStage:r,documents:n.previewDocs,isMissingAtlasOnlyStageSupport:!!a,showSearchIndexStaleResultsBanner:o,searchIndexName:i,serverErrorStageIdx:kt(e.pipelineBuilder.stageEditor.stages,t.index)}}))((function(e){return e.isDisabled?r().createElement("div",{className:Ds},r().createElement(Cs,null)):r().createElement("div",{className:Ds,"data-testid":`stage-preview-${e.index}`},r().createElement(us,{index:e.index}),r().createElement("div",{className:Ns},r().createElement(ks,e)))})),Ts=(0,s.AHW)({position:"relative",display:"flex",flexDirection:"column",alignItems:"stretch",overflow:"hidden"}),Ps=(0,s.AHW)({borderColor:s.MFm.yellow.base}),Ls=(0,s.AHW)({borderColor:s.MFm.red.base}),Os=(0,s.AHW)({display:"flex"}),Rs=(0,s.AHW)({width:"100%"}),Hs=(0,s.AHW)({display:"flex",position:"relative",flexDirection:"column",width:"100%",overflow:"auto"}),Fs=(0,s.AHW)({paddingTop:s.YKD[200],paddingBottom:s.YKD[200]}),Ws={top:!1,right:!0,bottom:!1,left:!1,topRight:!1,bottomRight:!1,bottomLeft:!1,topLeft:!1};function js({isAutoPreviewing:e,...t}){const n=r().createElement(Yo,(0,fi.A)({},t,{className:(0,s.cx)(Fs,t.className)}));return e?r().createElement(hi.c,{defaultSize:{width:"388px",height:"auto"},minWidth:"260px",maxWidth:"92%",enable:Ws,handleComponent:{right:r().createElement(Ci,null)},handleStyles:{right:{right:"-9px"}}},n):r().createElement("div",{className:Rs},n)}const Bs=(0,o.Ng)(((e,t)=>{const{stages:n}=e.pipelineBuilder.stageEditor,a=n[t.index];return{isEnabled:!a.disabled,isExpanded:!a.collapsed,hasSyntaxError:pe(a),hasServerError:!!a.serverError,isAutoPreviewing:e.autoPreview,showRerankFirstStageBanner:en(e,t.index),showRerankTokensBanner:"$rerank"===a.stageOperator&&!!e.autoPreview}}))((function({index:e,isEnabled:t,isExpanded:n,hasSyntaxError:i,hasServerError:o,isAutoPreviewing:l,showRerankFirstStageBanner:c,showRerankTokensBanner:d,...u}){const p=(0,a.useRef)(null),m=(0,a.useRef)(null),g=t?1:.6,{setNodeRef:h,style:f,listeners:y}=u,b=(0,a.useCallback)((e=>{h(e),m.current=e}),[m,h]);return r().createElement("div",{ref:b,style:f},r().createElement(s.yY_,{"data-testid":"stage-card","data-stage-index":e,className:(0,s.cx)(Ts,i&&Ps,o&&Ls)},r().createElement("div",y,r().createElement(uo,{onStageOperatorChange:(e,t,n)=>{(0,s.Rbc)((()=>{p.current?.focus(),n&&p.current?.applySnippet(n)}))},index:e})),c&&r().createElement(Ji,{"data-testid":"stage-rerank-first-stage-banner"}),d&&r().createElement(Go,{"data-testid":"stage-rerank-tokens-banner"}),n&&r().createElement("div",{style:{opacity:g},className:Os},r().createElement(js,{index:e,isAutoPreviewing:l,editorRef:p}),l&&r().createElement("div",{className:Hs},r().createElement(Ms,{index:e})))))}));var zs=n(72179);const _s=(0,s.AHW)({padding:`${s.YKD[200]}px ${s.YKD[400]}px`,textAlign:"left",width:"100%"}),$s=(0,s.AHW)({opacity:.5}),Ys=(0,s.AHW)({cursor:"grabbing"}),Ks=(0,s.AHW)({display:"inline",marginRight:s.YKD[200]}),Gs=r().forwardRef((function({id:e,title:t,stageOperator:n,isDragging:i,isDropping:o,onSelect:l,...c},d){const u=(0,a.useCallback)((e=>{"Enter"!==e.key&&"Enter"!==e.code||l?.()}),[l]);return r().createElement(s.yY_,(0,fi.A)({ref:d,contentStyle:"clickable",className:(0,s.cx)(_s,i&&$s,o&&Ys),onClick:l,onKeyDown:u},c),r().createElement(s.nBu,{as:"div","data-testid":`use-case-${e}`,className:Ks},t," ",r().createElement(s.Exy,null,n)))})),Vs=({id:e,title:t,stageOperator:n,onSelect:a})=>{const{setNodeRef:i,attributes:o,listeners:s,isDragging:l}=(0,zs.PM)({id:e,data:{type:"use-case",draggedUseCase:{id:e,title:t,stageOperator:n}}});return r().createElement(Gs,(0,fi.A)({id:e,title:t,stageOperator:n,isDragging:l,onSelect:a,ref:i},o,s))},Us=e=>e.replace(/^\$/,"").replace(/\./g,"_"),qs=e=>0===e.length?null:1===e.length?`$${e[0]}`:Object.fromEntries(e.map((e=>[Us(e),`$${e}`]))),Zs=[{label:"Ascending",value:"Asc"},{label:"Descending",value:"Desc"}],Js=e=>e.reduce(((e,t)=>(t.field&&(e[t.field]="Asc"===t.direction?1:-1),e)),{});let Qs=0;const Xs=()=>Qs++,el=(e,t)=>{const n=t.split(".");if(n.length>1){const a=((e,t=[])=>e.reduce(((e,t)=>{const n=e.length?e[e.length-1]+"."+t:t;return[...e,n]}),[]).filter((e=>!t.includes(e))))(n,[t]),r=a.some((t=>e.includes(t))),i=e.some((e=>e.startsWith(`${t}.`)));return r||i}return e.some((e=>e.startsWith(`${t}.`)))},tl=({fields:e,multiselect:t,"aria-label":n,placeholder:i,isRelatedFieldDisabled:o=!1,value:l,...c})=>{const d=(0,a.useMemo)((()=>e.map((({name:e,type:t})=>({value:e,type:t})))),[e]),u=(0,a.useMemo)((()=>t?"Select fields":"Select a field"),[t]);return r().createElement(s.WqN,(0,fi.A)({"aria-label":n??u,placeholder:i??u,multiselect:t,size:"default",clearable:!1,overflow:"scroll-x"},c,{options:d,renderOption:(e,n,a)=>r().createElement(s.jOs,{key:`field-option-${n}`,value:e.value,displayName:a?`Field: "${e.value}"`:e.value,description:e.type??"Unknown",disabled:!(!o||!t)&&el(l??[],e.value)})}))},nl=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[200],width:"max-content",maxWidth:"100%"}),al=(0,s.AHW)({display:"flex",justifyContent:"flex-start",alignItems:"center",gap:s.YKD[200]}),rl=(0,s.AHW)({minWidth:"17ch",textAlign:"right"}),il=(0,s.AHW)({width:"150px"}),ol=(0,s.AHW)({minWidth:"200px"}),sl=({index:e,comboboxClassName:t,fields:n,sortField:a,sortDirection:i,onChange:o})=>r().createElement("div",{className:al},r().createElement(s.nBu,{className:rl},0===e?"Sort documents by":"and"),r().createElement("div",{"data-testid":`sort-form-${e}-field`},r().createElement(tl,{className:t,value:a,onChange:e=>{e&&o("field",e)},fields:n})),r().createElement(s.nBu,null,"in"),r().createElement("div",{"data-testid":`sort-form-${e}-direction`},r().createElement(s.l6P,{className:il,allowDeselect:!1,"aria-label":"Select direction",value:i,onChange:e=>o("direction",e)},Zs.map(((e,t)=>r().createElement(s.c$x,{key:t,value:e.value},e.label))))));n(10838),n(63678);var ll=n(67092),cl=n(90605);const dl=e=>t=>({name:`${e}.${t.name}`,type:t.type}),ul=(e,t=new WeakSet)=>{const n=[];if(t.has(e))return n;t.add(e);for(const a in e){const r=e[a];if(n.push({name:a,type:ll.Ay.type(r)}),Array.isArray(r)){const e=pl(r,t).map(dl(a));n.push(...e)}else if("object"==typeof r&&null!==r&&!(0,ll.TB)(r)){const e=ul(r,t).map(dl(a));n.push(...e)}}return n},pl=(e,t=new WeakSet)=>{const n=[];for(const a of e)Array.isArray(a)?n.push(...pl(a,t)):"object"!=typeof a||null===a||(0,ll.TB)(a)||n.push(...ul(a,t));return n},ml=e=>{const t=pl(e),n=(0,cl.sortBy)(t,"name");return(0,cl.sortedUniqBy)(n,"name")},gl="compass-aggregations/collectionsFetched",hl="compass-aggregations/collectionFieldsFetched",fl="compass-aggregations/collectionDataUpdated",yl={},bl=e=>(t,n)=>{const a=n().collectionsFields,r={};e.forEach((({name:e,type:t})=>{r[e]=a[e]??{fields:[],isLoading:!1,type:t}})),(0,cl.isEqual)(Object.keys(a),Object.keys(r))||t({type:gl,data:r})},vl=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[200]}),xl=(0,s.AHW)({minWidth:"19ch",textAlign:"right"}),El=(0,s.AHW)({display:"flex",gap:s.YKD[200],alignItems:"center"}),Cl=(0,s.AHW)({width:"300px"}),wl=(0,o.Ng)((e=>({collectionsFields:e.collectionsFields})),{onSelectCollection:e=>async(t,n)=>{const{collectionsFields:a,namespace:r,dataService:{dataService:i}}=n();if(!i)return;const o=a[e];if(!(o&&o.fields.length>0)){t({type:fl,collection:e,data:{...o,fields:[],isLoading:!0,error:void 0}});try{if(!i.find||!i.sample)throw new Error("Collection schema sampling not available in this context");const{database:n}=(0,z.Ay)(r),a=`${n}.${e}`,s="collection"===o.type?await i.find(a,{},{sort:{$natural:-1},limit:1,maxTimeMS:1e4}):await i.sample(a,{size:1},{maxTimeMS:1e4});t({type:fl,collection:e,data:{...o,fields:ml(s).map((({name:e})=>e)),isLoading:!1}})}catch(n){t({type:fl,collection:e,data:{...o,fields:[],isLoading:!1,error:n}})}}}})((({fields:e,collectionsFields:t,onSelectCollection:n,onChange:i})=>{const[o,l]=(0,a.useState)({as:"",from:"",foreignField:"",localField:""}),c=(0,a.useCallback)(((e,t)=>{if(null===t)return;const a={...o,[e]:t};"from"!==e||o.as&&o.from!==o.as||(a.as=t);const r=Object.values(a).some((e=>!e));i(JSON.stringify(a),r?new Error("Enter all the fields"):null),"from"===e&&a.from!==o.from&&n(a.from),l(a)}),[o,l,i,n]),d=(0,a.useMemo)((()=>o.from?t[o.from]:null),[o.from,t]);return r().createElement("div",{className:vl},r().createElement("div",{className:El},r().createElement(s.nBu,{className:xl},"Join documents from"),r().createElement(s.G3_,{"aria-label":"Select collection",placeholder:"Select collection",value:o.from,clearable:!1,className:Cl,onChange:e=>c("from",e)},Object.keys(t).map(((e,t)=>r().createElement(s.jOs,{key:t,value:e}))))),r().createElement("div",{className:El},r().createElement(s.nBu,{className:xl},"where"),r().createElement(s.WqN,{className:Cl,"aria-label":"Select foreign field",placeholder:"Select foreign field",size:"default",clearable:!1,onChange:e=>c("foreignField",e),searchState:d?.isLoading?"loading":d?.error?"error":"unset",searchLoadingMessage:"Fetching fields ...",searchErrorMessage:"Failed to fetch the fields. Type the field name manually.",searchEmptyMessage:o.from?void 0:"Select a collection first.",options:(d?.fields??[]).map((e=>({value:e}))),renderOption:(e,t)=>r().createElement(s.jOs,{key:t,value:e.value,displayName:e.value})})),r().createElement("div",{className:El},r().createElement(s.nBu,{className:xl},"matches"),r().createElement(tl,{className:Cl,"aria-label":"Select local field",placeholder:"Select local field",clearable:!1,onChange:e=>c("localField",e),fields:e})),r().createElement("div",{className:El},r().createElement(s.nBu,{"aria-label":"Name of the array",id:"lookup-stage-as-input-label",className:xl},"as"),r().createElement("div",{className:Cl},r().createElement(s.ksK,{value:o.as,title:"Name of the array","aria-labelledby":"lookup-stage-as-input-label","data-testid":"name-of-the-array-input",placeholder:"Name of the array",onChange:e=>c("as",e.target.value)}))))})),Il=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[200]}),Sl=(0,s.AHW)({display:"flex",justifyContent:"flex-start",alignItems:"center",gap:s.YKD[200]}),Al=(0,s.AHW)({minWidth:"120px"}),kl=(0,s.AHW)({width:"350px"}),Dl=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[200]}),Nl=(0,s.AHW)({width:"350px"}),Ml={$avg:"Average",$min:"Minimum",$stdDevPop:"Standard Deviation",$count:"Count",$max:"Maximum",$sum:"Sum"},Tl=Object.keys(Ml);function Pl(e){return Tl.includes(e.value)}const Ll=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[200],width:"max-content",maxWidth:"100%"}),Ol=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[200]}),Rl=(0,s.AHW)({minWidth:"100px",textAlign:"right"}),Hl=Math.max(...Object.values(Ml).map((e=>e.length))),Fl=(0,s.AHW)({width:`${String(Hl)}ch`}),Wl=(0,s.AHW)({width:"300px"}),jl=(0,s.AHW)({width:"100%"}),Bl=({field:e,accumulator:t})=>{if("$count"===t)return"count";const n=t.replace(/\$/g,""),a=Us(e);return[n,a.startsWith("_")?"":"_",a].join("")},zl=({field:e,accumulator:t})=>({[t]:"$count"===t?{}:`$${e}`}),_l=({fields:e,serverVersion:t,data:n,onChange:i})=>{const o=(e,t,a)=>{if(!a)return;const r=[...n];r[e][t]=a,"accumulator"===t&&"$count"===a&&(r[e].field=""),i(r)},l=(0,a.useMemo)((()=>(0,_.zM)({serverVersion:t,meta:["accumulator"]}).filter(Pl).sort(((e,t)=>Ml[e.value].localeCompare(Ml[t.value])))),[t]);return r().createElement("div",{className:Ll},r().createElement(s.qQS,{items:n,onAddItem:e=>(e=>{const t=[...n];t.splice(e+1,0,{id:Xs(),field:"",accumulator:""}),i(t)})(e),onRemoveItem:e=>(e=>{const t=[...n];t.splice(e,1),i(t)})(e),itemKey:e=>String(e.id),renderItem:(t,n)=>r().createElement("div",{className:Ol},r().createElement(s.nBu,{className:Rl},0===n?"Calculate":"and"),r().createElement(s.l6P,{className:Fl,allowDeselect:!1,"aria-label":"Select accumulator",value:t.accumulator,onChange:e=>o(n,"accumulator",e)},l.map((e=>r().createElement(s.c$x,{value:e.value,key:e.value},Ml[e.value])))),"$count"!==t.accumulator&&r().createElement(r().Fragment,null,r().createElement(s.nBu,null,"of"),r().createElement(tl,{className:Wl,value:t.field,onChange:e=>o(n,"field",e),fields:e})))}))},$l=(0,o.Ng)((({serverVersion:e})=>({serverVersion:e})))((({fields:e,serverVersion:t,onChange:n})=>{const[i,o]=(0,a.useState)({groupFields:[],groupAccumulators:[{id:Xs(),field:"",accumulator:""}]}),l=(e,t)=>{const a={...i,[e]:t};o(a);const r=0===a.groupAccumulators.filter((e=>e.accumulator&&("$count"===e.accumulator||e.field))).length;n(JSON.stringify((e=>{const t=Object.fromEntries(e.groupAccumulators.filter((e=>e.accumulator&&("$count"===e.accumulator||e.field))).map((e=>[Bl(e),zl(e)])));return{_id:qs(e.groupFields),...t}})(a)),r?new Error("Select one group accumulator"):null)};return r().createElement("div",{className:Ll},r().createElement(_l,{serverVersion:t,fields:e,data:i.groupAccumulators,onChange:e=>l("groupAccumulators",e)}),r().createElement("div",{className:Ol},r().createElement(s.nBu,{className:Rl},"grouped by"),r().createElement(tl,{className:jl,value:i.groupFields,onChange:e=>l("groupFields",e),fields:e,multiselect:!0})))}));n(45602);const Yl="Select an operator",Kl="Expected value",Gl="Select a type",Vl=e=>`match-condition-${e}`,Ul=(()=>{let e=1;return(t={})=>({id:e++,field:"",operator:"$eq",value:"",bsonType:"String",...t})})(),ql=["Array","Binary","Code","MaxKey","MinKey","Object","BSONSymbol","BSONRegExp","Timestamp"],Zl=ll.Ay.castableTypes(!1).filter((e=>!ql.includes(e))),Jl=[{operator:"$eq",label:"="},{operator:"$ne",label:"!="},{operator:"$gt",label:">"},{operator:"$gte",label:">="},{operator:"$lt",label:"<"},{operator:"$lte",label:"<="}],Ql=(0,s.AHW)({display:"flex",width:"100%",alignItems:"center",gap:s.YKD[200]}),Xl=(0,s.AHW)({flex:"1 1 50%"}),ec=(0,s.AHW)({flex:"1 0 70px"}),tc=(0,s.AHW)({flex:"1 0 20%"}),nc=(0,s.AHW)({flex:"1 0 130px"}),ac=({fields:e,condition:t,onConditionChange:n})=>r().createElement("div",{"data-testid":Vl(t.id),className:Ql},r().createElement("div",{className:Xl},r().createElement(tl,{value:t.field,onChange:a=>{if(null!==a&&a!==t.field){const r=e.find((({name:e})=>e===a))?.type||ll.Ay.type(t.value);n({...t,field:a,bsonType:r})}},fields:e})),r().createElement("div",{className:ec},r().createElement(s.l6P,{size:"default",allowDeselect:!1,placeholder:Yl,"aria-label":Yl,value:t.operator,onChange:e=>{null!==e&&n({...t,operator:e})},"data-testid":"match-condition-operator-select"},Jl.map((({operator:e,label:t})=>r().createElement(s.c$x,{key:e,value:e},t))))),r().createElement("div",{className:tc},r().createElement(s.ksK,{placeholder:Kl,"data-testid":"match-stage-expected-value-input","aria-label":Kl,value:t.value,onChange:e=>{const a=e.target.value;n({...t,value:a})}})),r().createElement("div",{className:nc},r().createElement(s.l6P,{allowDeselect:!1,placeholder:Gl,"aria-label":Gl,value:t.bsonType,onChange:e=>{null!==e&&n({...t,bsonType:e})},"data-testid":"match-condition-type-select"},Zl.map((e=>r().createElement(s.c$x,{key:e,value:`${e}`},e)))))),rc=e=>`match-group-${e}`,ic=e=>`match-group-${e}-operator-select`,oc=e=>`match-group-${e}-add-nested-group-btn`,sc=e=>`match-group-${e}-remove-group-btn`,lc=(e=>{let t=1;return(n={})=>({id:t++,logicalOperator:"$and",conditions:[e()],nestedGroups:[],...n})})(Ul),cc=(0,s.AHW)({display:"flex",gap:s.YKD[400],flexDirection:"column"}),dc=(0,s.AHW)({padding:s.YKD[600],paddingTop:s.YKD[600]/2,borderRadius:s.YKD[600]/2}),uc=(0,s.AHW)({gap:s.YKD[400]}),pc=(0,s.AHW)({background:s.MFm.gray.light3}),mc=(0,s.AHW)({background:s.MFm.gray.light2}),gc=(0,s.AHW)({background:s.MFm.gray.dark3}),hc=(0,s.AHW)({background:s.MFm.gray.dark2}),fc=(0,s.AHW)({display:"flex",flexDirection:"row",alignItems:"center",gap:s.YKD[400]}),yc=(0,s.AHW)({display:"inherit"}),bc=({fields:e,group:t,nestingLevel:n,nestingDepth:a,onGroupChange:i,onGroupRemoved:o})=>{const l=(0,s.D27)(),c=3===n,d=n>0,u={paddingRight:(a-n)*s.YKD[600]},p=l?{[gc]:n%2!=0,[hc]:n%2==0}:{[pc]:n%2!=0,[mc]:n%2==0};return r().createElement("div",{"data-testid":rc(t.id),className:(0,s.cx)(cc,0!==n&&(0,s.cx)(dc,p))},r().createElement("div",{className:fc},r().createElement(s.IzF,{size:"small",value:t.logicalOperator,"data-testid":ic(t.id),onChange:e=>{(e=>{i({...t,logicalOperator:e})})(e)}},r().createElement(s.Zib,{value:"$and"},"AND"),r().createElement(s.Zib,{value:"$or"},"OR")),r().createElement(s.m_M,{align:"top",justify:"middle",enabled:c,trigger:r().createElement("div",{className:yc},r().createElement(s.$nd,{size:"xsmall",disabled:c,"aria-label":"Add nested group",leftGlyph:r().createElement(s.Int,{glyph:"Plus"}),"data-testid":oc(t.id),onClick:()=>{const e=[...t.nestedGroups,lc()];i({...t,nestedGroups:e})}},"Nested Group"))},"Compass does not support more than three nested match conditions."),d&&r().createElement(s.K0,{"aria-label":"Remove group",onClick:o,"data-testid":sc(t.id)},r().createElement(s.Int,{glyph:"Trash"}))),r().createElement("div",{style:u},r().createElement(s.qQS,{items:t.conditions,itemKey:e=>`group-${t.id}-condition-${e.id}`,renderItem:(n,a)=>r().createElement(ac,{fields:e,condition:n,onConditionChange:e=>((e,n)=>{const a=[...t.conditions];a[e]=n,i({...t,conditions:a})})(a,e)}),disableAddButton:()=>!1,onAddItem:e=>{const n=[...t.conditions];n.splice(e+1,0,Ul()),i({...t,conditions:n})},addButtonTestId:"add-condition-button",disableRemoveButton:()=>1===t.conditions.length,onRemoveItem:e=>{if(1===t.conditions.length)return;const n=[...t.conditions];n.splice(e,1),i({...t,conditions:n})},removeButtonTestId:"remove-condition-button"})),r().createElement(s.qQS,{className:uc,items:t.nestedGroups,itemKey:e=>`group-${t.id}-nested-group-${e.id}`,renderItem:(o,s)=>r().createElement(bc,{fields:e,group:o,nestingLevel:n+1,nestingDepth:a,onGroupChange:e=>((e,n)=>{const a=[...t.nestedGroups];a[e]=n,i({...t,nestedGroups:a})})(s,e),onGroupRemoved:()=>(e=>{const n=[...t.nestedGroups];n.splice(e,1),i({...t,nestedGroups:n})})(s)}),disableAddButton:()=>!0,onAddItem:()=>{},disableRemoveButton:()=>!0,onRemoveItem:()=>{}}))},vc=bc,xc=({nestedGroups:e})=>0===e.length?0:1+Math.max(...e.map(xc));function Ec(e){return!(!e.field||!e.bsonType)}function Cc({conditions:e,nestedGroups:t}){return e.some(Ec)||t.some(Cc)}function wc(e){const t=[];for(const n of e)t.push(...Object.keys(n));return new Set(t).size===t.length}function Ic(e){const t=ll.Ay.cast(e.value,e.bsonType);return"$eq"===e.operator?{[e.field]:t}:{[e.field]:{[e.operator]:t}}}function Sc({logicalOperator:e,conditions:t,nestedGroups:n}){const a=t.filter(Ec).map(Ic),r=n.filter(Cc).map(Sc);return{[e]:[...a,...r]}}const Ac=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[600],width:"100%",maxWidth:"1000px"}),kc={$first:{label:"First",needsSortFields:!1,nOperator:"$firstN",order:1},$last:{label:"Last",needsSortFields:!1,nOperator:"$lastN",order:2},$top:{label:"Top",needsSortFields:!0,nOperator:"$topN",order:3},$bottom:{label:"Bottom",needsSortFields:!0,nOperator:"$bottomN",order:4}},Dc=Object.values(kc).map((e=>e.nOperator)),Nc=Object.keys(kc);function Mc(e){return Nc.includes(e.value)}const Tc=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[200]}),Pc=(0,s.AHW)({display:"flex",flexDirection:"row",alignItems:"center",gap:s.YKD[200]}),Lc=(0,s.AHW)({minWidth:"120px",width:"120px",textAlign:"right"}),Oc=(0,s.AHW)({width:"150px"}),Rc=(0,s.AHW)({width:"100px"}),Hc=(0,s.AHW)({width:"300px"}),Fc=(0,o.Ng)((({serverVersion:e})=>({serverVersion:e})))((({fields:e,serverVersion:t,onChange:n})=>{const[i,o]=(0,a.useState)({groupFields:[],projectFields:[],accumulator:null,numberOfRecords:1,sortFields:[],sortDirection:"Asc"}),l=(e,t)=>{const a={...i,[e]:t};var r;o(a),n(JSON.stringify((e=>{const{accumulator:t,groupFields:n,projectFields:a,numberOfRecords:r,sortFields:i,sortDirection:o}=e;if(!t)return{};const s=kc[t],l=Js(i.map((e=>({field:e,direction:o})))),c=s.needsSortFields?"output":"input";return r>1?{_id:qs(e.groupFields),data:{[s.nOperator]:{n:r,[c]:qs(a),...s.needsSortFields?{sortBy:l}:{}}}}:s.needsSortFields?{_id:qs(e.groupFields),data:{[t]:{[c]:qs(a),sortBy:l}}}:{_id:qs(n),data:{[t]:qs(a)}}})(a)),(r=a).accumulator?r.numberOfRecords<1?new Error("Number of records is not valid."):0===r.projectFields.length?new Error("Accumulator fields are required."):r.accumulator&&kc[r.accumulator].needsSortFields&&0===r.sortFields.length?new Error("Sort fields are required."):null:new Error("Accumulator is required."))},c=(0,a.useMemo)((()=>(0,_.zM)({serverVersion:t,meta:["accumulator","accumulator:*"]}).filter(Mc).sort(((e,t)=>kc[e.value].order-kc[t.value].order))),[t]),d=(0,a.useMemo)((()=>(0,_.zM)({serverVersion:t,meta:["accumulator"]}).some((e=>{return t=e.value,Dc.includes(t);var t}))),[t]),u=i.accumulator?kc[i.accumulator]:null;return r().createElement("div",{className:Tc},r().createElement("div",{className:Pc},r().createElement(s.nBu,{className:Lc},"Return the"),r().createElement(s.l6P,{className:Oc,allowDeselect:!1,"aria-label":"Select accumulator",value:i.accumulator??"",onChange:e=>{var t;l("accumulator",(t=e,Nc.includes(t)?e:null))}},c.map((e=>r().createElement(s.c$x,{value:e.value,key:e.value},kc[e.value].label)))),d&&r().createElement(r().Fragment,null,r().createElement(s.ksK,{type:"number","aria-label":"Number of records","data-testid":"number-of-records-input",placeholder:"Number of records",className:Rc,value:i.numberOfRecords.toString(),min:1,onChange:e=>l("numberOfRecords",Number(e.target.value))}),r().createElement(s.nBu,null,"of")),r().createElement(tl,{className:Hc,"aria-label":"Select project field names",placeholder:"Select project field names",multiselect:!0,value:i.projectFields,onChange:e=>l("projectFields",e),fields:e})),r().createElement("div",{className:Pc},r().createElement(s.nBu,{className:Lc},"from a group of"),r().createElement(tl,{className:Hc,"aria-label":"Select group field names",placeholder:"Select group field names",multiselect:!0,value:i.groupFields,onChange:e=>l("groupFields",e),fields:e})),u?.needsSortFields&&r().createElement("div",{className:Pc},r().createElement(s.nBu,{className:Lc},"documents from a list sorted by"),r().createElement(tl,{className:Hc,"aria-label":"Select sort field names",placeholder:"Select sort field names",multiselect:!0,value:i.sortFields,onChange:e=>l("sortFields",e),fields:e}),r().createElement(s.nBu,null,"in"),r().createElement(s.l6P,{className:Oc,allowDeselect:!1,"aria-label":"Select direction",value:i.sortDirection,onChange:e=>l("sortDirection",e)},Zs.map(((e,t)=>r().createElement(s.c$x,{key:t,value:e.value},e.label)))),r().createElement(s.nBu,null,"order")))})),Wc=(0,s.AHW)({gap:s.YKD[200],width:"100%",maxWidth:"800px",display:"grid",gridTemplateColumns:"150px 1fr 1fr",alignItems:"center"}),jc=(0,s.AHW)({display:"contents"}),Bc=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[200]}),zc=(0,s.AHW)({textAlign:"right"}),_c=(0,s.AHW)({flex:1}),$c=[{id:"match",title:"Find all the documents that match one or more conditions",stageOperator:"$match",wizardComponent:({fields:e,onChange:t})=>{const[n,i]=(0,a.useState)(lc());return r().createElement("div",{className:Ac},r().createElement(vc,{key:n.id,fields:e,group:n,nestingLevel:0,nestingDepth:xc(n),onGroupChange:e=>{i(e);try{const n=function(e){return function(e){const t={},n=Object.entries(e);for(const[e,a]of n)if("$and"===e&&wc(a))for(const e of a)Object.assign(t,e);else t[e]=a;return t}(Sc(e))}(e);t((0,ka.AO)(n)||"",null)}catch(e){t("{}",e)}}}))}},{id:"basic-group",title:"Group my documents based on their field values",stageOperator:"$group",wizardComponent:({fields:e,onChange:t})=>{const[n,i]=(0,a.useState)([]);return r().createElement("div",{className:Dl},r().createElement(s.nBu,null,"Group documents based on"),r().createElement(tl,{className:Nl,multiselect:!0,value:n,onChange:e=>{i(e),t(JSON.stringify({_id:qs(e)}),0===e.length?new Error("Group fields cannot be empty"):null)},fields:e}))}},{id:"group-with-statistics",title:"Compute values within the groups I create",stageOperator:"$group",wizardComponent:$l},{id:"group-with-subset",title:"Return a subset of values based on their order or rank",stageOperator:"$group",wizardComponent:Fc},{id:"project",title:"Include or exclude a subset of fields from my documents",stageOperator:"$project",wizardComponent:({fields:e,onChange:t})=>{const[n,i]=(0,a.useState)({projectionType:"include",projectionFields:[]}),o=(e,a)=>{const r={...n,[e]:a};i(r);const o=(({projectionFields:e,projectionType:t})=>e.reduce(((e,n)=>null===n?e:{...e,[n]:"include"===t?1:0}),{}))(r);t(JSON.stringify(o),0===Object.keys(o).length?new Error("No field selected"):null)};return r().createElement("div",{className:Il},r().createElement("div",{className:Sl,"data-testid":"project-form"},r().createElement(s.l6P,{"data-testid":"project-form-projection",className:Al,allowDeselect:!1,"aria-label":"Select projection type",value:n.projectionType,onChange:e=>o("projectionType",e)},r().createElement(s.c$x,{value:"include"},"Include"),r().createElement(s.c$x,{value:"exclude"},"Exclude")),r().createElement(tl,{"data-testid":"project-form-field",className:kl,multiselect:!0,value:n.projectionFields,onChange:e=>o("projectionFields",[...e]),fields:e,isRelatedFieldDisabled:!0})))}},{id:"sort",title:"Sort documents based on a single or set of fields",stageOperator:"$sort",wizardComponent:({fields:e,onChange:t})=>{const[n,i]=(0,a.useState)([{id:Xs(),field:"",direction:"Asc"}]),o=e=>{const n=(e=>Js(e))(e);t(JSON.stringify(n),0===Object.keys(n).length?new Error("No field selected"):null),i(e)};return r().createElement("div",{className:nl},r().createElement(s.qQS,{items:n,onAddItem:e=>(e=>{const t=[...n];t.splice(e+1,0,{id:Xs(),field:"",direction:"Asc"}),o(t)})(e),onRemoveItem:e=>(e=>{const t=[...n];t.splice(e,1),o(t)})(e),itemTestId:e=>`sort-form-${e}`,itemKey:e=>String(e.id),renderItem:(t,a)=>r().createElement(sl,{comboboxClassName:ol,index:a,sortField:t.field,sortDirection:t.direction,fields:e,onChange:(e,t)=>((e,t,a)=>{const r=[...n];r[e][t]=a,o(r)})(a,e,t)})}))}},{id:"lookup",title:"Join documents from different collections to compare their field values",stageOperator:"$lookup",wizardComponent:wl},{id:"text-search",title:"Search for a text field across all documents in a collection",stageOperator:"$search",wizardComponent:(0,o.Ng)((e=>({indexes:e.searchIndexes.indexes,indexesStatus:e.searchIndexes.status})),{onFetchIndexes:()=>async e=>{await e($n(Hn))}})((({fields:e,onChange:t,indexes:n,indexesStatus:i,onFetchIndexes:o})=>{const[l,c]=(0,a.useState)({type:"text",path:"fields",maxEdits:2,text:"",indexName:""});(0,a.useEffect)((()=>{o()}),[o]);const d=(e,n)=>{(e=>{const n=(e=>({index:e.indexName||"default",text:{query:e.text,path:"wildcard"===e.path?{wildcard:"*"}:e.fields,..."fuzzy"===e.type?{fuzzy:{maxEdits:e.maxEdits}}:{}}}))(e);t(JSON.stringify(n),(e=>{if("fuzzy"===e.type){if(void 0===e.maxEdits)return new Error("No max edits provided.");if(e.maxEdits<1||e.maxEdits>2)return new Error("Max edits must be either 1 or 2.")}return"fields"!==e.path||e.fields?.length?e.text?null:new Error("No search text provided"):new Error("No fields provided.")})(e)),c(e)})({...l,[e]:n})};return r().createElement("div",{className:Wc},r().createElement("div",{className:jc},r().createElement(s.nBu,{className:zc},"Perform a"),r().createElement(s.l6P,{className:_c,allowDeselect:!1,"aria-label":"Select search type",value:l.type,onChange:e=>d("type",e)},r().createElement(s.c$x,{value:"text"},"text search"),r().createElement(s.c$x,{value:"fuzzy"},"fuzzy search")),r().createElement("div",{className:Bc},r().createElement(s.nBu,null,"with ",r().createElement("span",{id:"maxEdits-input-label"},"maxEdits")),r().createElement(s.ksK,{type:"number","aria-labelledby":"maxEdits-input-label","data-testid":"maxEdits-input",placeholder:"e.g 2",className:_c,value:l.maxEdits?.toString(),min:1,max:2,disabled:"fuzzy"!==l.type,onChange:e=>d("maxEdits",Number(e.target.value))}))),r().createElement("div",{className:jc},r().createElement(s.nBu,{className:zc},"for all documents where"),r().createElement(s.l6P,{className:_c,allowDeselect:!1,"aria-label":"Select search path",value:l.path,onChange:e=>d("path",e)},r().createElement(s.c$x,{value:"fields"},"field names"),r().createElement(s.c$x,{value:"wildcard"},"any fields")),r().createElement(tl,{className:_c,value:l.fields,onChange:e=>d("fields",e),fields:e,multiselect:!0,disabled:"wildcard"===l.path})),r().createElement("div",{className:jc},r().createElement(s.nBu,{className:zc},"contains"),r().createElement(s.ksK,{placeholder:"text","aria-labelledby":"","data-testid":"text-search-contains-input","aria-label":"text",value:l.text,className:_c,onChange:e=>d("text",e.target.value)}),r().createElement("div",{className:Bc},r().createElement(s.nBu,null,"using"),r().createElement(s.WqN,{className:_c,"aria-label":"Select or type a search index",placeholder:"Select or type a search index",size:"default",clearable:!1,onChange:e=>d("indexName",e??""),searchState:"LOADING"===i?"loading":"ERROR"===i?"error":"unset",searchLoadingMessage:"Fetching search indexes ...",searchErrorMessage:"Failed to fetch the search indexes. Type the index name manually.",options:n.map((e=>({value:e.name}))),renderOption:(e,t,n)=>r().createElement(s.jOs,{key:t,value:e.value,displayName:n?`Index: "${e.value}"`:e.value})}))))})),isAtlasOnly:!0}],Yc=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[400]}),Kc=(0,s.AHW)({display:"flex",justifyContent:"space-between",gap:s.YKD[200],padding:s.YKD[400],cursor:"grab"}),Gc=(0,s.AHW)({display:"flex",gap:s.YKD[200]}),Vc=(0,s.AHW)({padding:s.YKD[400],display:"flex",flexDirection:"column",gap:s.YKD[400]}),Uc=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[400]}),qc=(0,s.AHW)({display:"flex",gap:s.YKD[200],marginLeft:"auto"}),Zc=(0,s.AHW)({width:"300px",maxWidth:"auto"}),Jc=(0,o.Ng)(((e,t)=>{const{namespace:n,autoPreview:a,pipelineBuilder:{stageEditor:{stages:r}}}=e,i=r[t.index],o=r.slice(0,t.index).reverse().find((e=>"stage"===e.type&&!e.disabled));return{id:i.id,namespace:n,syntaxError:i.syntaxError,useCaseId:i.useCaseId,value:i.value,previousStageFields:a&&o?.previewDocs&&o?.previewDocs.length>0?ml(o.previewDocs.map((e=>e.generateObject()))):null}}),((e,t)=>({onChange:n=>e(((e,t)=>(n,a)=>{const{pipelineBuilder:{stageEditor:{stages:r}}}=a();if("wizard"===r[e].type)try{U(t),n({type:Ct,at:e,value:t,syntaxError:null})}catch(a){n({type:Ct,at:e,value:t,syntaxError:a})}})(t.index,n)),onCancel:()=>{return e((n=t.index,{type:Et,at:n}));var n},onApply:()=>{return e((n=t.index,(e,t,{pipelineBuilder:a,track:r,connectionInfoRef:i})=>{const{pipelineBuilder:{stageEditor:{stages:o}}}=t(),s=o[n];if("wizard"!==s.type)return;if(s.syntaxError||!s.value){const t=s.syntaxError||new SyntaxError("Cannot convert empty wizard to stage");return void e({type:Ct,at:n,value:s.value,syntaxError:t})}const l=It(o,n),c=a.addStage(l);c.changeOperator(s.stageOperator),c.changeValue((e=>{if(!e)return"";let t=e;try{t=JSON.stringify(JSON.parse(e),null,2)}catch{}try{return(0,K.G8)(t)}catch{return t}})(s.value));const d=i.current;r("Aggregation Edited",{num_stages:St(o).length+1,stage_action:"stage_added",stage_name:c.operator,stage_index:l+1,editor_view_type:"stage"},d),r("Aggregation Use Case Saved",{stage_name:c.operator},d),e({type:wt,at:n,stage:Bt(c,l)}),e(Tt(n)),e(it())}));var n}})))((({index:e,namespace:t,useCaseId:n,value:i,syntaxError:o,previousStageFields:l,onChange:c,onCancel:d,onApply:u,...p})=>{const{returnFocus:m,focusContainerRef:g}=function(){const e=(0,a.useRef)(null),t=(0,a.useRef)(document.activeElement);(0,a.useEffect)((()=>{if(e.current){const t='input:not([aria-hidden="true"]),\n select:not([aria-hidden="true"]),\n textarea:not([aria-hidden="true"]),\n button:not([aria-hidden="true"])',n=e.current.querySelector(t);n&&"focus"in n&&"function"==typeof n.focus&&n.focus()}function n(n){e.current&&!e.current.contains(n.target)&&(t.current=null)}return document.addEventListener("focus",n,!0),()=>{document.removeEventListener("focus",n,!0)}}),[]);const n=(0,a.useCallback)((()=>{t.current&&"focus"in t&&"function"==typeof t.focus&&t.current.focus()}),[]);return{focusContainerRef:e,returnFocus:n}}(),h=(0,po.EK)(t),f=(0,a.useMemo)((()=>Object.values(h).map((e=>{return{name:e.name,type:(t=e.type,"Document"===(t=Array.isArray(t)?t[0]:t)?"Object":t)};var t}))),[h]),y=(0,a.useCallback)((()=>{d?.(),m()}),[d,m]),[b,v]=(0,a.useState)(null),x=(0,a.useMemo)((()=>$c.find((e=>e.id===n))),[n]),E=(0,a.useCallback)(((e,t)=>{if(!t)return v(null),c(e);v(t)}),[v,c]);if(!x)return null;const C=o||b,w=!!C||!i,{setNodeRef:I,style:S,listeners:A}=p;return r().createElement("div",{ref:I,style:S},r().createElement(s.yY_,{"data-testid":"wizard-card","data-wizard-index":e,className:Yc},r().createElement("div",A,r().createElement("div",{className:Kc},r().createElement("div",{className:Gc},r().createElement(s.nBu,{weight:"medium"},x.title),r().createElement(s.N_E,{target:"_blank",href:le(x.stageOperator)},x.stageOperator)),x.isAtlasOnly&&r().createElement(s.Exy,null,"Atlas only"))),r().createElement("div",{ref:g},r().createElement("div",{className:Vc},r().createElement("div",{"data-testid":"wizard-form"},r().createElement(x.wizardComponent,{fields:l??f,onChange:E})),r().createElement("div",{className:Uc},r().createElement("div",{className:Zc},i&&C&&r().createElement(s.rpn,{warnings:[C?.message]})),r().createElement("div",{className:qc},r().createElement(s.$nd,{"data-testid":"wizard-cancel-action",onClick:y},"Cancel"),r().createElement(s.$nd,{"data-testid":"wizard-apply-action",onClick:u,variant:"primary",disabled:w},"Apply")))))))})),Qc=(0,s.AHW)({textAlign:"center"}),Xc=(0,s.AHW)({marginTop:s.YKD[200],marginBottom:s.YKD[800],position:"relative"}),ed=({onAddStage:e,variant:t})=>r().createElement("div",{className:Qc},"icon"===t?r().createElement(s.K0,{"aria-label":"Add stage",title:"Add stage","data-testid":"add-stage-icon-button",onClick:()=>e()},r().createElement(s.Int,{glyph:"PlusWithCircle"})):r().createElement(r().Fragment,null,r().createElement(s.$nd,{"data-testid":"add-stage",onClick:()=>e(),variant:"primary",leftGlyph:r().createElement(s.Int,{glyph:"Plus"})},"Add stage"),r().createElement("div",{className:Xc},r().createElement(s.N_E,{href:p},"Learn more about aggregation pipeline stages")))),td=e=>e.startsWith("droppable-"),nd=e=>`droppable-${e}`,ad=(0,s.AHW)({display:"flex",alignItems:"center",justifyContent:"center",minHeight:s.YKD[800],position:"relative"}),rd=(0,s.AHW)({position:"absolute",width:"100%",top:"50%",height:s.YKD[100]/4,background:s.MFm.green.dark1,borderRadius:s.YKD[200]}),id=({index:e,children:t})=>{const{setNodeRef:n,isOver:a}=(0,zs.zM)({id:nd(e)});return r().createElement("div",{ref:n,className:ad},a?r().createElement("div",{"data-testid":`use-case-drop-marker-${e}`,className:rd}):t)},od=(0,s.AHW)({display:"flex",flexDirection:"column"}),sd=({id:e,index:t,type:n})=>{const{setNodeRef:i,transform:o,transition:s,listeners:l,isDragging:c}=(0,yi.gl)({id:e+1}),d=(0,a.useRef)(null);(0,a.useEffect)((()=>{d.current&&d.current.scrollIntoView({behavior:"smooth",block:"center"})}),[]);const u={setNodeRef:i,style:{transform:bi.Ks.Transform.toString(o),transition:s,...c?{zIndex:1}:{}},listeners:l};return r().createElement("div",{ref:d,className:od},"stage"===n?r().createElement(Bs,(0,fi.A)({index:t},u)):r().createElement(Jc,(0,fi.A)({index:t},u)))},ld=({stagesIdAndType:e,onStageAddAfterEnd:t})=>{const n=e.map((({id:e})=>e+1));return r().createElement(yi.gB,{items:n,strategy:yi._G},e.map((({id:e,type:n},a)=>r().createElement(r().Fragment,{key:`stage-${e}`},r().createElement(id,{index:a-1},r().createElement(ed,{variant:"icon",onAddStage:()=>t(a-1)})),r().createElement(sd,{id:e,index:a,type:n})))))},cd=(0,s.AHW)({paddingTop:s.YKD[1600],paddingBottom:s.YKD[400],textAlign:"center"}),dd=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[200]}),ud=()=>r().createElement("div",{className:cd},r().createElement(s.N_E,{target:"blank",href:"https://feedback.mongodb.com/",hideExternalIcon:!0},r().createElement("div",{className:dd},r().createElement(s.Int,{glyph:"Megaphone"}),r().createElement("span",null,"Suggest a new use case")))),pd=(0,s.AHW)({height:"100%",paddingTop:s.YKD[100],borderBottomRightRadius:0,borderBottomLeftRadius:0,borderBottom:"none",backgroundColor:s.MFm.gray.light3,display:"flex",flexDirection:"column",gap:s.YKD[200]}),md=(0,s.AHW)({backgroundColor:s.MFm.gray.dark3}),gd=(0,s.AHW)({display:"flex",alignItems:"center"}),hd=(0,s.AHW)({marginLeft:"auto"}),fd=(0,s.AHW)({color:s.MFm.green.light2}),yd=(0,s.AHW)({color:s.MFm.green.dark2}),bd=(0,s.AHW)({paddingLeft:s.YKD[200],paddingRight:s.YKD[200]}),vd=(0,s.AHW)({display:"flex",flexDirection:"column",gap:s.YKD[200],overflow:"auto",paddingTop:s.YKD[100],paddingLeft:s.YKD[200],paddingRight:s.YKD[200],paddingBottom:s.YKD[400]}),xd=(0,o.Ng)(null,{onCloseSidePanel:fr,onSelectUseCase:jt})((({onCloseSidePanel:e,onSelectUseCase:t})=>{const n=(0,O.Jr)(),i=(0,Wr.jj)(),[o,l]=(0,a.useState)(""),c=(0,s.D27)(),d=(0,a.useMemo)((()=>$c.filter((({title:e,stageOperator:t})=>e.includes(o)||t.includes(o))).map((({id:e,title:t,stageOperator:n})=>({id:e,title:t,stageOperator:n})))),[o]),u=(0,a.useCallback)((e=>{l(e.target.value)}),[l]),p=(0,a.useCallback)((e=>{const a=$c.find((t=>t.id===e));a&&(t(e,a.stageOperator),n("Aggregation Use Case Added",{drag_and_drop:!1,stage_name:a.stageOperator},i.current))}),[t,n,i]);return r().createElement(s.yY_,{"data-testid":"aggregation-side-panel",className:(0,s.cx)(pd,c&&md)},r().createElement("div",{className:bd},r().createElement("div",{className:gd},r().createElement(s.nBu,{weight:"medium",className:c?fd:yd},"Stage Wizard"),r().createElement(s.K0,{className:hd,title:"Hide Stage Wizard","aria-label":"Hide Stage Wizard",onClick:()=>e()},r().createElement(s.Int,{glyph:"X"}))),r().createElement(s.DOo,{value:o,onChange:u,placeholder:"Search for a Stage","aria-label":"Search for a Stage"})),r().createElement("div",{className:vd,"data-testid":"side-panel-content"},d.map(((e,t)=>r().createElement(Vs,(0,fi.A)({},e,{key:e.id,onSelect:()=>p(e.id)})))),r().createElement(ud,null)))})),Ed="aggregations/input-documents/CollapseToggled",Cd="aggregations/input-documents/DocumentsFetchStarted",wd="aggregations/input-documents/DocumentsFetchFinished",Id={documents:[],error:null,isExpanded:!0,isLoading:!1},Sd=(e,t)=>({type:wd,documents:e,error:t}),Ad=()=>async(e,t,{preferences:n})=>{const{dataService:{dataService:a},namespace:r,maxTimeMS:i,settings:{sampleSize:o}}=t();if(!a)return;const s={maxTimeMS:(0,g.Tv)(n,i??l)},c=[{$limit:o}];e({type:Cd});try{const t=(await a.aggregate(r,c,s)).map((e=>new W.Ay(e)));e(Sd(t,null))}catch(t){e(Sd([],t))}},kd=(0,s.AHW)({display:"flex",gap:s.YKD[100],alignItems:"center",width:"100%",padding:`${s.YKD[100]}px ${s.YKD[200]}px`}),Dd=(0,s.AHW)({flex:1}),Nd=(0,s.AHW)({position:"relative",padding:`${s.YKD[200]}px ${s.YKD[200]+s.YKD[100]}px`,borderTopWidth:"1px",borderTopStyle:"solid"}),Md=(0,s.AHW)({borderTopColor:s.MFm.gray.light2}),Td=(0,s.AHW)({borderTopColor:s.MFm.gray.dark2}),Pd=(0,s.AHW)({marginTop:s.YKD[200],paddingBottom:s.YKD[200],display:"flex",overflowX:"scroll",gap:s.YKD[200]}),Ld=(0,s.AHW)({flexShrink:0,width:"384px",height:"170px",overflow:"scroll"}),Od=(0,o.Ng)((({inputDocuments:e,collectionStats:t})=>({documents:e.documents,isExpanded:e.isExpanded,isLoading:e.isLoading,count:t?.document_count})),{toggleInputDocumentsCollapsed:()=>({type:Ed}),refreshInputDocuments:Ad})((function({documents:e,isExpanded:t,isLoading:n,count:a,toggleInputDocumentsCollapsed:i,refreshInputDocuments:o}){const l=(0,s.D27)(),c=t?"Collapse":"Expand";return r().createElement(s.yY_,null,r().createElement("div",{className:kd},r().createElement(s.K0,{onClick:()=>{i(!t)},title:c,"aria-label":c},r().createElement(s.Int,{glyph:t?"ChevronDown":"ChevronRight",size:"small"})),r().createElement(s.nBu,{className:Dd},r().createElement("b",null,a??"N/A"," Document",1===a?"":"s")," ","in the collection"),r().createElement(s.K0,{onClick:o,"aria-label":"Refresh",title:"Refresh"},r().createElement(s.Int,{glyph:"Refresh",size:"small"}))),t&&r().createElement("div",{className:(0,s.cx)(Nd,l?Td:Md)},r().createElement(s.nBu,null,"Preview of documents"),n?r().createElement(Qo,{text:"Sampling Documents..."}):null,r().createElement("div",{className:Pd},e.map(((e,t)=>r().createElement(s.yY_,{key:t,className:Ld},r().createElement(Vo.yo,{doc:e,editable:!1})))))))})),Rd=e=>{const{active:t}=e;return"use-case"===t.data.current?.type},Hd=({children:e,stagesIdAndType:t,onStageMoveEnd:n,onUseCaseDropped:i})=>{const o=(0,O.Jr)(),[s,l]=(0,a.useState)(null),c=(0,zs.FR)((0,zs.MS)(zs.cA,{activationConstraint:{distance:10}}),(0,zs.MS)(zs.IG,{activationConstraint:{delay:250,tolerance:5}})),d=(0,Wr.jj)(),u=(0,a.useCallback)((e=>{const{over:t}=e,n=(e=>td(e)?+e.replace(/^droppable-/,""):null)(String(t?.id));s&&null!==n&&(o("Aggregation Use Case Added",{drag_and_drop:!0,stage_name:s.stageOperator},d.current),i(s.id,s.stageOperator,n)),l(null)}),[s,i,o,d]),p=(0,a.useCallback)((({oldIndex:e,newIndex:a})=>{const r=t.findIndex((({id:t})=>t+1===e)),i=t.findIndex((({id:e})=>e+1===a));n(r,i)}),[n,t]);return r().createElement(zs.Mp,{sensors:c,autoScroll:!1,onDragEnd:e=>{const{active:t,over:n}=e;(e=>{const{active:t,over:n}=e;return"use-case"===t.data.current?.type&&td(String(n?.id))})(e)?u(e):!Rd(e)&&n&&n.data.current?.sortable&&t.id!==n.id&&p({oldIndex:+t.id,newIndex:+n.id})},onDragStart:e=>{Rd(e)&&l(e.active.data.current?.draggedUseCase)}},e,s?r().createElement(zs.Hd,null,r().createElement(Gs,{id:s.id,title:s.title,stageOperator:s.stageOperator,isDropping:!0})):null)},Fd=(0,s.AHW)({position:"relative",height:"100%",paddingBottom:s.YKD[400],width:"100%",overflow:"auto"}),Wd=(0,s.AHW)({display:"flex",flexDirection:"column",width:"100%",height:"100%",flexGrow:1});function jd(e){const t=e.filter((e=>null!==e.stageOperator&&null!==e.value&&!e.disabled)),n=`[${t.map((e=>`{ ${e.stageOperator}: ${e.value} }`)).join(",\n")}\n]`;return t.some((e=>e.syntaxError))?n:(0,K.G8)(n)}const Bd={onStageMoveEnd:(e,t)=>(n,a,{pipelineBuilder:r,track:i,connectionInfoRef:o})=>{if(e===t)return;const{pipelineBuilder:{stageEditor:{stages:s}}}=a(),l=s[e],c=s[t],d="stage"===c.type?c.idxInPipeline:It(s,t,{includeIndex:e<t});"wizard"===l.type||l.idxInPipeline===d?n({type:vt,from:e,to:t}):(i("Aggregation Edited",{num_stages:St(s).length,stage_action:"stage_reordered",stage_name:l.stageOperator,stage_index:l.idxInPipeline+1,editor_view_type:nn(a())},o.current),r.moveStage(l.idxInPipeline,d),n({type:vt,from:e,to:t}),n(Tt(Math.min(e,t))),n(it()))},onStageAddAfterEnd:Ft,onUseCaseDropped:jt},zd=(0,o.Ng)((e=>({stagesIdAndType:e.pipelineBuilder.stageEditor.stagesIdAndType,pipelineText:jd(e.pipelineBuilder.stageEditor.stages),isSidePanelOpen:e.sidePanel.isPanelOpen})),Bd)((({stagesIdAndType:e,pipelineText:t,isSidePanelOpen:n,onStageMoveEnd:a,onStageAddAfterEnd:i,onUseCaseDropped:o})=>((0,ea.ZX)("currentPipeline",t),r().createElement(Hd,{stagesIdAndType:e,onStageMoveEnd:a,onUseCaseDropped:o},r().createElement("div",{"data-testid":"pipeline-builder-ui-workspace",className:Fd},r().createElement("div",{className:Wd},r().createElement(Od,null),r().createElement(ld,{stagesIdAndType:e,onStageAddAfterEnd:i}),r().createElement(id,{index:e.length-1}),r().createElement(ed,{variant:"button",onAddStage:i}))),n&&r().createElement(hi.c,{defaultSize:{width:"25%",height:"auto"},minWidth:"15%",maxWidth:"50%",enable:{left:!0},handleComponent:{left:r().createElement(Ci,null)},handleStyles:{left:{left:"0px",paddingTop:s.YKD[200],height:`calc(100% - ${s.YKD[200]}px)`}}},r().createElement(xd,null)))))),_d=(0,s.AHW)({position:"relative",display:"flex",flexDirection:"column",height:"100%",backgroundColor:s.MFm.gray.light3,paddingTop:s.YKD[400],paddingBottom:s.YKD[200],gap:s.YKD[200],marginRight:s.YKD[100],borderRadius:s.YKD[200]}),$d=(0,s.AHW)({backgroundColor:s.MFm.gray.dark4}),Yd=(0,s.AHW)({flex:"1 1 100%",overflow:"hidden"}),Kd=(0,s.AHW)({"& .cm-editor":{background:"transparent !important"}}),Gd=(0,s.AHW)({flex:"none",marginTop:"auto",marginLeft:s.YKD[400],marginRight:s.YKD[400]}),Vd={onChangePipelineText:e=>(t,n,{pipelineBuilder:a})=>{const{pipelineBuilder:{textEditor:{pipeline:{pipelineText:r}}}}=n();r!==e&&(a.changeSource(e),t({type:Gt,pipelineText:e,pipeline:a.pipeline,syntaxErrors:a.syntaxError}),t(qt()),t(it()))},onViewSearchIndexesClick:Vn,onCreateSearchIndexClick:qn,onEditSearchIndexClick:Un},Ud=(0,o.Ng)((({namespace:e,isTimeSeries:t,sourceName:n,pipelineBuilder:{textEditor:{pipeline:{pipeline:a,pipelineText:r,serverError:i,syntaxErrors:o},outputStage:{serverError:s}}},serverVersion:l,searchIndexes:{indexes:c,status:d}})=>{const{searchIndexName:u,searchStageOperator:p}=ie(r),m=!!u&&!!p&&["READY","POLLING"].includes(d)&&c.every((e=>e.name!==u)),g=a.reduce(((e,t)=>e??So(J(t))),null);return{namespace:e,isTimeSeries:t,sourceName:n,num_stages:a.length,pipelineText:r,serverError:i??s,syntaxErrors:o,serverVersion:l,searchIndexName:u,searchStageOperator:p,showSearchIndexDoesNotExistBanner:m,searchExtensionType:g}}),Vd)((({namespace:e,isTimeSeries:t,sourceName:n,num_stages:i,pipelineText:o,serverError:l,syntaxErrors:c,serverVersion:d,searchIndexName:u,searchStageOperator:p,showSearchIndexDoesNotExistBanner:m,searchExtensionType:h,onChangePipelineText:f,onViewSearchIndexesClick:y,onCreateSearchIndexClick:b,onEditSearchIndexClick:v})=>{const x=t?_.MD:n?_.gR:_.nP,E=(0,po.jv)(e),C=(0,O.Jr)(),w=(0,Wr.jj)(),I=(0,a.useRef)(o),S=(0,s.HIF)(o);(0,ea.ZX)("currentPipeline",o);const{utmSource:A,utmMedium:k}=(0,s.GUC)(),D=(0,a.useMemo)((()=>(0,K.hK)({serverVersion:d,fields:E.filter((e=>!!e.name)),stage:{namespace:x},utmSource:A,utmMedium:k})),[d,E,x,A,k]),N=(0,a.useCallback)((()=>{S.current&&S.current!==I.current&&(C("Aggregation Edited",{num_stages:i,editor_view_type:"text"},w.current),I.current=S.current)}),[S,C,i,w]),M=(0,a.useMemo)((()=>c.map((e=>e.loc&&e.loc.index?{message:e.message,severity:"error",from:e.loc.index,to:e.loc.index}:null)).filter((e=>!!e))),[c]),T=(0,s.D27)(),{enableSearchActivationProgramP1:P}=(0,O.p5)(),L=(0,g.Fg)("enableRerank")&&o.includes("$rerank")&&!ho(d),R=l||c.length>0||P&&m;return r().createElement("div",{className:(0,s.cx)(_d,T&&$d),"data-testid":"pipeline-as-text-editor"},r().createElement("div",{className:Yd},r().createElement(K.Jn,{text:o,onChangeText:f,annotations:M,id:"pipeline-text-editor","data-testid":"pipeline-text-editor",completer:D,minLines:16,onBlur:N,className:Kd})),L&&r().createElement(Ho,{"data-testid":"pipeline-editor-rerank-version-warning"}),R&&r().createElement("div",{className:Gd,"data-testid":"pipeline-as-text-error-container"},c.length>0?r().createElement(s.rpn,{warnings:c.map((e=>e.message))}):l?r().createElement(To,{message:l.message,searchIndexName:u,dataTestId:"pipeline-editor-error-message",searchExtensionType:h,onEditSearchIndexClick:v}):P&&p&&m?r().createElement(Lo,{searchIndexName:u,searchStageOperator:p,onViewIndexesClick:y,onCreateSearchIndexClick:b}):null))})),qd="compass-aggregations/pipeline-builder/text-editor-output-stage/FetchStarted",Zd="compass-aggregations/pipeline-builder/text-editor-output-stage/FetchSucceded",Jd="compass-aggregations/pipeline-builder/text-editor-output-stage/FetchFailed",Qd={isLoading:!1,isComplete:!1,serverError:null},Xd=(0,s.AHW)({alignItems:"center",display:"flex"}),eu=(0,s.AHW)({display:"flex",gap:s.YKD[400],alignItems:"center",justifyContent:"space-between"}),tu={className:(0,s.AHW)({flexShrink:0}),size:s.MpK.XSmall,variant:s.AkO.Default},nu=({text:e,actionButton:t,"data-testid":n})=>r().createElement(s.lZ$,{"data-testid":n,variant:s.uAY.Info,className:Xd},r().createElement("div",{className:eu},r().createElement(s.nBu,null,e),t)),au={onSaveCollection:()=>async(e,t,{pipelineBuilder:n,preferences:a,connectionScopedAppRegistry:r})=>{const{autoPreview:i,dataService:{dataService:o},namespace:s,maxTimeMS:c,collationString:d}=t();if(o&&!a.getPreferences().enableAggregationBuilderRunPipeline&&Ut(i,n.syntaxError))try{e({type:qd});const t=n.getPipelineFromSource(),i={maxTimeMS:c??l,collation:d.value??void 0},{signal:u}=new AbortController;await B({dataService:o,preferences:a,signal:u,namespace:s,pipeline:t,options:i}),e({type:Zd}),r.emit("agg-pipeline-out-executed",Q(s,t[t.length-1]))}catch(t){e({type:Jd,serverError:t})}},onOpenCollection:()=>(e,t)=>{const{namespace:n,pipelineBuilder:{textEditor:{pipeline:{pipeline:a}}}}=t(),r=Q(n,a[a.length-1]);r&&e(ns(r))}},ru=(0,o.Ng)((({pipelineBuilder:{textEditor:{outputStage:{isComplete:e,isLoading:t}}}})=>({isComplete:e,isLoading:t})),au)((({stageOperator:e,isLoading:t,isComplete:n,onSaveCollection:a,onOpenCollection:i})=>{const o=!(0,g.Fg)("enableAggregationBuilderRunPipeline");if(!e)return null;if(n&&o)return r().createElement(nu,{"data-testid":`${e}-is-complete-banner`,text:`Documents persisted to collection specified by ${e}.`,actionButton:r().createElement(s.$nd,(0,fi.A)({},tu,{onClick:i}),"Go to collection")});const l=t?r().createElement(s.Q0K,{title:"Loading"}):void 0;return r().createElement(nu,{"data-testid":`${e}-preview-banner`,text:"$out"===e?d:u,actionButton:o?r().createElement(s.$nd,(0,fi.A)({},tu,{disabled:t,onClick:a,leftGlyph:l}),"Save documents"):null})})),iu=(0,s.AHW)({display:"flex",flexDirection:"column",height:"100%",padding:s.YKD[400],paddingBottom:s.YKD[200],gap:s.YKD[200]}),ou=(0,s.AHW)({display:"flex",flexDirection:"row",alignItems:"flex-start"}),su=(0,s.AHW)({display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",textAlign:"center"}),lu=(0,s.AHW)({marginTop:s.YKD[400]}),cu=(0,s.AHW)({overflow:"auto"}),du=(0,s.AHW)({marginTop:0,marginRight:0,marginBottom:"auto",marginLeft:"auto"}),uu=(0,s.AHW)({marginTop:"auto"}),pu=({previewDocs:e,isLoading:t,isMissingAtlasSupport:n,atlasOperator:i,isPreviewStale:o,showSearchIndexStaleResultsBanner:l,searchIndexName:c})=>{const d=(0,a.useCallback)((e=>{const t=e.toEJSON();navigator.clipboard.writeText(t)}),[]),{enableSearchActivationProgramP1:u}=(0,O.p5)();return t?r().createElement("div",{className:su},r().createElement(s.Q0K,{size:"24px"})):n?r().createElement("div",{className:su},r().createElement(ts,{stageOperator:i})):e?0===e.length?!u&&i?r().createElement(hs,null):r().createElement("div",{className:su},r().createElement(s.pyG,null),r().createElement(s.nBu,{className:lu},"No preview documents")):r().createElement(r().Fragment,null,o&&r().createElement(s.rpn,{warnings:["Output outdated and no longer in sync."]}),r().createElement(Vo.Bo,{docs:e,copyToClipboard:d,isEditable:!1,className:cu}),u&&l&&r().createElement(ys,{searchIndexName:c})):r().createElement("div",{className:su},r().createElement(s.pyG,null),r().createElement(s.nBu,{className:lu},"Preview results to see a sample of the aggregated results from this pipeline."))},mu=(0,o.Ng)((e=>{const t=Xt(e),n=t[t.length-1]??"",{isLoading:a,previewDocs:r,serverError:i,isPreviewStale:o,pipelineText:s}=e.pipelineBuilder.textEditor.pipeline,l=t.find((e=>ne(e)))??"",c=ue(e.env,l,i),{searchIndexName:d}=ie(s);return{isLoading:a,previewDocs:r,isMergeStage:"$merge"===n,isOutStage:"$out"===n,isMissingAtlasSupport:c,atlasOperator:l,isPreviewStale:o,showSearchIndexStaleResultsBanner:!!d&&e.searchIndexes.indexes.some((e=>e.name===d&&"READY"!==e.status&&e.queryable)),searchIndexName:d}}),{onExpand:()=>(e,t)=>{const{pipelineBuilder:{textEditor:{pipeline:{previewDocs:n}}}}=t();n?.forEach((e=>e.expand()))},onCollapse:()=>(e,t)=>{const{pipelineBuilder:{textEditor:{pipeline:{previewDocs:n}}}}=t();n?.forEach((e=>e.collapse()))}})((({isLoading:e,isMergeStage:t,isOutStage:n,isMissingAtlasSupport:i,previewDocs:o,atlasOperator:l,isPreviewStale:c,showSearchIndexStaleResultsBanner:d,searchIndexName:u,onExpand:p,onCollapse:m})=>{const g=o?.length??0,h=1===g?"document":"documents",f=!e&&g>0,y=t?"$merge":n?"$out":null,b=(0,a.useCallback)((e=>{"expand"===e?p():"collapse"===e&&m()}),[p,m]);return r().createElement("div",{className:iu,"data-testid":"pipeline-as-text-preview"},r().createElement("div",{className:ou},r().createElement("div",null,r().createElement(s.bz9,null,"Pipeline Output Preview"),f&&r().createElement(s.nBu,null,"Sample of ",g," ",h)),r().createElement("div",{className:du},r().createElement(ri,{onChangeOption:b}))),r().createElement(pu,{isLoading:e,isMissingAtlasSupport:i,atlasOperator:l,previewDocs:o,isPreviewStale:c,showSearchIndexStaleResultsBanner:d,searchIndexName:u}),r().createElement("div",{className:uu,"data-testid":"output-stage-preview"},r().createElement(ru,{stageOperator:y})))})),gu=(0,s.AHW)({display:"flex",flexDirection:"column",height:"100%"}),hu=(0,s.AHW)({display:"flex",flex:1}),fu=(0,s.AHW)({flex:1,width:"100%"}),yu=(0,s.AHW)({flex:1,overflowX:"hidden"}),bu=(0,s.AHW)({paddingBottom:s.YKD[400],width:"100%",overflow:"auto"}),vu="pipeline-as-text-workspace",xu=(0,o.Ng)((e=>{const{autoPreview:t,pipelineBuilder:{textEditor:{pipeline:{pipeline:n}}}}=e;return{isAutoPreview:!!t,showRerankFirstStageBanner:en(e),showRerankTokensBanner:n.some((e=>"$rerank"===J(e)))&&!!t}}))((({isAutoPreview:e,showRerankFirstStageBanner:t,showRerankTokensBanner:n})=>e?r().createElement("div",{className:bu},r().createElement(s.yY_,{"data-testid":vu,className:gu},t&&r().createElement(Ji,{"data-testid":"pipeline-editor-rerank-first-stage-banner"}),n&&r().createElement(Go,{"data-testid":"pipeline-editor-rerank-tokens-banner"}),r().createElement("div",{className:hu},r().createElement(hi.c,{defaultSize:{width:"50%",height:"100%"},minWidth:"300px",maxWidth:"70%",enable:{right:!0},handleComponent:{right:r().createElement(Ci,null)}},r().createElement(Ud,null)),r().createElement("div",{className:yu},r().createElement(mu,null))))):r().createElement("div",{className:bu},r().createElement(s.yY_,{"data-testid":vu,className:gu},t&&r().createElement(Ji,{"data-testid":"pipeline-editor-rerank-first-stage-banner"}),r().createElement("div",{className:fu},r().createElement(Ud,null)))))),Eu=(0,s.AHW)({display:"flex",overflow:"hidden",paddingRight:s.YKD[400],paddingLeft:s.YKD[400],gap:s.YKD[200],height:"100%"}),Cu=(0,o.Ng)((({pipelineBuilder:{pipelineMode:e}})=>({pipelineMode:e})))((({pipelineMode:e})=>r().createElement("div",{className:Eu,"data-testid":"pipeline-builder-workspace"},"builder-ui"===e?r().createElement(zd,null):r().createElement(xu,null)))),wu=(0,s.AHW)({padding:s.YKD[400]}),Iu=({namespace:e,documents:t,view:n})=>{const i=(0,a.useCallback)((e=>{const t=e.toEJSON();navigator.clipboard.writeText(t)}),[]);if(0===t.length)return null;const o="document"===n?Vo.Bo:Vo.lh;return r().createElement(o,{namespace:e,isEditable:!1,docs:t,copyToClipboard:i,className:wu})},Su=()=>{const e=(0,s.D27)(),t=(0,a.useMemo)((()=>e?s.MFm.white:s.MFm.black),[e]);return r().createElement("svg",{className:"darkreader-ignore-child-inline-style",width:"72",height:"72",viewBox:"0 0 72 72",fill:"none",xmlns:"http://www.w3.org/2000/svg"},r().createElement("path",{d:"M46 35V31C46 29.8889 46.8224 29 47.8505 29H66.1495C67.1776 29 68 29.8889 68 31V35C68 36.1111 67.1776 37 66.1495 37H47.7477C46.8224 36.8889 46 36 46 35Z",fill:s.MFm.green.base}),r().createElement("path",{d:"M46 49V45C46 43.8889 46.8224 43 47.8505 43H66.1495C67.1776 43 68 43.8889 68 45V49C68 50.1111 67.1776 51 66.1495 51H47.7477C46.8224 51 46 50.1111 46 49Z",fill:s.MFm.green.base}),r().createElement("path",{d:"M4 28V24C4 22.8889 4.82243 22 5.85047 22H24.1495C25.1776 22 26 22.8889 26 24V28C26 29.1111 25.1776 30 24.1495 30H5.85047C4.82243 29.8889 4 29 4 28Z",fill:s.MFm.green.base}),r().createElement("path",{d:"M4 42V38C4 36.8889 4.82243 36 5.85047 36H24.1495C25.1776 36 26 36.8889 26 38V42C26 43.1111 25.1776 44 24.1495 44H5.85047C4.82243 44 4 43.1111 4 42Z",fill:s.MFm.green.base}),r().createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M6.94524 8.5H4V7.5H24.9672V8.5H22.0219V21.5H24.1495C25.4896 21.5 26.5 22.65 26.5 24V28C26.5 29.35 25.4896 30.5 24.1495 30.5H22.0219V35.5H24.1495C25.4896 35.5 26.5 36.65 26.5 38V42C26.5 43.35 25.4896 44.5 24.1495 44.5H22.0219V46.5123C22.0219 48.1019 23.3721 49.4509 24.9672 49.4509C25.7947 49.4509 26.467 49.1286 27.0882 48.6012C27.5767 48.1063 27.9125 47.3557 27.9125 46.5123V42.9754L27.9125 42.9719L28.011 29.0246V25.4877C28.011 15.5826 36.1108 7.5 46.0329 7.5C50.997 7.5 55.4502 9.52322 58.7838 12.7495L58.7893 12.7548L58.7946 12.7603C62.0283 16.0886 64.0548 20.6321 64.0548 25.4877V28.5H66.1495C67.4896 28.5 68.5 29.65 68.5 31V35C68.5 36.35 67.4896 37.5 66.1495 37.5H64.0548V42.5H66.1495C67.4896 42.5 68.5 43.65 68.5 45V49C68.5 50.35 67.4896 51.5 66.1495 51.5H64.0548V63.4016H67V64.4016H49.3919L49.3797 64.4018L49.3676 64.4016H46.0328V63.4016H48.8797V51.5H47.7477C46.4929 51.5 45.5 50.3307 45.5 49V45C45.5 43.65 46.5104 42.5 47.8505 42.5H48.8797V37.5H47.7178L47.688 37.4964C46.5128 37.3553 45.5 36.2544 45.5 35V31C45.5 29.65 46.5104 28.5 47.8505 28.5H48.8797V25.586C48.8797 23.9964 47.5295 22.6474 45.9344 22.6474C45.0884 22.6474 44.3359 22.9829 43.84 23.4705C43.3116 24.0904 42.9891 24.761 42.9891 25.586V46.5123C42.9891 56.4174 34.8893 64.5 24.9672 64.5C15.045 64.5 6.94524 56.4174 6.94524 46.5123V44.5H5.85047C4.51041 44.5 3.5 43.35 3.5 42V38C3.5 36.65 4.51041 35.5 5.85047 35.5H6.94524V30.5H5.82353L5.79674 30.4971C4.52832 30.36 3.5 29.2687 3.5 28V24C3.5 22.65 4.51041 21.5 5.85047 21.5H6.94524V8.5ZM7.94524 35.5H21.0219V30.5H7.94524V35.5ZM7.94524 44.5V46.5123C7.94524 55.8633 15.5955 63.5 24.9672 63.5C34.3388 63.5 41.9891 55.8633 41.9891 46.5123V25.586C41.9891 24.4526 42.4489 23.5554 43.0941 22.8041C43.0967 22.8011 43.0993 22.7982 43.1019 22.7953C43.1048 22.7921 43.1077 22.7889 43.1106 22.7858L43.1202 22.7759C43.8058 22.0917 44.8192 21.6474 45.9344 21.6474C48.0799 21.6474 49.8797 23.4422 49.8797 25.586V28.5H63.0548V25.4877C63.0548 20.9144 61.146 16.6182 58.0828 13.4627C54.9201 10.4044 50.713 8.5 46.0329 8.5C36.6612 8.5 29.011 16.1367 29.011 25.4877V29.0246L29.0109 29.0281L28.9125 42.9754V46.5123C28.9125 47.6261 28.4669 48.6381 27.7814 49.3223L27.7678 49.3359L27.7532 49.3484C27.0003 49.9924 26.1018 50.4509 24.9672 50.4509C22.8217 50.4509 21.0219 48.656 21.0219 46.5123V44.5H7.94524ZM21.0219 8.5V21.5H7.94524V8.5H21.0219ZM49.8797 37.5H63.0548V42.5H49.8797V37.5ZM49.8797 51.5H63.0548V63.4016H49.8797V51.5ZM4.5 24C4.5 23.1277 5.13445 22.5 5.85047 22.5H24.1495C24.8656 22.5 25.5 23.1277 25.5 24V28C25.5 28.8723 24.8656 29.5 24.1495 29.5H5.87932C5.1036 29.4033 4.5 28.7236 4.5 28V24ZM47.8505 29.5C47.1344 29.5 46.5 30.1277 46.5 31V35C46.5 35.7357 47.1153 36.4044 47.7803 36.5H66.1495C66.8656 36.5 67.5 35.8723 67.5 35V31C67.5 30.1277 66.8656 29.5 66.1495 29.5H47.8505ZM47.8505 43.5C47.1344 43.5 46.5 44.1277 46.5 45V49C46.5 49.8915 47.1519 50.5 47.7477 50.5H66.1495C66.8656 50.5 67.5 49.8723 67.5 49V45C67.5 44.1277 66.8656 43.5 66.1495 43.5H47.8505ZM4.5 38C4.5 37.1277 5.13445 36.5 5.85047 36.5H24.1495C24.8656 36.5 25.5 37.1277 25.5 38V42C25.5 42.8723 24.8656 43.5 24.1495 43.5H5.85047C5.13445 43.5 4.5 42.8723 4.5 42V38Z",fill:t}))},Au=()=>r().createElement("div",{"data-testid":"pipeline-empty-results"},r().createElement(s.HYq,{icon:Su,title:"No results",subTitle:"Try to modify your pipeline to get results"})),ku=(0,s.AHW)({overflow:"hidden",display:"grid",gridTemplateRows:"min-content 1fr",gridTemplateColumns:"1fr"}),Du=(0,s.AHW)({height:"100%",overflowY:"auto","&:not(:first-child)":{height:`calc(100% - ${s.YKD[400]}px)`,marginTop:s.YKD[400]}}),Nu=(0,s.AHW)({display:"flex",alignItems:"flex-start",paddingLeft:s.YKD[400]+s.YKD[100],paddingRight:s.YKD[800]+s.YKD[100]}),Mu=(0,s.AHW)({width:"100%",height:"100%",paddingTop:2*s.YKD[1600],justifyContent:"center"}),Tu=(0,s.AHW)({width:"100%"}),Pu=(0,s.AHW)({display:"flex",justifyContent:"space-between"}),Lu=(0,s.AHW)({flex:1}),Ou=(0,s.AHW)({display:"flex",justifyContent:"space-between",alignItems:"center"}),Ru=(0,s.AHW)({marginLeft:s.YKD[100]}),Hu=({children:e,center:t})=>r().createElement("div",{className:(0,s.cx)(Nu,t&&Mu)},e),Fu=(0,s.AHW)({display:"flex",flexDirection:"column",alignItems:"center",gap:s.YKD[200],maxWidth:8*s.YKD[1600],marginTop:s.YKD[200],marginBottom:s.YKD[200]}),Wu=(0,s.AHW)({color:s.MFm.green.dark2,textAlign:"center"}),ju=({namespace:e,onClick:t})=>r().createElement("div",{className:Fu},r().createElement(s.Pds,{className:Wu},"Results persisted",e?` in ${e} namespace`:""),e&&r().createElement(s.$nd,{"data-testid":"pipeline-results-go-to-collection",variant:"primaryOutline",onClick:t},"Go to collection")),Bu={onCancel:fn,onRetry:()=>(e,t)=>{const{aggregation:{page:n}}=t();return e(bn(n))},onOutClick:ns},zu=(0,o.Ng)((e=>{const{namespace:t,serverVersion:n,aggregation:{documents:a,loading:r,error:i,resultsViewType:o,pipeline:s}}=e,l=s[s.length-1],c=J(l)??"",d=s.reduce(((e,t)=>e??So(J(t))),null);return{namespace:t,documents:a,isLoading:r,error:i,isError:Boolean(i),isEmpty:0===a.length,resultsViewType:o,isMergeOrOutPipeline:te(c),mergeOrOutDestination:Q(t,l),serverVersion:n,hasRerankStage:s.some((e=>"$rerank"===J(e))),searchExtensionType:d}}),Bu)((({namespace:e,documents:t,isLoading:n,error:a,isError:i,isEmpty:o,isMergeOrOutPipeline:l,mergeOrOutDestination:c,resultsViewType:d,onOutClick:u,onRetry:p,onCancel:m,serverVersion:h,hasRerankStage:f,searchExtensionType:y})=>{const{atlasMetadata:b}=(0,Wr.qm)();let v=null;const x=(0,g.Fg)("enableRerank")&&f&&!ho(h),E=!(!i||!a)&&fo(a.message),C=i&&a?Io(a.message):null,w=E&&b?(0,_i.yV)({projectId:b.projectId}):null;return v=i&&a&&E?r().createElement(Hu,null,r().createElement(s.lZ$,{"data-testid":"pipeline-results-error",variant:s.uAY.Danger,className:Tu},r().createElement("b",null,"Native reranking not enabled"),r().createElement("br",null),r().createElement("div",{className:Ou},r().createElement("span",null,"Enable native reranking in project settings."),w&&r().createElement(s.$nd,{size:"xsmall",href:w,target:"_blank",rightGlyph:r().createElement(s.Int,{glyph:"OpenNewTab"})},"Project Settings")))):i&&a&&C?r().createElement(Hu,null,r().createElement(Do,{rateLimitInfo:C,searchExtensionType:y,dataTestId:"pipeline-results-error"})):i&&a?r().createElement(Hu,null,r().createElement(s.lZ$,{"data-testid":"pipeline-results-error",variant:s.uAY.Danger,className:Tu},r().createElement("div",{className:Pu},r().createElement("div",{className:Lu},a?.message),r().createElement(s.$nd,{size:"xsmall",onClick:p,"data-testid":"pipeline-results-error-retry-button",className:Ru},"RETRY"),a?.info&&r().createElement(s.$nd,{size:"xsmall",onClick:()=>(0,s.a0R)({details:a.info,closeAction:"close"}),"data-testid":"pipeline-results-error-details-button",className:Ru},"VIEW ERROR DETAILS")))):n?r().createElement(Hu,{center:!0},r().createElement(s.yao,{"data-testid":"pipeline-results-loader",progressText:l?"Persisting documents"+(c?` to ${c} namespace`:""):"Running aggregation",cancelText:"Stop",onCancel:m})):l?r().createElement(Hu,{center:!0},r().createElement(ju,{namespace:c,onClick:()=>{c&&u?.(c)}})):o?r().createElement(Au,null):r().createElement(Iu,{namespace:e,documents:t,view:d}),r().createElement("div",{"data-testid":"pipeline-results-workspace",className:ku},x&&r().createElement(Hu,null,r().createElement(Ho,{"data-testid":"pipeline-results-rerank-version-warning"})),r().createElement("div",{className:Du},v))})),_u=(0,s.AHW)({height:"100%",display:"flex",flexDirection:"column",gap:s.YKD[400]}),$u=(0,s.AHW)({display:"flex",justifyContent:"flex-start",gap:s.YKD[200],marginLeft:s.YKD[200],marginRight:s.YKD[200],flexWrap:"wrap"}),Yu=(0,s.AHW)({flex:1,overflowY:"auto",paddingBottom:s.YKD[400]}),Ku=(0,o.Ng)((({focusMode:{stageIndex:e},pipelineBuilder:{stageEditor:{stages:t}}})=>{const n=t[e];return{index:e,operator:n?.stageOperator}}))((({index:e,operator:t})=>{const n=(0,a.useRef)(null);if(-1===e)return null;const i=le(t)||p;return r().createElement("div",{className:_u},r().createElement("div",{className:$u},r().createElement(Ti,{onChange:(e,t,a)=>{(0,s.Rbc)((()=>{n.current?.focus(),a&&n.current?.applySnippet(a)}))},index:e}),r().createElement(s.N_E,{hideExternalIcon:!1,href:i,target:"_blank"},"Open docs")),r().createElement("div",{className:Yu},r().createElement($o,{editorRef:n,index:e})))})),Gu=(0,s.AHW)({display:"flex",flexDirection:"column",height:"100%",gap:s.YKD[200]}),Vu=(0,s.AHW)({display:"flex",flexDirection:"row",alignItems:"flex-start",marginBottom:s.YKD[200],flexWrap:"wrap"}),Uu=(0,s.AHW)({whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),qu=(0,s.AHW)({display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100%",textAlign:"center"}),Zu=(0,s.AHW)({marginTop:s.YKD[400]}),Ju=(0,s.AHW)({overflowY:"auto"}),Qu=(0,s.AHW)({marginTop:0,marginRight:0,marginBottom:"auto",marginLeft:"auto"}),Xu=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[200]}),ep=({title:e,isLoading:t=!1,documents:n=null,stageIndex:i=-1,stageOperator:o="",isMissingAtlasOnlyStageSupport:l=!1,showSearchIndexStaleResultsBanner:c=!1,searchIndexName:d=null,onExpand:u,onCollapse:p})=>{const m=(0,a.useCallback)((e=>{const t=e.toEJSON();navigator.clipboard.writeText(t)}),[]),g=(0,a.useCallback)((e=>{"expand"===e?u(i):"collapse"===e&&p(i)}),[u,p,i]),{enableSearchActivationProgramP1:h}=(0,O.p5)(),f=n?.length??0,y=1===f?"document":"documents",b=!t&&f>0,v=n&&n.length>0;let x=null;return x=te(o??"")?r().createElement("div",{className:qu},r().createElement(ls,{index:i})):l?r().createElement("div",{className:qu},r().createElement(ts,{stageOperator:o??""})):t?r().createElement("div",{className:qu},r().createElement("div",{className:Xu},r().createElement(s.Q0K,{title:"Loading"}),"Loading Preview Documents...")):n&&n.length>0?r().createElement(r().Fragment,null,r().createElement(Vo.Bo,{isEditable:!1,docs:n??[],copyToClipboard:m,className:Ju}),h&&c&&r().createElement(ys,{searchIndexName:d})):!h&&ae(o)?r().createElement(hs,null):r().createElement("div",{className:qu},r().createElement(s.nBu,{className:Zu},"No preview documents")),r().createElement("div",{className:Gu,"data-testid":"focus-mode-stage-preview"},r().createElement("div",{className:Vu},r().createElement("div",{className:Uu},r().createElement(s.bz9,null,e),b&&r().createElement(s.nBu,null,"Sample of ",f," ",y)),r().createElement("div",{className:Qu},v&&r().createElement(ri,{buttonText:"Options",onChangeOption:g}))),x)},tp=(0,o.Ng)((({focusMode:{stageIndex:e},env:t,inputDocuments:n,pipelineBuilder:{stageEditor:{stages:a}},searchIndexes:r})=>{if(-1===e)return{};const i=a.slice(0,e).map(((e,t)=>({stage:e,index:t}))).filter((({stage:e})=>"stage"===e.type&&!e.disabled)).pop()?.index??null;if(null===i)return{isLoading:n.isLoading,documents:n.documents};const o=a[i],s=ue(t,o.stageOperator,o.serverError);if(te(o.stageOperator||"")||ne(o.stageOperator||"")&&s)return{};const l=re(o.stageOperator,o.value),c=!!l&&r.indexes.some((e=>e.name===l&&"READY"!==e.status&&e.queryable));return{isLoading:o.loading,documents:o.previewDocs,stageIndex:i,stageOperator:o.stageOperator,isMissingAtlasOnlyStageSupport:s,showSearchIndexStaleResultsBanner:c,searchIndexName:l}}),{onExpand:Nt,onCollapse:Mt})((e=>r().createElement(ep,(0,fi.A)({},e,{title:"Stage Input"})))),np=(0,o.Ng)((({focusMode:{stageIndex:e},env:t,pipelineBuilder:{stageEditor:{stages:n}},searchIndexes:a})=>{if(-1===e)return{};const r=n[e],i=ue(t,r.stageOperator,r.serverError),o=re(r.stageOperator,r.value),s=!!o&&a.indexes.some((e=>e.name===o&&"READY"!==e.status&&e.queryable));return{isLoading:r.loading,documents:r.previewDocs,stageIndex:e,stageOperator:r.stageOperator,isMissingAtlasOnlyStageSupport:i,showSearchIndexStaleResultsBanner:s,searchIndexName:o}}),{onExpand:Nt,onCollapse:Mt})((e=>r().createElement(ep,(0,fi.A)({},e,{title:"Stage Output"})))),ap=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[400]}),rp=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[200]}),ip=(0,s.AHW)({textTransform:"uppercase",fontWeight:"bold",width:`${String(Math.max(...["Enabled","Disabled"].map((e=>e.length))))}ch`}),op=(0,s.AHW)({width:"240px"}),sp=(0,s.AHW)({display:"flex",alignItems:"center",gap:s.YKD[400]}),lp=(0,s.AHW)({flexShrink:0}),cp="mod+shift+9",dp="mod+shift+0",up="mod+shift+a",pp="mod+shift+b",mp=(0,o.Ng)((e=>{const{env:t,focusMode:{stageIndex:n},pipelineBuilder:{stageEditor:{stages:a}},searchIndexes:{isSearchIndexesSupported:r,indexes:i,status:o}}=e,s=a[n];return{stageIndex:n,isEnabled:!s?.disabled,stage:s,env:t,isSearchIndexesSupported:r,isRerankFirstStage:en(e,n),hasSearchIndex:i.length>0,isSearchIndexesLoading:"INITIAL"===o||"LOADING"===o||"POLLING"===o,stages:a.reduce(((e,t,n)=>("stage"===t.type&&e.push({idxInStore:n,stageOperator:t.stageOperator}),e)),[])}}),{onStageSelect:Fi,onStageDisabledToggleClick:Ht,onAddStageClick:e=>t=>{t(Ft(e)),t(Fi(e+1))},onCreateSearchIndex:Gn,onAddSearchStageBefore:Wt,onRefreshSearchIndexes:Yn})((({stageIndex:e,isEnabled:t,stages:n,env:i,isSearchIndexesSupported:o,isRerankFirstStage:l,hasSearchIndex:c,isSearchIndexesLoading:d,stage:u,onCreateSearchIndex:p,onAddStageClick:m,onStageSelect:h,onStageDisabledToggleClick:f,onAddSearchStageBefore:y,onRefreshSearchIndexes:b})=>{const[v,x]=(0,a.useState)(!1),E=(0,g.Fg)("showInsights"),C=(0,a.useMemo)((()=>{if(u)return zi(u,i,o,p)}),[u,i,o,p]),w=(0,a.useCallback)((()=>{y(e)}),[y,e]),I=Gi({isRerankFirstStage:l,hasSearchIndex:c,isSearchIndexesLoading:d,onAddSearchStageBefore:w})??C,S=(0,a.useCallback)((e=>{e&&l&&b()}),[l,b]),A=n[0].idxInStore===e,k=n[n.length-1].idxInStore===e,D=()=>{if(A)return;const t=n.findIndex((t=>t.idxInStore===e)),a=n[t-1].idxInStore;h(a)},N=()=>{if(k)return;const t=n.findIndex((t=>t.idxInStore===e)),a=n[t+1].idxInStore;h(a)},M=()=>{m(e-1),x(!1)},T=()=>{m(e),x(!1)};(0,s.vCs)(cp,D),(0,s.vCs)(dp,N),(0,s.vCs)(up,T),(0,s.vCs)(pp,M);const P=n.map((({stageOperator:e,idxInStore:t},n)=>({label:`Stage ${n+1}: ${e??"select"}`,value:t}))),L={width:`calc(${String(Math.max(...P.map((({label:e})=>e.length))))}ch + ${s.YKD[800]}px)`};return r().createElement("div",{className:ap},r().createElement("div",{className:rp},r().createElement(s.m_M,{enabled:!A,trigger:r().createElement(s.$nd,{size:"xsmall",disabled:A,onClick:D,"data-testid":"previous-stage-button","aria-label":"Edit previous stage"},r().createElement(s.Int,{size:"xsmall",title:null,role:"presentation",glyph:"ChevronLeft"}))},r().createElement(s.nBu,{className:sp},r().createElement("span",{className:lp},"Go to previous stage"),r().createElement("span",{className:lp},(0,s.Mf6)(cp)))),r().createElement(s.l6P,{"data-testid":"stage-select",allowDeselect:!1,style:L,size:"xsmall",value:String(e),"aria-label":"Select stage to edit",onChange:e=>{h(Number(e))}},P.map((({label:e,value:t})=>r().createElement(s.c$x,{key:e,value:String(t)},e)))),r().createElement(s.m_M,{enabled:!k,trigger:r().createElement(s.$nd,{size:"xsmall",disabled:k,onClick:N,"aria-label":"Edit next stage","data-testid":"next-stage-button"},r().createElement(s.Int,{size:"xsmall",title:null,role:"presentation",glyph:"ChevronRight"}))},r().createElement(s.nBu,{className:sp},r().createElement("span",null,"Go to next stage"),r().createElement("span",{className:lp},(0,s.Mf6)(dp))))),r().createElement("div",{className:rp},r().createElement("span",{"aria-hidden":"true",className:ip},t?"Enabled":"Disabled"),r().createElement(s.lMk,{size:"xsmall","aria-label":t?"Disable stage":"Enable stage",checked:t,onChange:t=>{f(e,!t)}})),r().createElement("div",null,r().createElement(s.W1t,{"data-testid":"add-stage-menu-content",className:op,open:v,setOpen:x,trigger:({onClick:e,children:t})=>r().createElement("div",{className:rp},r().createElement(s.$nd,{"data-testid":"add-stage-menu-button",size:"xsmall",leftGlyph:r().createElement(s.Int,{title:null,role:"presentation",glyph:"PlusWithCircle"}),rightGlyph:r().createElement(s.Int,{title:null,role:"presentation",glyph:"CaretDown"}),onClick:e},"Add stage"),t)},r().createElement(s.Drp,{onClick:T,description:(0,s.Mf6)(up),"data-text":"Add stage after"},"Add stage after"),r().createElement(s.Drp,{onClick:M,description:(0,s.Mf6)(pp),"data-text":"Add stage before"},"Add stage before"))),E&&I&&r().createElement(s.gIH,{signals:I,onPopoverOpenChange:S}))})),gp=(0,s.AHW)({display:"grid",gridTemplateRows:"min-content 1fr",gridTemplateColumns:"1fr",overflow:"hidden",padding:s.YKD[800],paddingBottom:0,height:"100%"}),hp=(0,s.AHW)({paddingBottom:s.YKD[200]}),fp=(0,s.AHW)({display:"flex",height:"100%",overflow:"hidden"}),yp=(0,s.AHW)({paddingTop:s.YKD[600],paddingRight:s.YKD[200]}),bp=(0,s.AHW)({paddingTop:s.YKD[600],paddingLeft:s.YKD[200]}),vp=(0,s.AHW)({height:"100%"}),xp=(0,s.AHW)({flex:1,paddingTop:s.YKD[600]}),Ep=(0,s.AHW)({}),Cp=(0,s.AHW)({backgroundColor:s.MFm.gray.light3}),wp=(0,s.AHW)({width:"50%",minWidth:"20%",maxWidth:"70%"}),Ip=(0,s.AHW)({width:"100%"}),Sp=({isAutoPreviewEnabled:e})=>{const t=(0,s.D27)();return e?r().createElement("div",{className:fp},r().createElement(hi.c,{defaultSize:{width:"25%",height:"auto"},minWidth:"15%",maxWidth:"40%",className:yp,enable:{right:!0},handleComponent:{right:r().createElement(Ci,null)},handleStyles:{right:{right:"-9px"}}},r().createElement("div",{className:vp,"data-testid":"stage-input"},r().createElement(tp,null))),r().createElement("div",{className:(0,s.cx)(xp,wp,t?Ep:Cp),"data-testid":"stage-editor"},r().createElement(Ku,null)),r().createElement(hi.c,{defaultSize:{width:"25%",height:"auto"},minWidth:"15%",maxWidth:"40%",className:bp,enable:{left:!0},handleComponent:{left:r().createElement(Ci,null)},handleStyles:{left:{left:"-1px"}}},r().createElement("div",{className:vp,"data-testid":"stage-output"},r().createElement(np,null)))):r().createElement("div",{className:fp},r().createElement("div",{className:(0,s.cx)(xp,Ip,t?Ep:Cp),"data-testid":"stage-editor"},r().createElement(Ku,null)))},Ap={onCloseModal:Hi},kp=(0,o.Ng)((e=>{const{focusMode:{isEnabled:t,stageIndex:n},autoPreview:a,pipelineBuilder:{stageEditor:{stages:r}}}=e,i=r[n];return{isModalOpen:t,isAutoPreviewEnabled:a,showRerankFirstStageBanner:en(e,n),showRerankTokensBanner:"$rerank"===i?.stageOperator&&!!a}}),Ap)((({isModalOpen:e,isAutoPreviewEnabled:t,showRerankFirstStageBanner:n,showRerankTokensBanner:a,onCloseModal:i})=>r().createElement(s.aFV,{setOpen:i,open:e,"data-testid":"focus-mode-modal",fullScreen:!0},r().createElement("div",{className:gp},r().createElement("div",null,r().createElement("div",{className:hp},r().createElement(mp,null)),r().createElement(s.d$,null),n&&r().createElement(Ji,{"data-testid":"focus-mode-rerank-first-stage-banner"}),a&&r().createElement(Go,{"data-testid":"focus-mode-rerank-tokens-banner"})),r().createElement(Sp,{isAutoPreviewEnabled:t}))))),Dp=(0,s.AHW)({display:"flex",flexGrow:1,flexDirection:"column",width:"100%",height:"100%",minHeight:0,position:"relative"}),Np=(0,s.AHW)({marginLeft:"20px",marginRight:"36px"}),Mp=({saveCurrentPipeline:e,savingPipelineNameChanged:t,savingPipelineApply:n,savingPipelineCancel:i,clonePipeline:o,showRunButton:l,showExplainButton:c,toggleSettingsIsExpanded:d,toggleSettingsIsCommentMode:u,setSettingsSampleSize:p,setSettingsLimit:m,isCommenting:g,applySettings:h,settings:f,savingPipeline:y,updateViewError:b,dismissViewError:v,workspace:x,limit:E=10,largeLimit:C=1e5,hasSearchStage:w,isReadonlyView:I,serverVersion:S,isSearchIndexesSupported:A,startPollingSearchIndexes:k,stopPollingSearchIndexes:D})=>{const{enableSearchActivationProgramP1:N}=(0,O.p5)(),M=_.rd.isVersionSearchCompatibleForViewsCompass(S),T=I?M:A;(0,a.useEffect)((()=>{if(N&&T)return w?k():D(),D}),[N,w,T,k,D]);const P=r().createElement(gi,{showRunButton:l,showExplainButton:c}),R=b?r().createElement("div",{className:Np},r().createElement(s.lZ$,{variant:"danger",dismissible:!0,onClose:v},b)):null,F=r().createElement(H,{name:y.name,isOpen:y.isOpen,isSaveAs:y.isSaveAs,saveCurrentPipeline:e,savingPipelineNameChanged:t,savingPipelineApply:n,savingPipelineCancel:i,clonePipeline:o});return r().createElement("div",{className:Dp},r().createElement(L,{isExpanded:f.isExpanded,toggleSettingsIsExpanded:d,toggleSettingsIsCommentMode:u,setSettingsSampleSize:p,setSettingsLimit:m,isCommenting:g,limit:E,largeLimit:C,applySettings:h,settings:f}),r().createElement(s.XvC,{toolbar:P},R,"results"===x?r().createElement(zu,null):r().createElement(Cu,null),r().createElement(kp,null),F))};Mp.displayName="PipelineComponent";const Tp=r().memo(Mp),Pp=(0,s.AHW)({display:"flex",alignItems:"flex-start",backgroundColor:s.MFm.gray.light3,position:"relative",width:"100%",zIndex:0,height:"100%"});class Lp extends a.Component{static displayName="AggregationsComponent";render(){return r().createElement("div",{className:Pp,"data-testid":"compass-aggregations"},r().createElement(Tp,this.props))}}const Op=(0,o.Ng)((e=>({namespace:e.namespace,name:e.name,collationString:e.collationString,isCommenting:e.comments,isAutoPreviewing:e.autoPreview,settings:e.settings,limit:e.limit,largeLimit:e.largeLimit,maxTimeMS:e.maxTimeMS,savingPipeline:e.savingPipeline,updateViewError:e.updateViewError,workspace:e.workspace,hasSearchStage:Xt(e,!1).some((e=>ae(e))),isReadonlyView:!!e.sourceName,serverVersion:e.serverVersion,isSearchIndexesSupported:e.searchIndexes.isSearchIndexesSupported})),{toggleSettingsIsExpanded:pr,toggleSettingsIsCommentMode:()=>({type:sr}),setSettingsSampleSize:e=>({type:lr,value:e}),setSettingsLimit:e=>({type:cr,value:e}),saveCurrentPipeline:_e,clonePipeline:()=>({type:ge}),applySettings:()=>(e,t)=>{const{settings:n}=t();e((e=>({type:dr,settings:e}))(n)),e(Zt())},savingPipelineNameChanged:e=>({type:Va,name:e}),savingPipelineApply:()=>(e,t)=>{const{name:n,savingPipeline:{name:a}}=t();e({type:Ua,name:n===a?`${a} (copy)`:a})},savingPipelineCancel:()=>({type:qa}),dismissViewError:Qn,startPollingSearchIndexes:()=>(e,t,{pollingIntervalRef:n})=>{null===n.searchIndexes&&(n.searchIndexes=setInterval((()=>{e((async e=>{await e($n(Fn))}))}),5e3))},stopPollingSearchIndexes:Kn})(Lp),Rp=Op;var Hp=n(82162),Fp=n(67219);const Wp={dataService:null},jp=(0,Hp.HY)({aiPipeline:(e=ve,t)=>fe(t,xe)?{...e,status:"fetching",errorMessage:void 0,aiPipelineRequestId:t.requestId}:fe(t,Ee)?401===t.statusCode?{...ve}:{...e,status:"ready",aiPipelineRequestId:null,errorMessage:t.errorMessage,errorCode:t.errorCode}:fe(t,ke)?{...e,status:"success",aiPipelineRequestId:null,lastAIPipelineRequestId:t.requestId}:fe(t,De)?{...e,status:"success",aiPipelineRequestId:null,isInputVisible:!0,isAggregationGeneratedFromQuery:!0,lastAIPipelineRequestId:t.requestId,aiPromptText:t.text}:fe(t,Ce)?{...e,status:"ready",aiPipelineRequestId:null}:fe(t,we)?{...e,isAggregationGeneratedFromQuery:!1}:fe(t,Ie)?{...e,isInputVisible:!0}:fe(t,Se)?{...e,isInputVisible:!1,isAggregationGeneratedFromQuery:!1}:fe(t,Ae)?{...e,status:"success"===e.status?"ready":e.status,aiPromptText:t.text}:e,pipelineMode:(e="builder-ui",t)=>fe(t,Qe)?t.mode:(fe(t,Fe)||fe(t,ke)||fe(t,De))&&t.syntaxErrors.length>0?"as-text":e,stageEditor:(e={stagesIdAndType:[],stages:[]},t)=>{if(fe(t,Fe)||fe(t,an.NewPipelineConfirmed)||fe(t,Qe)||fe(t,ke)||fe(t,De)){const e=t.stages.map(((e,t)=>Bt(e,t)));return{stagesIdAndType:zt(e),stages:e}}if(fe(t,ot)||fe(t,dt))return{...e,stages:[...e.stages.slice(0,t.id),{...e.stages[t.id],serverError:null,loading:!0,stageMetadata:null},...e.stages.slice(t.id+1)]};if(fe(t,st))return{...e,stages:[...e.stages.slice(0,t.id),{...e.stages[t.id],loading:!1,previewDocs:null,stageMetadata:null,serverError:null},...e.stages.slice(t.id+1)]};if(fe(t,lt)||fe(t,ut))return{...e,stages:[...e.stages.slice(0,t.id),{...e.stages[t.id],loading:!1,previewDocs:t.previewDocs,stageMetadata:t.stageMetadata,serverError:null},...e.stages.slice(t.id+1)]};if(fe(t,ct)||fe(t,pt))return{...e,stages:[...e.stages.slice(0,t.id),...e.stages.slice(t.id).map((e=>({...e,loading:!1,previewDocs:null,serverError:t.error})))]};if(fe(t,mt))return{...e,stages:[...e.stages.slice(0,t.id),{...e.stages[t.id],previewDocs:null,value:t.stage.value,syntaxError:t.stage.syntaxError,empty:t.stage.isEmpty,fromSnippet:!1},...e.stages.slice(t.id+1)]};if(fe(t,gt))return{...e,stages:[...e.stages.slice(0,t.id),{...e.stages[t.id],previewDocs:null,stageOperator:t.stage.operator,syntaxError:t.stage.syntaxError,empty:t.stage.isEmpty,fromSnippet:t.newSnippet},...e.stages.slice(t.id+1)]};if(fe(t,ft))return{...e,stages:[...e.stages.slice(0,t.id),{...e.stages[t.id],serverError:null,previewDocs:null,disabled:t.disabled},...e.stages.slice(t.id+1)]};if(fe(t,ht))return{...e,stages:[...e.stages.slice(0,t.id),{...e.stages[t.id],collapsed:t.collapsed},...e.stages.slice(t.id+1)]};if(fe(t,yt)){const n=t.after,a=[...e.stages];return a.splice(n+1,0,t.stage),{...e,stagesIdAndType:zt(a),stages:a.map(At())}}if(fe(t,bt)||fe(t,Et)){const n=[...e.stages];return n.splice(t.at,1),{...e,stagesIdAndType:zt(n),stages:n.map(At())}}if(fe(t,vt)){const n=[...e.stages],a=n.splice(t.from,1)[0];return n.splice(t.to,0,a),{...e,stagesIdAndType:zt(n),stages:n.map(At())}}if(fe(t,xt)){const{after:n,wizard:a}=t,r=[...e.stages];return r.splice(n+1,0,a),{...e,stages:r,stagesIdAndType:zt(r)}}if(fe(t,Ct)){const{at:n,value:a,syntaxError:r}=t,i=[...e.stages.slice(0,n),{...e.stages[n],value:a,syntaxError:r},...e.stages.slice(n+1)];return{...e,stages:i}}if(fe(t,wt)){const n=t.at,a=[...e.stages];return a.splice(n,1,t.stage),{...e,stagesIdAndType:zt(a),stages:a.map(At())}}return e},textEditor:(0,Hp.HY)({pipeline:(e=Vt,t)=>{if(fe(t,Qe)||fe(t,ke)||fe(t,De)||fe(t,Fe)||fe(t,an.NewPipelineConfirmed)){const n=t.pipeline??[];return{...e,serverError:null,pipelineText:t.pipelineText,pipeline:n,syntaxErrors:t.syntaxErrors,isPreviewStale:!1}}if(fe(t,Gt)){const n=t.pipeline??e.pipeline;return{...e,pipelineText:t.pipelineText,pipeline:n,syntaxErrors:t.syntaxErrors}}return fe(t,$t)?{...e,serverError:null,isLoading:!1}:fe(t,_t)?{...e,isPreviewStale:!1,serverError:null,isLoading:!0}:fe(t,Yt)?{...e,serverError:null,isLoading:!1,previewDocs:t.previewDocs,isPreviewStale:!1}:fe(t,Kt)?{...e,serverError:t.serverError,isLoading:!1,isPreviewStale:!0}:e},outputStage:(e=Qd,t)=>fe(t,Gt)||fe(t,Qe)||fe(t,ke)||fe(t,De)||fe(t,Fe)||fe(t,an.NewPipelineConfirmed)?{...Qd}:fe(t,qd)?{isLoading:!0,isComplete:!1,serverError:null}:fe(t,Zd)?{isLoading:!1,isComplete:!0,serverError:null}:fe(t,Jd)?{isLoading:!1,isComplete:!1,serverError:t.serverError}:e})}),Bp=_.L5,zp=c,_p=!0,$p={document_count:void 0,pipeline:void 0};function Yp(e){const{document_count:t,pipeline:n}=e.toJSON();return{document_count:t,pipeline:n}}const Kp="compass-aggregations/collection-stats/CollectionStatsFetched",Gp=(0,Hp.HY)({comments:function(e=!0,t){return fe(t,dr)?t.settings.isCommentMode??e:fe(t,an.NewPipelineConfirmed)||fe(t,ke)||fe(t,De)?_p:fe(t,Fe)?t.storedOptions.comments??_p:e},autoPreview:function(e=!0,t){return fe(t,mr)?t.value:!!fe(t,an.NewPipelineConfirmed)||(fe(t,Fe)?t.storedOptions.autoPreview:e)},dataService:function(e=Wp){return e},inputDocuments:(e=Id,t)=>fe(t,Ed)?{...e,isExpanded:!e.isExpanded}:fe(t,Cd)?{...e,isLoading:!0}:fe(t,wd)?{...e,documents:t.documents,error:t.error,isLoading:!1}:e,namespace:function(e=""){return e},env:function(e=Bp){return e},isTimeSeries:function(e=!1){return e},serverVersion:function(e="4.0.0"){return e},savedPipeline:function(e=We,t){const n=je[t.type];return n?n(e,t):e},name:(e="",t)=>fe(t,Ua)?t.name:fe(t,an.NewPipelineConfirmed)||fe(t,ke)||fe(t,De)?"":fe(t,Fe)?t.storedOptions.name:e,collationString:function(e=Na,t){return fe(t,Da)?Ma(t.value):fe(t,an.NewPipelineConfirmed)?{...Na}:fe(t,Fe)&&t.storedOptions.collationString?Ma(t.storedOptions.collationString):e},id:function(e="",t){return fe(t,Oe)||fe(t,ge)||fe(t,ke)||fe(t,De)||fe(t,an.NewPipelineConfirmed)?(new me.UUID).toString():fe(t,Fe)?t.storedOptions.id:e},isModified:function(e=!1,t){return!!(fe(t,yt)||fe(t,vt)||fe(t,ft)||fe(t,gt)||fe(t,bt)||fe(t,mt)||fe(t,Gt)||fe(t,De)||fe(t,ke))||!(fe(t,ge)||fe(t,an.NewPipelineConfirmed)||fe(t,He))&&e},settings:(e=ur,t)=>fe(t,or)?0==!e.isExpanded&&!0===e.isDirty?{...ur}:{...e,isExpanded:!e.isExpanded}:fe(t,sr)?{...e,isCommentMode:!e.isCommentMode,isDirty:!0}:fe(t,lr)?{...e,sampleSize:t.value,isDirty:!0}:fe(t,cr)?{...e,limit:t.value,isDirty:!0}:fe(t,dr)?{...e,isDirty:!1}:fe(t,an.NewPipelineConfirmed)?{...ur}:e,limit:function(e=10,t){return fe(t,dr)?t.settings.sampleSize??e:fe(t,an.NewPipelineConfirmed)?10:e},largeLimit:function(e=1e5,t){return fe(t,dr)?t.settings.limit??e:fe(t,an.NewPipelineConfirmed)?zp:e},maxTimeMS:(e=null,t)=>fe(t,Ta)?t.maxTimeMS:fe(t,an.NewPipelineConfirmed)?null:e,savingPipeline:function(e=Ja,t){return fe(t,Va)?{...e,name:t.name}:fe(t,Za)?{...e,isOpen:!0,isSaveAs:t.isSaveAs,name:t.name}:fe(t,qa)?{...e,name:"",isOpen:!1}:fe(t,Ua)||fe(t,an.NewPipelineConfirmed)?{...Ja}:e},editViewName:function(e=null){return e},sourceName:function(e=null){return e},outResultsFn:function(e=null){return e},updateViewError:function(e=null,t){return fe(t,Zn)?t.error:fe(t,Jn)||fe(t,an.NewPipelineConfirmed)?null:e},aggregation:(e=hn,t)=>fe(t,In.WorkspaceChanged)||fe(t,an.NewPipelineConfirmed)?hn:fe(t,ln)?{...e,pipeline:t.pipeline}:fe(t,cn)?{...e,loading:!0,error:void 0,documents:[],abortController:t.abortController,previousPageData:{page:e.page,documents:e.documents,isLast:e.isLast}}:fe(t,dn)?{...e,isLast:t.isLast,page:t.page,documents:t.documents,loading:!1,abortController:void 0,error:void 0,previousPageData:void 0}:fe(t,un)?{...e,documents:[],loading:!1,abortController:void 0,error:t.error,page:t.page,previousPageData:void 0}:fe(t,pn)?{...e,loading:!1,abortController:void 0,documents:e.previousPageData?.documents||[],page:e.previousPageData?.page||1,isLast:e.previousPageData?.isLast||!1,previousPageData:void 0}:fe(t,mn)?{...e,isLast:!0,loading:!1,page:t.page}:fe(t,gn)?{...e,resultsViewType:t.viewType}:e,workspace:(e=Sn,t)=>fe(t,In.WorkspaceChanged)?t.view:fe(t,ln)?"results":fe(t,an.NewPipelineConfirmed)?Sn:e,countDocuments:(e=Cn,t)=>fe(t,In.WorkspaceChanged)||fe(t,an.NewPipelineConfirmed)?Cn:fe(t,vn)?{loading:!0,count:e.count,abortController:t.abortController}:fe(t,xn)?{loading:!1,abortController:void 0,count:t.count}:fe(t,En)?{...e,loading:!1,abortController:void 0}:e,aggregationWorkspaceId:(e=(new me.UUID).toHexString())=>e,isDataLake:(e=!1)=>e,pipelineBuilder:jp,focusMode:function(e=Ri,t){return fe(t,Pi)?{isEnabled:!0,stageIndex:t.stageIndex,openedAt:Date.now()}:fe(t,Li)?{isEnabled:!1,stageIndex:-1,openedAt:null}:fe(t,Oi)?{...e,stageIndex:t.index}:e},sidePanel:function(e={isPanelOpen:!1},t){return fe(t,gr)?{...e,isPanelOpen:!e.isPanelOpen}:e},collectionsFields:function(e=yl,t){return fe(t,gl)?t.data:fe(t,fl)?{...e,[t.collection]:t.data}:fe(t,hl)?{...e,[t.collection]:{isLoading:!1,fields:t.fields,type:t.collectionType}}:e},insights:(e=at,t)=>fe(t,nt)?{...e,isCollectionScan:t.explainPlan.isCollectionScan}:fe(t,an.NewPipelineConfirmed)||fe(t,ke)||fe(t,De)||fe(t,Fe)?{...at}:e,searchIndexes:(e=_n,t)=>fe(t,jn)?{...e,status:t.reason===Fn?On:Ln}:fe(t,Bn)?{...e,indexes:t.indexes,status:Rn}:fe(t,zn)?{...e,status:e.status===Ln?"ERROR":Rn}:e,collectionStats:(e=$p,t)=>fe(t,Kp)?{...Yp(t.collection)}:e});var Vp=n(56872),Up=n(69044);const qp=Symbol("disabled");function Zp(e,t){e[qp]=t}function Jp(e,t=!1){try{return em(e,t),!0}catch{return!1}}function Qp(e){return"Identifier"===e.type?e.name:"StringLiteral"===e.type?e.value:null}const Xp={InvalidStage:"InvalidStage",NotObjectExpression:"NotObjectExpression",NoStageOperator:"NoStageOperator",UnrecognizedStageName:"UnrecognizedStageName",NoStageValue:"NoStageValue",InvalidStageValue:"InvalidStageValue"};function em(e,t=!1){let n=null,a=Xp.InvalidStage,r=e;if(e&&"ObjectExpression"===e.type)if(1!==e.properties.length||"ObjectProperty"!==e.properties[0].type||null==e.properties[0].key)n="A pipeline stage specification object must contain exactly one field.",a=Xp.NoStageOperator,r=e.properties[0]??r;else if(Qp(e.properties[0].key)?.startsWith("$"))t||null!=e.properties[0].value?t||function(e){if(e)try{return U(V(e)),!0}catch{return!1}return!1}(e)||(n="Stage value is invalid",a=Xp.InvalidStageValue,r=e.properties[0].value):(n="Stage value can not be empty",a=Xp.NoStageValue,r=e.properties[0].key);else{const t=Qp(e.properties[0].key)??"";n="Unrecognized pipeline stage name"+(t?`: '${t}'`:""),a=Xp.UnrecognizedStageName,r=e.properties[0].key}else n="Each element of the pipeline array must be an object",a=Xp.NotObjectExpression;if(n)throw new G(n,r?.loc?.start,a)}function tm(e){return e.toString().trim().split("\n").map((e=>({type:"CommentLine",value:` ${e.replace(/^\s*\/\/\s/,"")}`})))}class nm{source="";maybeObject=!1;push(e){if(this.maybeObject=this.maybeObject||/^\s*\{/.test(e),this.source+=(this.maybeObject||/^\s*\/\//.test(e)?e:`// ${e}`)+"\n",!this.maybeObject)return!1;try{const e=Up.YK(this.source.replace(/\}(,(\s*\{.*?)?|;)(\s*)$/,"}"));if(Jp(e)){const{groups:t}=this.source.match(/\}(,(?<newObject>\s*\{.*?)?|;)(\s*)$/)??{};return this.source=t?.newObject??"",this.maybeObject=!!t?.newObject,e}return this.source=this.source.trimEnd().split("\n").map((e=>/^\s*\/\//.test(e)?e:`// ${e}`)).join("\n")+"\n",this.maybeObject=!1,!1}catch{return!1}}}function am(e){const t=[],n=new Set,a=function(e){const t=[];let n=0;for(const a of e)"CommentBlock"===a.type?(t.push(a),n++):(t[n]??=[],t[n].push(a));return t}(e);for(const e of a){const a=Array.isArray(e)?e.map((e=>({value:e.value.replace(/^\s/,""),node:e}))):e.value.split("\n").map((t=>({value:t.replace(/^\s*\*/,""),node:e}))),r=new nm;let i=[];for(const e of a){i.push(e.node);const a=r.push(e.value);a&&(Zp(a,!0),t.push(a),i.forEach((e=>{n.add(e)})),i=[])}}return[n,t]}class rm{static parse(e){const t=[],n=rm._parseStringToRoot(e);if(0===n.elements.length&&n.innerComments?.length){const[e,a]=am(n.innerComments);0!==a.length&&(a[a.length-1].trailingComments=n.innerComments.filter((t=>!e.has(t))),function(e){e.forEach(((t,n)=>{om(t,e[n-1]?.loc?.end.line??0)}))}(a),delete n.innerComments),t.push(...a)}return n.elements.forEach((e=>{t.push(...function(e){const[t,n]=am(e.leadingComments??[]);e.leadingComments=e.leadingComments?.filter((e=>!t.has(e)));const[a,r]=am(e.trailingComments??[]);return e.trailingComments=e.trailingComments?.filter((e=>!a.has(e))),[...n,e,...r]}(e))})),{root:n,stages:t}}static _parseStringToRoot(e){const t=Up.YK(e);if("ArrayExpression"!==t.type)throw new G("Pipeline must be an array of aggregation stages");return t}static validate(e){let t=null;const n=[];try{t=rm._parseStringToRoot(e),t.elements.forEach((e=>{try{em(e)}catch(e){n.push(e)}}))}catch(e){n.push(e)}return{root:t,errors:n}}static generate(e,t){const n=t.length&&t.every((e=>e.disabled));return n?(e.elements=[],e.innerComments=t.flatMap((e=>tm(e)))):e.elements=rm._getStageNodes(t),V(e)}static _getStageNodes(e){const t=[];let n=[];for(const a of e){if(a.disabled){const e=tm(a);n.push(...e);continue}const e=a.node;n.length&&(e.leadingComments=[...n,...e.leadingComments??[]],n=[]),om(e,(t[t.length-1]?.loc?.end.line??0)+1),t.push(e)}const a=t[t.length-1];if(a&&n.length>0){a.trailingComments=[...a.trailingComments??[],...n];const e=a.trailingComments[0];e&&(e.loc=im((a.loc?.end.line??0)+1))}return t}}function im(e){return{start:{line:e,column:0},end:{line:e,column:0}}}function om(e,t){for(const n of e.leadingComments??[])n.loc=im(++t);e.loc=im(++t);for(const n of e.trailingComments??[])n.loc=im(++t)}function sm({key:e,value:t}={}){return{type:"ObjectExpression",properties:[{type:"ObjectProperty",...e&&{key:{type:"Identifier",name:e}},...t&&{value:Up.YK(t)},computed:!1,shorthand:!1}]}}class lm{id=et();node;disabled=!1;syntaxError=null;operator=null;value=null;constructor(e={type:"ObjectExpression",properties:[]}){this.node=e,this.disabled=function(e){return!!e[qp]}(e);try{em(e),this.operator=function(e){return"Identifier"===e.properties[0].key.type?e.properties[0].key.name:e.properties[0].key.value}(e),this.value=function(e){const t=e.properties[0],n=t.value;return t.trailingComments&&(n.trailingComments=[...n.trailingComments??[],...t.trailingComments??[]],delete t.trailingComments),V(n)}(e)}catch(e){this.syntaxError=e}}get isEmpty(){return!(this.syntaxError&&this.syntaxError.code!==Xp.NoStageOperator||this.operator?.trim()||this.value?.trim())}changeValue(e){this.value=e;try{Jp(this.node,!0)?this.node.properties[0].value=Up.YK(e):this.node=sm({value:e}),em(this.node),this.syntaxError=null}catch(e){this.syntaxError=e}return this}changeOperator(e){this.operator=e;try{Jp(this.node,!0)?this.node.properties[0].key={type:"Identifier",name:e}:this.node=sm({key:e}),em(this.node),this.syntaxError=null}catch(e){this.syntaxError=e}return this}changeDisabled(e){return Zp(this.node,e),this.disabled=e,this}toString(){let e="";if(this.syntaxError){const t=Vp.objectExpression(this.isEmpty?[]:[Vp.objectProperty(Vp.identifier("$$_STAGE_OPERATOR"),Vp.identifier("$$_STAGE_VALUE"))]);t.leadingComments=this.node.leadingComments,t.trailingComments=this.node.trailingComments,Vp.isObjectExpression(this.node)&&this.node.properties[0]&&t.properties[0]&&(t.properties[0].leadingComments=this.node.properties[0].leadingComments,t.properties[0].trailingComments=this.node.properties[0].trailingComments),e=V(t).replace("$$_STAGE_OPERATOR",this.operator??"").replace("$$_STAGE_VALUE",this.value??"")}else e=V(this.node);return this.disabled?e.split("\n").map((e=>/^\s*\/\//.test(e)?e:`// ${e}`)).join("\n"):e}toBSON(){return this.disabled?null:U(this.toString())}}const cm="[]",dm=1/0;class um{source=cm;_node=null;_pipeline=null;_syntaxError=[];_stages=[];previewManager;constructor(e,t,n=cm){this.previewManager=new Ze(e,t),this.changeSource(n),this.sourceToStages()}isEmptySource(){return""===this.source.trim()}get node(){return this.isEmptySource()?Vp.arrayExpression():this._node}set node(e){this._node=e}get pipeline(){return this.isEmptySource()?[]:this._pipeline}set pipeline(e){this._pipeline=e}get syntaxError(){return this.isEmptySource()?[]:this._syntaxError}set syntaxError(e){this._syntaxError=e}get stages(){return this.isEmptySource()?[]:this._stages}set stages(e){this._stages=e}get nonEmptyStages(){return this.stages.filter((e=>!e.isEmpty))}parseSourceToPipeline(){try{if(this.pipeline=U(this.source),!Array.isArray(this.pipeline))throw new Error("Pipeline should be an array")}catch{this.pipeline=null}}reset(e=cm){this.pipeline=[],this.stages=[],this.syntaxError=[],this.changeSource(e),this.sourceToStages()}changeSource(e){this.source=e,this.parseSourceToPipeline(),this.validateSource()}sourceToStages(){try{const{root:e,stages:t}=rm.parse(this.source);this.node=e,this.stages=t.map((e=>new lm(e))),this.syntaxError=this.stages.map((e=>e.syntaxError)).filter(Boolean)}catch(e){this.syntaxError=[e]}}validateSource(){const{root:e,errors:t}=rm.validate(this.source);this.node=e,this.syntaxError=t}getPipelineFromSource(){if(this.syntaxError.length>0)throw this.syntaxError[0];if(null===this.pipeline)throw new G("Invalid pipeline");return this.pipeline}stagesToSource(){if(!this.node)throw new Error("Trying to generate source from stages with invalid pipeline");this.changeSource(rm.generate(this.node,this.nonEmptyStages))}getStage(e){return this.stages[e]}addStage(e=this.stages.length-1){const t=new lm;return this.stages.splice(e+1,0,t),t}removeStage(e){return this.stages.splice(e,1)[0]}moveStage(e,t){const n=this.stages.splice(e,1)[0];return this.stages.splice(t,0,n),n}getPipelineStringFromStages(e=this.nonEmptyStages){const t=`[${e.map((e=>e.toString())).join(",\n")}\n]`,n=e.find((e=>!e.disabled&&e.syntaxError));return n?t:(0,K.G8)(t)}getPipelineStringFromSource(){return this.syntaxError.length>0?this.source:(0,K.G8)(this.source)}getPipelineFromStages(e=this.nonEmptyStages){return U(this.getPipelineStringFromStages(e))}stopPreview(e){this.previewManager.clearQueue(e)}cancelPreviewForStage(e){this.previewManager.cancelPreviewForStage(e)}cancelPreviewForPipeline(){this.cancelPreviewForStage(dm)}getPreviewForStage(e,t,n,a=!1){return this.previewManager.getPreviewForStage(e,t,this.getPipelineFromStages(this.stages.slice(0,e+1)),n,a)}isLastStagePreviewEqual(e,t=this.getPipelineFromStages(this.stages.slice(0,e+1))){return this.previewManager.isLastPipelineEqual(e,t)}getPreviewForPipeline(e,t,n=!1){const a=[...this.getPipelineFromSource()];return n&&de(a)&&a.pop(),this.previewManager.getPreviewForStage(dm,e,a,t)}isLastPipelinePreviewEqual(e=this.getPipelineFromSource(),t=!1){return e=[...e],t&&de(e)&&e.pop(),this.previewManager.isLastPipelineEqual(dm,e)}}const pm={connectionId:"",isRunning:!1,isVisible:!1,isDuplicating:!1,name:"",error:null,source:"",pipeline:[]},mm="aggregations/create-view/Open",gm="aggregations/create-view/Close",hm="aggregations/create-view/is-running/ToggleIsRunning",fm="aggregations/create-view/error/HandleError",ym="aggregations/create-view/error/ClearError",bm="aggregations/create-view/name/ChangeName",vm="aggregations/create-view/reset",xm=e=>({type:hm,isRunning:e}),Em=(e=pm,t)=>fe(t,vm)||fe(t,gm)?{...pm}:fe(t,mm)?{...e,...pm,isVisible:!0,connectionId:t.connectionId,isDuplicating:t.duplicate,source:t.source,pipeline:t.pipeline}:fe(t,hm)?{...e,isRunning:t.isRunning}:fe(t,bm)?{...e,name:t.name}:fe(t,fm)?{...e,error:t.error}:fe(t,ym)?{...e,error:null}:e,Cm=(0,s.AHW)({display:"flex",gap:s.YKD[200],alignItems:"center"}),wm=(0,o.Ng)((e=>({isRunning:e.isRunning,isVisible:e.isVisible,isDuplicating:e.isDuplicating,name:e.name,error:e.error?.message??null,source:e.source,pipeline:e.pipeline,connectionId:e.connectionId})),{createView:()=>async(e,t,{globalAppRegistry:n,connections:a,track:r,workspaces:i})=>{const{name:o,source:s,pipeline:l,connectionId:c}=t(),{database:d}=(0,z.Ay)(s),u={};e({type:ym});try{const t=a.getDataServiceForConnection(c);e(xm(!0)),await t.createView(o,s,l,u);const p=`${d}.${o}`;r("Aggregation Saved As View",{num_stages:l.length},a.getConnectionById(c)?.info),n.emit("view-created",p,{connectionId:c}),i.openCollectionWorkspace(c,p,{newTab:!0}),e({type:vm})}catch(t){e((p=t,e=>{e(xm(!1)),e({type:fm,error:p})}))}var p},changeViewName:e=>({type:bm,name:e}),closeModal:()=>({type:gm})})((({createView:e,isVisible:t,closeModal:n,name:i,changeViewName:o,isDuplicating:l,connectionId:c,isRunning:d,error:u})=>{const p=(0,O.Jr)(),{getConnectionById:m}=(0,Wr.cy)();return(0,a.useEffect)((()=>{t&&c&&p("Screen",{name:"create_view_modal"},m(c)?.info)}),[t,c,m,p]),r().createElement(s.k5W,{title:l?"Duplicate View":"Create a View",open:t,onSubmit:e,onCancel:n,submitButtonText:"Create","data-testid":"create-view-modal"},r().createElement(s.ksK,{"data-testid":"create-view-name",value:i||"",onChange:e=>{o(e.currentTarget.value)},label:"Name",name:"name"}),u?r().createElement(s.lZ$,{variant:"danger"},u):null,d?r().createElement(s.nBu,{className:Cm},r().createElement(s.Q0K,null),r().createElement("span",null,"Creating view…")):null)}));var Im=n(44457),Sm=n(45363),Am=n(2155);const km=(0,i.nk)({name:"CompassAggregations",component:function({children:e}){return r().createElement(r().Fragment,null,e)},activate:function(e,{dataService:t,localAppRegistry:n,globalAppRegistry:a,workspaces:r,instance:i,preferences:o,logger:s,track:l,atlasAiService:c,pipelineStorage:d,connectionInfoRef:u,connectionScopedAppRegistry:p,collection:m},{on:g,cleanup:h,addCleanup:f}){if(e.editViewName&&!e.pipeline)throw new Error("Option `editViewName` can be used only if `pipeline` is provided");const y=!(!e.editViewName||!e.pipeline),b=(e.pipeline?(0,ka.AO)(e.pipeline):e.pipelineText)??void 0,{collection:v}=(0,z.Ay)(e.namespace);if(!v)throw new Error("Aggregation plugin doesn't support database namespaces");const x=new um(t,o,b),E=x.stages.map(((e,t)=>Bt(e,t))),C=zt(E),w=(0,Hp.y$)(Gp,{dataService:{dataService:t},namespace:e.namespace,serverVersion:e.serverVersion,isTimeSeries:e.isTimeSeries,isDataLake:e.isDataLake,env:e.env??i.env,outResultsFn:e.outResultsFn,pipelineBuilder:{stageEditor:{stages:E,stagesIdAndType:C}},sourceName:e.sourceName,editViewName:e.editViewName,searchIndexes:{..._n,isSearchIndexesSupported:Boolean(e.isSearchIndexesSupported)},sidePanel:{isPanelOpen:"true"===localStorage.getItem(hr)},collectionStats:Yp(m)},(0,Hp.Tw)(Fp.A.withExtraArgument({globalAppRegistry:a,localAppRegistry:n,pipelineBuilder:x,pipelineStorage:d?.getStorage(),workspaces:r,instance:i,preferences:o,logger:s,track:l,atlasAiService:c,connectionInfoRef:u,connectionScopedAppRegistry:p,dataService:t,collection:m,pollingIntervalRef:{searchIndexes:null}}))),I=()=>{w.dispatch(Ad())};g(n,"generate-aggregation-from-query",(e=>{w.dispatch((({aggregation:e,userInput:t,requestId:n})=>(a,r,{pipelineBuilder:i})=>{const o=String(e?.pipeline);i.reset(o),a({type:De,stages:i.stages,pipelineText:i.source,pipeline:i.pipeline,syntaxErrors:i.syntaxError,text:t,requestId:n}),a(Zt())})(e))})),g(a,"refresh-data",(()=>{I()})),g(a,"import-finished",(({ns:e},{connectionId:t}={})=>{const{id:n}=u.current,{namespace:a}=w.getState();n===t&&e===a&&I()})),g(m,"change:status",((e,t)=>{"ready"===t&&w.dispatch((e=>({type:Kp,collection:e}))(e))})),!y&&e.aggregation&&w.dispatch(ze(e.aggregation,!1)),f(((e,t,n)=>{const{namespace:a,collections:r}=t;r&&r.length>0&&e.dispatch(bl(r));const i=(0,z.Ay)(a),o=n?.databases?.get(i.database);if(!o)return()=>{};const s=t=>{const n=t.collections.map((e=>({name:(0,z.Ay)(e._id).collection,type:e.type})));e.dispatch(bl(n??[]))};return s(o),o.on("change:collectionsStatus",s),()=>o.removeListener("change:collectionsStatus",s)})(w,e,i)),e.fields&&w.dispatch(((e,t,n)=>({type:hl,collection:e,fields:n,collectionType:t}))(v,e.sourceName?"view":"collection",e.fields.map((e=>e.name)))),I(),w.dispatch(Zt()),w.dispatch(Pa(o.getPreferences().maxTimeMS||null));const S=()=>!w.getState().isModified;return f(r.onTabReplace?.(S)),f(r.onTabClose?.(S)),f((()=>{w.dispatch(Kn())})),{store:w,deactivate:h}}},{dataService:Wr.S1,workspaces:Sm.__,instance:Im.A$,preferences:g.fx,logger:(0,ye.fF)("COMPASS-AGGREGATIONS-UI"),track:O.yL,atlasAiService:F.Dr,pipelineStorage:Am.oC,connectionInfoRef:Wr.wj,collection:Im.KK,connectionScopedAppRegistry:Wr.Do}),Dm={name:"Aggregations",provider:km,content:()=>{const e=(0,g.Fg)("enableAggregationBuilderRunPipeline"),t=(0,g.Fg)("enableExplainPlan");return r().createElement(s.ETl,null,r().createElement(Rp,{showRunButton:e,showExplainButton:t}))},header:function(){return r().createElement("div",{"data-testid":"aggregations-tab-title"},"Aggregations")}},Nm=(0,i.nk)({name:"CreateView",component:wm,activate:function(e,{globalAppRegistry:t,connections:n,logger:a,track:r,workspaces:i},{on:o,cleanup:s}){const l=(c={globalAppRegistry:t,connections:n,logger:a,track:r,workspaces:i},(0,Hp.y$)(Em,(0,Hp.Tw)(Fp.A.withExtraArgument(c))));var c;return o(t,"open-create-view",(function(e,t={}){if(!t.connectionId)throw new Error("Cannot open CreateViewModal without a connectionId");l.dispatch((({connectionId:e,sourceNs:t,sourcePipeline:n,duplicate:a})=>({type:mm,connectionId:e,source:t,pipeline:n,duplicate:a}))({connectionId:t.connectionId,sourceNs:e.source,sourcePipeline:e.pipeline,duplicate:e.duplicate??!1}))})),{store:l,deactivate:s}}},{connections:Wr.u4,logger:(0,ye.fF)("COMPASS-CREATE-VIEW-UI"),track:O.yL,workspaces:Sm.__})},70724:(e,t,n)=>{n.d(t,{Fv:()=>le,Jn:()=>me,hK:()=>Le,MM:()=>Ie,Xv:()=>$e,rq:()=>Oe,xG:()=>Te,g7:()=>Me,G8:()=>s,Tf:()=>ct});var a=n(681),r=n.n(a),i=n(29928),o=n.n(i);function s(e,t="javascript-expression",n={}){return r().format(e,{plugins:[o()],printWidth:50,parser:"javascript-expression"===t?"__js_expression":"json"===t?"json":"babel",trailingComma:"none",...n}).trim()}var l=n(55712),c=(n(95039),n(96652)),d=n.n(c),u=n(9283),p=n(10906),m=n(64710),g=n(93732),h=n(22756),f=n(51295),y=n(60262),b=n(90345),v=n(38273),x=n(74208),E=n(20327);const C=(0,f.AHW)({flex:"none",pointerEvents:"all"}),w=(0,f.AHW)({"& > div:has(svg)":{paddingLeft:3,paddingRight:3}}),I=(0,f.AHW)({position:"relative"}),S=(0,f.AHW)({opacity:1,width:14,height:14,transition:"opacity .2s linear"}),A=(0,f.AHW)({opacity:0}),k=(0,f.AHW)({position:"absolute",width:14,height:14,top:0,pointerEvents:"none",opacity:1,transition:"opacity .2s linear"}),D=(0,f.AHW)({opacity:0}),N=({label:e,icon:t,onClick:n,compact:a,...r})=>{const[i,o]=(0,c.useState)("success"),[s,l]=(0,c.useState)(!1),u=(0,c.useCallback)(((...e)=>{const t=n?.(...e);"boolean"==typeof t&&(o(t?"success":"error"),l(!0))}),[n]);return(0,c.useEffect)((()=>{if(!s)return;const e=setTimeout((()=>{l(!1)}),1e3);return()=>{clearTimeout(e)}}),[s]),d().createElement(f.$nd,{size:"xsmall","aria-label":e,title:e,onClick:u,className:(0,f.cx)(C,{[w]:a}),"data-testid":r["data-testid"]??`editor-action-${e}`},d().createElement("div",{className:I},d().createElement("div",{className:(0,f.cx)(S,s&&A)},"string"==typeof t?d().createElement(f.Int,{size:"small",role:"presentation",title:null,glyph:t}):t),d().createElement("div",{className:(0,f.cx)(k,!s&&D)},d().createElement(f.Int,{size:"small",glyph:"success"===i?"Checkmark":"X"}))))},M=({size:e=16,...t})=>d().createElement("svg",(0,l.A)({xmlns:"http://www.w3.org/2000/svg",fill:"none",width:e,height:e,viewBox:"0 0 16 16"},t),d().createElement("path",{fill:"currentColor",d:"M2 4a1 1 0 0 1 1-1h2a1 1 0 1 1 0 2H3a1 1 0 0 1-1-1Zm0 4a1 1 0 0 1 1-1h6a1 1 0 1 1 0 2H3a1 1 0 0 1-1-1Zm1 3a1 1 0 1 0 0 2h10a1 1 0 1 0 0-2H3Zm4-7a1 1 0 0 1 1-1h5a1 1 0 1 1 0 2H8a1 1 0 0 1-1-1Zm4 4a1 1 0 0 1 1-1h1a1 1 0 1 1 0 2h-1a1 1 0 0 1-1-1Z"})),T=(0,f.AHW)({position:"absolute",top:f.YKD[100],right:f.YKD[100],left:f.YKD[100],display:"none",gap:f.YKD[200],pointerEvents:"none"}),P=(0,f.AHW)({position:"relative",top:-f.YKD[100],left:-f.YKD[100]}),L=(0,f.AHW)({flex:"1 0 auto",pointerEvents:"none"}),O=({copyable:e,formattable:t,customActions:n,className:a,editorRef:r,onExpand:i,expanded:o})=>d().createElement("div",{className:(0,f.cx)("multiline-editor-actions",T,a)},i&&d().createElement("div",{className:P},d().createElement(N,{label:o?"Collapse all":"Expand all",icon:o?"CaretDown":"CaretRight",onClick:i,compact:!0})),d().createElement("span",{className:L}),e&&d().createElement(N,{label:"Copy",icon:"Copy",onClick:()=>r.current?.copyAll()??!1}),t&&d().createElement(N,{label:"Format",icon:d().createElement(M,{size:14,role:"presentation"}),onClick:()=>r.current?.prettify()??!1}),n&&n.map((e=>d().createElement(N,{key:e.label,icon:e.icon,label:e.label,onClick:()=>!!r.current?.editor&&e.action(r.current.editor)})))),R=(0,f.AHW)({fontSize:13,fontFamily:f.aIi.code}),H=(0,f.AHW)({borderRadius:f.YKD[100],boxShadow:`0 0 0 1px ${f.MFm.gray.light1}`}),F=(0,f.AHW)({boxShadow:`0 0 0 1px ${f.MFm.gray.dark2}`}),W=(0,f.AHW)({"& .cm-cursor":{display:"none !important"}}),j=(0,f.AHW)({"& .cm-scroller":{overflow:"-moz-scrollbars-none",msOverflowStyle:"none"},"& .cm-scroller::-webkit-scrollbar":{display:"none"}});function B(e){return e.facet(v.$t.readOnly)}const z=[{key:"Tab",run:e=>!B(e.state)&&(0,h.$w)(e)},{key:"Tab",run:({state:e,dispatch:t})=>!B(e)&&!e.selection.ranges.some((e=>!e.empty))&&(t(e.update(e.replaceSelection("\t"),{scrollIntoView:!0,userEvent:"input"})),!0)},m.Yc],_={light:{color:f.pNb.light[3],backgroundColor:f.pNb.light[0],disabledColor:f.pNb.light[2],disabledBackgroundColor:f.pNb.light[1],gutterColor:f.pNb.light[3],gutterBackgroundColor:f.pNb.light[0],gutterActiveLineBackgroundColor:(0,E.B3)(f.MFm.gray.light2,.5),gutterFoldButtonColor:f.MFm.black,cursorColor:f.MFm.gray.base,activeLineBackgroundColor:(0,E.B3)(f.MFm.gray.light2,.5),selectionBackgroundColor:f.MFm.blue.light2,bracketBorderColor:f.MFm.gray.light1,infoGutterIconColor:encodeURIComponent(f.MFm.blue.base),warningGutterIconColor:encodeURIComponent(f.MFm.yellow.base),errorGutterIconColor:encodeURIComponent(f.MFm.red.base),foldPlaceholderColor:f.MFm.gray.base,foldPlaceholderBackgroundColor:f.MFm.gray.light3,autocompleteColor:f.MFm.black,autocompleteBackgroundColor:f.MFm.white,autocompleteBorderColor:f.MFm.gray.light2,autocompleteMatchColor:f.MFm.green.dark1,autocompleteSelectedBackgroundColor:f.MFm.gray.light2},dark:{color:f.pNb.dark[3],backgroundColor:f.pNb.dark[0],disabledColor:f.pNb.dark[3],disabledBackgroundColor:f.MFm.gray.dark3,gutterColor:f.pNb.dark[3],gutterBackgroundColor:f.pNb.dark[0],gutterActiveLineBackgroundColor:(0,E.B3)(f.MFm.gray.dark2,.5),gutterFoldButtonColor:f.MFm.white,cursorColor:f.MFm.green.base,activeLineBackgroundColor:(0,E.B3)(f.MFm.gray.dark2,.5),selectionBackgroundColor:f.MFm.gray.dark2,bracketBorderColor:f.MFm.gray.light1,infoGutterIconColor:encodeURIComponent(f.MFm.blue.light1),warningGutterIconColor:encodeURIComponent(f.MFm.yellow.light2),errorGutterIconColor:encodeURIComponent(f.MFm.red.light1),foldPlaceholderColor:f.MFm.gray.base,foldPlaceholderBackgroundColor:f.MFm.gray.dark3,autocompleteColor:f.MFm.gray.light1,autocompleteBackgroundColor:f.MFm.gray.dark4,autocompleteBorderColor:f.MFm.gray.dark1,autocompleteMatchColor:f.MFm.gray.light3,autocompleteSelectedBackgroundColor:f.MFm.gray.dark2}},$={fontSize:"13px",fontFamily:f.aIi.code};function Y(e){return u.Lz.theme({"&":{color:_[e].color,backgroundColor:_[e].backgroundColor,maxHeight:"100%"},"& .cm-scroller":$,"&.cm-editor.cm-focused":{outline:"none"},"& .cm-content":{paddingTop:`${f.YKD[100]}px`,paddingBottom:`${f.YKD[100]}px`,caretColor:_[e].cursorColor},'[contenteditable="false"] ':{borderRadius:`${f.YKD[100]}px`},'.cm-content[contenteditable="false"] ':{cursor:"not-allowed",color:_[e].disabledColor,backgroundColor:_[e].disabledBackgroundColor},"& .cm-activeLine":{background:"none"},"&.cm-focused .cm-activeLine":{backgroundColor:_[e].activeLineBackgroundColor},"& .cm-gutters":{color:_[e].gutterColor,backgroundColor:_[e].gutterBackgroundColor,border:"none"},"& .cm-gutter-lint":{width:`${f.YKD[400]}px`},"& .cm-gutter-lint .cm-gutterElement":{padding:"0"},"& .cm-lineNumbers .cm-gutterElement":{userSelect:"none"},"& .cm-gutter-lint .cm-lint-marker":{width:`${f.YKD[400]}px`,height:`${f.YKD[400]}px`,padding:"2px"},"& .cm-gutter-lint .cm-lint-marker-info":{content:`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'%3E%3Cpath fill='${_[e].infoGutterIconColor}' fill-rule='evenodd' d='M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14ZM9 4a1 1 0 1 1-2 0 1 1 0 0 1 2 0ZM8 6a1 1 0 0 1 1 1v4h.5a.5.5 0 0 1 0 1h-3a.5.5 0 0 1 0-1H7V7h-.5a.5.5 0 0 1 0-1H8Z' clip-rule='evenodd'/%3E%3C/svg%3E%0A")`},"& .cm-gutter-lint .cm-lint-marker-warning":{content:`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'%3E%3Cpath fill='${_[e].warningGutterIconColor}' fill-rule='evenodd' d='M8.864 2.514a.983.983 0 0 0-1.728 0L1.122 13.539A.987.987 0 0 0 1.986 15h12.028a.987.987 0 0 0 .864-1.461L8.864 2.514ZM7 6a1 1 0 0 1 2 0v4a1 1 0 1 1-2 0V6Zm2 7a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z' clip-rule='evenodd'/%3E%3C/svg%3E%0A")`},"& .cm-gutter-lint .cm-lint-marker-error":{content:`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'%3E%3Cpath fill='${_[e].errorGutterIconColor}' fill-rule='evenodd' d='M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14zm1.414-9.828a1 1 0 1 1 1.414 1.414L9.414 8l1.414 1.414a1 1 0 1 1-1.414 1.414L8 9.414l-1.414 1.414a1 1 0 1 1-1.414-1.414L6.586 8 5.172 6.586a1 1 0 0 1 1.414-1.414L8 6.586l1.414-1.414z' clip-rule='evenodd'/%3E%3C/svg%3E%0A")`},"& .cm-activeLineGutter":{background:"none"},"&.cm-focused .cm-activeLineGutter":{backgroundColor:_[e].gutterActiveLineBackgroundColor},"& .cm-foldPlaceholder":{display:"inline-block",border:"none",color:_[e].foldPlaceholderColor,backgroundColor:_[e].foldPlaceholderBackgroundColor,boxShadow:`inset 0 0 0 1px ${_[e].foldPlaceholderColor}`,padding:"0 2px"},"& .foldMarker":{width:`${f.YKD[400]}px`,height:`${f.YKD[400]}px`,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},"& .foldMarker > svg":{width:"12px",height:"12px",display:"block",color:_[e].gutterFoldButtonColor},"& .cm-selectionBackground":{backgroundColor:_[e].selectionBackgroundColor},"&.cm-focused .cm-selectionBackground, ::selection":{backgroundColor:_[e].selectionBackgroundColor},"&.cm-focused .cm-matchingBracket":{background:"none",boxShadow:`0 0 0 1px ${_[e].bracketBorderColor}`,borderRadius:"2px"},"& .cm-selectionBackground:first-child":{borderTopLeftRadius:"3px",borderTopRightRadius:"3px"},"& .cm-selectionBackground:last-child":{borderBottomLeftRadius:"3px",borderBottomRightRadius:"3px"},"& .cm-cursor":{borderLeft:"2px solid",borderColor:_[e].cursorColor,marginLeft:"-1px"},"& .cm-tooltip":{...$,color:_[e].autocompleteColor,backgroundColor:_[e].autocompleteBackgroundColor,border:`1px solid ${_[e].autocompleteBorderColor}`},"& .cm-tooltip.cm-tooltip-autocomplete > ul":{fontFamily:f.aIi.code,boxShadow:`0 ${f.YKD[50]}px ${f.YKD[200]}px rgba(0, 0, 0, 0.25)`},"& .cm-tooltip-autocomplete ul li":{display:"flex"},"& .cm-tooltip-autocomplete ul li[aria-selected]":{color:_[e].autocompleteColor,backgroundColor:_[e].autocompleteSelectedBackgroundColor},"& .cm-completionIcon-query-history":{marginRight:`${f.YKD[200]}px`,"&:after":{content:'""',display:"flex",alignItems:"center",justifyContent:"center",width:"16px",height:"16px",backgroundImage:`url("data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M8 14C11.3137 14 14 11.3137 14 8C14 4.68629 11.3137 2 8 2C4.68629 2 2 4.68629 2 8C2 11.3137 4.68629 14 8 14ZM7.25 4.75C7.25 4.33579 7.58579 4 8 4C8.41421 4 8.75 4.33579 8.75 4.75V7.90966L10.4939 9.43556C10.8056 9.70832 10.8372 10.1821 10.5644 10.4939C10.2917 10.8056 9.81786 10.8372 9.50613 10.5644L7.51059 8.81833C7.5014 8.8104 7.4924 8.80226 7.48361 8.79391C7.41388 8.7278 7.35953 8.65117 7.32087 8.56867C7.27541 8.47195 7.25 8.36394 7.25 8.25V4.75Z' fill='${encodeURIComponent(_[e].autocompleteColor)}'/%3E%3C/svg%3E")`,backgroundSize:"contain",backgroundRepeat:"no-repeat",backgroundPosition:"center"}},"& .cm-completionIcon-favorite":{marginRight:`${f.YKD[200]}px`,"&:after":{content:'""',display:"flex",alignItems:"center",justifyContent:"center",width:"16px",height:"16px",backgroundImage:`url("data:image/svg+xml,%3Csvg width='12' height='12' viewBox='0 0 12 12' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M5.65373 0.832474C5.78183 0.524491 6.21813 0.52449 6.34622 0.832474L7.49904 3.60417C7.55301 3.73401 7.67511 3.82272 7.81528 3.83396L10.8076 4.07385C11.1401 4.1005 11.2749 4.51545 11.0216 4.73244L8.74176 6.68534C8.63496 6.77682 8.58839 6.92036 8.62101 7.05714L9.31746 9.9771C9.39486 10.3015 9.04191 10.558 8.75729 10.3841L6.19545 8.8194C6.07544 8.74612 5.92451 8.74612 5.80451 8.8194L3.2427 10.3841C2.95804 10.558 2.60507 10.3015 2.68246 9.9771L3.37898 7.05714C3.41161 6.92036 3.36497 6.77682 3.25817 6.68534L0.978375 4.73244C0.725048 4.51545 0.859867 4.1005 1.19236 4.07385L4.18464 3.83396C4.32481 3.82272 4.44691 3.73401 4.50092 3.60417L5.65373 0.832474Z' fill='${encodeURIComponent(_[e].autocompleteColor)}'/%3E%3C/svg%3E")`,backgroundSize:"contain",backgroundRepeat:"no-repeat",backgroundPosition:"center"}},"& .cm-completionIcon-field":{marginRight:`${f.YKD[50]}px`,display:"flex",alignItems:"center",justifyContent:"center",width:"16px",height:"16px","&:after":{content:'""',display:"block",width:"13px",height:"11px",backgroundImage:`url("data:image/svg+xml,%3Csvg width='13' height='11' viewBox='0 0 13 11' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M1 4.06383L4.96 5.78723M1 4.06383L7.18333 1.19342C7.44783 1.07064 7.75273 1.06942 8.0182 1.19009L12 3M1 4.06383V7.29287C1 7.66257 1.20398 8.00212 1.53039 8.17574L4.96 10M4.96 5.78723L12 3M4.96 5.78723V10M12 3V6.45563C12 6.86203 11.7541 7.22801 11.3778 7.38153L4.96 10' stroke='${encodeURIComponent(_[e].autocompleteColor)}' stroke-width='1.3'/%3E%3C/svg%3E")`,backgroundSize:"contain",backgroundRepeat:"no-repeat",backgroundPosition:"center"}},"& .cm-completionIcon-method":{marginRight:`${f.YKD[50]}px`,display:"flex",alignItems:"center",justifyContent:"center",width:"16px",height:"16px","&:after":{content:'""',display:"block",width:"13px",height:"13px",backgroundImage:`url("data:image/svg+xml,%3Csvg width='13' height='13' viewBox='0 0 13 13' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cg clip-path='url(%23clip0_914_100226)'%3E%3Cpath d='M1.5 4.13357L6.45 7.11111M1.5 4.13357L5.92043 1.33524C6.2443 1.13022 6.65686 1.12836 6.98256 1.33046L11.5 4.13357M1.5 4.13357V8.26879C1.5 8.60888 1.67284 8.92565 1.95883 9.1097L6.45 12M6.45 7.11111L11.5 4.13357M6.45 7.11111V12M11.5 4.13357V8.26289C11.5 8.6062 11.3239 8.92551 11.0335 9.10868L6.45 12' stroke='${encodeURIComponent(_[e].autocompleteColor)}' stroke-width='1.3'/%3E%3C/g%3E%3Cdefs%3E%3CclipPath id='clip0_914_100226'%3E%3Crect width='13' height='13' fill='white'/%3E%3C/clipPath%3E%3C/defs%3E%3C/svg%3E")`,backgroundSize:"contain",backgroundRepeat:"no-repeat",backgroundPosition:"center"}},"& .cm-completionLabel":{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",lineHeight:"110%",verticalAlign:"middle"},"& .cm-completionDetail":{color:(0,E.B3)(_[e].autocompleteColor,.5),fontStyle:"normal",marginRight:"1em",marginLeft:"1em"},"& .cm-completionMatchedText":{color:_[e].autocompleteMatchColor,fontWeight:"bold",textDecoration:"none"},".cm-tooltip.cm-completionInfo":{boxShadow:`0 ${f.YKD[50]}px ${f.YKD[200]}px rgba(0, 0, 0, 0.25)`,overflow:"auto",marginTop:0,paddingTop:0,fontSize:"12px",maxHeight:5*f.YKD[1600]+"px"},"& .cm-tooltip .completion-info p":{margin:0,marginRight:`${f.YKD[200]}px`,marginTop:`${f.YKD[200]}px`,marginBottom:`${f.YKD[200]}px`},"& .cm-tooltip .completion-info p:first-child":{marginTop:0},"& .cm-tooltip .completion-info p:last-child":{marginBottom:0},"& .cm-widgetBuffer":{verticalAlign:"top"}},{dark:"dark"===e})}const K={light:Y("light"),dark:Y("dark")};function G(e){return p.cr.define([{tag:[x._A.null,x._A.controlKeyword,x._A.operatorKeyword,x._A.definitionKeyword,x._A.moduleKeyword,x._A.keyword,x._A.modifier],color:f.pNb[e][10]},{tag:[x._A.number,x._A.bool,x._A.function(x._A.variableName),x._A.regexp],color:f.pNb[e][9]},{tag:[x._A.string,x._A.special(x._A.string)],color:f.pNb[e][7],fontWeight:600},{tag:[x._A.meta],color:f.pNb[e][6]},{tag:[x._A.propertyName,x._A.atom,x._A.self],color:f.pNb[e][5]},{tag:[x._A.separator,x._A.squareBracket,x._A.brace,x._A.variableName,x._A.definition(x._A.variableName),x._A.updateOperator,x._A.arithmeticOperator,x._A.logicOperator,x._A.bitwiseOperator,x._A.compareOperator,x._A.function(x._A.punctuation),x._A.punctuation,x._A.paren,x._A.derefOperator],color:f.pNb[e][3]},{tag:[x._A.lineComment,x._A.blockComment],color:f.pNb[e][2],fontStyle:"italic"}],{themeType:e})}const V={light:G("light"),dark:G("dark")},U=y.o$.configure({top:"SingleExpression"}),q={json:b.Pq,javascript:y.Q2,"javascript-expression":()=>new p.Yy(U)},Z=v.sj.define({});async function J(e){return new Promise((t=>{setTimeout(t,e)}))}async function Q(e,t,n){return await async function(e,t){for(;0!==e.updateState;){if(t?.aborted)return!1;await J()}return!0}(e,n),t=Array.isArray(t)?t:[t],e.dispatch(...t),!0}function X(e,t,n){const a=(0,f.HIF)(e),r=(0,f.nfZ)((()=>new v.xx)),i=(0,f.nfZ)((()=>r.of(a.current())));return(0,f.qac)((()=>{if(!n.current)return;const e=new AbortController;return Q(n.current,{effects:r.reconfigure(a.current())},e.signal),()=>{e.abort()}}),t),i}const ee=d().forwardRef((function({initialText:e,text:t,onChangeText:n,language:a="json",showLineNumbers:r=!0,showFoldGutter:i=!0,showAnnotationsGutter:o=!0,showScroll:s=!0,highlightActiveLine:y=!0,annotations:b,completer:x,customExtensions:E,darkMode:C,disabled:w=!1,className:I,readOnly:S=!1,onLoad:A=()=>{},onFocus:k=()=>{},onBlur:D=()=>{},onPaste:N=()=>{},minLines:M,maxLines:T,lineHeight:P=16,placeholder:L,commands:O,initialJSONFoldAll:B=!0,autoFocus:_=!1,...$},Y){const G=(0,f.D27)(C),U=(0,f.HIF)(n),J=(0,f.HIF)(A),ee=(0,f.HIF)(k),te=(0,f.HIF)(D),se=(0,f.HIF)(N),le=(0,c.useRef)(!!e),ce=(0,c.useRef)(e??t),de=(0,c.useRef)(a),ue=(0,c.useRef)(null),pe=(0,c.useRef)(null),me=(0,c.useRef)(),[{height:ge,hasScroll:he},fe]=(0,c.useState)({height:0,hasScroll:!1}),ye=(0,c.useRef)(B);(0,c.useImperativeHandle)(Y,(()=>({foldAll:()=>!!me.current&&re(me.current),unfoldAll:()=>!!me.current&&(0,p._I)(me.current),copyAll:()=>!!me.current&&ie(me.current),prettify:()=>!!me.current&&oe(me.current),applySnippet:e=>!!me.current&&ne(me.current,e),focus:()=>!!me.current&&(me.current.focus(),!0),cursorDocEnd:()=>!!me.current&&(0,m.aS)(me.current),startCompletion:()=>!!me.current&&(0,h.rB)(me.current),get editorContents(){return me.current?ae(me.current):null},get editor(){return me.current??null}})),[]);const be=X((()=>[q[a](),Z.of(a)]),a,me),ve=X((()=>!S&&y?[(0,u.dz)(),(0,u.Wu)()]:[]),[S,y],me),xe=X((()=>v.$t.readOnly.of(S)),S,me),Ee=X((()=>u.Lz.editable.of(!w)),w,me),Ce=X((()=>K[G?"dark":"light"]),G,me),we=X((()=>u.Lz.theme({"& .cm-scroller":{lineHeight:`${P}px`,...T&&T<1/0&&{maxHeight:T*P+"px"},height:"100%",overflowY:"auto"},"& .cm-content, & .cm-gutter":{...M&&{minHeight:M*P+"px"}}})),[M,T,P],me),Ie=X((()=>r?(0,u.$K)():[]),r,me),Se=X((()=>i?(0,p.Lv)({markerDOM(e){const t=document.createElement("span");return t.className="foldMarker foldMarker"+(e?"Open":"Closed"),t.ariaHidden="true",t.title=e?"Fold code block":"Unfold code block",t.innerHTML=e?'<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16"><path fill="currentColor" d="M8.679 10.796a.554.554 0 0 1-.858 0L4.64 6.976C4.32 6.594 4.582 6 5.069 6h6.362c.487 0 .748.594.43.976l-3.182 3.82z"/></svg>':'<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16"><path fill="currentColor" d="M10.796 7.321a.554.554 0 0 1 0 .858l-3.82 3.181c-.382.319-.976.058-.976-.429V4.57c0-.487.594-.748.976-.43l3.82 3.182z"/></svg>',t}}):[]),i,me),Ae=o||b&&0===b.length,ke=X((()=>Ae?(0,g.pJ)():[]),Ae,me),De=X((()=>x?(0,h.yU)({activateOnTyping:!0,override:[x],maxRenderedOptions:50}):[]),x,me),Ne=X((()=>L?(0,u.qf)(L):[]),L,me),Me=X((()=>O&&O.length>0?u.w4.of(O):[]),O,me),Te=X((()=>E??[]),[E],me),Pe=(0,c.useCallback)((()=>{me.current?.requestMeasure({read:e=>[e.contentHeight,e.scrollDOM.scrollWidth>e.scrollDOM.clientWidth],write([e,t]){fe((n=>e!==n.height||t!==n.hasScroll?{height:e,hasScroll:t}:n))}})}),[]);(0,c.useLayoutEffect)((()=>{if(!pe.current)throw new Error("Can't mount editor: DOM node is missing");const e=pe.current,t=me.current=new u.Lz({doc:ce.current,extensions:[v.$t.tabSize.of(2),ke,Ie,Se,(0,m.b6)(),(0,u.VH)(),(0,p.WD)(),(0,p.SG)(),(0,h.wm)(),De,be,(0,p.y9)(V.light),(0,p.y9)(V.dark),ve,we,Ce,Ne,Me,u.w4.of([{key:"Ctrl-Shift-b",run:oe},{key:"Ctrl-Shift-c",run:ie},...h.Bc,...m.pw,...m.cL,...p.f7,...h.OO,...z]),(0,u.vX)({parent:document.body}),Ee,xe,u.Lz.updateListener.of((e=>{Pe();const n=t.state.sliceDoc()??"";e.docChanged&&U.current?.(n,e)})),u.Lz.domEventHandlers({focus(e){ee.current?.(e)},blur(e){te.current?.(e)},paste(e){se.current?.(e)}}),Te],parent:e});if(e._cm=t,J.current(t),t&&"json"===de.current){const e=t.state.doc.length,n=(0,p.nd)(t.state,e)||(0,p.k7)(t,e,150);ye.current&&n&&re(t)}return Pe(),()=>{delete e._cm,t.destroy()}}),[ke,Se,be,Ie,xe,Ce,De,we,ve,Ne,Me,Pe,Te]),(0,c.useEffect)((()=>{if(!le.current&&me.current&&t!==(me.current.state.sliceDoc()??"")){const e=new AbortController;return Q(me.current,{changes:{from:0,to:me.current.state.doc.length,insert:t}},e.signal),()=>{e.abort()}}}),[t]),(0,c.useEffect)((()=>{if(!me.current)return;const e=new AbortController;return Q(me.current,{effects:g._k.of(b??[])},e.signal),()=>{e.abort()}}),[b]),(0,c.useLayoutEffect)((()=>{if(ue.current){const e=he&&s?10:0,t=Math.min(ge,(T??1/0)*P)+e;ue.current.style.height=`${t}px`}}),[T,ge,he,P,s]);const Le=(0,c.useRef)(_);return(0,c.useLayoutEffect)((()=>{Le.current&&me.current?.focus()}),[Le]),d().createElement("div",{ref:ue,className:(0,f.cx)(w&&H,w&&G&&F,S&&W,I),style:{width:"100%",minHeight:Math.max(P,(M??0)*P),position:"relative",maxHeight:"100%"}},d().createElement("div",(0,l.A)({ref:pe,className:(0,f.cx)(R,!s&&j),style:{position:"absolute",width:"100%",height:"100%"},"data-codemirror":"true"},$)))}));function te(e){return!e||"Array"!==e.name&&"Property"!==e.name&&("JsonText"===e.name||te(e.parent))}const ne=(e,t)=>{if(B(e.state))return!1;const n=(0,h.Gw)(t,{label:t});return"function"==typeof n.apply&&(n.apply(e,n,0,e.state.doc.length),!0)},ae=(e,t,n)=>e.state.sliceDoc(t,n)??"",re=e=>{const t=[];return(0,p.mv)(e.state).iterate({enter(n){if(["{","["].includes(String(n.name))&&(0,p.wg)(e.state,n.from,n.to)&&!te(n.node)){if(!n.node.parent)throw new Error("Trying to fold node without parent");const e=(0,p.yd)(n.node.parent);return e&&t.push(e),!1}}}),t.length>0&&Q(e,{effects:t.map((e=>p.R3.of(e)))}),!!t.length},ie=e=>(navigator.clipboard.writeText(e.state.sliceDoc()),!0),oe=e=>{if(B(e.state))return!1;const t=e.state.facet(Z)[0],n=e.state.sliceDoc();try{const a=s(n,t);if(a!==n)return Q(e,{changes:{from:0,to:e.state.doc.length,insert:a},scrollIntoView:!0}),!0}catch{}return!1},se=(0,f.AHW)({"& .cm-editor":{backgroundColor:"transparent"}}),le=d().forwardRef((function({className:e,...t},n){return d().createElement(ee,(0,l.A)({ref:n,maxLines:10,showFoldGutter:!1,showLineNumbers:!1,showAnnotationsGutter:!1,showScroll:!1,highlightActiveLine:!1,className:(0,f.cx)(se,e),language:"javascript-expression"},t))})),ce=(0,f.AHW)({position:"relative",height:"100%",backgroundColor:_.light.backgroundColor,"&:focus-within > .multiline-editor-actions,\n &:hover > .multiline-editor-actions":{display:"flex"}}),de=(0,f.AHW)({minHeight:f.YKD[800]-2}),ue=(0,f.AHW)({"& .cm-gutters":{paddingLeft:f.YKD[500]}}),pe=(0,f.AHW)({backgroundColor:_.dark.backgroundColor}),me=d().forwardRef((function({customActions:e,copyable:t=!0,formattable:n=!0,className:a,editorClassName:r,actionsClassName:i,darkMode:o,onCopy:s,onExpand:u,expanded:p,...m},g){const h=(0,f.D27)(o),y=(0,c.useRef)(null),b=(0,c.useRef)(null),v=(0,f.HIF)(s);(0,c.useImperativeHandle)(g,(()=>({foldAll:()=>b.current?.foldAll()??!1,unfoldAll:()=>b.current?.unfoldAll()??!1,copyAll:()=>(v.current?.(),b.current?.copyAll()??!1),prettify:()=>b.current?.prettify()??!1,focus:()=>b.current?.focus()??!1,applySnippet:e=>b.current?.applySnippet(e)??!1,cursorDocEnd:()=>b.current?.cursorDocEnd()??!1,startCompletion:()=>b.current?.startCompletion()??!1,get editorContents(){return b.current?.editorContents??null},get editor(){return b.current?.editor??null}})),[]);const x=e&&e.length>0,E=t||n||x;return d().createElement("div",{ref:y,className:(0,f.cx)(ce,h&&pe,E&&de,u&&ue,a),onClick:e=>{e.target===y.current&&b.current?.focus()}},d().createElement(ee,(0,l.A)({ref:b,className:r,language:"javascript-expression",minLines:10},m)),E&&d().createElement(O,{onExpand:u,expanded:p,copyable:t,formattable:n,editorRef:b,className:i,customActions:e}))}));var ge=n(69692);function he(e="",t,n){return(0,ge.zM)(t,n).filter((({value:t})=>t.toLowerCase().startsWith(e.toLowerCase())))}const fe=(0,h.d0)(["String"],h.c7);function ye(e){return(0,p.mv)(e.state).resolveInner(e.pos,-1)}function be(e,{utmSource:t,utmMedium:n}){return e=e.replace(/^\$/,""),`<a target="_blank" href="${(0,f.EJm)(`https://www.mongodb.com/docs/manual/reference/operator/aggregation/${e}/`,{utmSource:t,utmMedium:n})}">$${e}</a>`}function ve(e,t=" "){return e.split("\n").map((e=>`${t}${e}`)).join("\n")}function xe(e,t){return t.firstChild?(n=function(e,t){return e.sliceDoc(t.from,t.to)}(e,t.firstChild),n.replace(/(^('|")|('|")$)/g,"")):"";var n}const Ee=(e,t)=>{const n=[];if(!e?.parent)return n;if(["ArrayExpression","Array"].includes(e.parent.name)){let t=e.prevSibling,a=0;for(;t;)[":",",","["].includes(t.name)||a++,t=t.prevSibling;n.push(`[${a}]`)}if("Property"===e.name&&e.firstChild){const{from:a,to:r}=e.firstChild,i=t.slice(a,r).replace(/"/g,"").replace(/'/g,"");n.push(i)}return n.concat(Ee(e.parent,t))};function Ce(e,t){const n=["ObjectExpression","PropertyDefinition"].includes(e.name)||"ObjectExpression"===e.parent?.parent?.name&&!e.prevSibling;return Ee(n?e.parent?.parent:e,t).reverse()}function we(e,t="invalid"){const n={label:e.value,apply:"never"===t?e.value:(0,ge.Zt)(e.value,"always"===t),detail:e.meta?.startsWith("field")?"field":e.meta,type:e.meta?.startsWith("field")?"field":"method",info(){const t=Object.hasOwn(e,"description")&&"string"==typeof e.description?e.description:null;if(!t)return null;const n=document.createElement("div");return n.classList.add("completion-info"),n.addEventListener("mousedown",(e=>{"A"===e.target.nodeName&&e.preventDefault()})),n.innerHTML=t,n}};return e.snippet?(0,h.Gw)(e.snippet,n):n}const Ie=e=>{const t=he("",{fields:e,meta:["field:identifier"]});return e=>{const n=ye(e),a="json"===e.state.facet(Z)[0];if(function(e){return"PropertyName"===e.name||e.type.isError&&["Property","{"].includes(e.prevSibling?.name??"")}(n)||function(e){return"Property"===e.parent?.name&&(!e.prevSibling||"["===e.prevSibling.name)}(n)){const r=e.state.sliceDoc(n.from,e.pos).replace(/^("|')/,"");return{from:n.from,to:n.to,options:t.filter((e=>e.value.toLowerCase().startsWith(r.toLowerCase()))).map((e=>({label:(0,ge.Zt)(e.value,a),type:"property",detail:"field"}))),filter:!1}}return fe(e)}},Se=/[a-zA-Z_0-9$\-\u00A2-\u2000\u2070-\uFFFF]+/;function Ae({prefix:e,completions:t,escape:n}){return{from:e.from,to:e.to,options:t.map((e=>we(e,n))),validFor:Se}}function ke(e){return function(t){const n=t.matchBefore(Se),a=ye(t);if(!n||""===n.text)return null;if(["BlockComment","LineComment"].includes(a.type.name))return null;const r={context:t,prefix:n,token:a};return"String"===a.type.name&&e.String?e.String(r)??null:e.IdentifierLike?.(r)??null}}const De=(e={})=>{const t=he("",{meta:["query","field:identifier"],...e}),n=he("",{meta:["bson","bson-legacy-uuid"],...e});return e=>{const a=ye(e);if(["BlockComment","LineComment"].includes(a.type.name))return null;const r=e.state.sliceDoc(a.from,e.pos).replace(/^("|')/,"");if(!r)return null;const i=function(e){let t=e;for(;t;){if("Property"===t.parent?.name&&t.prevSibling&&"["!==t.prevSibling.name)return!0;if("ArrayExpression"!==t.parent?.name&&"Array"!==t.parent?.name)break;t=t.parent}return!1}(a);if(i&&"String"===a.type.name)return fe(e)??null;const o=i?n:t;return{from:a.from,to:a.to,options:o.filter((e=>e.value.toLowerCase().includes(r.toLowerCase()))).map((e=>we(e))),filter:!1}}},Ne=(e,t)=>""===t?e:e.filter((e=>e.value!==t&&e.value.startsWith(t))).map((e=>{const n=e.value.replace(`${t}.`,"");return{...e,value:n}})).filter((e=>e.value)),Me=(e={})=>{const t=he("",{meta:["json-schema","bson","query"],...e}),n=he("",{meta:["field:identifier"],...e}),a=he("",{meta:["bson-type-aliases"],...e}),r=De(e),i=he("",{meta:["query"],...e}),o=i.map((e=>e.value));return e=>{const s=ye(e),l=e.state.sliceDoc(0),c=e.matchBefore(Se);if(s.type.isTop)return{filter:!1,from:0,to:l.length,options:[(0,h.Gw)("{\n\t$jsonSchema: {\n\t\t${}\n\t}\n}",{label:"$jsonSchema",info:"json-schema validation object"})]};if(!c)return null;const d=Ce(s,l);if(0===d.length)return Ae({prefix:c,completions:i});if(((e,t)=>e.filter((e=>"$jsonSchema"!==e)).some((e=>t.includes(e))))(d,o))return r(e);if((e=>"required"===e[e.length-2])(d)||(e=>"properties"===e[e.length-1])(d)){const e=(e=>e.filter((e=>!["$jsonSchema"].includes(e))).map(((e,t,n)=>{if(["required","properties"].includes(e))return n[t-1]})).filter(Boolean).join("."))(d);return Ae({prefix:c,completions:Ne(n,e)})}return(e=>"bsonType"===(e[e.length-1]??"")||"bsonType"===e[e.length-2])(d)?Ae({prefix:c,completions:a,escape:"always"}):Ae({prefix:c,completions:t})}},Te=({stageOperator:e,utmSource:t,utmMedium:n,...a}={})=>{const r=De(a),i=he("",{...a,meta:["field:reference"]}),o=he("",{...a,meta:["expr:*","conv","bson","bson-legacy-uuid","field:identifier",...["$project","$group"].includes(e??"")?["accumulator","accumulator:*"]:[]]}).map((e=>e.meta?.startsWith("expr:")?{...e,description:`<p>${be(e.value,{utmSource:t,utmMedium:n})} pipeline operator</p>`}:e));return ke({String:({prefix:e,context:t})=>e.text.startsWith("$")?Ae({prefix:e,completions:i,escape:"never"}):fe(t),IdentifierLike:({prefix:t,context:n})=>"$match"===e?r(n):Ae({prefix:t,completions:o})})};n(21261),n(92879),n(31977),n(49743),n(9656),n(72673),n(35467),n(94476),n(64971),n(24330),n(83478),n(65166),n(1256),n(61038),n(73035),n(23855);const Pe=new Set(ge.Tf);function Le({utmSource:e,utmMedium:t,...n}={}){const a=he("",{...n,meta:["stage"]});return ke({IdentifierLike({context:r,prefix:i,token:o}){const s=function(e,t){for(const r of function*(e){let t=e;for(;t=t.parent;)yield t}(t))if("Property"===r.name){const i=xe(e,r);if(r.firstChild&&(a=t,(n=r.firstChild).from!==a.from||n.to!==a.to)&&Pe.has(i))return i}var n,a;return null}(r.state,o);if(s)return Te({stageOperator:s,utmSource:e,utmMedium:t,...n})(r);const l="PropertyName"===o.name||"Property"===o.parent?.name;return Ae({prefix:i,completions:a.map((n=>{const a=n.value;return{...n,...n.description&&{description:`<p>${be(a,{utmSource:e,utmMedium:t})} pipeline stage</p><p>${n.description}</p>`},...n.snippet&&{snippet:l?`${a}: ${n.snippet}`:`{\n${ve(`${a}: ${n.snippet}`)}\n}`}}}))})}})}const Oe=(e={})=>{const t=he("",{meta:["field:identifier"],...e});return e=>{const n=ye(e),a=e.state.sliceDoc(0),r=e.matchBefore(Se);return r?"fields"===(i=Ce(n,a))[i.length-1]?Ae({prefix:r,completions:t}):fe(e):null;var i}};var Re=n(9174);const He=(0,f.AHW)({textTransform:"capitalize",fontWeight:"bold",fontFamily:f.aIi.default}),Fe=(0,f.AHW)({fontFamily:f.aIi.code,margin:`${f.YKD[50]}px`,marginLeft:`${f.YKD[100]}px`,padding:0,whiteSpace:"pre-wrap"});function We(e,t){const n=e.queryProperties[t];return""===n||null==n?"":(0,Re.AO)(n)||""}function je(e){return Object.entries(e.queryProperties).map((([e,t])=>{const n=(0,Re.AO)(t,1);return n?`${"filter"===e?"":`${e}: `}${n}`:""})).filter(Boolean).reduce(((e,t)=>e?`${e}, ${t}`:t),"")}function Be(e){return e.replace(/[\s'"\n\t{}},]/g,"").toLowerCase()}function ze(e,t){if(!e.isObject)return""!==e.scalarSimplified&&e.scalarSimplified.startsWith(t);let n=t;for(const a of e.fields){if(t===a.simplified)return!1;if(a.simplified.startsWith(t))return!0;-1!==n.indexOf(a.simplified)&&(n=n.replace(a.simplified,""))}return 0===n.length}const _e=q["javascript-expression"]().language.parser;const $e=({savedQueries:e,options:t={},queryProperty:n,onApply:a,theme:r})=>{const i=(({savedQueries:e,onApply:t,queryProperty:n,theme:a})=>{const r=function(e,t){return e.map((e=>{const n=e.queryProperties[t],a="object"==typeof n;let r="",i=[];if(""===t||null==t)return null;if(a){if(n){const e=Array.isArray(n);if(e&&n.some((e=>"object"!=typeof e||Array.isArray(e)||2!==e.length)))return null;if(i=(e?n:Object.entries(n)).slice(0,10).map((([e,t])=>{const n="object"==typeof t||Array.isArray(t)?"":t;return{simplified:Be((0,Re.AO)({[e]:n})||"")}})),0===i.length||i.some((e=>e.simplified.length>200)))return null}}else{if(n?.length&&n?.length>200)return null;const e=(0,Re.AO)(n)||"";if(!e||e.length>200)return null;r=e?Be(e):""}return{query:e,label:We(e,t),displayLabel:je(e),isObject:a,scalarSimplified:r,fields:i}})).filter((e=>null!==e))}(e,n);return function(n){if(0===r.length)return null;const i=e[e.length-1].lastExecuted.getTime(),o=e[0].lastExecuted.getTime(),s=n.state.sliceDoc(0,n.pos),l=function(e,t){const n=Be(t);if(0===n.length)return e;const a=[];for(const t of e){if(a.length>=10)break;ze(t,n)&&a.push(t)}return a}(r,s),c=l.map((e=>{return{displayLabel:e.displayLabel,label:e.label,type:"recent"===e.query.type?"query-history":"favorite",detail:(0,f.Yq5)(e.query.lastExecuted.getTime()),info:()=>function(e,t){const n=V[t],a=document.createElement("div");return Object.entries(e.queryProperties).forEach((([e,t])=>{const r=(0,Re.AO)(t),i=document.createElement("div"),o=document.createElement("label");o.className=He,o.textContent=e;const s=document.createElement("pre");s.className=Fe,r&&(0,x.wY)(r,_e.parse(r),n,(function(e,t){const n=document.createTextNode(e);if(t){const e=document.createElement("span");e.appendChild(n),e.className=t,s.appendChild(e)}else s.appendChild(n)}),(function(){s.appendChild(document.createTextNode("\n"))})),i.append(o),i.appendChild(s),a.appendChild(i)})),{dom:a,destroy:()=>{for(;a.firstChild;)a.removeChild(a.firstChild)}}}(e.query,a).dom,apply:()=>{t(e.query.queryProperties)},boost:(n=e.query.lastExecuted.getTime(),r=-99,s=99,l=o,c=i,c===l?r+(s-r)/2:(s-r)*(n-l)/(c-l)+r)};var n,r,s,l,c}));return{from:n.pos,options:c}}})({savedQueries:e,onApply:a,queryProperty:n,theme:r}),o=De(t),s={name:"Query History",header:Ke};return async function(e){if("{}"===e.state.doc.toString())return i(e);const t=[],n=await o(e),a=await i(e);return n&&t.push(...n.options.map((e=>({...e})))),a&&t.push(...a.options.map((e=>({...e,section:s})))),{from:Math.min(a?.from??e.pos,n?.from??e.pos),options:t}}},Ye=(0,f.AHW)({display:"list-item",borderBottom:"1px dashed #ccc",margin:"5px 0"});function Ke(){const e=document.createElement("div");return e.className=Ye,e}var Ge=n(7582),Ve=n(15404),Ue=n(98726),qe=n(95854),Ze=n(43910),Je=n(36743),Qe=n(93706);const Xe="inmemory://json-schema.json",et="file:///json-schema-document.json",tt=(0,Ue.l)().use(qe.A).use(Ze.A,{handlers:{link:(e,t)=>({type:"element",tagName:"a",properties:{href:t.url,target:"_blank",rel:"noopener noreferrer",...t.title?{title:t.title}:{}},children:e.all(t)})}}).use((()=>e=>{e.children=e.children.flatMap((e=>"element"===e.type&&"p"===e.tagName?e.children:[e]))})).use(Je.A).use(Qe.A),nt={padding:`${f.YKD[200]}px`,maxWidth:"300px",whiteSpace:"pre-wrap",wordBreak:"break-word"},at=(0,f.AHW)(nt),rt=u.Lz.theme({".cm-tooltip-hover":{height:"auto !important"},".cm-tooltip-lint":nt}),it={Text:1,Method:2,Function:3,Constructor:4,Field:5,Variable:6,Class:7,Interface:8,Module:9,Property:10,Unit:11,Value:12,Enum:13,Keyword:14,Snippet:15,Color:16,File:17,Reference:18,Folder:19,EnumMember:20,Constant:21,Struct:22},ot={PlainText:1,Snippet:2};function st(e,t,n){const a=t.getText();return n.content===a&&n.jsonDoc||(n.jsonDoc=e.parseJSONDocument(t),n.content=a),n.jsonDoc}function lt(e){if(void 0!==e)switch(e){case it.Text:case it.Snippet:return"text";case it.Method:return"method";case it.Function:return"function";case it.Constructor:case it.Class:return"class";case it.Field:case it.Property:return"property";case it.Variable:case it.Value:return"variable";case it.Interface:case it.Struct:return"type";case it.Module:return"namespace";case it.Enum:case it.EnumMember:return"enum";case it.Keyword:return"keyword";case it.Constant:return"constant";default:return}}function ct(e,t){const[n,a]=(0,c.useState)({completer:void 0,extensions:[]}),[r,i]=(0,c.useState)([]),o=(0,c.useRef)(null),s=(0,c.useRef)({content:null,jsonDoc:null});(0,c.useEffect)((()=>{if(!e)return a({completer:void 0,extensions:[]}),void(o.current=null);const t=function(e){const t=JSON.stringify(e),n=(0,Ge.QD)({schemaRequestService:e=>e===Xe?Promise.resolve(t):Promise.reject(new Error(`Unable to load schema at ${e}`))});return n.configure({allowComments:!0,schemas:[{uri:Xe,fileMatch:["*"]}]}),n}(e);o.current=t;const n=s.current,r=e=>Ve.V.create(et,"json",0,e),i=u.Lz.updateListener.of((e=>{e.docChanged&&e.changes.iterChanges(((t,n,a,r,i)=>{const o=i.toString();(":"===o||o.startsWith("\n"))&&(0,h.rB)(e.view)}))}));a({completer:async e=>{if(!e.explicit){const t=e.state.doc.lineAt(e.pos);if(e.state.sliceDoc(t.from,e.pos).trimEnd().endsWith(","))return null}const a=e.state.doc.toString(),i=r(a),o=st(t,i,n),s=e.state.doc.lineAt(e.pos),l={line:s.number-1,character:e.pos-s.from},c=await t.doComplete(i,l,o);if(!c||0===c.items.length)return null;const d=e.matchBefore(/[^\s"'`:;,=()\[\]{}]*$/),u=d?d.from:e.pos,p=[];for(const e of c.items){const{detail:t,documentation:n,kind:a,label:r,textEdit:i,insertText:o}=e,s={label:r.replace(/^"(.*)"$/,"$1"),detail:t,type:lt(a),info:n&&"string"==typeof n?n:n&&"object"==typeof n&&"value"in n?n.value:void 0};if(i&&"range"in i){const t=i.newText,n=e.insertTextFormat;s.apply=(e,a,r,i)=>{let o=r;r>0&&'"'===e.state.sliceDoc(r-1,r)&&(o=r-1);let l=i;'"'===e.state.sliceDoc(i,i+1)&&(l=i+1),n===ot.Snippet?(0,h.UA)(t.replaceAll(/\$(\d+)/g,"$${$1}"))(e,s,o,l):e.dispatch((0,h.zH)(e.state,t,o,l)),(0,h.N)(e)}}else o&&(s.apply=o);p.push(s)}return{from:u,to:e.pos,options:p,validFor:/[^\s"'`:;,=()\[\]{}]*/}},extensions:[rt,i,(0,u.Ux)((async(e,a)=>{const i=e.state.doc.toString(),o=r(i),s=st(t,o,n),l=e.state.doc.lineAt(a),c={line:l.number-1,character:a-l.from},d=await t.doHover(o,c,s);if(!d||!d.contents)return null;let u,p=a;d.range&&(p=o.offsetAt(d.range.start),u=o.offsetAt(d.range.end));let m="";const g=d.contents;if("string"==typeof g?m=g:Array.isArray(g)?m=g.map((e=>"string"==typeof e?e:e.value)).join("\n\n"):"value"in g&&(m=g.value),!m)return null;const h={dom:(()=>{const e=document.createElement("div");return e.className=at,e.dataset.testid="json-schema-hover-tooltip",e.innerHTML=String(tt.processSync(m)),e})()};return{pos:p,end:u,create:()=>h}}))]})}),[e]),(0,c.useEffect)((()=>{if(!e||!o.current||0===n.extensions.length)return void i([]);let a=!1;return async function(){const e=o.current;if(!e)return;const n=Ve.V.create(et,"json",0,t),r=st(e,n,s.current),l=await e.doValidation(n,r);if(a)return;const c=l.map((e=>{const{message:t,range:a,severity:r}=e;return{message:t,from:n.offsetAt(a.start),to:n.offsetAt(a.end),severity:4===r?"hint":3===r?"info":2===r?"warning":"error"}}));i(c)}().catch((()=>{})),()=>{a=!0}}),[e,t,n.extensions.length]);const l=(0,c.useMemo)((()=>r.some((e=>"error"===e.severity||"warning"===e.severity))),[r]);return{completer:n.completer,extensions:n.extensions,annotations:r,hasErrors:l}}},73190:(e,t,n)=>{n.d(t,{Mn:()=>v,FX:()=>C});var a=n(96652),r=n.n(a),i=n(56900),o=n(56128),s=n(13390),l=n(21655),c=n(72099),d=n(17565),u=n(51295),p=n(15088).process;const m=r().createElement(r().Fragment,null,"When enabled, Compass occasionally calls the"," ",r().createElement(u.N_E,{href:"https://www.mongodb.com/docs/manual/reference/command/dbStats/#mongodb-dbcommand-dbcmd.dbStats"},"dbStats"),"and"," ",r().createElement(u.N_E,{href:"https://www.mongodb.com/docs/manual/reference/command/collStats/"},"collStats")," ","commands to access storage statistics for a given database or collection. Disabling this setting can help reduce Compass' overhead on your MongoDB deployments."),g={showDevFeatureFlags:{ui:!0,cli:!0,global:!0,omitFromHelp:!0,description:{short:"Show Developer Feature Flags"},validator:i.z.boolean().optional().default("dev"===p.env.HADRON_CHANNEL),type:"boolean"},enableDebugUseCsfleSchemaMap:{ui:!0,cli:!0,global:!0,description:{short:"CSFLE Schema Map Debugging"},validator:i.z.boolean().optional(),type:"boolean"},...o.e},h={id:{ui:!1,cli:!1,global:!1,description:null,validator:i.z.string().default("General"),type:"string"},lastKnownVersion:{ui:!1,cli:!1,global:!1,description:null,validator:i.z.string().default("0.0.0"),type:"string"},highestInstalledVersion:{ui:!1,cli:!1,global:!1,description:null,validator:i.z.string().default("0.0.0"),type:"string"},showedNetworkOptIn:{ui:!1,cli:!0,global:!1,description:null,omitFromHelp:!0,validator:i.z.boolean().default(!1),type:"boolean"},theme:{ui:!0,cli:!0,global:!0,description:{short:"Compass UI Theme"},validator:i.z.effect(i.z.enum(["DARK","LIGHT","OS_THEME"]),{type:"preprocess",transform:e=>"string"!=typeof e?e:(e||"light").toUpperCase()}).optional().default("LIGHT"),type:"string"},currentUserId:{ui:!1,cli:!1,global:!1,description:null,validator:i.z.string().optional(),type:"string"},telemetryAnonymousId:{ui:!1,cli:!1,global:!1,description:null,validator:i.z.string().uuid().optional(),type:"string"},telemetryAtlasUserId:{ui:!1,cli:!1,global:!1,description:null,validator:i.z.string().optional(),type:"string"},telemetryDeviceId:{ui:!1,cli:!1,global:!1,description:null,validator:i.z.string().optional(),type:"string"},userCreatedAt:{ui:!1,cli:!1,global:!1,description:null,validator:i.z.number().default(Date.now()),type:"number"},enableConnectInNewWindow:{ui:!1,cli:!1,global:!1,description:null,validator:i.z.boolean().default(!0),type:"boolean"},showEndOfLifeConnectionModal:{ui:!1,cli:!1,global:!1,description:null,validator:i.z.boolean().default(!0),type:"boolean"},zoomLevel:{ui:!1,cli:!1,global:!1,description:null,validator:i.z.number().optional(),type:"number"},windowBounds:{ui:!1,cli:!1,global:!1,description:null,validator:i.z.object({x:i.z.number().optional(),y:i.z.number().optional(),width:i.z.number().optional(),height:i.z.number().optional(),isMaximized:i.z.boolean().optional(),isFullScreen:i.z.boolean().optional()}).optional(),type:"object"},enableGuideCues:{ui:!1,cli:!1,global:!1,description:null,validator:i.z.boolean().default(!0),type:"boolean"},cloudFeatureRolloutAccess:{ui:!1,cli:!1,global:!1,description:null,validator:i.z.object({GEN_AI_COMPASS:i.z.boolean().optional()}).optional(),type:"object"},networkTraffic:{ui:!0,cli:!0,global:!0,description:{short:"Enable network traffic other than to the MongoDB database"},validator:i.z.boolean().default(!0),type:"boolean"},readOnly:{ui:!0,cli:!0,global:!0,description:{short:"Set Read-Only Mode",long:"Limit Compass strictly to read operations, with all write and delete capabilities removed."},validator:i.z.boolean().default(!1),type:"boolean"},readWrite:{ui:!0,cli:!1,global:!1,description:{short:"Set Read-Write Mode",long:"Limit Compass to data read write operations only, with cababilities like renaming / dropping namespaces or editing indexes removed."},deriveValue:E("readWrite",!0),validator:i.z.boolean().default(!1),type:"boolean"},enableShell:{ui:!0,cli:!0,global:!0,description:{short:"Enable MongoDB Shell",long:"Allow Compass to interact with MongoDB deployments via the embedded shell."},deriveValue:E("enableShell"),validator:i.z.boolean().default(!0),type:"boolean"},enableDbAndCollStats:{ui:!0,cli:!0,global:!0,description:{short:"Show Database and Collection Statistics",long:"The dbStats and collStats command returns storage statistics for a given database or collection. Disabling this setting can help reduce Compass' overhead on your MongoDB deployments.",longReact:m},validator:i.z.boolean().default(!0),type:"boolean"},enableMaps:{ui:!0,cli:!0,global:!0,description:{short:"Enable Geographic Visualizations",long:"Allow Compass to make requests to a 3rd party mapping service."},deriveValue:x("enableMaps"),validator:i.z.boolean().default(!0),type:"boolean"},enableGenAIFeatures:{ui:!0,cli:!0,global:!0,description:{short:"Enable AI Features",long:"Allow the use of AI features in Compass which make requests to 3rd party services."},deriveValue:x("enableGenAIFeatures"),validator:i.z.boolean().default(!0),type:"boolean"},enableFeedbackPanel:{ui:!0,cli:!0,global:!0,description:{short:"Give Product Feedback",long:"Enables a tool that our Product team can use to occasionally reach out for feedback about Compass."},deriveValue:x("enableFeedbackPanel"),validator:i.z.boolean().default(!0),type:"boolean"},trackUsageStatistics:{ui:!0,cli:!0,global:!0,description:{short:"Enable Usage Statistics",long:"Allow Compass to send anonymous usage statistics."},deriveValue:x("trackUsageStatistics"),validator:i.z.boolean().default(!0),type:"boolean"},autoUpdates:{ui:!0,cli:!0,global:!0,description:{short:"Enable Automatic Updates",long:"Allow Compass to periodically check for new updates."},deriveValue:x("autoUpdates"),validator:i.z.boolean().default(!0),type:"boolean"},protectConnectionStrings:{ui:!0,cli:!0,global:!0,description:{short:"Protect Connection String Secrets",long:"Hide credentials in connection strings from users."},validator:i.z.boolean().default(!1),type:"boolean"},defaultSortOrder:{ui:!0,cli:!0,global:!0,description:{short:"Default Sort for Query Bar",long:"All queries executed from the query bar will apply this sort. Not available for views and timeseries.",longReact:r().createElement(r().Fragment,null,"All queries executed from the query bar will apply this sort."," ",r().createElement("strong",null,"Not available for views and timeseries.")),options:{"":{label:"MongoDB server default",description:"Return documents in natural order of documents"},"{ _id: 1 }":{label:"_id: 1",description:"Return documents in ascending order by id"},"{ _id: -1 }":{label:"_id: -1",description:"Return documents in descending order by id"},"{ $natural: -1 }":{label:"$natural: -1",description:"Return documents in reverse natural order, but ignores existing indexes. ⚠️ Suitable if you use Compass only with development clusters. Avoid this option if you connect to production clusters as well."}}},validator:i.z.enum(["","{ _id: 1 }","{ _id: -1 }","{ $natural: -1 }"]).default(""),type:"string"},enableDevTools:{ui:!0,cli:!0,global:!0,description:{short:"Enable DevTools",long:"Enable the Chromium Developer Tools that can be used to debug Electron's process."},deriveValue:(f="enableDevTools",(e,t)=>({value:e(f)&&e("enableShell")&&!e("maxTimeMS")&&!e("protectConnectionStrings")&&!e("readOnly"),state:t(f)??(e("protectConnectionStrings")?t("protectConnectionStrings")??"derived":void 0)??(e("readOnly")?t("readOnly")??"derived":void 0)??(e("enableShell")?void 0:t("enableShell")??"derived")??(e("maxTimeMS")?t("maxTimeMS")??"derived":void 0)})),validator:i.z.boolean().default(!1),type:"boolean"},showKerberosPasswordField:{ui:!0,cli:!0,global:!0,description:{short:"Show Kerberos Password Field",long:"Show a password field for Kerberos authentication. Typically only useful when attempting to authenticate as another user than the current system user."},validator:i.z.boolean().default(!1),type:"boolean"},showOIDCDeviceAuthFlow:{ui:!0,cli:!0,global:!0,description:{short:"Show Device Auth Flow Checkbox",long:"Show a checkbox on the connection form to enable device auth flow authentication for MongoDB server OIDC Authentication. This enables a less secure authentication flow that can be used as a fallback when browser-based authentication is unavailable."},validator:i.z.boolean().default(!1),type:"boolean"},browserCommandForOIDCAuth:{ui:!0,cli:!0,global:!0,description:{short:"Browser command to use for authentication",long:"Specify a shell command that is run to start the browser for authenticating with the OIDC identity provider for the server connection or when logging in to your Atlas Cloud account. Leave this empty for default browser."},validator:i.z.string().optional(),type:"string"},persistOIDCTokens:{ui:!0,cli:!0,global:!0,description:{short:"Stay logged in with OIDC",long:"Remain logged in when using the MONGODB-OIDC authentication mechanism for MongoDB server connection. Access tokens are encrypted using the system keychain before being stored. Disabling this option will remove currently stored tokens."},validator:i.z.boolean().default(!0),type:"boolean"},forceConnectionOptions:{ui:!0,cli:!0,global:!0,description:{short:"Override Connection String Properties",long:"Force connection string properties to take specific values"},customPostProcess:function(e,t){if("string"==typeof e)return[...new l.URLSearchParams(e)];if(!e)return[];if("object"!=typeof e||null===e)return t(`Could not interpret ${(0,s.inspect)(e)} as a list of key-value pairs`),[];const n=[];if(Array.isArray(e))for(const a of e)if(Array.isArray(a)&&2===a.length)n.push([a[0],a[1]]);else if("object"!=typeof a||null===a||Array.isArray(a))t(`Could not interpret ${(0,s.inspect)(a)} as a key-value pair`);else for(const[e,t]of Object.entries(a))n.push([e,t]);else for(const[t,a]of Object.entries(e))if(Array.isArray(a))for(const e of a)n.push([t,e]);else n.push([t,a]);const a=[];for(const[e,r]of n)"object"==typeof e&&null!==e?t(`Could not interpret ${(0,s.inspect)(e)} as a record key`):"object"==typeof r&&null!==r?t(`Could not interpret ${(0,s.inspect)(r)} as a string value`):a.push([String(e),String(r)]);return a},validator:i.z.array(i.z.tuple([i.z.string(),i.z.string()])).optional(),type:"array"},maxTimeMS:{ui:!0,cli:!0,global:!0,description:{short:"Upper Limit for maxTimeMS for Compass Database Operations"},validator:i.z.number().optional(),type:"number"},installURLHandlers:{ui:!0,cli:!0,global:!0,description:{short:"Install Compass as URL Protocol Handler",long:"Register Compass as a handler for mongodb:// and mongodb+srv:// URLs"},validator:i.z.boolean().default(!0),type:"boolean"},protectConnectionStringsForNewConnections:{ui:!0,cli:!0,global:!0,description:{short:'If true, "Edit connection string" is disabled for new connections by default'},validator:i.z.boolean().default(!1),type:"boolean"},atlasServiceBackendPreset:{ui:!0,cli:!0,global:!0,description:{short:"Configuration used by atlas service"},validator:i.z.enum(["atlas-local","atlas-dev","atlas-qa","atlas-staging","atlas"]).default("atlas"),type:"string"},optInGenAIFeatures:{ui:!0,cli:!1,global:!1,description:{short:"User or Client Opt-in for Gen AI Features"},validator:i.z.boolean().default(!1),type:"boolean"},enableAtlasSearchIndexes:{ui:!0,cli:!0,global:!0,description:{short:"Enable Atlas Search Indexes"},validator:i.z.boolean().default(!0),type:"boolean"},enableImportExport:{ui:!0,cli:!0,global:!0,description:{short:"Enable import / export feature"},validator:i.z.boolean().default(!0),type:"boolean"},enableAggregationBuilderRunPipeline:{ui:!0,cli:!0,global:!0,description:{short:'Enable "Run Pipeline" feature in aggregation builder'},validator:i.z.boolean().default(!0),type:"boolean"},enableExplainPlan:{ui:!0,cli:!0,global:!0,description:{short:"Enable explain plan feature in CRUD and aggregation view"},validator:i.z.boolean().default(!0),type:"boolean"},enableAggregationBuilderExtraOptions:{ui:!0,cli:!0,global:!0,description:{short:"Enable preview input limit and collation options in aggregation view"},validator:i.z.boolean().default(!0),type:"boolean"},enableGenAISampleDocumentPassing:{ui:!0,cli:!0,global:!0,description:{short:"Enable sending sample field values with query and aggregation generation requests.",long:"Supplying sample field values improves the results from the AI."},validator:i.z.boolean().default(!1),type:"boolean"},enableGenAIToolCalling:{ui:!0,cli:!0,global:!0,description:{short:"Enable read-only tools in the MongoDB Assistant",long:"Allow the MongoDB Assistant to interact with your databases. All actions require your approval before running.",longReact:r().createElement(r().Fragment,null,"Allow the MongoDB Assistant to interact with your databases. All actions require your approval before running. Learn more about"," ",r().createElement(u.N_E,{href:"https://www.mongodb.com/docs/compass/query-with-natural-language/compass-ai-assistant/",target:"_blank"},"MongoDB database tools"))},validator:i.z.boolean().default(!0),type:"boolean"},enablePerformanceAdvisorBanner:{ui:!0,cli:!0,global:!0,description:{short:"Show performance advisor banner to users for performance tuning"},validator:i.z.boolean().default(!1),type:"boolean"},maximumNumberOfActiveConnections:{ui:!0,cli:!0,global:!0,description:{short:"Limits the amount of open connections."},validator:i.z.number().default(10),type:"number"},enableShowDialogOnQuit:{ui:!0,cli:!0,global:!0,description:{short:"Show Quit Confirmation Dialog",long:"Toggle whether confirmation dialog is shown when quitting Compass (cmd/ctrl-Q)."},validator:i.z.boolean().default(!0),type:"boolean"},proxy:{ui:!0,cli:!0,global:!0,description:{short:"Specify a proxy for Compass to use",long:"Specify a HTTP, HTTPS or Socks5 proxy to use for connecting to external services (default is picking proxies from environment variables)"},validator:i.z.union([i.z.string().url(),i.z.literal(""),i.z.custom((e=>{if("string"!=typeof e)return!1;try{return JSON.parse(e),!0}catch{return!1}}))]).default(""),type:"string",secrets:{extract(e){const{secrets:t,...n}=(0,c.R5)((0,d.nV)(e));return{remainder:JSON.stringify(n),secrets:JSON.stringify(t)}},merge:({remainder:e,secrets:t})=>(0,d.r2)((0,c.On)({...JSON.parse(e),secrets:JSON.parse(t)}))}},enableCreatingNewConnections:{ui:!0,cli:!0,global:!0,description:{short:"Enables creating new connection (accessing connection editing form) in Compass UI"},validator:i.z.boolean().default(!0),type:"boolean"},enableGenAIFeaturesAtlasProject:{ui:!1,cli:!0,global:!0,description:{short:"Enable Gen AI Features on Atlas Project Level"},validator:i.z.boolean().default(!0),type:"boolean"},enableGenAIFeaturesAtlasOrg:{ui:!1,cli:!0,global:!0,description:{short:"Enable Gen AI Features on Atlas Org Level"},validator:i.z.boolean().default(!0),type:"boolean"},enableGenAIToolCallingAtlasProject:{ui:!1,cli:!0,global:!0,description:{short:"Enable Gen AI Tool Calling on Atlas Project Level"},validator:i.z.boolean().default(!0),type:"boolean"},enableMyQueries:{ui:!0,cli:!0,global:!0,description:{short:"Enable My Queries feature to save and manage favorite queries and aggregations"},validator:i.z.boolean().default(!0),type:"boolean"},inferNamespacesFromPrivileges:{ui:!0,cli:!0,global:!0,description:{short:"Infer additional namespaces from privileges",long:"Show databases and collections implied by your roles and privileges, in addition to those returned by listDatabases and listCollections. This may include namespaces that don't exist yet."},validator:i.z.boolean().default(!0),type:"boolean"},maxTimeMSEnvLimit:{ui:!0,cli:!0,global:!0,description:{short:"Maximum time limit for operations in environment (milliseconds). Set to 0 for no limit."},validator:i.z.number().min(0).default(0),type:"number"},legacyUUIDDisplayEncoding:{ui:!0,cli:!0,global:!0,description:{short:"Encoding for Displaying Legacy UUID Values",long:"Select the encoding to be used when displaying legacy UUID of the binary subtype 3.",options:{"":{label:"Raw data (no encoding)",description:"Display legacy UUIDs as raw binary data"},LegacyJavaUUID:{label:"Legacy Java UUID",description:'Display legacy UUIDs using Java UUID encoding. LegacyJavaUUID("UUID_STRING")'},LegacyCSharpUUID:{label:"Legacy C# UUID",description:'Display legacy UUIDs using C# UUID encoding. LegacyCSharpUUID("UUID_STRING")'},LegacyPythonUUID:{label:"Legacy Python UUID",description:'Display legacy UUIDs using Python UUID encoding. LegacyPythonUUID("UUID_STRING")'}}},validator:i.z.enum(["","LegacyJavaUUID","LegacyCSharpUUID","LegacyPythonUUID"]).default(""),type:"string"},...g};var f;const y={exportConnections:{ui:!1,cli:!0,global:!1,description:{short:"Export Favorite Connections",long:"Export Compass favorite connections. Can be used with --passphrase."},validator:i.z.string().optional(),type:"string"},importConnections:{ui:!1,cli:!0,global:!1,description:{short:"Import Favorite Connections",long:"Import Compass favorite connections. Can be used with --passphrase."},validator:i.z.string().optional(),type:"string"},passphrase:{ui:!1,cli:!0,global:!1,description:{short:"Connection Export/Import Passphrase",long:"Specify a passphrase for encrypting/decrypting secrets."},validator:i.z.string().optional(),type:"string"},help:{ui:!1,cli:!0,global:!1,description:{short:"Show Compass Options"},validator:i.z.boolean().optional(),type:"boolean"},version:{ui:!1,cli:!0,global:!1,description:{short:"Show Compass Version"},validator:i.z.boolean().optional(),type:"boolean"},versions:{ui:!1,cli:!0,global:!1,description:{short:"Show Node, Electron, Chromium Versions"},validator:i.z.boolean().optional(),type:"boolean"},showExampleConfig:{ui:!1,cli:!0,global:!1,description:{short:"Show Example Config File"},validator:i.z.boolean().optional(),type:"boolean"},trustedConnectionString:{ui:!1,cli:!0,global:!1,description:{short:"Always allow to Automatically Connect",long:"Allow automatic connection establishment when launching Compass, even if the provided connection string contains connection options that would not be accepted when coming from an untrusted source"},validator:i.z.boolean().default(!1),type:"boolean"}},b={ignoreAdditionalCommandLineFlags:{ui:!1,cli:!0,global:!0,description:{short:"Allow Additional CLI Flags",long:"Allow specifying command-line flags that Compass does not understand, e.g. Electron or Chromium flags"},validator:i.z.boolean().default(!1),type:"boolean"},positionalArguments:{ui:!1,cli:!0,global:!1,description:{short:"Specify a Connection String or Connection ID to Automatically Connect"},omitFromHelp:!0,validator:i.z.array(i.z.string()).optional(),type:"array"},file:{ui:!1,cli:!0,global:!0,description:{short:"Specify a List of Connections for Automatically Connecting"},validator:i.z.string().optional(),type:"string"},username:{ui:!1,cli:!0,global:!0,description:{short:"Specify a Username for Automatically Connecting"},validator:i.z.string().optional(),type:"string"},password:{ui:!1,cli:!0,global:!0,description:{short:"Specify a Password for Automatically Connecting"},validator:i.z.string().optional(),type:"string"}},v={...h,...y,...b};function x(e){return(t,n)=>({value:t(e)&&t("networkTraffic"),state:n(e)??(t("networkTraffic")?void 0:n("networkTraffic")??"derived")})}function E(e,t=!1){return(n,a)=>({value:Boolean(t?n(e)||n("readOnly"):n(e)&&!n("readOnly")),state:a(e)??(n("readOnly")?a("readOnly")??"derived":void 0)})}function C(){return Object.fromEntries(Object.entries(h).map((([e,t])=>[e,t.validator.parse(void 0)])).filter((([,e])=>void 0!==e)))}},84917:(e,t,n)=>{n(59509),n(25691),n(23177),n(3142),n(51615),n(84217),n(25953),n(42319),n(28465),n(12887),n(36106),n(84542),n(57068),n(69517),n(81546);const a=n(5389),r=n(4579),i=n(49862),{getProperties:o}=n(29794),s=new Map;function l(e){return s.has(e)||s.set(e,i(e)),s.get(e)}const c=new Map;function d(e){return{initialize(){e.forEach((e=>{if(e in this&&"function"==typeof this[e]){const n=this[e];this[e]=(t=n,function(...e){const n=this.isCollection?`${this.parent.cid}$$coll$$${t.name}`:`${this.cid}$$${t.name}`;if(c.has(n))return c.get(n);const a=t.call(this,...e).finally((()=>{c.delete(n)}));return c.set(n,a),a})}var t}))}}}function u(e){return e.parent??e.collection??null}function p(e,...t){let n=u(this);for(;n;)n.emit(e,...t),n=u(n)}function m(e,t){const n=u(e);return n?n.modelType===t?n:m(n,t):null}function g({type:e,readonly:t,view_on:n,collation:a,pipeline:r,validation:i,clustered:o,fle2:s,inferred_from_privileges:l}){return{type:e,readonly:t,view_on:n,collation:a,pipeline:r,validation:i,clustered:o,fle2:s,inferred_from_privileges:l}}const h=a.extend(d(["fetch"]),{modelType:"Collection",idAttribute:"_id",props:{_id:{type:"string",required:!0},type:{type:"string",default:"collection"},status:{type:"string",default:"initial"},statusError:{type:"string",default:null},inferred_from_privileges:"boolean",readonly:"boolean",clustered:"boolean",fle2:"boolean",view_on:"string",collation:"object",pipeline:"array",validation:"object",is_capped:"boolean",document_count:"number",document_size:"number",avg_document_size:"number",storage_size:"number",free_storage_size:"number",index_count:"number",index_size:"number",bucket_count:"number",avg_bucket_size:"number"},derived:{ns:{deps:["_id"],fn(){return l(this._id).ns}},name:{deps:["_id"],fn(){return l(this._id).collection}},database:{deps:["_id"],fn(){return l(this._id).database}},system:{deps:["_id"],fn(){return l(this._id).system}},oplog:{deps:["_id"],fn(){return l(this._id).oplog}},command:{deps:["_id"],fn(){return l(this._id).command}},special:{deps:["_id"],fn(){return l(this._id).special}},specialish:{deps:["_id"],fn(){return l(this._id).specialish}},normal:{deps:["_id"],fn(){return l(this._id).normal}},isTimeSeries:{deps:["type"],fn(){return"timeseries"===this.type}},isView:{deps:["type"],fn(){return"view"===this.type}},sourceName:{deps:["view_on"],fn(){return this.view_on?`${this.database}.${this.view_on}`:null}},source:{deps:["sourceName"],fn(){return this.collection.get(this.sourceName)??null}},properties:{deps:["collation","type","is_capped","clustered","readonly","fle2"],fn(){return o(this)}},calculated_storage_size:{deps:["storage_size","free_storage_size"],fn(){if(void 0!==this.storage_size&&void 0!==this.free_storage_size)return this.storage_size-this.free_storage_size}}},async fetch({dataService:e,fetchInfo:t=!0,force:n=!1}){if(!function(e,t){return t||"ready"!==e}(this.status,n))return;const a=m(this,"Instance").shouldFetchDbAndCollStats();try{const n="initial"===this.status?"fetching":"refreshing";this.set({status:n});const[r,i]=await Promise.all([a?e.collectionStats(this.database,this.name,this.type):null,t?e.collectionInfo(this.database,this.name):null]);this.set({status:"ready",statusError:null,...r,...i&&g(i)}),this.inferred_from_privileges||m(this,"Database").set({inferred_from_privileges:!1})}catch(e){throw this.set({status:"error",statusError:e.message}),e}},async fetchMetadata({dataService:e}){try{await this.fetch({dataService:e})}catch(e){if("MongoServerError"!==e.name)throw e}const t=m(this,"Instance"),n=!this.isView&&await t.getIsSearchSupported({dataService:e,ns:this.ns}),a={namespace:this.ns,isReadonly:this.readonly,isTimeSeries:this.isTimeSeries,isClustered:this.clustered,isFLE:this.fle2,isSearchIndexesSupported:n,isDataLake:t.dataLake.isDataLake,isAtlas:"atlas"===t.env,serverVersion:t.build.version};return this.sourceName&&Object.assign(a,{sourceName:this.sourceName,sourcePipeline:this.pipeline}),a},toJSON(e={derived:!0}){const t=this.serialize(e);return t.source&&(t.source=t.source.toJSON()),t}}),f=r.extend(function(...e){return{initialize(...t){e.forEach((({initialize:e})=>{e.call(this,...t)}))}}}(d(["fetch"]),(y="collections",{initialize(){if(this.isCollection){this.on("add",p.bind(this,`add:${y}`)),this.on("remove",p.bind(this,`remove:${y}`)),this.on("change",p.bind(this,`change:${y}`));for(const e of Object.keys(this.model.prototype._definition))this.on(`change:${e}`,p.bind(this,`change:${y}.${e}`))}}})),{modelType:"CollectionCollection",mainIndex:"_id",indexes:["name"],comparator:"_id",model:h,async fetch({dataService:e}){const t=m(this,"Database")?.getId(),n=m(this,"Instance").shouldFetchNamespacesFromPrivileges();if(!t)throw new Error(`Trying to fetch ${this.modelType} that doesn't have the Database parent model`);const a=m(this,"Instance");if(!a)throw new Error(`Trying to fetch ${this.modelType} that doesn't have the Instance parent model`);const r=await e.listCollections(t,{},{nameOnly:!1,fetchNamespacesFromPrivileges:n,privileges:a.auth.privileges});this.set(r.filter((e=>!1===l(e._id).system||"system.profile"===l(e._id).collection)).map((({_id:e,...t})=>({_id:e,...g(t)}))))},toJSON(e={derived:!0}){return this.map((t=>t.toJSON(e)))}});var y;f.prototype[Symbol.iterator]=function*(){for(let e=0,t=this.length;e<t;e++)yield this.at(e)},e.exports=h,e.exports.Collection=f},85561:(e,t,n)=>{n.d(t,{In:()=>c});var a=n(62183),r=n(70002),i=n(736),o=n(42279),s=n(20625),l=n(38659);n(89213),n(28592);const c=(0,a.nk)({name:"CompassGenerativeAI",component:i.Fi,activate:l.Bf},{atlasAuthService:r.L1,atlasAiService:o.Dr,preferences:s.fx})},86735:(e,t,n)=>{n.d(t,{jD:()=>h.j,Ay:()=>D});var a=n(55712),r=n(20625),i=n(62183),o=n(96652),s=n.n(o),l=n(44142),c=n(93885),d=n(28508),u=n(51295);(0,u.AHW)({listStyle:"decimal",paddingLeft:u.YKD[800],li:{marginTop:u.YKD[100],marginBottom:u.YKD[100]}}),(0,u.AHW)({display:"flex",flexDirection:"column",gap:u.YKD[400]}),(0,u.AHW)({maxHeight:2*u.YKD[1600],overflowY:"scroll"}),(0,u.AHW)({flexDirection:"row",justifyContent:"space-between"});var p=n(44969),m=n(90605),g=n(26783),h=n(60254),f=n(21119),y=n(34615);const b={connect:p.Ng,disconnect:p.Zf,cancelEditConnection:p.vS,saveEditedConnectionInfo:p.RW,saveAndConnect:p.F,openSettingsModal:p.gH},v=(0,g.Ng)((function({isEditingNewConnection:e,isEditingConnectionInfoModalOpen:t,editingConnectionInfoId:n,connections:a}){const r=n?a.byId[n]:void 0,i=r?.info,o=!!r&&"connected"===r.status;return{isOpen:t,initialConnectionInfo:i,connectionErrorMessage:r?.error?.message,disableEditingConnectedConnection:o,editingConnectionInfoId:n,isEditingNewConnection:e}}),b)((({initialConnectionInfo:e,editingConnectionInfoId:t,isEditingNewConnection:n,...i})=>{const l=function(){const e=(0,r.Fg)("protectConnectionStrings"),t=(0,r.Fg)("forceConnectionOptions"),n=(0,r.Fg)("showKerberosPasswordField"),a=(0,r.Fg)("showOIDCDeviceAuthFlow"),i=(0,r.Fg)("enableOidc"),s=(0,r.Fg)("enableDebugUseCsfleSchemaMap"),l=(0,r.Fg)("protectConnectionStringsForNewConnections");return(0,o.useMemo)((()=>({protectConnectionStrings:e,forceConnectionOptions:t,showKerberosPasswordField:n,showOIDCDeviceAuthFlow:a,enableOidc:i,enableDebugUseCsfleSchemaMap:s,protectConnectionStringsForNewConnections:l})),[e,t,n,a,i,s,l])}(),{disableEditingConnectedConnection:c,connect:d,disconnect:u,cancelEditConnection:p,saveEditedConnectionInfo:m,saveAndConnect:g}=i;return t&&e?s().createElement(y.GQ,(0,a.A)({initialConnectionInfo:e},i,l,{onDisconnectClicked:()=>u(t),setOpen:e=>{!1===e&&p(t)},onCancel:()=>{p(t)},onSaveClicked:e=>m(e),onConnectClicked:n||c?void 0:e=>{d(e)},onSaveAndConnectClicked:c?void 0:e=>{g(e)}})):null})),x=v,E=(0,u.AHW)({width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"row",gap:u.YKD[800]}),C=(0,u.AHW)({display:"flex",flexDirection:"column",gap:u.YKD[400],alignItems:"flex-start",maxWidth:"400px"}),w=()=>s().createElement("svg",{width:"154",height:"129",viewBox:"0 0 154 129",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s().createElement("path",{d:"M149.404 7.31042L4.55714 7.31042C2.63425 7.31042 1.07544 8.86748 1.07544 10.7882L1.07544 106.277C1.07544 108.198 2.63425 109.755 4.55714 109.755L149.404 109.755C151.326 109.755 152.885 108.198 152.885 106.277V10.7882C152.885 8.86748 151.326 7.31042 149.404 7.31042Z",fill:"#00ED64",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),s().createElement("path",{d:"M152.974 18.715L1.02637 18.715",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),s().createElement("path",{d:"M7.13535 15.7424C8.49683 15.7424 9.60052 14.64 9.60052 13.28C9.60052 11.9201 8.49683 10.8176 7.13535 10.8176C5.77387 10.8176 4.67017 11.9201 4.67017 13.28C4.67017 14.64 5.77387 15.7424 7.13535 15.7424Z",fill:"white"}),s().createElement("path",{d:"M14.5702 15.7424C15.9316 15.7424 17.0353 14.64 17.0353 13.28C17.0353 11.9201 15.9316 10.8176 14.5702 10.8176C13.2087 10.8176 12.105 11.9201 12.105 13.28C12.105 14.64 13.2087 15.7424 14.5702 15.7424Z",fill:"white"}),s().createElement("path",{d:"M22.005 15.7424C23.3665 15.7424 24.4702 14.64 24.4702 13.28C24.4702 11.9201 23.3665 10.8176 22.005 10.8176C20.6435 10.8176 19.5398 11.9201 19.5398 13.28C19.5398 14.64 20.6435 15.7424 22.005 15.7424Z",fill:"white"}),s().createElement("path",{d:"M97.5955 93.5632C122.569 93.5632 142.813 73.3413 142.813 48.3962C142.813 23.4512 122.569 3.22931 97.5955 3.22931C72.6224 3.22931 52.3777 23.4512 52.3777 48.3962C52.3777 73.3413 72.6224 93.5632 97.5955 93.5632Z",fill:"#00ED64",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),s().createElement("path",{d:"M26.8862 127.409C26.8862 127.409 24.9465 129.317 20.1487 124.441C15.3509 119.566 17.2907 117.662 17.2907 117.662L53.6643 82.1783C53.6643 82.1783 56.0068 80.9127 60.2889 85.2587C64.5661 89.6047 63.2648 91.9249 63.2648 91.9249L26.8911 127.409H26.8862Z",fill:"#FF9F10",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),s().createElement("path",{d:"M62.3858 93.936C62.3858 93.936 59.7537 95.1034 55.1081 90.522C50.4626 85.9405 51.597 83.2967 51.597 83.2967L60.014 74.7812C60.014 74.7812 61.0796 76.7433 64.9492 80.5645C68.8189 84.3807 70.7979 85.4206 70.7979 85.4206L62.3809 93.936H62.3858Z",fill:"#FFC010",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),s().createElement("path",{d:"M127.87 85.0576C109.534 103.609 79.6126 103.8 61.0452 85.4844C42.4729 67.1684 42.2813 37.2811 60.618 18.7346C78.9546 0.183208 108.876 -0.00809336 127.443 18.3079C146.015 36.6238 146.207 66.5111 127.87 85.0576ZM123.966 21.8249C107.338 5.42685 80.5555 5.59853 64.1389 22.2075C47.7224 38.8164 47.8943 65.5693 64.522 81.9674C81.1496 98.3654 107.933 98.1937 124.349 81.5847C140.766 64.9758 140.594 38.2229 123.966 21.8249Z",fill:"white",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),s().createElement("path",{d:"M65.6563 83.125L56.6893 91.9347C56.6893 91.9347 60.1367 94.7552 62.3808 93.936L69.8795 86.5684L65.6514 83.125H65.6563Z",fill:"black"}),s().createElement("path",{d:"M55.1081 90.522L20.2764 124.49C20.2764 124.49 24.2197 128.89 26.8862 127.409L61.0844 94.0586C61.0844 94.0586 58.3982 93.8575 55.1081 90.5171V90.522Z",fill:"black"}),s().createElement("path",{d:"M131.401 81.5897C113.064 100.141 83.1434 100.332 64.5759 82.0164C46.0036 63.7005 45.8121 33.8132 64.1487 15.2667C82.4853 -3.28475 112.406 -3.47605 130.974 14.8399C149.546 33.1559 149.738 63.0432 131.401 81.5897ZM127.497 18.3569C110.869 1.9589 84.0862 2.13058 67.6697 18.7395C51.2532 35.3485 51.4251 62.1014 68.0527 78.4994C84.6804 94.8974 111.463 94.7257 127.88 78.1168C144.296 61.5078 144.125 34.755 127.497 18.3569Z",fill:"#FF9F10",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),s().createElement("path",{d:"M105.183 68.5124V48.5385L87.8625 38.5515L70.5474 48.5385V68.5124L87.8625 78.4993L105.183 68.5124Z",fill:"black",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),s().createElement("path",{d:"M115.598 62.5232V42.5542L98.2831 32.5672L80.963 42.5542V62.5232L98.2831 72.5101L115.598 62.5232Z",fill:"#FF9F10",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),s().createElement("path",{d:"M115.598 51.5503V31.5764L98.2831 21.5894L80.963 31.5764V51.5503L98.2831 61.5323L115.598 51.5503Z",fill:"white",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"}),s().createElement("path",{d:"M101.063 53.6055C100.292 54.3756 99.3635 54.7632 98.2831 54.7632C97.2028 54.7632 96.2746 54.3756 95.5036 53.6055C94.7327 52.8354 94.3447 51.9083 94.3447 50.8292C94.3447 49.7501 94.7327 48.823 95.5036 48.0529C96.2746 47.2827 97.2028 46.8952 98.2831 46.8952C99.3635 46.8952 100.292 47.2827 101.063 48.0529C101.834 48.823 102.221 49.7501 102.221 50.8292C102.221 51.9083 101.834 52.8354 101.063 53.6055ZM96.5545 44.7222L95.4889 37.9531V28.3536H101.087V37.9531L99.9822 44.7222H96.5594H96.5545Z",fill:"black"}),s().createElement("path",{d:"M98.2831 61.5323V72.5102L80.963 62.5232V51.5503L98.2831 61.5323Z",fill:"black",stroke:"black",strokeLinecap:"round",strokeLinejoin:"round"})),I=()=>s().createElement("div",{className:E},s().createElement(w,null),s().createElement("div",{className:C},s().createElement(u.H3,null,"An error occurred while querying your MongoDB deployment"),s().createElement(u.nBu,null,"Please try again in a few minutes."),s().createElement(u.$nd,{as:"a",href:"#/clusters",variant:"default"},"Back to Clusters"))),S=(0,g.Ng)((e=>({activeConnections:(0,g.y2)(e.connections.byId),initialConnectionLoadFailed:"loading-error"===e.connections.status})))((({activeConnections:e,showErrorStateOnConnectionLoadError:t,initialConnectionLoadFailed:n,children:a})=>{const r=(0,o.useMemo)((()=>e.map((e=>({...e.info,connectOptions:(0,p.HP)(e.info.id)?.getMongoClientConnectionOptions()?.options??null})))),[e]);return(0,f.ZX)("activeConnections",r),t&&n?s().createElement(I,null):s().createElement(g.tI,null,a,s().createElement(x,null))})),A=(0,i.nk)({name:"CompassConnections",component:S,activate(e,{logger:t,preferences:n,connectionStorage:a,track:r,globalAppRegistry:i,compassAssistant:o},{addCleanup:s,cleanup:l}){const c=(0,p.U1)(e.preloadStorageConnectionInfos,{logger:t,preferences:n,connectionStorage:a,track:r,getExtraConnectionData:e.onExtraConnectionDataRequest,appName:e.appName,connectFn:e.connectFn,globalAppRegistry:i,compassAssistant:o});return setTimeout((()=>{c.dispatch((0,p.K7)()),e.onAutoconnectInfoRequest&&c.dispatch((0,p.c7)(e.onAutoconnectInfoRequest,e.doNotReconnectDisconnectedAutoconnectInfo))})),s(n.onPreferenceValueChanged("persistOIDCTokens",(e=>{!1===e&&(async()=>{let e;try{e=await a.loadAll()}catch(e){return void t.log.warn(t.mongoLogId(1001000431),"Connection Storage","Failed to load connections when purging OIDC tokens",{error:e.message})}for(const n of e)if(n.connectionOptions.oidc?.serializedState)try{const e=(0,m.cloneDeep)(n);delete e.connectionOptions.oidc.serializedState,await(a.save?.({connectionInfo:e}))}catch(e){t.log.warn(t.mongoLogId(1001000432),"Connection Storage","Failed to purge OIDC tokens from connection",{connectionId:n.id,error:e.message})}})()}))),s((()=>{for(const e of c.getState().connections.ids)c.dispatch((0,p.Zf)(e))})),{store:c,deactivate:l,context:g.wA}}},{logger:(0,l.fF)("COMPASS-CONNECTIONS"),preferences:r.fx,connectionStorage:c.Qn,track:d.yL,compassAssistant:f.eD}),k=s().createContext(void 0);function D(e){const t=(0,o.useContext)(k);return s().createElement(A,(0,a.A)({connectFn:t},e))}},88261:(e,t,n)=>{n.d(t,{Q:()=>ai});var a=n(96652),r=n.n(a),i=n(62183),o=n(82162);const s="indexes/is-writable/WRITE_STATE_CHANGED";function l(e,t){return e.type===t}var c=n(13353),d=n(9174),u=n(51295),p=(n(95039),n(21261),n(92879),n(31977),n(49743),n(9656),n(72673),n(35467),n(94476),n(64971),n(24330),n(83478),n(65166),n(1256),n(61038),n(73035),n(23855),n(90605));const m="NOT_READY",g="READY",h="FETCHING",f="REFRESHING",y="POLLING",b="ERROR",v=["FETCHING","POLLING","REFRESHING"];function x(e){return e===g||e===f||e===y}const E="INITIAL_FETCH",C="REFRESH",w="POLL",I=e=>r().createElement(r().Fragment,null,"The index `",r().createElement("b",null,e),"` will no longer be visible to the query planner and cannot be used to support a query. If the impact is negative, you can unhide this index."),S=e=>r().createElement(r().Fragment,null,"The index `",r().createElement("b",null,e),"` will become visible to the query planner and can be used to support a query. If the impact is negative, you can hide this index.");var A=n(48783),k=n.n(A);const D="20.0.0-alpha0";function N(e){if(!e)return!0;try{return k().gte(e,D)}catch{return!0}}var M=n(86735),T=n(69692);function P(e){const{serverVersion:t,collectionStats:n}=e;return{isViewVersionSearchCompatible:T.rd.isVersionSearchCompatibleForViewsCompass(t),isViewPipelineSearchQueryable:!n?.pipeline||T.rd.isPipelineSearchQueryable(n?.pipeline)}}function L({readOnly:e,readWrite:t,enableAtlasSearchIndexes:n,enableSearchActivationProgramP1:a}){return r=>{const{isWritable:i,isReadonlyView:o,isSearchIndexesSupported:s}=r,{isViewVersionSearchCompatible:l,isViewPipelineSearchQueryable:c}=P(r),d=!o,u=(n||a)&&(o?l:s);return{isRegularIndexesReadable:d,isRegularIndexesWritable:d&&!e&&!t&&i,isSearchIndexesReadable:u,isSearchIndexesWritable:u&&!e&&!t&&i&&(!o||l&&c)}}}const O="compass-indexes/regular-indexes/fetch-indexes-started",R="compass-indexes/regular-indexes/fetch-indexes-succeeded",H="compass-indexes/regular-indexes/fetch-indexes-failed",F="compass-indexes/regular-indexes/failed-index-removed",W="compass-indexes/create-index/index-creation-started",j="compass-indexes/create-index/index-creation-failed",B="compass-indexes/create-index/rolling-index-timeout-check",z={status:m,indexes:[],inProgressIndexes:[],error:void 0},_=(e,t)=>({type:R,indexes:e,rollingIndexes:t}),$=["name","size"];function Y(e){return e.regularIndexes.indexes.map((e=>(0,p.pick)(e,$)))}const K=e=>async(t,n,{dataService:a,collection:r,connectionInfoRef:i,rollingIndexesService:o,preferences:s})=>{const{namespace:l,regularIndexes:{status:c},isWritable:d}=n(),{readOnly:u,readWrite:m,enableAtlasSearchIndexes:g}=s.getPreferences(),{isRegularIndexesReadable:h}=L({readOnly:u,readWrite:m,enableAtlasSearchIndexes:g,enableSearchActivationProgramP1:!1})(n());if(!h||!d)return void t(_([]));if(v.includes(c))return;const f=(0,M.jD)(i.current,"rollingIndexCreation"),y=!!s.getPreferences().enableRollingIndexes,b=f&&y;try{t((e=>({type:O,reason:e}))(e));const i=[a.indexes(l),b?o.listRollingIndexes(l):Promise.resolve(void 0)],[s,c]=await Promise.all(i),d=Y(n());t(_(s,c));const u=Y(n());e===E||(0,p.isEqual)(d,u)||r.fetch({dataService:a,force:!0}).catch((()=>{}))}catch(e){t((x=e.message,{type:H,error:x}))}var x},G=()=>async e=>{await e(K(E))},V=()=>async e=>{await e(K(C))},U=()=>function(e,t,{pollingIntervalRef:n}){null===n.regularIndexes&&(n.regularIndexes=setInterval((()=>{e((async e=>await e(K(w))))}),5e3))},q=()=>(e,t,{pollingIntervalRef:n})=>{null!==n.regularIndexes&&(clearInterval(n.regularIndexes),n.regularIndexes=null)};const Z=u.$TK,J=e=>(t,n)=>{const{regularIndexes:a}=n(),{inProgressIndexes:r}=a,i=r.find((t=>t.name===e));var o;i&&"failed"===i.status&&t((o=String(i.id),{type:F,inProgressIndexId:o}))},Q=e=>async(t,n,{connectionInfoRef:a,dataService:r,track:i})=>{const{namespace:o,regularIndexes:s}=n(),{indexes:l}=s;if(l.find((t=>t.name===e)))try{const n=a.current;if(i("Screen",{name:"drop_index_modal"},n),!await Z({variant:"danger",title:"Drop Index",description:`Are you sure you want to drop index "${e}"?`,requiredInputText:e,buttonText:"Drop","data-testid":"drop-index-modal"}))return;await r.dropIndex(o,e),i("Index Dropped",{atlas_search:!1},n),(0,u.c3r)("drop-index-success",{variant:"success",title:`Index "${e}" dropped`,timeout:3e3}),await t(K(C))}catch(t){(0,u.c3r)("drop-index-error",{variant:"important",title:`Failed to drop index "${e}"`,description:t.message,timeout:3e3})}},X=e=>async(t,n,{dataService:a})=>{const{namespace:r}=n();if(await Z({title:`Hiding \`${e}\``,description:I(e)}))try{await a.updateCollection(r,{index:{name:e,hidden:!0}}),await t(K(C))}catch(e){(0,u.c3r)("hide-index-error",{title:"Failed to hide the index",variant:"warning",description:`An error occurred while hiding the index. ${e.message}`})}},ee=e=>async(t,n,{dataService:a})=>{const{namespace:r}=n();if(await Z({title:`Unhiding \`${e}\``,description:S(e)}))try{await a.updateCollection(r,{index:{name:e,hidden:!1}}),await t(K(C))}catch(e){(0,u.c3r)("unhide-index-error",{title:"Failed to unhide the index",variant:"warning",description:`An error occurred while unhiding the index. ${e.message}`})}},te="compass-indexes/create-index/fields/field-added",ne="compass-indexes/create-index/fields/field-type-updated",ae="compass-indexes/create-index/fields/field-removed",re="compass-indexes/create-index/fields/fields-changed",ie="compass-indexes/create-index/option-changed",oe="compass-indexes/create-index/option-toggled",se="compass-indexes/create-index/error-encountered",le="compass-indexes/create-index/error-cleared",ce="compass-indexes/create-index/create-index-shown",de="compass-indexes/create-index/create-index-hidden",ue="compass-indexes/create-index/create-index-form-submitted",pe={unique:{type:"checkbox",label:"Create unique index",description:"A unique index ensures that the indexed fields do not store duplicate values; i.e. enforces uniqueness for the indexed fields."},name:{type:"text",label:"Index name",description:"Enter the name of the index to create, or leave blank to have MongoDB create a default name for the index.",units:void 0,optional:!0},expireAfterSeconds:{type:"number",label:"Create TTL",description:"TTL indexes are special single-field indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time or at a specific clock time.",units:"seconds",optional:!1},partialFilterExpression:{type:"code",label:"Partial Filter Expression",description:"Partial indexes only index the documents in a collection that meet a specified filter expression.",units:void 0,optional:!1},wildcardProjection:{type:"code",label:"Wildcard Projection",description:"Wildcard indexes support queries against unknown or arbitrary fields.",units:void 0,optional:!1},collation:{type:"code",label:"Use Custom Collation",description:"Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.",units:void 0,optional:!1},columnstoreProjection:{type:"code",label:r().createElement(r().Fragment,null,"Columnstore Projection ",r().createElement(u.Exy,null,"Preview")),description:"Columnstore indexes support queries against unknown or arbitrary fields.",units:void 0,optional:!1},sparse:{type:"checkbox",label:"Create sparse index",description:"Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value. The index skips over any document that is missing the indexed field."},buildInRollingProcess:{type:"checkbox",label:"Build in rolling process",description:r().createElement(r().Fragment,null,"Building an index in a rolling fashion reduces the resiliency of your cluster and increases index build times. We only recommend using rolling index builds when regular index builds do not meet your needs."," ",r().createElement(u.N_E,{href:"https://www.mongodb.com/docs/manual/core/rolling-index-builds/"},"Learn More"))}};function me(e,t){return{type:ie,name:e,value:t}}const ge=Object.fromEntries(Object.keys(pe).map((e=>[e,{value:"checkbox"!==pe[e].type&&"",enabled:!1}]))),he={indexId:(new c.ObjectId).toHexString(),isVisible:!1,error:null,fields:[{name:"",type:""}],options:ge},fe=e=>t=>{t({type:ce,initialQuery:e})},ye=e=>({type:se,error:e});function be(e){if("1 (asc)"===e)return 1;if("-1 (desc)"===e)return-1;if("text (full text search)"===e)return"text";if("2dsphere"===e)return e;throw new Error(`Unsupported field type: ${e}`)}function ve(e){return function(e){const t=e?.fields;return!!Array.isArray(t)&&t.some((e=>null!==e&&"object"==typeof e&&"autoEmbed"===e.type))}(e.latestDefinition)}n(59509),n(25691),n(23177),n(3142),n(51615),n(84217),n(25953),n(42319),n(28465),n(12887),n(36106),n(84542),n(57068),n(69517);var xe=n(70002),Ee=n(28508);const Ce={InvalidIndexSpecificationOption:"Invalid index definition.",IndexAlreadyExists:"This index name is already in use. Please choose another one."},we="compass-indexes/search-indexes/fetch-search-indexes-started",Ie="compass-indexes/search-indexes/fetch-search-indexes-succeeded",Se="compass-indexes/search-indexes/fetch-search-indexes-failed",Ae="compass-indexes/search-indexes/create-search-index-opened",ke="compass-indexes/search-indexes/create-search-index-closed",De="compass-indexes/search-indexes/create-search-index-started",Ne="compass-indexes/search-indexes/create-search-index-failed",Me="compass-indexes/search-indexes/create-search-index-succeeded",Te="compass-indexes/search-indexes/update-search-index-opened",Pe="compass-indexes/search-indexes/update-search-index-closed",Le="compass-indexes/search-indexes/update-search-index-started",Oe="compass-indexes/search-indexes/update-search-index-failed",Re="compass-indexes/search-indexes/update-search-index-succeeded",He={status:m,createIndex:{isModalOpen:!1,isBusy:!1},updateIndex:{isModalOpen:!1,isBusy:!1,indexName:""},error:void 0,indexes:[]},Fe=()=>({type:Ae}),We=()=>({type:ke}),je=()=>({type:Pe}),Be=e=>({type:Ie,indexes:e}),ze=e=>({type:Ne,error:e}),_e=()=>function(e,t,{pollingIntervalRef:n}){null===n.searchIndexes&&(n.searchIndexes=setInterval((()=>{e(qe())}),5e3))},$e=()=>(e,t,{pollingIntervalRef:n})=>{null!==n.searchIndexes&&(clearInterval(n.searchIndexes),n.searchIndexes=null)},Ye=({name:e,type:t,definition:n})=>async function(a,r,{track:i,connectionInfoRef:o,dataService:s}){const{namespace:l,searchIndexes:c}=r();if(a({type:De}),""!==e)if(c.indexes.some((t=>t.name===e)))a(ze(Ce.IndexAlreadyExists));else{try{await s.createSearchIndex(l,{name:e,definition:n,...t?{type:t}:{}})}catch(e){const n=e.message;return a(ze(Ce[n]||n)),void i("Index Create Failed",{atlas_search:!0,type:t},o.current)}a({type:Me}),i("Index Created",{atlas_search:!0,type:t},o.current),(0,u.c3r)("search-index-creation-in-progress",{title:`Your index ${e} is in progress.`,dismissible:!0,timeout:5e3,variant:"progress"}),a(rt()),await a(Ge(C))}else a(ze("Please enter the name of the index."))},Ke=({name:e,definition:t})=>async function(n,a,{track:r,connectionInfoRef:i,dataService:o}){const{namespace:s,searchIndexes:{indexes:l}}=a(),c=l.find((t=>t.name===e))?.latestDefinition;if((0,p.isEqual)(c,t))n(je());else try{n({type:Le}),await o.updateSearchIndex(s,e,t),n({type:Re}),r("Index Edited",{atlas_search:!0},i.current),(0,u.c3r)("search-index-update-in-progress",{title:`Your index ${e} is being updated.`,dismissible:!0,timeout:5e3,variant:"progress"}),await n(Ge(C))}catch(e){const t=e.message;return void n((e=>({type:Oe,error:e}))(Ce[t]||t))}},Ge=e=>async(t,n,{dataService:a,preferences:i,connectionInfoRef:o,experimentationServices:s,track:l})=>{const{isWritable:c,namespace:d,searchIndexes:{status:p,indexes:m}}=n(),{readOnly:g,readWrite:h,enableAtlasSearchIndexes:f}=i.getPreferences(),{atlasMetadata:y}=o.current,b=await s.getAssignment(Ee.Cv.searchActivationProgramP1,!1),x=b?.assignmentData?.variant===Ee.qP.searchActivationProgramP1Variant,{isSearchIndexesReadable:C}=L({readOnly:g,readWrite:h,enableAtlasSearchIndexes:f,enableSearchActivationProgramP1:x})(n());var w;if(C&&c){if(!v.includes(p))try{t((e=>({type:we,reason:e}))(e));const n=await a.getSearchIndexes(d);t(Be(n)),x&&e!==E&&function(e,t,n,a,i){const o=new Map(e.map((e=>[e.name,e])));for(const e of t){const t=o.get(e.name),s="vectorSearch"===e.type?"Vector search index":"Search index";"BUILDING"===e.status?t?"READY"!==t.status&&"FAILED"!==t.status||(0,u.c3r)(`search-index-rebuilding-${e.name}`,{title:`${s} is rebuilding`,description:`${s} ${e.name} is rebuilding and is ${t.queryable?"queryable":"non-queryable"}.`,dismissible:!0,timeout:5e3,variant:"progress"}):(0,u.c3r)(`search-index-building-${e.name}`,{title:"Index build in progress",description:`${s} ${e.name} is building and is non-queryable.`,dismissible:!0,timeout:5e3,variant:"progress"}):"FAILED"===e.status&&"FAILED"!==t?.status?(0,u.c3r)(`search-index-build-failed-${e.name}`,{title:`${s} build failed`,description:r().createElement(r().Fragment,null,"The index build for ",e.name," failed and is"," ",e.queryable?"queryable":"non-queryable","."," ",n?r().createElement(u.N_E,{href:(0,xe.Yc)({atlasMetadata:n,namespace:a,indexName:e.name,view:"StatusDetails"}),target:"_blank",onClick:()=>i(e)},"View Status Details by Node"):null),dismissible:!0,timeout:0,variant:"warning"}):"READY"===e.status&&"READY"!==t?.status&&(0,u.c3r)(`search-index-build-success-${e.name}`,{title:`${s} build complete`,description:`Your ${s.toLowerCase()} ${e.name} has finished building and is queryable.`,dismissible:!0,timeout:5e3,variant:"success"})}}(m,n,y,d,(e=>{l("Search Index Status Details Link Clicked",{index_type:e.type??"search"})}))}catch(e){t((w=e.message,{type:Se,error:w}))}}else t(Be([]))},Ve=()=>async e=>{await e(Ge(E))},Ue=()=>async e=>{await e(Ge(C))},qe=()=>async e=>await e(Ge(w)),Ze=u.$TK,Je=e=>async function(t,n,{track:a,connectionInfoRef:r,dataService:i,preferences:o}){const{namespace:s,searchIndexes:l}=n(),{enableAutoEmbeddingPublicPreview:c}=o.getPreferences(),d=l.indexes.find((t=>t.name===e)),p=Boolean(c)&&void 0!==d&&ve(d)?"Dropping this index will permanently remove all generated vector embeddings associated with it. All queries that use this index will stop working. If you create a new index later, embeddings will be generated again and will use additional tokens.":"If you drop this index, all queries using it will no longer function.";if(await Ze({title:`Are you sure you want to drop "${e}" from Cluster?`,buttonText:"Drop Index",variant:"danger",requiredInputText:e,description:p}))try{await i.dropSearchIndex(s,e),a("Index Dropped",{atlas_search:!0},r.current),(0,u.c3r)("search-index-delete-in-progress",{title:`Your index ${e} is being deleted.`,dismissible:!0,timeout:5e3,variant:"progress"}),await t(Ge(C))}catch(e){(0,u.c3r)("search-index-delete-failed",{title:"Failed to drop index.",description:e.message,dismissible:!0,timeout:5e3,variant:"warning"})}};function Qe(e){return[{$search:{index:e,text:{query:"string",path:"string"}}}]}function Xe(e){return`[\n {\n $vectorSearch: {\n // Name of the Atlas Vector Search index to use.\n index: ${JSON.stringify(e)},\n // Indexed vectorEmbedding type field to search.\n "path": "<field-to-search>",\n // Array of numbers that represent the query vector.\n // The array size must match the number of vector dimensions specified in the index definition for the field.\n "queryVector": [],\n // Number of nearest neighbors to use during the search.\n // Value must be less than or equal to (<=) 10000.\n "numCandidates": 50,\n "limit": 10,\n // Any MQL match expression that compares an indexed field with a boolean,\n // number (not decimals), or string to use as a prefilter.\n "filter": {}\n },\n },\n]`}function et(e){const t=(n=T.cn.snippet,a=e,n.replace(/\$\{(\d+):[^}]*\}/g,((e,t)=>{switch(t){case"1":return'"string"';case"2":return"0";case"3":return"1";case"4":return JSON.stringify("<field-to-search>");case"5":return"50";case"6":return JSON.stringify(a);case"7":return"10";case"8":return"";case"9":return"false";default:return"null"}}))).trim();var n,a;return`[\n {\n $vectorSearch: ${T.cn.comment} ${t}\n },\n]`}const tt="compass-indexes/index-list/index-view-changed",nt="regular-indexes",at=e=>({type:tt,view:e}),rt=()=>at("search-indexes"),it="indexes/description/GET_DESCRIPTION";function ot(e){const{index_count:t,index_size:n,pipeline:a}=e.toJSON();return{index_count:t,index_size:n,pipeline:a}}const st="compass-indexes/CollectionStatsFetchedCollection",lt={currentView:"indexes-list",currentIndexType:"search",currentIndexName:"",expandedRows:{},isRegularIndexesAccordionOpen:!0,isDirty:!1},ct="indexes/drawer/OPEN_INDEXES_LIST_DRAWER_VIEW",dt="indexes/drawer/OPEN_CREATE_SEARCH_INDEX_DRAWER_VIEW",ut="indexes/drawer/OPEN_EDIT_SEARCH_INDEX_DRAWER_VIEW",pt="indexes/drawer/SET_IS_DIRTY",mt="indexes/drawer/SET_EXPANDED_ROWS",gt="indexes/drawer/SET_REGULAR_INDEXES_ACCORDION_OPEN",ht=u.$TK,ft=async e=>!e||ht({title:"Any unsaved progress will be lost",buttonText:"Discard",variant:"danger",description:"Are you sure you want to continue?"}),yt=e=>async(t,n)=>{const a=n();if(!await ft(a.indexesDrawer.isDirty))return;const r=e&&a.searchIndexes.indexes.some((t=>t.name===e));t({type:ct,expandedRows:r?{[e]:!0}:{}})},bt=e=>async(t,n)=>{const{isDirty:a}=n().indexesDrawer;await ft(a)&&t({type:dt,currentIndexType:e})},vt=e=>async(t,n)=>{const{isDirty:a}=n().indexesDrawer;await ft(a)&&t({type:ut,currentIndexName:e})},xt=e=>({type:pt,isDirty:e}),Et=(0,o.HY)({isWritable:(e=!0,t)=>t.type===s?t.isWritable:e,isReadonlyView:function(e=!1,t){return"indexes/is-readonly-view/READONLY_VIEW_CHANGED"===t.type?t.isReadonlyView:e},isSearchIndexesSupported:function(e=!1,t){return"indexes/is-search-indexes-supported/is-search-indexes-supported-changed"===t.type?t.isSearchIndexesSupported:e},indexView:function(e=nt,t){return l(t,ce)?"regular-indexes":l(t,Ae)?"search-indexes":l(t,tt)?t.view:e},description:(e="Topology type not yet discovered.",t)=>t.type===it?t.description:e,serverVersion:function(e="4.0.0",t){return"compass-indexes/server-version/SERVER_VERSION_CHANGED"===t.type&&t.version||e},namespace:function(e="",t){return"explain/namespace/NAMESPACE_CHANGED"===t.type?t.namespace:e},regularIndexes:function(e=z,t){if(l(t,"compass-indexes/regular-indexes/indexes-opened"))return e;if(l(t,"compass-indexes/regular-indexes/indexes-closed"))return e;if(l(t,O))return{...e,status:t.reason===w?y:t.reason===C?f:h};if(l(t,R)){const n=new Set(t.indexes.map((e=>e.name)).concat((t.rollingIndexes??[]).map((e=>e.indexName)))),a=(0,p.isEqual)(e.indexes,t.indexes)?e.indexes:t.indexes,r=(0,p.isEqual)(e.rollingIndexes,t.rollingIndexes)?e.rollingIndexes:t.rollingIndexes,i=e.inProgressIndexes.filter((e=>!!e.error||!n.has(e.name))),o=(0,p.isEqual)(e.inProgressIndexes,i)?e.inProgressIndexes:i;return{...e,indexes:a,rollingIndexes:r,inProgressIndexes:o,status:g}}if(l(t,H))return{...e,error:e.status===h?(n=t.error,/[A-Z_]+:/.test(n)||/\b(4\d{2}|5\d{2})\b/.test(n)?"We're sorry, an unexpected error has occurred. Please try again.":n):e.error,status:e.status===h?b:g};var n;if(l(t,W)){const n=[...e.inProgressIndexes,t.inProgressIndex];return{...e,inProgressIndexes:n}}if(l(t,F))return{...e,inProgressIndexes:e.inProgressIndexes.filter((e=>e.id!==t.inProgressIndexId))};if(l(t,j)){const n=e.inProgressIndexes.findIndex((e=>e.id===t.inProgressIndexId)),a=e.inProgressIndexes;return a[n]={...a[n],status:"failed",error:t.error},{...e,inProgressIndexes:a}}if(l(t,B)){const n=e.inProgressIndexes.filter((e=>e.id!==t.indexId));return n.length===e.inProgressIndexes.length?e:{...e,inProgressIndexes:n}}return e},searchIndexes:function(e=He,t){if(l(t,Ae))return{...e,createIndex:{isModalOpen:!0,isBusy:!1}};if(l(t,ke))return{...e,createIndex:{isModalOpen:!1,isBusy:!1}};if(l(t,De))return{...e,createIndex:{...e.createIndex,isBusy:!0,error:void 0}};if(l(t,Ne))return{...e,createIndex:{...e.createIndex,error:t.error,isBusy:!1}};if(l(t,Me))return{...e,createIndex:{isModalOpen:!1,isBusy:!1}};if(l(t,Te))return{...e,updateIndex:{isModalOpen:!0,isBusy:!1,indexName:t.indexName}};if(l(t,Le))return{...e,updateIndex:{...e.updateIndex,error:void 0,isBusy:!0}};if(l(t,Oe))return{...e,updateIndex:{...e.updateIndex,error:t.error,isBusy:!1}};if(l(t,Re))return{...e,updateIndex:{...e.updateIndex,isBusy:!1,isModalOpen:!1,error:void 0}};if(l(t,Pe))return{...e,updateIndex:{...e.updateIndex,isModalOpen:!1,isBusy:!1,error:void 0}};if(l(t,we))return{...e,status:t.reason===w?y:t.reason===C?f:h};if(l(t,Ie)){const n=(0,p.isEqual)(e.indexes,t.indexes)?e.indexes:t.indexes;return{...e,indexes:n,status:g}}return l(t,Se)?{...e,error:e.status===h?t.error:e.error,status:e.status===h?b:g}:e},createIndex:(e=he,t)=>{if(l(t,te))return{...e,fields:[...e.fields,{name:"",type:""}],error:null};if(l(t,ae)){const n=[...e.fields];return n.splice(t.idx,1),{...e,fields:n,error:null}}if(l(t,ne)){const n=[...e.fields];if(t.idx>=0&&t.idx<n.length){const e={...n[t.idx]};e.type=t.fType,n[t.idx]=e}return{...e,fields:n,error:null}}return l(t,re)?{...e,fields:t.fields,error:null}:l(t,ie)?{...e,options:{...e.options,[t.name]:{value:t.value,enabled:"checkbox"===pe[t.name].type||e.options[t.name].enabled}}}:l(t,oe)?{...e,options:{...e.options,[t.name]:{...e.options[t.name],enabled:t.enabled}}}:l(t,ce)?{...{...JSON.parse(JSON.stringify(he)),indexId:(new c.ObjectId).toHexString()},isVisible:!0}:l(t,se)?{...e,error:t.error}:l(t,le)?{...e,error:null}:l(t,de)||l(t,ue)?{...e,isVisible:!1}:e},collectionStats:(e=null,t)=>function(e,t){return e.type===t}(t,st)?ot(t.collection):e,indexesDrawer:function(e=lt,t){return l(t,ct)?{...e,currentView:"indexes-list",expandedRows:t.expandedRows,isRegularIndexesAccordionOpen:0===Object.keys(t.expandedRows).length}:l(t,dt)?{...e,currentView:"create-search-index",currentIndexType:t.currentIndexType}:l(t,ut)?{...e,currentView:"edit-search-index",currentIndexName:t.currentIndexName}:l(t,pt)?{...e,isDirty:t.isDirty}:l(t,mt)?{...e,expandedRows:t.expandedRows}:l(t,gt)?{...e,isRegularIndexesAccordionOpen:t.isOpen}:l(t,Me)||l(t,Re)||l(t,ke)||l(t,Pe)?{...e,isDirty:!1}:e}}),Ct=Et;var wt=n(67219),It=n(17855);class St{atlasService;connectionInfo;constructor(e,t){this.atlasService=e,this.connectionInfo=t}async listRollingIndexes(e){const{atlasMetadata:t}=this.connectionInfo.current;if(!t)throw new Error("Can't list rolling indexes for a non-Atlas cluster: atlasMetadata is not available");const{database:n,collection:a}=(0,It.Ay)(e),r=await this.atlasService.automationAgentRequest(t,"listIndexStats",{db:n,collection:a});if(!r)throw new Error("Unexpected response from the automation agent backend: expected to get the request metadata, got undefined");return(await this.atlasService.automationAgentAwait(t,r.requestType,r._id)).response.filter((e=>"rolling build"===e.status))}async createRollingIndex(e,t,{collation:n,...a}){const{atlasMetadata:r}=this.connectionInfo.current;if(!r)throw new Error("Can't create a rolling index for a non-Atlas cluster: atlasMetadata is not available");if("serverless"===r.metricsType||"flex"===r.metricsType)throw new Error("Flex clusters do not support rolling index build creation");const{database:i,collection:o}=(0,It.Ay)(e),s={clusterId:r.metricsId,db:i,collection:o,keys:JSON.stringify(t),options:Object.keys(a).length>0?JSON.stringify(a):"",collationOptions:n?JSON.stringify(n):""},l=this.atlasService.cloudEndpoint(`/explorer/v1/groups/${r.projectId}/clusters/${r.metricsId}/index`);await this.atlasService.authenticatedFetch(l,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)})}}var At=n(19125),kt=n(20625),Dt=n(60783);const Nt=(0,u.AHW)({display:"flex",flexDirection:"row",gap:u.YKD[200],justifyContent:"flex-start",alignItems:"center"}),Mt=(0,u.AHW)({padding:u.YKD[400],paddingBottom:0}),Tt=(0,u.AHW)({marginLeft:"auto"}),Pt=(0,u.AHW)({marginRight:u.YKD[200]}),Lt=(0,u.AHW)({display:"inline-block",width:"fit-content"}),Ot=({isSearchManagementActive:e,isSearchIndexesSupported:t,isWritable:n,onCreateRegularIndexClick:i,onCreateSearchIndexClick:o,isReadonlyView:s,indexView:l,isViewPipelineSearchQueryable:c})=>{const d=(0,Ee.Jr)(),p=(0,a.useCallback)((e=>{switch(e){case"createRegularIndex":return i();case"createSearchIndex":return o()}}),[i,o]);return s&&e?"search-indexes"===l?r().createElement(u.$nd,{disabled:!n||!c,onClick:()=>{o(),d("Create Search Index for View Clicked",{context:"Indexes Tab"})},variant:"primary",size:"small"},"Create Search Index"):null:!s&&t&&e?r().createElement(u.F1Z,{"data-testid":"multiple-index-types-creation-dropdown",buttonText:"Create",buttonProps:{size:"small",variant:"primary",disabled:!n},actions:[{action:"createRegularIndex",label:"Index"},{action:"createSearchIndex",label:"Search Index"}],onAction:p,hideOnNarrow:!1}):r().createElement(u.$nd,{"data-testid":"open-create-index-modal-button",disabled:!n,onClick:i,variant:"primary",size:"small"},"Create Index")},Rt={onCreateRegularIndexClick:()=>fe(),onCreateSearchIndexClick:Fe,onIndexViewChanged:at},Ht=(0,At.Ng)((({namespace:e,isWritable:t,isReadonlyView:n,isSearchIndexesSupported:a,description:r,serverVersion:i,searchIndexes:o,indexView:s,collectionStats:l})=>({namespace:e,isWritable:t,isReadonlyView:n,isSearchIndexesSupported:a,writeStateDescription:r,indexView:s,serverVersion:i,searchIndexes:o,collectionStats:l})),Rt)((({namespace:e,indexView:t,errorMessage:n,isReadonlyView:a,isWritable:i,onCreateRegularIndexClick:o,onCreateSearchIndexClick:s,isRefreshing:l,writeStateDescription:c,hasTooManyIndexes:d,showAtlasSearchLink:p,isSearchIndexesSupported:m,onRefreshIndexes:g,onIndexViewChanged:h,serverVersion:f,collectionStats:y})=>{const{readWrite:b,enableAtlasSearchIndexes:v,showInsights:x}=(0,kt.gc)(["readWrite","enableAtlasSearchIndexes","showInsights"]),{enableSearchActivationProgramP1:E}=(0,Ee.p5)(),C=v||E,{atlasMetadata:w}=(0,Dt.qm)(),I=(0,Ee.Jr)(),S=x&&!n,A=(!a||T.rd.isVersionSearchCompatibleForViewsCompass(f))&&!b&&!n,D=l?r().createElement("div",{className:Pt},r().createElement(u.Q0K,{title:"Refreshing Indexes"})):r().createElement(u.Int,{glyph:"Refresh",title:"Refresh Indexes"}),N=!a||!y?.pipeline||T.rd.isPipelineSearchQueryable(y.pipeline);return r().createElement("div",{className:Mt,"data-testid":"indexes-toolbar-container"},(!a||T.rd.isVersionSearchCompatibleForViewsCompass(f)&&C)&&r().createElement("div",{"data-testid":"indexes-toolbar"},r().createElement("div",{className:Nt},A&&r().createElement(u.m_M,{enabled:!i||!N,align:"top",justify:"middle",trigger:r().createElement("div",{className:Lt},r().createElement(Ot,{isSearchManagementActive:C,isSearchIndexesSupported:m,isWritable:i,onCreateRegularIndexClick:o,onCreateSearchIndexClick:s,isReadonlyView:a,indexView:t,isViewPipelineSearchQueryable:N}))},!i&&c||!N&&"Search indexes can only be created on views containing $match stages with the $expr operator, $addFields, or $set"),r().createElement(u.$nd,{"data-testid":"refresh-indexes-button",disabled:l,onClick:()=>g(),variant:"default",size:"small",leftGlyph:D},"Refresh"),p&&w&&r().createElement(u.N_E,{href:(0,xe.Yc)({atlasMetadata:w,namespace:e}),onClick:()=>{I("Manage Search Indexes Link Clicked",{context:"Indexes Tab"})},hideExternalIcon:!0,arrowAppearance:"persist"},"Manage your search indexes"),S&&d&&r().createElement(u.gIH,{signals:u.qpO.get("too-many-indexes")}),C&&r().createElement(u.IzF,{size:"xsmall",onChange:e=>h(e),className:Tt,label:"Viewing",value:t,"data-testid":"indexes-segment-controls"},a&&r().createElement(u.m_M,{align:"top",justify:"end",enabled:!0,renderMode:"portal",trigger:r().createElement(u.Zib,{"data-testid":"regular-indexes-tab",value:"regular-indexes",disabled:a},"Indexes")},"Readonly views may not contain standard indexes."),!a&&r().createElement(u.Zib,{"data-testid":"regular-indexes-tab",value:"regular-indexes"},"Indexes"),!m&&!a&&r().createElement(u.m_M,{align:"top",justify:"end",enabled:!0,renderMode:"portal",trigger:r().createElement(u.Zib,{"data-testid":"search-indexes-tab",value:"search-indexes",disabled:!0},"Search Indexes")},(e=>{try{return k().gte(e,"6.0.7")}catch{return!1}})(f)?r().createElement("p",null,"Unable to fetch search indexes. This can occur when your cluster does not support search indexes or the request to list search indexes failed."):r().createElement(r().Fragment,null,r().createElement("p",null,"Atlas Search index management in Compass is only available for Atlas local deployments and clusters running MongoDB 6.0.7 or newer."),r().createElement("p",null,"For clusters running an earlier version of MongoDB, you can manage your Atlas Search indexes from the Atlas web Ul, with the CLI, or with the Administration API."))),(m||a)&&r().createElement(u.Zib,{"data-testid":"search-indexes-tab",value:"search-indexes"},"Search Indexes")))),!!n&&r().createElement(u.dFH,{"data-testid":"indexes-error",errors:[n]}))}));var Ft=n(45363);const Wt=(0,u.AHW)({width:"100%",height:"100%"}),jt=(0,u.AHW)({width:"100%",height:"100%",paddingBottom:u.YKD[400]}),Bt="index-actions-cell",zt=(0,u.AHW)({":hover":{[`.${Bt}`]:{button:{opacity:1}}}}),_t=(0,u.AHW)({button:{opacity:0,"&:focus":{opacity:1}},minWidth:u.YKD[800]}),$t=(0,u.AHW)({zIndex:5,background:u.MFm.white}),Yt=(0,u.AHW)({background:u.MFm.black}),Kt=(0,u.AHW)({whiteSpace:"nowrap","> div":{justifyContent:"space-between"}});function Gt({id:e,"data-testid":t,columns:n,data:i,tableWrapperClassName:o,cellClassName:s,showActionsOnHover:l=!0,expanded:c,onExpandedChange:d}){const[p,m]=(0,Ft.i2)(`${e}-sorting-state`,[]),[g,h]=(0,a.useState)({}),f=c??g,y=d??h,b=(0,a.useRef)(f);b.current=f;const v=(0,a.useCallback)((e=>{const t="function"==typeof e?e(b.current):e;y(t)}),[y]),x=(0,u.iXE)({data:i,getRowId:e=>e.id,columns:n,enableSortingRemoval:!1,withPagination:!1,state:{sorting:p,expanded:f},onSortingChange:m,onExpandedChange:v}),{rows:E}=x.getRowModel(),C=(0,u.D27)();return r().createElement("div",{className:Wt},r().createElement(u.XIK,{className:(0,u.cx)(jt,o),"data-testid":`${t}-list`,table:x,shouldTruncate:!1},r().createElement(u.ndF,{isSticky:!0,className:(0,u.cx)($t,C&&Yt)},x.getHeaderGroups().map((e=>r().createElement(u.Syw,{key:e.id},e.headers.map((e=>r().createElement(u.A3f,{className:(0,u.cx)(Kt,s),"data-testid":`${t}-header-${e.id}`,key:e.id,header:e},(0,u.KvR)(e.column.columnDef.header,e.getContext())))))))),r().createElement(u.BFY,null,E.map((e=>e.isExpandedContent?r().createElement(u.bHD,{key:e.id,row:e}):r().createElement(u.fI1,{key:e.id,row:e,className:zt,"data-testid":`${t}-row-${e.original.name??e.id}`},e.getVisibleCells().map((e=>{const n="actions"===e.column.id;return r().createElement(u.fhW,{key:e.id,id:e.id,cell:e,className:(0,u.cx)(s,{[Bt]:n&&l,[_t]:n&&l}),"data-testid":`${t}-${e.column.id}-field`},(0,u.KvR)(e.column.columnDef.cell,e.getContext()))}))))))))}const Vt={SINGLE:"https://docs.mongodb.org/manual/core/index-single/",COMPOUND:"https://docs.mongodb.org/manual/core/index-compound/",UNIQUE:"https://docs.mongodb.org/manual/core/index-unique/",PARTIAL:"https://docs.mongodb.org/manual/core/index-partial/",SPARSE:"https://docs.mongodb.org/manual/core/index-sparse/",TTL:"https://docs.mongodb.org/manual/core/index-ttl/","2D":"https://docs.mongodb.org/manual/core/2d/","2DSPHERE":"https://docs.mongodb.org/manual/core/2dsphere/",GEOHAYSTACK:"https://docs.mongodb.org/manual/core/geohaystack/",GEOSPATIAL:"https://docs.mongodb.org/manual/applications/geospatial-indexes/#geospatial-indexes",WILDCARD:"https://docs.mongodb.com/manual/core/index-wildcard/",CLUSTERED:"https://www.mongodb.com/docs/manual/core/clustered-collections/",COLUMNSTORE:null,TEXT:"https://docs.mongodb.org/manual/core/index-text/",HASHED:"https://docs.mongodb.org/manual/core/index-hashed/",REGULAR:"https://docs.mongodb.com/manual/indexes/#single-field",COLLATION:"https://docs.mongodb.com/master/reference/bson-type-comparison-order/#collation",COLLATION_REF:"https://docs.mongodb.com/master/reference/collation",HIDDEN:"https://www.mongodb.com/docs/manual/core/index-hidden/",SHARDKEY:"https://www.mongodb.com/docs/manual/core/sharding-shard-key/",UNKNOWN:null};function Ut(e="UNKNOWN"){return Vt[e?.toUpperCase()]??null}const qt=(0,u.AHW)({gap:u.YKD[200]}),Zt=(0,u.AHW)({lineHeight:0,color:u.MFm.white,span:{backgroundImage:"none !important"}},u.Rg),Jt=({text:e,link:t})=>r().createElement(u.Exy,{variant:u.xUU.DarkGray,className:qt,"data-testid":`${e}-badge`},e,r().createElement(u.N_E,{hideExternalIcon:!0,"aria-label":e,className:Zt,href:t},r().createElement(u.Int,{glyph:"InfoWithCircle"}))),Qt=(0,u.AHW)({display:"flex",textTransform:"capitalize",alignItems:"center",gap:u.YKD[50],minWidth:u.YKD[1800]}),Xt=e=>-1!==["text","wildcard","columnstore"].indexOf(e??""),en=({extra:e})=>{const t=["weights","default_language","language_override","wildcardProjection","columnstoreProjection"],n=[];for(const a in e)t.includes(a)&&n.push(r().createElement(u.nBu,{key:a},`${a}: ${JSON.stringify(e[a])}`));return r().createElement(r().Fragment,null,n)},tn=({type:e,extra:t,showBadge:n=!0})=>{const a=Ut(e)??"#",i=(0,u.D27)(),o=e??"unknown";return r().createElement(u.m_M,{enabled:Xt(e),trigger:({children:e,...t})=>r().createElement("div",t,n?r().createElement(Jt,{text:o,link:a}):r().createElement("div",{className:Qt},o,r().createElement(u.N_E,{hideExternalIcon:!0,"aria-label":o,href:a},r().createElement(u.Int,{glyph:"InfoWithCircle",fill:i?u.MFm.gray.light1:u.MFm.gray.dark1}))),e)},t&&r().createElement(en,{extra:t}))},nn=e=>{const t=e<=1e3?0:1;return(0,u.V0R)(e,!0,t)},an=({relativeSize:e,size:t})=>r().createElement(u.m_M,{trigger:r().createElement(u.nBu,null,nn(t))},r().createElement(u.nBu,null,(e=>`${e.toFixed(2)}% compared to largest index`)(e))),rn=({usage:e,since:t})=>r().createElement(u.m_M,{trigger:r().createElement(u.nBu,null,null==e?"Usage data unavailable":r().createElement(r().Fragment,null,e," ",t?`(since ${t.toDateString()})`:""))},r().createElement(u.nBu,null,(e=>null==e?"Either the server does not support the $indexStats command or the user is not authorized to execute it.":`${e} index hits since index creation or last server restart`)(e))),on=(0,u.AHW)({display:"flex",gap:u.YKD[100],minWidth:7*u.YKD[400],alignItems:"baseline"}),sn=(e,t)=>{return"ttl"===e&&void 0!==t.expireAfterSeconds?`expireAfterSeconds: ${t.expireAfterSeconds}`:"partial"===e&&void 0!==t.partialFilterExpression?(n=t.partialFilterExpression,`partialFilterExpression: ${JSON.stringify(n)}`):null;var n},ln="HIDDEN",cn=e=>"shardKey"===e?"SHARD KEY":e,dn=({text:e,link:t,tooltip:n})=>r().createElement(u.m_M,{enabled:!!n,trigger:({children:n,...a})=>r().createElement("div",a,r().createElement(Jt,{link:t,text:e}),n),triggerEvent:"hover"},r().createElement(u.nBu,null,n)),un=({extra:e,properties:t,cardinality:n})=>r().createElement("div",{className:on},e&&t?.map((t=>r().createElement(dn,{key:t,text:cn(t),link:Ut(t)??"#",tooltip:sn(t,e)}))),"compound"===n&&r().createElement(dn,{text:n,link:Ut(n)??"#"}),e?.hidden&&r().createElement(dn,{text:ln,link:Ut(ln)??"#"})),pn=(0,u.AHW)({display:"flex",gap:u.YKD[100],alignItems:"baseline"}),mn=({"data-testid":e,children:t,tooltip:n,darkMode:a,variant:i})=>r().createElement(u.m_M,{enabled:!!n,darkMode:a,trigger:({children:n,...a})=>r().createElement("div",a,r().createElement(u.Exy,{"data-testid":e,variant:i},t),n)},r().createElement(u.nBu,null,n)),gn=({status:e,error:t,tooltip:n})=>{const a=(0,u.D27)();return r().createElement("div",{className:pn},"ready"===e&&r().createElement(u.Exy,{"data-testid":"index-ready",variant:u.xUU.Green},"Ready"),"building"===e&&r().createElement(mn,{"data-testid":"index-building",variant:u.xUU.Blue,tooltip:"This index is being built in a rolling process"},"Building"),"inprogress"===e&&r().createElement(mn,{"data-testid":"index-in-progress",variant:u.xUU.Blue,tooltip:n,darkMode:a},"In Progress"),"creating"===e&&r().createElement(u.Exy,{"data-testid":"index-creating",variant:u.xUU.Blue},"Creating"),"failed"===e&&r().createElement(mn,{"data-testid":"index-failed",tooltip:t||"",darkMode:a,variant:u.xUU.Red},"Failed"),"unknown"===e&&r().createElement(mn,{"data-testid":"index-unknown",tooltip:n||"Build status unavailable (insufficient permissions)",darkMode:a,variant:u.xUU.Yellow},"Unknown"))},hn=(0,u.AHW)({justifyContent:"flex-end"}),fn=(0,u.AHW)({display:"flex",alignItems:"center",justifyContent:"flex-end",gap:u.YKD[200]}),yn=e=>"buildProgress"in e&&"type"in e,bn=e=>"status"in e&&!("type"in e),vn=e=>bn(e)?"creating"===e.status:!!e.building||!!e.buildProgress.currentOp?.active,xn=(e,t)=>{const n=[];return vn(e)?n.push({action:"delete",label:`Cancel Index ${e.name}`,tooltip:"Cancel Index",icon:"XWithCircle",variant:"destructive"}):(((e,t)=>!(!t||!yn(e))&&!vn(e)&&(e=>{try{return k().gte(e,"4.4.0")}catch{return!0}})(t))(e,t)&&yn(e)&&n.push(e.extra?.hidden?{action:"unhide",label:`Unhide Index ${e.name}`,tooltip:"Unhide Index",icon:"Visibility"}:{action:"hide",label:`Hide Index ${e.name}`,tooltip:"Hide Index",icon:"VisibilityOff"}),(e=>!bn(e)||"failed"===e.status)(e)&&n.push({action:"delete",label:`Drop Index ${e.name}`,tooltip:"Drop Index",icon:"Trash"})),n},En=({index:e,serverVersion:t,onDeleteIndexClick:n,onDeleteFailedIndexClick:i,onHideIndexClick:o,onUnhideIndexClick:s})=>{const l=(0,a.useMemo)((()=>xn(e,t)),[e,t]),c=(0,a.useMemo)((()=>!!(n||i||o||s)),[i,n,o,s]),d=(0,a.useCallback)((t=>{"delete"===t?bn(e)&&"failed"===e.status?i?.(e.name):n?.(e.name):"hide"===t?o?.(e.name):"unhide"===t&&s?.(e.name)}),[e,n,i,o,s]),p=(e=>e.buildProgress)(e);if(vn(e)){const e=p.currentOp,t=e?.secsRunning,n=e?.progress;let a;const i=void 0!==t;return a=n?`Building… ${Math.trunc(100*n)}%`:i?`Building For… ${(0,u.a3k)(t)}`:"Building…",r().createElement("div",{className:fn,"data-testid":"index-building-spinner"},r().createElement(u.nBu,null,a),r().createElement(u.Q0K,{size:16,title:"Index build in progress"}),c&&l.length>0?r().createElement(u.ful,{"data-testid":"index-actions",actions:l,onAction:d}):null)}return c&&l.length>0?r().createElement(u.ful,{"data-testid":"index-actions",className:hn,actions:l,onAction:d}):null};function Cn(e){const t=!e.buildProgress.statsError,n=!e.buildProgress.progressError;if(!t&&!n)return"unknown";if(!0===e.building||e.buildProgress.currentOp?.active)return"inprogress";const a=e.buildProgress.currentOp?.progress;return a&&a<1?"inprogress":"ready"}function wn(e){return"in-progress-index"===e.compassIndexType?r().createElement(tn,{type:"unknown"}):"rolling-index"===e.compassIndexType?r().createElement(tn,{type:e.indexType.label}):r().createElement(tn,{type:e.type,extra:e.extra})}function In({indexes:e,inProgressIndexes:t,rollingIndexes:n,serverVersion:i,onHideIndexClick:o,onUnhideIndexClick:s,onDeleteIndexClick:l,onDeleteFailedIndexClick:c,renderNameOverride:d,renderTypeOverride:p,renderExpandedContentOverride:m}){const g=function(e,t,n){const a=new Set(n.map((e=>e.indexName)));return[...e.filter((e=>!a.has(e.name))).map((e=>({...e,compassIndexType:"regular-index"}))),...t.map((e=>({...e,compassIndexType:"in-progress-index"}))),...n.map((e=>({...e,compassIndexType:"rolling-index",fields:e.keys.map((e=>({field:e.name,value:e.value})))})))]}(e,t,n),h=(0,a.useMemo)((()=>g.map((e=>{let t;return t="in-progress-index"===e.compassIndexType?function(e,{renderNameOverride:t,renderTypeOverride:n,onDeleteFailedIndexClick:a}){return{id:e.id,name:e.name,displayName:t?t(e.name):e.name,indexInfo:e,type:n?n(e):wn(e),size:r().createElement(an,{size:0,relativeSize:0}),usageCount:r().createElement(rn,{usage:void 0,since:void 0}),properties:null,status:r().createElement(gn,{status:e.status,error:e.error}),actions:r().createElement(En,{index:e,onDeleteFailedIndexClick:a})}}(e,{renderNameOverride:d,renderTypeOverride:p,onDeleteFailedIndexClick:c}):"rolling-index"===e.compassIndexType?function(e,{renderNameOverride:t,renderTypeOverride:n}){return{id:`rollingIndex-${e.indexName}`,name:e.indexName,displayName:t?t(e.indexName):e.indexName,indexInfo:e,type:n?n(e):wn(e),size:r().createElement(an,{size:0,relativeSize:0}),usageCount:r().createElement(rn,{usage:void 0,since:void 0}),properties:null,status:r().createElement(gn,{status:"building"}),actions:null}}(e,{renderNameOverride:d,renderTypeOverride:p}):function(e,{renderNameOverride:t,renderTypeOverride:n,serverVersion:a,onHideIndexClick:i,onUnhideIndexClick:o,onDeleteIndexClick:s}){const l=Cn(e);return{id:e.name,name:e.name,displayName:t?t(e.name):e.name,indexInfo:e,type:n?n(e):wn(e),size:r().createElement(an,{size:e.size,relativeSize:e.relativeSize}),usageCount:r().createElement(rn,{usage:e.usageCount,since:e.usageSince}),properties:r().createElement(un,{cardinality:e.cardinality,extra:e.extra,properties:e.properties}),status:r().createElement(gn,{status:l,tooltip:e.buildProgress.currentOp?.msg}),actions:"_id_"!==e.name&&r().createElement(En,{index:e,serverVersion:a,onDeleteIndexClick:s,onHideIndexClick:i,onUnhideIndexClick:o})}}(e,{renderNameOverride:d,renderTypeOverride:p,serverVersion:i,onDeleteIndexClick:l,onHideIndexClick:o,onUnhideIndexClick:s}),{...t,renderExpandedContent:m?()=>m(e,t):()=>r().createElement(u.K7,{keys:e.fields,"data-testid":`indexes-details-${t.name}`})}}))),[g,d,p,m,l,c,o,s,i]);return{data:h}}function Sn(e){return"regular-index"!==e.compassIndexType?"":"compound"===e.cardinality?"compound":e.properties?.[0]||""}function An(e,t){return"in-progress-index"===e.compassIndexType?"type"===t?"unknown":"size"===t||"usageCount"===t?0:e[t]:"rolling-index"===e.compassIndexType?"size"===t||"usageCount"===t?0:"name"===t?e.indexName:"type"===t?e.indexType.label:"status"===t?"building":e[t]:"status"===t?Cn(e):e[t]}function kn(e,t,n){if(!function(e){return["name","type","size","usageCount","properties","status"].includes(e)}(n))return 0;if("properties"===n)return function(e,t){const n=Sn(e),a=Sn(t);return n>a?-1:n<a?1:0}(e.original.indexInfo,t.original.indexInfo);const a=An(e.original.indexInfo,n),r=An(t.original.indexInfo,n);return void 0===a||void 0===r?0:a>r?-1:r>a?1:0}const Dn=[{accessorKey:"name",header:"Name & Definition",cell:e=>e.row.original.displayName,enableSorting:!0},{accessorKey:"type",header:"Type",cell:e=>e.getValue(),enableSorting:!0,sortingFn:kn},{accessorKey:"size",header:"Size",cell:e=>e.getValue(),enableSorting:!0,sortingFn:kn},{accessorKey:"usageCount",header:"Usage",cell:e=>e.getValue(),sortingFn:kn,size:300,enableSorting:!0},{accessorKey:"properties",header:"Properties",cell:e=>e.getValue(),sortingFn:kn,enableSorting:!0},{accessorKey:"status",header:"Status",cell:e=>e.getValue(),sortingFn:kn,enableSorting:!0}],Nn=[...Dn,{accessorKey:"actions",header:"",cell:e=>e.getValue()}],Mn=[{accessorKey:"name",header:"Name",cell:e=>e.row.original.displayName,enableSorting:!0},{accessorKey:"type",header:"Type",cell:e=>e.getValue(),enableSorting:!0,sortingFn:kn},{accessorKey:"status",header:"Status",cell:e=>e.getValue(),sortingFn:kn,enableSorting:!0}],Tn=[...Mn,{accessorKey:"actions",header:"",cell:e=>e.getValue()}],Pn={onDeleteIndexClick:Q,onDeleteFailedIndexClick:J,onHideIndexClick:X,onUnhideIndexClick:ee,onRegularIndexesOpened:U,onRegularIndexesClosed:q},Ln=(0,At.Ng)((({serverVersion:e,regularIndexes:t})=>({serverVersion:e,indexes:t.indexes,inProgressIndexes:t.inProgressIndexes,rollingIndexes:t.rollingIndexes??[],error:t.error})),Pn)((({indexes:e,inProgressIndexes:t,rollingIndexes:n,serverVersion:i,onHideIndexClick:o,onUnhideIndexClick:s,onDeleteIndexClick:l,onDeleteFailedIndexClick:c,onRegularIndexesOpened:d,onRegularIndexesClosed:u,error:p})=>{const m=(0,Ft.BE)(),{readOnly:g,readWrite:h,enableAtlasSearchIndexes:f}=(0,kt.gc)(["readOnly","readWrite","enableAtlasSearchIndexes"]),{enableSearchActivationProgramP1:y}=(0,Ee.p5)(),{isRegularIndexesWritable:b}=(0,At.d4)(L({readOnly:g,readWrite:h,enableAtlasSearchIndexes:f,enableSearchActivationProgramP1:y}),At.bN);(0,a.useEffect)((()=>(d(m),()=>{u(m)})),[m,d,u]);const{data:v}=In({indexes:e,inProgressIndexes:t,rollingIndexes:n,serverVersion:i,onHideIndexClick:o,onUnhideIndexClick:s,onDeleteIndexClick:l,onDeleteFailedIndexClick:c});return p?null:r().createElement(Gt,{id:"regular-indexes","data-testid":"indexes",columns:b?Nn:Dn,data:v})})),On=(0,u.AHW)({display:"flex",alignItems:"center",gap:u.YKD[200]}),Rn=(0,u.AHW)({transitionProperty:"background-color, box-shadow, border-color"}),Hn=(0,u.AHW)({visibility:"hidden"}),Fn=({index:e,context:t,onDropIndex:n,onEditIndex:i,onRunAggregateIndex:o})=>{const s=(0,a.useMemo)((()=>[{action:"edit",label:`Edit Index ${e.name}`,tooltip:"Edit Index",icon:"Edit",isDisabled:!i},{action:"drop",label:`Drop Index ${e.name}`,tooltip:"Drop Index",icon:"Trash"}]),[e,i]),l=(0,Ee.Jr)(),c=(0,a.useCallback)((a=>{"drop"===a?(l("Index Drop Action Clicked",{context:t,index_type:e.type??"search"}),n(e.name)):"edit"===a&&(l("Index Edit Action Clicked",{context:t,index_type:e.type??"search"}),i?.(e.name))}),[t,n,i,e,l]);return r().createElement("div",{className:On},o&&r().createElement(u.$nd,{"data-testid":"search-index-actions-aggregate-action",className:(0,u.cx)(Rn,!e.queryable&&Hn),size:"xsmall",onClick:()=>o(e.name)},"Aggregate"),r().createElement(u.ful,{"data-testid":"search-index-actions",actions:s,onAction:c}))},Wn=()=>{const e=(0,u.D27)(),t=(0,a.useMemo)((()=>e?u.MFm.white:u.MFm.black),[e]);return r().createElement("svg",{width:"72",height:"72",viewBox:"0 0 72 72",fill:"none",xmlns:"http://www.w3.org/2000/svg"},r().createElement("path",{d:"M47 53C54.1797 53 60 47.1797 60 40C60 32.8203 54.1797 27 47 27C39.8203 27 34 32.8203 34 40C34 47.1797 39.8203 53 47 53Z",fill:u.MFm.green.base,stroke:t,strokeMiterlimit:"10",strokeLinecap:"round",strokeLinejoin:"round"}),r().createElement("path",{d:"M56 49L68 61",stroke:t}),r().createElement("path",{d:"M4 35.9501H6.2M6.2 35.9501C9.4 35.9501 12.1 33.3553 12.1 30.0619V19.5828C12.1 14.8922 15.9 11 20.7 11M6.2 35.9501C9.4 35.9501 12.1 38.5449 12.1 41.8383V52.4172C12.1 57.1078 15.9 61 20.7 61M54.0001 35.9501H51.8001M51.8001 35.9501C48.6001 35.9501 45.9001 38.5449 45.9001 41.8383V52.4172C45.9001 57.1078 42.1001 61 37.3001 61M51.8001 35.9501C48.6001 35.9501 45.9 33.3553 45.9 30.0619V19.5828C45.9 14.8922 42.1 11 37.3 11",stroke:t,strokeMiterlimit:"10"}))},jn={BUILDING:u.xUU.Blue,FAILED:u.xUU.Red,PENDING:u.xUU.Yellow,READY:u.xUU.Green,STALE:u.xUU.LightGray,DELETING:u.xUU.Red};function Bn({status:e,"data-testid":t}){const n=jn[e];return r().createElement(u.Exy,{variant:n,"data-testid":t},e)}const zn=(0,u.AHW)({textTransform:"none",gap:u.YKD[100]}),_n=(0,u.AHW)({display:"inline-flex",gap:u.YKD[100],marginBottom:u.YKD[200],padding:`0px ${u.YKD[1600]}px`});function $n({definition:e}){return r().createElement(r().Fragment,null,e.fields&&0!==e.fields.length?e.fields.map((e=>r().createElement(u.m_M,{align:"top",key:e.path,justify:"middle",trigger:({children:t,...n})=>r().createElement("div",n,r().createElement(u.Exy,{className:zn},e.path),t)},JSON.stringify(e,null,2)))):r().createElement(u.MWq,null,"No fields in the index definition."))}function Yn({definition:e}){const t=[];return e.mappings?.dynamic&&t.push({name:"Dynamic Mappings",className:void 0}),e.mappings?.fields&&t.push(...Object.keys(e.mappings.fields).map((e=>({name:e,className:zn})))),r().createElement(r().Fragment,null,0===t.length?r().createElement(u.MWq,null,"No mappings in the index definition."):t.map((e=>r().createElement(u.Exy,{key:e.name,className:e.className},e.name))))}function Kn({indexes:e,renderActions:t,renderNameOverride:n,renderTypeOverride:i,renderExpandedContentOverride:o}){return{data:(0,a.useMemo)((()=>e.map((e=>{const a="vectorSearch"===e.type;return{id:e.name,name:e.name,displayName:n?n(e.name):e.name,status:r().createElement(Bn,{status:e.status,"data-testid":`search-indexes-status-${e.name}`}),type:i?i(e):a?r().createElement(Jt,{text:"Vector Search",link:"https://www.mongodb.com/docs/atlas/atlas-vector-search/create-index/"}):r().createElement(Jt,{text:"Search",link:"https://www.mongodb.com/docs/atlas/atlas-search/create-index/"}),indexInfo:e,isVectorSearchIndex:a,actions:t(e,a),renderExpandedContent:o?()=>o(e,a):()=>r().createElement("div",{className:_n,"data-testid":`search-indexes-details-${e.name}`},a?r().createElement($n,{definition:e.latestDefinition}):r().createElement(Yn,{definition:e.latestDefinition}))}}))),[e,n,i,o,t])}}const Gn=[{accessorKey:"type",header:"Type",cell:e=>e.getValue(),sortingFn:function(e,t){return void 0===t.original.indexInfo.type?-1:void 0===e.original.indexInfo.type?1:e.original.indexInfo.type>t.original.indexInfo.type?-1:e.original.indexInfo.type<t.original.indexInfo.type?1:0},enableSorting:!0},{accessorKey:"status",header:"Status",cell:e=>e.getValue(),sortingFn:function(e,t){return void 0===t.original.indexInfo.status?-1:void 0===e.original.indexInfo.status?1:e.original.indexInfo.status>t.original.indexInfo.status?-1:e.original.indexInfo.status<t.original.indexInfo.status?1:0},enableSorting:!0}],Vn=[{accessorKey:"name",header:"Name and Fields",cell:e=>e.row.original.displayName,enableSorting:!0},...Gn],Un=[...Vn,{accessorKey:"actions",header:"",cell:e=>e.getValue()}],qn=[{accessorKey:"name",header:"Name",cell:e=>e.row.original.displayName,enableSorting:!0},...Gn],Zn=[...qn,{accessorKey:"actions",header:"",cell:e=>e.getValue()}];function Jn({onOpenCreateModalClick:e,isReadonlyView:t,isViewPipelineSearchQueryable:n}){const a=(0,Ee.Jr)(),i=t&&!n;return r().createElement(u.HYq,{icon:Wn,title:"No search indexes yet",subTitle:"Atlas Search is an embedded full-text search in MongoDB Atlas that gives you a seamless, scalable experience for building relevance-based app features.",callToAction:r().createElement(u.m_M,{enabled:i,align:"top",justify:"middle",trigger:r().createElement(u.$nd,{onClick:()=>{e(),t&&a("Create Search Index for View Clicked",{context:"Indexes Tab"})},"data-testid":"create-atlas-search-index-button",variant:"primary",size:"small",disabled:i},"Create Atlas Search Index")},"Search indexes can only be created on views containing $match stages with the $expr operator, $addFields, or $set."),callToActionLink:r().createElement("span",null,"Not sure where to start? ",r().createElement(u.N_E,{href:"https://www.mongodb.com/docs/atlas/atlas-search/",target:"_blank"},"Visit our Docs"))})}const Qn={onDropIndexClick:Je,onOpenCreateModalClick:Fe,onEditIndexClick:e=>({type:Te,indexName:e}),onSearchIndexesOpened:_e,onSearchIndexesClosed:$e},Xn=(0,At.Ng)((({searchIndexes:e,namespace:t,isReadonlyView:n})=>({namespace:t,isReadonlyView:n,indexes:e.indexes,status:e.status})),Qn)((({namespace:e,indexes:t,isReadonlyView:n,status:i,onOpenCreateModalClick:o,onEditIndexClick:s,onDropIndexClick:l,onSearchIndexesOpened:c,onSearchIndexesClosed:d})=>{const{openCollectionWorkspace:u}=(0,Ft.$L)(),{id:p}=(0,Dt.qm)(),m=(0,Ft.BE)(),{readOnly:g,readWrite:h,enableAtlasSearchIndexes:f,enableAutoEmbeddingPublicPreview:y}=(0,kt.gc)(["readOnly","readWrite","enableAtlasSearchIndexes","enableAutoEmbeddingPublicPreview"]),{enableSearchActivationProgramP1:b}=(0,Ee.p5)();(0,a.useEffect)((()=>(c(m),()=>{d(m)})),[m,c,d]);const{isSearchIndexesWritable:v}=(0,At.d4)(L({readOnly:g,readWrite:h,enableAtlasSearchIndexes:f,enableSearchActivationProgramP1:b}),At.bN),{isViewPipelineSearchQueryable:E}=(0,At.d4)(P,At.bN),C=(0,a.useCallback)(((t,n)=>r().createElement(Fn,{index:t,context:"Indexes Tab",onDropIndex:l,onEditIndex:s,onRunAggregateIndex:t=>{u(p,e,{newTab:!0,...n?{initialPipelineText:y?et(t):Xe(t)}:{initialPipeline:Qe(t)}})}})),[p,e,l,s,u,y]),{data:w}=Kn({indexes:t,renderActions:C});return x(i)?0===t.length?r().createElement(Jn,{onOpenCreateModalClick:o,isReadonlyView:n,isViewPipelineSearchQueryable:E}):r().createElement(Gt,{id:"search-indexes","data-testid":"search-indexes",columns:v?Un:Vn,data:w}):null}));var ea=n(70724);const ta=(0,u.AHW)({display:"flex",flexDirection:"column",gap:u.YKD[100]}),na=(0,u.AHW)({display:"flex",gap:u.YKD[100],alignItems:"center"}),aa=({isVectorSearchSupported:e,tooltip:t,onTemplate:n})=>{const[i,o]=(0,a.useState)("0"),s=(0,u.BiT)(),l=(0,a.useCallback)((e=>{o(e),n(T.Nw[+e])}),[n]),c=(0,a.useMemo)((()=>e?T.Nw.filter((e=>"KNN Vector field mapping"!==e.name)):T.Nw),[e]);return r().createElement("div",{className:ta},r().createElement("div",{className:na},r().createElement(u.JU7,{id:s,htmlFor:"template-dropdown"},"Template"),r().createElement(u.Ls4,{align:"right"},t)),r().createElement(u.l6P,{id:"template-dropdown","aria-labelledby":s,value:i,allowDeselect:!1,onChange:l},c.map(((e,t)=>r().createElement(u.c$x,{key:t,value:`${t}`},e.name)))))},ra=(0,u.AHW)({display:"flex",flexDirection:"column",gap:u.YKD[100]}),ia=(0,u.AHW)({display:"flex",gap:u.YKD[100],alignItems:"center"}),oa=Object.create({autoEmbed:T.wb,bringYourOwn:T.MU}),sa=({tooltip:e,value:t,onTemplateChoice:n})=>{const i=(0,u.BiT)(),o=(0,a.useCallback)((e=>{n(e,oa[e])}),[n]);return r().createElement("div",{className:ra,"data-testid":"vector-search-index-template"},r().createElement("div",{className:ia},r().createElement(u.JU7,{id:i,htmlFor:"vector-template-dropdown"},"Template"),r().createElement(u.Ls4,{align:"right"},e)),r().createElement(u.l6P,{id:"vector-template-dropdown","aria-labelledby":i,value:t,allowDeselect:!1,onChange:o},r().createElement(u.c$x,{value:"autoEmbed"},"Automated embedding"),r().createElement(u.c$x,{value:"bringYourOwn"},"Bring your own embeddings")))};var la=n(25607),ca=n(19461);function da(e){const t=(0,ca.Ay)(e,{mode:ca.X6.Strict,allowComments:!0,allowMethods:!0});if(!t||"object"!=typeof t)throw new Error("The provided index definition is invalid.");return t}const ua=(0,u.AHW)({display:"flex",flexDirection:"column",gap:u.YKD[400]}),pa=(0,u.AHW)({display:"flex",flexDirection:"row",gap:u.YKD[400]}),ma=(0,u.AHW)({flexGrow:1}),ga=(0,u.AHW)({width:"40%",flexShrink:0}),ha=(0,u.AHW)({display:"flex",flexDirection:"column",gap:u.YKD[200],overflow:"auto",padding:u.YKD[100]}),fa=(0,u.AHW)({display:"flex",flexDirection:"column",gap:u.YKD[100]}),ya=(0,u.AHW)({display:"flex",justifyContent:"flex-end",gap:u.YKD[2]}),ba=[{label:"Search",value:"search"},{label:"Vector Search",value:"vectorSearch"}],va=({namespace:e,mode:t,initialIndexName:n,initialIndexDefinition:i,initialIndexType:o,isModalOpen:s,isBusy:l,isVectorSearchSupported:c,error:d,onSubmit:p,onClose:m})=>{const g="search"===o||"vectorSearch"===o?o:"search",h=(0,a.useRef)(null),f=(0,Dt.jj)(),{enableAutoEmbeddingPublicPreview:y}=(0,kt.gc)(["enableAutoEmbeddingPublicPreview"]),b=y?"autoEmbed":"bringYourOwn",[{indexType:v,indexName:x,indexDefinition:E,parsingError:C,vectorTemplateChoice:w},I]=(0,a.useState)((()=>({indexType:g,indexName:n,indexDefinition:i,parsingError:void 0,vectorTemplateChoice:b}))),S=(0,a.useMemo)((()=>{if(C&&C.pos){const e=Math.max(C.pos-4,0);return[{message:C.message,severity:"error",from:e,to:e}]}return[]}),[C]);(0,Ee.ou)((e=>{if(s){const n=f.current;e("Screen",{name:"create"===t?"create_search_index_modal":"update_search_index_modal"},n),"create"===t&&e("Index Create Opened",{atlas_search:!0},n)}}),[s,t,f],void 0),(0,u.wTI)((()=>{s&&I({indexType:g,indexName:n,indexDefinition:i,parsingError:void 0,vectorTemplateChoice:b})}),[s]);const A=(0,a.useCallback)((e=>{let t;try{da(e)}catch(e){t=e}I((n=>({...n,indexDefinition:e,parsingError:t})))}),[]),k=(0,a.useCallback)((()=>{if(C)return;const e=da(E);p({name:x,definition:e,...c?{type:v}:{}})}),[p,C,x,v,E,c]),D=(0,a.useCallback)((e=>{(0,u.Rbc)((()=>{h.current?.focus(),h.current?.applySnippet(e.snippet)}))}),[h]),N=(0,a.useCallback)(((e,t)=>{I((t=>({...t,vectorTemplateChoice:e,parsingError:void 0}))),D(t)}),[D]),M=(0,a.useCallback)((({target:{value:e}})=>{const t="vectorSearch"===e?y?T.wb:T.MU:T.Nw[0];I((t=>({...t,parsingError:void 0,vectorTemplateChoice:"vectorSearch"===e?b:"bringYourOwn",indexName:"vectorSearch"===e&&"default"===t.indexName?"vector_index":"vector_index"===t.indexName?"default":t.indexName,indexType:e}))),D(t)}),[D,y,b]),P=(0,la.jv)(e),L=(0,a.useMemo)((()=>(0,ea.rq)({fields:P})),[P]),O=(0,a.useMemo)((()=>{if(!y)return!1;try{return ve({latestDefinition:da(i)})}catch{return!1}}),[t,y,i]),R="update"===t&&"vectorSearch"===g;return r().createElement(u.aFV,{open:s,setOpen:m,"data-testid":"search-index-modal"},r().createElement(u.rQ0,{title:"create"===t?"Create Atlas Search Index":`Edit ${"vectorSearch"===g?"Vector Search":"Search"} Index "${x}"`}),r().createElement(u.cwr,{className:ua},r().createElement("div",{className:ha},"create"===t&&r().createElement(r().Fragment,null,r().createElement("section",{className:fa},r().createElement(u.JU7,{htmlFor:"name-of-search-index"},"Name of Search Index"),r().createElement(u.ksK,{id:"name-of-search-index","data-testid":"name-of-search-index","aria-labelledby":"Name of Search Index",type:"text",state:""===x?"error":"none",errorMessage:""===x?"Please enter the name of the index.":"",value:x,onChange:e=>{I((t=>({...t,indexName:e.target.value})))}})),r().createElement(u.d$,null),c&&r().createElement(r().Fragment,null,r().createElement("section",{className:fa},r().createElement(u.JU7,{htmlFor:"search-index-type"},"Atlas Search Index type"),r().createElement(u.E99,{id:"search-index-type","data-testid":"search-index-type",onChange:M,value:v},ba.map((({label:e,value:t})=>r().createElement(u.VCA,{id:`search-index-type-${t}-button`,"data-testid":`search-index-type-${t}-button`,checked:v===t,value:t,key:t},e))))),r().createElement(u.d$,null))),r().createElement("div",{className:fa},r().createElement("section",{className:pa},r().createElement("div",{className:ma},r().createElement(u.JU7,{htmlFor:"definition-of-search-index"},"Index Definition"),r().createElement("br",null),"create"===t&&r().createElement(u.nBu,null,"By default,"," ","vectorSearch"===v?"vector search":"search"," ","indexes will have the following search configurations. You can refine this later."),r().createElement(u.N_E,{href:"vectorSearch"===v?"https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-tutorial/":"https://www.mongodb.com/docs/atlas/atlas-search/tutorial/",target:"_blank",hideExternalIcon:!0},"View Atlas"," ","vectorSearch"===v?"Vector Search":"Search"," ","tutorials ",r().createElement(u.Int,{size:"small",glyph:"OpenNewTab"}))),"search"===v&&!R&&r().createElement("div",{className:ga},r().createElement(aa,{isVectorSearchSupported:c,tooltip:"Selecting a new template will replace your existing index definition in the code editor.",onTemplate:D})),"vectorSearch"===v&&!R&&y&&r().createElement("div",{className:ga},r().createElement(sa,{value:w,tooltip:"Selecting a new template will replace your existing index definition in the code editor.",onTemplateChoice:N}))),r().createElement(ea.Jn,{key:v,ref:h,id:"definition-of-search-index","data-testid":"definition-of-search-index",text:E,annotations:S,onChangeText:A,minLines:16,completer:L}),"vectorSearch"===v&&y&&"autoEmbed"===w&&"create"===t&&r().createElement(u.lZ$,{"data-testid":"auto-embedding-cost-banner"},"Automated Embedding uses embedding models, which incur usage-based costs. The generated vector embeddings are stored in your MongoDB cluster. The model inference platform runs on MongoDB's infrastructure in GCP cloud in a US region."))),C&&r().createElement(u.rpn,{warnings:C.message}),!C&&d&&r().createElement(u.dFH,{errors:d}),"update"===t&&r().createElement(u.lZ$,null,"Note: Updating the index may slow down your device temporarily due to resource usage. Save indexes only with changes to avoid reindexing."),O&&r().createElement(u.lZ$,{"data-testid":"auto-embed-edit-restricted-banner"},"You cannot edit an autoEmbed field (updating path, model, quantization, etc.) in an existing index during Public Preview. This includes adding, removing, or modifying fields. To use a different autoEmbed configuration, create a new index.")),r().createElement(u.jlY,{className:ya},r().createElement(u.$nd,{variant:"default",onClick:m},"Cancel"),r().createElement(u.$nd,{"data-testid":"search-index-submit-button",variant:"primary",onClick:k,disabled:l||!!C,isLoading:l,loadingIndicator:r().createElement(u.Q0K,null)},"create"===t?"Create Search Index":"Save")))};function xa(e){if(!e)return!0;try{return k().gte(e,"7.0.2")||k().gte(e,"6.0.11")&&k().lt(e,"7.0.0")}catch{return!0}}const Ea={onCloseModalClick:We,onCreateIndexClick:Ye},Ca=(0,At.Ng)((({serverVersion:e,namespace:t,searchIndexes:{createIndex:{isBusy:n,isModalOpen:a,error:r}}})=>({isVectorSearchSupported:xa(e),namespace:t,isModalOpen:a,isBusy:n,error:r})),Ea)((({namespace:e,isModalOpen:t,isBusy:n,isVectorSearchSupported:a,error:i,onCreateIndexClick:o,onCloseModalClick:s})=>r().createElement(va,{namespace:e,mode:"create",isVectorSearchSupported:a,initialIndexName:"default",initialIndexDefinition:"{\n mappings: {\n dynamic: true,\n },\n}",isModalOpen:t,isBusy:n,error:i,onSubmit:o,onClose:s}))),wa={onCloseModalClick:je,onUpdateIndexClick:Ke},Ia=(0,At.Ng)((({serverVersion:e,namespace:t,searchIndexes:{indexes:n,updateIndex:{indexName:a,isBusy:r,isModalOpen:i,error:o}}})=>{const s=n.find((e=>e.name===a));return{isVectorSearchSupported:xa(e),namespace:t,isModalOpen:i,isBusy:r,indexName:a,indexDefinition:JSON.stringify(s?.latestDefinition,null,2),indexType:s?.type,error:o}}),wa)((({namespace:e,indexName:t,indexDefinition:n,indexType:a,isModalOpen:i,isBusy:o,isVectorSearchSupported:s,error:l,onUpdateIndexClick:c,onCloseModalClick:d})=>r().createElement(va,{namespace:e,isVectorSearchSupported:s,mode:"update",initialIndexName:t,initialIndexType:a,initialIndexDefinition:n,isModalOpen:i,isBusy:o,error:l,onSubmit:c,onClose:d})));var Sa=n(55712);const Aa=["1 (asc)","-1 (desc)","2dsphere","text (full text search)","columnstore"],ka={name:"Select or type a field name",type:"Select a type"},Da=(0,u.AHW)({display:"flex",gap:u.YKD[200]}),Na=(0,u.AHW)({flexGrow:1,textTransform:"none",whiteSpace:"nowrap"}),Ma=(0,u.AHW)({textTransform:"none",whiteSpace:"nowrap"});function Ta({fields:e,serverVersion:t,schemaFields:n,onAddFieldClick:i,onRemoveFieldClick:o,onSelectFieldNameClick:s,onSelectFieldTypeClick:l}){const c=(0,Ee.Jr)(),[d,p]=(0,a.useMemo)((()=>{const e=N(t);return[Aa.filter((t=>e||"columnstore"!==t)),`calc(${Math.max(...Aa.map((e=>e.length)))}ch + ${u.YKD[1600]+(e?u.YKD[1600]:0)}px)`]}),[t]),m=(0,a.useCallback)(((e,t)=>{null!==t&&s(e,t)}),[s]),g=(0,a.useCallback)((()=>{i(),c("New Index Field Added",{context:"Create Index Modal"})}),[i,c]),h=n.map((e=>({value:e})));return r().createElement(u.qQS,{items:e,renderItem:(e,t)=>r().createElement("div",{className:Da,"data-testid":`create-index-fields-line-${t}`},r().createElement("div",{className:Na,"data-testid":`create-index-fields-name-${t}`},r().createElement(u.WqN,{"aria-label":"Index fields",placeholder:ka.name,size:"default",clearable:!1,overflow:"scroll-x",inputValue:e.name,onChange:e=>m(t,e),options:h,renderOption:(e,t,n)=>r().createElement(u.jOs,{key:`field-option-${t}`,value:e.value,displayName:n?`Field: "${e.value}"`:e.value})})),r().createElement("div",{className:Ma,"data-testid":`create-index-fields-type-${t}`},r().createElement(u.l6P,{id:`create-index-fields-type-select-${t}`,placeholder:ka.type,onChange:e=>l(t,e),allowDeselect:!1,value:e.type,popoverZIndex:999999,"aria-labelledby":"Field type",style:{width:p}},d.map((e=>r().createElement(u.c$x,{key:e,value:e},e,"columnstore"===e&&r().createElement(r().Fragment,null," ",r().createElement(u.Exy,null,"Preview")))))))),onAddItem:g,onRemoveItem:o,addButtonTestId:"add-index-field-button",removeButtonTestId:"remove-index-field-button"})}const Pa=(0,At.Ng)(((e,{name:t})=>({label:pe[t].label,description:pe[t].description,checked:e.createIndex.options[t].value})),{onChange:me})((({name:e,label:t,description:n,disabled:a,checked:i,onChange:o})=>{const s=`create-index-modal-${e}`;return r().createElement(u.GEW,null,r().createElement(u.Sc0,{id:s,"data-testid":`${s}-checkbox`,checked:i,onChange:t=>{o(e,t.target.checked)},label:r().createElement(u.JU7,{htmlFor:s,"data-testid":`${s}-label`},t),description:n,disabled:a}))})),La=(0,At.Ng)(((e,{name:t})=>({type:pe[t].type,label:pe[t].label,description:pe[t].description,optional:pe[t].optional,units:pe[t].units,value:e.createIndex.options[t].value,enabled:e.createIndex.options[t].enabled})),{onChange:me,onToggled:function(e,t){return{type:oe,name:e,enabled:t}}})((({name:e,type:t,label:n,description:a,disabled:i,optional:o,units:s,value:l,onChange:c,enabled:d,onToggled:p})=>{const m=`create-index-modal-${e}`,g=`${m}-${t}`;return r().createElement(u.V7r,{id:m,toggled:!i&&d,onToggle:t=>{p(e,t)},label:n,"data-testid":m,description:a,disabled:i},"code"===t?r().createElement(ea.Jn,{"data-testid":g,text:l,onChangeText:t=>{c(e,t)},id:g,"aria-labelledby":m,readOnly:i}):r().createElement(u.ksK,{id:g,value:l,"data-testid":g,type:t,onChange:t=>{c(e,t.target.value)},spellCheck:!1,disabled:i,optional:o,label:s,"aria-labelledby":s?void 0:m}))})),Oa=(0,u.AHW)({margin:`${u.YKD[600]}px 0 ${u.YKD[800]}px 0`}),Ra=(0,u.AHW)({marginBottom:u.YKD[100]}),Ha=(0,u.AHW)({paddingLeft:u.YKD[100]+2});function Fa({namespace:e,fields:t,serverVersion:n,onSelectFieldNameClick:i,onSelectFieldTypeClick:o,onAddFieldClick:s,onRemoveFieldClick:l}){const{id:c}=(0,Dt.qm)(),d=!!(0,kt.Fg)("enableRollingIndexes"),p=(0,Dt.SA)(c,"rollingIndexCreation"),m=d&&p,g=(0,Ee.Jr)(),h=(0,la.jv)(e),f=(0,a.useMemo)((()=>h.map((e=>e.name))),[h]);return r().createElement(r().Fragment,null,r().createElement("div",{className:Oa,"data-testid":"create-index-form"},r().createElement(u.nBu,{weight:"medium",className:Ra},"Index fields"),t.length>0?r().createElement(Ta,{schemaFields:f,fields:t,serverVersion:n,isRemovable:!(t.length>1),onSelectFieldNameClick:i,onSelectFieldTypeClick:o,onAddFieldClick:s,onRemoveFieldClick:l}):null),r().createElement(u.nD3,{"data-testid":"create-index-modal-toggle-options",text:"Options",setOpen:()=>{g("Options Clicked",{context:"Create Index Modal"})}},r().createElement("div",{"data-testid":"create-index-modal-options",className:Ha},r().createElement(Pa,{name:"unique"}),r().createElement(La,{name:"name"}),r().createElement(La,{name:"expireAfterSeconds"}),r().createElement(La,{name:"partialFilterExpression"}),r().createElement(La,{name:"wildcardProjection"}),r().createElement(La,{name:"collation"}),N(n)&&r().createElement(La,{name:"columnstoreProjection"}),r().createElement(Pa,{name:"sparse"}),m&&r().createElement(Pa,{name:"buildInRollingProcess"}))))}const Wa=(0,u.AHW)({display:"flex",flexDirection:"row",width:"100%",justifyContent:"flex-end",alignItems:"center",gap:u.YKD[200]}),ja=(0,u.AHW)({flexGrow:1,width:"100%"}),Ba=(0,u.AHW)({flex:"none"}),za=(0,At.Ng)((({createIndex:e})=>{const{fields:t}=e;return{fields:t}}))((function({error:e,onErrorBannerCloseClick:t,onCreateIndexClick:n,onCancelCreateIndexClick:a,fields:i}){const o=(0,Ee.Jr)(),s=!(e=>e.every((e=>e.name&&e.type)))(i);return r().createElement("div",{className:Wa},e&&r().createElement("div",{"data-testid":"create-index-actions-error-banner-wrapper",className:ja},r().createElement(u.lZ$,{variant:"danger",dismissible:!0,onClose:t},e)),r().createElement(u.$nd,{"data-testid":"create-index-actions-cancel-button",onClick:()=>{a(),o("Cancel Button Clicked",{context:"Create Index Modal"})}},"Cancel"),r().createElement(u.$nd,{"data-testid":"create-index-actions-create-index-button",onClick:n,variant:"primary",className:Ba,disabled:s},"Create Index"))})),_a=za,$a={onErrorBannerCloseClick:()=>({type:le}),onCreateIndexClick:()=>(e,t,{track:n})=>{n("Create Index Button Clicked",{context:"Create Index Modal"});const a=t().createIndex.options;let r=Object.create(null);try{r=Object.fromEntries(t().createIndex.fields.map((e=>[e.name,be(e.type)])))}catch(t){return void e(ye(t.message))}const i={},o=(0,d.Kz)(a.collation.value??"")||void 0;if(!a.collation.enabled||o)if(a.collation.enabled&&(i.collation=o),a.unique.enabled&&(i.unique=a.unique.value),a.sparse.enabled&&(i.sparse=a.sparse.value),a.name.enabled&&a.name.value&&(i.name=a.name.value),a.expireAfterSeconds.enabled&&(i.expireAfterSeconds=Number(a.expireAfterSeconds.value),isNaN(i.expireAfterSeconds)))e(ye(`Bad TTL: "${String(a.expireAfterSeconds.value)}"`));else{if(a.wildcardProjection.enabled)try{i.wildcardProjection=c.EJSON.parse(a.wildcardProjection.value??"")}catch(t){return void e(ye(`Bad WildcardProjection: ${String(t)}`))}if(a.columnstoreProjection.enabled)try{i.columnstoreProjection=c.EJSON.parse(a.columnstoreProjection.value??"")}catch(t){return void e(ye(`Bad ColumnstoreProjection: ${String(t)}`))}if(a.partialFilterExpression.enabled)try{i.partialFilterExpression=c.EJSON.parse(a.partialFilterExpression.value??"")}catch(t){return void e(ye(`Bad PartialFilterExpression: ${String(t)}`))}for(const e of Object.keys(a))(""===(s=a[e].value)||!1===s)&&delete i[e];var s;e({type:ue}),e(function(e,t,n,a){return async(r,i,{track:o,dataService:s,rollingIndexesService:l,connectionInfoRef:c})=>{const d=i().namespace,u=((e,{name:t,spec:n})=>({id:e,status:"creating",fields:Object.entries(n).map((([e,t])=>({field:e,value:t}))),name:t||Object.keys(n).reduce(((e,t)=>`${""===e?"":`${e}_`}${t}_${n[t]}`),""),buildProgress:{currentOp:{active:!0}}}))(e,{name:n.name,spec:t});r((e=>({type:W,inProgressIndex:e}))(u));const p=Object.entries(t).map((([e,t])=>({name:e,type:String(t)}))),m={unique:n.unique,ttl:void 0!==n.expireAfterSeconds,columnstore_index:(g=p,g.some((e=>"columnstore"===e.type))),has_columnstore_projection:void 0!==n.columnstoreProjection,has_wildcard_projection:void 0!==n.wildcardProjection,custom_collation:void 0!==n.collation,geo:p.some((({type:e})=>"2dsphere"===e)),atlas_search:!1};var g;try{const i=a?l.createRollingIndex.bind(l):s.createIndex.bind(s);await i(d,t,n),r((e=>({type:"compass-indexes/create-index/index-creation-succeeded",inProgressIndexId:e}))(e)),o("Index Created",m,c.current),a&&setTimeout((()=>{r({type:B,indexId:e})}),15e3).unref?.(),await r(V())}catch(t){r(((e,t)=>({type:j,inProgressIndexId:e,error:t}))(e,t.message)),o("Index Create Failed",m,c.current)}}}(t().createIndex.indexId,r,i,!!a.buildInRollingProcess.value))}else e(ye("You must provide a valid collation object"))},onCancelCreateIndexClick:()=>({type:de}),onAddFieldClick:()=>({type:te}),onRemoveFieldClick:e=>({type:ae,idx:e}),onSelectFieldNameClick:(e,t)=>(n,a)=>{const r=a(),i=[...r.createIndex.fields];if(e>=0&&e<r.createIndex.fields.length){if(r.createIndex.fields.some(((n,a)=>n.name===t&&a!==e)))return void n(ye("Index keys must be unique"));const a={...i[e]};a.name=t,i[e]=a,n((e=>({type:re,fields:e}))(i))}},onSelectFieldTypeClick:(e,t)=>({type:ne,idx:e,fType:t})},Ya=(0,At.Ng)((({namespace:e,serverVersion:t,createIndex:n})=>{const{fields:a,error:r,isVisible:i}=n;return{fields:a,error:r,isVisible:i,namespace:e,serverVersion:t}}),$a)((function({isVisible:e,namespace:t,error:n,onErrorBannerCloseClick:i,onCreateIndexClick:o,onCancelCreateIndexClick:s,...l}){const c=(0,Dt.jj)(),d=(0,Ee.Jr)(),p=(0,a.useCallback)((e=>{e||(s(),d("Create Index Modal Closed",{context:"Create Index Modal"}))}),[s,d]);return(0,Ee.ou)((t=>{const n=c.current;e&&(t("Screen",{name:"create_index_modal"},n),t("Index Create Opened",{atlas_search:!1},n))}),[e,c],void 0),r().createElement(u.aFV,{open:e,setOpen:p,"data-testid":"create-index-modal"},r().createElement(u.rQ0,{title:"Create Index",subtitle:t}),r().createElement(u.cwr,null,r().createElement(Fa,(0,Sa.A)({namespace:t},l))),r().createElement(u.jlY,null,r().createElement(_a,{error:n,onErrorBannerCloseClick:i,onCreateIndexClick:o,onCancelCreateIndexClick:s})))})),Ka=(0,u.AHW)({display:"flex",justifyContent:"space-between",alignItems:"center",width:"100%"}),Ga=(0,At.Ng)((({serverVersion:e})=>({serverVersion:e})))((({serverVersion:e})=>{const{atlasMetadata:t}=(0,Dt.qm)(),n=!!t,a=n?"Upgrade your cluster or manage search indexes on views in the Atlas UI.":"Upgrade your cluster to create search indexes on views.";return r().createElement(u.lZ$,{variant:u.uAY.Warning,"data-testid":"view-version-incompatible-banner"},r().createElement("b",null,"Looking for search indexes?"),r().createElement("br",null),r().createElement("div",{className:Ka},r().createElement("span",null,"Your MongoDB version is ",e,". Creating and managing search indexes on views ",!n&&"in Compass"," is supported on MongoDB version 8.1 or higher. ",a),n&&r().createElement(u.$nd,{size:"xsmall",href:(0,xe.q9)(t),target:"_blank"},"Upgrade Cluster")))})),Va=(0,At.Ng)((({searchIndexes:e})=>({hasNoSearchIndexes:0===e.indexes.length})))((({hasNoSearchIndexes:e})=>r().createElement(u.lZ$,{variant:e?"warning":"danger","data-testid":"view-not-search-compatible-banner"},!e&&r().createElement(r().Fragment,null,r().createElement("b",null,"Looking for search indexes?")," ",r().createElement("br",null)),"This view is incompatible with search indexes. Only views containing $match stages with the $expr operator, $addFields, or $set are compatible with search indexes."," ",!e&&"Edit the view to rebuild search indexes."," ",r().createElement(u.N_E,{href:"https://www.mongodb.com/docs/atlas/atlas-search/view-support/",hideExternalIcon:!0},"Learn more.")))),Ua=({containerClassName:e})=>r().createElement(u.HYq,{containerClassName:e,icon:Wn,title:"No standard indexes",subTitle:"Standard views use the indexes of the underlying collection. As a result, you cannot create, drop or re-build indexes on a standard view directly, nor get a list of indexes on the view.",callToActionLink:r().createElement(u.N_E,{href:"https://www.mongodb.com/docs/manual/core/views/",target:"_blank"},"Learn more about views")}),qa=(0,u.AHW)({gap:u.YKD[400],display:"flex",flexDirection:"column",width:"100%",height:"100%",flexGrow:1}),Za=({namespace:e,dismissed:t,onDismissClick:n})=>{const{enableSearchActivationProgramP1:a}=(0,Ee.p5)(),{atlasMetadata:i}=(0,Dt.qm)(),o=(0,Ee.Jr)();return!i||t?null:r().createElement(u.lZ$,{variant:"info",dismissible:!0,onClose:n},!a&&r().createElement(u.nBu,{weight:"medium"},"Looking for search indexes?"),a?"View index sizes, queryability status, and per-node build progress in ":"These indexes can be created and viewed under ",r().createElement(u.N_E,{target:"_blank",rel:"noopener",href:(0,xe.Yc)({atlasMetadata:i,namespace:e}),onClick:()=>{o("Atlas Search Indexes for View Link Clicked",{context:"Indexes Tab"})},hideExternalIcon:!0},"Search and Vector Search"),".")};const Ja=(0,u.AHW)({padding:u.YKD[400],paddingBottom:0,display:"grid",gridTemplateColumns:"100%",gap:u.YKD[200]}),Qa={refreshRegularIndexes:V,refreshSearchIndexes:Ue},Xa=(0,At.Ng)((({namespace:e,isReadonlyView:t,regularIndexes:n,searchIndexes:a,indexView:r})=>({namespace:e,isReadonlyView:t,regularIndexes:n,searchIndexes:a,currentIndexesView:r})),Qa)((function({namespace:e,isReadonlyView:t,regularIndexes:n,searchIndexes:a,currentIndexesView:i,refreshRegularIndexes:o,refreshSearchIndexes:s}){const[l,c]=(0,u.yRS)("mongodb_compass_dismissedSearchIndexesBanner",!1),d="regular-indexes"===i?n.error:a.error,p="regular-indexes"===i&&n.indexes.length>10,m=(S="regular-indexes"===i?n.status:a.status)===h||S===f,g="regular-indexes"===i?o:s,{readOnly:y,readWrite:b,enableAtlasSearchIndexes:v}=(0,kt.gc)(["readOnly","readWrite","enableAtlasSearchIndexes"]),{enableSearchActivationProgramP1:x}=(0,Ee.p5)(),{isViewVersionSearchCompatible:E,isViewPipelineSearchQueryable:C}=(0,At.d4)(P,At.bN),{isRegularIndexesReadable:w,isSearchIndexesReadable:I}=(0,At.d4)(L({readOnly:y,readWrite:b,enableAtlasSearchIndexes:v,enableSearchActivationProgramP1:x}),At.bN);var S;return r().createElement("div",{className:qa},r().createElement(u.XvC,{toolbar:r().createElement(Ht,{errorMessage:d||null,hasTooManyIndexes:p,isRefreshing:m,onRefreshIndexes:g,showAtlasSearchLink:!t&&!(v||x)&&l})},r().createElement("div",{className:Ja},(()=>{if(t){if(!E)return r().createElement(Ga,null);if(!C)return r().createElement(Va,null)}return t&&(v||x)?null:r().createElement(Za,{namespace:e,dismissed:l,onDismissClick:()=>{c(!0)}})})(),w&&"regular-indexes"===i&&r().createElement(Ln,null),I&&"search-indexes"===i&&r().createElement(Xn,null),t&&!I&&r().createElement(Ua,null))),r().createElement(Ca,null),r().createElement(Ia,null),r().createElement(Ya,null))}));var er=n(44457),tr=n(44142);const nr=(0,u.AHW)({display:"flex",gap:u.YKD[200]}),ar=(0,u.AHW)({listStyleType:"none",padding:0,margin:0,textAlign:"left"}),rr=(e,t="number")=>{if("number"!=typeof(n=e)||isNaN(n))return"N/A";var n;const a=e<=1e3?0:1;return"bytes"===t?(0,u.V0R)(e,!0,a):(0,u.$Mb)(e)},ir=({text:e,details:t})=>r().createElement("div",{"data-testid":"collection-stats"},r().createElement(u.m_M,{"data-testid":"collection-stats-tooltip",align:"bottom",justify:"middle",trigger:r().createElement("span",{onClick:()=>{}},r().createElement(u.Exy,null,e))},r().createElement("ol",{className:ar},t.map(((e,t)=>r().createElement("li",{"data-testid":`tooltip-detail-${t}`,key:`tooltip-detail-${t}`},e)))))),or=(0,At.Ng)((({collectionStats:e})=>({collectionStats:e})))((({collectionStats:e})=>{const{indexCount:t,totalIndexSize:n,avgIndexSize:i}=(0,a.useMemo)((()=>{const{index_count:t=NaN,index_size:n=NaN}=e??{};return{indexCount:rr(t,"number"),totalIndexSize:rr(n,"bytes"),avgIndexSize:rr((a=n,r=t,r<=0?0:a/r),"bytes")};var a,r}),[e]),o=(0,kt.Fg)("enableDbAndCollStats"),s=[`Indexes: ${t}`,`Total Size: ${n}`,`Avg. Size: ${i}`];return r().createElement("div",{"data-testid":"indexes-tab-title",className:nr},"Indexes",o&&r().createElement(ir,{text:t,details:s}))})),sr=(0,u.AHW)({display:"flex",flexDirection:"column",gap:u.YKD[100],padding:u.YKD[200]});function lr(e){return e.length>8?r().createElement(u.p8Z,{definition:e},`${e.slice(0,8)}…`):e}function cr(e){return"in-progress-index"===e.compassIndexType?r().createElement(tn,{type:"unknown",showBadge:!1}):"rolling-index"===e.compassIndexType?r().createElement(tn,{type:e.indexType.label,showBadge:!1}):r().createElement(tn,{type:e.type,extra:e.extra,showBadge:!1})}function dr(e,t){return r().createElement(u.nBu,{className:sr},r().createElement("div",null,r().createElement("b",null,"Index Name: "),t.name),r().createElement(u.K7,{keys:e.fields,"data-testid":`indexes-details-${t.name}`}))}const ur=(0,u.AHW)({marginTop:0}),pr=(0,u.AHW)({overflowX:"auto"}),mr=(0,u.AHW)({":first-of-type":{paddingLeft:0},":last-of-type":{paddingRight:0}}),gr=({isRegularIndexesWritable:e,onCreateRegularIndexClick:t})=>r().createElement(u.HYq,{containerClassName:ur,icon:Wn,title:"No standard indexes found",callToActionLink:r().createElement(u.$nd,{disabled:!e,onClick:t,size:"xsmall"},"Create index")}),hr={onDeleteIndexClick:Q,onDeleteFailedIndexClick:J,onHideIndexClick:X,onUnhideIndexClick:ee,onCreateRegularIndexClick:fe},fr=(0,At.Ng)((({serverVersion:e,regularIndexes:t})=>({serverVersion:e,indexes:t.indexes,inProgressIndexes:t.inProgressIndexes,rollingIndexes:t.rollingIndexes??[],error:t.error})),hr)((({indexes:e,inProgressIndexes:t,rollingIndexes:n,serverVersion:i,onHideIndexClick:o,onUnhideIndexClick:s,onDeleteIndexClick:l,onDeleteFailedIndexClick:c,onCreateRegularIndexClick:d,error:u,searchTerm:p})=>{const{readOnly:m,readWrite:g,enableAtlasSearchIndexes:h}=(0,kt.gc)(["readOnly","readWrite","enableAtlasSearchIndexes"]),{enableSearchActivationProgramP1:f}=(0,Ee.p5)(),{isRegularIndexesWritable:y}=(0,At.d4)(L({readOnly:m,readWrite:g,enableAtlasSearchIndexes:h,enableSearchActivationProgramP1:f}),At.bN),{data:b}=In({indexes:e,inProgressIndexes:t,rollingIndexes:n,serverVersion:i,onHideIndexClick:o,onUnhideIndexClick:s,onDeleteIndexClick:l,onDeleteFailedIndexClick:c,renderNameOverride:lr,renderTypeOverride:cr,renderExpandedContentOverride:dr}),v=(0,a.useMemo)((()=>p?b.filter((e=>e.name.includes(p))):b),[b,p]);return u?null:0===v.length?r().createElement(gr,{isRegularIndexesWritable:y,onCreateRegularIndexClick:d}):r().createElement(Gt,{id:"regular-indexes","data-testid":"indexes",columns:y?Tn:Mn,data:v,tableWrapperClassName:pr,cellClassName:mr,showActionsOnHover:!1})})),yr=()=>{const e=(0,u.D27)(),t=(0,a.useMemo)((()=>e?u.MFm.white:u.MFm.black),[e]);return r().createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"72",height:"72",viewBox:"0 0 40 40",fill:"none"},r().createElement("path",{d:"M15.556 2.22217C8.19967 2.22217 2.22266 8.19918 2.22266 15.5555C2.22266 22.9118 8.19967 28.8888 15.556 28.8888C22.9123 28.8888 28.8893 22.9118 28.8893 15.5555C28.8893 8.19918 22.9123 2.22217 15.556 2.22217Z",fill:u.MFm.green.base,stroke:t,strokeMiterlimit:"10",strokeLinecap:"round",strokeLinejoin:"round"}),r().createElement("circle",{cx:"2.71655",cy:"2.71655",r:"2.71655",transform:"matrix(0.707107 0.707107 0.707107 -0.707107 14.5 12.842)",stroke:t}),r().createElement("line",{y1:"-0.5",x2:"7.90024",y2:"-0.5",transform:"matrix(-0.707107 0.707107 0.707107 0.707107 16.6445 14.9023)",stroke:t}),r().createElement("line",{y1:"-0.5",x2:"2.71655",y2:"-0.5",transform:"matrix(0.707107 0.707107 0.707107 -0.707107 11.1719 19.8032)",stroke:t}),r().createElement("line",{y1:"-0.5",x2:"2.71655",y2:"-0.5",transform:"matrix(0.707107 0.707107 0.707107 -0.707107 12.8906 18.1567)",stroke:t}),r().createElement("path",{d:"M25 25L37.7778 37.7778",stroke:t,strokeMiterlimit:"10"}))},br=(0,u.AHW)({display:"flex",flexDirection:"column",gap:u.YKD[100],padding:u.YKD[200]});function vr(e){return e.length>10?r().createElement(u.p8Z,{definition:e},`${e.slice(0,10)}…`):e}function xr(e){return"vectorSearch"===e.type?"Vector":"Search"}function Er(e,t){return r().createElement(u.nBu,{className:br},r().createElement("div",null,r().createElement("b",null,"Index Name: "),e.name),r().createElement("div",null,r().createElement("b",null,"Status: "),e.status),r().createElement("div",null,r().createElement("b",null,"Index Fields: "),function(e,t){if(t)return e.fields.map((e=>`"${e.path}"`)).join(", ");const n=[];return e.mappings?.dynamic&&n.push("[dynamic]"),n.concat(Object.keys(e.mappings?.fields||{}).map((e=>`"${e}"`))).join(", ")}(e.latestDefinition,t)),r().createElement("div",null,r().createElement("b",null,"Queryable: "),e.queryable.toString()))}const Cr=(0,u.AHW)({marginTop:0}),wr=(0,u.AHW)({overflowX:"auto"}),Ir=(0,u.AHW)({":first-of-type":{paddingLeft:0},":last-of-type":{paddingRight:0}}),Sr=({isSearchIndexesWritable:e,onActionDispatch:t})=>r().createElement(u.HYq,{containerClassName:Cr,icon:yr,title:"No search indexes found",subTitle:r().createElement("span",null,"Define a"," ",r().createElement(u.N_E,{href:"https://www.mongodb.com/docs/atlas/atlas-search/manage-indexes/",target:"_blank"},"search")," ","or"," ",r().createElement(u.N_E,{href:"https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-type/",target:"_blank"},"vector search index")," ","to start using $search or $vectorSearch."),callToActionLink:r().createElement(u.F1Z,{buttonText:"Create a search index",buttonProps:{size:"xsmall",disabled:!e},actions:[{action:"createSearchIndex",label:"Search Index"},{action:"createVectorSearchIndex",label:"Vector Search Index"}],onAction:t})}),Ar={onDropIndexClick:Je,onEditIndexClick:vt,onCreateSearchIndexClick:bt,onExpandedChange:e=>({type:mt,expandedRows:e})},kr=(0,At.Ng)((({searchIndexes:e,indexesDrawer:t})=>({status:e.status,indexes:e.indexes,expandedRows:t.expandedRows})),Ar)((({indexes:e,status:t,searchTerm:n,expandedRows:i,onEditIndexClick:o,onDropIndexClick:s,onCreateSearchIndexClick:l,onExpandedChange:c})=>{const d=(0,Ee.Jr)(),{readOnly:u,readWrite:p,enableAtlasSearchIndexes:m}=(0,kt.gc)(["readOnly","readWrite","enableAtlasSearchIndexes"]),{enableSearchActivationProgramP1:g}=(0,Ee.p5)(),{isSearchIndexesWritable:h}=(0,At.d4)(L({readOnly:u,readWrite:p,enableAtlasSearchIndexes:m,enableSearchActivationProgramP1:g}),At.bN),f=(0,a.useCallback)((e=>{switch(e){case"createSearchIndex":return d("Index Create Action Clicked",{context:"Search Indexes Drawer Table",index_type:"search"}),l("search");case"createVectorSearchIndex":return d("Index Create Action Clicked",{context:"Search Indexes Drawer Table",index_type:"vectorSearch"}),l("vectorSearch")}}),[l,d]),y=(0,a.useCallback)((e=>r().createElement(Fn,{index:e,context:"Search Indexes Drawer Table",onDropIndex:s,onEditIndex:o})),[s,o]),{data:b}=Kn({indexes:e,renderNameOverride:vr,renderTypeOverride:xr,renderActions:y,renderExpandedContentOverride:Er}),v=(0,a.useMemo)((()=>n?b.filter((e=>e.name.includes(n))):b),[b,n]),E=(0,a.useCallback)((e=>{!0!==e&&c(e)}),[c]);return x(t)?0===v.length?r().createElement(Sr,{isSearchIndexesWritable:h,onActionDispatch:f}):r().createElement(Gt,{id:"search-indexes","data-testid":"search-indexes",columns:h?Zn:qn,data:v,expanded:i,onExpandedChange:E,tableWrapperClassName:wr,cellClassName:Ir,showActionsOnHover:!1}):null})),Dr=(0,u.AHW)({padding:u.YKD[400],gap:u.YKD[400],display:"flex",flexDirection:"column"}),Nr=(0,u.AHW)({display:"flex",alignItems:"center",justifyContent:"space-between"}),Mr=(0,u.AHW)({marginTop:0}),Tr=(0,u.AHW)({marginRight:u.YKD[200]});function Pr(e){return e===h||e===f}const Lr={onRefreshClick:()=>e=>{e(V()),e(Ue())},onCreateRegularIndexClick:fe,onCreateSearchIndexClick:bt,onRegularIndexesAccordionOpen:e=>({type:gt,isOpen:e}),startPolling:()=>e=>{e(U()),e(_e())},stopPolling:()=>e=>{e(q()),e($e())}},Or=(0,At.Ng)((({isReadonlyView:e,regularIndexes:t,searchIndexes:n,indexesDrawer:a})=>({isReadonlyView:e,regularIndexes:t,searchIndexes:n,isRegularIndexesAccordionOpen:a.isRegularIndexesAccordionOpen})),Lr)((({isReadonlyView:e,regularIndexes:t,searchIndexes:n,isRegularIndexesAccordionOpen:i,onRegularIndexesAccordionOpen:o,onRefreshClick:s,onCreateRegularIndexClick:l,onCreateSearchIndexClick:c,startPolling:d,stopPolling:p})=>{const[m,g]=(0,a.useState)(""),{openDrawer:h}=(0,u.u6F)(),f=(0,Ee.Jr)(),y=(0,Dt.jj)();(0,a.useEffect)((()=>{f("Screen",{name:"indexes_list_drawer"},y.current)}),[f,y]);const{readOnly:b,readWrite:v,enableAtlasSearchIndexes:x}=(0,kt.gc)(["readOnly","readWrite","enableAtlasSearchIndexes"]),{isViewVersionSearchCompatible:E,isViewPipelineSearchQueryable:C}=(0,At.d4)(P,At.bN),{isRegularIndexesReadable:w,isRegularIndexesWritable:I,isSearchIndexesReadable:S,isSearchIndexesWritable:A}=(0,At.d4)(L({readOnly:b,readWrite:v,enableAtlasSearchIndexes:x,enableSearchActivationProgramP1:!0}),At.bN);(0,a.useEffect)((()=>(d(),p)),[d,p]);const k=(0,a.useCallback)((e=>{switch(e){case"createRegularIndex":return f("Index Create Action Clicked",{context:"Indexes List Drawer View",index_type:"regular"}),l();case"createSearchIndex":return f("Index Create Action Clicked",{context:"Indexes List Drawer View",index_type:"search"}),c("search"),void h(Xr);case"createVectorSearchIndex":return f("Index Create Action Clicked",{context:"Indexes List Drawer View",index_type:"vectorSearch"}),c("vectorSearch"),void h(Xr)}}),[l,c,h,f]),D=w&&Pr(t.status)||S&&Pr(n.status),N=D?r().createElement("div",{className:Tr},r().createElement(u.Q0K,{title:"Refreshing Indexes"})):r().createElement(u.Int,{glyph:"Refresh",title:"Refresh Indexes"});return r().createElement("div",{className:Dr},r().createElement("div",{className:Nr},r().createElement(u.$nd,{disabled:D||!w&&!S,onClick:()=>{f("Index Refresh Clicked",{context:"Indexes List Drawer View"}),s()},variant:"default",size:"xsmall",leftGlyph:N},"Refresh"),r().createElement(u.F1Z,{buttonText:"Create new",buttonProps:{size:"xsmall",variant:"primary",disabled:!I&&!A},actions:[{action:"createRegularIndex",label:"Standard Index",isDisabled:!I},{action:"createSearchIndex",label:"Search Index",isDisabled:!A},{action:"createVectorSearchIndex",label:"Vector Search Index",isDisabled:!A}],onAction:k})),r().createElement(u.DOo,{"aria-label":"Indexes search",placeholder:"Find by index name",size:"small",value:m,onChange:e=>g(e.target.value)}),r().createElement(u.nD3,{text:"Standard",open:i,setOpen:o},w?r().createElement(fr,{searchTerm:m}):r().createElement(Ua,{containerClassName:Mr})),r().createElement(u.nD3,{text:"Search",defaultOpen:!0},(()=>{if(e){if(!E)return r().createElement(Ga,null);if(!C)return r().createElement(Va,null)}return null})(),S&&r().createElement(kr,{searchTerm:m})))}));function Rr(e,t,n){const r=(0,a.useRef)(e);(0,a.useEffect)((()=>{!r.current||e||t||n(),r.current=e}),[e,t,n])}function Hr(e,t){return(0,a.useCallback)((n=>{t(!0),e(n)}),[e,t])}const Fr=(0,u.AHW)({display:"flex",flexDirection:"column",height:"100%"}),Wr=(0,u.AHW)({padding:u.YKD[400],display:"flex",flexDirection:"column",gap:u.YKD[400],flexGrow:1,overflowY:"auto"}),jr=(0,u.AHW)({display:"flex",gap:u.YKD[200],justifyContent:"flex-end",padding:u.YKD[400]}),Br=(0,u.AHW)({borderRadius:u.YKD[300],border:`1px solid ${u.MFm.gray.light2}`,background:u.MFm.gray.light3,overflow:"hidden"}),zr=(0,u.AHW)({border:`1px solid ${u.MFm.gray.dark2}`,background:u.MFm.gray.dark3}),_r=(0,u.AHW)({overflowWrap:"anywhere",textWrap:"wrap"});var $r=n(24840),Yr=n(22713);const Kr={onClose:yt,onResetCreateState:We,createIndex:Ye,onIndexDefinitionEdit:xt},Gr=(0,At.Ng)((({namespace:e,searchIndexes:t,indexesDrawer:n})=>({namespace:e,searchIndexes:t.indexes,currentIndexType:n.currentIndexType,isBusy:t.createIndex.isBusy,error:t.createIndex.error})),Kr)((({namespace:e,searchIndexes:t,currentIndexType:n,isBusy:i,error:o,onClose:s,onResetCreateState:l,createIndex:c,onIndexDefinitionEdit:d})=>{const p=(0,Ee.Jr)(),m=(0,Dt.jj)();(0,a.useEffect)((()=>{p("Screen",{name:"create_search_index_drawer"},m.current)}),[p,m]);const g=(0,a.useRef)(null),[h,f]=(0,a.useState)(("vectorSearch"===n?T.MU.snippet:T.Nw[0].snippet).replace(/\${\d+:([^}]+)}/gm,"$1")),[y,b]=(0,a.useState)(((e,t)=>{const n=new Set(e.map((e=>e.name)));if(!n.has(t))return t;let a=1;for(;n.has(`${t}_${a}`);)a++;return`${t}_${a}`})(t,"vectorSearch"===n?"vector_index":"default")),{atlasMetadata:v}=(0,Dt.qm)(),{readOnly:x,readWrite:E,enableAtlasSearchIndexes:C}=(0,kt.gc)(["readOnly","readWrite","enableAtlasSearchIndexes"]),{isSearchIndexesWritable:w}=(0,At.d4)(L({readOnly:x,readWrite:E,enableAtlasSearchIndexes:C,enableSearchActivationProgramP1:!0}),At.bN),I="vectorSearch"===n?Yr:$r,{completer:S,extensions:A,annotations:k,hasErrors:D}=(0,ea.Tf)(I,h),N=!D&&!i;(0,a.useEffect)((()=>()=>l()),[l]),Rr(i,o,s);const M=(0,u.D27)(),P=Hr(f,d),O=(0,a.useCallback)((()=>{p("Search Index Create Submitted",{context:"Create Search Index Drawer View",index_type:n}),c({name:y,definition:da(h),type:n})}),[y,h,c,n,p]),R="vectorSearch"===n?"Vector Search Index":"Search Index";return r().createElement("div",{className:Fr,"data-testid":"create-search-index-drawer-view"},r().createElement("div",{className:Wr},r().createElement(u.Pds,{className:_r,"data-testid":"create-search-index-drawer-view-title"},"Create ",R," for ",e),r().createElement(u.nBu,null,"search"===n?"Full-text search for relevance-based app features.":"For semantic search and AI applications."),r().createElement(u.ksK,{"data-testid":"create-search-index-drawer-view-name-input",value:y,onChange:e=>b(e.target.value),label:"Index Name",description:`Give your ${R.toLowerCase()} a name for easy reference`,state:""===y?"error":"none",errorMessage:""===y?"Please enter the name of the index.":"",disabled:!w}),r().createElement(u.nBu,null,"By default, your ",R.toLowerCase()," will have the following configurations. We recommend starting with this and refining it later if you need to."),r().createElement("div",{className:(0,u.cx)(Br,M&&zr)},r().createElement(ea.Jn,{ref:g,id:"create-search-index-drawer-view-editor","data-testid":"create-search-index-drawer-view-editor",text:h,onChangeText:P,minLines:16,showLineNumbers:!0,language:"json",initialJSONFoldAll:!1,completer:S,customExtensions:A,annotations:k,readOnly:!w})),o&&r().createElement(u.dFH,{errors:o})),r().createElement("div",{className:jr},r().createElement(u.$nd,{"data-testid":"create-search-index-drawer-view-cancel-button",variant:"default",onClick:()=>{p("Search Index Create Cancelled",{context:"Create Search Index Drawer View",index_type:n}),s()}},"Cancel"),r().createElement(u.m_M,{trigger:r().createElement(u.$nd,{"data-testid":"create-search-index-drawer-view-submit-button",variant:"primary",isLoading:i,loadingIndicator:r().createElement(u.Q0K,null),disabled:!N||!w,onClick:O},"Create ",R),enabled:!w},"You currently don't have permission to create ",R,"es in this"," ",v?"project, please contact Project Owner to request the Project Data Access Admin role.":"cluster.")))})),Vr=(0,u.AHW)({overflowX:"auto",flexShrink:0}),Ur=(0,u.AHW)({display:"flex",alignItems:"center",gap:u.YKD[400],width:"max-content"}),qr={onClose:yt,onResetUpdateState:je,updateIndex:Ke,onIndexDefinitionEdit:xt},Zr=(0,At.Ng)((({namespace:e,searchIndexes:t,indexesDrawer:n})=>{const a=t.indexes.find((e=>e.name===n.currentIndexName));if(!a)throw new Error("Search index not found");return{namespace:e,searchIndex:a,isBusy:t.updateIndex.isBusy,error:t.updateIndex.error}}),qr)((({namespace:e,searchIndex:t,isBusy:n,error:i,onClose:o,onResetUpdateState:s,updateIndex:l,onIndexDefinitionEdit:c})=>{const d=(0,Ee.Jr)(),p=(0,Dt.jj)();(0,a.useEffect)((()=>{d("Screen",{name:"edit_search_index_drawer"},p.current)}),[d,p]);const m=(0,a.useRef)(null),[g,h]=(0,a.useState)(JSON.stringify(t.latestDefinition,null,2)),{atlasMetadata:f}=(0,Dt.qm)(),{readOnly:y,readWrite:b,enableAtlasSearchIndexes:v}=(0,kt.gc)(["readOnly","readWrite","enableAtlasSearchIndexes"]),{isSearchIndexesWritable:x}=(0,At.d4)(L({readOnly:y,readWrite:b,enableAtlasSearchIndexes:v,enableSearchActivationProgramP1:!0}),At.bN),E="vectorSearch"===t.type?Yr:$r,{completer:C,extensions:w,annotations:I,hasErrors:S}=(0,ea.Tf)(E,g),A=(0,a.useMemo)((()=>{if(S)return!1;try{const e=da(g),a=t.latestDefinition;return!n&&JSON.stringify(e)!==JSON.stringify(a)}catch{return!1}}),[g,t.latestDefinition,n,S]);(0,a.useEffect)((()=>()=>s()),[s]),Rr(n,i,o);const k=(0,u.D27)(),D=Hr(h,c),N=(0,a.useCallback)((()=>{d("Search Index Edit Submitted",{context:"Edit Search Index Drawer View",index_type:t.type??"search"}),l({name:t.name,definition:da(g)})}),[t,g,l,d]),M="vectorSearch"===t.type?"Vector Search Index":"Search Index";return r().createElement("div",{className:Fr,"data-testid":"edit-search-index-drawer-view"},r().createElement("div",{className:Wr},r().createElement(u.Pds,{"data-testid":"edit-search-index-drawer-view-title"},"Edit ",M),r().createElement("div",{className:Vr},r().createElement("div",{className:Ur},r().createElement("span",{"data-testid":"edit-search-index-drawer-view-index-name"},t.name),r().createElement(u.Exy,{"data-testid":"edit-search-index-drawer-view-index-type-badge",variant:u.xUU.Blue},M),r().createElement(Bn,{status:t.status,"data-testid":"edit-search-index-drawer-view-status"}),r().createElement(u.Exy,{"data-testid":"edit-search-index-drawer-view-queryable-badge",variant:t.queryable?u.xUU.LightGray:u.xUU.Red},t.queryable?"Queryable":"Non-queryable"))),r().createElement(u.nBu,{className:_r},"This ",M.toLowerCase()," parses the data in ",r().createElement("b",null,e)," ","and has the following configurations."),r().createElement("div",{className:(0,u.cx)(Br,k&&zr)},r().createElement(ea.Jn,{ref:m,id:"edit-search-index-drawer-view-editor","data-testid":"edit-search-index-drawer-view-editor",text:g,onChangeText:D,minLines:16,showLineNumbers:!0,language:"json",initialJSONFoldAll:!1,completer:C,customExtensions:w,annotations:I,readOnly:!x})),i&&r().createElement(u.dFH,{errors:i})),r().createElement("div",{className:jr},r().createElement(u.$nd,{"data-testid":"edit-search-index-drawer-view-cancel-button",variant:"default",onClick:()=>{d("Search Index Edit Cancelled",{context:"Edit Search Index Drawer View",index_type:t.type??"search"}),o()}},"Cancel"),r().createElement(u.m_M,{trigger:r().createElement(u.$nd,{"data-testid":"edit-search-index-drawer-view-submit-button",variant:"primary",isLoading:n,loadingIndicator:r().createElement(u.Q0K,null),disabled:!A||!x,onClick:N},"Save and Rebuild"),enabled:!x},"You currently don't have permission to edit ",M,"es in this"," ",f?"project, please contact Project Owner to request the Project Data Access Admin role.":"cluster.")))})),Jr=(0,u.AHW)({width:"fit-content"}),Qr=(0,u.AHW)({display:"flex",alignItems:"center",gap:u.YKD[200],fontSize:"16px",fontWeight:"semibold"}),Xr="compass-indexes-drawer",ei={openIndexesListDrawerView:yt},ti=(0,At.Ng)((({indexesDrawer:e})=>({currentView:e.currentView,isDirty:e.isDirty})),ei)((({currentView:e,isDirty:t,subTab:n,openIndexesListDrawerView:i})=>{const{enableSearchActivationProgramP1:o}=(0,Ee.p5)(),s=(0,a.useCallback)((async()=>!t||await(0,u.$TK)({title:"Any unsaved progress will be lost",buttonText:"Discard",variant:"danger",description:"Are you sure you want to continue?"})),[t]);return o?r().createElement(r().Fragment,null,r().createElement(u.TmU,{id:"Indexes"===n?"compass-indexes-drawer-disabled":Xr,title:"indexes-list"===e?"Indexes":r().createElement("div",{className:Jr},r().createElement(u.N_E,{onClick:i},r().createElement("div",{className:Qr},r().createElement(u.Int,{glyph:"ArrowLeft"}),"Back to All Indexes"))),label:"Indexes"===n?"You are already on the indexes page":"Indexes",glyph:"SearchIndex",disabled:"Indexes"===n,beforeSectionHide:s,guideCue:{cueId:"indexes-drawer",title:"Easily access all your search indexes",description:"Click to view and manage search indexes.",buttonText:"Got it",tooltipAlign:"left",tooltipJustify:"start"}},"indexes-list"===e&&r().createElement(Or,null),"create-search-index"===e&&r().createElement(Gr,null),"edit-search-index"===e&&r().createElement(Zr,null)),"Indexes"!==n&&r().createElement(Ya,null)):null})),ni=(0,i.nk)({name:"CompassIndexes",component:function({children:e}){return r().createElement(r().Fragment,null,e)},activate:function(e,{connectionInfoRef:t,instance:n,localAppRegistry:a,globalAppRegistry:r,logger:i,track:l,dataService:c,collection:d,atlasService:u,preferences:p,workspaces:m,experimentationServices:g},{on:h,cleanup:f,addCleanup:y}){const b=(0,o.y$)(Ct,{isWritable:n.isWritable,description:n.description,namespace:e.namespace,serverVersion:e.serverVersion,isReadonlyView:e.isReadonly,isSearchIndexesSupported:e.isSearchIndexesSupported,indexView:e.isReadonly?"search-indexes":nt,collectionStats:ot(d)},(0,o.Tw)(wt.A.withExtraArgument({localAppRegistry:a,globalAppRegistry:r,logger:i,track:l,connectionInfoRef:t,dataService:c,collection:d,rollingIndexesService:new St(u,t),pollingIntervalRef:{regularIndexes:null,searchIndexes:null},preferences:p,experimentationServices:g})));h(a,"open-create-index-modal",(e=>{b.dispatch(fe(e?.query))})),h(a,"open-create-search-index-modal",(()=>{b.dispatch(Fe())})),h(a,"open-indexes-list-drawer-view",(e=>{b.dispatch(yt(e))})),h(a,"open-edit-search-index-drawer-view",(e=>{b.dispatch(vt(e))})),h(a,"open-create-search-index-drawer-view",(e=>{b.dispatch(bt(e))})),h(r,"refresh-data",(()=>{b.dispatch(G()),e.isSearchIndexesSupported&&b.dispatch(Ve())})),h(n,"change:isWritable",(()=>{var e;b.dispatch((e=n.isWritable,{type:s,isWritable:e}))})),h(n,"change:description",(()=>{b.dispatch((e=>({type:it,description:e}))(n.description))})),b.dispatch(G()),(e.isSearchIndexesSupported||e.isReadonly)&&b.dispatch(Ve()),h(d,"change:status",((e,t)=>{"ready"===t&&b.dispatch({type:st,collection:e})})),y((()=>{b.dispatch(q()),b.dispatch($e())}));const v=()=>!b.getState().indexesDrawer.isDirty;return y(m.onTabReplace?.(v)),y(m.onTabClose?.(v)),{store:b,deactivate:()=>f()}}},{dataService:Dt.S1,connectionInfoRef:Dt.wj,instance:er.A$,logger:(0,tr.fF)("COMPASS-INDEXES-UI"),track:Ee.yL,collection:er.KK,atlasService:xe.fA,preferences:kt.fx,workspaces:Ft.__,experimentationServices:Ee.Uf}),ai={name:"Indexes",provider:ni,content:Xa,header:or,drawer:ti}},89213:(e,t,n)=>{n.d(t,{R:()=>r,c:()=>a});class a extends Error{constructor(e){super(e),this.name="AtlasAiServiceInvalidInputError"}}class r extends Error{constructor(e){super(e),this.name="AtlasAiServiceApiResponseParseError"}}},96441:(e,t,n)=>{n.d(t,{A:()=>j});var a=n(62183),r=(n(21261),n(92879),n(31977),n(49743),n(9656),n(72673),n(35467),n(94476),n(64971),n(24330),n(83478),n(65166),n(1256),n(61038),n(73035),n(23855),n(96652)),i=n.n(r),o=n(19125),s=n(51295),l=(n(95039),n(17855)),c=n(93758),d=n.n(c),u=n(4863);const p=["Pipeline","Query","Delete Query","Update Query"];function m(e){return["Query","Delete Query","Update Query"].includes(e.exportMode)}var g=n(28508),h=n(19461);function f(e){const t=(0,h.Ay)(e,{mode:h.X6.Strict,allowComments:!0,allowMethods:!0});if(!Array.isArray(t))throw new Error("Source expression is not an aggregation stage array");return t.length}var y=n(20625),b=n(70724),v=n(82162);function x(e,t){return e.type===t}const E={inputExpression:{filter:"",exportMode:"Query"},modalOpen:!1,uri:"<uri>",namespace:""},C="export-to-language/OPEN_MODAL";function w(e){return{type:C,inputExpression:e}}const I="export-to-language/CLOSE_MODAL",S=(e=E,t)=>x(t,C)?{...e,modalOpen:!0,inputExpression:t.inputExpression}:x(t,I)?{...e,modalOpen:!1}:e;function A(e){let t;try{t=e.getConnectionString().clone()}catch{return"<uri>"}return/^(mongodb compass|compass web)/i.exec(t.searchParams.get("appName")||"")&&t.searchParams.delete("appName"),t.href}var k=n(60783);const D=[{displayName:"Java",language:"java"},{displayName:"Node",language:"javascript"},{displayName:"C#",language:"csharp"},{displayName:"Python",language:"python"},{displayName:"Ruby",language:"ruby"},{displayName:"Go",language:"go"},{displayName:"Rust",language:"rust"},{displayName:"PHP",language:"php"}],N=new Set(D.map((e=>e.language))),M=[{displayName:"Shell",language:"javascript"}],T=(0,s.AHW)({marginBottom:s.YKD[400]}),P=(0,s.AHW)({display:"flex",gap:s.YKD[600]}),L=(0,s.AHW)({flex:"1 1 0px"}),O=(0,s.AHW)({marginBottom:s.YKD[200],display:"block"}),R=(0,s.AHW)({alignItems:"start",height:4*s.YKD[1600]-s.YKD[800]+"px","& > div":{height:"100%",gridTemplateRows:"min-content auto"},"& pre":{alignItems:"flex-start"}}),H=(0,s.AHW)({marginTop:s.YKD[200],width:"auto"});function F(e){if(!("aggregation"in e))return{};try{return{num_stages:f(e.aggregation)}}catch{return{num_stages:-1}}}const W=(0,o.Ng)(((e,t)=>({modalOpen:e.modalOpen,inputExpression:e.inputExpression,uri:e.uri,namespace:e.namespace})),{onModalClose:function(){return{type:I}}})((({modalOpen:e,onModalClose:t,inputExpression:n,uri:a,namespace:o})=>{const c=(0,g.Jr)(),p=(0,k.jj)(),[h,f]=(0,r.useState)("python"),[v,x]=(0,r.useState)(!1),[E,C]=(0,r.useState)(!1),[w,I]=(0,r.useState)(!1),S=n.exportMode,A=m(n),W=!!(0,y.Fg)("protectConnectionStrings"),[j,B]=(0,r.useMemo)((()=>{try{const e=function({inputExpression:e,outputLanguage:t,includeImports:n,includeDrivers:a,useBuilders:r,uri:i,namespace:o,protectConnectionStrings:s}){const c=e.exportMode;r=r&&"java"===t&&m(e);let p="";if(a){const n=(0,l.Ay)(o),a=Object.assign({options:{collection:n.collection,database:n.database,uri:(0,u.x)(s,i)}},e);p=d().shell[t].compileWithDriver(a,r)}else{const n="aggregation"in e?e.aggregation:e.filter;p=d().shell[t].compile(n,r,!1)}return n&&(p=`${d().shell[t].getImports(c,a)}\n\n${p}`),p}({inputExpression:n,outputLanguage:h,includeImports:v,includeDrivers:E,useBuilders:w,uri:a,namespace:o,protectConnectionStrings:W});return[e,null]}catch(e){return[null,e?.message]}}),[E,v,n,o,h,a,w,W]),z="java"===h&&A,_=A?n.filter:n.aggregation;(0,s.wTI)((()=>{if(e){const e=p.current;"Query"===S?c("Query Export Opened",{},e):"Delete Query"===S?c("Delete Export Opened",{},e):"Update Query"===S?c("Update Export Opened",{},e):"Pipeline"===S&&c("Aggregation Export Opened",F(n),e),c("Screen",{name:"export_to_language_modal"},e)}}),[e]);const $=(0,r.useCallback)((()=>{const e={language:h,with_import_statements:v,with_drivers_syntax:E,with_builders:w};"Update Query"===S?c("Update Exported",e,p.current):"Delete Query"===S?c("Delete Exported",e,p.current):"Query"===S?c("Query Exported",e,p.current):"Pipeline"===S&&c("Aggregation Exported",{...e,...F(n)},p.current)}),[c,p,h,v,E,w,n,S]),Y=(0,r.useMemo)((()=>(0,b.G8)(_,"javascript-expression")),[_]);return i().createElement(s.WhU,{"data-testid":"export-to-language-modal",open:e,onClose:t,title:`Export ${S} To Language`,size:"large"},B&&i().createElement(s.lZ$,{variant:"danger",className:T},B),i().createElement(s.GEW,{className:P},i().createElement("div",{className:L,"data-testid":"export-to-language-input-field"},i().createElement(s.JU7,{"data-testid":"export-to-language-export-from",htmlFor:"export-to-language-input",className:O},"My ",S),i().createElement(s.CyN,{className:R,id:"export-to-language-input","data-testid":"export-to-language-input",language:"Shell",panel:i().createElement(s.Zkm,{languageOptions:M,onChange:()=>{}})},Y)),i().createElement("div",{className:L,"data-testid":"export-to-language-output-field"},i().createElement(s.JU7,{"data-testid":"export-to-language-export-to-label",htmlFor:"export-to-language-output",className:O},"Exported ",S),i().createElement(s.CyN,{className:R,id:"export-to-language-output",language:h,"data-testid":"export-to-language-output",panel:i().createElement(s.Zkm,{languageOptions:D,onChange:e=>{if(t=e.language,N.has(t))return f(e.language);var t},onCopy:$})},j||""))),i().createElement(s.Sc0,{className:H,"data-testid":"export-to-language-include-imports",onChange:()=>x(!v),label:"Include Import Statements",checked:v,bold:!1}),i().createElement(s.Sc0,{className:H,"data-testid":"export-to-language-include-drivers",onChange:()=>C(!E),label:"Include Driver Syntax",checked:E,bold:!1}),z&&i().createElement(s.Sc0,{className:H,"data-testid":"export-to-language-use-builders",onChange:()=>I(!w),label:"Use Builders",checked:w,bold:!1}))})),j=(0,a.nk)({name:"ExportToLanguage",component:W,activate:function({namespace:e},{localAppRegistry:t,dataService:n},{on:a,cleanup:r}){const i=(0,v.y$)(S,{...E,namespace:e,uri:A(n)});return a(t,"open-aggregation-export-to-language",(e=>{i.dispatch(w({aggregation:e,exportMode:"Pipeline"}))})),a(t,"open-query-export-to-language",((e,t="Query")=>{if(n=t,!p.includes(n)||"Pipeline"===t)throw new Error(t?`Export mode "${t}" is not a valid export mode value for query export`:"Export mode must be provided with the type of query you want to export to.");var n;const a={exportMode:t,filter:"{}"};for(const t of["filter","project","sort","collation","skip","limit","maxTimeMS"])e[t]&&(a[t]="filter"===t?e[t]??a[t]:e[t]);i.dispatch(w(a))})),{store:i,deactivate:r}}},{dataService:k.S1})},98051:(e,t,n)=>{n.d(t,{A:()=>yt});var a=n(19125),r=n(96652),i=n.n(r),o=n(51295),s=(n(59509),n(25691),n(23177),n(3142),n(51615),n(84217),n(25953),n(42319),n(28465),n(12887),n(36106),n(84542),n(57068),n(69517),n(32318)),l=n(20625);function c(e,t){return e.type===t}const d="compass-explain-plan-modal/CloseExplainPlanModal",u="compass-explain-plan-modal/FetchExplainPlanModalLoading",p="compass-explain-plan-modal/FetchExplainPlanModalSuccess",m="compass-explain-plan-modal/FetchExplainPlanModalError",g={namespace:"",isDataLake:!1,error:null,isModalOpen:!1,status:"initial",explainPlan:null,rawExplainPlan:null,explainPlanFetchId:-1,operationType:null,initialViewType:"tree"},h=(e=g,t)=>c(t,u)?{...e,isModalOpen:!0,status:"loading",error:null,explainPlan:null,rawExplainPlan:null,explainPlanFetchId:t.id,operationType:t.operationType,initialViewType:t.initialViewType}:c(t,p)?{...e,status:"ready",explainPlan:t.explainPlan,rawExplainPlan:t.rawExplainPlan,explainPlanFetchId:-1}:c(t,m)?{...e,status:"error",explainPlan:null,error:t.error,rawExplainPlan:t.rawExplainPlan,explainPlanFetchId:-1}:c(t,d)?{...e,isModalOpen:!1}:e,f=new Map;let y=0;function b(){const e=++y,t=new AbortController;return f.set(e,t),{id:e,signal:t.signal}}function v(e){return f.delete(e)}class x extends Error{rawExplainPlan;constructor(e,t){super(e),this.rawExplainPlan=t}}const E=(e,t)=>async(n,a,{dataService:r,preferences:i,track:o,connectionInfoRef:c,logger:{log:d,mongoLogId:u}})=>{const p=c.current,{isDataLake:m,namespace:g}=a(),h=e.query?"query":"aggregation",f=m?"queryPlannerExtended":"executionStats";let y=null,b=null;if(e.aggregation){const{collation:n,maxTimeMS:a}=e.aggregation,c=e.aggregation.pipeline.filter((e=>!(e=>Object.prototype.hasOwnProperty.call(e,"$out")||Object.prototype.hasOwnProperty.call(e,"$merge"))(e))),m=(0,l.Tv)(i,a??6e4);y=await r.explainAggregate(g,c,{collation:n,maxTimeMS:m},{explainVerbosity:f,maxTimeMS:m,abortSignal:t});try{b=new s.d(y).serialize()}catch(e){throw d.warn(u(1001000137),"Explain","Failed to parse aggregation explain",{message:e.message}),new x(e.message,y)}o("Aggregation Explained",{num_stages:c.length,index_used:b.usedIndexes.length>0},p)}if(e.query){const{filter:n,maxTimeMS:a,...c}=e.query,m=(0,l.Tv)(i,a??6e4);y=await r.explainFind(g,n,{...c,maxTimeMS:m},{explainVerbosity:f,maxTimeMS:m,abortSignal:t});try{b=new s.d(y).serialize()}catch(e){throw d.warn(u(1001000192),"Explain","Failed to parse find explain",{message:e.message}),new x(e.message,y)}o("Explain Plan Executed",{with_filter:Object.entries(n).length>0,index_used:b.usedIndexes.length>0},p)}return b?{explainPlan:b,rawExplainPlan:y,operationType:h,namespace:g}:null};var C=n(70724),w=n(55712),I=n(90605);const S=(e,t)=>{const n=t.count++,a=[...s.d.getChildStages(e)].map((e=>S(e,t))),r=!!e.shardName,i=a.length?Math.max(...a.map((e=>e.curStageExecTimeMS))):0,o=void 0!==e.executionTimeMillisEstimate?e.executionTimeMillisEstimate:e.executionTimeMillis,l=r||void 0===o?i:o,c={id:`stage-${n}`,name:e.stage||e.shardName,nReturned:e.nReturned,curStageExecTimeMS:l,prevStageExecTimeMS:i,isShard:r,details:(0,I.omit)(e,["inputStage","inputStages","shards","executionStages"]),children:a};return{...c,highlights:A(c)}},A=e=>{switch(e.name){case"IXSCAN":case"EXPRESS_IXSCAN":return{"Index Name":e.details?.indexName,"Multi Key Index":e.details?.isMultiKey};case"PROJECTION":return{"Transform by":JSON.stringify(e.details?.transformBy)};case"COLLSCAN":return{"Documents Examined":e.details?.docsExamined};default:return{}}};var k=n(94665);function D({translateX:e,gapY:t=0,link:n,linkColor:a,arrowColor:o,getLinkWidth:s}){const{linkPaths:l,arrowPath:c}=(0,r.useMemo)((()=>{const a=n.source,r=n.target,i=e+a.x,o=e+r.x,l=a.y,c=r.y,d=a.ySize-t,u=i,p=l+d/2,m=o,g=c,h=l+d+t/2;if(i===o)return{linkPaths:[{pathDef:`M ${u} ${p} V ${g}`,strokeWidth:s(a.data,r.data)}],arrowPath:r.noChildren?{pathDef:`M ${u} ${h} V ${g}`,strokeWidth:4}:null};const f=l+d,y=f+(c-f)/2,b=s(a.data,r.data,{isFirstVerticalHalf:!0}),v=s(a.data,r.data);return{linkPaths:[{pathDef:`M ${u} ${p} V ${y}`,strokeWidth:b},{pathDef:`M ${u} ${y} H ${m}`,strokeWidth:v},{pathDef:`M ${m} ${y-v/2} V ${y+y}`,strokeWidth:v}]}}),[t,n.source,n.target,e,s]);return i().createElement(i().Fragment,null,l.map((({pathDef:e,strokeWidth:t},n)=>i().createElement("path",{key:n,className:`path-${n}`,fill:"none",stroke:a,strokeWidth:t,d:e}))),c&&i().createElement("path",{fill:"none",stroke:o,d:c.pathDef,strokeWidth:c.strokeWidth,markerStart:"url(#arrowhead)"}))}const N=(0,o.AHW)({position:"relative",margin:"0 auto",transformOrigin:"top left",transitionProperty:"width, height, transform",transitionDuration:"0.1s",transitionTimingFunction:"linear"}),M=(0,o.AHW)({position:"absolute",top:0,left:0}),T=function({data:e,getNodeSize:t,getNodeKey:n,linkColor:a,getLinkWidth:o,arrowColor:s,horizontalSpacing:l,verticalSpacing:c,children:d,scale:u=1,...p}){const m=(0,r.useRef)(null),{translateX:g,width:h,height:f,nodes:y,links:b}=(0,r.useMemo)((()=>{const n=(0,k.u)({nodeSize:e=>{const n=e.data,[a,r]=t(n);return[a,r+c]},spacing:l}),a=n.hierarchy(e),r=n(a),i=r.descendants(),o=r.links();return{translateX:-r.extents.left,width:r.extents.right-r.extents.left,height:r.extents.bottom-r.extents.top,nodes:i,links:o}}),[e,t,c,l]);return i().createElement("div",p,i().createElement("div",{style:{width:h*u,height:f*u,transform:`scale(${u})`},className:N},i().createElement("svg",{className:M,ref:m,width:h,height:f},i().createElement("defs",null,i().createElement("marker",{markerWidth:"5",markerHeight:"5",refX:"9",refY:"11",viewBox:"0 0 25 21",orient:"auto-start-reverse",id:"arrowhead"},i().createElement("polyline",{points:"0,15 7.5,7.5 0,0",fill:"none",strokeWidth:"4",stroke:s,strokeLinecap:"round",transform:"matrix(1,0,0,1,2,3.5)",strokeLinejoin:"round"}))),i().createElement("g",null,b.map(((e,t)=>i().createElement(D,{key:t,link:e,gapY:c,translateX:g,linkColor:a,arrowColor:s,getLinkWidth:o}))))),y.map((e=>i().createElement("div",{key:n(e.data),style:{position:"absolute",left:e.left+g,top:e.top,width:e.xSize,height:e.ySize}},d(e.data))))))};var P=n(25213),L=n.n(P);const O={clockBackgroundColor:o.MFm.white,clockFaceColor:o.MFm.gray.light1,textColor:o.MFm.gray.base,msColor:o.MFm.blue.base,previousElapsedArcColor:o.MFm.gray.light2,currentElapsedArcColor:o.MFm.blue.base},R={clockBackgroundColor:o.MFm.black,clockFaceColor:o.MFm.gray.light1,textColor:o.MFm.gray.base,msColor:o.MFm.blue.light2,previousElapsedArcColor:o.MFm.gray.dark2,currentElapsedArcColor:o.MFm.blue.light2},H=(0,o.AHW)({fontWeight:"normal",fontSize:"10px",textAlign:"center"}),F=(0,o.AHW)({color:O.textColor}),W=(0,o.AHW)({color:R.textColor}),j=(0,o.AHW)({position:"relative"}),B=(0,o.AHW)({position:"absolute",top:0,left:0,display:"flex",flexDirection:"column",justifyContent:"center"}),z=(0,o.AHW)({fontWeight:"bold",fontSize:"13px",lineHeight:"13px"}),_=(0,o.AHW)({fontSize:"11px",lineHeight:"11px"}),$=(0,o.AHW)({color:O.msColor}),Y=(0,o.AHW)({color:R.msColor}),K=(0,o.AHW)({position:"absolute",top:0,left:0}),G=50,V=50,U=({totalExecTimeMS:e,curStageExecTimeMS:t,prevStageExecTimeMS:n,className:a})=>{const s=(0,r.useRef)(null),{value:l,unit:c}=(0,r.useMemo)((()=>q(t-n)),[t,n]),d=(0,o.D27)(),{clockFaceColor:u,clockBackgroundColor:p,previousElapsedArcColor:m,currentElapsedArcColor:g}=(0,r.useMemo)((()=>d?R:O),[d]);return(0,r.useEffect)((()=>{if(!s.current)return;const a=s.current;return function({width:e,height:t,strokeColor:n,fillColor:a,svgElement:r}){const i=Math.min(e,t)/2;L().select(r).append("path").attr("d",L().svg.arc().innerRadius(0).outerRadius(i-1).startAngle(0).endAngle(2*Math.PI)).attr("transform",`translate(${e/2},${t/2})`).style("fill",a),L().select(r).append("path").attr("d",L().svg.arc().innerRadius(i-1).outerRadius(i).startAngle(0).endAngle(2*Math.PI)).attr("transform",`translate(${e/2},${t/2})`).style("fill",n),[0,45,90,135,180,225,270,315].forEach((e=>{const t=.3*i;L().select(r).append("line").attr("x1",i+(i-t)*Math.sin(e*(Math.PI/180))).attr("y1",i-(i-t)*Math.cos(e*(Math.PI/180))).attr("x2",i+i*Math.sin(e*(Math.PI/180))).attr("y2",i-i*Math.cos(e*(Math.PI/180))).attr("stroke",n).attr("stroke-width",1)}))}({width:G,height:V,strokeColor:u,fillColor:p,svgElement:a}),function({svgElement:e,strokeWidth:t,width:n,height:a,totalExecTimeMS:r,curStageExecTimeMS:i,prevStageExecTimeMS:o,previousElapsedArcColor:s,currentElapsedArcColor:l}){const c=o/r*2*Math.PI||0,d=i/r*2*Math.PI||0,u=c,p=Math.min(n,a)/2;[{startAngle:0,endAngle:u,fill:s},{startAngle:c,endAngle:d,fill:l}].forEach((({startAngle:r,endAngle:i,fill:o})=>{const s=L().svg.arc().innerRadius(p-t/2).outerRadius(p+t/2).startAngle(r).endAngle(i);L().select(e).append("path").attr("d",s).attr("transform",`translate(${n/2},${a/2})`).style("fill",o)}))}({width:G,height:V,strokeWidth:5,svgElement:a,curStageExecTimeMS:t,prevStageExecTimeMS:n,totalExecTimeMS:e,previousElapsedArcColor:m,currentElapsedArcColor:g}),()=>{L().select(a).selectAll("*").remove()}}),[t,n,e,p,u,m,g]),i().createElement("div",{className:(0,o.cx)(a,H,d?W:F),style:{width:G,height:V}},i().createElement("div",{className:j,style:{width:G,height:V}},i().createElement("svg",{width:G,height:V,ref:s,className:K,viewBox:"-3 -3 56 56"}),i().createElement("div",{className:B,style:{width:G,height:V}},i().createElement("span",{className:(0,o.cx)(z,d?Y:$)},l),i().createElement("span",{className:_},c))))},q=e=>{const t=e=>e-Math.floor(e)!=0,n=e/36e5;if(n>=1)return{value:t(n)?n.toFixed(1):n.toString(),unit:"h"};const a=e/6e4;if(a>=1)return{value:t(a)?a.toFixed(1):a.toString(),unit:"min"};const r=e/1e3;return r>=1?{value:t(r)?r.toFixed(1):r.toString(),unit:"s"}:{value:e.toString(),unit:"ms"}},Z=(0,o.AHW)({position:"absolute",width:278,padding:"14px",borderRadius:o.YKD[200]}),J=(0,o.AHW)({borderColor:o.MFm.gray.light2}),Q=(0,o.AHW)({display:"flex",alignItems:"center",gap:o.YKD[200],cursor:"pointer"}),X=(0,o.AHW)({whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),ee=(0,o.AHW)({marginTop:o.YKD[200],marginBottom:o.YKD[200]}),te=(0,o.AHW)({position:"relative"}),ne=(0,o.AHW)({position:"absolute",top:-o.YKD[800],right:-(8+o.YKD[800])}),ae=(0,o.AHW)({marginTop:o.YKD[400],height:"100%",overflow:"hidden"}),re=(0,o.AHW)({position:"relative",display:"grid",gridTemplateColumns:"1fr 110px",marginTop:"12px",alignItems:"center"}),ie=(0,o.AHW)({display:"inline-block",width:o.YKD[600]-4,height:o.YKD[600]-4,lineHeight:o.YKD[600]-4+"px",borderRadius:"100px",textAlign:"center",fontWeight:700,backgroundColor:o.MFm.blue.base,color:o.MFm.white}),oe=(0,o.AHW)({width:"auto",padding:`0 ${o.YKD[200]}px`}),se=(0,o.AHW)({backgroundColor:o.MFm.blue.light2,color:o.MFm.black}),le=(0,o.AHW)({borderRadius:0,borderColor:o.MFm.gray.base,width:278,height:o.YKD[800],paddingLeft:o.YKD[200],paddingRight:o.YKD[200],display:"flex",alignItems:"center",justifyContent:"center"}),ce=(0,o.AHW)({color:o.MFm.gray.base,fontSize:"16px",fontWeight:600,textAlign:"center",overflow:"hidden",textTransform:"uppercase",textOverflow:"ellipsis",whiteSpace:"nowrap"}),de=(0,o.AHW)({overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}),ue=({stats:e})=>{const t=(0,o.D27)();return i().createElement("span",{className:(0,o.cx)(ie,{[oe]:String(e).length>1,[se]:t})},e)},pe=e=>i().createElement(o.yY_,{className:le,title:e.name},i().createElement(o.nBu,{baseFontSize:16,className:ce},((e,t=20,n=6,a=4)=>{if(e.length<=t)return e;const r=e.substring(0,n),i=e.substring(n);return`${r}…${i.substring(i.length-a)}`})(e.name))),me=({field:e,value:t})=>void 0===t?null:i().createElement("li",{className:de},i().createElement("span",null,e,": "),i().createElement("strong",{title:t},t)),ge=({highlights:e})=>i().createElement("ul",null,Object.entries(e).map((([e,t],n)=>i().createElement(me,{key:n,field:e,value:"boolean"==typeof t?t?"yes":"no":t})))),he=({nReturned:e,prevStageExecTimeMS:t,curStageExecTimeMS:n,totalExecTimeMS:a})=>i().createElement("div",{className:re},i().createElement("div",null,i().createElement("span",null,"Returned "),i().createElement(ue,{stats:e})),i().createElement("div",null,i().createElement("span",null,"Execution Time"),i().createElement("span",null,i().createElement(o.m_M,{align:"top",justify:"middle",trigger:i().createElement("div",{className:ne},i().createElement(U,{prevStageExecTimeMS:t,curStageExecTimeMS:n,totalExecTimeMS:a}))},"The clock represents the total time the query took to complete. The blue clock segment is the time taken by the highlighted stage (",n-t," ms). The gray clock segment is the time taken by preceding stages.")))),fe=e=>i().createElement(i().Fragment,null,i().createElement("div",{className:Q},i().createElement(o.Int,{glyph:e.detailsOpen?"ChevronDown":"ChevronRight"}),i().createElement(o.Pds,{className:X},e.name)),i().createElement(he,{nReturned:e.nReturned,prevStageExecTimeMS:e.prevStageExecTimeMS,curStageExecTimeMS:e.curStageExecTimeMS,totalExecTimeMS:e.totalExecTimeMS}),Object.entries(e.highlights).length>0&&i().createElement("div",null,i().createElement(o.d$,{className:ee}),i().createElement(ge,{highlights:e.highlights})),e.detailsOpen&&i().createElement(o.yY_,{className:ae,onClick:e=>e.stopPropagation()},i().createElement(C.Jn,{language:"json",readOnly:!0,formattable:!1,showLineNumbers:!1,initialJSONFoldAll:!1,showAnnotationsGutter:!1,minLines:1,maxLines:15,text:JSON.stringify(e.details,null," ")||"{}","data-testid":"explain-stage-details"}))),ye=({name:e="",nReturned:t=0,isShard:n=!1,totalExecTimeMS:a=1,curStageExecTimeMS:r=0,prevStageExecTimeMS:s=0,highlights:l={},details:c={},detailsOpen:d=!1,onToggleDetailsClick:u=()=>{}})=>{const p=(0,o.D27)();return n?i().createElement(pe,{name:e}):i().createElement(o.ZpM,{"data-testid":"explain-stage",className:(0,o.cx)(Z,{[J]:p}),style:{boxShadow:d?void 0:"none"},onClick:u},i().createElement("div",{className:te},i().createElement(fe,{name:e,nReturned:t,highlights:l,curStageExecTimeMS:r,prevStageExecTimeMS:s,totalExecTimeMS:a,onToggleDetailsClick:u,detailsOpen:d,details:c})))},be=(0,o.AHW)({zIndex:1}),ve=o.YKD[1600],xe=e=>{const t=84+20*Object.keys(e.highlights).length;return[278,e.isShard?6:t]},Ee=(e,t,n)=>e.isShard||t.isShard?n?.isFirstVerticalHalf?o.YKD[600]:o.YKD[200]:o.YKD[100],Ce=e=>e.id,we=({executionStats:e,scale:t})=>{const n=(0,o.D27)(),[a,s]=(0,r.useState)(null),l=(0,r.useMemo)((()=>(e=>{const t=e?.executionStages;try{return t?S(t,{count:0}):void 0}catch{return}})(e)),[e]);return l?i().createElement(T,{"data-testid":"explain-tree",data:l,getNodeSize:xe,getNodeKey:Ce,linkColor:n?o.MFm.gray.dark2:o.MFm.gray.light2,arrowColor:n?o.MFm.gray.base:o.MFm.gray.light1,getLinkWidth:Ee,horizontalSpacing:ve,verticalSpacing:38,className:be,scale:t},(e=>{const t=Ce(e);return i().createElement("div",{style:{position:"relative",zIndex:a===t?2:1}},i().createElement(ye,(0,w.A)({detailsOpen:a===t,onToggleDetailsClick:()=>{s(a===t?null:t)}},e,{totalExecTimeMS:l.curStageExecTimeMS})))})):null},Ie=e=>String(e),Se=(0,o.AHW)({display:"flex",alignItems:"center",gap:o.YKD[200]}),Ae=(0,o.AHW)({lineHeight:"20px"}),ke=({as:e="li",glyph:t,value:n,formatter:a=Ie,label:r,definition:s,"data-testid":l})=>i().createElement(e,{className:Se},t?i().cloneElement(t,{viewBox:`0 0 ${o.YKD[400]} ${o.YKD[400]}`,width:o.YKD[400],height:o.YKD[400]}):null,i().createElement(o.p8Z,{definition:s,className:Ae,tooltipProps:{align:"left",spacing:o.YKD[400]},"data-testid":l},void 0===n?r:i().createElement(i().Fragment,null,i().createElement("strong",null,a(n))," ",r))),De=(0,o.AHW)({display:"grid",gridTemplateRows:"auto 1fr",maxHeight:"100%",overflow:"hidden"}),Ne=(0,o.AHW)({paddingTop:o.YKD[400],paddingBottom:o.YKD[400],paddingLeft:o.YKD[600],paddingRight:o.YKD[600],backgroundColor:o.MFm.gray.light3,boxShadow:`0 0 0 1px ${o.MFm.gray.light2}`}),Me=(0,o.AHW)({backgroundColor:o.MFm.gray.dark3,boxShadow:`0 0 0 1px ${o.MFm.gray.dark2}`}),Te=(0,o.AHW)({display:"grid",gap:o.YKD[400],paddingTop:o.YKD[400],paddingBottom:o.YKD[600],paddingLeft:o.YKD[600],paddingRight:o.YKD[600],overflow:"auto"}),Pe=(0,o.AHW)({display:"flex",flexDirection:"column",alignItems:"flex-start",gap:o.YKD[200]}),Le=(0,o.AHW)({verticalAlign:"text-top"}),Oe={COVERED:"Query covered by index:",MULTIPLE:"Query used the following indexes (shard results differ):",INDEX:"Query used the following index:"},Re=({indexType:e,indexKeys:t,onCreateIndexInsightClick:n})=>{const a=(0,o.D27)(),r=(0,l.Fg)("showInsights"),s=a?o.MFm.yellow.base:o.MFm.yellow.dark2;return"CLUSTERED"===e?null:"COLLSCAN"===e||"UNAVAILABLE"===e?i().createElement("div",{className:Se,style:{color:s}},i().createElement(o.Int,{glyph:"Warning"}),i().createElement("span",null,"No index available for this query."),r&&i().createElement(o.gIH,{signals:{...o.qpO.get("explain-plan-without-index"),onPrimaryActionButtonClick:n}})):i().createElement("div",{className:Pe},i().createElement(ke,{as:"div",label:Oe[e],definition:i().createElement(i().Fragment,null,"The index(es) used to fulfill the query. A value of"," ",i().createElement(o.OHu,{className:Le,direction:1})," ","indicates an ascending index, and a value of"," ",i().createElement(o.OHu,{className:Le,direction:-1})," ","indicates a descending index.")}),t.map((([e,t])=>i().createElement(o.sAP,{key:`${e}:${String(t)}`,field:e,value:t}))))},He=(0,a.Ng)(null,{onCreateIndexInsightClick:()=>(e,t,{localAppRegistry:n})=>{n?.emit("open-create-index-modal")}})((({docsReturned:e,docsExamined:t,executionTimeMs:n,sortedInMemory:a,indexKeysExamined:r,indexType:s,indexKeys:l,onCreateIndexInsightClick:c})=>{const d=(0,o.D27)();return i().createElement(o.yY_,{className:De,"data-testid":"explain-plan-summary"},i().createElement(o.Pds,{className:(0,o.cx)(Ne,d&&Me)},"Query Performance Summary"),i().createElement("ul",{className:Te},i().createElement(ke,{glyph:i().createElement("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none"},i().createElement("g",{stroke:"#889397",strokeLinecap:"round",strokeLinejoin:"round"},i().createElement("path",{d:"M10 2v2.66667c0 .17681.0702.34638.1953.4714.125.12503.2946.19526.4714.19526h2.6666"}),i().createElement("path",{d:"M12 11.3333H7.33333c-.35362 0-.69276-.1404-.94281-.3905C6.14048 10.6928 6 10.3536 6 10V3.33333c0-.35362.14048-.69276.39052-.94281C6.64057 2.14048 6.97971 2 7.33333 2H10l3.3333 3.33333V10c0 .3536-.1404.6928-.3905.9428-.25.2501-.5892.3905-.9428.3905Z"}),i().createElement("path",{d:"M10.6666 11.3333v1.3334c0 .3536-.1405.6927-.3905.9428-.2501.25-.58923.3905-.94285.3905H4.66659c-.35363 0-.69277-.1405-.94281-.3905-.25005-.2501-.39053-.5892-.39053-.9428V6.00001c0-.35363.14048-.69277.39053-.94281.25004-.25005.58918-.39053.94281-.39053h1.33333"}))),value:e,"data-testid":"docsReturned",label:"documents returned",definition:"Number of documents returned by the query."}),i().createElement(ke,{glyph:i().createElement("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none"},i().createElement("g",{stroke:"#889397",strokeLinecap:"round",strokeLinejoin:"round"},i().createElement("path",{d:"M9.33325 2v2.66667c0 .17681.07024.34638.19526.4714.12503.12503.2946.19526.47141.19526h2.66668"}),i().createElement("path",{d:"M7.99992 14H4.66659c-.35363 0-.69277-.1405-.94281-.3905-.25005-.2501-.39053-.5892-.39053-.9428V3.33333c0-.35362.14048-.69276.39053-.94281C3.97382 2.14048 4.31296 2 4.66659 2h4.66666l3.33335 3.33333v3"}),i().createElement("path",{d:"M9.33325 11.6667c0 .442.1756.8659.48816 1.1785.31259.3125.73649.4881 1.17849.4881.442 0 .866-.1756 1.1785-.4881.3126-.3126.4882-.7365.4882-1.1785 0-.4421-.1756-.866-.4882-1.1785-.3125-.3126-.7365-.4882-1.1785-.4882-.442 0-.8659.1756-1.17849.4882-.31256.3125-.48816.7364-.48816 1.1785ZM12.3333 13l1.6666 1.6667"}))),value:t,"data-testid":"docsExamined",label:"documents examined",definition:"Number of documents examined during query execution. When an index covers a query, this value is 0."}),i().createElement(ke,{glyph:i().createElement("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none"},i().createElement("g",{stroke:"#889397",strokeLinecap:"round",strokeLinejoin:"round"},i().createElement("path",{d:"M2 8c0 .78793.15519 1.56815.45672 2.2961.30153.728.74349 1.3894 1.30064 1.9465.55715.5572 1.21859.9991 1.94654 1.3007C6.43185 13.8448 7.21207 14 8 14s1.56815-.1552 2.2961-.4567c.728-.3016 1.3894-.7435 1.9465-1.3007.5572-.5571.9991-1.2185 1.3007-1.9465C13.8448 9.56815 14 8.78793 14 8c0-1.5913-.6321-3.11742-1.7574-4.24264C11.1174 2.63214 9.5913 2 8 2c-1.5913 0-3.11742.63214-4.24264 1.75736C2.63214 4.88258 2 6.4087 2 8Z"}),i().createElement("path",{d:"M8 4.66667v3.33334L10 10"}))),value:n,"data-testid":"executionTimeMs",formatter:e=>`${String(e)} ms`,label:"execution time",definition:"Total time in milliseconds for query plan selection and query execution."}),i().createElement(ke,{glyph:i().createElement("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none"},i().createElement("path",{fill:"#889397",fillRule:"evenodd",d:"M5.26047 5.79391c-.18746.18746-.18746.49137 0 .67883.18745.18745.49137.18745.67882 0l2.06059-2.0606 2.06062 2.0606c.1874.18745.4913.18745.6788 0 .1874-.18746.1874-.49137 0-.67883l-2.40001-2.4c-.09003-.09001-.21212-.14058-.33941-.14058-.12731 0-.2494.05057-.33942.14058l-2.39999 2.4Zm5.47883 4.41219c.1874-.1875.1874-.4914 0-.67885-.1875-.18745-.4914-.18745-.6788 0L7.99988 11.5878 5.93929 9.52725c-.18745-.18745-.49137-.18745-.67882 0-.18746.18745-.18746.49135 0 .67885l2.39999 2.4c.18746.1874.49138.1874.67883 0l2.40001-2.4Z",clipRule:"evenodd"})),value:a,"data-testid":"sortedInMemory",formatter:e=>e?"Is":"Is not",label:"sorted in memory",definition:"Indicates whether the sort operation occurred in system memory. In-memory sorts perform better than on-disk sorts."}),i().createElement(ke,{glyph:i().createElement("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none"},i().createElement("g",{stroke:"#889397",strokeLinecap:"round",strokeLinejoin:"round"},i().createElement("path",{d:"M5.33325 8.5c0 .30942.28095.60617.78105.82496.5001.21879 1.17837.34171 1.88562.34171.70724 0 1.38552-.12292 1.88562-.34171.50006-.21879.78106-.51554.78106-.82496 0-.30942-.281-.60616-.78106-.82496-.5001-.21879-1.17838-.3417-1.88562-.3417-.70725 0-1.38552.12291-1.88562.3417-.5001.2188-.78105.51554-.78105.82496Z"}),i().createElement("path",{d:"M5.33325 8.33334v2.49996c0 .644 1.19334 1.1667 2.66667 1.1667 1.47333 0 2.66668-.5227 2.66668-1.1667V8.33334M9.33325 2v2.66667c0 .17681.07024.34638.19526.4714.12503.12503.2946.19526.47141.19526h2.66668"}),i().createElement("path",{d:"M11.3333 14H4.66659c-.35363 0-.69277-.1405-.94281-.3905-.25005-.2501-.39053-.5892-.39053-.9428V3.33333c0-.35362.14048-.69276.39053-.94281C3.97382 2.14048 4.31296 2 4.66659 2h4.66666l3.33335 3.33333v7.33337c0 .3536-.1405.6927-.3905.9428-.2501.25-.5892.3905-.9428.3905Z"}))),value:r,"data-testid":"indexKeysExamined",label:"index keys examined",definition:"Number of indexes examined to fulfill the query."}),i().createElement(Re,{indexType:s,indexKeys:l,onCreateIndexInsightClick:c})))})),Fe=function(){return i().createElement(o.lZ$,{variant:o.uAY.Warning},"Visual explain plan is not supported with this query on this collection in this Compass release. Please refer to the raw json output of the explain for insight into the operation.")},We=(0,o.AHW)({display:"flex",flexDirection:"column",overflow:"hidden"}),je=(0,o.AHW)({boxShadow:"none !important","&:first-child":{borderBottomLeftRadius:0,borderBottomRightRadius:0,borderBottom:"none"},"&:last-child":{borderTopLeftRadius:0,borderTopRightRadius:0},"& > div:last-child":{paddingLeft:6,paddingRight:6}}),Be=({value:e,step:t=.1,minValue:n=.2,onZoomChange:a})=>i().createElement("div",{className:We},i().createElement(o.$nd,{className:je,leftGlyph:i().createElement(o.Int,{glyph:"Plus"}),onClick:()=>{a(Math.max(n,e+t))},size:"small","aria-label":"Zoom in"}),i().createElement(o.$nd,{className:je,leftGlyph:i().createElement(o.Int,{glyph:"Minus"}),onClick:()=>{a(Math.max(n,e-t))},size:"small","aria-label":"Zoom out"})),ze=(0,o.AHW)({position:"relative",width:"100%",height:"100%"}),_e=(0,o.AHW)({position:"relative",width:"100%",height:"100%",overflow:"auto"}),$e=(0,o.AHW)({position:"absolute",left:0,bottom:o.YKD[400]}),Ye=({executionStats:e})=>{const[t,n]=(0,r.useState)(1);return i().createElement("div",{className:ze},i().createElement("div",{className:_e},i().createElement(we,{executionStats:e,scale:t})),i().createElement("div",{className:$e},i().createElement(Be,{value:t,onZoomChange:n})))},Ke=(0,o.AHW)({height:"100%",display:"grid",gridTemplateColumns:"1fr",gridTemplateRows:"auto 1fr",rowGap:o.YKD[600]}),Ge=(0,o.AHW)({display:"grid",rowGap:o.YKD[600]}),Ve=(0,o.AHW)({display:"flex",overflow:"hidden",gap:o.YKD[600]}),Ue=(0,o.AHW)({flex:"1 1 0%",minWidth:"0%"}),qe=(0,o.AHW)({height:"100%",overflow:"hidden"}),Ze=(0,o.AHW)({"& .cm-editor":{paddingLeft:o.YKD[200]}}),Je=(0,o.AHW)({height:"100%",overflow:"auto"}),Qe=(0,o.AHW)({flex:"none"}),Xe=({explainPlan:e,rawExplainPlan:t,initialViewType:n,error:a})=>{const[s,l]=(0,r.useState)(a?"json":n??"tree"),c=(0,r.useMemo)((()=>t?(0,C.G8)(JSON.stringify(t),"json"):""),[t]),d=(0,r.useMemo)((()=>e?.usedIndexes.flatMap((e=>Object.entries(e.fields)))??[]),[e]),u=Boolean(a&&t&&!e);return a&&!u?i().createElement(o.lZ$,{variant:"danger"},a):i().createElement("div",{className:Ke},i().createElement("div",{className:Ge},i().createElement(o.IzF,{onChange:l,value:s,"data-testid":"explain-view-type-control"},i().createElement(o.Zib,{value:"tree",glyph:i().createElement(o.Int,{glyph:"Diagram"}),disabled:!!a},"Visual Tree"),i().createElement(o.Zib,{value:"json",glyph:i().createElement(o.Int,{glyph:"CurlyBraces"}),disabled:!!a},"Raw Output")),u&&i().createElement(Fe,null)),i().createElement("div",{className:Ve},i().createElement("div",{className:Ue},"json"===s&&i().createElement(o.yY_,{className:qe},i().createElement(C.Jn,{language:"json",text:c,readOnly:!0,showAnnotationsGutter:!1,showLineNumbers:!1,formattable:!1,initialJSONFoldAll:!1,editorClassName:Ze,"data-testid":"raw-explain-plan"})),"tree"===s&&i().createElement("div",{className:Je},i().createElement(Ye,{executionStats:e?.executionStats}))),!u&&i().createElement("div",{className:Qe},i().createElement(He,{docsReturned:e?.nReturned??0,docsExamined:e?.totalDocsExamined??0,executionTimeMs:e?.executionTimeMillis??0,sortedInMemory:e?.inMemorySort??!1,indexKeysExamined:e?.totalKeysExamined??0,indexType:e?.indexType??"UNAVAILABLE",indexKeys:d}))))};var et=n(21119);const tt=(0,o.AHW)({"& > div":{display:"grid",gridTemplateColumns:"1fr",gridTemplateRows:"auto 1fr auto"}}),nt=(0,o.AHW)({flex:1,minHeight:2*o.YKD[1600],display:"flex",alignItems:"center",justifyContent:"center"}),at=(0,o.AHW)({paddingTop:o.YKD[400],paddingLeft:o.YKD[800],paddingRight:o.YKD[800],overflow:"hidden"}),rt=(0,o.AHW)({display:"flex",alignItems:"flex-end",justifyContent:"space-between",paddingRight:o.YKD[800]}),it=(0,o.AHW)({flex:1}),ot=(0,o.AHW)({marginTop:o.YKD[800],flexShrink:0,display:"flex",alignItems:"center",gap:o.YKD[200]}),st=(0,o.AHW)({height:"100%",display:"flex",alignItems:"center",justifyContent:"center"}),lt=(0,o.AHW)({height:"100%",display:"flex"}),ct=()=>i().createElement("div",{className:nt,"data-testid":"explain-plan-loading"},i().createElement(o.iyS,{progressText:"Running explain"})),dt=(0,a.Ng)((e=>({isModalOpen:e.isModalOpen,status:e.status,explainPlan:e.explainPlan,rawExplainPlan:e.rawExplainPlan,error:e.error,operationType:e.operationType,initialViewType:e.initialViewType})),{onModalClose:()=>(e,t)=>{!function(e){const t=f.get(e);t?.abort(),f.delete(e)}(t().explainPlanFetchId),e({type:d})}})((({isModalOpen:e=!1,status:t="initial",explainPlan:n,rawExplainPlan:a,error:r,operationType:s,initialViewType:l="tree",onModalClose:c})=>{const{interpretExplainPlan:d}=(0,et.hb)();return i().createElement(o.aFV,{"data-testid":"explain-plan-modal",className:tt,open:e,setOpen:c,fullScreen:!0},i().createElement("div",{className:rt},i().createElement("div",{className:it},i().createElement(o.rQ0,{title:"Explain Plan",subtitle:i().createElement("div",null,"Explain provides key execution metrics that help diagnose slow queries and optimize index usage. ",i().createElement(o.N_E,{href:"https://www.mongodb.com/docs/upcoming/reference/explain-results/#mongodb-data-explain.executionStats",target:"_blank"},"Learn more"))})),n&&d&&i().createElement("div",{className:ot},i().createElement(o.$nd,{size:"small",variant:"default",leftGlyph:i().createElement(o.Int,{glyph:"Sparkle",style:{color:o.MFm.green.dark1}}),"data-testid":"interpret-for-me-button",onClick:()=>{c(),d({namespace:n.namespace,explainPlan:JSON.stringify(n),operationType:s??"aggregation"})},disabled:"ready"!==t},"Interpret"),i().createElement(o.m_M,{triggerEvent:"hover",trigger:i().createElement("span",{className:st},i().createElement(o.Int,{color:o.MFm.gray.dark1,glyph:"InfoWithCircle"}))},"Understand Explain output in natural language and get suggestions to improve performance"))),i().createElement("div",{className:at},"loading"===t&&i().createElement("div",{className:lt},i().createElement(ct,null)),("ready"===t||"error"===t)&&i().createElement(Xe,{explainPlan:n,rawExplainPlan:a,error:r,initialViewType:l})),i().createElement(o.jlY,null,i().createElement(o.$nd,{onClick:c,"data-testid":"explain-close-button"},"loading"===t?"Cancel":"Close")))}));var ut=n(82162),pt=n(67219),mt=n(62183),gt=n(60783),ht=n(44142),ft=n(28508);const yt=(0,mt.nk)({name:"ExplainPlanModal",component:dt,activate:function({namespace:e,isDataLake:t},n,{on:a,cleanup:r}){const i=(0,ut.y$)(h,{...g,namespace:e,isDataLake:t},(0,ut.Tw)(pt.A.withExtraArgument(n)));return a(n.localAppRegistry,"open-explain-plan-modal",(e=>{i.dispatch((e=>async(t,n,{dataService:a,logger:{log:r,mongoLogId:i}})=>{const{id:o,signal:s}=b(),l=e.query?"query":"aggregation";t({type:u,id:o,operationType:l,initialViewType:e.initialViewType??"tree"});try{const n=await t(E(e,s));t({type:p,explainPlan:n?.explainPlan??null,rawExplainPlan:n?.rawExplainPlan??null})}catch(e){if(a.isCancelError(e))return;r.error(i(1001000138),"Explain","Failed to run explain",{message:e.message}),t({type:m,error:e.message,rawExplainPlan:e instanceof x?e.rawExplainPlan:null})}finally{v(o)}})(e))})),a(n.localAppRegistry,"open-explain-plan-for-interpret",(e=>{i.dispatch((e=>async(t,n,a)=>{const{id:r,signal:i}=b();try{const n=await t(E(e,i));n&&a.compassAssistant.interpretExplainPlan?.({namespace:n.namespace,explainPlan:JSON.stringify(n.explainPlan),operationType:n.operationType})}catch(e){if(a.dataService.isCancelError(e))return;a.logger.log.error(a.logger.mongoLogId(1001000434),"Explain","Failed to run explain for interpret",{message:e.message})}finally{v(r)}})(e))})),{store:i,deactivate:r}}},{logger:(0,ht.fF)("EXPLAIN-PLAN-MODAL-UI"),track:ft.yL,connectionInfoRef:gt.wj,dataService:gt.S1,preferences:l.fx,compassAssistant:et.eD})}};